From bbff9338a0f71443bb80c47f8128075eefe0a0a0 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Fri, 16 Oct 2026 11:19:32 +0800 Subject: [PATCH] Add hose-ebot command for Hose outbound discovery and approval callback --- skills/seal-use/references/cli.md | 9 + .../references/hose-enterprise-deploy.md | 25 + src/cli/commands/hose-ebot.test.ts | 580 ++++++++++++++++++ src/cli/commands/hose-ebot.ts | 125 ++++ src/cli/help.ts | 50 ++ src/cli/parser.ts | 20 +- src/cli/read-only.test.ts | 4 + src/cli/read-only.ts | 3 + src/cli/runner.ts | 6 + src/domains/hose/close/outbound.ts | 86 ++- src/domains/hose/open/approval.ts | 123 ++++ src/domains/hose/open/client.ts | 5 +- src/domains/hose/open/index.ts | 1 + src/domains/seal/capabilities/hose.ts | 217 +++++++ src/domains/seal/capabilities/index.ts | 5 + 15 files changed, 1242 insertions(+), 17 deletions(-) create mode 100644 src/cli/commands/hose-ebot.test.ts create mode 100644 src/cli/commands/hose-ebot.ts create mode 100644 src/domains/hose/open/approval.ts create mode 100644 src/domains/seal/capabilities/hose.ts diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index d8b60b9..270e735 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -157,6 +157,9 @@ seal-use deploy hosecloud status [--corp ] seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp ] seal-use deploy hosecloud sync [] [--auto] [--dry-run] [--yes|--confirm] [--corp ] seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--rejection-num ] [--dry-run] [--yes|--confirm] [--corp ] +seal-use hose-ebot search [--type invoking|callback] [--limit ] [--reveal] [--corp ] +seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp ] +seal-use hose-ebot callback --flow-id --node-id --action --comment <审批意见> [--sign-key ] [--policy ] [--add-approver-ids ] [--reject-to ] [--resubmit-method ] [--dry-run] [--yes|--confirm] [--corp ] seal-use preference get [--corp ] seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp ] seal-use preference thinking-depth set --default [--dry-run] [--corp ] @@ -249,6 +252,12 @@ Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSec - `seal-use auth hose-extract-keys ` and `seal-use auth hose-keys [--corp ]` are the explicit Hose auth-domain commands. The old `extract-keys`/`extract-key`/`extract-hose-keys` and `keys` forms remain aliases. - `seal-use auth hose-openapi-token [--corp ] [--force]` exchanges the persisted Hose `appKey/appSecurity` for an OpenAPI `accessToken` and prints it as machine JSON (`token`, `expiresAt`, `cached`; aliases `openapi-token`, `hose-token`). A still-fresh cached token is reused by default (`cached: true`, with a stderr notice); `--force` mints a new one. Unlike `auth check`, the token is intentionally unredacted. Rejects non-Hose tenants with exit code 2; missing credentials exit 13. +Hose outbound discovery & EBot callback (first-level `hose-ebot` command; Hose-only): + +- `seal-use hose-ebot search [--type invoking|callback] [--limit ] [--reveal]` is the default entry: it searches the Hose outbound message log by document SN and returns records that each carry a unique `id` (`INVOKING`=出站触发, `CALLBACK`=回调), plus the `flowId`/`nodeId`/`messageId`/`rejectionNum` a callback needs. Read-only; any `signKey` inside records is masked unless `--reveal`. +- `seal-use hose-ebot messages [--type flow|message] [--reveal]` lists every outbound message config on the Hose side (`messageName`, `signKey`, `callbackUrl`, `enable`, …). `signKey` is the `config_id` embedded in the callback URL; masked unless `--reveal`. Read-only. +- `seal-use hose-ebot callback --flow-id --node-id --action --comment <审批意见> …` runs the EBot approval callback (`POST /api/openapi/v1/approval`) and writes the result into the approval flow; success is `value.code=204`. Requires `--dry-run` (masked preview) or `--yes/--confirm` (otherwise exit 10). `--sign-key` is optional when the enterprise has exactly one Seal Hose integration. Upstream business codes map to exit codes: 401→11, 400→13, 412/500→1. Only EBot-node approvals are supported upstream. + Read-only discovery: - `seal-use contacts departments|children|users|sync-time --corp ` queries the tenant's organization tree and last directory sync time. diff --git a/skills/seal-use/references/hose-enterprise-deploy.md b/skills/seal-use/references/hose-enterprise-deploy.md index 7ffe81b..e8a9157 100644 --- a/skills/seal-use/references/hose-enterprise-deploy.md +++ b/skills/seal-use/references/hose-enterprise-deploy.md @@ -91,6 +91,31 @@ seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id -- 实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。 出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。 +### 出站发现与 EBot 回调(一级命令 `hose-ebot`) + +`sync` 之后,出站消息的发现与回调审批走独立的一级命令 `seal-use hose-ebot`(Hose 专属,非合思租户拒绝,退出码 13): + +```text +# 9. 按单号搜索出站/回调记录(默认入口;每条记录带唯一 id) +seal-use hose-ebot search --corp +seal-use hose-ebot search --type invoking --corp # 只看 出站触发 +seal-use hose-ebot search --type callback --corp # 只看 回调 + +# 10. 列出全部出站消息配置,发现 signKey(即回调地址中的 config_id) +seal-use hose-ebot messages --corp +seal-use hose-ebot messages --reveal --type flow --corp # 明文 signKey + +# 11. 回调审批(写入审批流;先 --dry-run 预览,正式执行必须 --yes) +seal-use hose-ebot callback --corp --sign-key \ + --flow-id --node-id --action accept --comment "同意" --dry-run +seal-use hose-ebot callback --corp --sign-key \ + --flow-id --node-id --action accept --comment "同意" --yes +``` + +- `hose-ebot search` 返回记录的唯一 `id`,回调所需的 `flowId`/`nodeId` 直接来自记录的 `request` 字段;`--type invoking|callback` 区分出站触发与回调,`--limit` 控制条数(默认 20)。 +- `hose-ebot messages --reveal` 输出的 `signKey` 就是 `hose-ebot callback --sign-key` 的入参;企业仅有一个 Seal 合思集成时可省略 `--sign-key` 自动解析。 +- 回调成功返回 `value.code=204`;上游业务码映射退出码:401(signKey 错误)→11、400(参数错误)→13、412/500 →1。缺少 `--yes`/`--confirm` 且无 `--dry-run` 时退出码 10。accessToken 在回调前实时换取,不复用缓存;仅支持 EBot 节点的审批回调。 + --- ## 4. 关键配置参数定义 diff --git a/src/cli/commands/hose-ebot.test.ts b/src/cli/commands/hose-ebot.test.ts new file mode 100644 index 0000000..86e4733 --- /dev/null +++ b/src/cli/commands/hose-ebot.test.ts @@ -0,0 +1,580 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { KyInstance } from "ky"; +import { CorpConfigSchema } from "../../core/config/types.js"; +import { classifyCliError } from "../../core/errors.js"; +import { parseArgs } from "../parser.js"; +import { handleHoseEbotCommand } from "./hose-ebot.js"; + +const ORIGINAL_ENV = { + tokenStore: process.env.SEAL_USE_TOKEN_STORE, + usageFile: process.env.SEAL_USE_USAGE_FILE +}; +const ORIGINAL_FETCH = globalThis.fetch; +const ORIGINAL_LOG = console.log; +const ORIGINAL_ERROR = console.error; + +let tempDir: string | undefined; + +beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-")); + process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json"); + process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json"); +}); + +afterEach(() => { + restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore); + restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile); + globalThis.fetch = ORIGINAL_FETCH; + console.log = ORIGINAL_LOG; + console.error = ORIGINAL_ERROR; + if (tempDir) { + rmSync(tempDir, { recursive: true, force: true }); + tempDir = undefined; + } +}); + +function restoreEnv(name: string, value: string | undefined) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; +} + +const hoseCorp = CorpConfigSchema.parse({ + id: "hose-ebot", + name: "合思 EBot 测试企业", + environment: "test", + seal: { url: "https://hose-ebot.sealai.cc" }, + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + appKey: "key-1", + appSecurity: "sec-1", + closeToken: "web-session-token", + corpId: "ID01LG7ksGroB1", + staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN" + } +}); + +const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({ + ...hoseCorp, + id: "hose-ebot-nocreds", + source: { + type: "hose", + domain: "https://app.ekuaibao.com", + closeToken: "web-session-token", + corpId: "ID01LG7ksGroB1", + staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN" + } +}); + +const sealCorp = CorpConfigSchema.parse({ + id: "seal-ebot", + name: "原生 Seal 企业", + environment: "test", + seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } }, + source: { + type: "seal", + sealUrl: "https://seal.test", + token: "mock-token", + staffId: "seal-staff", + corpId: "seal-corp" + } +}); + +const messageFixture = { + items: [ + { + id: "ID01Vj4Zq1Lytp", + messageName: "希尔顿Seal AI审核1", + messageType: "flow", + enable: true, + signKey: "Q4H15lpixMyE7secretvalue", + callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue", + corporationId: "ID01LG7ksGroB1", + actionEvent: ["backlog.processed"], + formFields: ["action", "flowId", "nodeId"] + }, + { + id: "ID01Vj4VDa8CGH", + messageName: "完成回调", + messageType: "message", + enable: false, + signKey: "Q4H15lpixOtherSecret", + callbackUrl: "https://sealai.cc/api/hosecloud/complete", + corporationId: "ID01LG7ksGroB1", + actionEvent: ["flow.completed"] + } + ] +}; + +const logFixture = { + items: [ + { + id: "log-1", + name: "出站调用", + type: "INVOKING", + state: "SUCCESS", + createTime: 1727764000000, + flowId: { id: "FLOW-1", form: { code: "SN123" } }, + nodeName: "AI 审核节点", + request: { + flowId: "FLOW-1", + nodeId: "NODE-1", + messageId: "MSG-1", + rejectionNum: 0 + } + }, + { + id: "log-2", + name: "审批回调", + type: "CALLBACK", + state: "SUCCESS", + createTime: 1727764010000, + flowId: { id: "FLOW-1", form: { code: "SN123" } }, + nodeName: "AI 审核节点", + request: { + flowId: "FLOW-1", + nodeId: "NODE-1", + signKey: "Q4H15lpixMyE7secretvalue", + action: "accept", + comment: "AI 审核通过" + } + } + ] +}; + +function mockFetch(responses: { + messages?: unknown; + logs?: unknown; + token?: unknown; + approval?: unknown; +}) { + const record: { + calls: number; + messageUrl?: string; + logUrl?: string; + logBody?: unknown; + tokenUrl?: string; + tokenBody?: unknown; + approvalUrl?: string; + approvalBody?: unknown; + } = { calls: 0 }; + + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + record.calls++; + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url; + let bodyText: string | undefined; + if (init?.body) { + bodyText = String(init.body); + } else if (input && typeof input === "object" && "clone" in input) { + bodyText = await (input as Request).clone().text().catch(() => undefined); + } + + if (url.includes("/api/outbound/v1/message/messageLog")) { + record.logUrl = url; + record.logBody = bodyText ? JSON.parse(bodyText) : undefined; + return new Response(JSON.stringify(responses.logs ?? logFixture), { + status: 200, + headers: { "content-type": "application/json" } + }); + } + + if (url.includes("/api/outbound/v1/message")) { + record.messageUrl = url; + return new Response(JSON.stringify(responses.messages ?? messageFixture), { + status: 200, + headers: { "content-type": "application/json" } + }); + } + + if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) { + record.tokenUrl = url; + record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined; + return new Response( + JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }), + { status: 200, headers: { "content-type": "application/json" } } + ); + } + + if (url.includes("/api/openapi/v1/approval")) { + record.approvalUrl = url; + record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined; + const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } }; + return new Response(JSON.stringify(resp), { + status: 200, + headers: { "content-type": "application/json" } + }); + } + + return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 }); + }) as typeof fetch; + + return record; +} + +function fakeClient(integrations: Array> = []) { + return { + get: async () => ({ + json: async () => ({ integrations }) + }) + } as unknown as KyInstance; +} + +async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) { + const lines: string[] = []; + console.log = (line: string) => lines.push(String(line)); + console.error = () => {}; + const args = parseArgs(argv); + await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args); + return JSON.parse(lines.join("\n")) as Record; +} + +async function captureError(action: () => Promise): Promise { + try { + await action(); + } catch (error) { + return error; + } + throw new Error("expected action to throw, but it succeeded"); +} + +describe("hose-ebot messages", () => { + test("lists configured outbound messages with a masked signKey by default", async () => { + const record = mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]); + + expect(output.count).toBe(2); + expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1"); + const messages = output.messages as Array>; + expect(messages[0]).toMatchObject({ + id: "ID01Vj4Zq1Lytp", + messageName: "希尔顿Seal AI审核1", + messageType: "flow", + enable: true + }); + // maskHoseSecurity keeps the first 8 and last 4 characters. + expect(messages[0]!.signKey).toBe("Q4H15lpi...alue"); + expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue"); + expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue"); + expect(output.revealed).toBe(false); + }); + + test("filters by type and reveals the signKey with --reveal", async () => { + mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "messages", "--type", "flow", "--reveal" + ]); + + expect(output.count).toBe(1); + expect(output.revealed).toBe(true); + const messages = output.messages as Array>; + expect(messages).toHaveLength(1); + expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue"); + }); + + test("rejects a non-Hose enterprise with exit code 13", async () => { + const record = mockFetch({}); + const error = await captureError(() => + callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"]) + ); + expect(classifyCliError(error).exitCode).toBe(13); + expect(record.calls).toBe(0); + }); +}); + +describe("hose-ebot search", () => { + test("requires an SN and lists records with their unique ids", async () => { + const usageError = await captureError(() => + callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"]) + ); + expect(classifyCliError(usageError).exitCode).toBe(2); + + const record = mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "search", "SN123", "--limit", "5" + ]); + + expect(output.count).toBe(2); + expect(output.sn).toBe("SN123"); + expect(output.type).toBe("all"); + expect(record.logBody).toMatchObject({ + limit: { start: 0, count: 5 }, + filterBy: '(flowId.form.code==("SN123"))' + }); + const records = output.records as Array>; + expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" }); + expect((records[0]!.request as Record).nodeId).toBe("NODE-1"); + // Callback records embed signKey; masked unless --reveal. + expect((records[1]!.request as Record).signKey).not.toBe( + "Q4H15lpixMyE7secretvalue" + ); + }); + + test("filters to invoking or callback records with --type", async () => { + const record = mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "search", "SN123", "--type", "callback" + ]); + + expect(output.type).toBe("callback"); + expect(output.count).toBe(1); + const records = output.records as Array>; + expect(records[0]!.type).toBe("CALLBACK"); + // The client-side filter over-fetches first so the page stays full. + expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } }); + + // Also accepts uppercase --type CALLBACK + const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "search", "SN123", "--type", "CALLBACK" + ]); + expect(outputUpper.count).toBe(1); + }); + + test("reveals the record signKey with --reveal", async () => { + mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "search", "SN123", "--reveal" + ]); + const records = output.records as Array>; + expect((records[1]!.request as Record).signKey).toBe( + "Q4H15lpixMyE7secretvalue" + ); + }); + + test("rejects an unknown verb with exit code 2", async () => { + const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"])); + expect(classifyCliError(error).exitCode).toBe(2); + expect(String((error as Error).message)).toContain("Unknown hose-ebot command"); + }); +}); + +describe("hose-ebot callback", () => { + const callbackArgv = (extra: string[] = []) => [ + "hose-ebot", "callback", + "--flow-id", "FLOW-1", + "--node-id", "NODE-1", + "--action", "accept", + "--comment", "同意", + ...extra + ]; + + test("refuses to run without --yes/--confirm before any network call", async () => { + const record = mockFetch({}); + const error = await captureError(() => + callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"])) + ); + expect(classifyCliError(error).exitCode).toBe(10); + expect(record.calls).toBe(0); + expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback"); + }); + + test("previews a masked payload with --dry-run without minting a token", async () => { + const record = mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, [ + ...callbackArgv(["--sign-key", "sig-1", "--dry-run"]) + ]); + + expect(output.preview).toBe(true); + expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval"); + const payload = output.payload as Record; + expect(payload).toMatchObject({ + flowId: "FLOW-1", + nodeId: "NODE-1", + action: "accept", + comment: "同意" + }); + expect(payload.signKey).not.toBe("sig-1"); + expect(record.calls).toBe(0); + }); + + test("mints a fresh accessToken and posts the callback on a confirmed run", async () => { + const record = mockFetch({}); + const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([ + "--sign-key", "sig-1", + "--yes" + ])); + + expect(output).toMatchObject({ + ok: true, + code: "204", + message: "EBot执行完成", + flowId: "FLOW-1", + nodeId: "NODE-1", + action: "accept" + }); + expect(record.approvalUrl).toContain("/api/openapi/v1/approval"); + expect(record.approvalUrl).toContain("accessToken=live-openapi-token"); + expect(record.approvalBody).toMatchObject({ + signKey: "sig-1", + flowId: "FLOW-1", + nodeId: "NODE-1", + action: "accept", + comment: "同意" + }); + }); + + test("normalizes action aliases like agree/approve/reject", async () => { + const record = mockFetch({}); + await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "callback", + "--sign-key", "sig-1", + "--flow-id", "FLOW-1", + "--node-id", "NODE-1", + "--action", "agree", + "--comment", "口语化同意", + "--yes" + ]); + expect(record.approvalBody).toMatchObject({ action: "accept" }); + + await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "callback", + "--sign-key", "sig-1", + "--flow-id", "FLOW-1", + "--node-id", "NODE-1", + "--action", "reject", + "--comment", "口语化驳回", + "--yes" + ]); + expect(record.approvalBody).toMatchObject({ action: "refuse" }); + }); + + test("passes optional callback fields through to the wire payload with camelCase support", async () => { + const record = mockFetch({}); + await callHoseEbot(fakeClient(), hoseCorp, [ + "hose-ebot", "callback", + "--sign-key", "sig-1", + "--flow-id", "FLOW-1", + "--node-id", "NODE-1", + "--action", "refuse", + "--comment", "驳回", + "--policy", "ALL", + "--addApproverIds", "staff-1,staff-2", + "--rejectTo", "NODE-0", + "--resubmitMethod", "TO_REJECTOR", + "--yes" + ]); + + expect(record.approvalBody).toMatchObject({ + action: "refuse", + policy: "ALL", + addApproverIds: ["staff-1", "staff-2"], + rejectTo: "NODE-0", + resubmitMethod: "TO_REJECTOR" + }); + }); + + test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => { + const record = mockFetch({}); + const client = fakeClient([ + { type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" } + ]); + await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"])); + expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" }); + }); + + test("maps upstream business codes to exit codes and references hose-ebot messages", async () => { + mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } }); + const error401 = await captureError(() => + callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"])) + ); + expect(classifyCliError(error401).exitCode).toBe(11); + expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal"); + + mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } }); + const error412 = await captureError(() => + callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"])) + ); + expect(classifyCliError(error412).exitCode).toBe(1); + expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search"); + + mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } }); + const error400 = await captureError(() => + callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"])) + ); + expect(classifyCliError(error400).exitCode).toBe(13); + }); + + test("validates preAdd and aftAdd approver and policy requirements before network call", async () => { + const record = mockFetch({}); + const preAddError = await captureError(() => + callHoseEbot( + fakeClient(), + hoseCorp, + callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"]) + ) + ); + expect(classifyCliError(preAddError).exitCode).toBe(13); + expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人"); + expect(record.calls).toBe(0); + + const aftAddPolicyError = await captureError(() => + callHoseEbot( + fakeClient(), + hoseCorp, + callbackArgv([ + "--action", + "aftAdd", + "--add-approver-ids", + "user1,user2", + "--sign-key", + "sig-1", + "--yes" + ]) + ) + ); + expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13); + expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL"); + expect(record.calls).toBe(0); + }); + + test("normalizes lowercase policy and kebab-case resubmit-method", async () => { + const record = mockFetch({ + approval: { value: { code: "204", message: "success" } } + }); + + await callHoseEbot( + fakeClient(), + hoseCorp, + callbackArgv([ + "--action", + "aftAdd", + "--add-approver-ids", + "user1,user2", + "--policy", + "all", + "--resubmit-method", + "from-start", + "--sign-key", + "sig-1", + "--yes" + ]) + ); + expect(record.approvalBody).toMatchObject({ + action: "aftAdd", + addApproverIds: ["user1", "user2"], + policy: "ALL", + resubmitMethod: "FROM_START" + }); + }); + + test("rejects a non-Hose enterprise with exit code 13", async () => { + const record = mockFetch({}); + const error = await captureError(() => + callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"])) + ); + expect(classifyCliError(error).exitCode).toBe(13); + expect(record.calls).toBe(0); + }); + + test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => { + const record = mockFetch({}); + const error = await captureError(() => + callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"])) + ); + expect(classifyCliError(error).exitCode).toBe(13); + expect(String((error as Error).message)).toContain("缺少合思凭证"); + expect(record.calls).toBe(0); + }); +}); diff --git a/src/cli/commands/hose-ebot.ts b/src/cli/commands/hose-ebot.ts new file mode 100644 index 0000000..1067925 --- /dev/null +++ b/src/cli/commands/hose-ebot.ts @@ -0,0 +1,125 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { CliError } from "../errors.js"; +import { runCapability } from "../helpers.js"; +import { booleanOption, numberOption, stringOption } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +const USAGE = + "Usage:\n" + + " seal-use hose-ebot search [--type invoking|callback] [--limit ] [--reveal] [--corp ]\n" + + " seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp ]\n" + + " seal-use hose-ebot callback --flow-id --node-id --action --comment <审批意见> [--sign-key ] [--dry-run] [--yes|--confirm] [--corp ]"; + +function normalizeEbotAction(raw: string | undefined): string | undefined { + if (!raw) return undefined; + const lower = raw.trim().toLowerCase(); + if (lower === "accept" || lower === "agree" || lower === "approve") return "accept"; + if (lower === "refuse" || lower === "reject") return "refuse"; + if (lower === "preadd" || lower === "pre-add") return "preAdd"; + if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd"; + return raw; +} + +function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined { + if (!raw) return undefined; + const upper = raw.trim().toUpperCase(); + if (upper === "ALL" || upper === "ANY") return upper; + return raw as "ALL" | "ANY"; +} + +function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined { + if (!raw) return undefined; + const norm = raw.trim().toUpperCase().replace(/-/g, "_"); + if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm; + return raw as "FROM_START" | "TO_REJECTOR"; +} + +/** + * First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop: + * search is the default entry (discover records by document SN), `messages` + * discovers outbound message configs and their signKey, and `callback` runs + * the approval callback. + */ +export async function handleHoseEbotCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + if (!action) { + throw new CliError(USAGE, 2); + } + + if (action === "search") { + const sn = maybeName ?? stringOption(args.options.sn); + if (!sn) { + throw new CliError(`Missing document SN.\n\n${USAGE}`, 2); + } + const rawType = stringOption(args.options.type)?.trim().toLowerCase(); + await runCapability( + "sealHoseOutboundSearch", + client, + corp, + { + sn, + type: rawType, + limit: numberOption(args.options.limit), + reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true + }, + outputOptions(args.options) + ); + return; + } + + if (action === "messages") { + const rawType = stringOption(args.options.type)?.trim().toLowerCase(); + await runCapability( + "sealHoseOutboundMessages", + client, + corp, + { + reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true, + type: rawType + }, + outputOptions(args.options) + ); + return; + } + + if (action === "callback") { + const addApproverIdsRaw = + stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds); + await runCapability( + "sealHoseApprovalCallback", + client, + corp, + { + signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]), + flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]), + nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]), + action: normalizeEbotAction(stringOption(args.options.action)), + comment: stringOption(args.options.comment), + policy: normalizeEbotPolicy(stringOption(args.options.policy)), + addApproverIds: addApproverIdsRaw + ? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean) + : undefined, + rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo), + resubmitMethod: normalizeResubmitMethod( + stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod) + ), + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]), + confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true + }, + outputOptions(args.options) + ); + return; + } + + throw new CliError( + `Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`, + 2 + ); +} diff --git a/src/cli/help.ts b/src/cli/help.ts index a79d265..145361c 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -855,6 +855,56 @@ export const HELP_REGISTRY: AreaHelp[] = [ } ] }, + { + area: "hose-ebot", + title: "Hose EBot outbound discovery & callback (合思 EBot 出站发现与审批回调)", + description: "按单号搜索出站/回调记录、列出出站消息配置(signKey),并执行 EBot 审批回调。", + commands: [ + { + name: "search", + summary: "【出站发现·默认入口】按单号搜索出站消息调用记录(只读)", + usage: ["seal-use hose-ebot search [--type invoking|callback] [--limit ] [--reveal] [--corp ]"], + options: [ + { flag: "--type ", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" }, + { flag: "--limit ", description: "返回条数上限(默认 20,最大 100)" }, + { flag: "--reveal, -r", description: "明文展示记录中的 signKey(默认脱敏)" } + ], + description: + "在合思 CloseAPI 出站消息日志中按单号 (SN) 搜索,返回带唯一 id 的记录列表(INVOKING 出站触发 / CALLBACK 回调),含 flowId/nodeId/messageId/rejectionNum 等回调上下文。" + }, + { + name: "messages", + summary: "【出站配置】列出全部出站消息配置,发现 signKey 与回调地址(只读)", + usage: ["seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp ]"], + options: [ + { flag: "--type ", description: "按类型过滤:flow=审批流 EBot 出站,message=完成回调/通知" }, + { flag: "--reveal, -r", description: "明文展示 signKey(默认脱敏为 8...4 形式)" } + ], + description: + "经合思 CloseAPI 只读查询本企业全部出站消息配置(messageName、signKey、callbackUrl、enable 等)。signKey 即出站回调地址中的 config_id,可直接用于 'hose-ebot callback'。" + }, + { + name: "callback", + summary: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签)", + usage: [ + "seal-use hose-ebot callback --flow-id --node-id --action --comment <审批意见> [--sign-key ] [--policy ] [--add-approver-ids ] [--reject-to ] [--resubmit-method ] [--dry-run] [--yes|--confirm] [--corp ]" + ], + options: [ + { flag: "--comment ", description: "审批意见(必填)" }, + { flag: "--sign-key ", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" }, + { flag: "--action ", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" }, + { flag: "--policy ", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" }, + { flag: "--add-approver-ids ", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" }, + { flag: "--reject-to ", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" }, + { flag: "--resubmit-method ", description: "驳回后重提方式;缺省按 EBot 节点配置" }, + { flag: "--dry-run", description: "仅预览回调请求(signKey 脱敏),不执行" }, + { flag: "--yes, --confirm", description: "正式执行必需;届时实时换取 accessToken 后回调" } + ], + description: + "调用合思开放接口 POST /api/openapi/v1/approval,向审批流回写 EBot 节点审批结果,成功返回 value.code=204。仅支持 EBot 节点的审批;signKey 可通过 'seal-use hose-ebot messages --reveal' 发现。" + } + ] + }, { area: "preference", title: "Audit preferences and thinking depth", diff --git a/src/cli/parser.ts b/src/cli/parser.ts index ae355c7..374118e 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -40,9 +40,9 @@ export const BOOLEAN_FLAGS = new Set([ // Read with stringOption/numberOption/splitOption(...). export const VALUE_FLAGS = new Set([ - "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity", + "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", - "channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", + "channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix", @@ -60,12 +60,12 @@ export const VALUE_FLAGS = new Set([ "n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "p", "package-id", "package-ids", "packageId", "packageIds", - "path", "phone", "policyId", "poll-interval", "pollInterval", "port", + "path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "purpose", "q", "query", - "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum", + "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "reviewed-by", "reviewedBy", "report-id", - "repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", + "repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id", "runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey", @@ -86,11 +86,11 @@ export const VALUE_FLAGS = new Set([ // Registered flags. Unknown flags are rejected. export const KNOWN_FLAGS = new Set([ - "V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key", + "V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key", "app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId", "bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome", - "code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content", + "code", "comment", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", @@ -114,12 +114,12 @@ export const KNOWN_FLAGS = new Set([ "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite", "p", "package-id", "package-ids", "packageId", "packageIds", "path", - "phone", "plain", "policyId", "poll-interval", "pollInterval", "port", + "phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "publish", "purpose", "q", "query", "quiet", "r", "recode", "record-id", "record-ids", - "recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo", + "recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo", "report-id", - "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow", + "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow", "reviewed-by", "reviewedBy", "reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios", diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index 6825552..86dc8f8 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -60,6 +60,8 @@ describe("CLI read-only classification", () => { ["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"], ["approval-runs", "list", "--corp", "corp-a"], ["deploy", "hosecloud", "status", "--corp", "corp-a"], + ["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"], + ["hose-ebot", "messages", "--corp", "corp-a"], ["preferences", "get"], ["doctor", "tenant", "--corp", "corp-a"], ["langfuse", "check"], @@ -91,6 +93,8 @@ describe("CLI read-only classification", () => { ["simulation", "create", "--mode", "hosecloud"], ["deploy", "hosecloud", "sync", "sign-key"], ["deploy", "hosecloud", "configure"], + // The EBot approval callback writes accept/refuse into the live approval flow. + ["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"], ["webhook", "delete", "hook-1"], ["webhook", "replay"], ["users", "reset-password", "corp-a:u1"], diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 587079a..540b731 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -64,6 +64,9 @@ const READ_ONLY_COMMANDS: Record = { "integrations" ], deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"], + // `hose-ebot callback` is deliberately absent: it mints an accessToken and writes an + // approval action into the live flow. Only the two discovery verbs read. + "hose-ebot": ["search", "messages"], preference: ["get", "thinking-depth policies list"], // `config mode`/`config lint` are omitted: classification is token-prefix based, so their // read forms cannot be separated from the value-taking write forms. `config get` returns diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 9d1ce1e..40beef4 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -39,6 +39,7 @@ export const KNOWN_AREAS = new Set([ "corps", "corp", "source", + "hose-ebot", "auth", "users", "contacts", @@ -416,6 +417,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) { return; } + if (area === "hose-ebot") { + await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args); + return; + } + if (area === "preference" || area === "preferences") { await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args); return; diff --git a/src/domains/hose/close/outbound.ts b/src/domains/hose/close/outbound.ts index 4883f71..cdf7d57 100644 --- a/src/domains/hose/close/outbound.ts +++ b/src/domains/hose/close/outbound.ts @@ -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; + 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 { + 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 { 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 { 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); } diff --git a/src/domains/hose/open/approval.ts b/src/domains/hose/open/approval.ts new file mode 100644 index 0000000..e0563bb --- /dev/null +++ b/src/domains/hose/open/approval.ts @@ -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 { + 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) : {}; + const valueObj = rawObj.value && typeof rawObj.value === "object" ? (rawObj.value as Record) : 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 || "未知错误"}`); +} diff --git a/src/domains/hose/open/client.ts b/src/domains/hose/open/client.ts index 650468d..6c30da3 100644 --- a/src/domains/hose/open/client.ts +++ b/src/domains/hose/open/client.ts @@ -38,13 +38,14 @@ export function createHoseOpenClientWithCredentials( export async function createHoseOpenClient( corp: CorpConfig, - customHeaders?: Record + customHeaders?: Record, + options?: { force?: boolean } ): Promise { 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, diff --git a/src/domains/hose/open/index.ts b/src/domains/hose/open/index.ts index 498d3bc..11fcc9e 100644 --- a/src/domains/hose/open/index.ts +++ b/src/domains/hose/open/index.ts @@ -1,3 +1,4 @@ export * from "./types.js"; export * from "./client.js"; export * from "./api.js"; +export * from "./approval.js"; diff --git a/src/domains/seal/capabilities/hose.ts b/src/domains/seal/capabilities/hose.ts new file mode 100644 index 0000000..455b9ad --- /dev/null +++ b/src/domains/seal/capabilities/hose.ts @@ -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 + }; + } + } +]; diff --git a/src/domains/seal/capabilities/index.ts b/src/domains/seal/capabilities/index.ts index 7da6c7c..b396d3d 100644 --- a/src/domains/seal/capabilities/index.ts +++ b/src/domains/seal/capabilities/index.ts @@ -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 = new Set([ "sealDeployHosecloudRequirements", "sealDeployHosecloudStatus", "sealExpensesList", + "sealHoseOutboundMessages", + "sealHoseOutboundSearch", "sealInsightExport", "sealInsightPerformanceGet", "sealInsightRisksByTagGet", @@ -138,6 +142,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet = new Set([ "sealDeployHosecloudConfigure", "sealDeployHosecloudSync", "sealDeployHosecloudTestOutbound", + "sealHoseApprovalCallback", "sealInsightRecordAnalyze", "sealPreferenceDecisionUpdate", "sealPreferenceThinkingDepthPoliciesRemove",