Files
seal-use/src/domains/seal/tools.ts
T

4257 lines
163 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { z } from "zod";
import { 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 { 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";
type ToolContext = {
corp: CorpConfig;
};
type SealToolDefinition = {
name: string;
description: string;
parameters: z.ZodType;
handler: (client: KyInstance, params: never, context: ToolContext) => Promise<unknown>;
};
export const sealTools = [
{
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
)
},
{
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)
},
{
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)
},
{
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_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)
},
{
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
)
},
{
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_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_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_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)
});
}
},
{
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_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
};
}
},
{
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
};
}
},
{
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
};
}
},
{
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
};
}
}
];
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);
}
function presentWebhookIntegration(
integration: WebhookIntegration,
includeSecret: boolean
) {
return includeSecret
? integration
: { ...integration, secret: "<redacted>" };
}
function getConfiguredSealBaseUrl(corp: CorpConfig): string {
if (corp.seal.url) return corp.seal.url;
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source);
return corp.source.sealUrl;
}
type ApprovalRunSummary = {
id: string;
tenantId?: string;
agentId?: string;
status?: string;
taskMode?: string;
finalExecutionMode?: string;
sourceSystem?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
documentId?: string;
simulationBatchId?: string;
langfuseTraceId?: string;
langfuseSessionFallback?: string;
ruleSetVersionNumber?: number;
ruleSetPublishedAt?: number;
ruleSetPublishedByName?: string;
humanResult?: string;
humanResultPath?: string;
aiDecision?: unknown;
aiSummary?: unknown;
createdAt?: string | number;
updatedAt?: string | number;
};
type ApprovalRunsSummaryOptions = {
date: string;
timezone: string;
fetched: number;
total?: number;
};
type RuleField = keyof ApprovalRule;
function projectApprovalRules(
data: { rules: ApprovalRule[]; hasPendingDeletes: boolean },
params: {
countOnly?: boolean;
fields?: RuleField[];
limit?: number;
offset?: number;
}
) {
const count = data.rules.length;
if (params.countOnly || params.limit === 0) {
return { count };
}
const offset = params.offset ?? 0;
const rules = data.rules.slice(offset, params.limit === undefined ? undefined : offset + params.limit);
const fields = params.fields;
return {
count,
hasPendingDeletes: data.hasPendingDeletes,
rules: fields ? rules.map((rule) => pickRuleFields(rule, fields)) : rules
};
}
function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
const output: Partial<ApprovalRule> = {};
for (const field of fields) {
if (rule[field] !== undefined) {
if (field === "code") {
const val = rule.code;
if (typeof val === "number") {
output.code = formatRuleCode(val) as never;
} else if (typeof val === "string") {
const digits = val.match(/\d+/)?.[0];
output.code = (digits ? formatRuleCode(Number(digits)) : val) as never;
} else {
output.code = val as never;
}
} else {
output[field] = rule[field] as never;
}
}
}
return output;
}
type RulePushPlan = {
created: LocalRuleItem[];
updated: Array<{ id: string; rule: LocalRuleItem; changedFields: string[] }>;
deleted: ApprovalRule[];
unchanged: Array<Pick<ApprovalRule, "id">>;
};
export function buildRulePushPlan(
remoteRules: ApprovalRule[],
localRules: LocalRuleItem[]
): RulePushPlan {
const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule]));
const usedRemoteIds = new Set<string>();
const created: LocalRuleItem[] = [];
const updated: RulePushPlan["updated"] = [];
const unchanged: RulePushPlan["unchanged"] = [];
for (const localRule of localRules) {
let remoteRule: ApprovalRule | undefined;
if (localRule.id) {
remoteRule = remoteById.get(localRule.id);
if (!remoteRule) {
throw new Error(
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
);
}
if (usedRemoteIds.has(localRule.id)) {
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
}
} else {
const matches = remoteRules.filter(
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
);
if (matches.length > 1) {
throw new Error(
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
);
}
remoteRule = matches[0];
}
if (!remoteRule) {
created.push(localRule);
continue;
}
usedRemoteIds.add(remoteRule.id);
const changedFields = ruleChangedFields(remoteRule, localRule);
if (changedFields.length) {
updated.push({ id: remoteRule.id, rule: localRule, changedFields });
} else {
unchanged.push({ id: remoteRule.id });
}
}
return {
created,
updated,
deleted: remoteRules.filter((rule) => !usedRemoteIds.has(rule.id)),
unchanged
};
}
function rulesHaveSameContent(remoteRule: ApprovalRule, localRule: LocalRuleItem): boolean {
return remoteRule.description === localRule.description.trim() &&
remoteRule.scope === (localRule.scope ?? "ALL") &&
remoteRule.strictness === normalizeRuleStrictness(localRule.strictness);
}
function ruleChangedFields(remoteRule: ApprovalRule, localRule: LocalRuleItem): string[] {
const changed: string[] = [];
if (remoteRule.description !== localRule.description.trim()) changed.push("description");
if (remoteRule.scope !== (localRule.scope ?? "ALL")) changed.push("scope");
if (remoteRule.strictness !== normalizeRuleStrictness(localRule.strictness)) changed.push("strictness");
return changed;
}
function normalizeRuleStrictness(value?: string): string {
const normalized = value?.toUpperCase() ?? "MUST_FOLLOW";
if (normalized.includes("SHOULD")) return "SHOULD_FOLLOW";
if (normalized.includes("SUGGEST")) return "SUGGESTION";
return "MUST_FOLLOW";
}
export type SimulationBatchCreateInput = {
mode?: string;
sourceSystem?: string;
flowIds?: string[];
documentSn?: string | string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
packageId?: string;
templateId?: string;
schemaConfig?: Record<string, unknown>;
approvalCode?: string;
nodeId?: string;
runMode?: string;
requestIds?: string[];
workflowTypeId?: string;
flowStatusList?: number[];
businessCodes?: string[];
documentType?: string;
formCodes?: string[];
formSubTypeBizCode?: string;
formStatus?: string;
pageNo?: number;
pageSize?: number;
startTime?: number;
endTime?: number;
status?: string[];
limit?: number;
// 预留:其他取数模式(如合思时间范围)透传参数,覆盖构建结果
rawParams?: Record<string, unknown>;
};
function parseDurationMs(duration: string): number {
const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);
if (!match || !match[1]) return 600000;
const val = parseFloat(match[1]);
const unit = (match[2] ?? "s").toLowerCase();
switch (unit) {
case "ms": return val;
case "s": return val * 1000;
case "m": return val * 60 * 1000;
case "h": return val * 3600 * 1000;
case "d": return val * 86400 * 1000;
default: return val * 1000;
}
}
function redactIntegrationSecrets(integration: Record<string, unknown>) {
return Object.fromEntries(
Object.entries(integration).map(([key, value]) => [
key,
["apiKey", "apiSecret", "secret"].includes(key) && typeof value === "string" ? "***" : value
])
);
}
function mutationPreview(
context: ToolContext,
endpoint: string,
before: unknown,
after: unknown,
impactCount: number
) {
const baseUrl = getConfiguredSealBaseUrl(context.corp).replace(/\/+$/, "");
return {
preview: true,
targetUrl: `${baseUrl}/${endpoint.replace(/^\/+/, "")}`,
changesDiff: {
before: redactPreviewValue(before),
after: redactPreviewValue(after)
},
impactCount
};
}
function redactPreviewValue(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redactPreviewValue);
if (!value || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
["apiKey", "apiSecret", "secret", "token", "password"].includes(key) && typeof item === "string"
? "***"
: redactPreviewValue(item)
])
);
}
export function buildSimulationBatchParams(input: SimulationBatchCreateInput): Record<string, unknown> {
const sourceSystem = input.sourceSystem ?? input.mode ?? "hosecloud";
const params: Record<string, unknown> = {
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
skipExpenseExtraction: input.skipExpenseExtraction ?? true,
thinkingDepthOverride: input.thinkingDepthOverride ?? "default",
disableAttachmentCache: input.disableAttachmentCache ?? false
};
const docSns = input.flowIds ?? (typeof input.documentSn === "string" ? input.documentSn.split(",").map((s) => s.trim()).filter(Boolean) : input.documentSn);
if (sourceSystem === "hosecloud") {
if (!docSns?.length && input.startTime === undefined) {
throw new Error("hosecloud 模式需要提供 flowIds(单号列表)");
}
Object.assign(params, {
dataCollectionMode: "2",
rejectNodeName: input.rejectNodeName ?? null,
sourceSystem: "hosecloud"
});
if (docSns?.length) params.flowIds = docSns;
if (input.signKey) params.signKey = input.signKey;
if (input.startTime !== undefined) params.startTime = input.startTime;
if (input.endTime !== undefined) params.endTime = input.endTime;
if (input.status) params.status = input.status;
if (input.limit) params.limit = input.limit;
} else if (sourceSystem === "material_pack" || sourceSystem === "material-pack") {
const packageIds = input.packageIds ?? (input.packageId ? [input.packageId] : undefined);
if (!packageIds?.length) {
throw new Error("material_pack 模式需要提供 packageIds(材料包 id)");
}
const templateId = input.templateId ?? (input.schemaConfig as { id?: string } | undefined)?.id;
if (!templateId) {
throw new Error("material_pack 模式需要提供 templateId(或 schemaConfig.id)");
}
Object.assign(params, {
templateId,
packageIds,
approvalCode: input.approvalCode ?? "material_pack",
nodeId: input.nodeId ?? "material_pack",
runMode: input.runMode ?? "import_and_simulate"
});
if (input.schemaConfig !== undefined) params.schemaConfig = input.schemaConfig;
} else if (sourceSystem === "weaver") {
Object.assign(params, {
sourceSystem: "weaver",
workflowTypeId: input.workflowTypeId,
requestIds: input.requestIds,
flowStatusList: input.flowStatusList,
nodeId: input.nodeId,
startTime: input.startTime,
endTime: input.endTime,
status: input.status,
limit: input.limit ?? 100,
rejectNodeName: input.rejectNodeName ?? null
});
} else if (sourceSystem === "helios") {
Object.assign(params, {
sourceSystem: "helios",
documentType: input.documentType,
businessCodes: input.businessCodes,
rejectNodeName: input.rejectNodeName ?? null
});
} else if (sourceSystem === "maycur" || sourceSystem === "maycur-standard") {
Object.assign(params, {
sourceSystem,
formCodes: input.formCodes ?? docSns,
createdAtStart: input.startTime,
createdAtEnd: input.endTime,
formSubTypeBizCode: input.formSubTypeBizCode,
formStatus: input.formStatus,
pageNo: input.pageNo ?? 1,
pageSize: input.pageSize ?? 100,
signKey: input.signKey
});
} else if (sourceSystem === "feishu") {
Object.assign(params, {
sourceSystem: "feishu",
approvalCode: input.approvalCode,
nodeId: input.nodeId,
startTime: input.startTime,
endTime: input.endTime,
status: input.status,
limit: input.limit ?? 100,
signKey: input.signKey
});
} else {
Object.assign(params, { sourceSystem });
}
if (input.rawParams) Object.assign(params, input.rawParams);
return params;
}
function summarizeSimulationBatch(batch: SimulationBatch) {
return {
id: batch.id,
status: batch.status,
approvalCode: batch.approvalCode,
sourceSystem: batch.sourceSystem,
totalCount: batch.totalCount,
processedCount: batch.processedCount,
successCount: batch.successCount,
failedCount: batch.failedCount,
createdCount: batch.createdCount,
createFailedCount: batch.createFailedCount,
requestSummary: batch.requestSummary,
resultSummary: batch.resultSummary,
createdAt: batch.createdAt
};
}
function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
const sourceDocumentSN = record.sourceDocumentSN;
const humanResult = extractHumanResult(record);
const ai = summarizeApprovalRunResult(record);
return {
id: record.id,
tenantId: record.tenantId,
agentId: record.agentId,
status: record.status,
taskMode: record.taskMode,
finalExecutionMode: record.finalExecutionMode,
sourceSystem: record.sourceSystem,
sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
documentId: record.documentId,
simulationBatchId: record.sourceExtendData?.simulation_batch_id,
langfuseTraceId: record.sourceExtendData?._langfuseTraceId,
langfuseSessionFallback: sourceDocumentSN ? `hosecloud-${sourceDocumentSN}` : undefined,
ruleSetVersionNumber: record.ruleSetVersionNumber,
ruleSetPublishedAt: record.ruleSetPublishedAt,
ruleSetPublishedByName: record.ruleSetPublishedByName,
humanResult: humanResult?.value,
humanResultPath: humanResult?.path,
aiDecision: ai.decision,
aiSummary: ai.summary,
createdAt: record.createdAt,
updatedAt: record.updatedAt
};
}
function summarizeApprovalRuns(records: ApprovalRun[], options: ApprovalRunsSummaryOptions) {
return {
date: options.date,
timezone: options.timezone,
fetched: options.fetched,
matched: records.length,
total: options.total,
statusCounts: countBy(records, (record) => record.status ?? "unknown"),
taskModeCounts: countBy(records, (record) => record.taskMode ?? "unknown"),
records: records.map((record) => {
const summary = summarizeApprovalRun(record);
return {
createdAt: formatLocalDateTime(summary.createdAt, options.timezone),
sourceDocumentSN: summary.sourceDocumentSN,
sourceDocumentId: summary.sourceDocumentId,
status: summary.status,
taskMode: summary.taskMode,
finalExecutionMode: summary.finalExecutionMode,
simulationBatchId: summary.simulationBatchId,
langfuseTraceId: summary.langfuseTraceId,
langfuseSessionFallback: summary.langfuseSessionFallback,
ruleSetVersionNumber: summary.ruleSetVersionNumber,
ruleSetPublishedAt: formatLocalDateTime(summary.ruleSetPublishedAt, options.timezone),
ruleSetPublishedByName: summary.ruleSetPublishedByName,
humanResult: summary.humanResult,
humanResultPath: summary.humanResultPath,
recordId: summary.id
};
})
};
}
function parseFieldPaths(fields: string | string[] | undefined): string[] {
if (!fields) return [];
const raw = Array.isArray(fields) ? fields : fields.split(",");
return raw.map((field) => field.trim()).filter(Boolean);
}
function pickRunFields(record: Record<string, unknown>, fields: readonly string[]) {
const output: Record<string, unknown> = {};
for (const field of fields) {
if (field === "metadata") {
output.metadata = approvalRunMetadata(record as ApprovalRun);
continue;
}
const value = getPath(record, field);
if (value !== undefined) setPath(output, field, value);
}
return output;
}
function approvalRunMetadata(record: ApprovalRun) {
const summary = summarizeApprovalRun(record);
return {
recordId: summary.id,
tenantId: summary.tenantId,
agentId: summary.agentId,
sourceSystem: summary.sourceSystem,
sourceDocumentSN: summary.sourceDocumentSN,
sourceDocumentId: summary.sourceDocumentId,
documentId: summary.documentId,
status: summary.status,
taskMode: summary.taskMode,
finalExecutionMode: summary.finalExecutionMode,
simulationBatchId: summary.simulationBatchId,
langfuseTraceId: summary.langfuseTraceId,
langfuseSessionFallback: summary.langfuseSessionFallback,
ruleSetVersionNumber: summary.ruleSetVersionNumber,
ruleSetPublishedAt: summary.ruleSetPublishedAt,
ruleSetPublishedByName: summary.ruleSetPublishedByName,
createdAt: summary.createdAt,
updatedAt: summary.updatedAt
};
}
function summarizeApprovalRunDetail(record: ApprovalRun) {
return {
metadata: approvalRunMetadata(record),
document: summarizeApprovalRunDocument(record).document,
aiResult: summarizeApprovalRunResult(record),
manualResult: extractHumanResult(record)?.value,
manualResultPath: extractHumanResult(record)?.path,
ruleSetVersionNumber: record.ruleSetVersionNumber,
ruleSetPublishedAt: record.ruleSetPublishedAt,
ruleSetPublishedByName: record.ruleSetPublishedByName
};
}
function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
traceId: record.sourceExtendData?._langfuseTraceId,
langfuseTraceId: record.sourceExtendData?._langfuseTraceId,
decision: firstPath(result, [
"decision",
"manualApproval.decision",
"manualApproval.result",
"review.decision",
"finalDecision"
]),
summary: firstPath(result, [
"summary",
"result.summary",
"review.summary",
"conclusion"
]),
riskPointCount: countPathCandidates(result, [
"riskPoints",
"risks",
"risk_points",
"review.riskPoints"
]),
matchedRuleCount: countPathCandidates(result, [
"matchedRules",
"hitRules",
"ruleResults",
"rules",
"review.matchedRules"
])
};
}
function summarizeApprovalRunDocument(record: ApprovalRun) {
const document = asRecord(record.document);
const fields = flattenDocumentFields(record.document);
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
return {
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
document: compactObject({
id: document?.id,
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
title: document?.title ?? document?.name,
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
amount: firstByLabel(fields, ["金额", "报销金额", "付款金额", "合计", "价税合计"]) ?? firstPath(document, ["amount", "totalAmount", "expenseAmount"]),
expenseType: firstByLabel(fields, ["费用类型", "费用类别", "报销类型"]),
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
keyFields: fields.slice(0, 30)
}),
invoices: collectInvoiceSummary(record),
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
aiResult: summarizeApprovalRunResult(record),
manualResult: extractHumanResult(record)?.value,
hints: compactObject({
amountMentions: findKeywordLines(fieldText, ["金额", "合计", "税率"], 8),
partyMentions: findKeywordLines(fieldText, ["买方", "卖方", "甲方", "乙方", "收款"], 8)
})
};
}
function extractCitedRules(record: ApprovalRun) {
const candidates: Array<[string, unknown]> = [
["result.citedRules", getPath(record, "result.citedRules")],
["result.matchedRules", getPath(record, "result.matchedRules")],
["result.ruleResults", getPath(record, "result.ruleResults")],
["result.rules", getPath(record, "result.rules")],
["pipelineData.citedRules", getPath(record, "pipelineData.citedRules")],
["pipelineData.matchedRules", getPath(record, "pipelineData.matchedRules")]
];
const rules: Array<Record<string, unknown>> = [];
const seen = new Set<string>();
for (const [path, value] of candidates) {
const items = Array.isArray(value)
? value
: value && typeof value === "object"
? Object.values(value as Record<string, unknown>)
: [];
items.forEach((item, index) => {
const object = asRecord(item);
if (!object) return;
const runtimeRuleId = stringFromUnknown(object.runtimeRuleId) ?? stringFromUnknown(object.runtimeId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.ruleId);
const ruleCode = stringFromUnknown(object.ruleCode) ?? stringFromUnknown(object.code) ?? (runtimeRuleId ? runtimeRuleIdToCode(runtimeRuleId) : undefined);
const output = compactObject({
runtimeRuleId,
ruleCode,
versionNumber: numberFromUnknown(object.versionNumber) ?? record.ruleSetVersionNumber,
scope: stringFromUnknown(object.scope),
strictness: stringFromUnknown(object.strictness),
appliedAnalysis: object.appliedAnalysis ?? object.analysis ?? object.reasoning,
checkResult: object.checkResult ?? object.result ?? object.decision,
findings: object.findings ?? object.riskPoints ?? object.evidence,
sourcePath: `${path}.${index}`
});
const key = JSON.stringify(output);
if (!seen.has(key)) {
seen.add(key);
rules.push(output);
}
});
}
return {
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
ruleSetVersionNumber: record.ruleSetVersionNumber,
count: rules.length,
rules
};
}
function firstPath(object: Record<string, unknown> | undefined, paths: readonly string[]) {
if (!object) return undefined;
for (const path of paths) {
const value = getPath(object, path);
if (value !== undefined) return value;
}
return undefined;
}
function countPathCandidates(object: Record<string, unknown> | undefined, paths: readonly string[]) {
if (!object) return 0;
for (const path of paths) {
const value = getPath(object, path);
if (Array.isArray(value)) return value.length;
if (value && typeof value === "object") return Object.keys(value).length;
if (typeof value === "number") return value;
}
return 0;
}
function getPath(value: unknown, path: string): unknown {
return path.split(".").reduce<unknown>((current, segment) => {
if (current === undefined || current === null) return undefined;
if (Array.isArray(current)) {
const index = Number(segment);
return Number.isInteger(index) ? current[index] : undefined;
}
if (typeof current === "object") {
return (current as Record<string, unknown>)[segment];
}
return undefined;
}, value);
}
function setPath(target: Record<string, unknown>, path: string, value: unknown) {
const segments = path.split(".");
let current = target;
for (const segment of segments.slice(0, -1)) {
const existing = current[segment];
if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
current[segment] = {};
}
current = current[segment] as Record<string, unknown>;
}
current[segments[segments.length - 1] ?? path] = value;
}
function compactObject(object: Record<string, unknown>) {
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: undefined;
}
function numberFromUnknown(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function flattenDocumentFields(value: unknown) {
const fields: Array<Record<string, unknown>> = [];
collectDocumentFields(value, "document", fields);
return fields;
}
function collectDocumentFields(value: unknown, path: string, output: Array<Record<string, unknown>>) {
if (Array.isArray(value)) {
value.forEach((item, index) => collectDocumentFields(item, `${path}.${index}`, output));
return;
}
const object = asRecord(value);
if (!object) return;
const label = stringFromUnknown(object.label) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.title) ?? stringFromUnknown(object.fieldName);
const rawValue = object.value ?? object.displayValue ?? object.text ?? object.content;
if (label && rawValue !== undefined && typeof rawValue !== "object") {
output.push(compactObject({
path,
label,
value: rawValue,
type: stringFromUnknown(object.type) ?? stringFromUnknown(object.fieldType)
}));
}
for (const [key, child] of Object.entries(object)) {
if (key === "attachments") continue;
collectDocumentFields(child, `${path}.${key}`, output);
}
}
function firstByLabel(fields: Array<Record<string, unknown>>, labels: string[]) {
const hit = fields.find((field) => {
const label = stringFromUnknown(field.label) ?? "";
return labels.some((item) => label.includes(item));
});
return hit?.value;
}
function collectInvoiceSummary(record: ApprovalRun) {
const invoices: Array<Record<string, unknown>> = [];
collectInvoiceObjects(record.result, "result", invoices);
collectInvoiceObjects(record.document, "document", invoices);
return invoices.slice(0, 20);
}
function collectInvoiceObjects(value: unknown, path: string, output: Array<Record<string, unknown>>) {
if (Array.isArray(value)) {
value.forEach((item, index) => collectInvoiceObjects(item, `${path}.${index}`, output));
return;
}
const object = asRecord(value);
if (!object) return;
if (/invoice|发票/i.test(path)) {
output.push(compactObject({
path,
fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name),
buyer: object.buyer ?? object.buyerName ?? object.purchaserName,
seller: object.seller ?? object.sellerName,
amount: object.amount ?? object.totalAmount ?? object.total,
taxRate: object.taxRate,
category: object.category ?? object.type
}));
}
for (const [key, child] of Object.entries(object)) {
collectInvoiceObjects(child, `${path}.${key}`, output);
}
}
function findKeywordLines(text: string, keywords: string[], limit: number) {
return text
.split(/\r?\n/)
.filter((line) => keywords.some((keyword) => line.includes(keyword)))
.slice(0, limit);
}
function summarizeRunBridge(records: ApprovalRun[]) {
return records.map((record) => {
const summary = summarizeApprovalRun(record);
return {
recordId: summary.id,
tenantId: summary.tenantId,
agentId: summary.agentId,
sourceDocumentSN: summary.sourceDocumentSN,
sourceDocumentId: summary.sourceDocumentId,
simulationBatchId: summary.simulationBatchId,
langfuseTraceId: summary.langfuseTraceId,
langfuseSessionFallback: summary.langfuseSessionFallback,
ruleSetVersionNumber: summary.ruleSetVersionNumber,
ruleSetPublishedAt: summary.ruleSetPublishedAt,
ruleSetPublishedByName: summary.ruleSetPublishedByName,
resolution:
summary.langfuseTraceId
? "trace"
: summary.langfuseSessionFallback
? "session-fallback"
: "unresolved"
};
});
}
function summarizeRuleVersion(version: RuleSetVersion) {
return {
id: version.id,
tenantId: version.tenantId,
versionNumber: version.versionNumber,
versionName: version.versionName,
publishedBy: version.publishedBy,
publishedByName: version.publishedByName,
rulesCount: version.rules.length,
publishedAt: version.publishedAt,
createdAt: version.createdAt
};
}
async function resolveRuleVersionForLookup(
client: KyInstance,
params: { versionId?: string; versionNumber?: number; latest?: boolean; recordId?: string }
) {
if (params.recordId && !params.versionId && !params.versionNumber && !params.latest) {
const record = await api.getApprovalRun(client, params.recordId);
if (!record.ruleSetVersionNumber) {
throw new Error(`Approval run ${params.recordId} has no ruleSetVersionNumber`);
}
return resolveRuleVersion(client, { versionNumber: record.ruleSetVersionNumber });
}
return resolveRuleVersion(client, params);
}
function findRuleInVersion(
version: RuleSetVersion,
selector: { code?: string; runtimeId?: string }
) {
const normalizedCode = normalizeRuleCode(selector.code);
const runtimeIndex = runtimeRuleIndex(selector.runtimeId);
const index = normalizedCode ? Number(normalizedCode.slice(1)) : runtimeIndex;
if (!index || index < 1) {
throw new Error("Pass --code '#0038' or --runtime-id rule-205");
}
const rule = version.rules.find((item, itemIndex) => {
const object = item as Record<string, unknown>;
const itemCode = normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode));
return itemCode === normalizedCode || itemIndex + 1 === index;
});
if (!rule) return undefined;
const object = rule as Record<string, unknown>;
const position = version.rules.indexOf(rule) + 1;
return compactObject({
runtimeRuleId: stringFromUnknown(object.runtimeRuleId) ?? `rule-${position}`,
ruleCode: normalizeRuleCode(stringFromUnknown(object.code) ?? stringFromUnknown(object.ruleCode)) ?? formatRuleCode(position),
versionId: version.id,
versionNumber: version.versionNumber,
versionName: version.versionName,
publishedAt: version.publishedAt,
publishedByName: version.publishedByName,
description: rule.description,
scope: rule.scope,
strictness: rule.strictness,
status: stringFromUnknown(object.status)
});
}
function normalizeRuleCode(value?: string) {
if (!value) return undefined;
const digits = value.match(/\d+/)?.[0];
return digits ? formatRuleCode(Number(digits)) : value;
}
function runtimeRuleIndex(value?: string) {
if (!value) return undefined;
const match = value.match(/(\d+)$/);
return match ? Number(match[1]) : undefined;
}
function runtimeRuleIdToCode(value: string) {
const index = runtimeRuleIndex(value);
return index ? formatRuleCode(index) : undefined;
}
function formatRuleCode(value: number) {
return `#${String(value).padStart(4, "0")}`;
}
function pickApprovalRunCandidate(record: ApprovalRun, fields: string[]) {
const summary = summarizeApprovalRun(record);
const candidate = {
recordId: summary.id,
sourceDocumentSN: summary.sourceDocumentSN,
sourceDocumentId: summary.sourceDocumentId,
simulationBatchId: summary.simulationBatchId,
status: summary.status,
taskMode: summary.taskMode,
ruleSetVersionNumber: summary.ruleSetVersionNumber,
langfuseTraceId: summary.langfuseTraceId,
manualResult: summary.humanResult,
aiDecision: summary.aiDecision,
aiSummary: summary.aiSummary,
createdAt: summary.createdAt
};
if (fields.length === 0) return candidate;
return pickRunFields(candidate, fields);
}
async function resolveApprovalRunForUrl(
client: KyInstance,
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string }
): Promise<ApprovalRun> {
if (params.recordId) {
return api.getApprovalRun(client, params.recordId);
}
const data = await api.listApprovalRuns(client, {
limit: 1,
search: params.sourceDocumentSN ?? params.sourceDocumentId,
sourceDocumentSN: params.sourceDocumentSN,
sourceDocumentId: params.sourceDocumentId
});
const record = data.records[0];
if (!record) {
const lookup = params.sourceDocumentSN
? `sourceDocumentSN ${params.sourceDocumentSN}`
: `sourceDocumentId ${params.sourceDocumentId}`;
throw new Error(`Approval run not found for ${lookup}`);
}
return api.getApprovalRun(client, record.id);
}
function resolveSealBaseUrl(corp: CorpConfig): string {
if (corp.seal?.url) return corp.seal.url.replace(/\/+$/, "");
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source).replace(/\/+$/, "");
if ("sealUrl" in corp.source && typeof corp.source.sealUrl === "string" && corp.source.sealUrl) {
return corp.source.sealUrl.replace(/\/+$/, "");
}
return `https://${corp.id.toLowerCase()}.sealai.cc`;
}
function normalizeUrl(value: string): string {
return value.replace(/\/+$/, "");
}
function stringFromUnknown(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value : undefined;
}
async function pickApprovalRuns(
client: KyInstance,
params: { query: string; sn?: string; batchId?: string; latest?: boolean; limit: number; maxScan: number }
) {
const pageSize = Math.min(100, Math.max(params.limit, 20));
const records: ApprovalRun[] = [];
let total: number | undefined;
let scanned = 0;
while (scanned < params.maxScan && records.length < params.limit) {
const data = await api.listApprovalRuns(client, {
offset: scanned,
limit: Math.min(pageSize, params.maxScan - scanned),
search: params.sn ?? params.query,
sourceDocumentSN: params.sn
});
total = data.total;
scanned += data.records.length;
const filtered = filterRuns(data.records, params.query)
.filter((record) => !params.sn || record.sourceDocumentSN === params.sn)
.filter((record) => !params.batchId || record.sourceExtendData?.simulation_batch_id === params.batchId);
records.push(...filtered);
if (data.records.length === 0 || (total !== undefined && scanned >= total)) break;
}
records.sort((left, right) => timestampOf(right.createdAt) - timestampOf(left.createdAt));
return {
total,
scanned,
records: records.slice(0, params.latest ? 1 : params.limit)
};
}
function timestampOf(value: unknown): number {
if (typeof value === "number") return value;
if (typeof value === "string") {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : 0;
}
return 0;
}
async function resolveRuleVersion(
client: KyInstance,
params: { versionId?: string; versionNumber?: number; latestRuleVersion?: boolean; 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;
}
async function resolveRuleVersionSelector(client: KyInstance, selector: string): Promise<RuleSetVersion> {
const normalized = selector.trim();
if (!normalized) throw new Error("Rule version selector cannot be empty");
if (normalized === "latest") {
const versions = await api.listApprovalRuleVersions(client);
const latest = versions[0];
if (!latest) throw new Error("No rule versions found");
return api.getApprovalRuleVersion(client, latest.id);
}
const versionNumber = Number(normalized);
if (Number.isInteger(versionNumber) && versionNumber > 0) {
const versions = await api.listApprovalRuleVersions(client);
const version = versions.find((item) => item.versionNumber === versionNumber);
if (!version) throw new Error(`Rule version not found: ${versionNumber}`);
return api.getApprovalRuleVersion(client, version.id);
}
return api.getApprovalRuleVersion(client, normalized);
}
function filterRuns(records: ApprovalRun[], query?: string): ApprovalRun[] {
const normalized = query?.trim().toLowerCase();
if (!normalized) return records;
return records.filter((record) => {
const directValues = [
record.id,
record.sourceDocumentSN,
record.sourceDocumentId,
record.documentId,
record.sourceExtendData?._langfuseTraceId,
record.sourceExtendData?.simulation_batch_id,
record.status,
record.taskMode,
record.finalExecutionMode,
record.sourceSystem,
record.ruleSetVersionNumber,
record.ruleSetPublishedByName
];
return directValues.some((value) => scalarIncludes(value, normalized)) ||
objectContainsScalar(record, normalized);
});
}
function scalarIncludes(value: unknown, normalized: string): boolean {
if (value === null || value === undefined) return false;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return String(value).toLowerCase().includes(normalized);
}
return false;
}
function objectContainsScalar(value: unknown, normalized: string, depth = 0): boolean {
if (depth > 6) return false;
if (scalarIncludes(value, normalized)) return true;
if (!value || typeof value !== "object") return false;
if (Array.isArray(value)) {
return value.some((item) => objectContainsScalar(item, normalized, depth + 1));
}
return Object.entries(value as Record<string, unknown>).some(([key, item]) =>
scalarIncludes(key, normalized) || objectContainsScalar(item, normalized, depth + 1)
);
}
function filterRunsByHumanResult(records: ApprovalRun[], humanResult?: string): ApprovalRun[] {
const normalized = humanResult?.trim().toLowerCase();
if (!normalized) return records;
return records.filter((record) =>
extractHumanResult(record)?.value.toLowerCase().includes(normalized)
);
}
function withApprovalRunFilters<T extends {
manualApprovalStatus?: string | string[];
humanResult?: string;
}>(params: T) {
return {
...params,
manualApprovalStatus: resolveManualApprovalStatus(
params.manualApprovalStatus,
params.humanResult
)
};
}
function resolveManualApprovalStatus(
manualApprovalStatus?: string | string[],
humanResult?: string
): string | string[] | undefined {
if (manualApprovalStatus) return manualApprovalStatus;
const normalized = humanResult?.trim().toLowerCase();
if (!normalized) return undefined;
if (["驳回", "已驳回", "拒绝", "不通过", "terminated", "reject", "rejected", "denied"].includes(normalized)) {
return "TERMINATED";
}
return undefined;
}
async function prepareApprovalRuns(
client: KyInstance,
records: ApprovalRun[],
filters: {
query?: string;
humanResult?: string;
}
): Promise<ApprovalRun[]> {
const queriedRecords = filterRuns(records, filters.query);
if (!filters.humanResult?.trim()) return queriedRecords;
const detailedRecords = await Promise.all(
queriedRecords.map(async (record) => {
if (extractHumanResult(record)) return record;
try {
return await api.getApprovalRun(client, record.id);
} catch {
return record;
}
})
);
return filterRunsByHumanResult(detailedRecords, filters.humanResult);
}
type HumanResultMatch = {
value: string;
path: string;
};
function approvalRunAliases(record: ApprovalRun) {
return {
originalDocumentData: {
path: "document",
frontendLabel: "单据原始数据",
description: "前端详情页展示的单据原始数据对象",
id: record.document?.id ?? record.documentId,
sourceDocumentSN: record.document?.sourceDocumentSN ?? record.sourceDocumentSN,
sourceDocumentId: record.document?.sourceDocumentId ?? record.sourceDocumentId
},
aiDocumentFields: {
path: "document.fields",
frontendLabel: "AI 看的单据",
description: "AI 审核实际读取的字段数组,即单据原始数据中的 fields",
fieldCount: record.document?.fields?.length
},
aiDocument: {
path: "document.fields",
frontendLabel: "AI 看的单据",
description: "兼容别名,等同于 aiDocumentFields",
aliasOf: "aiDocumentFields",
fieldCount: record.document?.fields?.length
},
sourceDocument: {
path: "sourceExtendData.hosecloudViewUrl",
description: "合思原始单据入口;详情响应中只有入口和源单据 ID,不包含完整原始单据 JSON",
sourceSystem: record.sourceSystem,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
originalDocumentId: record.sourceExtendData?.original_document_id,
viewUrl: record.sourceExtendData?.hosecloudViewUrl
},
aiResult: {
path: "result",
description: "AI 最终审核结构化结果"
},
aiAuditLog: {
path: "pipelineData.logs",
description: "AI 审核过程日志"
},
manualApproval: {
path: "manualApprovalRecord",
description: "人工审核结果、节点和驳回原因"
}
};
}
function extractHumanResult(record: ApprovalRun): HumanResultMatch | undefined {
const roots: Array<[string, unknown]> = [
["result", record.result],
["pipelineData", record.pipelineData]
];
for (const [path, value] of roots) {
const match = findHumanResultValue(value, path);
if (match) return match;
}
return undefined;
}
function findHumanResultValue(
value: unknown,
path: string,
depth = 0
): HumanResultMatch | undefined {
if (depth > 8 || value === null || value === undefined) return undefined;
if (Array.isArray(value)) {
for (let index = 0; index < value.length; index += 1) {
const match = findHumanResultValue(value[index], `${path}[${index}]`, depth + 1);
if (match) return match;
}
return undefined;
}
if (typeof value !== "object") return undefined;
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
const childPath = `${path}.${key}`;
const match = findHumanResultValue(child, childPath, depth + 1);
if (match) return match;
if (isHumanResultKey(key) || isHumanResultKey(childPath)) {
const text = stringifyHumanResultValue(child);
if (text) return { value: text, path: childPath };
}
}
return undefined;
}
function isHumanResultKey(key: string): boolean {
const normalized = key.toLowerCase();
const isHuman =
normalized.includes("human") ||
normalized.includes("manual") ||
normalized.includes("reviewer") ||
normalized.includes("operator") ||
key.includes("人工") ||
key.includes("人工审批") ||
key.includes("人工审核");
const isResult =
normalized.includes("result") ||
normalized.includes("decision") ||
normalized.includes("outcome") ||
normalized.includes("conclusion") ||
normalized.includes("action") ||
key.includes("结果") ||
key.includes("结论") ||
key.includes("动作");
return isHuman && isResult;
}
function stringifyHumanResultValue(value: unknown): string | undefined {
if (typeof value === "string") return value.trim() || undefined;
if (typeof value === "number" || typeof value === "boolean") return String(value);
if (!value || typeof value !== "object") return undefined;
const object = value as Record<string, unknown>;
for (const key of ["label", "name", "text", "value", "result", "decision", "outcome", "status", "action"]) {
const text = stringifyHumanResultValue(object[key]);
if (text) return text;
}
return undefined;
}
function matchesRunLookup(
record: ApprovalRun,
lookup: {
recordId?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
}
): boolean {
if (lookup.recordId && record.id !== lookup.recordId) return false;
if (lookup.sourceDocumentSN && record.sourceDocumentSN !== lookup.sourceDocumentSN) return false;
if (lookup.sourceDocumentId && record.sourceDocumentId !== lookup.sourceDocumentId) return false;
return true;
}
function countBy<T>(items: T[], keyFor: (item: T) => string): Record<string, number> {
return items.reduce<Record<string, number>>((counts, item) => {
const key = keyFor(item);
counts[key] = (counts[key] ?? 0) + 1;
return counts;
}, {});
}
function localDateKey(value: string | number | undefined, timezone: string): string | undefined {
const date = toDate(value);
if (!date) return undefined;
const parts = localParts(date, timezone);
const year = parts.year;
const month = (parts.month ?? "01").padStart(2, "0");
const day = (parts.day ?? "01").padStart(2, "0");
return `${year}-${month}-${day}`;
}
function formatLocalDateTime(value: string | number | undefined, timezone: string): string | undefined {
const date = toDate(value);
if (!date) return undefined;
const parts = localParts(date, timezone);
const month = (parts.month ?? "01").padStart(2, "0");
const day = (parts.day ?? "01").padStart(2, "0");
const hour = (parts.hour ?? "00").padStart(2, "0");
const minute = (parts.minute ?? "00").padStart(2, "0");
const second = (parts.second ?? "00").padStart(2, "0");
return `${parts.year ?? "0000"}-${month}-${day} ${hour}:${minute}:${second}`;
}
function toDate(value: string | number | undefined): Date | null {
if (value === undefined) return null;
const date = new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
function localParts(date: Date, timezone: string): Record<string, string> {
return Object.fromEntries(
new Intl.DateTimeFormat("en-CA", {
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
})
.formatToParts(date)
.filter((part) => part.type !== "literal")
.map((part) => [part.type, part.value])
);
}