Add hose-ebot command for Hose outbound discovery and approval callback

This commit is contained in:
gitea committed 2026-10-16 11:19:50 +08:00
1 parent 21e1a9d27a
commit bbff9338a0
15 files changed
+1242 -17

No files matched your search

+81 -5
View File
@@ -36,13 +36,88 @@ export interface HoseOutboundLogItem {
response?: unknown;
}
/**
* A configured outbound message on the Hose side (EBot push or completion
* callback). Only the fields seal-use surfaces are kept; Hose returns more.
*/
export interface HoseOutboundMessageConfig {
id: string;
messageName?: string;
messageType?: string;
enable?: boolean;
signKey?: string;
callbackUrl?: string;
corporationId?: string;
actionEvent?: string[];
formFields?: string[];
remark?: string;
createTime?: number;
updateTime?: number;
}
function parseOutboundMessage(item: unknown): HoseOutboundMessageConfig | undefined {
if (!item || typeof item !== "object" || Array.isArray(item)) return undefined;
const raw = item as Record<string, unknown>;
if (typeof raw.id !== "string" || !raw.id) return undefined;
const stringList = (value: unknown): string[] | undefined =>
Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string")
: undefined;
return {
id: raw.id,
messageName: typeof raw.messageName === "string" ? raw.messageName : undefined,
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
enable: typeof raw.enable === "boolean" ? raw.enable : undefined,
signKey: typeof raw.signKey === "string" ? raw.signKey : undefined,
callbackUrl: typeof raw.callbackUrl === "string" ? raw.callbackUrl : undefined,
corporationId: typeof raw.corporationId === "string" ? raw.corporationId : undefined,
actionEvent: stringList(raw.actionEvent),
formFields: stringList(raw.formFields),
remark: typeof raw.remark === "string" ? raw.remark : undefined,
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined
};
}
/**
* List every configured outbound message for the tenant via the read-only
* CloseAPI `GET api/outbound/v1/message`. Each row carries the `signKey` that
* the EBot callback URL embeds as `config_id`, which is how operators find
* which signature key belongs to which message.
*/
export async function fetchHoseOutboundMessages(
sourceCorp: CorpConfig
): Promise<HoseOutboundMessageConfig[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
`企业「${sourceCorp.name}」非合思(hose)租户,无法查询合思出站消息配置。`
);
}
const client = await createHoseCloseClient(sourceCorp);
const response = (await client
.get("api/outbound/v1/message", {
searchParams: { corpId: sourceCorp.source.corpId }
})
.json()) as { items?: unknown };
if (!Array.isArray(response.items)) {
throw new Error("合思出站消息接口未返回 items 列表,响应结构与预期不符");
}
return response.items
.map(parseOutboundMessage)
.filter((message): message is HoseOutboundMessageConfig => message !== undefined);
}
/**
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
*/
export async function searchOutboundMessageLogs(
client: KyInstance,
corpId: string,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
const response = (await client
.post("api/outbound/v1/message/messageLog", {
@@ -51,10 +126,10 @@ export async function searchOutboundMessageLogs(
corpId
},
json: {
limit: { start: 0, count: 20 },
limit: { start: 0, count: options?.limit ?? 20 },
orderBy: [{ value: "createTime", order: "DESC" }],
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
filterBy: `(flowId.form.code==("${sn}"))`
filterBy: `(flowId.form.code==("${sn.replace(/"/g, '\\"')}"))`
}
})
.json()) as { items?: HoseOutboundLogItem[] };
@@ -67,7 +142,8 @@ export async function searchOutboundMessageLogs(
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
@@ -76,5 +152,5 @@ export async function fetchHoseOutboundLogs(
}
const client = await createHoseCloseClient(sourceCorp);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn, options);
}
+123
View File
@@ -0,0 +1,123 @@
import { HTTPError } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { CliError, validationError } from "../../../core/errors.js";
import { createHoseOpenClient } from "./client.js";
/**
* EBot approval callback (`POST api/openapi/v1/approval`) — the OpenAPI call an
* external service makes after processing an outbound message, so the EBot node
* can advance (accept/refuse) or add approvers. Only EBot-node approvals are
* supported upstream; everything else comes back as business code 412.
*/
export const EBOT_APPROVAL_ACTIONS = ["accept", "refuse", "preAdd", "aftAdd"] as const;
export type EbotApprovalAction = (typeof EBOT_APPROVAL_ACTIONS)[number];
export const EBOT_RESUBMIT_METHODS = ["FROM_START", "TO_REJECTOR"] as const;
export type EbotApprovalCallbackParams = {
signKey: string;
flowId: string;
nodeId: string;
action: EbotApprovalAction;
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
};
export type EbotApprovalCallbackResult = {
code: string;
message: string;
};
export async function executeEbotApprovalCallback(
corp: CorpConfig,
params: EbotApprovalCallbackParams
): Promise<EbotApprovalCallbackResult> {
if (corp.source.type !== "hose") {
throw validationError(
`企业「${corp.name}」非合思(hose)租户,无法调用合思 OpenAPI 审批回调。`
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法换取 accessToken 执行审批回调。`
);
}
if ((params.action === "preAdd" || params.action === "aftAdd") && (!params.addApproverIds || params.addApproverIds.length === 0)) {
throw validationError(
`执行${params.action === "preAdd" ? "前加签 (preAdd)" : "后加签 (aftAdd)"}时,必须通过 --add-approver-ids 指定加签审批人 ID 列表。`
);
}
if (params.action === "aftAdd" && (params.addApproverIds?.length ?? 0) > 1 && !params.policy) {
throw validationError(
"后加签审批人超过 1 人时,必须指定会签方式 --policy ALL (会签) 或 --policy ANY (或签)。"
);
}
// The manual requires a token minted right before the callback: accessToken
// expires quickly and stale reuse is not worth the risk on a flow write.
const client = await createHoseOpenClient(corp, undefined, { force: true });
let response: unknown;
try {
response = await client.post("api/openapi/v1/approval", {
json: {
signKey: params.signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
}
}).json();
} catch (error) {
// HTTP 400 means our request body was rejected — an input problem, so the
// caller gets exit 13 with the upstream body; HTTP 401/403 fall through to
// the shared classifier (exit 11).
if (error instanceof HTTPError && error.response.status === 400) {
throw validationError(`合思审批回调参数被上游拒绝 (HTTP 400):${error.message}`);
}
throw error;
}
const rawObj = (response && typeof response === "object") ? (response as Record<string, unknown>) : {};
const valueObj = rawObj.value && typeof rawObj.value === "object" ? (rawObj.value as Record<string, unknown>) : rawObj;
const rawCode = valueObj.code ?? rawObj.code;
const code = rawCode !== undefined ? String(rawCode) : undefined;
const message = (typeof valueObj.message === "string" ? valueObj.message : (typeof rawObj.message === "string" ? rawObj.message : "")) || "";
if (code === "204") {
return { code, message };
}
if (code === "401") {
throw new CliError(
"合思审批回调失败:签名秘钥 signKey 错误 (401)。" +
"请核对出站消息配置中的 signKey(seal-use hose-ebot messages --reveal 可查看)。",
11
);
}
if (code === "400") {
throw validationError(`合思审批回调参数错误 (400):${message || "请求参数错误"}`);
}
if (code === "412") {
throw new CliError(
`合思审批回调失败:业务前置条件不满足 (412):${message || "当前节点不可审批或已被处理"}。\n` +
"👉 建议:运行 seal-use hose-ebot search <单号SN> 核对单据当前节点与出站记录。",
1
);
}
if (!code) {
throw new Error(`合思审批回调未返回业务码,响应与预期不符:${JSON.stringify(response)}`);
}
throw new Error(`合思审批回调失败 (${code}):${message || "未知错误"}`);
}
+3 -2
View File
@@ -38,13 +38,14 @@ export function createHoseOpenClientWithCredentials(
export async function createHoseOpenClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
customHeaders?: Record<string, string>,
options?: { force?: boolean }
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp);
const token = await ensureHoseOpenapiToken(corp, { force: options?.force });
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
+1
View File
@@ -1,3 +1,4 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./approval.js";
+217
View File
@@ -0,0 +1,217 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { maskHoseSecurity, normalizeBaseUrl } from "../../../core/auth/hose.js";
import { confirmationRequired, validationError } from "../../../core/errors.js";
import { fetchHoseOutboundLogs, fetchHoseOutboundMessages } from "../../hose/close/outbound.js";
import { executeEbotApprovalCallback } from "../../hose/open/approval.js";
import { listHoseIntegrations, selectHoseIntegration } from "../outbound/push.js";
import type { CapabilityContext } from "./helpers.js";
/**
* The niche Hose outbound loop, exposed under the first-level `seal-use hose-ebot`
* command: discover outbound records by document SN, discover the outbound
* message configs (and their signKey), then write the EBot approval callback.
*/
export const hoseCapabilities = [
{
name: "sealHoseOutboundSearch",
description: "按单号搜索合思出站消息调用记录(出站触发 INVOKING / 回调 CALLBACK),返回含唯一 id 的记录列表",
parameters: z.object({
sn: z.string().describe("合思单号 (flowId.form.code)"),
type: z
.enum(["invoking", "callback"])
.optional()
.describe("记录类型筛选:invoking=出站触发,callback=回调;缺省全部"),
limit: z
.number()
.int()
.positive()
.max(100)
.optional()
.default(20)
.describe("返回条数上限(默认 20,最大 100)"),
reveal: z.boolean().optional().describe("明文返回记录中的 signKey(默认脱敏)")
}),
handler: async (
_client: KyInstance,
params: { sn: string; type?: "invoking" | "callback"; limit: number; reveal?: boolean },
context: CapabilityContext
) => {
// The type filter applies client-side, so over-fetch first to keep the
// requested page size after filtering.
const serverCount = params.type ? Math.min(params.limit * 4, 100) : params.limit;
const allRecords = await fetchHoseOutboundLogs(context.corp, params.sn, { limit: serverCount });
const filtered = params.type
? allRecords.filter((record) => (record.type ?? "").toLowerCase() === params.type)
: allRecords;
const records = filtered.slice(0, params.limit);
return {
corpId: context.corp.id,
sn: params.sn,
type: params.type ?? "all",
count: records.length,
revealed: params.reveal === true,
records: records.map((record) =>
record.request?.signKey
? {
...record,
request: {
...record.request,
signKey: params.reveal
? record.request.signKey
: maskHoseSecurity(record.request.signKey)
}
}
: record
)
};
}
},
{
name: "sealHoseOutboundMessages",
description: "列出合思侧全部出站消息配置(含 signKey、回调地址、启用状态),用于发现 EBot 出站消息及其签名密钥",
parameters: z.object({
reveal: z.boolean().optional().describe("明文返回 signKey(默认脱敏为 8...4 形式)"),
type: z
.enum(["flow", "message"])
.optional()
.describe("按消息类型过滤:flow=审批流 EBot 出站,message=完成回调/通知")
}),
handler: async (
_client: KyInstance,
params: { reveal?: boolean; type?: "flow" | "message" },
context: CapabilityContext
) => {
const messages = await fetchHoseOutboundMessages(context.corp);
const filtered = params.type
? messages.filter((message) => message.messageType === params.type)
: messages;
return {
corpId: context.corp.id,
corpName: context.corp.name,
count: filtered.length,
revealed: params.reveal === true,
messages: filtered.map((message) => ({
...message,
signKey: message.signKey
? params.reveal
? message.signKey
: maskHoseSecurity(message.signKey)
: undefined
}))
};
}
},
{
name: "sealHoseApprovalCallback",
description: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签),向审批流回写结果;需 --yes/--confirm,或 --dry-run 预览",
parameters: z.object({
signKey: z
.string()
.optional()
.describe("出站消息签名密钥;缺省时从本企业 Seal 合思集成解析(仅一个集成时自动选择)"),
flowId: z.string().describe("单据 ID(出站消息中的 flowId)"),
nodeId: z.string().describe("当前 EBot 节点 ID(出站消息中的 nodeId)"),
action: z
.enum(["accept", "refuse", "preAdd", "aftAdd"])
.describe("accept 同意 / refuse 驳回 / preAdd 前加签 / aftAdd 后加签"),
comment: z.string().describe("审批意见"),
policy: z.enum(["ALL", "ANY"]).optional().describe("会签方式:ALL 会签 / ANY 或签(后加签超过一人时必填)"),
addApproverIds: z.array(z.string()).optional().describe("前后加签审批人 ID 列表(后加签时必填)"),
rejectTo: z.string().optional().describe("驳回目标节点 ID;缺省按 EBot 节点驳回配置"),
resubmitMethod: z
.enum(["FROM_START", "TO_REJECTOR"])
.optional()
.describe("驳回后重提方式:FROM_START 重新走审批流 / TO_REJECTOR 直接送审至此节点"),
dryRun: z.boolean().optional().default(false).describe("仅预览回调请求,不执行"),
confirm: z.boolean().optional().describe("明确确认执行回调;CLI 使用 --yes 或 --confirm")
}),
handler: async (
client: KyInstance,
params: {
signKey?: string;
flowId: string;
nodeId: string;
action: "accept" | "refuse" | "preAdd" | "aftAdd";
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
dryRun?: boolean;
confirm?: boolean;
},
context: CapabilityContext
) => {
if (!params.dryRun && params.confirm !== true) {
throw confirmationRequired(
"Refusing to run the Hose EBot approval callback without --yes or --confirm. Use --dry-run to preview first.",
`seal-use hose-ebot callback --flow-id ${params.flowId} --node-id ${params.nodeId} --action ${params.action} --comment "${params.comment}" --dry-run --corp ${context.corp.id}`
);
}
if (context.corp.source.type !== "hose") {
throw validationError(
`企业「${context.corp.name}」非合思(hose)租户,无法执行合思 EBot 审批回调。`
);
}
// An explicit signKey (typically discovered via `hose-ebot messages --reveal`)
// skips the Seal-side lookup; without one the configured integration decides.
let signKey = params.signKey?.trim();
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const integration = selectHoseIntegration({
integrations: listHoseIntegrations(config),
corpName: context.corp.name,
corpId: context.corp.id
});
signKey = integration.signKey;
}
if (!signKey) {
throw validationError(
`企业「${context.corp.name}」的合思出站配置未保存 signKey,请重新执行 configure。`
);
}
const payload = {
signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
};
if (params.dryRun) {
return {
preview: true,
corpId: context.corp.id,
endpoint: `${normalizeBaseUrl(context.corp.source.domain)}/api/openapi/v1/approval`,
payload: { ...payload, signKey: maskHoseSecurity(signKey) },
note: "仅预览:正式执行需去掉 --dry-run 并追加 --yes(届时实时换取 accessToken 后回调)。"
};
}
const result = await executeEbotApprovalCallback(context.corp, payload);
console.error(`✓ 回调审批成功 (code ${result.code}): ${result.message}`);
console.error(
`👉 Next action: seal-use hose-ebot search <单号SN> --corp ${context.corp.id} 核对该单出站/回调记录`
);
return {
corpId: context.corp.id,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
ok: true,
...result
};
}
}
];
+5
View File
@@ -7,6 +7,7 @@ import { webhookCapabilities } from "./webhook.js";
import { approvalRunsCapabilities } from "./approval-runs.js";
import { simulationCapabilities } from "./simulation.js";
import { deployCapabilities } from "./deploy.js";
import { hoseCapabilities } from "./hose.js";
import { preferenceCapabilities } from "./preference.js";
import { reportCapabilities } from "./reports.js";
@@ -23,6 +24,7 @@ export const sealCapabilities = [
...approvalRunsCapabilities,
...simulationCapabilities,
...deployCapabilities,
...hoseCapabilities,
...preferenceCapabilities,
...reportCapabilities
];
@@ -90,6 +92,8 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudRequirements",
"sealDeployHosecloudStatus",
"sealExpensesList",
"sealHoseOutboundMessages",
"sealHoseOutboundSearch",
"sealInsightExport",
"sealInsightPerformanceGet",
"sealInsightRisksByTagGet",
@@ -138,6 +142,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudConfigure",
"sealDeployHosecloudSync",
"sealDeployHosecloudTestOutbound",
"sealHoseApprovalCallback",
"sealInsightRecordAnalyze",
"sealPreferenceDecisionUpdate",
"sealPreferenceThinkingDepthPoliciesRemove",