Compare commits

...
12 Commits
Author SHA1 Message Date
yunyingk e88f472b50 Merge pull request #287 from yunyingk/codex/release-v0.11.22
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
Release v0.11.22: Automated release bump
2026-11-17 11:17:58 +08:00
gitea 1ddf6db9e8 Release v0.11.22: Automated release bump 2026-11-17 11:16:46 +08:00
yunyingk 4b92d397df Merge pull request #286 from yunyingk/mac15/simulation-rule-source-maycur
feat(simulation): 支持单租户未发布草稿快照、已发布版本回溯与每刻报销接入
2026-11-17 11:15:43 +08:00
gitea d25c09c3be feat(simulation): 支持单租户未发布草稿快照、已发布版本回溯与每刻报销接入
- 模拟测试原生支持 ruleSource:默认保持以线上生效规则运行(无破坏性变更);显式传递 --draft 对未发布草稿拍摄不可变快照;传递 --rule-version <versionId> 回溯指定历史发布版本。
- 单租户原地即可闭环草稿模拟验证与多版本对比,彻底解耦对双企业组(corps sync-test 强制预发版)的硬依赖。
- 新增每刻报销(maycur / maycur-standard)来源系统支持,引入 --form-codes 单号批量测试并自动解析租户 signKey。
- 完善 simulation create 参数解析器、Zod 类型定义、Help 文档与 Skill 决策工作流规约。
2026-11-17 11:14:15 +08:00
yunyingk 03189c072d Merge pull request #285 from yunyingk/codex/release-v0.11.21
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
Release v0.11.21: Automated release bump
2026-11-13 12:42:13 +08:00
gitea 1a023f9996 Release v0.11.21: Automated release bump 2026-11-13 12:40:58 +08:00
yunyingk 0ddd8283fe Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
Refactor: 优化 Langfuse 检索与审批单诊断的 CLI 人体工程学体验
2026-11-13 12:40:01 +08:00
gitea b980c60c3a Improve CLI ergonomics for Langfuse search and approval run diagnosis 2026-11-13 12:35:59 +08:00
yunyingk 67cd168ed4 Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
fix(approval-runs): 不再把传输层失败当成业务结论
2026-11-10 19:49:37 +08:00
yunyingk 8bc1401eae Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
fix(cli): 停止在用户可见面上宣传已退役的 --flow 拼写
2026-11-10 19:49:28 +08:00
yunyingk c572cba842 fix(approval-runs): 传输层失败不再被误判为业务结论
`sealApprovalRunFlowGet` 用两次"请求被拒"充当路由信号:记录查询被拒,就
认为入参是单号;运行记录列表被拒,就认为该单据没有 AI 记录。两处都写成
裸 `catch {}`,于是所有失败都被吸收进这两个业务结论。

后果不是偶尔不准,而是以十足的语气给出错误答案:token 过期、连接重置、
网关 5xx 会被渲染成「单据已删除」或「AI 从未审核」,用户没有任何线索去
怀疑刚才那次请求其实失败了;退出码同时失去语义,本该由 classifyCliError
产出 11(认证/上游失败),实际退化成一次"成功的查询"。

现在只有标识符形态的拒绝才计为未命中:HTTP 400/404/422,或响应体确实
到达但不是一条审批记录。认证失败、5xx、限流、以及根本没有响应的传输
错误一律原样上抛。

- errors:导出既有的 `responseStatus` 结构读取器,让调用方能区分"没有
  响应"与"收到了 400/404 响应"。
- approval-runs:新增 `isUpstreamLookupMiss`,替换两处裸 catch。
- test:新增四个回归用例(401/403/503/连接失败),断言原始错误对象抵达
  调用方;另加一条非合思租户的守卫用例。
2026-11-10 19:47:48 +08:00
yunyingk 71845c35e7 fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
`approval-runs get --flow` 至今仍是 `approval-runs hose-flow` 的静默遗留
别名:解析器的布尔标志白名单里还留着它,命令实现里也仍在转发。但 CLI
协议第 6 节要求兼容拼写只能停留在实现层,不得出现在 help、Skill、
references、README 或正常运行时提示中。

问题在于这条规矩被自己的文档破了:`get --help` 中 `--raw-json` 的描述写着
"incompatible with --summary, --fields and --flow",references 里同一句话也
照抄了一遍。用户只要撞上一次参数冲突,就会被 CLI 主动教一遍退役拼写。

- help:`--raw-json` 描述去掉 `--flow`,改为指向规范命令
  `approval-runs hose-flow <recordId|SN>`。
- approval-run-lightweight.md:同步修正,并补上原生合思流程时间线的入口。
- 运行时:冲突报错改为只列调用方实际传入的标志,不再主动广播退役拼写。
- naming-charter:新增裸 `--flow` 的边界守卫。原有
  LEGACY_SURFACE_TOKENS 是子串匹配,无法表达这个概念(`--flow-id`、
  `--flow-ids`、`--flow-concurrency` 都是规范参数),这正是该泄漏存活
  八个版本的根因。
