Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4147cec58 | ||
|
|
aed3a10958 | ||
|
|
7af7be4925 | ||
|
|
152f96ec78 | ||
|
|
2fc88e208c | ||
|
|
042d223704 | ||
|
|
0296c2bff2 | ||
|
|
c094980ae5 | ||
|
|
932957ea08 | ||
|
|
f6cd2c68b0 | ||
|
|
38e1a45fc2 | ||
|
|
fa4113e828 | ||
|
|
793fcff5d5 |
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "seal-use",
|
"name": "seal-use",
|
||||||
"version": "0.11.3",
|
"version": "0.11.5",
|
||||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "yingqing"
|
"name": "yingqing"
|
||||||
|
|||||||
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.11.5] - 2026-10-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
|
||||||
|
- Update agent skill docs for Hose outbound replay and test-outbound
|
||||||
|
- Add Hose outbound replay with CloseAPI log matching and safety guards
|
||||||
|
- Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
|
||||||
|
- Unify assistance link duration parsing with hour floor and stderr hints
|
||||||
|
- Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
|
||||||
|
- Add configurable expiration for Seal and Hose assistance links
|
||||||
|
|
||||||
|
|
||||||
|
## [0.11.4] - 2026-10-10
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Merge pull request #211 from yunyingk/mac15/diagnose-simulation-dx-improvements
|
||||||
|
- Refine simulation DX, diagnose fields extraction, and rule mapping
|
||||||
|
|
||||||
|
|
||||||
## [0.11.3] - 2026-10-10
|
## [0.11.3] - 2026-10-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "seal-use",
|
"name": "seal-use",
|
||||||
"version": "0.11.3",
|
"version": "0.11.5",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
name: seal-use
|
name: seal-use
|
||||||
description: "v0.11.3: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
description: "v0.11.5: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||||
metadata:
|
metadata:
|
||||||
version: 0.11.3
|
version: 0.11.5
|
||||||
short-description: Seal tenant and Hose approval automation (v0.11.3)
|
short-description: Seal tenant and Hose approval automation (v0.11.5)
|
||||||
---
|
---
|
||||||
|
|
||||||
# Seal Use
|
# Seal Use
|
||||||
|
|||||||
@@ -145,13 +145,15 @@ seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
|
|||||||
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
|
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
|
||||||
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||||
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
||||||
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]
|
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--force] [--corp <corpId>]
|
||||||
|
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--corp <corpId>]
|
||||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||||
seal-use deploy hosecloud list [--corp <corpId>]
|
seal-use deploy hosecloud list [--corp <corpId>]
|
||||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||||
seal-use deploy hosecloud status [--corp <corpId>]
|
seal-use deploy hosecloud status [--corp <corpId>]
|
||||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
||||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
|
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
|
||||||
|
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--corp <corpId>]
|
||||||
seal-use preference get [--corp <corpId>]
|
seal-use preference get [--corp <corpId>]
|
||||||
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
|
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
|
||||||
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
|
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
|
||||||
|
|||||||
@@ -78,6 +78,9 @@ seal-use deploy hosecloud get [<signKey>] --corp <corpId>
|
|||||||
|
|
||||||
# 7. 检查发布与多平台集成状态
|
# 7. 检查发布与多平台集成状态
|
||||||
seal-use deploy hosecloud status --corp <corpId>
|
seal-use deploy hosecloud status --corp <corpId>
|
||||||
|
|
||||||
|
# 8. 测试/重放出站请求 (要求 assisted 模式,强制中文 nodeId 阻断安全门禁)
|
||||||
|
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] --corp <corpId>
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -192,6 +192,26 @@ flowchart TD
|
|||||||
```
|
```
|
||||||
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
|
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
|
||||||
|
|
||||||
|
- **方式 D:合思出站通道高仿重放 (Hose Outbound Replay,单据/附件仿真专属)**:
|
||||||
|
基于合思出站(EBot Outbound Webhook)官方通道的仿真重放。通过合思管理后台 CloseAPI 自动抓取历史出站日志中真实有效的 `messageId`、`flowId` 与 `rejectionNum`,并向测试环境出站网关推送;Seal 会依据真实 `messageId` 从合思开放平台拉取完整单据字段与全量二进制附件(发票、合同等),仿真度极高:
|
||||||
|
```bash
|
||||||
|
# 预览重放(自动从合思 CloseAPI 检索日志、提取真实 messageId 并做安全检查,不实际推送)
|
||||||
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --dry-run
|
||||||
|
|
||||||
|
# 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录)
|
||||||
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId>
|
||||||
|
|
||||||
|
# 精准匹配指定驳回重提轮次
|
||||||
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId>
|
||||||
|
|
||||||
|
# 底层直接推送出站调试消息(仅限 assisted 模式)
|
||||||
|
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId>
|
||||||
|
```
|
||||||
|
> **专属安全红线契约**:
|
||||||
|
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
|
||||||
|
> 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。
|
||||||
|
> 3. **中文 nodeId 物理阻断**:出站报文中注入中文标记 `nodeId: "FLOW:测试模拟节点_禁止流转"`。因为合思辅助审核也会调用审批回调,篡改后合思在回调时必定返回 `HTTP 200 { code: 412, message: "当前的审批节点不为:..." }` 物理级阻断,双重保障生产单据绝不会被意外流转或修改。
|
||||||
|
|
||||||
3. **轮询并检查判定结果**:
|
3. **轮询并检查判定结果**:
|
||||||
```bash
|
```bash
|
||||||
# 查看状态与进度
|
# 查看状态与进度
|
||||||
|
|||||||
+1
-1
@@ -70,7 +70,7 @@ describe("CLI version & help handling", () => {
|
|||||||
expect(result.stdout).toContain("seal-use webhook get|find <idOrName>");
|
expect(result.stdout).toContain("seal-use webhook get|find <idOrName>");
|
||||||
expect(result.stdout).toContain("seal-use webhook add --name <name> --result-url <url>");
|
expect(result.stdout).toContain("seal-use webhook add --name <name> --result-url <url>");
|
||||||
expect(result.stdout).toContain("seal-use corps add-link <url>");
|
expect(result.stdout).toContain("seal-use corps add-link <url>");
|
||||||
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--corp <corpId>]");
|
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]");
|
||||||
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
|
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -93,6 +93,83 @@ describe("auth links", () => {
|
|||||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("supports --expire 7d for native Seal link and passes expiresInHours: 168", async () => {
|
||||||
|
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-link-expire-"));
|
||||||
|
const enterprises = join(root, "enterprises");
|
||||||
|
tempDirs.push(root);
|
||||||
|
mkdirSync(enterprises, { recursive: true });
|
||||||
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||||
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||||
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||||
|
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||||
|
|
||||||
|
writeFileSync(
|
||||||
|
join(enterprises, "native-seal.json"),
|
||||||
|
JSON.stringify({
|
||||||
|
id: "native-seal",
|
||||||
|
name: "原生 Seal 企业",
|
||||||
|
environment: "production",
|
||||||
|
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
|
||||||
|
source: {
|
||||||
|
type: "seal",
|
||||||
|
token: "seal-token",
|
||||||
|
sealUrl: "https://native.seal.test",
|
||||||
|
expiresIn: 3600,
|
||||||
|
corpId: "native-corp",
|
||||||
|
staffId: "native-staff"
|
||||||
|
},
|
||||||
|
auth: { refreshTtl: 300 }
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let recordedPayload: any = null;
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const requestUrl = typeof input === "string"
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.toString()
|
||||||
|
: input.url;
|
||||||
|
const url = new URL(requestUrl);
|
||||||
|
if (url.pathname === "/api/v1/delegation/create") {
|
||||||
|
if (input instanceof Request) {
|
||||||
|
recordedPayload = await input.clone().json();
|
||||||
|
} else if (init?.body) {
|
||||||
|
recordedPayload = JSON.parse(String(init.body));
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
data: {
|
||||||
|
id: "delegation-7d",
|
||||||
|
token: "delegation-token-7d",
|
||||||
|
link: "https://native.seal.test/delegation?token=delegation-token-7d"
|
||||||
|
}
|
||||||
|
}), { status: 200, headers: { "content-type": "application/json" } });
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||||
|
status: 404,
|
||||||
|
headers: { "content-type": "application/json" }
|
||||||
|
});
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const result = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "7d"]);
|
||||||
|
expect(result.isError).toBe(false);
|
||||||
|
expect(recordedPayload).toMatchObject({
|
||||||
|
expiresInHours: 168
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test fractional duration: floors to 1h and prints stderr guidance
|
||||||
|
const floorResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "90m"]);
|
||||||
|
expect(floorResult.isError).toBe(false);
|
||||||
|
expect(recordedPayload).toMatchObject({
|
||||||
|
expiresInHours: 1
|
||||||
|
});
|
||||||
|
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
|
||||||
|
|
||||||
|
// Test reject exceeding 7 days (168 hours)
|
||||||
|
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
|
||||||
|
expect(invalidResult.isError).toBe(true);
|
||||||
|
expect(invalidResult.exitCode).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
test("formats hose-link with corp metadata, link, and Beijing ISO expiry without url field", async () => {
|
test("formats hose-link with corp metadata, link, and Beijing ISO expiry without url field", async () => {
|
||||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-"));
|
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-"));
|
||||||
const enterprises = join(root, "enterprises");
|
const enterprises = join(root, "enterprises");
|
||||||
@@ -164,6 +241,82 @@ describe("auth links", () => {
|
|||||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("supports --expire 7d for hose-link and converts to 604800 seconds", async () => {
|
||||||
|
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-7d-"));
|
||||||
|
const enterprises = join(root, "enterprises");
|
||||||
|
tempDirs.push(root);
|
||||||
|
mkdirSync(enterprises, { recursive: true });
|
||||||
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||||
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||||
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||||
|
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||||
|
|
||||||
|
writeFileSync(
|
||||||
|
join(enterprises, "hose-corp.json"),
|
||||||
|
JSON.stringify({
|
||||||
|
id: "hose-corp",
|
||||||
|
name: "合思测试企业",
|
||||||
|
environment: "production",
|
||||||
|
seal: { url: "https://hose-corp.sealai.cc" },
|
||||||
|
source: {
|
||||||
|
type: "hose",
|
||||||
|
domain: "https://app.ekuaibao.com",
|
||||||
|
appKey: "key-1",
|
||||||
|
appSecurity: "sec-1",
|
||||||
|
corpId: "HOSE-CORP",
|
||||||
|
staffId: "HOSE-CORP:STAFF-1"
|
||||||
|
},
|
||||||
|
auth: { refreshTtl: 300 }
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let recordedHoseBody: any = null;
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
const url = new URL(requestUrl);
|
||||||
|
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
value: { accessToken: "test-openapi-token", expireTime: 7200 }
|
||||||
|
}),
|
||||||
|
{ status: 200, headers: { "content-type": "application/json" } }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
|
||||||
|
if (input instanceof Request) {
|
||||||
|
recordedHoseBody = await input.clone().json();
|
||||||
|
} else if (init?.body) {
|
||||||
|
recordedHoseBody = JSON.parse(String(init.body));
|
||||||
|
}
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
value: {
|
||||||
|
message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-7d"
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{ status: 200, headers: { "content-type": "application/json" } }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||||
|
status: 404,
|
||||||
|
headers: { "content-type": "application/json" }
|
||||||
|
});
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const result = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "7d"]);
|
||||||
|
expect(result.isError).toBe(false);
|
||||||
|
expect(recordedHoseBody).toMatchObject({
|
||||||
|
expireDate: 604800
|
||||||
|
});
|
||||||
|
|
||||||
|
const result2 = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "2"]);
|
||||||
|
expect(result2.isError).toBe(false);
|
||||||
|
expect(recordedHoseBody).toMatchObject({
|
||||||
|
expireDate: 7200
|
||||||
|
});
|
||||||
|
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
|
||||||
|
});
|
||||||
|
|
||||||
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
|
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
|
||||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-check-"));
|
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-check-"));
|
||||||
const enterprises = join(root, "enterprises");
|
const enterprises = join(root, "enterprises");
|
||||||
|
|||||||
+17
-10
@@ -5,7 +5,12 @@ import type { CorpConfig } from "../../core/config/types.js";
|
|||||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
import {
|
||||||
|
booleanOption,
|
||||||
|
parseDelegationExpireHours,
|
||||||
|
parseHoseExpireSeconds,
|
||||||
|
stringOption
|
||||||
|
} from "../parser.js";
|
||||||
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
|
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
|
||||||
import type { ParsedArgs } from "../types.js";
|
import type { ParsedArgs } from "../types.js";
|
||||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||||
@@ -40,11 +45,13 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
|||||||
|
|
||||||
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
||||||
const note = stringOption(args.options.note);
|
const note = stringOption(args.options.note);
|
||||||
|
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||||
|
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||||
const session = await exchangeHoseAssistLink(fromLink);
|
const session = await exchangeHoseAssistLink(fromLink);
|
||||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||||
const me = await getMe(client);
|
const me = await getMe(client);
|
||||||
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
||||||
const delegation = await createDelegation(client, { note });
|
const delegation = await createDelegation(client, { note, expiresInHours });
|
||||||
|
|
||||||
printJson({
|
printJson({
|
||||||
tenant: {
|
tenant: {
|
||||||
@@ -60,7 +67,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
|||||||
isAdmin: me.user.isAdmin
|
isAdmin: me.user.isAdmin
|
||||||
},
|
},
|
||||||
delegation,
|
delegation,
|
||||||
expiresIn: session.expiresIn
|
expiresIn: session.expiresIn,
|
||||||
|
expiresAt: formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000)
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -90,18 +98,20 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
||||||
|
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||||
|
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||||
const delegation = await runCapabilityResult(
|
const delegation = await runCapabilityResult(
|
||||||
"sealDelegationCreate",
|
"sealDelegationCreate",
|
||||||
client,
|
client,
|
||||||
corp,
|
corp,
|
||||||
{ note }
|
{ note, expiresInHours }
|
||||||
);
|
);
|
||||||
if (action === "hose-link") {
|
if (action === "hose-link") {
|
||||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||||
}
|
}
|
||||||
const delegationRecord = delegation as Record<string, unknown>;
|
const delegationRecord = delegation as Record<string, unknown>;
|
||||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||||
const expiresAt = formatBeijingIso(Date.now() + 86400 * 1000);
|
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
|
||||||
printJson({
|
printJson({
|
||||||
id: delegationRecord.id,
|
id: delegationRecord.id,
|
||||||
corpId: corp.source.corpId ?? corp.id,
|
corpId: corp.source.corpId ?? corp.id,
|
||||||
@@ -116,11 +126,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (action === "hose-link") {
|
if (action === "hose-link") {
|
||||||
const rawExpire = args.options.expire;
|
const rawExpire = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||||
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
|
const expiresIn = parseHoseExpireSeconds(rawExpire, 7200);
|
||||||
if (expiresIn === undefined || expiresIn <= 0) {
|
|
||||||
throw new Error(`Invalid --expire: ${String(rawExpire)}. Must be a positive number of seconds (e.g. --expire 7200 or --expire 86400).`);
|
|
||||||
}
|
|
||||||
const force =
|
const force =
|
||||||
booleanOption(args.options.force) === true ||
|
booleanOption(args.options.force) === true ||
|
||||||
booleanOption(args.options.refresh) === true ||
|
booleanOption(args.options.refresh) === true ||
|
||||||
|
|||||||
@@ -78,11 +78,17 @@ export async function handleCorpBindings(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
|
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
|
||||||
|
console.error(
|
||||||
|
`⚠️ [bind-test] 检测到冲突:已强制解除生产企业「${prodCorp.name}」(${prodCorp.id}) 与原测试企业「${prodCorp.testCorpId}」的绑定关联。`
|
||||||
|
);
|
||||||
try {
|
try {
|
||||||
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
|
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
|
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
|
||||||
|
console.error(
|
||||||
|
`⚠️ [bind-test] 检测到冲突:已强制解除测试企业「${testCorp.name}」(${testCorp.id}) 与原生产企业「${testCorp.prodCorpId}」的绑定关联。`
|
||||||
|
);
|
||||||
try {
|
try {
|
||||||
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
|
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../dom
|
|||||||
import { selectCorp } from "../../helpers.js";
|
import { selectCorp } from "../../helpers.js";
|
||||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||||
import { printJson } from "../../printer.js";
|
import { outputOptions, printJson } from "../../printer.js";
|
||||||
import type { ParsedArgs } from "../../types.js";
|
import type { ParsedArgs } from "../../types.js";
|
||||||
|
|
||||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
||||||
@@ -50,7 +50,16 @@ export async function handleCorpSync(
|
|||||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }));
|
const result = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true });
|
||||||
|
const targetVersion = (result as { target?: { publishedVersion?: { versionNumber?: number; versionName?: string; rulesCount?: number } } })?.target?.publishedVersion;
|
||||||
|
const rulesList = (result as { ruleMapping?: unknown[] })?.ruleMapping ?? [];
|
||||||
|
console.error(
|
||||||
|
`✅ 测试企业同步完成: 生产「${prodCorp.name}」(${prodCorp.id}) -> 测试「${testCorp.name}」(${testCorp.id})\n` +
|
||||||
|
`📦 已发布测试版本: v${targetVersion?.versionNumber ?? "?"} (${targetVersion?.versionName ?? "最新"}) | 规则总数: ${targetVersion?.rulesCount ?? rulesList.length} 条\n` +
|
||||||
|
`🔄 规则映射已归档: 共 ${rulesList.length} 条规则已与测试环境对齐\n` +
|
||||||
|
`👉 下一步模拟测试建议: seal-use simulation create --document-sn <单号> --corp ${testCorp.id} --extract-expenses`
|
||||||
|
);
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
|
|||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import { runCapability } from "../helpers.js";
|
import { runCapability } from "../helpers.js";
|
||||||
import { booleanOption, jsonObject, stringOption } from "../parser.js";
|
import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js";
|
||||||
import { outputOptions } from "../printer.js";
|
import { outputOptions } from "../printer.js";
|
||||||
import type { ParsedArgs } from "../types.js";
|
import type { ParsedArgs } from "../types.js";
|
||||||
import * as api from "../../domains/seal/api.js";
|
import * as api from "../../domains/seal/api.js";
|
||||||
@@ -166,5 +166,35 @@ export async function handleDeployCommand(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync.`);
|
if (action === "test-outbound" || action === "outbound-test") {
|
||||||
|
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||||
|
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
|
||||||
|
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
|
||||||
|
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
|
||||||
|
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
|
||||||
|
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
|
||||||
|
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
|
||||||
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||||
|
|
||||||
|
await runCapability(
|
||||||
|
"sealDeployHosecloudTestOutbound",
|
||||||
|
client,
|
||||||
|
corp,
|
||||||
|
{
|
||||||
|
signKey,
|
||||||
|
flowId,
|
||||||
|
sn,
|
||||||
|
messageId,
|
||||||
|
nodeId,
|
||||||
|
rejectionNum,
|
||||||
|
corporationId,
|
||||||
|
dryRun
|
||||||
|
},
|
||||||
|
outputOptions(args.options)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +66,26 @@ export async function handleSimulationCommand(
|
|||||||
const wait = booleanOption(args.options.wait) === true;
|
const wait = booleanOption(args.options.wait) === true;
|
||||||
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]) ?? (wait ? false : true);
|
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]) ?? (wait ? false : true);
|
||||||
|
|
||||||
|
const extractExpenses =
|
||||||
|
booleanOption(args.options.extract) ??
|
||||||
|
booleanOption(args.options["extract-expenses"]) ??
|
||||||
|
booleanOption(args.options.extractExpenses) ??
|
||||||
|
booleanOption(args.options["with-expense-extraction"]) ??
|
||||||
|
booleanOption(args.options.withExpenseExtraction);
|
||||||
|
const skipExpenseOption =
|
||||||
|
booleanOption(args.options["skip-extract"]) ??
|
||||||
|
booleanOption(args.options.skipExtract) ??
|
||||||
|
booleanOption(args.options.skipExpenseExtraction) ??
|
||||||
|
booleanOption(args.options["skip-expense-extraction"]);
|
||||||
|
const skipExpenseExtraction =
|
||||||
|
extractExpenses !== undefined ? !extractExpenses : skipExpenseOption;
|
||||||
|
|
||||||
|
if (extractExpenses === true) {
|
||||||
|
console.error(
|
||||||
|
"💡 [simulation] 已开启后台费用明细提取入库 (--extract)。此批次明细将写入费用库,供后续跨单防重报检索。"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const result = await runCapabilityResult(
|
const result = await runCapabilityResult(
|
||||||
"sealSimulationBatchCreate",
|
"sealSimulationBatchCreate",
|
||||||
client,
|
client,
|
||||||
@@ -78,7 +98,7 @@ export async function handleSimulationCommand(
|
|||||||
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
||||||
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
||||||
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
||||||
skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]),
|
skipExpenseExtraction,
|
||||||
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
||||||
signKey,
|
signKey,
|
||||||
packageIds,
|
packageIds,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { CorpConfig } from "../../core/config/types.js";
|
|||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import { confirmationRequired } from "../errors.js";
|
import { confirmationRequired } from "../errors.js";
|
||||||
import { runCapability } from "../helpers.js";
|
import { runCapability } from "../helpers.js";
|
||||||
import { booleanOption, stringOption } from "../parser.js";
|
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
|
||||||
import { outputOptions } from "../printer.js";
|
import { outputOptions } from "../printer.js";
|
||||||
import type { ParsedArgs } from "../types.js";
|
import type { ParsedArgs } from "../types.js";
|
||||||
|
|
||||||
@@ -73,9 +73,17 @@ export async function handleUsersCommand(
|
|||||||
|
|
||||||
if (action === "delegation" || action === "impersonate") {
|
if (action === "delegation" || action === "impersonate") {
|
||||||
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
|
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
|
||||||
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");
|
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
|
||||||
const note = stringOption(args.options.note);
|
const note = stringOption(args.options.note);
|
||||||
await runCapability("sealUserDelegationCreate", client, corp, { userIdOrPhone, note }, outputOptions(args.options));
|
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||||
|
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||||
|
await runCapability(
|
||||||
|
"sealUserDelegationCreate",
|
||||||
|
client,
|
||||||
|
corp,
|
||||||
|
{ userIdOrPhone, note, expiresInHours },
|
||||||
|
outputOptions(args.options)
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -513,4 +513,61 @@ describe("seal-use webhook replay CLI", () => {
|
|||||||
const parsed = JSON.parse(forceResult.stdout);
|
const parsed = JSON.parse(forceResult.stdout);
|
||||||
expect(parsed.targetCorp.id).toBe("prod-corp-target");
|
expect(parsed.targetCorp.id).toBe("prod-corp-target");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("approval-runs replay --channel hose-outbound executes dry-run preview with safety guards", async () => {
|
||||||
|
setupMockEnv();
|
||||||
|
|
||||||
|
const mockHoseIntegrations = [
|
||||||
|
{
|
||||||
|
type: "hosecloud",
|
||||||
|
signKey: "sign-key-xyz",
|
||||||
|
outboundName: "测试出站通道",
|
||||||
|
mode: "assisted",
|
||||||
|
corporationId: "corp-id-123"
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||||
|
const requestUrl =
|
||||||
|
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
|
||||||
|
if (
|
||||||
|
requestUrl.includes("api/v1/system/preferences/approval-style") ||
|
||||||
|
requestUrl.includes("api/v1/agent/ai-approval/config")
|
||||||
|
) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
data: { integrations: mockHoseIntegrations }
|
||||||
|
}),
|
||||||
|
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new Response("Not found", { status: 404 });
|
||||||
|
}) as any;
|
||||||
|
|
||||||
|
const result = await runCli([
|
||||||
|
"approval-runs",
|
||||||
|
"replay",
|
||||||
|
"--sn",
|
||||||
|
"S26002992",
|
||||||
|
"--channel",
|
||||||
|
"hose-outbound",
|
||||||
|
"--message-id",
|
||||||
|
"ID01Wh05v0In3F",
|
||||||
|
"--flow-id",
|
||||||
|
"ID01Wah1FQ9faf",
|
||||||
|
"--dry-run"
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(result.isError).toBe(false);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
const parsed = JSON.parse(result.stdout);
|
||||||
|
expect(parsed.preview).toBe(true);
|
||||||
|
expect(parsed.channel).toBe("hose-outbound");
|
||||||
|
expect(parsed.payload.messageId).toBe("ID01Wh05v0In3F");
|
||||||
|
expect(parsed.payload.nodeId).toBe("FLOW:测试模拟节点_禁止流转");
|
||||||
|
expect(parsed.safetyGuards.targetModeAssisted).toBe(true);
|
||||||
|
expect(parsed.safetyGuards.nodeId412Blocked).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
resolveReplayCorpPair,
|
resolveReplayCorpPair,
|
||||||
type ReplayRecordsQuery
|
type ReplayRecordsQuery
|
||||||
} from "../../domains/seal/webhook-replay.js";
|
} from "../../domains/seal/webhook-replay.js";
|
||||||
|
import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js";
|
||||||
import {
|
import {
|
||||||
checkWebhookReadiness,
|
checkWebhookReadiness,
|
||||||
exportApprovalRunsToResourcePack,
|
exportApprovalRunsToResourcePack,
|
||||||
@@ -148,6 +149,42 @@ export async function handleWebhookCommand(
|
|||||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||||
|
|
||||||
|
const channel =
|
||||||
|
stringOption(args.options.channel) ??
|
||||||
|
(booleanOption(args.options["hose-outbound"]) || booleanOption(args.options.outbound) ? "hose-outbound" : undefined);
|
||||||
|
|
||||||
|
if (channel === "hose-outbound" || channel === "outbound") {
|
||||||
|
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
|
||||||
|
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
|
||||||
|
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
|
||||||
|
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
|
||||||
|
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
|
||||||
|
const targetSignKey =
|
||||||
|
stringOption(args.options.signKey) ??
|
||||||
|
stringOption(args.options["sign-key"]) ??
|
||||||
|
stringOption(args.options.webhook);
|
||||||
|
|
||||||
|
const result = await executeHoseOutboundReplay({
|
||||||
|
sourceCorp,
|
||||||
|
targetCorp,
|
||||||
|
sourceClient,
|
||||||
|
targetClient,
|
||||||
|
sn,
|
||||||
|
recordId,
|
||||||
|
flowId,
|
||||||
|
messageId,
|
||||||
|
nodeId,
|
||||||
|
corporationId,
|
||||||
|
rejectionNum,
|
||||||
|
targetSignKey,
|
||||||
|
dryRun,
|
||||||
|
force
|
||||||
|
});
|
||||||
|
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const query: ReplayRecordsQuery = {
|
const query: ReplayRecordsQuery = {
|
||||||
recordId,
|
recordId,
|
||||||
recordIds,
|
recordIds,
|
||||||
|
|||||||
+25
-7
@@ -584,11 +584,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
usage: [
|
usage: [
|
||||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
||||||
|
"seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--target-corp <corpId>] [--dry-run]",
|
||||||
|
"seal-use approval-runs replay <recordId> --channel hose-outbound [--target-corp <corpId>] [--dry-run]",
|
||||||
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
|
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
|
||||||
],
|
],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||||
|
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
|
||||||
|
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
|
||||||
|
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
|
||||||
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
||||||
{ flag: "--status <status>", description: "Filter records by status" },
|
{ flag: "--status <status>", description: "Filter records by status" },
|
||||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
||||||
@@ -654,9 +659,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "create",
|
name: "create",
|
||||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window)",
|
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
|
||||||
usage: [
|
usage: [
|
||||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
||||||
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
||||||
]
|
]
|
||||||
@@ -747,6 +752,14 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
name: "hosecloud sync",
|
name: "hosecloud sync",
|
||||||
summary: "Synchronize HoseCloud rules and definitions",
|
summary: "Synchronize HoseCloud rules and definitions",
|
||||||
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
|
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hosecloud test-outbound",
|
||||||
|
summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)",
|
||||||
|
usage: [
|
||||||
|
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--corp <corpId>]",
|
||||||
|
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--corp <corpId>]"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -835,11 +848,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
name: "link",
|
name: "link",
|
||||||
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
||||||
usage: [
|
usage: [
|
||||||
"seal-use auth link [--note <note>] [--corp <corpId>]",
|
"seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]",
|
||||||
"seal-use auth link --from-link <url> [--note <note>]"
|
"seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]"
|
||||||
],
|
],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
|
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
|
||||||
|
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" },
|
||||||
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
|
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
|
||||||
],
|
],
|
||||||
description:
|
description:
|
||||||
@@ -859,9 +873,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{
|
{
|
||||||
name: "hose-link",
|
name: "hose-link",
|
||||||
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
|
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
|
||||||
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
|
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]"],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
|
{ flag: "--expire, --expires-in <duration>", description: "链接有效时间,推荐 '7d' 或 '2h'(默认 2h,兼容秒数如 7200)" },
|
||||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||||
],
|
],
|
||||||
description:
|
description:
|
||||||
@@ -912,7 +926,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{
|
{
|
||||||
name: "delegation",
|
name: "delegation",
|
||||||
summary: "Create delegation token for a specific user",
|
summary: "Create delegation token for a specific user",
|
||||||
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]"]
|
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
|
||||||
|
options: [
|
||||||
|
{ flag: "--note <note>", description: "委托授权备注说明" },
|
||||||
|
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "reset-password",
|
name: "reset-password",
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
KNOWN_FLAGS,
|
KNOWN_FLAGS,
|
||||||
numberOption,
|
numberOption,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
|
parseDelegationExpireHours,
|
||||||
|
parseHoseExpireSeconds,
|
||||||
splitOption,
|
splitOption,
|
||||||
stringOption,
|
stringOption,
|
||||||
VALUE_FLAGS
|
VALUE_FLAGS
|
||||||
@@ -116,6 +118,45 @@ describe("option helpers", () => {
|
|||||||
expect(splitOption("")).toBeUndefined();
|
expect(splitOption("")).toBeUndefined();
|
||||||
expect(splitOption(true)).toBeUndefined();
|
expect(splitOption(true)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("parseDelegationExpireHours parses days, hours, rounds down with stderr notice, and clamps to 1..168", () => {
|
||||||
|
expect(parseDelegationExpireHours(undefined)).toBe(24);
|
||||||
|
expect(parseDelegationExpireHours("7d")).toBe(168);
|
||||||
|
expect(parseDelegationExpireHours("1d")).toBe(24);
|
||||||
|
expect(parseDelegationExpireHours("24h")).toBe(24);
|
||||||
|
expect(parseDelegationExpireHours("2h")).toBe(2);
|
||||||
|
expect(parseDelegationExpireHours("168")).toBe(168);
|
||||||
|
expect(parseDelegationExpireHours(168)).toBe(168);
|
||||||
|
expect(parseDelegationExpireHours("86400")).toBe(24);
|
||||||
|
expect(parseDelegationExpireHours("7200s")).toBe(2);
|
||||||
|
|
||||||
|
// Floor fractional hours and clamp minimum to 1h
|
||||||
|
expect(parseDelegationExpireHours("90m")).toBe(1);
|
||||||
|
expect(parseDelegationExpireHours("1.5h")).toBe(1);
|
||||||
|
expect(parseDelegationExpireHours("30m")).toBe(1);
|
||||||
|
expect(parseDelegationExpireHours("1800s")).toBe(1);
|
||||||
|
|
||||||
|
expect(() => parseDelegationExpireHours("8d")).toThrow("最多为 7 天 (168h)");
|
||||||
|
expect(() => parseDelegationExpireHours("0h")).toThrow("必须为大于 0 的有效时长");
|
||||||
|
expect(() => parseDelegationExpireHours("invalid")).toThrow("必须为有效时长格式");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("parseHoseExpireSeconds parses days, hours, minutes, raw seconds, and converts unitless small numbers to hours", () => {
|
||||||
|
expect(parseHoseExpireSeconds(undefined)).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds("7200")).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds(7200)).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds("2h")).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds("7d")).toBe(604800);
|
||||||
|
expect(parseHoseExpireSeconds("30m")).toBe(1800);
|
||||||
|
|
||||||
|
// Unitless small numbers (<= 168) convert to hours automatically
|
||||||
|
expect(parseHoseExpireSeconds(2)).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds("2")).toBe(7200);
|
||||||
|
expect(parseHoseExpireSeconds("24")).toBe(86400);
|
||||||
|
|
||||||
|
expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长");
|
||||||
|
expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("flag registry cross-check", () => {
|
describe("flag registry cross-check", () => {
|
||||||
|
|||||||
+180
-25
@@ -26,14 +26,14 @@ export const BOOLEAN_FLAGS = new Set([
|
|||||||
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
||||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||||
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
||||||
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
|
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||||
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
|
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||||
"workspace", "yes"
|
"workspace", "yes"
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -41,27 +41,27 @@ export const BOOLEAN_FLAGS = new Set([
|
|||||||
export const VALUE_FLAGS = new Set([
|
export const VALUE_FLAGS = new Set([
|
||||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||||
"code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
"channel", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date",
|
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
|
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
|
||||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||||
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||||
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
|
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
|
||||||
"from-link", "host", "humanResult", "id", "input", "integration",
|
"from-link", "host", "humanResult", "id", "input", "integration",
|
||||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||||
"max-runs",
|
"max-runs",
|
||||||
"month",
|
"month",
|
||||||
"n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out",
|
"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",
|
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
|
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
||||||
"reviewed-by", "reviewedBy",
|
"reviewed-by", "reviewedBy",
|
||||||
"report-id",
|
"report-id",
|
||||||
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
||||||
@@ -88,35 +88,35 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"V", "access-token", "accessToken", "add", "all", "app-key",
|
"V", "access-token", "accessToken", "add", "all", "app-key",
|
||||||
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
||||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||||
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
|
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only",
|
||||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
||||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||||
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
|
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||||
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
||||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
||||||
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
||||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||||
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
|
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
|
||||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
|
||||||
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
|
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
|
||||||
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||||
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||||
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||||
"max-runs",
|
"max-runs",
|
||||||
"month",
|
"month",
|
||||||
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait",
|
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
|
||||||
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir",
|
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
|
||||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo",
|
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
|
||||||
"report-id",
|
"report-id",
|
||||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||||
"reviewed-by", "reviewedBy",
|
"reviewed-by", "reviewedBy",
|
||||||
@@ -124,7 +124,7 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||||
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
||||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
|
||||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||||
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
||||||
@@ -137,7 +137,7 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||||
"until", "url", "userId", "v", "version", "version-name",
|
"until", "url", "userId", "v", "version", "version-name",
|
||||||
"verdict",
|
"verdict",
|
||||||
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||||
"workspace", "yes"
|
"workspace", "yes"
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -436,3 +436,158 @@ export function materialPackFilePolicyOptions(
|
|||||||
allowedExtensions
|
allowedExtensions
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function parseDelegationExpireHours(
|
||||||
|
value: string | boolean | number | undefined,
|
||||||
|
defaultHours = 24
|
||||||
|
): number {
|
||||||
|
if (value === undefined || value === null || value === "") {
|
||||||
|
return defaultHours;
|
||||||
|
}
|
||||||
|
let rawHours: number;
|
||||||
|
let isFractionalOrTruncated = false;
|
||||||
|
|
||||||
|
if (typeof value === "number") {
|
||||||
|
if (!Number.isFinite(value) || value <= 0) {
|
||||||
|
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
|
||||||
|
}
|
||||||
|
if (value > 168) {
|
||||||
|
rawHours = value / 3600;
|
||||||
|
if (value % 3600 !== 0) isFractionalOrTruncated = true;
|
||||||
|
} else {
|
||||||
|
rawHours = value;
|
||||||
|
if (!Number.isInteger(value)) isFractionalOrTruncated = true;
|
||||||
|
}
|
||||||
|
} else if (typeof value === "string") {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
const match = trimmed.match(
|
||||||
|
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
|
||||||
|
);
|
||||||
|
if (!match || !match[1]) {
|
||||||
|
throw usageError(
|
||||||
|
`Invalid --expire: '${value}'。必须为有效时长格式,推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const val = parseFloat(match[1]);
|
||||||
|
if (!Number.isFinite(val) || val <= 0) {
|
||||||
|
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
|
||||||
|
}
|
||||||
|
const unit = (match[2] ?? "").toLowerCase();
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
if (val > 168) {
|
||||||
|
rawHours = val / 3600;
|
||||||
|
if (val % 3600 !== 0) isFractionalOrTruncated = true;
|
||||||
|
} else {
|
||||||
|
rawHours = val;
|
||||||
|
if (!Number.isInteger(val)) isFractionalOrTruncated = true;
|
||||||
|
}
|
||||||
|
} else if (unit.startsWith("d")) {
|
||||||
|
rawHours = val * 24;
|
||||||
|
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
|
||||||
|
} else if (unit.startsWith("h")) {
|
||||||
|
rawHours = val;
|
||||||
|
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
|
||||||
|
} else if (unit.startsWith("m")) {
|
||||||
|
rawHours = val / 60;
|
||||||
|
if (val % 60 !== 0) isFractionalOrTruncated = true;
|
||||||
|
} else if (unit.startsWith("s")) {
|
||||||
|
rawHours = val / 3600;
|
||||||
|
if (val % 3600 !== 0) isFractionalOrTruncated = true;
|
||||||
|
} else {
|
||||||
|
rawHours = val;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw usageError(`Invalid --expire: ${String(value)}。`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawHours > 168) {
|
||||||
|
throw usageError(
|
||||||
|
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalHours = Math.floor(rawHours);
|
||||||
|
|
||||||
|
if (finalHours < 1) {
|
||||||
|
finalHours = 1;
|
||||||
|
console.error(
|
||||||
|
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
|
||||||
|
);
|
||||||
|
return finalHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFractionalOrTruncated) {
|
||||||
|
console.error(
|
||||||
|
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return finalHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseHoseExpireSeconds(
|
||||||
|
value: string | boolean | number | undefined,
|
||||||
|
defaultSeconds = 7200
|
||||||
|
): number {
|
||||||
|
if (value === undefined || value === null || value === "") {
|
||||||
|
return defaultSeconds;
|
||||||
|
}
|
||||||
|
let seconds: number;
|
||||||
|
if (typeof value === "number") {
|
||||||
|
if (!Number.isFinite(value) || value <= 0) {
|
||||||
|
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长。`);
|
||||||
|
}
|
||||||
|
if (value <= 168) {
|
||||||
|
seconds = Math.round(value * 3600);
|
||||||
|
console.error(
|
||||||
|
`👉 提示: 检测到未加单位的数值 ${value},已按 ${value} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${value}h。`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
seconds = Math.round(value);
|
||||||
|
}
|
||||||
|
} else if (typeof value === "string") {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
const match = trimmed.match(
|
||||||
|
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
|
||||||
|
);
|
||||||
|
if (!match || !match[1]) {
|
||||||
|
throw usageError(
|
||||||
|
`Invalid --expire: '${value}'。必须为有效时长,推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const val = parseFloat(match[1]);
|
||||||
|
if (!Number.isFinite(val) || val <= 0) {
|
||||||
|
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长。`);
|
||||||
|
}
|
||||||
|
const unit = (match[2] ?? "").toLowerCase();
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
if (val <= 168) {
|
||||||
|
seconds = Math.round(val * 3600);
|
||||||
|
console.error(
|
||||||
|
`👉 提示: 检测到未加单位的数值 ${value},已按 ${val} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${val}h。`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
seconds = Math.round(val);
|
||||||
|
}
|
||||||
|
} else if (unit.startsWith("d")) {
|
||||||
|
seconds = Math.round(val * 86400);
|
||||||
|
} else if (unit.startsWith("h")) {
|
||||||
|
seconds = Math.round(val * 3600);
|
||||||
|
} else if (unit.startsWith("m")) {
|
||||||
|
seconds = Math.round(val * 60);
|
||||||
|
} else if (unit.startsWith("s")) {
|
||||||
|
seconds = Math.round(val);
|
||||||
|
} else {
|
||||||
|
seconds = Math.round(val);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw usageError(`Invalid --expire: ${String(value)}。`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seconds <= 0) {
|
||||||
|
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
|
||||||
|
}
|
||||||
|
return seconds;
|
||||||
|
}
|
||||||
@@ -60,6 +60,13 @@ export class LangfuseClient {
|
|||||||
if (response.status === 401 || response.status === 403) {
|
if (response.status === 401 || response.status === 403) {
|
||||||
throw new CliError(detail, 11, "检查注入的 Langfuse 密钥是否仍然有效");
|
throw new CliError(detail, 11, "检查注入的 Langfuse 密钥是否仍然有效");
|
||||||
}
|
}
|
||||||
|
if (response.status === 404) {
|
||||||
|
const isProjectMismatch = body.includes("authorized project") || body.includes("not found");
|
||||||
|
const suggestion = isProjectMismatch
|
||||||
|
? "当前使用内置生产 Langfuse 凭据。若单据来自测试或 Staging 环境(如 staging.sealai.cc),其 Trace 属于 Staging 项目,无法通过内置生产凭据查询。可设置 LANGFUSE_BASE_URL、LANGFUSE_PUBLIC_KEY、LANGFUSE_SECRET_KEY 环境变量临时覆盖凭据。"
|
||||||
|
: "确认 Trace ID / Session ID 是否正确,或已过生命周期保留期";
|
||||||
|
throw new CliError(detail, 1, suggestion);
|
||||||
|
}
|
||||||
throw new CliError(detail, 1);
|
throw new CliError(detail, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-4
@@ -842,6 +842,24 @@ export async function syncHosecloudOutbound(
|
|||||||
return json.data ?? json;
|
return json.data ?? json;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function postHosecloudOutbound(
|
||||||
|
client: KyInstance,
|
||||||
|
signKey: string,
|
||||||
|
payload: {
|
||||||
|
flowId: string;
|
||||||
|
nodeId: string;
|
||||||
|
messageId: string;
|
||||||
|
rejectionNum: number;
|
||||||
|
corporationId: string;
|
||||||
|
}
|
||||||
|
): Promise<{ success?: boolean; message?: string; [key: string]: unknown }> {
|
||||||
|
const response = await client.post(`api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`, {
|
||||||
|
json: payload
|
||||||
|
});
|
||||||
|
const json = (await response.json().catch(() => ({}))) as { data?: unknown };
|
||||||
|
return (json.data ?? json) as { success?: boolean; message?: string; [key: string]: unknown };
|
||||||
|
}
|
||||||
|
|
||||||
export async function uploadMaterialPackage(
|
export async function uploadMaterialPackage(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
params: { fileName: string; fileBuffer: Uint8Array }
|
params: { fileName: string; fileBuffer: Uint8Array }
|
||||||
@@ -882,7 +900,7 @@ export async function listDelegations(client: KyInstance): Promise<SealDelegatio
|
|||||||
|
|
||||||
export async function createDelegation(
|
export async function createDelegation(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
params?: { note?: string }
|
params?: { note?: string; expiresInHours?: number }
|
||||||
): Promise<SealDelegationCreateResult> {
|
): Promise<SealDelegationCreateResult> {
|
||||||
return unwrap(
|
return unwrap(
|
||||||
await client.post("api/v1/delegation/create", { json: params ?? {} }),
|
await client.post("api/v1/delegation/create", { json: params ?? {} }),
|
||||||
@@ -1162,7 +1180,7 @@ export async function loginWithPhonePassword(
|
|||||||
|
|
||||||
export async function createDelegationForUser(
|
export async function createDelegationForUser(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
params: { userIdOrPhone: string; note?: string },
|
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
|
||||||
createClientForToken: (token: string) => Promise<KyInstance>,
|
createClientForToken: (token: string) => Promise<KyInstance>,
|
||||||
corp?: CorpConfig
|
corp?: CorpConfig
|
||||||
): Promise<{
|
): Promise<{
|
||||||
@@ -1249,7 +1267,8 @@ export async function createDelegationForUser(
|
|||||||
if (targetUserSealToken) {
|
if (targetUserSealToken) {
|
||||||
const userClient = await createClientForToken(targetUserSealToken);
|
const userClient = await createClientForToken(targetUserSealToken);
|
||||||
const delegation = await createDelegation(userClient, {
|
const delegation = await createDelegation(userClient, {
|
||||||
note: params.note ?? `Delegation generated by admin for ${user.name}`
|
note: params.note ?? `Delegation generated by admin for ${user.name}`,
|
||||||
|
expiresInHours: params.expiresInHours
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1287,7 +1306,8 @@ export async function createDelegationForUser(
|
|||||||
|
|
||||||
const userClient = await createClientForToken(token);
|
const userClient = await createClientForToken(token);
|
||||||
const delegation = await createDelegation(userClient, {
|
const delegation = await createDelegation(userClient, {
|
||||||
note: params.note ?? `Delegation generated by admin for ${user.name}`
|
note: params.note ?? `Delegation generated by admin for ${user.name}`,
|
||||||
|
expiresInHours: params.expiresInHours
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -735,6 +735,53 @@ describe("sealCapabilities", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("approval run cited rules attaches mappedProdCode when test snapshot exists", async () => {
|
||||||
|
const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-cited-"));
|
||||||
|
process.env.SEAL_USE_MAPPINGS_DIR = mappingDir;
|
||||||
|
try {
|
||||||
|
saveRuleMappingSnapshot({
|
||||||
|
syncedAt: "2026-10-10T10:00:00+08:00",
|
||||||
|
source: { id: "corp-prod", name: "Prod Corp" },
|
||||||
|
target: { id: "corp-test", name: "Test Corp", publishedVersionNumber: 16, rulesCount: 1 },
|
||||||
|
versionMapping: {
|
||||||
|
sourceProdVersionNumber: 22,
|
||||||
|
sourceProdVersionName: "Prod v22",
|
||||||
|
targetTestVersionNumber: 16,
|
||||||
|
targetTestVersionName: "Test v16"
|
||||||
|
},
|
||||||
|
ruleMapping: [{
|
||||||
|
index: 0,
|
||||||
|
sourceRuleId: "prod-rule-17",
|
||||||
|
sourceRuleCode: 17,
|
||||||
|
targetRuleId: "test-rule-38",
|
||||||
|
targetRuleCode: "0038",
|
||||||
|
description: "Prod rule 17",
|
||||||
|
scope: "travel",
|
||||||
|
strictness: "MUST_FOLLOW"
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
||||||
|
expect(tool).toBeDefined();
|
||||||
|
|
||||||
|
const handler = tool!.handler as CapabilityHandler;
|
||||||
|
const context = { corp: { ...fakeContext().corp, id: "corp-test", environment: "test" as const } };
|
||||||
|
const result = await handler(
|
||||||
|
fakeApprovalRunsClient(),
|
||||||
|
{ recordId: "run-1" },
|
||||||
|
context
|
||||||
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
||||||
|
|
||||||
|
expect(result.rules[0]).toMatchObject({
|
||||||
|
code: "0038",
|
||||||
|
mappedProdCode: "0017",
|
||||||
|
mappedProdRuleId: "prod-rule-17"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("approval run document summary returns key fields without raw payload", async () => {
|
test("approval run document summary returns key fields without raw payload", async () => {
|
||||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDocumentSummaryGet");
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDocumentSummaryGet");
|
||||||
expect(tool).toBeDefined();
|
expect(tool).toBeDefined();
|
||||||
|
|||||||
@@ -377,10 +377,11 @@ export const approvalRunsCapabilities = [
|
|||||||
}),
|
}),
|
||||||
handler: async (
|
handler: async (
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
params: { recordId: string }
|
params: { recordId: string },
|
||||||
|
context: CapabilityContext
|
||||||
) => {
|
) => {
|
||||||
const record = await api.getApprovalRun(client, params.recordId);
|
const record = await api.getApprovalRun(client, params.recordId);
|
||||||
return extractCitedRules(record);
|
return extractCitedRules(record, context.corp);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -654,7 +655,7 @@ export const approvalRunsCapabilities = [
|
|||||||
|
|
||||||
const documentSummary = summarizeApprovalRunDocument(detail);
|
const documentSummary = summarizeApprovalRunDocument(detail);
|
||||||
const resultSummary = summarizeApprovalRunResult(detail);
|
const resultSummary = summarizeApprovalRunResult(detail);
|
||||||
const citedRules = extractCitedRules(detail);
|
const citedRules = extractCitedRules(detail, context.corp);
|
||||||
|
|
||||||
let ruleVersion: {
|
let ruleVersion: {
|
||||||
version: ReturnType<typeof summarizeRuleVersion>;
|
version: ReturnType<typeof summarizeRuleVersion>;
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ import type { KyInstance } from "ky";
|
|||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import { probeHoseDomain } from "../../../core/auth/hose.js";
|
import { probeHoseDomain } from "../../../core/auth/hose.js";
|
||||||
|
import { safetyBlocked, validationError } from "../../../core/errors.js";
|
||||||
import {
|
import {
|
||||||
|
type ApprovalRun,
|
||||||
type HosecloudConfigInput
|
type HosecloudConfigInput
|
||||||
} from "../types.js";
|
} from "../types.js";
|
||||||
import type {
|
import type {
|
||||||
@@ -217,5 +219,184 @@ export const deployCapabilities = [
|
|||||||
result
|
result
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sealDeployHosecloudTestOutbound",
|
||||||
|
description: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发,强制要求目标集成必须为 assisted 模式",
|
||||||
|
parameters: z.object({
|
||||||
|
signKey: z.string().optional().describe("合思集成 sign-key(若企业仅有一个合思配置可自动识别)"),
|
||||||
|
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
|
||||||
|
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
|
||||||
|
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
|
||||||
|
nodeId: z.string().optional().default("FLOW:测试模拟节点_禁止流转").describe("合思流程节点 ID(默认填入中文阻断标识)"),
|
||||||
|
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
|
||||||
|
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
|
||||||
|
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送")
|
||||||
|
}),
|
||||||
|
handler: async (
|
||||||
|
client: KyInstance,
|
||||||
|
params: {
|
||||||
|
signKey?: string;
|
||||||
|
flowId?: string;
|
||||||
|
sn?: string;
|
||||||
|
messageId: string;
|
||||||
|
nodeId?: string;
|
||||||
|
rejectionNum?: number;
|
||||||
|
corporationId?: string;
|
||||||
|
dryRun?: boolean;
|
||||||
|
},
|
||||||
|
context: CapabilityContext
|
||||||
|
) => {
|
||||||
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
|
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||||
|
if (hoseConfigs.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
`当前企业 (${context.corp.name}) 尚未添加合思发布配置。\n` +
|
||||||
|
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${context.corp.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let integration: any;
|
||||||
|
if (params.signKey) {
|
||||||
|
integration = hoseConfigs.find((i: any) => i.signKey === params.signKey);
|
||||||
|
if (!integration) {
|
||||||
|
throw validationError(
|
||||||
|
`未找到 signKey 为「${params.signKey}」的合思集成配置。可用 signKey: ${hoseConfigs.map((i: any) => i.signKey).join(", ")}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (hoseConfigs.length === 1) {
|
||||||
|
integration = hoseConfigs[0];
|
||||||
|
} else {
|
||||||
|
const list = hoseConfigs.map((i: any) => `"${i.outboundName ?? "SealAI 审批"}" (signKey: ${i.signKey})`).join(", ");
|
||||||
|
throw validationError(
|
||||||
|
`当前企业存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
|
||||||
|
const mode = integration.mode ?? "assisted";
|
||||||
|
if (mode !== "assisted") {
|
||||||
|
throw safetyBlocked(
|
||||||
|
`安全阻断:目标合思配置「${integration.outboundName ?? integration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。为防止自动向合思回写审批动作影响生产/线上流程,严禁在此模式下测试出站通道。`,
|
||||||
|
`请先在目标企业将模式调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${context.corp.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 消息凭证校验
|
||||||
|
const messageId = params.messageId?.trim();
|
||||||
|
if (!messageId) {
|
||||||
|
throw validationError(
|
||||||
|
"缺少必需参数 --message-id。合思开放平台出站协议要求使用真实有效的 messageId 换取单据上下文,请从合思出站请求日志中提取提供。"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 解析 flowId
|
||||||
|
let flowId = params.flowId?.trim();
|
||||||
|
const sn = params.sn?.trim();
|
||||||
|
if (!flowId && sn) {
|
||||||
|
try {
|
||||||
|
const existing = await api.listApprovalRuns(client, {
|
||||||
|
search: sn,
|
||||||
|
sourceDocumentSN: sn,
|
||||||
|
limit: 5
|
||||||
|
});
|
||||||
|
const match = (existing.records || []).find(
|
||||||
|
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn
|
||||||
|
);
|
||||||
|
if (match?.sourceDocumentId) {
|
||||||
|
flowId = match.sourceDocumentId;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
if (!flowId && sn.startsWith("ID01")) {
|
||||||
|
flowId = sn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flowId) {
|
||||||
|
throw validationError(
|
||||||
|
"缺少必需参数 --flow-id(合思单据/流程 ID)。若已存在该单的历史运行记录,也可通过 --sn <单号> 自动解析。"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 解析 corporationId
|
||||||
|
const corporationId = params.corporationId?.trim() || integration.corporationId;
|
||||||
|
if (!corporationId) {
|
||||||
|
throw validationError(
|
||||||
|
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodeId = params.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
|
||||||
|
const rejectionNum = params.rejectionNum ?? 0;
|
||||||
|
|
||||||
|
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
||||||
|
const webhookUrl = `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(integration.signKey)}`;
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
flowId,
|
||||||
|
nodeId,
|
||||||
|
messageId,
|
||||||
|
rejectionNum,
|
||||||
|
corporationId
|
||||||
|
};
|
||||||
|
|
||||||
|
if (params.dryRun) {
|
||||||
|
return {
|
||||||
|
preview: true,
|
||||||
|
url: webhookUrl,
|
||||||
|
targetCorp: context.corp.id,
|
||||||
|
targetIntegration: {
|
||||||
|
signKey: integration.signKey,
|
||||||
|
outboundName: integration.outboundName,
|
||||||
|
mode: integration.mode
|
||||||
|
},
|
||||||
|
safetyCheck: {
|
||||||
|
mode: "assisted",
|
||||||
|
passed: true,
|
||||||
|
note: "目标企业出站模式为 assisted,AI 绝不会向合思回写审批动作;且默认 nodeId 包含中文阻断标记,双重安全保障。"
|
||||||
|
},
|
||||||
|
payload
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await api.postHosecloudOutbound(client, integration.signKey, payload);
|
||||||
|
|
||||||
|
// 等待后台队列消费 (2秒)
|
||||||
|
await new Promise((r) => setTimeout(r, 2000));
|
||||||
|
let createdRecord: ApprovalRun | undefined;
|
||||||
|
try {
|
||||||
|
const runs = await api.listApprovalRuns(client, {
|
||||||
|
limit: 5,
|
||||||
|
search: flowId
|
||||||
|
});
|
||||||
|
createdRecord = (runs.records || []).find(
|
||||||
|
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === flowId
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// 非阻塞
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`);
|
||||||
|
if (createdRecord) {
|
||||||
|
console.error(`✓ 异步消费成功!已在【${context.corp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
|
||||||
|
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${context.corp.id}`);
|
||||||
|
} else {
|
||||||
|
console.error(`ℹ️ 消息已入队正在异步消费,可在几秒后刷新后台页面或查询: seal-use approval-runs list --corp ${context.corp.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
targetCorp: context.corp.id,
|
||||||
|
signKey: integration.signKey,
|
||||||
|
mode: integration.mode,
|
||||||
|
payload,
|
||||||
|
response,
|
||||||
|
recordId: createdRecord?.id,
|
||||||
|
recordStatus: createdRecord?.status,
|
||||||
|
taskMode: createdRecord?.taskMode
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
@@ -635,10 +635,30 @@ export function summarizeApprovalRunResult(record: ApprovalRun) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function prioritizeKeyFields(fields: Array<Record<string, unknown>>, maxCount = 60) {
|
||||||
|
const priorityKeywords = ["金额", "费用", "报销", "申请", "借款", "付款", "部门", "事由", "收款", "公司", "抬头", "税", "类别", "项目", "说明", "币种"];
|
||||||
|
const prioritized: Array<Record<string, unknown>> = [];
|
||||||
|
const others: Array<Record<string, unknown>> = [];
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
const label = stringFromUnknown(field.label) ?? "";
|
||||||
|
const path = stringFromUnknown(field.path) ?? "";
|
||||||
|
const isPriority = priorityKeywords.some((k) => label.includes(k) || path.toLowerCase().includes(k.toLowerCase()));
|
||||||
|
if (isPriority) {
|
||||||
|
prioritized.push(field);
|
||||||
|
} else {
|
||||||
|
others.push(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...prioritized, ...others].slice(0, maxCount);
|
||||||
|
}
|
||||||
|
|
||||||
export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||||
const document = asRecord(record.document);
|
const document = asRecord(record.document);
|
||||||
const fields = flattenDocumentFields(record.document);
|
const fields = flattenDocumentFields(record.document);
|
||||||
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
|
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
|
||||||
|
const prioritizedFields = prioritizeKeyFields(fields, 60);
|
||||||
return {
|
return {
|
||||||
recordId: record.id,
|
recordId: record.id,
|
||||||
sourceDocumentSN: record.sourceDocumentSN,
|
sourceDocumentSN: record.sourceDocumentSN,
|
||||||
@@ -648,11 +668,44 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
|||||||
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
||||||
title: document?.title ?? document?.name,
|
title: document?.title ?? document?.name,
|
||||||
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
|
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
|
||||||
amount: firstByLabel(fields, ["金额", "报销金额", "付款金额", "合计", "价税合计"]) ?? firstPath(document, ["amount", "totalAmount", "expenseAmount"]),
|
amount:
|
||||||
expenseType: firstByLabel(fields, ["费用类型", "费用类别", "报销类型"]),
|
firstByLabel(fields, [
|
||||||
|
"金额",
|
||||||
|
"报销金额",
|
||||||
|
"付款金额",
|
||||||
|
"申请金额",
|
||||||
|
"借款金额",
|
||||||
|
"实报金额",
|
||||||
|
"总金额",
|
||||||
|
"费用金额",
|
||||||
|
"单据金额",
|
||||||
|
"合计",
|
||||||
|
"价税合计",
|
||||||
|
"明细合计",
|
||||||
|
"总计"
|
||||||
|
]) ??
|
||||||
|
firstPath(document, ["amount", "totalAmount", "expenseAmount", "applyAmount", "paymentAmount"]) ??
|
||||||
|
fields.find((f) => {
|
||||||
|
const path = stringFromUnknown(f.path)?.toLowerCase() ?? "";
|
||||||
|
return path.endsWith(".amount") || path.endsWith(".totalamount");
|
||||||
|
})?.value,
|
||||||
|
expenseType:
|
||||||
|
firstByLabel(fields, [
|
||||||
|
"费用类型",
|
||||||
|
"费用类别",
|
||||||
|
"报销类型",
|
||||||
|
"报销类别",
|
||||||
|
"支出类别",
|
||||||
|
"费用科目",
|
||||||
|
"单据类型",
|
||||||
|
"业务类型"
|
||||||
|
]) ??
|
||||||
|
firstPath(document, ["expenseType", "expenseCategory", "categoryName", "businessType"]),
|
||||||
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
|
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
|
||||||
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
|
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
|
||||||
keyFields: fields.slice(0, 30)
|
keyFields: prioritizedFields,
|
||||||
|
totalFieldsCount: fields.length,
|
||||||
|
fieldsTruncated: fields.length > prioritizedFields.length
|
||||||
}),
|
}),
|
||||||
invoices: collectInvoiceSummary(record),
|
invoices: collectInvoiceSummary(record),
|
||||||
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
|
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
|
||||||
@@ -665,7 +718,7 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function extractCitedRules(record: ApprovalRun) {
|
export function extractCitedRules(record: ApprovalRun, corp?: CorpConfig | string) {
|
||||||
const candidates: Array<[string, unknown]> = [
|
const candidates: Array<[string, unknown]> = [
|
||||||
["result.rulesResult", getPath(record, "result.rulesResult")],
|
["result.rulesResult", getPath(record, "result.rulesResult")],
|
||||||
["result.hitRules", getPath(record, "result.hitRules")],
|
["result.hitRules", getPath(record, "result.hitRules")],
|
||||||
@@ -740,6 +793,35 @@ export function extractCitedRules(record: ApprovalRun) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const corpId = typeof corp === "string" ? corp : corp?.id;
|
||||||
|
if (corpId) {
|
||||||
|
try {
|
||||||
|
const snapshot = loadRuleMappingSnapshot(corpId, record.ruleSetVersionNumber ?? "latest");
|
||||||
|
if (snapshot && snapshot.ruleMapping) {
|
||||||
|
for (const rule of rules) {
|
||||||
|
const ruleCode = stringFromUnknown(rule.code);
|
||||||
|
const runtimeRuleId = stringFromUnknown(rule.runtimeRuleId);
|
||||||
|
const codeNum = parseRuleCodeNumber(ruleCode ?? runtimeRuleId);
|
||||||
|
const matchedItem = snapshot.ruleMapping.find((m) => {
|
||||||
|
if (ruleCode && (String(m.targetRuleCode) === ruleCode || m.targetRuleCode === ruleCode)) return true;
|
||||||
|
if (runtimeRuleId && (m.targetRuleId === runtimeRuleId || `rule-${m.targetRuleCode}` === runtimeRuleId)) return true;
|
||||||
|
if (codeNum !== undefined) {
|
||||||
|
const targetNum = parseRuleCodeNumber(m.targetRuleCode);
|
||||||
|
if (targetNum !== undefined && targetNum === codeNum) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
if (matchedItem) {
|
||||||
|
const mappedCodeNum = parseRuleCodeNumber(matchedItem.sourceRuleCode);
|
||||||
|
rule.mappedProdCode = mappedCodeNum !== undefined ? formatRuleCode(mappedCodeNum) : String(matchedItem.sourceRuleCode);
|
||||||
|
rule.mappedProdRuleId = matchedItem.sourceRuleId;
|
||||||
|
rule.mappingNote = `测试规则 ${ruleCode ?? runtimeRuleId} 对应生产规则 ${rule.mappedProdCode}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
recordId: record.id,
|
recordId: record.id,
|
||||||
sourceDocumentSN: record.sourceDocumentSN,
|
sourceDocumentSN: record.sourceDocumentSN,
|
||||||
|
|||||||
@@ -29,10 +29,19 @@ export const identityCapabilities = [
|
|||||||
name: "sealDelegationCreate",
|
name: "sealDelegationCreate",
|
||||||
description: "创建新的 Seal 授权链接 (Delegation)",
|
description: "创建新的 Seal 授权链接 (Delegation)",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
note: z.string().optional().describe("授权链接的备注或说明信息")
|
note: z.string().optional().describe("授权链接的备注或说明信息"),
|
||||||
|
expiresInHours: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1)
|
||||||
|
.max(168)
|
||||||
|
.optional()
|
||||||
|
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
|
||||||
}),
|
}),
|
||||||
handler: async (client: KyInstance, params: { note?: string }) =>
|
handler: async (
|
||||||
api.createDelegation(client, params)
|
client: KyInstance,
|
||||||
|
params: { note?: string; expiresInHours?: number }
|
||||||
|
) => api.createDelegation(client, params)
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "sealDelegationRevoke",
|
name: "sealDelegationRevoke",
|
||||||
@@ -107,11 +116,18 @@ export const identityCapabilities = [
|
|||||||
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
|
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
|
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
|
||||||
note: z.string().optional().describe("授权链接备注信息")
|
note: z.string().optional().describe("授权链接备注信息"),
|
||||||
|
expiresInHours: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1)
|
||||||
|
.max(168)
|
||||||
|
.optional()
|
||||||
|
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
|
||||||
}),
|
}),
|
||||||
handler: async (
|
handler: async (
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
params: { userIdOrPhone: string; note?: string },
|
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
|
||||||
context: CapabilityContext
|
context: CapabilityContext
|
||||||
) =>
|
) =>
|
||||||
api.createDelegationForUser(
|
api.createDelegationForUser(
|
||||||
|
|||||||
@@ -135,6 +135,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
|
|||||||
"sealDelegationRevoke",
|
"sealDelegationRevoke",
|
||||||
"sealDeployHosecloudConfigure",
|
"sealDeployHosecloudConfigure",
|
||||||
"sealDeployHosecloudSync",
|
"sealDeployHosecloudSync",
|
||||||
|
"sealDeployHosecloudTestOutbound",
|
||||||
"sealInsightRecordAnalyze",
|
"sealInsightRecordAnalyze",
|
||||||
"sealPreferenceDecisionUpdate",
|
"sealPreferenceDecisionUpdate",
|
||||||
"sealPreferenceThinkingDepthPoliciesRemove",
|
"sealPreferenceThinkingDepthPoliciesRemove",
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ export const simulationCapabilities = [
|
|||||||
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
|
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
|
||||||
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
|
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
|
||||||
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
|
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
|
||||||
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
|
skipExpenseExtraction: z.boolean().optional().describe("跳过后台历史费用明细库提取(防重报检索用), 默认 true"),
|
||||||
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
|
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
|
||||||
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
|
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
|
||||||
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
|
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
|
||||||
@@ -317,8 +317,30 @@ export const simulationCapabilities = [
|
|||||||
console.error(
|
console.error(
|
||||||
`⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...`
|
`⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...`
|
||||||
);
|
);
|
||||||
|
let retryCount = 0;
|
||||||
while (true) {
|
while (true) {
|
||||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
let batch;
|
||||||
|
try {
|
||||||
|
batch = await api.getSimulationBatch(client, params.batchId);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const isInitialPhase = Date.now() - startedAt < 15000;
|
||||||
|
const statusStr = String(
|
||||||
|
(err && typeof err === "object" && "status" in err ? (err as { status: unknown }).status : "") ??
|
||||||
|
(err instanceof Error ? err.message : "")
|
||||||
|
);
|
||||||
|
const isNotFoundOrForbidden =
|
||||||
|
statusStr.includes("403") || statusStr.includes("404") || statusStr.toLowerCase().includes("not found");
|
||||||
|
if (isInitialPhase && isNotFoundOrForbidden && retryCount < 4) {
|
||||||
|
retryCount++;
|
||||||
|
console.error(
|
||||||
|
`⏳ [Simulation] 批次 ${params.batchId} 刚创建,等待服务端落库就绪 (重试 ${retryCount}/4)...`
|
||||||
|
);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
const status = (batch.status ?? "").toLowerCase();
|
const status = (batch.status ?? "").toLowerCase();
|
||||||
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
|
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
|
||||||
return {
|
return {
|
||||||
@@ -332,7 +354,22 @@ export const simulationCapabilities = [
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (Date.now() - startedAt >= timeoutMs) {
|
if (Date.now() - startedAt >= timeoutMs) {
|
||||||
throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`);
|
console.error(
|
||||||
|
`⏳ [Simulation] 批次 ${params.batchId} 等待超时(已等待 ${(Date.now() - startedAt) / 1000}s)。批次仍在服务端执行中。`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
batchId: params.batchId,
|
||||||
|
completed: false,
|
||||||
|
timedOut: true,
|
||||||
|
status: status || "running",
|
||||||
|
elapsedMs: Date.now() - startedAt,
|
||||||
|
message: `等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。任务仍在后台执行。`,
|
||||||
|
next: {
|
||||||
|
status: `seal-use simulation status ${params.batchId}`,
|
||||||
|
getRecords: `seal-use simulation batch-records ${params.batchId}`,
|
||||||
|
wait: `seal-use simulation wait ${params.batchId}`
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import {
|
||||||
|
selectMatchingOutboundLog,
|
||||||
|
validateHoseOutboundReplaySafety,
|
||||||
|
type HoseOutboundLogItem
|
||||||
|
} from "./hose-outbound-replay.js";
|
||||||
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
|
||||||
|
const mockLogs: HoseOutboundLogItem[] = [
|
||||||
|
{
|
||||||
|
id: "log-callback-3",
|
||||||
|
name: "全自动模式审批_财务部门",
|
||||||
|
type: "CALLBACK",
|
||||||
|
state: "SUCCESS",
|
||||||
|
createTime: 1789461868758,
|
||||||
|
request: {
|
||||||
|
action: "accept",
|
||||||
|
flowId: "ID01Wah1FQ9faf",
|
||||||
|
nodeId: "FLOW:355474724:884326991",
|
||||||
|
comment: "AI建议【通过】\n查看详情:https://test.sealai.cc/approval-result/01a0a43c-521b-778c-b11b-238c8496dfec"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "log-invoking-3",
|
||||||
|
name: "全自动模式审批_财务部门",
|
||||||
|
type: "INVOKING",
|
||||||
|
state: "SUCCESS",
|
||||||
|
createTime: 1789461809348,
|
||||||
|
nodeName: "财务部门",
|
||||||
|
request: {
|
||||||
|
flowId: "ID01Wah1FQ9faf",
|
||||||
|
nodeId: "FLOW:355474724:884326991",
|
||||||
|
messageId: "ID01Wh05v0In3F",
|
||||||
|
rejectionNum: 3,
|
||||||
|
corporationId: "ID01lwQSjf93Bl"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "log-callback-2",
|
||||||
|
name: "全自动报销审批. - 完成回调",
|
||||||
|
type: "CALLBACK",
|
||||||
|
state: "SUCCESS",
|
||||||
|
createTime: 1789112525311,
|
||||||
|
request: {
|
||||||
|
action: "refuse",
|
||||||
|
flowId: "ID01Wah1FQ9faf",
|
||||||
|
nodeId: "FLOW:215172549:1248083206",
|
||||||
|
comment: "AI建议【驳回】\n查看详情:https://test.sealai.cc/approval-result/01a08f69-ad6f-76b8-8c81-81190544150d"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "log-invoking-2",
|
||||||
|
name: "全自动报销审批.",
|
||||||
|
type: "INVOKING",
|
||||||
|
state: "SUCCESS",
|
||||||
|
createTime: 1789112460936,
|
||||||
|
nodeName: "财务部门",
|
||||||
|
request: {
|
||||||
|
flowId: "ID01Wah1FQ9faf",
|
||||||
|
nodeId: "FLOW:215172549:1248083206",
|
||||||
|
messageId: "ID01WahQ3gbhMP",
|
||||||
|
rejectionNum: 2,
|
||||||
|
corporationId: "ID01lwQSjf93Bl"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockSourceCorp: CorpConfig = {
|
||||||
|
id: "prod-corp",
|
||||||
|
name: "生产企业",
|
||||||
|
environment: "production",
|
||||||
|
seal: {
|
||||||
|
url: "https://prod.sealai.cc",
|
||||||
|
endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" }
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
type: "hose",
|
||||||
|
domain: "https://app.ekuaibao.com",
|
||||||
|
appKey: "key-123",
|
||||||
|
appSecurity: "sec-456",
|
||||||
|
staffId: "staff-1",
|
||||||
|
corpId: "corp-1"
|
||||||
|
},
|
||||||
|
auth: { refreshTtl: 300 },
|
||||||
|
testCorpId: "test-corp"
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockTargetCorp: CorpConfig = {
|
||||||
|
id: "test-corp",
|
||||||
|
name: "测试企业",
|
||||||
|
environment: "test",
|
||||||
|
seal: {
|
||||||
|
url: "https://test.sealai.cc",
|
||||||
|
endpoints: { approvalStylePreferences: "api/v1/system/preferences/approval-style" }
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
type: "seal",
|
||||||
|
token: "token-abc",
|
||||||
|
sealUrl: "https://test.sealai.cc",
|
||||||
|
expiresIn: 3600,
|
||||||
|
staffId: "seal"
|
||||||
|
},
|
||||||
|
auth: { refreshTtl: 300 },
|
||||||
|
prodCorpId: "prod-corp"
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("selectMatchingOutboundLog", () => {
|
||||||
|
test("defaults to the latest invoking log when no options given", () => {
|
||||||
|
const selected = selectMatchingOutboundLog(mockLogs);
|
||||||
|
expect(selected).toBeDefined();
|
||||||
|
expect(selected?.id).toBe("log-invoking-3");
|
||||||
|
expect(selected?.request?.messageId).toBe("ID01Wh05v0In3F");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches by explicit messageId", () => {
|
||||||
|
const selected = selectMatchingOutboundLog(mockLogs, { messageId: "ID01WahQ3gbhMP" });
|
||||||
|
expect(selected).toBeDefined();
|
||||||
|
expect(selected?.id).toBe("log-invoking-2");
|
||||||
|
expect(selected?.request?.rejectionNum).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches by recordId reverse lookup via CALLBACK comment", () => {
|
||||||
|
const selected = selectMatchingOutboundLog(mockLogs, {
|
||||||
|
recordId: "01a08f69-ad6f-76b8-8c81-81190544150d"
|
||||||
|
});
|
||||||
|
expect(selected).toBeDefined();
|
||||||
|
expect(selected?.id).toBe("log-invoking-2");
|
||||||
|
expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches by rejectionNum", () => {
|
||||||
|
const selected = selectMatchingOutboundLog(mockLogs, { rejectionNum: 2 });
|
||||||
|
expect(selected).toBeDefined();
|
||||||
|
expect(selected?.request?.messageId).toBe("ID01WahQ3gbhMP");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns undefined if no invoking logs exist", () => {
|
||||||
|
const emptyLogs: HoseOutboundLogItem[] = [
|
||||||
|
{ id: "1", name: "cb", type: "CALLBACK", state: "OK", createTime: 123 }
|
||||||
|
];
|
||||||
|
expect(selectMatchingOutboundLog(emptyLogs)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("validateHoseOutboundReplaySafety", () => {
|
||||||
|
test("passes when source and target are paired and target is assisted", () => {
|
||||||
|
expect(() =>
|
||||||
|
validateHoseOutboundReplaySafety(
|
||||||
|
mockSourceCorp,
|
||||||
|
mockTargetCorp,
|
||||||
|
{ mode: "assisted", outboundName: "测试通道", signKey: "key-1" }
|
||||||
|
)
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks when source and target are NOT paired", () => {
|
||||||
|
const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" };
|
||||||
|
const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" };
|
||||||
|
expect(() =>
|
||||||
|
validateHoseOutboundReplaySafety(
|
||||||
|
unpairedSource,
|
||||||
|
unpairedTarget,
|
||||||
|
{ mode: "assisted", signKey: "k" }
|
||||||
|
)
|
||||||
|
).toThrow(/未配置双向测试绑定关系/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks when target is production", () => {
|
||||||
|
const prodTarget = { ...mockTargetCorp, environment: "production" as const };
|
||||||
|
expect(() =>
|
||||||
|
validateHoseOutboundReplaySafety(
|
||||||
|
mockSourceCorp,
|
||||||
|
prodTarget,
|
||||||
|
{ mode: "assisted", signKey: "k" }
|
||||||
|
)
|
||||||
|
).toThrow(/标记为正式生产环境/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks when target mode is NOT assisted", () => {
|
||||||
|
expect(() =>
|
||||||
|
validateHoseOutboundReplaySafety(
|
||||||
|
mockSourceCorp,
|
||||||
|
mockTargetCorp,
|
||||||
|
{ mode: "fully_automatic", signKey: "k" }
|
||||||
|
)
|
||||||
|
).toThrow(/非 assisted(辅助审核)模式/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows force override for unpaired tenants", () => {
|
||||||
|
const unpairedTarget = { ...mockTargetCorp, prodCorpId: "other-prod" };
|
||||||
|
const unpairedSource = { ...mockSourceCorp, testCorpId: "other-test" };
|
||||||
|
expect(() =>
|
||||||
|
validateHoseOutboundReplaySafety(
|
||||||
|
unpairedSource,
|
||||||
|
unpairedTarget,
|
||||||
|
{ mode: "assisted", signKey: "k" },
|
||||||
|
true
|
||||||
|
)
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
import type { KyInstance } from "ky";
|
||||||
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
import { safetyBlocked, validationError } from "../../core/errors.js";
|
||||||
|
import { createHoseCloseClient } from "../hose/close/client.js";
|
||||||
|
import * as api from "./api.js";
|
||||||
|
import type { ApprovalRun } from "./types.js";
|
||||||
|
|
||||||
|
export interface HoseOutboundLogItem {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: "INVOKING" | "CALLBACK" | string;
|
||||||
|
state: string;
|
||||||
|
flowId?: {
|
||||||
|
id: string;
|
||||||
|
form?: {
|
||||||
|
code?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
nodeName?: string;
|
||||||
|
createTime: number;
|
||||||
|
messageType?: string;
|
||||||
|
request?: {
|
||||||
|
flowId?: string;
|
||||||
|
nodeId?: string;
|
||||||
|
messageId?: string;
|
||||||
|
rejectionNum?: number;
|
||||||
|
corporationId?: string;
|
||||||
|
action?: string;
|
||||||
|
comment?: string;
|
||||||
|
signKey?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
response?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HoseOutboundReplayOptions {
|
||||||
|
sourceCorp: CorpConfig;
|
||||||
|
targetCorp: CorpConfig;
|
||||||
|
sourceClient?: KyInstance;
|
||||||
|
targetClient: KyInstance;
|
||||||
|
sn?: string;
|
||||||
|
recordId?: string;
|
||||||
|
flowId?: string;
|
||||||
|
messageId?: string;
|
||||||
|
nodeId?: string;
|
||||||
|
corporationId?: string;
|
||||||
|
rejectionNum?: number;
|
||||||
|
targetSignKey?: string;
|
||||||
|
dryRun?: boolean;
|
||||||
|
force?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
|
||||||
|
*/
|
||||||
|
export async function fetchHoseOutboundLogs(
|
||||||
|
sourceCorp: CorpConfig,
|
||||||
|
sn: string
|
||||||
|
): Promise<HoseOutboundLogItem[]> {
|
||||||
|
if (sourceCorp.source.type !== "hose") {
|
||||||
|
throw validationError(
|
||||||
|
`源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = await createHoseCloseClient(sourceCorp);
|
||||||
|
const corpId = sourceCorp.source.corpId;
|
||||||
|
|
||||||
|
const response = (await client
|
||||||
|
.post("api/outbound/v1/message/messageLog", {
|
||||||
|
searchParams: {
|
||||||
|
messageType: "flow",
|
||||||
|
corpId
|
||||||
|
},
|
||||||
|
json: {
|
||||||
|
limit: { start: 0, count: 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}"))`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.json()) as { items?: HoseOutboundLogItem[] };
|
||||||
|
|
||||||
|
return response.items ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select the best matching INVOKING log from a list of outbound message logs.
|
||||||
|
*/
|
||||||
|
export function selectMatchingOutboundLog(
|
||||||
|
logs: HoseOutboundLogItem[],
|
||||||
|
options: {
|
||||||
|
messageId?: string;
|
||||||
|
recordId?: string;
|
||||||
|
recordCreatedAt?: number;
|
||||||
|
rejectionNum?: number;
|
||||||
|
} = {}
|
||||||
|
): HoseOutboundLogItem | undefined {
|
||||||
|
const invokingLogs = logs.filter((item) => item.type === "INVOKING");
|
||||||
|
if (invokingLogs.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Explicit messageId match
|
||||||
|
if (options.messageId) {
|
||||||
|
return invokingLogs.find((item) => item.request?.messageId === options.messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Exact recordId match via CALLBACK link/comment
|
||||||
|
if (options.recordId) {
|
||||||
|
const callbackWithRecordId = logs.find(
|
||||||
|
(item) =>
|
||||||
|
item.type === "CALLBACK" &&
|
||||||
|
typeof item.request?.comment === "string" &&
|
||||||
|
item.request.comment.includes(options.recordId!)
|
||||||
|
);
|
||||||
|
if (callbackWithRecordId) {
|
||||||
|
// Find the invoking event right before this callback
|
||||||
|
const priorInvoking = invokingLogs.find(
|
||||||
|
(item) => item.createTime <= callbackWithRecordId.createTime
|
||||||
|
);
|
||||||
|
if (priorInvoking) {
|
||||||
|
return priorInvoking;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: match by timestamp delta (< 60s)
|
||||||
|
if (options.recordCreatedAt) {
|
||||||
|
const closestByTime = invokingLogs
|
||||||
|
.filter((item) => item.createTime <= options.recordCreatedAt! + 1000)
|
||||||
|
.sort(
|
||||||
|
(a, b) =>
|
||||||
|
Math.abs(options.recordCreatedAt! - a.createTime) -
|
||||||
|
Math.abs(options.recordCreatedAt! - b.createTime)
|
||||||
|
)[0];
|
||||||
|
if (closestByTime) {
|
||||||
|
return closestByTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Match by rejectionNum if provided
|
||||||
|
if (options.rejectionNum !== undefined) {
|
||||||
|
const matchRejection = invokingLogs.find(
|
||||||
|
(item) => item.request?.rejectionNum === options.rejectionNum
|
||||||
|
);
|
||||||
|
if (matchRejection) {
|
||||||
|
return matchRejection;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Default: latest invoking log
|
||||||
|
return invokingLogs[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate security preconditions for Hose outbound replay.
|
||||||
|
*/
|
||||||
|
export function validateHoseOutboundReplaySafety(
|
||||||
|
sourceCorp: CorpConfig,
|
||||||
|
targetCorp: CorpConfig,
|
||||||
|
targetIntegration: { mode?: string; outboundName?: string; signKey?: string },
|
||||||
|
force = false
|
||||||
|
): void {
|
||||||
|
// 1. Double-binding guard: prevent accidental cross-tenant execution outside paired sandbox
|
||||||
|
const isPaired =
|
||||||
|
sourceCorp.testCorpId === targetCorp.id ||
|
||||||
|
targetCorp.prodCorpId === sourceCorp.id ||
|
||||||
|
sourceCorp.id === targetCorp.id;
|
||||||
|
|
||||||
|
if (!isPaired && !force) {
|
||||||
|
throw safetyBlocked(
|
||||||
|
`安全阻断:源企业「${sourceCorp.name}」(${sourceCorp.id}) 与目标企业「${targetCorp.name}」(${targetCorp.id}) 未配置双向测试绑定关系 (testCorpId / prodCorpId)。\n` +
|
||||||
|
`出站重放具备高仿真性,仅允许在绑定的生产-测试企业对之间执行。如确需跨租户测试,请添加 --force 参数。`,
|
||||||
|
`请检查企业配置 ~/.config/seal-use/enterprises/ 或添加 --force`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Production target guard
|
||||||
|
if (targetCorp.environment === "production" && !force) {
|
||||||
|
throw safetyBlocked(
|
||||||
|
`安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` +
|
||||||
|
`为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`,
|
||||||
|
`seal-use approval-runs replay --target-corp <testCorpId> ...`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Mode guard: target Hose integration MUST be assisted
|
||||||
|
const mode = targetIntegration.mode ?? "assisted";
|
||||||
|
if (mode !== "assisted") {
|
||||||
|
throw safetyBlocked(
|
||||||
|
`安全阻断:目标测试企业「${targetCorp.name}」的合思配置「${targetIntegration.outboundName ?? targetIntegration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` +
|
||||||
|
`为防止自动向合思回写审批动作影响流程,严禁在非 assisted 模式下重放出站单据。`,
|
||||||
|
`请先将目标企业的合思配置调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${targetIntegration.signKey}","mode":"assisted"}' --corp ${targetCorp.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main execution handler for Hose outbound replay.
|
||||||
|
*/
|
||||||
|
export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) {
|
||||||
|
const { sourceCorp, targetCorp, targetClient, dryRun, force } = options;
|
||||||
|
|
||||||
|
// 1. Get target corp's Hose integrations
|
||||||
|
const targetConfig = await api.getApprovalStylePreferences(
|
||||||
|
targetClient,
|
||||||
|
targetCorp.seal?.endpoints?.approvalStylePreferences
|
||||||
|
);
|
||||||
|
const hoseConfigs: Array<{
|
||||||
|
type: string;
|
||||||
|
signKey?: string;
|
||||||
|
outboundName?: string;
|
||||||
|
mode?: string;
|
||||||
|
corporationId?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}> = (targetConfig.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||||
|
if (hoseConfigs.length === 0) {
|
||||||
|
throw validationError(
|
||||||
|
`目标测试企业「${targetCorp.name}」未配置任何合思出站发布通道。请先运行:seal-use deploy hosecloud configure --corp ${targetCorp.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const foundIntegration = options.targetSignKey
|
||||||
|
? hoseConfigs.find((i) => i.signKey === options.targetSignKey)
|
||||||
|
: hoseConfigs[0];
|
||||||
|
|
||||||
|
if (!foundIntegration || !foundIntegration.signKey) {
|
||||||
|
if (options.targetSignKey) {
|
||||||
|
throw validationError(
|
||||||
|
`在目标企业中未找到 signKey 为「${options.targetSignKey}」的合思配置。可用配置: ${hoseConfigs.map((i) => i.signKey).filter(Boolean).join(", ")}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw validationError(
|
||||||
|
`目标测试企业「${targetCorp.name}」未配置有效的合思 signKey。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetIntegration = {
|
||||||
|
...foundIntegration,
|
||||||
|
signKey: foundIntegration.signKey
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Validate safety constraints
|
||||||
|
validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force);
|
||||||
|
|
||||||
|
// 3. Resolve document SN & record details
|
||||||
|
let sn = options.sn?.trim();
|
||||||
|
let sourceRecord: ApprovalRun | undefined;
|
||||||
|
|
||||||
|
if (options.recordId) {
|
||||||
|
if (options.sourceClient) {
|
||||||
|
try {
|
||||||
|
sourceRecord = await api.getApprovalRun(options.sourceClient, options.recordId);
|
||||||
|
if (sourceRecord?.sourceDocumentSN) {
|
||||||
|
sn = sourceRecord.sourceDocumentSN;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sn && !options.messageId) {
|
||||||
|
throw validationError(
|
||||||
|
"缺少必需参数:请提供单号 (--sn <SN>) 或运行记录 ID (<recordId>),以便自动从合思检索出站消息日志。"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Retrieve or match outbound log
|
||||||
|
let selectedLog: HoseOutboundLogItem | undefined;
|
||||||
|
if (!options.messageId && sn) {
|
||||||
|
console.error(`ℹ️ 正在通过合思 CloseAPI 检索单据「${sn}」的历史出站消息日志...`);
|
||||||
|
const logs = await fetchHoseOutboundLogs(sourceCorp, sn);
|
||||||
|
const recordCreatedAt =
|
||||||
|
typeof sourceRecord?.createdAt === "number"
|
||||||
|
? sourceRecord.createdAt
|
||||||
|
: typeof sourceRecord?.createdAt === "string"
|
||||||
|
? Date.parse(sourceRecord.createdAt)
|
||||||
|
: undefined;
|
||||||
|
selectedLog = selectMatchingOutboundLog(logs, {
|
||||||
|
recordId: options.recordId,
|
||||||
|
recordCreatedAt: Number.isNaN(recordCreatedAt) ? undefined : recordCreatedAt,
|
||||||
|
rejectionNum: options.rejectionNum
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!selectedLog || !selectedLog.request?.messageId) {
|
||||||
|
throw validationError(
|
||||||
|
`在合思出站日志中未找到单据「${sn}」的有效出站记录 (type: INVOKING)。\n` +
|
||||||
|
`请确认该单据在合思审批流中是否触发过出站消息(EBot节点),或显式提供 --message-id 参数。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Construct payload
|
||||||
|
const flowId =
|
||||||
|
options.flowId?.trim() ??
|
||||||
|
selectedLog?.request?.flowId ??
|
||||||
|
selectedLog?.flowId?.id ??
|
||||||
|
sourceRecord?.sourceDocumentId ??
|
||||||
|
(sn?.startsWith("ID01") ? sn : undefined);
|
||||||
|
|
||||||
|
if (!flowId) {
|
||||||
|
throw validationError(
|
||||||
|
`未能解析出单据「${sn}」的合思流程实例 ID (flowId)。请确认单据信息或显式提供 flowId。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId;
|
||||||
|
if (!messageId) {
|
||||||
|
throw validationError("未能获取到有效 messageId。");
|
||||||
|
}
|
||||||
|
|
||||||
|
const rejectionNum =
|
||||||
|
options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0;
|
||||||
|
|
||||||
|
const corporationId =
|
||||||
|
options.corporationId?.trim() ??
|
||||||
|
selectedLog?.request?.corporationId ??
|
||||||
|
(sourceCorp.source as any)?.corpId ??
|
||||||
|
targetIntegration.corporationId;
|
||||||
|
|
||||||
|
// Crucial: Chinese mock nodeId causes Hose to return HTTP 412 on callback, creating an indestructible safety gate
|
||||||
|
const nodeId = options.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
|
||||||
|
|
||||||
|
const targetSealUrl = (
|
||||||
|
targetCorp.seal.url ?? `https://${targetCorp.id.toLowerCase()}.sealai.cc`
|
||||||
|
).replace(/\/+$/, "");
|
||||||
|
const targetWebhookUrl = `${targetSealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(targetIntegration.signKey)}`;
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
flowId,
|
||||||
|
nodeId,
|
||||||
|
messageId,
|
||||||
|
rejectionNum,
|
||||||
|
corporationId
|
||||||
|
};
|
||||||
|
|
||||||
|
// 6. Dry run preview
|
||||||
|
if (dryRun) {
|
||||||
|
return {
|
||||||
|
preview: true,
|
||||||
|
channel: "hose-outbound",
|
||||||
|
sourceCorp: {
|
||||||
|
id: sourceCorp.id,
|
||||||
|
name: sourceCorp.name,
|
||||||
|
environment: sourceCorp.environment
|
||||||
|
},
|
||||||
|
targetCorp: {
|
||||||
|
id: targetCorp.id,
|
||||||
|
name: targetCorp.name,
|
||||||
|
environment: targetCorp.environment
|
||||||
|
},
|
||||||
|
targetIntegration: {
|
||||||
|
signKey: targetIntegration.signKey,
|
||||||
|
outboundName: targetIntegration.outboundName,
|
||||||
|
mode: targetIntegration.mode
|
||||||
|
},
|
||||||
|
matchedLog: selectedLog
|
||||||
|
? {
|
||||||
|
logId: selectedLog.id,
|
||||||
|
nodeName: selectedLog.nodeName,
|
||||||
|
createTime: selectedLog.createTime,
|
||||||
|
messageId: selectedLog.request?.messageId,
|
||||||
|
rejectionNum: selectedLog.request?.rejectionNum
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
safetyGuards: {
|
||||||
|
pairedBinding: true,
|
||||||
|
targetModeAssisted: true,
|
||||||
|
nodeId412Blocked: true
|
||||||
|
},
|
||||||
|
targetUrl: targetWebhookUrl,
|
||||||
|
payload
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. Live execution
|
||||||
|
const response = await api.postHosecloudOutbound(
|
||||||
|
targetClient,
|
||||||
|
targetIntegration.signKey,
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
|
||||||
|
console.error(`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${rejectionNum})`);
|
||||||
|
console.error(`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${nodeId})`);
|
||||||
|
|
||||||
|
// Wait 2.5s for worker queue consumption
|
||||||
|
await new Promise((r) => setTimeout(r, 2500));
|
||||||
|
let createdRecord: ApprovalRun | undefined;
|
||||||
|
try {
|
||||||
|
const runs = await api.listApprovalRuns(targetClient, {
|
||||||
|
limit: 5,
|
||||||
|
search: flowId
|
||||||
|
});
|
||||||
|
createdRecord = (runs.records || []).find(
|
||||||
|
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === sn
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// non-blocking
|
||||||
|
}
|
||||||
|
|
||||||
|
if (createdRecord) {
|
||||||
|
console.error(`✓ 异步消费成功!已在【${targetCorp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
|
||||||
|
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${targetCorp.id}`);
|
||||||
|
} else {
|
||||||
|
console.error(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
channel: "hose-outbound",
|
||||||
|
sourceCorp: {
|
||||||
|
id: sourceCorp.id,
|
||||||
|
name: sourceCorp.name
|
||||||
|
},
|
||||||
|
targetCorp: {
|
||||||
|
id: targetCorp.id,
|
||||||
|
name: targetCorp.name
|
||||||
|
},
|
||||||
|
targetSignKey: targetIntegration.signKey,
|
||||||
|
mode: targetIntegration.mode,
|
||||||
|
matchedMessageId: messageId,
|
||||||
|
rejectionNum,
|
||||||
|
payload,
|
||||||
|
response,
|
||||||
|
recordId: createdRecord?.id,
|
||||||
|
recordStatus: createdRecord?.status,
|
||||||
|
taskMode: createdRecord?.taskMode
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in new issue
Block a user