Add hose-ebot command for Hose outbound discovery and approval callback
This commit is contained in:
1 parent
21e1a9d27a
commit
bbff9338a0
15 files changed
+1242
-17
No files matched your search
@@ -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<Record<string, unknown>> = []) {
|
||||
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<string, unknown>;
|
||||
}
|
||||
|
||||
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
|
||||
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<Record<string, unknown>>;
|
||||
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<Record<string, unknown>>;
|
||||
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<Record<string, unknown>>;
|
||||
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
|
||||
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
|
||||
// Callback records embed signKey; masked unless --reveal.
|
||||
expect((records[1]!.request as Record<string, unknown>).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<Record<string, unknown>>;
|
||||
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<Record<string, unknown>>;
|
||||
expect((records[1]!.request as Record<string, unknown>).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<string, unknown>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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 <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
|
||||
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
|
||||
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
|
||||
|
||||
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<ReturnType<typeof createSealClient>>,
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -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 <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--type <invoking|callback>", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" },
|
||||
{ flag: "--limit <n>", 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 <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--type <flow|message>", 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 <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "--comment <text>", description: "审批意见(必填)" },
|
||||
{ flag: "--sign-key <key>", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" },
|
||||
{ flag: "--action <accept|refuse|preAdd|aftAdd>", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" },
|
||||
{ flag: "--policy <ALL|ANY>", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" },
|
||||
{ flag: "--add-approver-ids <id,id>", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" },
|
||||
{ flag: "--reject-to <nodeId>", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" },
|
||||
{ flag: "--resubmit-method <FROM_START|TO_REJECTOR>", 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",
|
||||
|
||||
+10
-10
@@ -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",
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -64,6 +64,9 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"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
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user