Refactor seal tools into modular domains and fix layer inversions
- Split monolithic tools.ts (4,257 lines) into 11 domain-specific modules in src/domains/seal/tools/ - Extract helpers.ts containing 71 helper functions and shared tool types - Retain tools.ts as thin re-export for complete backward compatibility - Fix layer inversions: sink CliError to core/errors.ts, extract linter paths to core/paths.ts, move tenant-diagnose to domain - Eliminate null as any in runner.ts by widening signatures and adding proper runtime guards - Rebuild dist/mcp/server.js to satisfy pre-push bundle gate
This commit is contained in:
1 parent
d868a29c5d
commit
ab9b9965e9
26 files changed
+6375
-4983
No files matched your search
+36
-32
@@ -33,43 +33,47 @@ export async function handleAuthExtractKeysCommand(maybeName: string | undefined
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) {
|
||||
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig | null, args: ParsedArgs) {
|
||||
const subAction = args.command[2]?.toLowerCase();
|
||||
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
|
||||
|
||||
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
||||
const note = stringOption(args.options.note);
|
||||
const session = await exchangeHoseAssistLink(fromLink);
|
||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||
const me = await getMe(client);
|
||||
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
||||
const delegation = await createDelegation(client, { note });
|
||||
|
||||
printJson({
|
||||
tenant: {
|
||||
id: me.tenant.id,
|
||||
name: me.tenant.name,
|
||||
tenantSlug: me.tenant.tenantSlug,
|
||||
corpId: session.corpId
|
||||
},
|
||||
user: {
|
||||
id: me.user.id,
|
||||
name: me.user.name,
|
||||
providerUserId: me.user.providerUserId,
|
||||
isAdmin: me.user.isAdmin
|
||||
},
|
||||
delegation,
|
||||
expiresIn: session.expiresIn
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!corp) {
|
||||
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
|
||||
}
|
||||
|
||||
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
|
||||
printJson(await diagnoseAuth(corp));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) {
|
||||
const subAction = args.command[2]?.toLowerCase();
|
||||
|
||||
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
|
||||
if (fromLink) {
|
||||
const note = stringOption(args.options.note);
|
||||
const session = await exchangeHoseAssistLink(fromLink);
|
||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||
const me = await getMe(client);
|
||||
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
||||
const delegation = await createDelegation(client, { note });
|
||||
|
||||
printJson({
|
||||
tenant: {
|
||||
id: me.tenant.id,
|
||||
name: me.tenant.name,
|
||||
tenantSlug: me.tenant.tenantSlug,
|
||||
corpId: session.corpId
|
||||
},
|
||||
user: {
|
||||
id: me.user.id,
|
||||
name: me.user.name,
|
||||
providerUserId: me.user.providerUserId,
|
||||
isAdmin: me.user.isAdmin
|
||||
},
|
||||
delegation,
|
||||
expiresIn: session.expiresIn
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp.source?.type === "seal")) {
|
||||
const client = await createSealClient(corp);
|
||||
|
||||
if (subAction === "list") {
|
||||
|
||||
+20
-14
@@ -28,18 +28,24 @@ import type { ParsedArgs } from "../types.js";
|
||||
export async function handleRulesCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
client: Awaited<ReturnType<typeof createSealClient>> | null,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
// lint, linters, and map actions can run without a network client
|
||||
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
|
||||
if (!client && !clientless) {
|
||||
throw new Error(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
|
||||
}
|
||||
|
||||
if (action === "count") {
|
||||
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
|
||||
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "list") {
|
||||
if (booleanOption(args.options.count)) {
|
||||
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
|
||||
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -48,7 +54,7 @@ export async function handleRulesCommand(
|
||||
if (booleanOption(args.options.summary)) {
|
||||
await runTool(
|
||||
"seal_approval_rules_list",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
fields: RULE_SUMMARY_FIELDS,
|
||||
@@ -60,7 +66,7 @@ export async function handleRulesCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await runToolResult("seal_approval_rules_list", client, corp, { limit, offset });
|
||||
const result = await runToolResult("seal_approval_rules_list", client!, corp, { limit, offset });
|
||||
const output = outputOptions(args.options);
|
||||
protectLargeRuleListOutput(result, output.allowFull === true || Boolean(output.outputFile));
|
||||
printJson(result, output);
|
||||
@@ -76,7 +82,7 @@ export async function handleRulesCommand(
|
||||
`seal-use rules clear --corp ${corp.id} --dry-run`
|
||||
);
|
||||
}
|
||||
const result = await runToolResult("seal_approval_rules_clear", client, corp, {
|
||||
const result = await runToolResult("seal_approval_rules_clear", client!, corp, {
|
||||
dryRun,
|
||||
recode: booleanOption(args.options.recode)
|
||||
});
|
||||
@@ -95,7 +101,7 @@ export async function handleRulesCommand(
|
||||
}
|
||||
|
||||
if (action === "versions") {
|
||||
await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options));
|
||||
await runTool("seal_approval_rule_versions_list", client!, corp, {}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -104,7 +110,7 @@ export async function handleRulesCommand(
|
||||
if (!version) throw new Error("Usage: seal-use rules version <versionId|versionNumber|latest>");
|
||||
await runTool(
|
||||
"seal_approval_rule_version_get",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
parseRuleVersionSelector(version),
|
||||
outputOptions(args.options)
|
||||
@@ -121,7 +127,7 @@ export async function handleRulesCommand(
|
||||
const singleSelector = args.command[4];
|
||||
await runTool(
|
||||
"seal_approval_rule_version_diff",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
from,
|
||||
@@ -142,7 +148,7 @@ export async function handleRulesCommand(
|
||||
const code = rawCode ? (rawCode.startsWith("#") || rawCode.startsWith("rule-") ? rawCode : (rawCode.match(/^\d+$/) ? `#${rawCode.padStart(4, "0")}` : rawCode)) : undefined;
|
||||
await runTool(
|
||||
"seal_approval_rule_get",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
...ruleVersionGetOptions(stringOption(args.options.version)),
|
||||
@@ -160,7 +166,7 @@ export async function handleRulesCommand(
|
||||
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <versionId|versionNumber|latest>]");
|
||||
await runTool(
|
||||
"seal_approval_search",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
keywords: [keyword],
|
||||
@@ -183,7 +189,7 @@ export async function handleRulesCommand(
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
|
||||
await runTool(
|
||||
"seal_approval_rules_pull",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
version,
|
||||
@@ -203,7 +209,7 @@ export async function handleRulesCommand(
|
||||
|
||||
const result = await runToolResult(
|
||||
"seal_approval_rules_push",
|
||||
client,
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
@@ -231,7 +237,7 @@ export async function handleRulesCommand(
|
||||
if (action === "lint") {
|
||||
await runTool(
|
||||
"seal_approval_rules_lint",
|
||||
client,
|
||||
client as Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp,
|
||||
{
|
||||
file: stringOption(args.options.file) ?? stringOption(args.options.f),
|
||||
|
||||
+10
-58
@@ -1,58 +1,10 @@
|
||||
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
||||
|
||||
export class CliError extends Error {
|
||||
readonly exitCode: CliExitCode;
|
||||
readonly nextAction?: string;
|
||||
|
||||
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
|
||||
super(message);
|
||||
this.name = "CliError";
|
||||
this.exitCode = exitCode;
|
||||
this.nextAction = nextAction;
|
||||
}
|
||||
}
|
||||
|
||||
export class PayloadTooLargeError extends CliError {
|
||||
constructor(message: string, nextAction?: string) {
|
||||
super(message, 12, nextAction);
|
||||
this.name = "PayloadTooLargeError";
|
||||
}
|
||||
}
|
||||
|
||||
export function usageError(message: string, nextAction?: string): CliError {
|
||||
return new CliError(message, 2, nextAction);
|
||||
}
|
||||
|
||||
export function confirmationRequired(message: string, nextAction: string): CliError {
|
||||
return new CliError(message, 10, nextAction);
|
||||
}
|
||||
|
||||
export function classifyCliError(error: unknown): {
|
||||
exitCode: CliExitCode;
|
||||
nextAction?: string;
|
||||
} {
|
||||
if (error instanceof CliError) {
|
||||
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
||||
}
|
||||
|
||||
const value = error instanceof Error ? error.message : String(error);
|
||||
const status = responseStatus(error);
|
||||
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
|
||||
return { exitCode: 11 };
|
||||
}
|
||||
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
|
||||
return { exitCode: 2 };
|
||||
}
|
||||
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
|
||||
return { exitCode: 10 };
|
||||
}
|
||||
return { exitCode: 1 };
|
||||
}
|
||||
|
||||
function responseStatus(error: unknown): number | undefined {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const response = (error as { response?: unknown }).response;
|
||||
if (!response || typeof response !== "object") return undefined;
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return typeof status === "number" ? status : undefined;
|
||||
}
|
||||
// Re-export from core — this file is the legacy entry point.
|
||||
// Domain-layer code should import from "../core/errors.js" directly.
|
||||
export {
|
||||
type CliExitCode,
|
||||
CliError,
|
||||
PayloadTooLargeError,
|
||||
usageError,
|
||||
confirmationRequired,
|
||||
classifyCliError
|
||||
} from "../core/errors.js";
|
||||
+2
-2
@@ -360,7 +360,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
source: { type: "native" }
|
||||
} as any;
|
||||
}
|
||||
await handleRulesCommand(action, maybeName, null as any, corp, args);
|
||||
await handleRulesCommand(action, maybeName, null, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -377,7 +377,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
(action === "link" || action === "seal-link") &&
|
||||
("from-link" in args.options || maybeName === "from-link")
|
||||
) {
|
||||
await handleAuthCommand(action, null as any, args);
|
||||
await handleAuthCommand(action, null, args);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { accessSync, constants, existsSync, readdirSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../domains/seal/linter/loader.js";
|
||||
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
|
||||
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
|
||||
|
||||
@@ -1,426 +1,8 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
|
||||
export interface TenantHealthCheck {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "pass" | "warn" | "fail";
|
||||
summary: string;
|
||||
details: Record<string, unknown>;
|
||||
recommendation?: string;
|
||||
}
|
||||
|
||||
export interface TenantDoctorDiagnosis {
|
||||
ok: boolean;
|
||||
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
|
||||
timestamp: string;
|
||||
corp: {
|
||||
id: string;
|
||||
name: string;
|
||||
environment: "production" | "test";
|
||||
sourceType: string;
|
||||
boundCorpId?: string;
|
||||
boundCorpRole?: "prodParent" | "testTarget";
|
||||
boundCorpRoleDescription?: string;
|
||||
};
|
||||
summary: {
|
||||
totalChecks: number;
|
||||
passedChecks: number;
|
||||
warningChecks: number;
|
||||
failedChecks: number;
|
||||
};
|
||||
checks: TenantHealthCheck[];
|
||||
quota: {
|
||||
featureCode: string;
|
||||
balance: number;
|
||||
deductionAmount: number;
|
||||
estimatedRuns: number;
|
||||
status: "sufficient" | "low" | "exhausted";
|
||||
};
|
||||
rules: {
|
||||
totalCount: number;
|
||||
activeCount: number;
|
||||
quotaUsed?: number;
|
||||
quotaRemaining?: number;
|
||||
};
|
||||
webhooks: {
|
||||
integrationCount: number;
|
||||
hasReplayChannel: boolean;
|
||||
activeWebhookId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function diagnoseTenantContract(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig
|
||||
): Promise<TenantDoctorDiagnosis> {
|
||||
const checks: TenantHealthCheck[] = [];
|
||||
const environment = corp.environment === "test" ? "test" : "production";
|
||||
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
|
||||
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
|
||||
const boundCorpRoleDescription = boundCorpId
|
||||
? environment === "test"
|
||||
? "已绑定生产母企业 (上游配置与样本源)"
|
||||
: "已绑定测试靶场 (下游隔离演练环境)"
|
||||
: undefined;
|
||||
|
||||
// 1. Auth & Admin Probe
|
||||
let userDetail: any = null;
|
||||
let tenantDetail: any = null;
|
||||
try {
|
||||
const whoami = await api.getMe(client);
|
||||
userDetail = whoami.user;
|
||||
tenantDetail = whoami.tenant;
|
||||
|
||||
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
|
||||
if (isAdmin) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "pass",
|
||||
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: true,
|
||||
permissionLevel: "超级管理员(具备完整操作权限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
tenantSlug: tenantDetail?.tenantSlug,
|
||||
permissions: userDetail.permissions
|
||||
}
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "warn",
|
||||
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: false,
|
||||
permissionLevel: "普通用户(部分管理配置受限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
permissions: userDetail.permissions
|
||||
},
|
||||
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "fail",
|
||||
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) },
|
||||
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Billing & AI Approval Quota Probe
|
||||
let quotaInfo = {
|
||||
featureCode: "ai-approval",
|
||||
balance: 0,
|
||||
deductionAmount: 120,
|
||||
estimatedRuns: 0,
|
||||
status: "exhausted" as "sufficient" | "low" | "exhausted"
|
||||
};
|
||||
|
||||
let ruleQuota = {
|
||||
used: 0,
|
||||
remaining: 0
|
||||
};
|
||||
|
||||
try {
|
||||
const billing = await api.getBillingStatus(client);
|
||||
const features = Array.isArray(billing.features) ? billing.features : [];
|
||||
|
||||
// Find AI Approval feature
|
||||
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
|
||||
if (aiApproval) {
|
||||
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
|
||||
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
|
||||
? aiApproval.deductionAmount
|
||||
: 120;
|
||||
const estimatedRuns = Math.floor(balance / deductionAmount);
|
||||
|
||||
quotaInfo.balance = balance;
|
||||
quotaInfo.deductionAmount = deductionAmount;
|
||||
quotaInfo.estimatedRuns = estimatedRuns;
|
||||
|
||||
if (balance <= 0) {
|
||||
quotaInfo.status = "exhausted";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "fail",
|
||||
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: `请前往后台充值补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
|
||||
});
|
||||
} else if (estimatedRuns < 10) {
|
||||
quotaInfo.status = "low";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: `建议补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
|
||||
});
|
||||
} else {
|
||||
quotaInfo.status = "sufficient";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "pass",
|
||||
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
|
||||
details: { balance, deductionAmount, estimatedRuns }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
|
||||
details: { features: features.map((f: any) => f?.code) }
|
||||
});
|
||||
}
|
||||
|
||||
// Rule quota
|
||||
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
|
||||
if (ruleFeat) {
|
||||
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
|
||||
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Rules & Draft State Probe
|
||||
let rulesSummary = {
|
||||
totalCount: 0,
|
||||
activeCount: 0,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
};
|
||||
|
||||
try {
|
||||
const rulesData = await api.listApprovalRules(client);
|
||||
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
|
||||
rulesSummary.totalCount = rules.length;
|
||||
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
|
||||
|
||||
if (rules.length === 0) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "warn",
|
||||
summary: "当前租户未配置任何审核规则 (规则数为 0)",
|
||||
details: { totalCount: 0, activeCount: 0 },
|
||||
recommendation: environment === "test" && boundCorpId
|
||||
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
|
||||
: "可运行 seal-use rules add 创建基础规则"
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "pass",
|
||||
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
|
||||
details: {
|
||||
totalCount: rulesSummary.totalCount,
|
||||
activeCount: rulesSummary.activeCount,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "fail",
|
||||
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Webhook Integration Probe
|
||||
let webhooksSummary = {
|
||||
integrationCount: 0,
|
||||
hasReplayChannel: false,
|
||||
activeWebhookId: undefined as string | undefined
|
||||
};
|
||||
|
||||
try {
|
||||
const integrations = await api.listWebhookIntegrations(client);
|
||||
webhooksSummary.integrationCount = integrations.length;
|
||||
|
||||
const replayChannel = integrations.find(
|
||||
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
|
||||
);
|
||||
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
|
||||
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
|
||||
|
||||
if (integrations.length === 0) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "pass",
|
||||
summary: "未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将自动创建)",
|
||||
details: { integrationCount: 0 }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "pass",
|
||||
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
|
||||
details: {
|
||||
integrationCount: integrations.length,
|
||||
hasReplayChannel: webhooksSummary.hasReplayChannel,
|
||||
activeWebhookId: webhooksSummary.activeWebhookId
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "warn",
|
||||
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Environment Pairing Probe
|
||||
if (environment === "test") {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "pass",
|
||||
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "warn",
|
||||
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "pass",
|
||||
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "warn",
|
||||
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Compute overall verdict
|
||||
const failedChecks = checks.filter((c) => c.status === "fail").length;
|
||||
const warningChecks = checks.filter((c) => c.status === "warn").length;
|
||||
const passedChecks = checks.filter((c) => c.status === "pass").length;
|
||||
|
||||
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
|
||||
if (failedChecks > 0) {
|
||||
verdict = "BLOCKED";
|
||||
} else if (warningChecks > 0) {
|
||||
verdict = "DEGRADED";
|
||||
}
|
||||
|
||||
return {
|
||||
ok: failedChecks === 0,
|
||||
verdict,
|
||||
timestamp: new Date().toISOString(),
|
||||
corp: {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
environment,
|
||||
sourceType: corp.source?.type ?? "native",
|
||||
boundCorpId,
|
||||
boundCorpRole,
|
||||
boundCorpRoleDescription
|
||||
},
|
||||
summary: {
|
||||
totalChecks: checks.length,
|
||||
passedChecks,
|
||||
warningChecks,
|
||||
failedChecks
|
||||
},
|
||||
checks,
|
||||
quota: quotaInfo,
|
||||
rules: rulesSummary,
|
||||
webhooks: webhooksSummary
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
|
||||
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
|
||||
|
||||
const verdictBadge =
|
||||
verdict === "HEALTHY"
|
||||
? "🟢 健康良好 (HEALTHY)"
|
||||
: verdict === "DEGRADED"
|
||||
? "🟡 亚健康降级 (DEGRADED)"
|
||||
: "🔴 阻断受限 (BLOCKED)";
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
|
||||
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
|
||||
" " + "─".repeat(60)
|
||||
];
|
||||
|
||||
// Core metrics overview
|
||||
lines.push(
|
||||
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
|
||||
);
|
||||
if (corp.boundCorpId) {
|
||||
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
|
||||
}
|
||||
lines.push(" " + "─".repeat(60));
|
||||
|
||||
for (const check of checks) {
|
||||
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
|
||||
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
|
||||
if (check.recommendation) {
|
||||
lines.push(` 👉 建议: ${check.recommendation}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(" " + "─".repeat(60));
|
||||
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
|
||||
if (quota.status === "exhausted" || quota.status === "low") {
|
||||
lines.push(` 👉 Next action: seal-use auth link --corp ${corp.id}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
// Re-export from domain layer — this file is the legacy entry point.
|
||||
// tenant-diagnose inherently depends on domains/seal/api, so it now lives there.
|
||||
export {
|
||||
type TenantHealthCheck,
|
||||
type TenantDoctorDiagnosis,
|
||||
diagnoseTenantContract,
|
||||
formatTenantDoctorDashboard
|
||||
} from "../../domains/seal/doctor/tenant-diagnose.js";
|
||||
@@ -0,0 +1,58 @@
|
||||
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
||||
|
||||
export class CliError extends Error {
|
||||
readonly exitCode: CliExitCode;
|
||||
readonly nextAction?: string;
|
||||
|
||||
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
|
||||
super(message);
|
||||
this.name = "CliError";
|
||||
this.exitCode = exitCode;
|
||||
this.nextAction = nextAction;
|
||||
}
|
||||
}
|
||||
|
||||
export class PayloadTooLargeError extends CliError {
|
||||
constructor(message: string, nextAction?: string) {
|
||||
super(message, 12, nextAction);
|
||||
this.name = "PayloadTooLargeError";
|
||||
}
|
||||
}
|
||||
|
||||
export function usageError(message: string, nextAction?: string): CliError {
|
||||
return new CliError(message, 2, nextAction);
|
||||
}
|
||||
|
||||
export function confirmationRequired(message: string, nextAction: string): CliError {
|
||||
return new CliError(message, 10, nextAction);
|
||||
}
|
||||
|
||||
export function classifyCliError(error: unknown): {
|
||||
exitCode: CliExitCode;
|
||||
nextAction?: string;
|
||||
} {
|
||||
if (error instanceof CliError) {
|
||||
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
||||
}
|
||||
|
||||
const value = error instanceof Error ? error.message : String(error);
|
||||
const status = responseStatus(error);
|
||||
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
|
||||
return { exitCode: 11 };
|
||||
}
|
||||
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
|
||||
return { exitCode: 2 };
|
||||
}
|
||||
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
|
||||
return { exitCode: 10 };
|
||||
}
|
||||
return { exitCode: 1 };
|
||||
}
|
||||
|
||||
function responseStatus(error: unknown): number | undefined {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const response = (error as { response?: unknown }).response;
|
||||
if (!response || typeof response !== "object") return undefined;
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return typeof status === "number" ? status : undefined;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use");
|
||||
export const PRIMARY_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
|
||||
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, "official");
|
||||
@@ -0,0 +1,426 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import * as api from "../api.js";
|
||||
|
||||
export interface TenantHealthCheck {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "pass" | "warn" | "fail";
|
||||
summary: string;
|
||||
details: Record<string, unknown>;
|
||||
recommendation?: string;
|
||||
}
|
||||
|
||||
export interface TenantDoctorDiagnosis {
|
||||
ok: boolean;
|
||||
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
|
||||
timestamp: string;
|
||||
corp: {
|
||||
id: string;
|
||||
name: string;
|
||||
environment: "production" | "test";
|
||||
sourceType: string;
|
||||
boundCorpId?: string;
|
||||
boundCorpRole?: "prodParent" | "testTarget";
|
||||
boundCorpRoleDescription?: string;
|
||||
};
|
||||
summary: {
|
||||
totalChecks: number;
|
||||
passedChecks: number;
|
||||
warningChecks: number;
|
||||
failedChecks: number;
|
||||
};
|
||||
checks: TenantHealthCheck[];
|
||||
quota: {
|
||||
featureCode: string;
|
||||
balance: number;
|
||||
deductionAmount: number;
|
||||
estimatedRuns: number;
|
||||
status: "sufficient" | "low" | "exhausted";
|
||||
};
|
||||
rules: {
|
||||
totalCount: number;
|
||||
activeCount: number;
|
||||
quotaUsed?: number;
|
||||
quotaRemaining?: number;
|
||||
};
|
||||
webhooks: {
|
||||
integrationCount: number;
|
||||
hasReplayChannel: boolean;
|
||||
activeWebhookId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function diagnoseTenantContract(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig
|
||||
): Promise<TenantDoctorDiagnosis> {
|
||||
const checks: TenantHealthCheck[] = [];
|
||||
const environment = corp.environment === "test" ? "test" : "production";
|
||||
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
|
||||
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
|
||||
const boundCorpRoleDescription = boundCorpId
|
||||
? environment === "test"
|
||||
? "已绑定生产母企业 (上游配置与样本源)"
|
||||
: "已绑定测试靶场 (下游隔离演练环境)"
|
||||
: undefined;
|
||||
|
||||
// 1. Auth & Admin Probe
|
||||
let userDetail: any = null;
|
||||
let tenantDetail: any = null;
|
||||
try {
|
||||
const whoami = await api.getMe(client);
|
||||
userDetail = whoami.user;
|
||||
tenantDetail = whoami.tenant;
|
||||
|
||||
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
|
||||
if (isAdmin) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "pass",
|
||||
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: true,
|
||||
permissionLevel: "超级管理员(具备完整操作权限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
tenantSlug: tenantDetail?.tenantSlug,
|
||||
permissions: userDetail.permissions
|
||||
}
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "warn",
|
||||
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: false,
|
||||
permissionLevel: "普通用户(部分管理配置受限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
permissions: userDetail.permissions
|
||||
},
|
||||
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "fail",
|
||||
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) },
|
||||
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Billing & AI Approval Quota Probe
|
||||
let quotaInfo = {
|
||||
featureCode: "ai-approval",
|
||||
balance: 0,
|
||||
deductionAmount: 120,
|
||||
estimatedRuns: 0,
|
||||
status: "exhausted" as "sufficient" | "low" | "exhausted"
|
||||
};
|
||||
|
||||
let ruleQuota = {
|
||||
used: 0,
|
||||
remaining: 0
|
||||
};
|
||||
|
||||
try {
|
||||
const billing = await api.getBillingStatus(client);
|
||||
const features = Array.isArray(billing.features) ? billing.features : [];
|
||||
|
||||
// Find AI Approval feature
|
||||
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
|
||||
if (aiApproval) {
|
||||
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
|
||||
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
|
||||
? aiApproval.deductionAmount
|
||||
: 120;
|
||||
const estimatedRuns = Math.floor(balance / deductionAmount);
|
||||
|
||||
quotaInfo.balance = balance;
|
||||
quotaInfo.deductionAmount = deductionAmount;
|
||||
quotaInfo.estimatedRuns = estimatedRuns;
|
||||
|
||||
if (balance <= 0) {
|
||||
quotaInfo.status = "exhausted";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "fail",
|
||||
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: `请前往后台充值补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
|
||||
});
|
||||
} else if (estimatedRuns < 10) {
|
||||
quotaInfo.status = "low";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: `建议补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
|
||||
});
|
||||
} else {
|
||||
quotaInfo.status = "sufficient";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "pass",
|
||||
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
|
||||
details: { balance, deductionAmount, estimatedRuns }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
|
||||
details: { features: features.map((f: any) => f?.code) }
|
||||
});
|
||||
}
|
||||
|
||||
// Rule quota
|
||||
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
|
||||
if (ruleFeat) {
|
||||
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
|
||||
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Rules & Draft State Probe
|
||||
let rulesSummary = {
|
||||
totalCount: 0,
|
||||
activeCount: 0,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
};
|
||||
|
||||
try {
|
||||
const rulesData = await api.listApprovalRules(client);
|
||||
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
|
||||
rulesSummary.totalCount = rules.length;
|
||||
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
|
||||
|
||||
if (rules.length === 0) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "warn",
|
||||
summary: "当前租户未配置任何审核规则 (规则数为 0)",
|
||||
details: { totalCount: 0, activeCount: 0 },
|
||||
recommendation: environment === "test" && boundCorpId
|
||||
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
|
||||
: "可运行 seal-use rules add 创建基础规则"
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "pass",
|
||||
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
|
||||
details: {
|
||||
totalCount: rulesSummary.totalCount,
|
||||
activeCount: rulesSummary.activeCount,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "fail",
|
||||
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Webhook Integration Probe
|
||||
let webhooksSummary = {
|
||||
integrationCount: 0,
|
||||
hasReplayChannel: false,
|
||||
activeWebhookId: undefined as string | undefined
|
||||
};
|
||||
|
||||
try {
|
||||
const integrations = await api.listWebhookIntegrations(client);
|
||||
webhooksSummary.integrationCount = integrations.length;
|
||||
|
||||
const replayChannel = integrations.find(
|
||||
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
|
||||
);
|
||||
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
|
||||
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
|
||||
|
||||
if (integrations.length === 0) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "pass",
|
||||
summary: "未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将自动创建)",
|
||||
details: { integrationCount: 0 }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "pass",
|
||||
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
|
||||
details: {
|
||||
integrationCount: integrations.length,
|
||||
hasReplayChannel: webhooksSummary.hasReplayChannel,
|
||||
activeWebhookId: webhooksSummary.activeWebhookId
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "warn",
|
||||
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Environment Pairing Probe
|
||||
if (environment === "test") {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "pass",
|
||||
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "warn",
|
||||
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "pass",
|
||||
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "warn",
|
||||
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Compute overall verdict
|
||||
const failedChecks = checks.filter((c) => c.status === "fail").length;
|
||||
const warningChecks = checks.filter((c) => c.status === "warn").length;
|
||||
const passedChecks = checks.filter((c) => c.status === "pass").length;
|
||||
|
||||
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
|
||||
if (failedChecks > 0) {
|
||||
verdict = "BLOCKED";
|
||||
} else if (warningChecks > 0) {
|
||||
verdict = "DEGRADED";
|
||||
}
|
||||
|
||||
return {
|
||||
ok: failedChecks === 0,
|
||||
verdict,
|
||||
timestamp: new Date().toISOString(),
|
||||
corp: {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
environment,
|
||||
sourceType: corp.source?.type ?? "native",
|
||||
boundCorpId,
|
||||
boundCorpRole,
|
||||
boundCorpRoleDescription
|
||||
},
|
||||
summary: {
|
||||
totalChecks: checks.length,
|
||||
passedChecks,
|
||||
warningChecks,
|
||||
failedChecks
|
||||
},
|
||||
checks,
|
||||
quota: quotaInfo,
|
||||
rules: rulesSummary,
|
||||
webhooks: webhooksSummary
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
|
||||
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
|
||||
|
||||
const verdictBadge =
|
||||
verdict === "HEALTHY"
|
||||
? "🟢 健康良好 (HEALTHY)"
|
||||
: verdict === "DEGRADED"
|
||||
? "🟡 亚健康降级 (DEGRADED)"
|
||||
: "🔴 阻断受限 (BLOCKED)";
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
|
||||
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
|
||||
" " + "─".repeat(60)
|
||||
];
|
||||
|
||||
// Core metrics overview
|
||||
lines.push(
|
||||
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
|
||||
);
|
||||
if (corp.boundCorpId) {
|
||||
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
|
||||
}
|
||||
lines.push(" " + "─".repeat(60));
|
||||
|
||||
for (const check of checks) {
|
||||
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
|
||||
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
|
||||
if (check.recommendation) {
|
||||
lines.push(` 👉 建议: ${check.recommendation}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(" " + "─".repeat(60));
|
||||
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
|
||||
if (quota.status === "exhausted" || quota.status === "low") {
|
||||
lines.push(` 👉 Next action: seal-use auth link --corp ${corp.id}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { isAbsolute, join, resolve } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../../core/paths.js";
|
||||
import { builtinRuleLinter } from "./builtin.js";
|
||||
import { hlabRuleLinter } from "./hlab.js";
|
||||
import { OFFICIAL_LINTER_TEMPLATES } from "./official-templates.js";
|
||||
import { strictRuleLinter } from "./strict.js";
|
||||
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
|
||||
|
||||
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
|
||||
export { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR };
|
||||
export const OFFICIAL_SUBDIR_NAME = "official";
|
||||
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, OFFICIAL_SUBDIR_NAME);
|
||||
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
|
||||
|
||||
export interface LoadedLinter {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { CliError } from "../../../cli/errors.js";
|
||||
import { CliError } from "../../../core/errors.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import * as api from "../api.js";
|
||||
|
||||
+3
-4256
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,836 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const approvalRunsTools = [
|
||||
{
|
||||
name: "seal_approval_runs_search",
|
||||
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,
|
||||
search: query
|
||||
}));
|
||||
const records = await prepareApprovalRuns(client, data.records, {
|
||||
humanResult: params.humanResult
|
||||
});
|
||||
|
||||
return {
|
||||
...data,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_runs_summary",
|
||||
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("运行记录创建开始时间戳(毫秒),对应前端 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 中做本地包含匹配")
|
||||
}),
|
||||
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: params.startDate,
|
||||
endDate: params.endDate,
|
||||
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: "seal_approval_runs_export",
|
||||
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: ToolContext
|
||||
) => exportApprovalRunsToExcel(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_get",
|
||||
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: "seal_approval_run_flow_get",
|
||||
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: ToolContext
|
||||
) => {
|
||||
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 new Error("必须提供 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
|
||||
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
|
||||
: 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
|
||||
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
|
||||
: 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: "seal_approval_run_cited_rules_get",
|
||||
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 extractCitedRules(record);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_document_summary_get",
|
||||
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: "seal_approval_run_attachments_get",
|
||||
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: "seal_approval_run_result_get",
|
||||
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: "seal_approval_run_url_get",
|
||||
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: ToolContext
|
||||
) => {
|
||||
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;
|
||||
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
|
||||
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 identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
|
||||
let warning: string | undefined;
|
||||
|
||||
if (useAutoLogin) {
|
||||
if (isHoseDoc) {
|
||||
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
|
||||
}
|
||||
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}`;
|
||||
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
|
||||
|
||||
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 ? " (管理员)" : "";
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
|
||||
console.error(
|
||||
`⚠️ 安全警示 (免密直达链接):\n` +
|
||||
`• 身份主体:${userName}${roleLabel}\n` +
|
||||
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
|
||||
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
|
||||
);
|
||||
}
|
||||
|
||||
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
|
||||
const activeMode = useAutoLogin ? "auto_login" : "direct";
|
||||
|
||||
return {
|
||||
url: activeUrl,
|
||||
type: linkType,
|
||||
mode: activeMode,
|
||||
sealResultUrl,
|
||||
hoseDocumentUrl,
|
||||
// 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 ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_pick",
|
||||
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: ToolContext
|
||||
) => {
|
||||
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);
|
||||
const nextRuleVersionPayload = nextRuleVersionNumber === undefined
|
||||
? '"latestRuleVersion":true'
|
||||
: `"ruleVersionNumber":${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 tool seal_approval_search --corp ${context.corp.id} --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${nextRuleVersionPayload}}'`,
|
||||
getVersionContext: `seal-use tool seal_approval_context_get --corp ${context.corp.id} --json '{${nextRuleVersionPayload}}'`
|
||||
},
|
||||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_langfuse_bridge_get",
|
||||
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: "seal_approval_runs_stats",
|
||||
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: "seal_approval_runs_count",
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,179 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const billingTools = [
|
||||
{
|
||||
name: "seal_llm_config_get",
|
||||
description: "查询当前 Seal 租户的大模型 (LLM) 配置",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.getLlmConfig(client)
|
||||
},
|
||||
{
|
||||
name: "seal_llm_providers_list",
|
||||
description: "查询支持的大模型 (LLM) 供应商与配置属性字段",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listLlmProviders(client)
|
||||
},
|
||||
{
|
||||
name: "seal_permissions_available_list",
|
||||
description: "查询系统可选权限清单(如超级管理员、智能审核管理、数据管理等)",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listAvailablePermissions(client)
|
||||
},
|
||||
{
|
||||
name: "seal_permissions_configs_list",
|
||||
description: "查询当前租户已绑定的权限配置",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listPermissionConfigs(client)
|
||||
},
|
||||
{
|
||||
name: "seal_billing_status_get",
|
||||
description: "查询当前 Seal 租户的订阅状态与各功能额度(AI审批、审核规则、知识文档等)",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.getBillingStatus(client)
|
||||
},
|
||||
{
|
||||
name: "seal_billing_plans_list",
|
||||
description: "查询系统支持的订阅套餐列表",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listBillingPlans(client)
|
||||
},
|
||||
{
|
||||
name: "seal_billing_features_list",
|
||||
description: "查询系统支持的功能特性定义列表",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listBillingFeatures(client)
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,176 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const contactsTools = [
|
||||
{
|
||||
name: "seal_contacts_departments_root_list",
|
||||
description: "列出当前 Seal 租户通讯录的顶级部门",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listRootDepartments(client)
|
||||
},
|
||||
{
|
||||
name: "seal_contacts_department_get",
|
||||
description: "获取指定通讯录部门的详细信息",
|
||||
parameters: z.object({
|
||||
departmentId: z.string().describe("部门 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { departmentId: string }) =>
|
||||
api.getDepartment(client, params.departmentId)
|
||||
},
|
||||
{
|
||||
name: "seal_contacts_department_children_list",
|
||||
description: "列出指定通讯录部门的直接子部门",
|
||||
parameters: z.object({
|
||||
departmentId: z.string().describe("部门 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { departmentId: string }) =>
|
||||
api.listDepartmentChildren(client, params.departmentId)
|
||||
},
|
||||
{
|
||||
name: "seal_contacts_department_users_list",
|
||||
description: "列出指定通讯录部门下的用户",
|
||||
parameters: z.object({
|
||||
departmentId: z.string().describe("部门 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { departmentId: string }) =>
|
||||
api.listDepartmentUsers(client, params.departmentId)
|
||||
},
|
||||
{
|
||||
name: "seal_contacts_last_sync_time_get",
|
||||
description: "查询通讯录最后同步时间",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.getContactsLastSyncTime(client)
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,331 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const deployTools = [
|
||||
{
|
||||
name: "seal_deploy_hosecloud_requirements",
|
||||
description: "获取 Seal AI 审批发布到合思费控所需配置字段与说明",
|
||||
parameters: z.object({}),
|
||||
handler: async () => {
|
||||
return {
|
||||
input: "JSON via --json '{\"apiKey\":\"...\",\"apiSecret\":\"...\",\"mode\":\"assisted\"}'",
|
||||
questions: [
|
||||
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom,未指定时自动探测)", required: false, default: "production" },
|
||||
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?(如专属私有云域名)", requiredWhen: "apiOrigin=custom" },
|
||||
{ field: "apiKey", prompt: "合思 API Key(appKey)是什么?", required: true, secret: true },
|
||||
{ field: "apiSecret", prompt: "合思 API Secret(appSecurity)是什么?", required: true, secret: true },
|
||||
{ field: "mode", prompt: "使用全自动、半自动还是辅助审核?(fully_automatic/semi_automatic/assisted)", required: true, default: "assisted" },
|
||||
{ field: "autoApprovalRate", prompt: "自动审批比例是多少?(0-100)", requiredWhen: "mode!=assisted" },
|
||||
{ field: "rejectResubmitMethod", prompt: "驳回重提后从哪个节点继续?(node_default/to_ebot/from_start)" },
|
||||
{ field: "autoApproveNodeNames", prompt: "哪些节点允许自动审批?(string[])" },
|
||||
{ field: "outboundName", prompt: "合思审批流节点消息名称是什么?", default: "SealAI 审批" }
|
||||
]
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_deploy_hosecloud_list",
|
||||
description: "列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
|
||||
return {
|
||||
count: integrations.length,
|
||||
integrations: integrations.map(redactIntegrationSecrets)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_deploy_hosecloud_get",
|
||||
description: "查询【Seal AI 审批发布到合思费控】的单项配置详情",
|
||||
parameters: z.object({
|
||||
signKey: z.string().describe("合思集成 sign-key")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { signKey: string }) => {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const integration = (config.integrations ?? []).find(
|
||||
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
|
||||
);
|
||||
if (!integration) {
|
||||
throw new Error(`未找到合思配置:${params.signKey}`);
|
||||
}
|
||||
return redactIntegrationSecrets(integration as Record<string, unknown>);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_deploy_hosecloud_status",
|
||||
description: "检查【Seal AI 审批发布到合思费控】与多平台集成状态",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const status = await api.getSimulationIntegrationStatus(client);
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
|
||||
return {
|
||||
status,
|
||||
integrations: integrations.map(redactIntegrationSecrets)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_deploy_hosecloud_configure",
|
||||
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
|
||||
parameters: z.object({
|
||||
apiKey: z.string().describe("合思 API Key (appKey)"),
|
||||
apiSecret: z.string().describe("合思 API Secret (appSecurity)"),
|
||||
signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"),
|
||||
outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"),
|
||||
specificationId: z.string().optional(),
|
||||
specificationName: z.string().optional(),
|
||||
mode: z.enum(["fully_automatic", "semi_automatic", "assisted"]).default("assisted"),
|
||||
autoApprovalRate: z.number().min(0).max(100).optional(),
|
||||
rejectResubmitMethod: z.enum(["node_default", "to_ebot", "from_start"]).optional(),
|
||||
autoApproveNodeNames: z.array(z.string()).optional(),
|
||||
apiOrigin: z.string().default("production"),
|
||||
customApiUrl: z.string().optional(),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: ToolContext) => {
|
||||
const { dryRun, ...inputParams } = rawParams;
|
||||
const apiKey = inputParams.apiKey ?? (inputParams as any).appKey;
|
||||
const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity;
|
||||
if (!apiKey || !apiSecret) {
|
||||
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
|
||||
}
|
||||
const params = { ...inputParams, apiKey, apiSecret };
|
||||
let effectiveApiOrigin = params.apiOrigin ?? "production";
|
||||
let effectiveCustomApiUrl = params.customApiUrl;
|
||||
|
||||
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
|
||||
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
|
||||
try {
|
||||
const probe = await probeHoseDomain(params.apiKey, params.apiSecret);
|
||||
if (probe?.domain) {
|
||||
if (probe.domain === "https://app.ekuaibao.com") {
|
||||
effectiveApiOrigin = "production";
|
||||
effectiveCustomApiUrl = undefined;
|
||||
} else {
|
||||
effectiveApiOrigin = "custom";
|
||||
effectiveCustomApiUrl = probe.domain;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探测失败时平滑降级,由后续后端校验处理
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
|
||||
throw new Error("自定义合思环境必须提供 customApiUrl");
|
||||
}
|
||||
|
||||
const corpResult = await api.getHosecloudCorporation(client, {
|
||||
apiKey: params.apiKey,
|
||||
apiSecret: params.apiSecret,
|
||||
apiOrigin: effectiveApiOrigin,
|
||||
customApiUrl: effectiveCustomApiUrl
|
||||
});
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const signKey = params.signKey ?? randomBytes(6).toString("hex");
|
||||
const nextIntegration = {
|
||||
type: "hosecloud",
|
||||
...params,
|
||||
apiOrigin: effectiveApiOrigin,
|
||||
...(effectiveCustomApiUrl ? { customApiUrl: effectiveCustomApiUrl } : {}),
|
||||
signKey,
|
||||
corporationId: corpResult.corporationId
|
||||
};
|
||||
const existing = (config.integrations ?? []).filter(
|
||||
(item: any) => item.type !== "hosecloud" || item.signKey !== signKey
|
||||
);
|
||||
existing.push(nextIntegration);
|
||||
const nextConfig = {
|
||||
...config,
|
||||
integrationSystem: "hosecloud",
|
||||
integrations: existing
|
||||
};
|
||||
if (dryRun) {
|
||||
return mutationPreview(
|
||||
context,
|
||||
context.corp.seal.endpoints.approvalStylePreferences,
|
||||
config,
|
||||
nextConfig,
|
||||
1
|
||||
);
|
||||
}
|
||||
await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences);
|
||||
|
||||
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
|
||||
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`);
|
||||
|
||||
return {
|
||||
integration: redactIntegrationSecrets(nextIntegration)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_deploy_hosecloud_sync",
|
||||
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
|
||||
parameters: z.object({
|
||||
signKey: z.string().describe("合思集成 sign-key")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { signKey: string }, context: ToolContext) => {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const integration = (config.integrations ?? []).find(
|
||||
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
|
||||
);
|
||||
if (!integration) {
|
||||
throw new Error(`未找到合思配置:${params.signKey}`);
|
||||
}
|
||||
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
||||
const messageName = (integration as any).outboundName ?? "SealAI 审批";
|
||||
const result = await api.syncHosecloudOutbound(client, {
|
||||
signKey: params.signKey,
|
||||
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
|
||||
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
|
||||
messageName,
|
||||
mode: (integration as any).mode ?? "assisted"
|
||||
});
|
||||
|
||||
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
|
||||
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
|
||||
|
||||
return {
|
||||
signKey: params.signKey,
|
||||
synced: true,
|
||||
result
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,251 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const identityTools = [
|
||||
{
|
||||
name: "seal_whoami",
|
||||
description: "查询当前 Seal 用户身份及租户信息",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.getMe(client)
|
||||
},
|
||||
{
|
||||
name: "seal_session_get",
|
||||
description: "查询当前 Seal Bearer session、用户和过期时间",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.getSession(client)
|
||||
},
|
||||
{
|
||||
name: "seal_delegation_list",
|
||||
description: "查询当前 Seal 租户下的授权链接 (Delegation) 列表",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => api.listDelegations(client)
|
||||
},
|
||||
{
|
||||
name: "seal_delegation_create",
|
||||
description: "创建新的 Seal 授权链接 (Delegation)",
|
||||
parameters: z.object({
|
||||
note: z.string().optional().describe("授权链接的备注或说明信息")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { note?: string }) =>
|
||||
api.createDelegation(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_delegation_revoke",
|
||||
description: "撤销/废除指定的 Seal 授权链接 (Delegation)",
|
||||
parameters: z.object({
|
||||
tokenId: z.string().describe("授权链接 ID (delegation record ID)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { tokenId: string }) =>
|
||||
api.revokeDelegation(client, params.tokenId)
|
||||
},
|
||||
{
|
||||
name: "seal_user_create",
|
||||
description: "创建本地 Seal 用户,生成并返回初始随机密码",
|
||||
parameters: z.object({
|
||||
name: z.string().describe("用户姓名"),
|
||||
phone: z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),
|
||||
permissions: z.array(z.string()).optional().describe("权限列表,默认为 []"),
|
||||
departmentIds: z.array(z.string()).optional().describe("关联部门 ID 数组")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
|
||||
) => api.createLocalUser(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_user_reset_password",
|
||||
description: "重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",
|
||||
parameters: z.object({
|
||||
userId: z.string().describe("用户 ID (_id)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { userId: string }) =>
|
||||
api.resetUserPassword(client, params.userId)
|
||||
},
|
||||
{
|
||||
name: "seal_user_get",
|
||||
description: "获取指定 Seal 用户的详细信息",
|
||||
parameters: z.object({
|
||||
userId: z.string().describe("用户 ID (_id)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { userId: string }) =>
|
||||
api.getUserDetail(client, params.userId)
|
||||
},
|
||||
{
|
||||
name: "seal_user_search",
|
||||
description: "按姓名、手机号或邮箱搜索 Seal 成员用户列表",
|
||||
parameters: z.object({
|
||||
keyword: z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { keyword?: string }) =>
|
||||
api.searchUsers(client, params.keyword ?? "")
|
||||
},
|
||||
{
|
||||
name: "seal_user_delete",
|
||||
description: "删除指定 Seal 本地用户",
|
||||
parameters: z.object({
|
||||
userId: z.string().describe("用户 ID (_id)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { userId: string }) =>
|
||||
api.deleteLocalUser(client, params.userId)
|
||||
},
|
||||
{
|
||||
name: "seal_user_activate",
|
||||
description: "启用/激活已离职的 Seal 用户账号",
|
||||
parameters: z.object({
|
||||
userId: z.string().describe("用户 ID (_id)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { userId: string }) =>
|
||||
api.activateLocalUser(client, params.userId)
|
||||
},
|
||||
{
|
||||
name: "seal_user_delegation_create",
|
||||
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
|
||||
parameters: z.object({
|
||||
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
|
||||
note: z.string().optional().describe("授权链接备注信息")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { userIdOrPhone: string; note?: string },
|
||||
context: ToolContext
|
||||
) =>
|
||||
api.createDelegationForUser(
|
||||
client,
|
||||
params,
|
||||
(token) => createSealClientForToken(context.corp, token),
|
||||
context.corp
|
||||
)
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,157 @@
|
||||
import { identityTools } from "./identity.js";
|
||||
import { contactsTools } from "./contacts.js";
|
||||
import { insightTools } from "./insight.js";
|
||||
import { billingTools } from "./billing.js";
|
||||
import { rulesTools } from "./rules.js";
|
||||
import { webhookTools } from "./webhook.js";
|
||||
import { approvalRunsTools } from "./approval-runs.js";
|
||||
import { simulationTools } from "./simulation.js";
|
||||
import { deployTools } from "./deploy.js";
|
||||
import { preferenceTools } from "./preference.js";
|
||||
|
||||
export * from "./helpers.js";
|
||||
|
||||
export const sealTools = [
|
||||
...identityTools,
|
||||
...contactsTools,
|
||||
...insightTools,
|
||||
...billingTools,
|
||||
...rulesTools,
|
||||
...webhookTools,
|
||||
...approvalRunsTools,
|
||||
...simulationTools,
|
||||
...deployTools,
|
||||
...preferenceTools
|
||||
];
|
||||
|
||||
export type SealTool = (typeof sealTools)[number];
|
||||
|
||||
/**
|
||||
* MCP read/write classification for the tool registry.
|
||||
*
|
||||
* The two sets are exhaustive by construction: `tools.test.ts` asserts they partition `sealTools`
|
||||
* exactly, so a newly added tool fails the suite until it is classified here. The read-only MCP tool
|
||||
* (`seal_cli`) may only invoke names in {@link SEAL_READ_ONLY_TOOLS}; everything else is reachable
|
||||
* solely through `seal_cli_write`.
|
||||
*
|
||||
* Read-only means it reads tenant state, or writes only a local file. Anything that creates, updates,
|
||||
* deletes, publishes, pushes, replays, uploads, activates or mints a credential counts as mutating —
|
||||
* including when it reads like a query. `seal_insight_record_analyze` is the instructive case: it
|
||||
* sounds like a read but issues a POST that starts an analysis server-side.
|
||||
*/
|
||||
export const SEAL_READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
|
||||
"seal_approval_context_get",
|
||||
"seal_approval_document_get",
|
||||
"seal_approval_documents_list",
|
||||
"seal_approval_rule_get",
|
||||
"seal_approval_rule_version_diff",
|
||||
"seal_approval_rule_version_get",
|
||||
"seal_approval_rule_versions_list",
|
||||
"seal_approval_rules_lint",
|
||||
"seal_approval_rules_list",
|
||||
"seal_approval_rules_pull",
|
||||
"seal_approval_run_attachments_get",
|
||||
"seal_approval_run_cited_rules_get",
|
||||
"seal_approval_run_document_summary_get",
|
||||
"seal_approval_run_flow_get",
|
||||
"seal_approval_run_get",
|
||||
"seal_approval_run_langfuse_bridge_get",
|
||||
"seal_approval_run_pick",
|
||||
"seal_approval_run_result_get",
|
||||
"seal_approval_run_url_get",
|
||||
"seal_approval_runs_count",
|
||||
"seal_approval_runs_export",
|
||||
"seal_approval_runs_search",
|
||||
"seal_approval_runs_stats",
|
||||
"seal_approval_runs_summary",
|
||||
"seal_approval_search",
|
||||
"seal_approval_style_preferences_get",
|
||||
"seal_billing_features_list",
|
||||
"seal_billing_plans_list",
|
||||
"seal_billing_status_get",
|
||||
"seal_contacts_department_children_list",
|
||||
"seal_contacts_department_get",
|
||||
"seal_contacts_department_users_list",
|
||||
"seal_contacts_departments_root_list",
|
||||
"seal_contacts_last_sync_time_get",
|
||||
"seal_delegation_list",
|
||||
"seal_deploy_hosecloud_get",
|
||||
"seal_deploy_hosecloud_list",
|
||||
"seal_deploy_hosecloud_requirements",
|
||||
"seal_deploy_hosecloud_status",
|
||||
"seal_expenses_list",
|
||||
"seal_insight_export",
|
||||
"seal_insight_performance_get",
|
||||
"seal_insight_risks_by_tag_get",
|
||||
"seal_insight_stats_get",
|
||||
"seal_invoices_list",
|
||||
"seal_llm_config_get",
|
||||
"seal_llm_providers_list",
|
||||
"seal_permissions_available_list",
|
||||
"seal_permissions_configs_list",
|
||||
"seal_preference_get",
|
||||
"seal_preference_thinking_depth_policies_list",
|
||||
"seal_session_get",
|
||||
"seal_simulation_batch_get",
|
||||
"seal_simulation_batch_records_get",
|
||||
"seal_simulation_batch_status",
|
||||
"seal_simulation_batch_wait",
|
||||
"seal_simulation_batches_list",
|
||||
"seal_simulation_feishu_approval_definitions_list",
|
||||
"seal_simulation_integrations_get",
|
||||
"seal_simulation_specifications_list",
|
||||
"seal_simulation_templates_get",
|
||||
"seal_user_get",
|
||||
"seal_user_search",
|
||||
"seal_webhook_get",
|
||||
"seal_webhook_list",
|
||||
"seal_webhook_ready",
|
||||
"seal_whoami"
|
||||
]);
|
||||
|
||||
export const SEAL_MUTATING_TOOLS: ReadonlySet<string> = new Set([
|
||||
"seal_approval_delete_document",
|
||||
"seal_approval_document_create",
|
||||
"seal_approval_document_update",
|
||||
"seal_approval_rule_create",
|
||||
"seal_approval_rule_delete",
|
||||
"seal_approval_rule_update",
|
||||
"seal_approval_rule_version_publish",
|
||||
"seal_approval_rules_clear",
|
||||
"seal_approval_rules_push",
|
||||
"seal_approval_style_preferences_update",
|
||||
"seal_delegation_create",
|
||||
"seal_delegation_revoke",
|
||||
"seal_deploy_hosecloud_configure",
|
||||
"seal_deploy_hosecloud_sync",
|
||||
"seal_insight_record_analyze",
|
||||
"seal_preference_decision_update",
|
||||
"seal_preference_thinking_depth_policies_remove",
|
||||
"seal_preference_thinking_depth_policies_upsert",
|
||||
"seal_preference_thinking_depth_set",
|
||||
"seal_simulation_batch_clean",
|
||||
"seal_simulation_batch_create",
|
||||
"seal_simulation_material_package_upload",
|
||||
"seal_user_activate",
|
||||
"seal_user_create",
|
||||
"seal_user_delegation_create",
|
||||
"seal_user_delete",
|
||||
"seal_user_reset_password",
|
||||
"seal_webhook_add",
|
||||
"seal_webhook_delete",
|
||||
"seal_webhook_material_pack",
|
||||
"seal_webhook_replay",
|
||||
"seal_webhook_update"
|
||||
]);
|
||||
|
||||
export function isReadOnlySealTool(name: string): boolean {
|
||||
return SEAL_READ_ONLY_TOOLS.has(name);
|
||||
}
|
||||
|
||||
const sealToolByName = new Map<string, SealTool>(
|
||||
sealTools.map((tool) => [tool.name, tool])
|
||||
);
|
||||
|
||||
export function findSealTool(name: string): SealTool | undefined {
|
||||
return sealToolByName.get(name);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const insightTools = [
|
||||
{
|
||||
name: "seal_insight_stats_get",
|
||||
description: "查询智能洞察风险标签统计及分析状态",
|
||||
parameters: z.object({
|
||||
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
|
||||
endDate: z.string().optional().describe("统计结束时间(ISO 8601)"),
|
||||
limit: z.number().int().positive().max(100).optional().describe("最多返回的风险标签数量")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { startDate?: string; endDate?: string; limit?: number }
|
||||
) => api.getInsightStats(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_risks_by_tag_get",
|
||||
description: "按风险标签查询智能洞察风险单据明细及 AI 分析依据",
|
||||
parameters: z.object({
|
||||
tagId: z.string().describe("风险标签 ID(如 B.1.1、B.1.6)"),
|
||||
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
|
||||
endDate: z.string().optional().describe("统计结束时间(ISO 8601)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { tagId: string; startDate?: string; endDate?: string }
|
||||
) => api.getInsightRisksByTag(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_performance_get",
|
||||
description: "查询智能洞察审核效能指标(自动化率、准确率等)及决策流向桑基图",
|
||||
parameters: z.object({
|
||||
startDate: z.union([z.string(), z.number()]).optional().describe("统计开始时间(ISO 8601 或毫秒时间戳)"),
|
||||
endDate: z.union([z.string(), z.number()]).optional().describe("统计结束时间(ISO 8601 或毫秒时间戳)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { startDate?: string | number; endDate?: string | number }
|
||||
) => api.getInsightPerformance(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_record_analyze",
|
||||
description: "对指定的审批单运行记录按需触发智能洞察风险分析",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("审批单运行记录 ID (recordId)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId: string }
|
||||
) => api.analyzeInsightRecord(client, params.recordId)
|
||||
},
|
||||
{
|
||||
name: "seal_insight_export",
|
||||
description: "导出智能洞察风险研报为高保真 Excel 文件(含效能概览、Top风险标签、风险单据穿透明细)",
|
||||
parameters: z.object({
|
||||
startDate: z.string().optional().describe("统计开始时间(ISO 8601 或时间戳)"),
|
||||
endDate: z.string().optional().describe("统计结束时间(ISO 8601 或时间戳)"),
|
||||
limit: z.number().int().positive().optional().describe("最多下钻分析的风险标签数量"),
|
||||
outputFile: z.string().optional().describe("自定义 Excel 保存路径"),
|
||||
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录"),
|
||||
force: z.boolean().optional().describe("时间跨度超过 180 天时是否强制导出")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: InsightExportOptions,
|
||||
context: ToolContext
|
||||
) => exportInsightReportToExcel(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "seal_expenses_list",
|
||||
description: "分页查询费用明细",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
startDate: z.string().optional().describe("开始时间"),
|
||||
endDate: z.string().optional().describe("结束时间"),
|
||||
search: z.string().optional().describe("搜索费用类型、描述或金额")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: api.DataListParams) => api.listExpenses(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_invoices_list",
|
||||
description: "分页查询进项发票",
|
||||
parameters: z.object({
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
startDate: z.string().optional().describe("开始时间"),
|
||||
endDate: z.string().optional().describe("结束时间"),
|
||||
search: z.string().optional().describe("搜索发票号码或销售方")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: api.DataListParams) => api.listInvoices(client, params)
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,267 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const preferenceTools = [
|
||||
{
|
||||
name: "seal_preference_get",
|
||||
description: "获取当前决策偏好、思考深度偏好与绑定的规则版本",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const config = (await api.getApprovalStylePreferences(client)) as any;
|
||||
return {
|
||||
decisionPreferences: config.decisionPreferences,
|
||||
thinkingDepthPreference: config.thinkingDepthPreference,
|
||||
ruleSetVersionId: config.ruleSetVersionId
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_preference_decision_update",
|
||||
description: "修改审核决策偏好(立即影响当前运行中的审核智能体及后续决策)",
|
||||
parameters: z.object({
|
||||
explicitApprove: z.string().optional(),
|
||||
explicitReject: z.string().optional(),
|
||||
exemptApprove: z.string().optional(),
|
||||
review: z.string().optional(),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: Partial<DecisionPreferences> & { dryRun?: boolean }, context: ToolContext) => {
|
||||
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
|
||||
const { dryRun, ...changes } = params;
|
||||
const updated = {
|
||||
...config,
|
||||
decisionPreferences: {
|
||||
...config.decisionPreferences,
|
||||
...changes
|
||||
}
|
||||
};
|
||||
if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
|
||||
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
|
||||
return {
|
||||
decisionPreferences: updated.decisionPreferences
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_preference_thinking_depth_set",
|
||||
description: "修改默认思考深度(medium 或 high)",
|
||||
parameters: z.object({
|
||||
defaultLevel: z.enum(["medium", "high"]).describe("默认思考深度"),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { defaultLevel: "medium" | "high"; dryRun?: boolean }, context: ToolContext) => {
|
||||
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
|
||||
const updated = {
|
||||
...config,
|
||||
thinkingDepthPreference: {
|
||||
defaultLevel: params.defaultLevel,
|
||||
routingPolicies: config.thinkingDepthPreference?.routingPolicies ?? []
|
||||
}
|
||||
};
|
||||
if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
|
||||
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
|
||||
return {
|
||||
thinkingDepthPreference: updated.thinkingDepthPreference
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_preference_thinking_depth_policies_list",
|
||||
description: "列出思考深度路由策略列表",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const config = (await api.getApprovalStylePreferences(client)) as any;
|
||||
return {
|
||||
policies: config.thinkingDepthPreference?.routingPolicies ?? []
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_preference_thinking_depth_policies_upsert",
|
||||
description: "新增或修改思考深度路由策略",
|
||||
parameters: ThinkingPolicySchema.extend({
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (client: KyInstance, policy: ThinkingPolicy & { dryRun?: boolean }, context: ToolContext) => {
|
||||
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
|
||||
const { dryRun, ...cleanPolicy } = policy;
|
||||
const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? [];
|
||||
const next = existing.filter((item) => item.id !== cleanPolicy.id);
|
||||
next.push(cleanPolicy);
|
||||
const updated = {
|
||||
...config,
|
||||
thinkingDepthPreference: {
|
||||
defaultLevel: config.thinkingDepthPreference?.defaultLevel ?? "medium",
|
||||
routingPolicies: next
|
||||
}
|
||||
};
|
||||
if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
|
||||
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
|
||||
return {
|
||||
policy: cleanPolicy,
|
||||
policies: next
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_preference_thinking_depth_policies_remove",
|
||||
description: "删除一条思考深度路由策略",
|
||||
parameters: z.object({
|
||||
policyId: z.string().describe("路由策略 ID"),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { policyId: string; dryRun?: boolean }, context: ToolContext) => {
|
||||
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
|
||||
const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? [];
|
||||
const next = existing.filter((item) => item.id !== params.policyId);
|
||||
if (next.length === existing.length) {
|
||||
throw new Error(`未找到路由策略:${params.policyId}`);
|
||||
}
|
||||
const updated = {
|
||||
...config,
|
||||
thinkingDepthPreference: {
|
||||
defaultLevel: config.thinkingDepthPreference?.defaultLevel ?? "medium",
|
||||
routingPolicies: next
|
||||
}
|
||||
};
|
||||
if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
|
||||
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
|
||||
return {
|
||||
removedId: params.policyId,
|
||||
policies: next
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,938 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const rulesTools = [
|
||||
{
|
||||
name: "seal_approval_rules_list",
|
||||
description: "列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文",
|
||||
parameters: z.object({
|
||||
countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"),
|
||||
fields: z.array(z.enum([
|
||||
"id",
|
||||
"code",
|
||||
"tenantId",
|
||||
"status",
|
||||
"strictness",
|
||||
"scope",
|
||||
"createdAt",
|
||||
"updatedAt",
|
||||
"description"
|
||||
])).optional().describe("只返回指定字段;不传则返回完整规则"),
|
||||
limit: z.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),
|
||||
offset: z.number().int().nonnegative().optional().describe("跳过前多少条规则")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
countOnly?: boolean;
|
||||
fields?: RuleField[];
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
) => {
|
||||
const data = await api.listApprovalRules(client);
|
||||
return projectApprovalRules(data, params);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_clear",
|
||||
description: "清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",
|
||||
parameters: z.object({
|
||||
dryRun: z.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),
|
||||
recode: z.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { dryRun?: boolean; recode?: boolean },
|
||||
context: ToolContext
|
||||
) => {
|
||||
const before = await api.listApprovalRules(client);
|
||||
if (params.dryRun) {
|
||||
return {
|
||||
...mutationPreview(context, "api/v1/rules", before.rules, [], before.rules.length),
|
||||
corpId: context.corp.id,
|
||||
corpName: context.corp.name,
|
||||
dryRun: true,
|
||||
beforeCount: before.rules.length,
|
||||
deleted: 0,
|
||||
afterCount: before.rules.length,
|
||||
hasPendingDeletes: before.hasPendingDeletes
|
||||
};
|
||||
}
|
||||
|
||||
const failed: Array<{ ruleId: string; error: string }> = [];
|
||||
let deleted = 0;
|
||||
for (const rule of before.rules) {
|
||||
try {
|
||||
await api.deleteApprovalRule(client, rule.id);
|
||||
deleted += 1;
|
||||
} catch (error) {
|
||||
failed.push({
|
||||
ruleId: rule.id,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const warnings: string[] = [];
|
||||
let recode: unknown;
|
||||
if (deleted > 0 && params.recode !== false) {
|
||||
recode = await api.recodeApprovalRules(client);
|
||||
if (
|
||||
recode &&
|
||||
typeof recode === "object" &&
|
||||
"ok" in recode &&
|
||||
recode.ok !== true
|
||||
) {
|
||||
warnings.push("batch-recode did not complete; current rules were still deleted");
|
||||
}
|
||||
}
|
||||
|
||||
const after = await api.listApprovalRules(client);
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
corpName: context.corp.name,
|
||||
dryRun: false,
|
||||
beforeCount: before.rules.length,
|
||||
deleted,
|
||||
failed,
|
||||
afterCount: after.rules.length,
|
||||
hasPendingDeletes: after.hasPendingDeletes,
|
||||
warnings,
|
||||
recode
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_create",
|
||||
description: "新建 Seal 草稿审批规则",
|
||||
parameters: z.object({
|
||||
description: z.string().describe("规则描述"),
|
||||
scope: z.string().describe("适用场景"),
|
||||
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { description: string; scope: string; strictness: string }
|
||||
) => api.createApprovalRule(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_update",
|
||||
description: "更新 Seal 草稿审批规则",
|
||||
parameters: z.object({
|
||||
ruleId: z.string().describe("规则 ID"),
|
||||
description: z.string().optional(),
|
||||
scope: z.string().optional(),
|
||||
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
|
||||
) => {
|
||||
let resolvedRuleId = params.ruleId;
|
||||
if (resolvedRuleId && (resolvedRuleId.startsWith("#") || resolvedRuleId.startsWith("rule-") || resolvedRuleId.match(/^\d+$/))) {
|
||||
const draftData = await api.listApprovalRules(client).catch(() => undefined);
|
||||
if (draftData?.rules) {
|
||||
const normalizedInput = normalizeRuleCode(resolvedRuleId);
|
||||
const runtimeIdx = runtimeRuleIndex(resolvedRuleId);
|
||||
const targetIndex = normalizedInput ? Number(normalizedInput.slice(1)) : runtimeIdx;
|
||||
const matched = draftData.rules.find((r, idx) => {
|
||||
const code = normalizeRuleCode(stringFromUnknown((r as any).code) ?? stringFromUnknown((r as any).ruleCode));
|
||||
return code === normalizedInput || (targetIndex !== undefined && idx + 1 === targetIndex);
|
||||
});
|
||||
if (matched) {
|
||||
resolvedRuleId = matched.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
const { ruleId, ...rest } = params;
|
||||
const result = await api.updateApprovalRule(client, resolvedRuleId, rest);
|
||||
|
||||
if (params.description) {
|
||||
try {
|
||||
const globalConfig = loadGlobalConfig();
|
||||
if (globalConfig.lint?.enabled) {
|
||||
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
|
||||
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
|
||||
if (lintResult.issues.length > 0) {
|
||||
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
|
||||
for (const issue of lintResult.issues) {
|
||||
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
|
||||
if (issue.suggestion) {
|
||||
console.error(` 👉 建议: ${issue.suggestion}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 容错降级:质检异常绝不阻断规则更新
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_delete",
|
||||
description: "删除 Seal 草稿审批规则",
|
||||
parameters: z.object({
|
||||
ruleId: z.string().describe("规则 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { ruleId: string }) => {
|
||||
await api.deleteApprovalRule(client, params.ruleId);
|
||||
return { success: true };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_versions_list",
|
||||
description: "列出 Seal 已发布审批规则版本摘要,不展开每个版本的规则快照",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
return {
|
||||
count: versions.length,
|
||||
latest: versions[0] ? summarizeRuleVersion(versions[0]) : undefined,
|
||||
versions: versions.map(summarizeRuleVersion)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_version_get",
|
||||
description: "获取指定 Seal 已发布审批规则版本详情,包含该版本的规则快照",
|
||||
parameters: z.object({
|
||||
versionId: z.string().optional().describe("规则版本 ID"),
|
||||
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
|
||||
latest: z.boolean().optional().describe("为 true 时获取最新版本")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { versionId?: string; versionNumber?: number; latest?: boolean }
|
||||
) => {
|
||||
if (params.versionId) return api.getApprovalRuleVersion(client, params.versionId);
|
||||
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
const version = params.versionNumber
|
||||
? versions.find((item) => item.versionNumber === params.versionNumber)
|
||||
: versions[0];
|
||||
|
||||
if (!version) {
|
||||
throw new Error(params.versionNumber
|
||||
? `Rule version not found: ${params.versionNumber}`
|
||||
: "No rule versions found");
|
||||
}
|
||||
|
||||
return version;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_version_diff",
|
||||
description: "对比两个已发布审批规则版本;优先使用本地持久化稳定 ID,没有时回退到 code",
|
||||
parameters: z.object({
|
||||
from: z.string().min(1).describe("起始规则版本号、版本 ID 或 latest"),
|
||||
to: z.string().min(1).describe("目标规则版本号、版本 ID 或 latest"),
|
||||
ruleId: z.string().optional().describe("只对比指定稳定规则 ID"),
|
||||
code: z.string().optional().describe("只对比指定规则 code"),
|
||||
includeUnchanged: z.boolean().optional().describe("是否返回未变化规则,默认 false"),
|
||||
full: z.boolean().optional().describe("超过默认 diff 上限时返回完整内容"),
|
||||
format: z.enum(["unified", "json"]).default("unified").describe("输出格式;unified 将 diff 文本放入 unifiedDiff 字段")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
from: string;
|
||||
to: string;
|
||||
ruleId?: string;
|
||||
code?: string;
|
||||
includeUnchanged?: boolean;
|
||||
full?: boolean;
|
||||
format?: "unified" | "json";
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const fromVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.from));
|
||||
const toVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.to));
|
||||
let result = diffRuleVersions(fromVersion, toVersion, {
|
||||
includeUnchanged: params.includeUnchanged
|
||||
});
|
||||
if (!params.ruleId && !params.code) return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
|
||||
|
||||
const changes = result.changes.filter((change) => {
|
||||
if (params.ruleId && change.ruleId === params.ruleId) return true;
|
||||
if (!params.code) return false;
|
||||
return normalizedRuleCode(params.code) === normalizedRuleCode(change.before?.code ?? change.before?.ruleCode ?? change.after?.code ?? change.after?.ruleCode ?? change.ruleId);
|
||||
});
|
||||
const counts = { added: 0, removed: 0, modified: 0, unchanged: 0 };
|
||||
for (const change of changes) counts[change.status] += 1;
|
||||
result = {
|
||||
...result,
|
||||
counts,
|
||||
changes,
|
||||
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n")
|
||||
};
|
||||
return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_version_publish",
|
||||
description: "发布 Seal 草稿审批规则为新版本",
|
||||
parameters: z.object({
|
||||
versionName: z.string().describe("版本名称")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { versionName: string }, context: ToolContext) => {
|
||||
const draft = await api.listApprovalRules(client).catch(() => undefined);
|
||||
const published = await api.publishApprovalRuleVersion(client, params.versionName);
|
||||
if (draft) {
|
||||
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
|
||||
}
|
||||
return published;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rule_get",
|
||||
description: "按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照",
|
||||
parameters: z.object({
|
||||
versionId: z.string().optional().describe("规则版本 ID"),
|
||||
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
|
||||
latest: z.boolean().optional().describe("为 true 时取最新版本"),
|
||||
code: z.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),
|
||||
runtimeId: z.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),
|
||||
recordId: z.string().optional().describe("从运行记录推断 ruleSetVersionNumber")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
versionId?: string;
|
||||
versionNumber?: number;
|
||||
latest?: boolean;
|
||||
code?: string;
|
||||
runtimeId?: string;
|
||||
recordId?: string;
|
||||
}
|
||||
) => {
|
||||
const version = await resolveRuleVersionForLookup(client, params);
|
||||
const rule = findRuleInVersion(version, {
|
||||
code: params.code,
|
||||
runtimeId: params.runtimeId
|
||||
});
|
||||
if (!rule) {
|
||||
throw new Error(`Rule not found in version ${version.versionNumber}`);
|
||||
}
|
||||
return rule;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_lint",
|
||||
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
|
||||
parameters: z.object({
|
||||
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
|
||||
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
|
||||
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
|
||||
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
|
||||
ruleId: z.string().optional().describe("按规则 ID 过滤"),
|
||||
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
|
||||
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
|
||||
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
file?: string;
|
||||
linter?: string;
|
||||
version?: string;
|
||||
code?: string;
|
||||
ruleId?: string;
|
||||
minScore?: number;
|
||||
level?: "all" | "error" | "warning";
|
||||
summary?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
let targets: RuleLintTarget[] = [];
|
||||
let versionNumber: number | undefined;
|
||||
|
||||
if (params.file) {
|
||||
const local = loadLocalRulesFile(params.file);
|
||||
targets = localRulesToLintTargets(local.rules);
|
||||
versionNumber = local.meta.versionNumber;
|
||||
} else if (params.version) {
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
const versionNumberParsed = Number(params.version);
|
||||
const version = isNaN(versionNumberParsed)
|
||||
? params.version === "latest"
|
||||
? versions[0]
|
||||
: versions.find((v) => v.id === params.version)
|
||||
: versions.find((v) => v.versionNumber === versionNumberParsed);
|
||||
|
||||
if (!version) {
|
||||
throw new Error(`未找到指定的规则版本: ${params.version}`);
|
||||
}
|
||||
versionNumber = version.versionNumber;
|
||||
targets = (version.rules ?? []).map((r, idx) => ({
|
||||
id: (r as any).id ?? (r as any).runtimeId,
|
||||
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: (r as any).scope,
|
||||
strictness: (r as any).strictness
|
||||
}));
|
||||
} else {
|
||||
const draftData = await api.listApprovalRules(client);
|
||||
targets = (draftData.rules ?? []).map((r, idx) => ({
|
||||
id: r.id,
|
||||
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: r.scope,
|
||||
strictness: r.strictness
|
||||
}));
|
||||
}
|
||||
|
||||
if (params.code) {
|
||||
targets = targets.filter(
|
||||
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
|
||||
);
|
||||
}
|
||||
if (params.ruleId) {
|
||||
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
|
||||
}
|
||||
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
|
||||
const loadedLinter = await loadRuleLinter(linterNameOrPath);
|
||||
|
||||
const batchResult = await lintRuleBatch(
|
||||
targets,
|
||||
loadedLinter,
|
||||
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
|
||||
{ minScore: params.minScore, level: params.level, summary: params.summary }
|
||||
);
|
||||
|
||||
if (params.minScore && batchResult.overallScore < params.minScore) {
|
||||
throw new Error(
|
||||
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
|
||||
);
|
||||
}
|
||||
|
||||
return batchResult;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_pull",
|
||||
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
|
||||
parameters: z.object({
|
||||
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
|
||||
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
version?: string;
|
||||
out?: string;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const outPath = params.out ?? "./rules.local.json";
|
||||
let rules: LocalRuleItem[] = [];
|
||||
let source = "draft";
|
||||
let versionNumber: number | undefined;
|
||||
|
||||
if (params.version) {
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
const versionNumberParsed = Number(params.version);
|
||||
const targetVersion = isNaN(versionNumberParsed)
|
||||
? params.version === "latest"
|
||||
? versions[0]
|
||||
: versions.find((v) => v.id === params.version)
|
||||
: versions.find((v) => v.versionNumber === versionNumberParsed);
|
||||
|
||||
if (!targetVersion) {
|
||||
throw new Error(`未找到指定的规则版本: ${params.version}`);
|
||||
}
|
||||
versionNumber = targetVersion.versionNumber;
|
||||
source = `version:${versionNumber}`;
|
||||
rules = (targetVersion.rules ?? []).map((r, idx) => ({
|
||||
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: (r as any).scope ?? "ALL",
|
||||
strictness: (r as any).strictness ?? "MUST_FOLLOW"
|
||||
}));
|
||||
} else {
|
||||
const draftData = await api.listApprovalRules(client);
|
||||
rules = (draftData.rules ?? []).map((r, idx) => ({
|
||||
id: r.id,
|
||||
code: r.code ?? idx + 1,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: r.scope ?? "ALL",
|
||||
strictness: r.strictness ?? "MUST_FOLLOW",
|
||||
status: r.status
|
||||
}));
|
||||
}
|
||||
|
||||
const savedPath = saveLocalRulesFile(outPath, {
|
||||
corpId: context.corp.id,
|
||||
source,
|
||||
versionNumber,
|
||||
exportedAt: new Date().toISOString(),
|
||||
rulesCount: rules.length,
|
||||
rules
|
||||
});
|
||||
|
||||
return {
|
||||
saved: true,
|
||||
path: savedPath,
|
||||
rulesCount: rules.length,
|
||||
corpId: context.corp.id,
|
||||
source,
|
||||
versionNumber
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_push",
|
||||
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
|
||||
parameters: z.object({
|
||||
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
|
||||
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
|
||||
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
|
||||
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
|
||||
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
file?: string;
|
||||
dryRun?: boolean;
|
||||
confirm?: boolean;
|
||||
publish?: boolean;
|
||||
versionName?: string;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const filePath = params.file ?? "./rules.local.json";
|
||||
const local = loadLocalRulesFile(filePath);
|
||||
const isConfirmed = params.confirm === true;
|
||||
const isDryRun = params.dryRun ?? !isConfirmed;
|
||||
|
||||
const before = await api.listApprovalRules(client);
|
||||
const plan = buildRulePushPlan(before.rules, local.rules);
|
||||
|
||||
if (isDryRun) {
|
||||
return {
|
||||
...mutationPreview(
|
||||
context,
|
||||
"api/v1/rules",
|
||||
before.rules,
|
||||
local.rules.map((rule) => ({
|
||||
description: rule.description,
|
||||
scope: rule.scope ?? "ALL",
|
||||
strictness: rule.strictness ?? "MUST_FOLLOW"
|
||||
})),
|
||||
before.rules.length + local.rules.length
|
||||
),
|
||||
corpId: context.corp.id,
|
||||
dryRun: true,
|
||||
localFile: local.resolvedPath,
|
||||
localRulesCount: local.rules.length,
|
||||
remoteDraftCount: before.rules.length,
|
||||
changes: plan,
|
||||
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
|
||||
preservedRuleIds: [
|
||||
...plan.updated.map((change) => change.id),
|
||||
...plan.unchanged.map((rule) => rule.id)
|
||||
],
|
||||
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
|
||||
willPublish: Boolean(params.publish),
|
||||
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
|
||||
};
|
||||
}
|
||||
|
||||
for (const rule of plan.deleted) {
|
||||
await api.deleteApprovalRule(client, rule.id);
|
||||
}
|
||||
|
||||
const created: Array<{ id: string; description: string; code?: string | number }> = [];
|
||||
for (const rule of plan.created) {
|
||||
const newRule = await api.createApprovalRule(client, {
|
||||
description: rule.description,
|
||||
scope: rule.scope ?? "ALL",
|
||||
strictness: normalizeRuleStrictness(rule.strictness)
|
||||
});
|
||||
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
|
||||
}
|
||||
|
||||
const updated: string[] = [];
|
||||
for (const change of plan.updated) {
|
||||
await api.updateApprovalRule(client, change.id, {
|
||||
description: change.rule.description,
|
||||
scope: change.rule.scope ?? "ALL",
|
||||
strictness: normalizeRuleStrictness(change.rule.strictness)
|
||||
});
|
||||
updated.push(change.id);
|
||||
}
|
||||
|
||||
let publishedVersion: unknown = undefined;
|
||||
if (params.publish) {
|
||||
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
|
||||
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
|
||||
publishedVersion = await api.publishApprovalRuleVersion(client, name);
|
||||
try {
|
||||
const draft = await api.listApprovalRules(client);
|
||||
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
dryRun: false,
|
||||
localFile: local.resolvedPath,
|
||||
deletedRules: plan.deleted.length,
|
||||
createdRules: created.length,
|
||||
updatedRules: updated.length,
|
||||
unchangedRules: plan.unchanged.length,
|
||||
preservedRuleIds: [
|
||||
...updated,
|
||||
...plan.unchanged.map((rule) => rule.id)
|
||||
],
|
||||
recoded: false,
|
||||
published: publishedVersion ?? false
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_documents_list",
|
||||
description: "列出 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
scenarios: z.array(z.string()).optional().describe("场景过滤"),
|
||||
offset: z.number().int().nonnegative().optional(),
|
||||
limit: z.number().int().positive().optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { scenarios?: string[]; offset?: number; limit?: number }
|
||||
) => api.listApprovalDocuments(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_document_get",
|
||||
description: "获取 Seal 审批知识文档详情",
|
||||
parameters: z.object({
|
||||
documentId: z.string().describe("文档 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { documentId: string }) =>
|
||||
api.getApprovalDocument(client, params.documentId)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_document_create",
|
||||
description: "新建 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
title: z.string(),
|
||||
purpose: z.string(),
|
||||
content: z.string().describe("正文,通常为 Markdown"),
|
||||
contentType: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
scenarios: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
title: string;
|
||||
purpose: string;
|
||||
content: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => api.createApprovalDocument(client, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_document_update",
|
||||
description: "更新 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
documentId: z.string(),
|
||||
title: z.string().optional(),
|
||||
purpose: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
contentType: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
scenarios: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
documentId: string;
|
||||
title?: string;
|
||||
purpose?: string;
|
||||
content?: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => {
|
||||
const { documentId, ...rest } = params;
|
||||
return api.updateApprovalDocument(client, documentId, rest);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_delete_document",
|
||||
description: "删除 Seal 审批知识文档",
|
||||
parameters: z.object({
|
||||
documentId: z.string().describe("知识文档 ID")
|
||||
}),
|
||||
handler: (client: KyInstance, params: { documentId: string }) =>
|
||||
api.deleteApprovalDocument(client, params.documentId)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_search",
|
||||
description: "按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",
|
||||
parameters: z.object({
|
||||
keywords: z.array(z.string()).min(1).describe("关键词组"),
|
||||
matchMode: z.enum(["any", "all"]).optional().describe("any 命中任一关键词,all 要求同一行命中全部关键词"),
|
||||
areas: z.array(z.enum(["rules", "documents", "preferences"])).optional().describe("检索范围"),
|
||||
caseSensitive: z.boolean().optional().describe("是否大小写敏感"),
|
||||
contextLines: z.number().int().nonnegative().optional().describe("返回命中行前后几行,默认 3"),
|
||||
documentLimit: z.number().int().positive().optional().describe("缓存刷新时最多拉取文档数,默认 100"),
|
||||
maxResults: z.number().int().positive().optional().describe("最多返回命中数,默认 50"),
|
||||
refresh: z.boolean().optional().describe("是否跳过 5 分钟内存缓存并强制刷新"),
|
||||
ruleVersionScope: z.enum(["current", "all", "version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"),
|
||||
ruleVersionId: z.string().optional().describe("ruleVersionScope=version 时指定版本 ID"),
|
||||
ruleVersionNumber: z.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"),
|
||||
latestRuleVersion: z.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"),
|
||||
snippetOnly: z.boolean().optional().describe("只返回命中行,不返回前后文"),
|
||||
maxChars: z.number().int().positive().optional().describe("每个文本片段最多返回字符数"),
|
||||
fields: z.array(z.string()).optional().describe("只搜索指定字段,如 history.description、description、scope")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
keywords: string[];
|
||||
matchMode?: "any" | "all";
|
||||
areas?: Array<"rules" | "documents" | "preferences">;
|
||||
caseSensitive?: boolean;
|
||||
contextLines?: number;
|
||||
documentLimit?: number;
|
||||
maxResults?: number;
|
||||
refresh?: boolean;
|
||||
ruleVersionScope?: "current" | "all" | "version";
|
||||
ruleVersionId?: string;
|
||||
ruleVersionNumber?: number;
|
||||
latestRuleVersion?: boolean;
|
||||
snippetOnly?: boolean;
|
||||
maxChars?: number;
|
||||
fields?: string[];
|
||||
},
|
||||
context: ToolContext
|
||||
) => searchApprovalContent(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_context_get",
|
||||
description: "聚合获取 Seal 现有审批规则、审批文档和审批风格偏好",
|
||||
parameters: z.object({
|
||||
documentLimit: z.number().int().positive().optional().describe("最多返回的审批文档数量"),
|
||||
ruleVersionId: z.string().optional().describe("指定已发布规则版本 ID;指定后 rules 返回该版本快照"),
|
||||
ruleVersionNumber: z.number().int().positive().optional().describe("指定已发布规则版本号;指定后 rules 返回该版本快照"),
|
||||
latestRuleVersion: z.boolean().optional().describe("为 true 时 rules 返回最新已发布版本快照")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
documentLimit?: number;
|
||||
ruleVersionId?: string;
|
||||
ruleVersionNumber?: number;
|
||||
latestRuleVersion?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const currentContext = await api.getApprovalContext(client, {
|
||||
documentLimit: params.documentLimit,
|
||||
stylePreferencesEndpoint: context.corp.seal.endpoints.approvalStylePreferences
|
||||
});
|
||||
|
||||
if (!params.ruleVersionId && !params.ruleVersionNumber && !params.latestRuleVersion) {
|
||||
return currentContext;
|
||||
}
|
||||
|
||||
const version = await resolveRuleVersion(client, params);
|
||||
return {
|
||||
...currentContext,
|
||||
rules: {
|
||||
version: summarizeRuleVersion(version),
|
||||
rules: version.rules
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_style_preferences_get",
|
||||
description: "获取 Seal 审批风格偏好配置",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance, _params: unknown, context: ToolContext) =>
|
||||
api.getApprovalStylePreferences(
|
||||
client,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_style_preferences_update",
|
||||
description: "更新 Seal 审批风格偏好配置",
|
||||
parameters: z.object({
|
||||
tone: z.string().optional(),
|
||||
language: z.string().optional(),
|
||||
detailLevel: z.string().optional(),
|
||||
outputFormat: z.string().optional(),
|
||||
examples: z.array(z.string()).optional(),
|
||||
prohibitedPhrases: z.array(z.string()).optional(),
|
||||
customInstructions: z.string().optional()
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: Record<string, unknown>,
|
||||
context: ToolContext
|
||||
) =>
|
||||
api.updateApprovalStylePreferences(
|
||||
client,
|
||||
params,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
)
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,430 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const simulationTools = [
|
||||
{
|
||||
name: "seal_simulation_feishu_approval_definitions_list",
|
||||
description: "列出飞书模拟测试可用的审批定义,便于选择 approvalCode",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const approvalDefinitions = await api.listFeishuSimulationApprovalDefinitions(client);
|
||||
return { count: approvalDefinitions.length, approvalDefinitions };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_records_get",
|
||||
description: "获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("simulation batch ID"),
|
||||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { batchId: string; query?: string }
|
||||
) => {
|
||||
const records = filterRuns(
|
||||
await api.listSimulationBatchRecords(client, params.batchId),
|
||||
params.query
|
||||
);
|
||||
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
count: records.length,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
bridge: summarizeRunBridge(records)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_create",
|
||||
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",
|
||||
parameters: z.object({
|
||||
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
|
||||
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
|
||||
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
|
||||
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
|
||||
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
|
||||
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
|
||||
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
|
||||
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
|
||||
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
|
||||
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),
|
||||
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
|
||||
noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),
|
||||
rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
mode?: "hosecloud" | "material_pack";
|
||||
flowIds?: string[];
|
||||
rejectNodeName?: string | null;
|
||||
thinkingDepthOverride?: "default" | "medium" | "high";
|
||||
skipInvoiceGeneration?: boolean;
|
||||
skipExpenseExtraction?: boolean;
|
||||
disableAttachmentCache?: boolean;
|
||||
signKey?: string;
|
||||
packageIds?: string[];
|
||||
templateId?: string;
|
||||
schemaConfig?: Record<string, unknown>;
|
||||
noWait?: boolean;
|
||||
rawParams?: Record<string, unknown>;
|
||||
}
|
||||
) => {
|
||||
const mode = params.mode ?? "hosecloud";
|
||||
let signKey = params.signKey;
|
||||
if (mode === "hosecloud" && !signKey) {
|
||||
const integrations = await api.listSimulationHosecloudIntegrations(client);
|
||||
signKey = integrations.find((item) => item.signKey)?.signKey;
|
||||
if (!signKey) {
|
||||
throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供");
|
||||
}
|
||||
}
|
||||
|
||||
const payload = buildSimulationBatchParams({
|
||||
mode,
|
||||
flowIds: params.flowIds,
|
||||
rejectNodeName: params.rejectNodeName,
|
||||
thinkingDepthOverride: params.thinkingDepthOverride,
|
||||
skipInvoiceGeneration: params.skipInvoiceGeneration,
|
||||
skipExpenseExtraction: params.skipExpenseExtraction,
|
||||
disableAttachmentCache: params.disableAttachmentCache,
|
||||
signKey,
|
||||
packageIds: params.packageIds,
|
||||
templateId: params.templateId,
|
||||
schemaConfig: params.schemaConfig,
|
||||
rawParams: params.rawParams
|
||||
});
|
||||
|
||||
const result = mode === "material_pack"
|
||||
? await api.createMaterialPackBatch(client, payload)
|
||||
: await api.createSimulationBatch(client, payload);
|
||||
|
||||
return {
|
||||
...result,
|
||||
created: true,
|
||||
noWait: params.noWait ?? true,
|
||||
asyncTicket: result.batchId,
|
||||
next: {
|
||||
status: `seal-use simulation status ${result.batchId}`,
|
||||
wait: `seal-use simulation wait ${result.batchId}`,
|
||||
getBatch: `seal-use simulation get ${result.batchId}`,
|
||||
getRecords: `seal-use simulation batch-records ${result.batchId}`,
|
||||
listBatches: "seal-use simulation list"
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batches_list",
|
||||
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
|
||||
parameters: z.object({
|
||||
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { limit?: number }) => {
|
||||
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
|
||||
return {
|
||||
count: batches.length,
|
||||
batches: batches.map(summarizeSimulationBatch),
|
||||
next: {
|
||||
getBatch: "seal-use simulation get <batchId>",
|
||||
getRecords: "seal-use simulation batch-records <batchId>"
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_get",
|
||||
description: "获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("simulation batch ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { batchId: string }) => {
|
||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
||||
return {
|
||||
batch,
|
||||
next: {
|
||||
getRecords: "seal-use simulation batch-records <batchId>"
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_status",
|
||||
description: "单次读取 Seal 模拟批次状态,不阻塞等待;适合根据异步票据轮询",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("simulation batch ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { batchId: string }) => {
|
||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
||||
const status = String(batch.status ?? "UNKNOWN").toUpperCase();
|
||||
const terminal = ["COMPLETED", "FAILED", "CANCELLED", "CANCELED"].includes(status);
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
status,
|
||||
terminal,
|
||||
totalCount: batch.totalCount,
|
||||
processedCount: batch.processedCount,
|
||||
successCount: batch.successCount,
|
||||
failedCount: batch.failedCount,
|
||||
createdAt: batch.createdAt,
|
||||
updatedAt: batch.updatedAt,
|
||||
next: terminal
|
||||
? { getRecords: `seal-use simulation batch-records ${params.batchId}` }
|
||||
: { status: `seal-use simulation status ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` }
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_templates_get",
|
||||
description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const templates = await api.listSimulationTemplates(client);
|
||||
return {
|
||||
count: templates.length,
|
||||
templates: templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
approvalSystem: template.approvalSystem,
|
||||
hosecloudConfig: template.hosecloudConfig,
|
||||
updatedAt: template.updatedAt
|
||||
})),
|
||||
next: {
|
||||
createBatch: "seal-use simulation create --mode hosecloud --flow-ids ..."
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_integrations_get",
|
||||
description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
const [status, hosecloudIntegrations] = await Promise.all([
|
||||
api.getSimulationIntegrationStatus(client),
|
||||
api.listSimulationHosecloudIntegrations(client)
|
||||
]);
|
||||
return { status, hosecloudIntegrations };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_material_package_upload",
|
||||
description: "上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)",
|
||||
parameters: z.object({
|
||||
filePath: z.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { filePath?: string }) => {
|
||||
if (!params.filePath) {
|
||||
throw new Error("filePath is required");
|
||||
}
|
||||
const fileBuffer = readFileSync(params.filePath);
|
||||
const fileName = params.filePath.split(/[\\/]/).pop() ?? "material-pack.zip";
|
||||
const materialPackage = await api.uploadMaterialPackage(client, {
|
||||
fileName,
|
||||
fileBuffer
|
||||
});
|
||||
return {
|
||||
materialPackage,
|
||||
next: {
|
||||
createBatch: `seal-use simulation create --mode material_pack --package-ids ${materialPackage.id} --schema-config schema.json`
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_wait",
|
||||
description: "等待 Seal 模拟测试批次完成(轮询状态直到 completed/failed/canceled 或超时)",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("模拟批次 ID"),
|
||||
timeout: z.string().default("10m").describe("最长等待时间, 默认 10m"),
|
||||
pollInterval: z.string().default("2s").describe("轮询间隔, 默认 2s")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { batchId: string; timeout?: string; pollInterval?: string }) => {
|
||||
const timeoutMs = parseDurationMs(params.timeout ?? "10m");
|
||||
const pollIntervalMs = parseDurationMs(params.pollInterval ?? "2s");
|
||||
const startedAt = Date.now();
|
||||
while (true) {
|
||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
||||
const status = (batch.status ?? "").toLowerCase();
|
||||
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
|
||||
return {
|
||||
batch,
|
||||
completed: true,
|
||||
status,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
next: {
|
||||
getRecords: `seal-use simulation batch-records ${params.batchId}`
|
||||
}
|
||||
};
|
||||
}
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_batch_clean",
|
||||
description: "删除模拟测试批次产生的测试数据",
|
||||
parameters: z.object({
|
||||
batchId: z.string().describe("模拟批次 ID")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { batchId: string }) => {
|
||||
const result = await api.cleanSimulationBatch(client, params.batchId);
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
cleaned: true,
|
||||
result
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_simulation_specifications_list",
|
||||
description: "列出指定合思集成可用的单据模板列表",
|
||||
parameters: z.object({
|
||||
signKey: z.string().optional().describe("合思集成 sign-key")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { signKey?: string }) => {
|
||||
const specifications = await api.listSimulationSpecifications(client, params.signKey);
|
||||
return {
|
||||
count: specifications.length,
|
||||
specifications
|
||||
};
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,459 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "../api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { searchApprovalContent } from "../search.js";
|
||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "../rules-local.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
} from "../material-pack/index.js";
|
||||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
getHoseOpenFlow
|
||||
} from "../../hose/index.js";
|
||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
type ApprovalRun,
|
||||
type RuleSetVersion,
|
||||
type SimulationBatch,
|
||||
type WebhookIntegration,
|
||||
type WebhookMode,
|
||||
type ThinkingPolicy,
|
||||
type DecisionPreferences,
|
||||
type HosecloudConfigInput
|
||||
} from "../types.js";
|
||||
import type {
|
||||
ToolContext,
|
||||
SealToolDefinition,
|
||||
ApprovalRunSummary,
|
||||
ApprovalRunsSummaryOptions,
|
||||
RuleField,
|
||||
RulePushPlan,
|
||||
SimulationBatchCreateInput,
|
||||
HumanResultMatch
|
||||
} from "./helpers.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
|
||||
const {
|
||||
presentWebhookIntegration,
|
||||
getConfiguredSealBaseUrl,
|
||||
projectApprovalRules,
|
||||
pickRuleFields,
|
||||
buildRulePushPlan,
|
||||
rulesHaveSameContent,
|
||||
ruleChangedFields,
|
||||
normalizeRuleStrictness,
|
||||
parseDurationMs,
|
||||
redactIntegrationSecrets,
|
||||
mutationPreview,
|
||||
redactPreviewValue,
|
||||
buildSimulationBatchParams,
|
||||
summarizeSimulationBatch,
|
||||
summarizeApprovalRun,
|
||||
summarizeApprovalRuns,
|
||||
parseFieldPaths,
|
||||
pickRunFields,
|
||||
approvalRunMetadata,
|
||||
summarizeApprovalRunDetail,
|
||||
summarizeApprovalRunResult,
|
||||
summarizeApprovalRunDocument,
|
||||
extractCitedRules,
|
||||
firstPath,
|
||||
countPathCandidates,
|
||||
getPath,
|
||||
setPath,
|
||||
compactObject,
|
||||
asRecord,
|
||||
numberFromUnknown,
|
||||
flattenDocumentFields,
|
||||
collectDocumentFields,
|
||||
firstByLabel,
|
||||
collectInvoiceSummary,
|
||||
collectInvoiceObjects,
|
||||
findKeywordLines,
|
||||
summarizeRunBridge,
|
||||
summarizeRuleVersion,
|
||||
resolveRuleVersionForLookup,
|
||||
findRuleInVersion,
|
||||
normalizeRuleCode,
|
||||
runtimeRuleIndex,
|
||||
runtimeRuleIdToCode,
|
||||
formatRuleCode,
|
||||
pickApprovalRunCandidate,
|
||||
resolveApprovalRunForUrl,
|
||||
resolveSealBaseUrl,
|
||||
normalizeUrl,
|
||||
stringFromUnknown,
|
||||
pickApprovalRuns,
|
||||
timestampOf,
|
||||
resolveRuleVersion,
|
||||
resolveRuleVersionSelector,
|
||||
filterRuns,
|
||||
scalarIncludes,
|
||||
objectContainsScalar,
|
||||
filterRunsByHumanResult,
|
||||
withApprovalRunFilters,
|
||||
resolveManualApprovalStatus,
|
||||
prepareApprovalRuns,
|
||||
approvalRunAliases,
|
||||
extractHumanResult,
|
||||
findHumanResultValue,
|
||||
isHumanResultKey,
|
||||
stringifyHumanResultValue,
|
||||
matchesRunLookup,
|
||||
countBy,
|
||||
localDateKey,
|
||||
formatLocalDateTime,
|
||||
toDate,
|
||||
localParts
|
||||
} = helpers;
|
||||
|
||||
export const webhookTools = [
|
||||
{
|
||||
name: "seal_webhook_list",
|
||||
description: "列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",
|
||||
parameters: z.object({
|
||||
query: z.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),
|
||||
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { query?: string; includeSecret?: boolean },
|
||||
context: ToolContext
|
||||
) => {
|
||||
const integrations = api.filterWebhookIntegrations(
|
||||
await api.listWebhookIntegrations(
|
||||
client,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
),
|
||||
params.query
|
||||
);
|
||||
return {
|
||||
count: integrations.length,
|
||||
integrations: integrations.map((integration) => presentWebhookIntegration(integration, params.includeSecret === true))
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_get",
|
||||
description: "按 Webhook 集成 ID 或名称精确查找一条集成",
|
||||
parameters: z.object({
|
||||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||||
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { selector: string; includeSecret?: boolean },
|
||||
context: ToolContext
|
||||
) => {
|
||||
const integration = api.findWebhookIntegration(
|
||||
await api.listWebhookIntegrations(
|
||||
client,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
),
|
||||
params.selector
|
||||
);
|
||||
return presentWebhookIntegration(integration, params.includeSecret === true);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_add",
|
||||
description: "新增 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||||
parameters: z.object({
|
||||
name: z.string().min(1).describe("集成名称"),
|
||||
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
|
||||
outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||||
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"),
|
||||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
name: string;
|
||||
mode?: WebhookMode;
|
||||
outgoingResultWebhook: string;
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||||
dryRun?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const baseUrl = getConfiguredSealBaseUrl(context.corp);
|
||||
const preview = params.dryRun
|
||||
? await api.previewAddWebhookIntegration(client, baseUrl, params, context.corp.seal.endpoints.approvalStylePreferences)
|
||||
: undefined;
|
||||
const integration = preview?.integration ?? await api.addWebhookIntegration(
|
||||
client,
|
||||
baseUrl,
|
||||
params,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
if (params.dryRun) {
|
||||
return mutationPreview(
|
||||
context,
|
||||
context.corp.seal.endpoints.approvalStylePreferences,
|
||||
preview!.before,
|
||||
preview!.after,
|
||||
1
|
||||
);
|
||||
}
|
||||
return {
|
||||
saved: true,
|
||||
integration: presentWebhookIntegration(integration, true)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_update",
|
||||
description: "更新现有 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||||
parameters: z.object({
|
||||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||||
name: z.string().min(1).optional(),
|
||||
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
|
||||
outgoingResultWebhook: z.string().url().optional(),
|
||||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||||
secret: z.string().min(1).optional(),
|
||||
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一"),
|
||||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
selector: string;
|
||||
name?: string;
|
||||
mode?: WebhookMode;
|
||||
outgoingResultWebhook?: string;
|
||||
autoApprovalRate?: number;
|
||||
secret?: string;
|
||||
rotateSecret?: boolean;
|
||||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||||
dryRun?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
if (params.secret !== undefined && params.rotateSecret) {
|
||||
throw new Error("Webhook secret and rotateSecret cannot be used together");
|
||||
}
|
||||
const preview = params.dryRun
|
||||
? await api.previewUpdateWebhookIntegration(client, params.selector, params, context.corp.seal.endpoints.approvalStylePreferences)
|
||||
: undefined;
|
||||
const integration = preview?.integration ?? await api.updateWebhookIntegration(
|
||||
client,
|
||||
params.selector,
|
||||
params,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
if (params.dryRun) {
|
||||
return mutationPreview(
|
||||
context,
|
||||
context.corp.seal.endpoints.approvalStylePreferences,
|
||||
preview!.before,
|
||||
preview!.after,
|
||||
1
|
||||
);
|
||||
}
|
||||
return {
|
||||
saved: true,
|
||||
integration: presentWebhookIntegration(
|
||||
integration,
|
||||
params.secret !== undefined || params.rotateSecret === true
|
||||
)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_delete",
|
||||
description: "删除指定 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||||
parameters: z.object({
|
||||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||||
confirm: z.boolean().optional().describe("执行删除时必须明确传 true;dryRun 可省略"),
|
||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行删除")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { selector: string; confirm?: boolean; dryRun?: boolean },
|
||||
context: ToolContext
|
||||
) => {
|
||||
if (!params.confirm && !params.dryRun) {
|
||||
throw new Error("Refusing to delete Webhook integration without confirm=true");
|
||||
}
|
||||
const preview = params.dryRun
|
||||
? await api.previewDeleteWebhookIntegration(client, params.selector, context.corp.seal.endpoints.approvalStylePreferences)
|
||||
: undefined;
|
||||
const integration = preview?.integration ?? await api.deleteWebhookIntegration(
|
||||
client,
|
||||
params.selector,
|
||||
context.corp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
if (params.dryRun) {
|
||||
return mutationPreview(
|
||||
context,
|
||||
context.corp.seal.endpoints.approvalStylePreferences,
|
||||
preview!.before,
|
||||
preview!.after,
|
||||
1
|
||||
);
|
||||
}
|
||||
return {
|
||||
deleted: true,
|
||||
integration: presentWebhookIntegration(integration, false)
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_replay",
|
||||
description: "将正式(生产)企业或指定企业的审批记录通过 Webhook 渠道重放到测试企业进行规则回归与模拟验证",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional().describe("待重放的单条审批记录 ID"),
|
||||
sn: z.string().optional().describe("待重放的单据编号 (sourceDocumentSN)"),
|
||||
sourceCorpId: z.string().optional().describe("单据来源企业 ID (若省略,基于绑定关系自动解析为正式企业)"),
|
||||
targetCorpId: z.string().optional().describe("重放目标企业 ID (若省略,基于绑定关系自动解析为测试企业)"),
|
||||
webhook: z.string().optional().describe("目标 Webhook 通道 ID 或名称"),
|
||||
limit: z.number().optional().describe("批量重放单据数量 (默认 1)"),
|
||||
status: z.string().optional().describe("单据状态过滤 (例如 completed, failed 等)"),
|
||||
snPrefix: z.string().optional().describe("重放单号前缀"),
|
||||
snSuffix: z.string().optional().describe("重放单号后缀"),
|
||||
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
|
||||
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
recordId?: string;
|
||||
sn?: string;
|
||||
sourceCorpId?: string;
|
||||
targetCorpId?: string;
|
||||
webhook?: string;
|
||||
limit?: number;
|
||||
status?: string;
|
||||
snPrefix?: string;
|
||||
snSuffix?: string;
|
||||
dryRun?: boolean;
|
||||
force?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const selectCorpFn = (id?: string) => {
|
||||
const corps = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
return resolveCorpConfig(
|
||||
corps,
|
||||
{
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corpId: id
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
};
|
||||
|
||||
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
|
||||
{
|
||||
sourceCorpId: params.sourceCorpId,
|
||||
targetCorpId: params.targetCorpId,
|
||||
activeCorp: context.corp,
|
||||
force: params.force
|
||||
},
|
||||
selectCorpFn
|
||||
);
|
||||
|
||||
const sourceClient = sourceCorp.id === context.corp.id ? client : await createSealClient(sourceCorp);
|
||||
const targetClient = targetCorp.id === context.corp.id ? client : await createSealClient(targetCorp);
|
||||
|
||||
return executeApprovalRunsReplay({
|
||||
query: {
|
||||
recordId: params.recordId,
|
||||
sn: params.sn,
|
||||
limit: params.limit,
|
||||
status: params.status
|
||||
},
|
||||
sourceClient,
|
||||
targetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
webhookSelector: params.webhook,
|
||||
snPrefix: params.snPrefix,
|
||||
snSuffix: params.snSuffix,
|
||||
dryRun: params.dryRun
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_ready",
|
||||
description: "检查当前企业的 Webhook 就绪状态看板(包括企业环境、租户身份、凭证连通性、已激活 Webhook 通道及材料包预检)",
|
||||
parameters: z.object({
|
||||
filePath: z.string().optional().describe("可选的材料包路径(ZIP 或 信息表.xlsx),用于同步做本地预检")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { filePath?: string },
|
||||
context: ToolContext
|
||||
) => {
|
||||
return checkWebhookReadiness(client, context.corp, { filePath: params.filePath });
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_material_pack",
|
||||
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网,push 模式单通道自动选择",
|
||||
parameters: z.object({
|
||||
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
|
||||
mode: z.enum(["preview", "push"]).default("preview"),
|
||||
webhook: z.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { filePath: string; mode?: "preview" | "push"; webhook?: string },
|
||||
context: ToolContext
|
||||
) => {
|
||||
const input = readMaterialPackFile(params.filePath);
|
||||
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
|
||||
const integrations = await api.listWebhookIntegrations(client);
|
||||
let integration: WebhookIntegration;
|
||||
if (params.webhook) {
|
||||
integration = api.findWebhookIntegration(integrations, params.webhook);
|
||||
} else if (integrations.length === 1) {
|
||||
integration = integrations[0]!;
|
||||
} else if (integrations.length > 1) {
|
||||
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
|
||||
} else {
|
||||
throw new Error("当前租户未配置任何 Webhook 集成通道。");
|
||||
}
|
||||
return pushMaterialPack(input.fileBuffer, input.fileName, {
|
||||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||||
secret: integration.secret,
|
||||
materialPackFilePolicy: integration.materialPackFilePolicy,
|
||||
customHeaders: resolveSealCustomHeaders(context.corp.seal)
|
||||
});
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
import type { MaterialField } from "./material-pack/types.js";
|
||||
import { webhookHeaders } from "./material-pack/signature.js";
|
||||
import { CliError } from "../../cli/errors.js";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import * as api from "./api.js";
|
||||
|
||||
Reference in new issue
Block a user