399 lines
17 KiB
TypeScript
399 lines
17 KiB
TypeScript
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import { randomBytes } from "node:crypto";
|
||
import * as api from "../api.js";
|
||
import { probeHoseDomain } from "../../../core/auth/hose.js";
|
||
import { confirmationRequired, validationError } from "../../../core/errors.js";
|
||
import { type HosecloudConfigInput } from "../types.js";
|
||
import {
|
||
assertAssistedIntegration,
|
||
BLOCKING_NODE_ID,
|
||
buildOutboundPayload,
|
||
buildOutboundWebhookUrl,
|
||
flowIdFromDocumentSn,
|
||
listHoseIntegrations,
|
||
pushOutboundAndVerify,
|
||
resolveCorporationId,
|
||
selectHoseIntegration
|
||
} from "../outbound/push.js";
|
||
import type {
|
||
CapabilityContext
|
||
} from "./helpers.js";
|
||
import * as helpers from "./helpers.js";
|
||
|
||
const {
|
||
redactIntegrationSecrets,
|
||
mutationPreview
|
||
} = helpers;
|
||
|
||
export const deployCapabilities = [
|
||
{
|
||
name: "sealDeployHosecloudRequirements",
|
||
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: "sealDeployHosecloudList",
|
||
description: "列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",
|
||
parameters: z.object({}),
|
||
handler: async (client: KyInstance) => {
|
||
const config = await api.getApprovalStylePreferences(client);
|
||
const integrations = listHoseIntegrations(config);
|
||
return {
|
||
count: integrations.length,
|
||
integrations: integrations.map(redactIntegrationSecrets)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealDeployHosecloudGet",
|
||
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 = listHoseIntegrations(config).find(
|
||
(item) => item.signKey === params.signKey
|
||
);
|
||
if (!integration) {
|
||
throw new Error(`未找到合思配置:${params.signKey}`);
|
||
}
|
||
return redactIntegrationSecrets(integration as Record<string, unknown>);
|
||
}
|
||
},
|
||
{
|
||
name: "sealDeployHosecloudStatus",
|
||
description: "检查【Seal AI 审批发布到合思费控】与多平台集成状态",
|
||
parameters: z.object({}),
|
||
handler: async (client: KyInstance) => {
|
||
const status = await api.getSimulationIntegrationStatus(client);
|
||
const config = await api.getApprovalStylePreferences(client);
|
||
const integrations = listHoseIntegrations(config);
|
||
return {
|
||
status,
|
||
integrations: integrations.map(redactIntegrationSecrets)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealDeployHosecloudConfigure",
|
||
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
|
||
parameters: z.object({
|
||
// Optional in the schema because the handler accepts two spellings of the
|
||
// same credential (`apiKey`, or the legacy `appKey` alias) and enforces
|
||
// that one pair is present itself — see the check right below. Marking
|
||
// only `apiKey` required would reject `appKey` payloads the handler has
|
||
// always accepted.
|
||
apiKey: z.string().optional().describe("合思 API Key (appKey)"),
|
||
apiSecret: z.string().optional().describe("合思 API Secret (appSecurity)"),
|
||
appKey: z.string().optional().describe("apiKey 的旧写法,等价"),
|
||
appSecurity: z.string().optional().describe("apiSecret 的旧写法,等价"),
|
||
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,不执行写入"),
|
||
confirm: z.boolean().optional().describe("明确确认保存配置;CLI 使用 --yes 或 --confirm")
|
||
}),
|
||
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: CapabilityContext) => {
|
||
const { dryRun, confirm, appKey, appSecurity, ...inputParams } = rawParams;
|
||
const apiKey = inputParams.apiKey ?? (typeof appKey === "string" ? appKey : undefined);
|
||
const apiSecret = inputParams.apiSecret ?? (typeof appSecurity === "string" ? appSecurity : undefined);
|
||
if (!apiKey || !apiSecret) {
|
||
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
|
||
}
|
||
const params = { ...inputParams, apiKey, apiSecret };
|
||
let effectiveApiOrigin = params.apiOrigin ?? "production";
|
||
let effectiveCustomApiUrl = params.customApiUrl;
|
||
|
||
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
|
||
throw new Error("自定义合思环境必须提供 customApiUrl");
|
||
}
|
||
if (!dryRun && confirm !== true) {
|
||
throw confirmationRequired(
|
||
"Refusing to save Hose integration configuration without --yes or --confirm. Use --dry-run to preview first.",
|
||
"seal-use help deploy hosecloud configure"
|
||
);
|
||
}
|
||
|
||
// 自动平台/域名探测:当未提供 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 {
|
||
// 探测失败时平滑降级,由后续后端校验处理
|
||
}
|
||
}
|
||
|
||
const corpResult = await api.getHosecloudCorporation(client, {
|
||
apiKey: params.apiKey,
|
||
apiSecret: params.apiSecret,
|
||
apiOrigin: effectiveApiOrigin,
|
||
customApiUrl: effectiveCustomApiUrl
|
||
});
|
||
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
|
||
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} --dry-run --corp ${context.corp.id}`);
|
||
|
||
return {
|
||
integration: redactIntegrationSecrets(nextIntegration)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealDeployHosecloudSync",
|
||
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
|
||
parameters: z.object({
|
||
signKey: z.string().describe("合思集成 sign-key"),
|
||
dryRun: z.boolean().optional().describe("只预览待同步的消息名称、回调地址和模式,不执行同步"),
|
||
confirm: z.boolean().optional().describe("明确确认同步到合思;CLI 使用 --yes 或 --confirm")
|
||
}),
|
||
handler: async (client: KyInstance, params: { signKey: string; dryRun?: boolean; confirm?: boolean }, context: CapabilityContext) => {
|
||
if (!params.dryRun && params.confirm !== true) {
|
||
throw confirmationRequired(
|
||
"Refusing to synchronize Hose outbound messages without --yes or --confirm. Use --dry-run to preview first.",
|
||
`seal-use deploy hosecloud sync ${params.signKey} --dry-run --corp ${context.corp.id}`
|
||
);
|
||
}
|
||
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
|
||
const integration = listHoseIntegrations(config).find(
|
||
(item) => 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.outboundName ?? "SealAI 审批";
|
||
const payload = {
|
||
signKey: params.signKey,
|
||
webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey),
|
||
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
|
||
messageName,
|
||
mode: integration.mode ?? "assisted"
|
||
};
|
||
if (params.dryRun) {
|
||
return {
|
||
...mutationPreview(context, "api/hosecloud/outbound-config/sync", null, payload, 1),
|
||
signKey: params.signKey,
|
||
remoteStateKnown: false,
|
||
note: "仅预览将同步的消息名称、回调地址和模式;合思远端当前配置尚未读取。"
|
||
};
|
||
}
|
||
const result = await api.syncHosecloudOutbound(client, payload);
|
||
|
||
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
|
||
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
|
||
|
||
return {
|
||
signKey: params.signKey,
|
||
synced: true,
|
||
result
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealDeployHosecloudTestOutbound",
|
||
description: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发,强制要求目标集成必须为 assisted 模式",
|
||
parameters: z.object({
|
||
signKey: z.string().optional().describe("合思集成 sign-key(若企业仅有一个合思配置可自动识别)"),
|
||
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
|
||
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
|
||
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
|
||
nodeId: z.string().optional().default(BLOCKING_NODE_ID).describe("合思流程节点 ID(默认填入中文阻断标识)"),
|
||
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
|
||
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
|
||
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送"),
|
||
confirm: z.boolean().optional().describe("明确确认实际推送;CLI 使用 --yes 或 --confirm")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
signKey?: string;
|
||
flowId?: string;
|
||
sn?: string;
|
||
messageId: string;
|
||
nodeId?: string;
|
||
rejectionNum?: number;
|
||
corporationId?: string;
|
||
dryRun?: boolean;
|
||
confirm?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const config = await api.getApprovalStylePreferences(client);
|
||
const integration = selectHoseIntegration({
|
||
integrations: listHoseIntegrations(config),
|
||
signKey: params.signKey,
|
||
corpName: context.corp.name,
|
||
corpId: context.corp.id
|
||
});
|
||
|
||
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
|
||
assertAssistedIntegration(integration, {
|
||
corpName: context.corp.name,
|
||
corpId: context.corp.id
|
||
});
|
||
|
||
// 2. 消息凭证校验
|
||
const messageId = params.messageId?.trim();
|
||
if (!messageId) {
|
||
throw validationError(
|
||
"缺少必需参数 --message-id。合思开放平台出站协议要求使用真实有效的 messageId 换取单据上下文,请从合思出站请求日志中提取提供。"
|
||
);
|
||
}
|
||
|
||
// 3. 解析 flowId
|
||
let flowId = params.flowId?.trim();
|
||
const sn = params.sn?.trim();
|
||
if (!flowId && sn) {
|
||
try {
|
||
const existing = await api.listApprovalRuns(client, {
|
||
search: sn,
|
||
sourceDocumentSN: sn,
|
||
limit: 5
|
||
});
|
||
const match = (existing.records || []).find(
|
||
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn
|
||
);
|
||
if (match?.sourceDocumentId) {
|
||
flowId = match.sourceDocumentId;
|
||
}
|
||
} catch {
|
||
// 忽略
|
||
}
|
||
if (!flowId) {
|
||
flowId = flowIdFromDocumentSn(sn);
|
||
}
|
||
}
|
||
|
||
if (!flowId) {
|
||
throw validationError(
|
||
"缺少必需参数 --flow-id(合思单据/流程 ID)。若已存在该单的历史运行记录,也可通过 --sn <单号> 自动解析。"
|
||
);
|
||
}
|
||
|
||
// 4. 解析 corporationId
|
||
const corporationId = resolveCorporationId([params.corporationId, integration.corporationId]);
|
||
|
||
const payload = buildOutboundPayload({
|
||
flowId,
|
||
messageId,
|
||
nodeId: params.nodeId,
|
||
rejectionNum: params.rejectionNum,
|
||
corporationId
|
||
});
|
||
const webhookUrl = buildOutboundWebhookUrl(context.corp, integration.signKey!);
|
||
|
||
if (params.dryRun) {
|
||
return {
|
||
preview: true,
|
||
url: webhookUrl,
|
||
targetCorp: context.corp.id,
|
||
targetIntegration: {
|
||
signKey: integration.signKey,
|
||
outboundName: integration.outboundName,
|
||
mode: integration.mode
|
||
},
|
||
safetyCheck: {
|
||
mode: "assisted",
|
||
passed: true,
|
||
nodeId412Blocked: payload.nodeId === BLOCKING_NODE_ID,
|
||
note: payload.nodeId === BLOCKING_NODE_ID
|
||
? "目标企业出站模式为 assisted;使用默认中文 nodeId 阻断标记。"
|
||
: "目标企业出站模式为 assisted;自定义 nodeId 未验证具备 HTTP 412 阻断保障。"
|
||
},
|
||
payload
|
||
};
|
||
}
|
||
|
||
const { response, createdRecord } = await pushOutboundAndVerify({
|
||
client,
|
||
signKey: integration.signKey!,
|
||
payload,
|
||
flowId,
|
||
sn,
|
||
confirm: params.confirm,
|
||
corpName: context.corp.name,
|
||
corpId: context.corp.id,
|
||
pushedMessages: [
|
||
`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`
|
||
]
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
targetCorp: context.corp.id,
|
||
signKey: integration.signKey,
|
||
mode: integration.mode,
|
||
payload,
|
||
response,
|
||
consumptionVerified: createdRecord !== undefined,
|
||
recordId: createdRecord?.id,
|
||
recordStatus: createdRecord?.status,
|
||
taskMode: createdRecord?.taskMode
|
||
};
|
||
}
|
||
}
|
||
];
|