2026-11-10 19:47:43 +08:00
23 changed files with 474 additions and 108 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.20",
"version": "0.11.22",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+18
View File
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.22] - 2026-11-17
### Added
- Merge pull request #286 from yunyingk/mac15/simulation-rule-source-maycur
- feat(simulation): 支持单租户未发布草稿快照、已发布版本回溯与每刻报销接入
## [0.11.21] - 2026-11-13
### Added
- Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
- Improve CLI ergonomics for Langfuse search and approval run diagnosis
- Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
- Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
- fix(approval-runs): 传输层失败不再被误判为业务结论
- fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
## [0.11.20] - 2026-11-08
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.20",
"version": "0.11.22",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+7 -5
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.20: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.22: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.20
short-description: Seal tenant and Hose approval automation (v0.11.20)
version: 0.11.22
short-description: Seal tenant and Hose approval automation (v0.11.22)
---
# Seal Use
@@ -84,13 +84,15 @@ bun run dev:override # 编译本机二进制、打版本号并原子覆盖
2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。
3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。
## `corps` 主线
## `corps` 主线与规则演进
企业接入、发现、维护与测试配对的具体语法见 `seal-use help corps`;材料选择与操作流程按下方 reference 路由。
Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
规则变更与验证闭环:
- **单租户快照测试(首选,无需双企业组)**:`simulation create` 原生支持 `ruleSource`(默认以当前线上生效规则运行;加 `--draft` 显式对未发布草稿拍摄不可变快照;`--rule-version` 挂载指定历史版本),单个企业租户内执行 `seal-use simulation create --corp <corpId> --flow-ids <SN> --draft --wait` 即可原地完成草稿快照测试,不再需要双企业组与 `sync-test` 预发版造快照。
- **双租户物理隔离(可选)**:仅在需严格物理隔离外部审批流出站、跨租户出站仿真重放或执行全量自动化回归矩阵(`test regression` 阻断生产环境)时,才使用 `corps bind-test` 与 `corps sync-test`。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
## 规则编号重排:两次调用
@@ -76,7 +76,7 @@ seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- `--raw-json` 不能与 `--summary` 或 `--fields` 同用;这两个参数会改写返回结构,CLI 会以退出码 2 明确拒绝。需要合思原生审批流时间线时,用 `seal-use approval-runs hose-flow <recordId|SN>`,不要从审核详情接口取。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
## Understand The Case First
+3 -2
View File
@@ -136,8 +136,9 @@ seal-use report review dismiss [--hours <n>] [--corp <corpId>]
seal-use report review list [--corp <corpId>]
seal-use report review import <台账.xlsx|csv> --corp <corpId>
seal-use simulation batch-records <batchId> [--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 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] [--draft] [--rule-version <versionId>] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--draft] [--rule-version <versionId>] [--corp <corpId>]
seal-use simulation create --mode maycur --form-codes "MC001,MC002" [--draft] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
@@ -13,17 +13,46 @@
# 国内镜像源秒级自愈与升级
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
```
2. **测试先行,优先草稿隔离 (Staging-First Recommendation)**:
- 强烈建议生产环境的规则修改优先以草稿态(`draft`)保存,并通过 `seal-use corps sync-test` 自动同步到绑定的测试企业进行模拟验证。
- Agent 应主动向用户建议该安全演进闭环,但**绝不替用户做决定**。最终的操作权在用户手中;若用户明确指示直接在生产企业发布,Agent 必须尊重并遵照用户意图执行。
3. **合思集成安全隔离 (Hosecloud Zero-Impact Sync)**:
- 测试环境进行合思模拟测试,必须在测试企业中保存合思凭证。
- `corps sync-test` 会自动读取本地生产 source 凭证并为测试环境配置 `assisted`(辅助)模式的合思集成,名称格式为 `{企业名前缀}(Seal测)`。
2. **单租户原生快照测试(首选,不再强求双企业组)**:
- 过去平台模拟测试因无法指定规则版本,必须通过双企业组(生产 + 测试)与 `corps sync-test` 在测试企业预发版来固化快照。
- 现在 Seal 后端原生支持 `ruleSource`:创建模拟时默认以当前线上生效的正式规则运行;若要测试刚刚修改的未发布规则草稿,显式传递 `--draft` 即可自动对当前草稿拍摄不可变快照(`ruleSource: { type: "current" }`);亦可通过 `--rule-version <versionId>` 挂载指定历史发布版本。
- **单企业租户即可原生闭环草稿快照测试与多版本对比**,无需强行开通或绑定第二个测试企业。
3. **双企业租户物理隔离场景(保留边界)**:
- 双企业组(`corps bind-test` + `corps sync-test`)不再是为了“制造快照”,而是为了:
1. 物理隔离外部费控审批流出站(测试端合思集成设为 `assisted`,防止外部推送副作用);
2. 执行全自动大样本回归测试矩阵(`seal-use test regression` 硬阻断生产企业执行);
3. 跨租户 Webhook 与出站仿真重放。
- **严禁向合思执行同步 (`deploy hosecloud sync`)**:测试环境的合思配置只保存在 Seal 端,绝不向合思生产系统推送 EBot 节点或创建真实出站消息,保障生产费控审批流的绝对安全。
---
## 端到端标准演进闭环 (The 5-Stage Lifecycle)
## 端到端标准演进闭环 (Evolution Lifecycles)
### 路径 A:单企业租户原生快照演进闭环(优先首选)
```mermaid
flowchart TD
A["Stage 1: 规则草稿修改 (rules update)"] --> B["Stage 2: 单租户原生快照模拟 (simulation create --draft --wait)"]
B --> C{"快照模拟与版本比对是否通过?"}
C -- 存在偏差/翻转误伤 --> A
C -- 验证通过 --> D["Stage 3: 生产正式发布 (rules publish)"]
```
1. **修改草稿**:`seal-use rules update <code> --corp <corpId>`。
2. **原地快照模拟验证**:
```bash
# 显式使用 --draft 为当前未发布草稿拍摄不可变快照
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --draft --wait
# 或与线上当前生效规则基线、历史已发布版本回溯比对
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --wait
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --rule-version "<versionId>" --wait
```
3. **正式发布**:用户确认后执行 `seal-use rules publish "<变更说明>" --corp <corpId>`。
---
### 路径 B:双企业租户物理隔离演进闭环(特定场景选)
```mermaid
flowchart TD
@@ -163,12 +192,26 @@ flowchart TD
```
> **红线保障**:系统硬性规定回归测试严禁在生产环境发起;且前置计算点数余额,余额不足直接拒绝执行;基于出站 HTTPS 轮询,客户端无公网 IP 亦可稳定工作。
- **方式 B:合思原生模拟任务 (Simulation Create,单据与附件测试首选)**:
针对目标真实单据号(或客诉单据)在测试环境发起模拟。**强烈建议单据及附件审核优先采用本方式**,因为平台原生模拟通道会调用合思官方 OpenAPI 完整抓取单据正文与全部发票、合同等二进制附件,完整度最高;且支持 `--wait` 自动挂起轮询直至出结果:
- **方式 B:平台原生模拟任务 (Simulation Create,单据与附件测试首选)**:
针对目标真实单据号(或客诉单据)在测试环境发起模拟。**强烈建议单据及附件审核优先采用本方式**,因为平台原生模拟通道会调用上游官方 API 完整抓取单据正文与全部发票、合同等二进制附件,完整度最高;且支持 `--wait` 自动挂起轮询直至出结果:
```bash
# 异步创建后自动轮询等待结果(推荐)
# 异步创建后自动轮询等待结果(默认使用当前规则草稿快照)
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
# 指定已发布历史规则版本进行回溯比对(例如比对修复前后的版本差异)
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号>" --rule-version "<versionId>" --wait
# 深度推理与附件无缓存全量重跑(深度思考模式下生效)
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号>" --thinking-depth high --disable-attachment-cache --wait
# 每刻报销原生单据模拟测试
seal-use simulation create --corp <testCorpId> --mode maycur --form-codes "<单号1>,<单号2>" --wait
```
> **规则源与版本快照(`ruleSource`)**:
> - 默认或显式传 `--rule-source current` 时,系统自动为当前草稿拍摄规则快照(`type: "snapshot"`),界面与批次详情显示 `当前规则快照(未发布)· 拍摄时间`。
> - 指定 `--rule-version <versionId>` 时,锁定使用已发布的历史版本(`type: "published"`),用于精准评估特定版本的判定准确度。
> - 审核记录中同步包含 `ruleSetSnapshotCreatedAt` 与思考深度(`thinkingDepthLevel`)。
>
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
>
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
+3
View File
@@ -102,6 +102,9 @@ describe("approval run native JSON fallback", () => {
expect(result.exitCode).toBe(2)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("--raw-json cannot be combined")
// The message names only what the caller actually passed, so the retired
// `--flow` spelling is never advertised to anyone who did not use it.
expect(result.stderr).toContain(flags[0]!)
}
expect(requests).toHaveLength(0)
})
+13 -6
View File
@@ -187,11 +187,18 @@ export async function handleApprovalRunsCommand(
}
if (action === "get") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw new Error("Missing approval run recordId");
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
if (rawJson) {
// Name only the flags the caller actually passed: legacy spellings stay
// implementation-only and must not be advertised to everyone else.
const conflicts = [
booleanOption(args.options.flow) ? "--flow" : undefined,
booleanOption(args.options.summary) ? "--summary" : undefined,
stringOption(args.options.fields) !== undefined ? "--fields" : undefined
].filter((flag): flag is string => flag !== undefined);
if (conflicts.length) throw usageError(`--raw-json cannot be combined with ${conflicts.join(", ")}`);
}
if (booleanOption(args.options.flow)) {
await runCapability(
@@ -219,21 +226,21 @@ export async function handleApprovalRunsCommand(
}
if (action === "cited-rules") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "diagnose") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
+6 -1
View File
@@ -20,7 +20,12 @@ export async function handleLangfuseCommand(
const options = args.options;
const out = outputOptions(options);
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
const refreshIfMissing = () => {
if (booleanOption(options["no-refresh"]) || booleanOption(options.offline)) return false;
const explicit = booleanOption(options["refresh-if-missing"]);
if (explicit !== undefined) return explicit;
return true;
};
if (action === "check") {
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
+28
View File
@@ -87,6 +87,31 @@ export async function handleSimulationCommand(
);
}
const isDraft =
booleanOption(args.options.draft) ||
booleanOption(args.options.current) ||
booleanOption(args.options["current-rules"]) ||
booleanOption(args.options.currentRules) ||
stringOption(args.options.ruleSource) === "current" ||
stringOption(args.options["rule-source"]) === "current";
const ruleVersion =
stringOption(args.options.ruleVersion) ??
stringOption(args.options["rule-version"]) ??
stringOption(args.options["rule-version-id"]) ??
stringOption(args.options.ruleVersionId);
let ruleSource: { type: "current" } | { type: "published"; versionId: string } | undefined;
if (isDraft) {
ruleSource = { type: "current" };
} else if (ruleVersion) {
ruleSource = { type: "published", versionId: ruleVersion };
}
const formCodes =
splitOption(args.options.formCodes) ??
splitOption(args.options["form-codes"]);
const result = await runCapabilityResult(
"sealSimulationBatchCreate",
client,
@@ -96,11 +121,14 @@ export async function handleSimulationCommand(
sourceSystem: mode,
flowIds,
documentSn: flowIds,
formCodes,
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
skipExpenseExtraction,
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
ruleSource,
ruleVersion,
signKey,
packageIds,
packageId,
+5 -4
View File
@@ -578,7 +578,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Get detailed approval record payload",
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
options: [
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary and --fields. Native Hose flow timeline lives in `seal-use approval-runs hose-flow <recordId|SN>`" },
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
]
@@ -849,10 +849,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "create",
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction; defaults to latest published rules; pass --draft for unreleased draft snapshot)",
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-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 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] [--draft] [--rule-version <versionId>] [--corp <corpId>]",
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--draft] [--rule-version <versionId>] [--corp <corpId>]",
"seal-use simulation create --mode maycur --form-codes \"MC001,MC002\" [--draft] [--corp <corpId>]",
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
]
},
+10
View File
@@ -76,6 +76,16 @@ describe("naming charter: visible help surface", () => {
const offenders = LEGACY_SURFACE_TOKENS.filter((token) => serialized.includes(token));
expect(offenders).toEqual([]);
});
test("never documents the retired bare flow switch", () => {
// `--flow` on `approval-runs get` is a silent legacy alias for
// `approval-runs hose-flow`, so the visible surface must not name it.
// LEGACY_SURFACE_TOKENS matches by substring and cannot express this:
// `--flow-id`, `--flow-ids` and `--flow-concurrency` are canonical.
const serialized = JSON.stringify(HELP_REGISTRY);
const offenders = serialized.match(/--flow(?![A-Za-z0-9-])/g) ?? [];
expect(offenders).toEqual([]);
});
});
describe("naming charter: parser accepts canonical and legacy spellings", () => {
+3 -3
View File
@@ -27,7 +27,7 @@ export const BOOLEAN_FLAGS = new Set([
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"download", "downloads", "draft", "current", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"include-bridge", "includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
@@ -54,7 +54,7 @@ export const VALUE_FLAGS = new Set([
"documentId", "document-limit", "documentLimit", "documentSn", "documentType", "domain", "enable",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "form-codes", "formCodes", "format", "from",
"from-link", "host", "hours", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
"lines", "link", "linter", "manual-approval-status", "manual-status", "manualApprovalStatus", "manualStatus",
@@ -70,7 +70,7 @@ export const VALUE_FLAGS = new Set([
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window",
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "rule-version", "ruleVersion", "runtime-id",
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "rule-source", "ruleSource", "rule-version", "ruleVersion", "rule-version-id", "ruleVersionId", "runtime-id",
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
"simulation-batch-id", "simulationBatchId", "since", "sn", "sn-prefix", "sn-suffix", "snPrefix",
+7 -1
View File
@@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean {
);
}
function responseStatus(error: unknown): number | undefined {
/**
* Read the HTTP status off an error thrown by the HTTP layer, structurally:
* ky's `HTTPError` is not a dependency of this module, and test doubles only
* carry `{ response: { status } }`. `undefined` means the request never got a
* response (DNS failure, connection reset, timeout).
*/
export function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
+32 -13
View File
@@ -1,3 +1,5 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import { CliError } from "../../core/errors.js";
/**
@@ -9,8 +11,8 @@ import { CliError } from "../../core/errors.js";
* embeds them into release binaries. End users therefore need zero setup.
*
* Precedence: injected build vars → plain `LANGFUSE_*` shell vars (development
* convenience when running from source) → nothing. Reading user config files is
* deliberately absent: this domain must work without any local configuration.
* convenience when running from source) → gitignored local `.env.langfuse` → nothing.
* Reading user config files is deliberately absent: this domain must work without any local configuration.
*/
export type LangfuseConfig = {
baseUrl: string;
@@ -31,6 +33,29 @@ function normalizeBaseUrl(baseUrl: string): string {
return baseUrl.replace(/\/+$/, "");
}
function tryReadEnvLangfuse(): Record<string, string> {
if (process.env.NODE_ENV === "test") return {};
try {
const envPath = resolve(process.cwd(), ".env.langfuse");
if (!existsSync(envPath)) return {};
const content = readFileSync(envPath, "utf8");
const result: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const idx = trimmed.indexOf("=");
if (idx !== -1) {
const key = trimmed.slice(0, idx).trim();
const val = trimmed.slice(idx + 1).trim().replace(/^["']|["']$/g, "");
result[key] = val;
}
}
return result;
} catch {
return {};
}
}
export function hasLangfuseCredentials(): boolean {
const { baseUrl, publicKey, secretKey } = readLangfuseCredentials();
return Boolean(baseUrl && publicKey && secretKey);
@@ -43,18 +68,12 @@ function readLangfuseCredentials(): {
secretKey?: string;
projectId?: string;
} {
// Literal `process.env.X` accesses on purpose: `bun build --env=SEAL_BUILD_*`
// inlines static property reads at compile time, while a computed key
// (`process.env["SEAL_BUILD_" + name]`) stays a runtime lookup and comes back
// empty from a release binary. Reads happen per call so tests and dev shells
// can change the environment between invocations. The `LANGFUSE_*` fallbacks
// are deliberately outside the SEAL_BUILD_ prefix: they are never inlined and
// remain live shell-env vars for development runs from source.
const envFile = tryReadEnvLangfuse();
return {
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID)
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL, envFile.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY, envFile.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY, envFile.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID, envFile.LANGFUSE_PROJECT_ID)
};
}
+18
View File
@@ -88,6 +88,8 @@ import {
SimulationIntegrationStatusSchema,
SimulationHosecloudIntegration,
SimulationHosecloudIntegrationSchema,
SimulationMaycurIntegration,
SimulationMaycurIntegrationSchema,
MaterialPackage,
MaterialPackageSchema,
SimulationSpecification,
@@ -824,6 +826,22 @@ export async function listSimulationHosecloudIntegrations(
return z.array(SimulationHosecloudIntegrationSchema).parse(data);
}
export async function listSimulationMaycurPrivateIntegrations(
client: KyInstance
): Promise<SimulationMaycurIntegration[]> {
const json = (await client.get("api/v1/simulation/maycur-private-integrations").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationMaycurIntegrationSchema).parse(data);
}
export async function listSimulationMaycurStandardIntegrations(
client: KyInstance
): Promise<SimulationMaycurIntegration[]> {
const json = (await client.get("api/v1/simulation/maycur-standard-integrations").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationMaycurIntegrationSchema).parse(data);
}
export async function cleanSimulationBatch(
client: KyInstance,
batchId: string
@@ -0,0 +1,95 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { findSealCapability } from "../capabilities.js";
/**
* The flow lookup uses a rejected record query as a routing signal ("this was
* not a record ID, treat it as a document number") and a rejected run listing
* as "this document has no AI records". Both are fine for an identifier-shaped
* rejection and catastrophic for anything else: an expired token or a reset
* connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」,
* which is a wrong answer delivered with full confidence.
*
* These cases stop before the Hose client is built, so no tenant is required.
*/
const HOSE_CORP = {
id: "corp-hose",
name: "测试合思企业",
source: { type: "hose" }
} as unknown as CorpConfig;
type Handler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
function flowHandler(): Handler {
const capability = findSealCapability("sealApprovalRunFlowGet");
expect(capability).toBeDefined();
return capability!.handler as unknown as Handler;
}
function failingClient(error: unknown): KyInstance {
return {
get: () => {
throw error;
}
} as unknown as KyInstance;
}
function httpError(status: number): Error {
return Object.assign(new Error(`Request failed with status code ${status}`), {
response: { status }
});
}
async function captured(promise: Promise<unknown>): Promise<unknown> {
try {
await promise;
return undefined;
} catch (error) {
return error;
}
}
const SURFACED = [
["expired credentials", httpError(401)],
["forbidden credentials", httpError(403)],
["upstream service failure", httpError(503)],
["connection failure without a response", new TypeError("fetch failed")]
] as const;
describe("sealApprovalRunFlowGet failure attribution", () => {
for (const [label, error] of SURFACED) {
test(`surfaces ${label} instead of absorbing it as a document number`, async () => {
const thrown = await captured(
flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP })
);
// Identity, not message: the original error must reach the CLI layer so
// classifyCliError can still produce exit code 11 for auth failures.
expect(thrown).toBe(error);
});
}
test("keeps rejecting non-Hose enterprises before any request", async () => {
let called = false;
const client = {
get: () => {
called = true;
throw new Error("must not be reached");
}
} as unknown as KyInstance;
const thrown = await captured(
flowHandler()(client, { target: "B26001887" }, {
corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig
})
);
expect(String(thrown)).toContain("非合思");
expect(called).toBe(false);
});
});
+35 -5
View File
@@ -1,4 +1,4 @@
import { usageError, validationError } from "../../../core/errors.js";
import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -48,6 +48,28 @@ const {
summarizeRuleVersion
} = helpers;
/**
* Decide whether a failed lookup means "the caller's input was not an ID of
* that kind" or something worse.
*
* Distinguishing them matters because both call sites below use the failure as
* a routing signal: a rejected record lookup means "treat the input as a
* document number", and a rejected run listing means "this document has no AI
* records". Swallowing everything turns a transient failure into a confident
* business verdict — an expired token or a reset connection would surface as
* 「单据已删除」 or 「AI 从未审核」, which is worse than an error.
*/
function isUpstreamLookupMiss(error: unknown): boolean {
const status = responseStatus(error);
if (status !== undefined) {
// Malformed or unknown identifier: the answer we were hoping for.
return status === 400 || status === 404 || status === 422;
}
// No response at all (DNS, reset, timeout) is never a miss. Structural
// validation failures are: the body arrived, it just is not an approval run.
return classifyCliError(error).exitCode === 13;
}
export const approvalRunsCapabilities = [
{
name: "sealApprovalRunsSearch",
@@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// Not a record ID: the caller passed a document number. Continue as SN.
}
let runs: ApprovalRun[] = [];
@@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// No AI records for this document is a legitimate outcome.
}
if (runs.length === 0 && targetRecord) {
@@ -763,6 +787,12 @@ export const approvalRunsCapabilities = [
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
traceSearch: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse search ${detail.sourceExtendData._langfuseTraceId} --query <关键词>`
: undefined,
traceOutline: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse outline ${detail.sourceExtendData._langfuseTraceId} --include-io-preview`
: undefined,
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
}
};
+34 -43
View File
@@ -21,6 +21,7 @@ import type {
ApprovalRun,
RuleSetVersion,
SimulationBatch,
SimulationRuleSourceInput,
WebhookIntegration
} from "../types.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
@@ -230,39 +231,18 @@ export function normalizeRuleStrictness(value?: string): string {
}
export type SimulationBatchCreateInput = {
mode?: string;
sourceSystem?: string;
flowIds?: string[];
documentSn?: string | string[];
mode?: string; sourceSystem?: string; signKey?: string;
flowIds?: string[]; documentSn?: string | string[]; formCodes?: string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
packageId?: string;
templateId?: string;
schemaConfig?: Record<string, unknown>;
approvalCode?: string;
nodeId?: string;
runMode?: string;
requestIds?: string[];
workflowTypeId?: string;
flowStatusList?: number[];
businessCodes?: string[];
documentType?: string;
formCodes?: string[];
formSubTypeBizCode?: string;
formStatus?: string;
pageNo?: number;
pageSize?: number;
startTime?: number;
endTime?: number;
status?: string[];
limit?: number;
// 预留:其他取数模式(如合思时间范围)透传参数,覆盖构建结果
rawParams?: Record<string, unknown>;
skipInvoiceGeneration?: boolean; skipExpenseExtraction?: boolean; disableAttachmentCache?: boolean;
ruleSource?: SimulationRuleSourceInput; ruleVersion?: string;
packageIds?: string[]; packageId?: string; templateId?: string;
schemaConfig?: Record<string, unknown>; approvalCode?: string; nodeId?: string; runMode?: string;
requestIds?: string[]; workflowTypeId?: string; flowStatusList?: number[]; businessCodes?: string[];
documentType?: string; formSubTypeBizCode?: string; formStatus?: string;
pageNo?: number; pageSize?: number; startTime?: number; endTime?: number;
status?: string[]; limit?: number; rawParams?: Record<string, unknown>;
};
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
@@ -320,6 +300,12 @@ export function buildSimulationBatchParams(input: SimulationBatchCreateInput): R
thinkingDepthOverride: input.thinkingDepthOverride ?? "default",
disableAttachmentCache: input.disableAttachmentCache ?? false
};
const resolvedRuleSource =
input.ruleSource ??
(input.ruleVersion ? { type: "published", versionId: input.ruleVersion } : undefined);
if (resolvedRuleSource) {
params.ruleSource = resolvedRuleSource;
}
const docSns = input.flowIds ?? (typeof input.documentSn === "string" ? input.documentSn.split(",").map((s) => s.trim()).filter(Boolean) : input.documentSn);
@@ -376,17 +362,21 @@ export function buildSimulationBatchParams(input: SimulationBatchCreateInput): R
rejectNodeName: input.rejectNodeName ?? null
});
} else if (sourceSystem === "maycur" || sourceSystem === "maycur-standard") {
Object.assign(params, {
sourceSystem,
formCodes: input.formCodes ?? docSns,
createdAtStart: input.startTime,
createdAtEnd: input.endTime,
formSubTypeBizCode: input.formSubTypeBizCode,
formStatus: input.formStatus,
pageNo: input.pageNo ?? 1,
pageSize: input.pageSize ?? 100,
signKey: input.signKey
});
const formCodes = input.formCodes ?? docSns;
if (formCodes?.length) {
Object.assign(params, { sourceSystem, formCodes, ...(input.signKey ? { signKey: input.signKey } : {}) });
} else {
Object.assign(params, {
sourceSystem,
createdAtStart: input.startTime,
createdAtEnd: input.endTime,
formSubTypeBizCode: input.formSubTypeBizCode,
formStatus: input.formStatus,
pageNo: input.pageNo ?? 1,
pageSize: input.pageSize ?? 100,
signKey: input.signKey
});
}
} else if (sourceSystem === "feishu") {
Object.assign(params, {
sourceSystem: "feishu",
@@ -418,6 +408,7 @@ export function summarizeSimulationBatch(batch: SimulationBatch) {
failedCount: batch.failedCount,
createdCount: batch.createdCount,
createFailedCount: batch.createFailedCount,
ruleSource: batch.ruleSource,
requestSummary: batch.requestSummary,
resultSummary: batch.resultSummary,
createdAt: batch.createdAt
@@ -598,7 +589,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
export function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
...summarizeExtraFindings(record),
...summarizeExtraFindings(record, true),
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
@@ -324,6 +324,29 @@ describe("buildSimulationBatchParams", () => {
});
});
test("builds request payload with specified ruleVersion", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
ruleVersion: "01a123bd-ef1c-7579-8ebc-3c02058c9c72"
});
expect(params.ruleSource).toEqual({
type: "published",
versionId: "01a123bd-ef1c-7579-8ebc-3c02058c9c72"
});
});
test("builds request payload with explicit ruleSource", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
ruleSource: { type: "current" }
});
expect(params.ruleSource).toEqual({ type: "current" });
});
test("rejects hosecloud mode without flowIds", () => {
expect(() => buildSimulationBatchParams({ mode: "hosecloud", signKey: SIGN_KEY }))
.toThrow("hosecloud 模式需要提供 flowIds");
+36 -11
View File
@@ -5,7 +5,9 @@ import { readFileSync } from "node:fs";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import * as api from "../api.js";
import {
type SimulationBatch
type SimulationBatch,
SimulationRuleSourceInputSchema,
type SimulationRuleSourceInput
} from "../types.js";
import * as helpers from "./helpers.js";
import { parseDurationMs } from "../../../core/duration.js";
@@ -85,16 +87,21 @@ export const simulationCapabilities = [
},
{
name: "sealSimulationBatchCreate",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;默认幂等:复用窗口内同 flow-ids/packageIds 的既有批次直接返回不重复扣费(--force 跳过);其他取数模式通过 rawParams 预留透传。",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)、每刻报销(maycur/maycur-standard)、泛微(weaver)、汇联易(helios)与材料包导入(material_pack)模式;默认以线上生效规则运行,支持 ruleSource.type=current 或 --draft 显式拍摄未发布草稿快照,或指定 ruleVersion 回溯已发布版本;默认幂等:复用窗口内同 flow-ids/packageIds 的既有批次直接返回不重复扣费(--force 跳过);其他取数模式通过 rawParams 预留透传。",
parameters: z.object({
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
mode: z.enum(["hosecloud", "material_pack", "weaver", "helios", "maycur", "maycur-standard"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入; weaver=泛微OA; helios=汇联易; maycur=每刻报销私有版; maycur-standard=每刻报销标准版"),
sourceSystem: z.string().optional().describe("来源系统,缺省同 mode"),
flowIds: z.array(z.string()).max(100).optional().describe("合思/通用单据流水号列表"),
documentSn: z.union([z.string(), z.array(z.string())]).optional().describe("单据编号(别名)"),
formCodes: z.array(z.string()).max(100).optional().describe("每刻报销单号列表"),
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
skipExpenseExtraction: z.boolean().optional().describe("跳过后台历史费用明细库提取(防重报检索用), 默认 true"),
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
ruleSource: SimulationRuleSourceInputSchema.optional().describe("规则来源: { type: 'current' } 或 { type: 'published', versionId: '...' }"),
ruleVersion: z.string().optional().describe("指定已发布规则版本 ID (等同于 ruleSource.type=published)"),
signKey: z.string().optional().describe("合思/每刻集成标识; 缺省时自动取对应集成"),
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
@@ -106,13 +113,18 @@ export const simulationCapabilities = [
handler: async (
client: KyInstance,
params: {
mode?: "hosecloud" | "material_pack";
mode?: "hosecloud" | "material_pack" | "weaver" | "helios" | "maycur" | "maycur-standard";
sourceSystem?: string;
flowIds?: string[];
documentSn?: string | string[];
formCodes?: string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
ruleSource?: SimulationRuleSourceInput;
ruleVersion?: string;
signKey?: string;
packageIds?: string[];
templateId?: string;
@@ -123,7 +135,7 @@ export const simulationCapabilities = [
rawParams?: Record<string, unknown>;
}
) => {
const mode = params.mode ?? "hosecloud";
const mode = params.mode ?? (params.sourceSystem as typeof params.mode) ?? "hosecloud";
let signKey = params.signKey;
if (mode === "hosecloud" && !signKey) {
const integrations = await api.listSimulationHosecloudIntegrations(client);
@@ -131,16 +143,27 @@ export const simulationCapabilities = [
if (!signKey) {
throw validationError("未找到合思集成 signKey, 请通过 signKey 参数提供");
}
} else if (mode === "maycur" && !signKey) {
const integrations = await api.listSimulationMaycurPrivateIntegrations(client).catch(() => []);
signKey = integrations.find((item) => item.signKey)?.signKey;
} else if (mode === "maycur-standard" && !signKey) {
const integrations = await api.listSimulationMaycurStandardIntegrations(client).catch(() => []);
signKey = integrations.find((item) => item.signKey)?.signKey;
}
const payload = buildSimulationBatchParams({
mode,
sourceSystem: params.sourceSystem ?? mode,
flowIds: params.flowIds,
documentSn: params.documentSn,
formCodes: params.formCodes,
rejectNodeName: params.rejectNodeName,
thinkingDepthOverride: params.thinkingDepthOverride,
skipInvoiceGeneration: params.skipInvoiceGeneration,
skipExpenseExtraction: params.skipExpenseExtraction,
disableAttachmentCache: params.disableAttachmentCache,
ruleSource: params.ruleSource,
ruleVersion: params.ruleVersion,
signKey,
packageIds: params.packageIds,
templateId: params.templateId,
@@ -361,14 +384,16 @@ export const simulationCapabilities = [
},
{
name: "sealSimulationIntegrationsGet",
description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",
description: "查询模拟测试可用的来源集成状态与合思/每刻集成选项(signKey 等)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const [status, hosecloudIntegrations] = await Promise.all([
const [status, hosecloudIntegrations, maycurPrivateIntegrations, maycurStandardIntegrations] = await Promise.all([
api.getSimulationIntegrationStatus(client),
api.listSimulationHosecloudIntegrations(client)
api.listSimulationHosecloudIntegrations(client).catch(() => []),
api.listSimulationMaycurPrivateIntegrations(client).catch(() => []),
api.listSimulationMaycurStandardIntegrations(client).catch(() => [])
]);
return { status, hosecloudIntegrations };
return { status, hosecloudIntegrations, maycurPrivateIntegrations, maycurStandardIntegrations };
}
},
{
+42 -1
View File
@@ -238,6 +238,9 @@ export const ApprovalRunSchema = z.object({
ruleSetVersionNumber: z.number().optional(),
ruleSetPublishedAt: z.number().optional(),
ruleSetPublishedByName: z.string().optional(),
ruleSetSnapshotCreatedAt: z.number().optional(),
thinkingDepthLevel: z.string().optional(),
durationMs: z.number().optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
@@ -480,7 +483,9 @@ export const SimulationBatchParamsSchema = z.object({
packageIds: z.array(z.string()).optional(),
packageLabel: z.string().optional(),
runMode: z.string().optional(),
schemaConfig: SimulationSchemaConfigSchema.optional()
schemaConfig: SimulationSchemaConfigSchema.optional(),
ruleSource: z.unknown().optional(),
formCodes: z.array(z.string()).optional()
}).passthrough();
export const SimulationRequestSummarySchema = z.object({
@@ -498,6 +503,34 @@ export const SimulationResultSummarySchema = z.object({
message: z.string().optional()
}).passthrough();
export const SimulationRuleSourceSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("snapshot"),
snapshotId: z.string(),
createdAt: z.number().optional()
}),
z.object({
type: z.literal("published"),
versionId: z.string(),
versionNumber: z.number().optional()
}),
z.object({
type: z.literal("current")
})
]);
export type SimulationRuleSource = z.infer<typeof SimulationRuleSourceSchema>;
export const SimulationRuleSourceInputSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("current")
}),
z.object({
type: z.literal("published"),
versionId: z.string().min(1)
})
]);
export type SimulationRuleSourceInput = z.infer<typeof SimulationRuleSourceInputSchema>;
export const SimulationBatchSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
@@ -514,6 +547,7 @@ export const SimulationBatchSchema = z.object({
params: SimulationBatchParamsSchema.optional(),
requestSummary: SimulationRequestSummarySchema.nullable().optional(),
resultSummary: SimulationResultSummarySchema.nullable().optional(),
ruleSource: SimulationRuleSourceSchema.optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
@@ -556,6 +590,13 @@ export const SimulationHosecloudIntegrationSchema = z.object({
corporationId: z.string().optional()
}).passthrough();
export const SimulationMaycurIntegrationSchema = z.object({
signKey: z.string(),
displayName: z.string(),
sourceSystem: z.enum(["maycur", "maycur-standard"]).optional()
}).passthrough();
export type SimulationMaycurIntegration = z.infer<typeof SimulationMaycurIntegrationSchema>;
export const MaterialPackageSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),