Compare commits

..
16 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
yunyingk 8ecadbb124 Merge pull request #281 from yunyingk/codex/release-v0.11.20
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
chore: 发布 v0.11.20 补丁版本
2026-11-08 23:19:40 +08:00
gitea dec52cf5fa chore: 发布 v0.11.20 补丁版本 2026-11-08 23:18:00 +08:00
yunyingk b49e3a6ea0 Merge pull request #280 from yunyingk/mac15/tenant-disable-active-gate
feat: 新增租户 active 状态与统一禁用闸门
2026-11-08 12:53:31 +08:00
gitea 0ff3d9a313 feat: 新增租户 active 状态与统一禁用闸门 2026-11-08 12:52:05 +08:00
41 changed files with 1334 additions and 122 deletions

No files matched your search

+3
View File
@@ -15,6 +15,9 @@ tmp/
.local/
/reports/
# WorkBuddy workspace data (memory logs, project state) — keep on disk, never commit
.workbuddy/
# Developer-only build-time credentials for compile-time injection — never committed
.env.langfuse
.env
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.19",
"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"
+23
View File
@@ -7,6 +7,29 @@ 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
- 新增租户 active 状态与启用/禁用管理命令,统一阻止对已禁用租户执行操作;完善配置校验、CLI/MCP 闸门及使用文档。
## [0.11.19] - 2026-11-06
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.19",
"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",
+8 -5
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.19: 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.19
short-description: Seal tenant and Hose approval automation (v0.11.19)
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`。
## 规则编号重排:两次调用
@@ -155,6 +157,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| 导出审核记录 Excel、额外人工审批流、高级筛选或导出任务等待 | `references/approval-run-export.md` | 只查命令语法时读 `cli.md`;报告与复核台账走 `report-templates.md` |
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| 租户禁用/启用、企业已停用、命令提示「已禁用」 | `references/tenant-status.md` | 只查命令语法时读 `cli.md` |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
@@ -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
+5 -2
View File
@@ -46,6 +46,8 @@ seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--dry-run] [--confirm]
seal-use corps rename <corpId> --name <newName>
seal-use corps disable <corpId> [--dry-run] [--confirm]
seal-use corps enable <corpId> [--dry-run] [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
@@ -134,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` 控上限)。
@@ -0,0 +1,56 @@
# 租户启用 / 禁用状态
适用信号:企业已停用、需要临时封禁某个租户、命令报「已禁用」、想确认禁用后还能不能搜到该企业。
## 状态定义
企业配置文件(`~/.config/seal-use/enterprises/*.json`)顶层的 `active` 字段:
```json
{
"id": "acme",
"name": "Acme Corporation",
"active": false,
"source": { "type": "hose", "...": "..." }
}
```
- 字段在**企业**上,不在 `source` 里。合思来源(`type: "hose"`)与 Seal 本源(`type: "seal"`)共用同一个开关,行为完全一致,不存在某一来源例外。
- **字段缺失 = 启用**。旧配置零迁移;读取和任何配置更新都会把缺省值物化成显式的 `active: true`。
- **字段值非法 = 禁用(fail-closed)**。`"false"` 字符串、`null`、`0`、对象等任何非布尔值都归一化为 `active: false`。配置文件**不会**被丢弃,企业仍可检索并显示 `active: false`,指向它的命令一律阻断,stderr 告警并给出修复命令。绝不会把写坏的值当成启用。
- 显式 `active: false` = 禁用。不要靠删除配置文件、改文件名或清空凭据来「禁用」,那会破坏检索可见性与恢复路径。
## 命令
```bash
seal-use corps disable <corpId> --dry-run # 预览,不写文件
seal-use corps disable <corpId> --confirm # 实际禁用
seal-use corps enable <corpId> --confirm # 恢复
```
- 不加 `--confirm` / `--yes` 会返回退出码 `10`(确认门)。
- `--dry-run` 返回 `preview: true` 与 `changesDiff: { before, after }`,不写配置。
- 这两个命令是**唯一**能解析禁用企业的命令;没有它们,禁用后无法恢复。
## 行为口径(严格遵守)
| 场景 | 结果 |
| --- | --- |
| `corps list` / `corps search` / `corps find` | 禁用企业**仍可检索**,输出带 `active: false`。禁用不影响搜索可见性 |
| 任何显式指定该企业 ID 的命令 | **统一阻断、不执行**,退出码 `14`,stderr 提示 `seal-use corps enable <corpId> --confirm` |
| `corps enable` / `corps disable` | 允许执行(唯一豁免) |
阻断发生在企业解析处(`resolveCorpConfig`),早于创建 HTTP client、认证续期和任何业务 handler,因此不会有网络请求或副作用。覆盖:
- CLI 所有 `--corp <id>` 与位置参数形式(查询、写操作、绑定、同步、诊断、本地导出任务);
- MCP 的 `seal_use` 与 `seal_use_write` 两个网关;
- stateful 模式下 `defaultCorpId` 指向禁用企业、或无显式 ID 时兜底命中的第一个企业;
- webhook 重放的 `--source-corp` / `--target-corp` 以及能力注册表中的等价解析;
- 本地 `rules lint --file` 与 `report --ledger` 的降级分支不会吞掉该阻断。
## 排查步骤
1. `seal-use corps search <关键词>` 确认企业仍在列表中并读取 `active` 字段。
2. 若确需操作该企业:`seal-use corps enable <corpId> --confirm`。这个值非法时同样有效——该命令会把字段重写为 `true`,一并修复坏配置。
3. 若确需保持禁用,不要绕过闸门(不要直接改 ID、不要复制配置换新 ID)。解除封禁是唯一正当路径。
4. 退出码 `14` 属安全守卫拦截,不是认证失败(`11`)或参数错误(`2`)。若看到 `13`「No enterprise config found」,说明整个配置文件被跳过(JSON 格式错误或必填字段缺失),与本开关无关。详见 `references/cli.md`。
+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>]");
+2
View File
@@ -1,4 +1,5 @@
import { usageError } from "../../core/errors.js";
import { handleCorpActive } from "./corps/active.js";
import { handleCorpBindings } from "./corps/bindings.js";
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
import { handleCorpOverview } from "./corps/overview.js";
@@ -14,6 +15,7 @@ export async function handleCorpsCommand(
args: ParsedArgs
) {
if (await handleCorpOverview(action, maybeName, args)) return;
if (await handleCorpActive(action, maybeName, args)) return;
if (await handleCorpBindings(action, maybeName, args)) return;
if (await handleCorpSync(action, maybeName, args)) return;
if (await handleCorpOnboarding(action, maybeName, args)) return;
+63
View File
@@ -0,0 +1,63 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, dryRunOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
/**
* Tenant availability switch for both `hose` and `seal` sources.
*
* This is the ONLY command surface allowed to resolve a disabled tenant: without
* it, `corps enable` could not restore an enterprise that the gate now blocks.
* All other commands resolve through `selectCorp()` and are refused upstream.
*/
export async function handleCorpActive(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
if (action !== "disable" && action !== "enable") return false;
const corpId = maybeName ?? stringOption(args.options.corp);
if (!corpId) {
throw usageError(`Usage: seal-use corps ${action} <corpId> [--dry-run] [--confirm]`);
}
const targetActive = action === "enable";
const { selectCorp } = await import("../../helpers.js");
const corp = selectCorp(corpId, { allowDisabled: true });
const previousActive = corp.active ?? true;
if (dryRunOption(args)) {
printJson({
preview: true,
dryRun: true,
mutation: `corps ${action}`,
corpId: corp.id,
corpName: corp.name,
sourceType: corp.source.type,
changesDiff: { before: previousActive, after: targetActive },
note: "禁用只阻断显式指定该企业 ID 的命令,不影响 corps list/search 的检索可见性。"
});
return true;
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to ${action} enterprise '${corp.name}' (${corp.id}) without --confirm.`,
`seal-use corps ${action} ${corp.id} --confirm`
);
}
const updated = updateCorpConfig(corp.id, { active: targetActive });
printJson({
success: true,
id: updated.id,
name: updated.name,
sourceType: updated.source.type,
active: updated.active,
previousActive
});
return true;
}
+6
View File
@@ -35,6 +35,9 @@ export async function handleCorpOverview(
}
const corpId = stringOption(args.options.corp);
// Deliberately NOT filtered by `active`: disabling a tenant gates command
// execution at corp resolution, never discovery. Keep disabled enterprises
// searchable for both `hose` and `seal` sources and just surface the flag.
const allCorps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const currentCorpId = corpId ?? (
@@ -88,6 +91,7 @@ export async function handleCorpOverview(
printJson(displayList.map((item) => ({
id: item.id,
name: item.name,
active: item.active ?? true,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
@@ -113,6 +117,7 @@ export async function handleCorpOverview(
printJson({
id: corp.id,
name: corp.name,
active: corp.active ?? true,
environment: corp.environment ?? "production",
configFile,
seal: {
@@ -139,6 +144,7 @@ export async function handleCorpOverview(
printJson({
id: corp.id,
name: corp.name,
active: corp.active ?? true,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type,
@@ -0,0 +1,291 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../../runner.js";
import { selectCorp } from "../../helpers.js";
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { resolveReplayCorpPair } from "../../../domains/seal/replay/webhook.js";
const ENV_KEYS = [
"SEAL_USE_ENTERPRISES_DIR",
"SEAL_USE_CONFIG_FILE",
"SEAL_USE_TOKEN_STORE",
"SEAL_USE_USAGE_FILE",
"SEAL_DISABLE_BG_UPDATE"
] as const;
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
for (const key of ENV_KEYS) {
const value = ORIGINAL_ENV[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const SOURCE_VARIANTS = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://acme.sealai.cc"
}
}
] as const;
function setup(): { root: string; enterprises: string } {
const root = mkdtempSync(join(tmpdir(), "seal-tenant-active-"));
tempDirs.push(root);
const enterprises = join(root, "enterprises");
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");
process.env.SEAL_DISABLE_BG_UPDATE = "1";
return { root, enterprises };
}
function writeCorp(
dir: string,
options: {
id: string;
name: string;
source: Record<string, unknown>;
active?: unknown;
}
): string {
const payload: Record<string, unknown> = {
id: options.id,
name: options.name,
source: options.source,
seal: { url: "https://acme.sealai.cc" },
auth: { refreshTtl: 300 }
};
if (options.active !== undefined) payload.active = options.active;
const path = join(dir, `${options.id}.json`);
writeFileSync(path, JSON.stringify(payload));
return path;
}
function corpFile(dir: string, id: string): Record<string, unknown> {
return JSON.parse(readFileSync(join(dir, `${id}.json`), "utf-8"));
}
/** Fail loudly if a command reaches any upstream API: a blocked command must never execute. */
function guardNetwork(): { calls: () => number } {
let calls = 0;
globalThis.fetch = (async () => {
calls += 1;
throw new Error("network request must not happen for a disabled tenant");
}) as unknown as typeof globalThis.fetch;
return { calls: () => calls };
}
/** Commands that explicitly name the tenant id, spanning local/corp/client handlers. */
function commandsNamingCorp(id: string): string[][] {
return [
["corps", "get", id],
["corps", "current", "--corp", id],
["corps", "mark", id, "--env", "test"],
["corps", "rename", id, "--name", "Renamed"],
["contacts", "departments", "--corp", id],
["rules", "list", "--corp", id],
["documents", "list", "--corp", id],
["billing", "status", "--corp", id],
["webhook", "list", "--corp", id],
["source", "config", "--corp", id],
["auth", "status", "--corp", id]
];
}
describe("tenant active state: both sources share one gate", () => {
for (const { label, source } of SOURCE_VARIANTS) {
const id = `acme-${label}`;
const name = `Acme ${label} Corporation`;
test(`${label}: disabled tenant stays visible in corps list and search`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const listed = await runCli(["corps", "list", "--all"]);
expect(listed.exitCode).toBe(0);
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
id, name, active: false, sourceType: label
}));
const searched = await runCli(["corps", "search", "Acme", "--strict"]);
expect(searched.exitCode).toBe(0);
const matches = JSON.parse(searched.stdout) as Array<{ id: string; active: boolean }>;
expect(matches.find((item) => item.id === id)).toMatchObject({ id, active: false });
});
test(`${label}: every command explicitly naming the disabled tenant is blocked without executing`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const network = guardNetwork();
for (const command of commandsNamingCorp(id)) {
const result = await runCli(command);
expect({ command, exitCode: result.exitCode }).toEqual({ command, exitCode: 14 });
expect(result.isError).toBe(true);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("已禁用");
expect(result.stderr).toContain(`seal-use corps enable ${id}`);
}
expect(network.calls()).toBe(0);
});
test(`${label}: a malformed active value fails closed without hiding the enterprise`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: "false" });
const network = guardNetwork();
const listed = await runCli(["corps", "list", "--all"]);
expect(listed.exitCode).toBe(0);
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
id, name, active: false, sourceType: label
}));
expect(listed.stderr).toContain("active 字段值非法");
// The block reports a disabled tenant (14), not a missing config (13),
// and the enterprise never disappears from discovery.
const blocked = await runCli(["corps", "get", id]);
expect(blocked.exitCode).toBe(14);
expect(blocked.stdout).toBe("");
expect(blocked.stderr).toContain("已禁用");
expect(network.calls()).toBe(0);
const recovered = await runCli(["corps", "enable", id, "--confirm"]);
expect(recovered.exitCode).toBe(0);
expect(corpFile(enterprises, id).active).toBe(true);
});
test(`${label}: an active tenant with the same source still runs through corp resolution`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: true });
const result = await runCli(["corps", "get", id]);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ id, active: true });
});
test(`${label}: disable/enable lifecycle with dry-run and confirmation gate`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source });
const preview = await runCli(["corps", "disable", id, "--dry-run"]);
expect(preview.exitCode).toBe(0);
expect(JSON.parse(preview.stdout)).toMatchObject({
preview: true,
dryRun: true,
mutation: "corps disable",
corpId: id,
sourceType: label,
changesDiff: { before: true, after: false }
});
expect(corpFile(enterprises, id).active).toBeUndefined();
const unconfirmed = await runCli(["corps", "disable", id]);
expect(unconfirmed.exitCode).toBe(10);
expect(corpFile(enterprises, id).active).toBeUndefined();
const disabled = await runCli(["corps", "disable", id, "--confirm"]);
expect(disabled.exitCode).toBe(0);
expect(JSON.parse(disabled.stdout)).toMatchObject({ id, active: false, previousActive: true });
expect(corpFile(enterprises, id).active).toBe(false);
// Re-enabling must work even though the tenant is disabled: this is the
// single documented exemption from the block.
const enabled = await runCli(["corps", "enable", id, "--confirm"]);
expect(enabled.exitCode).toBe(0);
expect(JSON.parse(enabled.stdout)).toMatchObject({ id, active: true, previousActive: false });
expect(corpFile(enterprises, id).active).toBe(true);
const afterEnable = await runCli(["corps", "get", id]);
expect(afterEnable.exitCode).toBe(0);
});
test(`${label}: a stateful default pointing at a disabled tenant is blocked`, async () => {
const { root, enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
writeFileSync(join(root, "config.json"), JSON.stringify({
stateful: true,
defaultCorpId: id
}));
const network = guardNetwork();
const result = await runCli(["contacts", "departments"]);
expect(result.exitCode).toBe(14);
expect(result.stdout).toBe("");
expect(network.calls()).toBe(0);
});
test(`${label}: replay refuses a disabled source or target corp through both selectors`, () => {
const { enterprises } = setup();
const activeId = `active-${label}`;
const disabledId = `off-${label}`;
writeCorp(enterprises, { id: activeId, name: "Active Corp", source, active: true });
writeCorp(enterprises, { id: disabledId, name: "Disabled Corp", source, active: false });
const activeCorp = selectCorp(activeId);
// CLI replay path: `selectCorp` is passed straight into resolveReplayCorpPair.
expect(() => resolveReplayCorpPair(
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
selectCorp
)).toThrow("已禁用");
expect(() => resolveReplayCorpPair(
{ sourceCorpId: disabledId, targetCorpId: activeId, activeCorp, force: true },
selectCorp
)).toThrow("已禁用");
// Capability registry replay path builds its own resolveCorpConfig selector.
const capabilitySelector = (id?: string) => resolveCorpConfig(
loadCorpConfigs(),
{
stateful: loadGlobalConfig().stateful,
defaultCorpId: loadGlobalConfig().defaultCorpId,
corpId: id
},
getEnterprisesDirCandidates()
);
expect(() => resolveReplayCorpPair(
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
capabilitySelector
)).toThrow("已禁用");
});
test(`${label}: local lint/ledger fallbacks cannot swallow a disabled-tenant block`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const lint = await runCli(["rules", "lint", "--file", "rules.json", "--corp", id]);
expect(lint.exitCode).toBe(14);
expect(lint.stderr).toContain("已禁用");
const ledger = await runCli(["report", "validate", "--ledger", "ledger.xlsx", "--corp", id]);
expect(ledger.exitCode).toBe(14);
expect(ledger.stderr).toContain("已禁用");
});
}
});
+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);
+5 -1
View File
@@ -6,6 +6,7 @@ import { runCapabilityResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import { CliError, usageError } from "../../core/errors.js";
import { isCorpDisabledError } from "../../core/config/active.js";
import {
BUILTIN_MONTHLY_TEMPLATE,
exportReportPackage,
@@ -36,7 +37,10 @@ export async function handleLocalReportCommand(action: string | undefined, args:
try {
const { selectCorp } = await import("../helpers.js");
corp = selectCorp(corpId);
} catch {
} catch (error) {
// Ledger/review work is tenant-free, but if the caller explicitly named a
// disabled enterprise, the block must still stand instead of falling back.
if (isCorpDisabledError(error)) throw error;
corp = {
corpId,
id: corpId,
+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,
+27 -4
View File
@@ -98,6 +98,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
],
description: "Safely updates the display name of a configured enterprise without modifying underlying files manually."
},
{
name: "disable",
group: "企业配置",
summary: "Disable a tenant without removing it from enterprise search",
usage: ["seal-use corps disable <corpId> [--dry-run] [--confirm]"],
options: [
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
],
description: "Sets active=false on a Hose or Seal enterprise. The enterprise stays visible in `corps list/search`, but every command that explicitly resolves its ID is refused until it is enabled again."
},
{
name: "enable",
group: "企业配置",
summary: "Re-enable a disabled tenant",
usage: ["seal-use corps enable <corpId> [--dry-run] [--confirm]"],
options: [
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
],
description: "Sets active=true. This is the only command allowed to resolve a disabled enterprise, so a disabled tenant can always be restored."
},
{
name: "bind-test",
group: "测试配对与验证",
@@ -556,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" }
]
@@ -827,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>]"
]
},
+3 -2
View File
@@ -10,7 +10,7 @@ import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
import { printJson } from "./printer.js";
import type { OutputOptions } from "./types.js";
export function selectCorp(corpId?: string): CorpConfig {
export function selectCorp(corpId?: string, options: { allowDisabled?: boolean } = {}): CorpConfig {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const corp = resolveCorpConfig(
@@ -18,7 +18,8 @@ export function selectCorp(corpId?: string): CorpConfig {
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId
corpId,
allowDisabled: options.allowDisabled
},
getEnterprisesDirCandidates()
);
+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",
+5 -1
View File
@@ -6,6 +6,7 @@ import type { CorpConfig } from "../core/config/types.js";
import { VERSION_INFO } from "../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { classifyCliError, usageError, validationError } from "../core/errors.js";
import { isCorpDisabledError } from "../core/config/active.js";
import {
booleanOption,
materialPackFilePolicyOptions,
@@ -313,7 +314,10 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
let corp: CorpConfig;
try {
corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
} catch {
} catch (error) {
// Local lint tolerates a missing enterprise config, but a disabled tenant
// is an explicit block: never degrade into the synthetic workspace corp.
if (isCorpDisabledError(error)) throw error;
corp = {
id: "local",
name: "Local Workspace",
+38
View File
@@ -0,0 +1,38 @@
import { CliError, safetyBlocked } from "../errors.js";
import type { CorpConfig } from "./types.js";
/** `safetyBlocked` exit code. Shared so local command fallbacks can re-throw this block. */
export const CORP_DISABLED_EXIT_CODE = 14;
/**
* Legacy configs and `as CorpConfig` fixtures omit `active`. Only an explicit
* `false` disables a tenant, so nothing that never set the field can be blocked
* by accident.
*/
export function isCorpActive(corp: CorpConfig): boolean {
return corp.active !== false;
}
/**
* The single tenant gate. `resolveCorpConfig` calls this on every resolution
* path (explicit `--corp`, stateful default, first-corp fallback, replay
* source/target resolution, background export workers), which is what makes the
* block uniform across the CLI and both MCP gateways.
*
* `corps enable` / `corps disable` resolve with `allowDisabled: true`; they are
* the only commands that may touch a disabled tenant, otherwise a disabled
* tenant could never be restored.
*/
export function assertCorpActive(corp: CorpConfig): void {
if (isCorpActive(corp)) return;
throw safetyBlocked(
`企业「${corp.name}」(${corp.id}) 已禁用,命令未执行。启用后才能继续对该企业执行操作。`,
`seal-use corps enable ${corp.id} --confirm`
);
}
/** True for the structured block thrown by {@link assertCorpActive}. */
export function isCorpDisabledError(error: unknown): error is CliError {
return error instanceof CliError && error.exitCode === CORP_DISABLED_EXIT_CODE;
}
+74
View File
@@ -300,6 +300,80 @@ describe("loadCorpConfigs", () => {
});
});
describe("loadCorpConfigs tenant active materialization", () => {
const sources = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: { type: "seal", token: "seal-token", sealUrl: "https://seal.sealai.cc" }
}
];
test("materializes active=true for legacy configs of both sources and keeps explicit false", () => {
const dir = makeTempDir();
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-legacy.json`), JSON.stringify({
id: `${label}-legacy`, name: `${label} Legacy`, source
}));
writeFileSync(join(dir, `${label}-disabled.json`), JSON.stringify({
id: `${label}-disabled`, name: `${label} Disabled`, active: false, source
}));
}
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const byId = new Map(loadCorpConfigs().map((item) => [item.id, item]));
for (const { label } of sources) {
expect(byId.get(`${label}-legacy`)?.active).toBe(true);
expect(byId.get(`${label}-disabled`)?.active).toBe(false);
}
});
test("a malformed active value loads as disabled without dropping the enterprise", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-malformed.json`), JSON.stringify({
id: `${label}-malformed`, name: `${label} Malformed`, active: "false", source
}));
}
const byId = new Map(loadCorpConfigs().map((item) => [item.id, item]));
for (const { label } of sources) {
expect(byId.has(`${label}-malformed`)).toBe(true);
expect(byId.get(`${label}-malformed`)?.active).toBe(false);
}
// Fail-closed is NOT a parse failure: the file must never be skipped.
expect(getLastCorpConfigLoadIssues()).toEqual([]);
});
test("updateCorpConfig writes an explicit active value for both sources", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-update.json`), JSON.stringify({
id: `${label}-update`, name: `${label} Update`, source
}));
const updated = updateCorpConfig(`${label}-update`, { active: false });
expect(updated.active).toBe(false);
expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(false);
const restored = updateCorpConfig(`${label}-update`, { active: true });
expect(restored.active).toBe(true);
expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(true);
}
});
});
describe("syncLegacyEnterprisesDir", () => {
test("migrates files from legacy to primary and deletes legacy when > 7 days old", () => {
const primary = makeTempDir();
+36 -3
View File
@@ -93,6 +93,9 @@ let lastCorpLoadIssues: CorpConfigLoadIssue[] = [];
// Files already warned about this process: loadCorpConfigs runs several times
// per invocation (selection, dispatch, tool handlers), so warn each file once.
const warnedCorpFiles = new Set<string>();
// A malformed `active` value is normalized to disabled instead of dropping the
// whole file. Track those separately so the warning names the right remedy.
const warnedActiveCorpFiles = new Set<string>();
/**
* Issues from the most recent loadCorpConfigs() call. A malformed file must not
@@ -112,6 +115,7 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, { config: CorpConfig; path: string }>();
const issues: CorpConfigLoadIssue[] = [];
const activeWarnings: Array<{ dir: string; file: string; corpId: string }> = [];
for (const dir of dirs) {
for (const file of readdirSync(dir)
@@ -119,13 +123,26 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
let corp: CorpConfig;
let activeMalformed = false;
try {
const content = readFileSync(fullPath, "utf-8");
corp = CorpConfigSchema.parse(JSON.parse(content));
const raw = JSON.parse(content) as Record<string, unknown>;
const parsed = CorpConfigSchema.parse(raw);
// `CorpConfigSchema.active` is fail-closed: a non-boolean value parses
// to `false` instead of rejecting the file. Detect it here so the user
// learns why the tenant became unusable and how to fix it.
activeMalformed = "active" in raw && typeof raw.active !== "boolean";
// Materialize the tenant availability default so every config read from
// disk carries an explicit boolean. Legacy files without `active` stay
// enabled; `false` (explicit or normalized) gates command execution.
corp = { ...parsed, active: parsed.active ?? true };
} catch (error) {
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
continue;
}
if (activeMalformed) {
activeWarnings.push({ dir, file, corpId: corp.id });
}
byId.set(corp.id, { config: corp, path: fullPath });
}
}
@@ -144,6 +161,19 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
console.error(`👉 Next action: seal-use doctor (检查配置文件格式与权限)`);
}
const freshActive = activeWarnings.filter((item) => {
const key = `${item.dir}/${item.file}`;
if (warnedActiveCorpFiles.has(key)) return false;
warnedActiveCorpFiles.add(key);
return true;
});
for (const item of freshActive) {
console.error(
`⚠️ 企业配置 ${item.dir}/${item.file} 的 active 字段值非法(只能是 true/false),企业 ${item.corpId} 已按禁用处理;仍可检索,但指向它的命令会被阻断。`
);
console.error(`👉 Next action: seal-use corps enable ${item.corpId} --confirm (或把配置修正为 "active": true)`);
}
return Array.from(byId.values());
}
@@ -268,6 +298,9 @@ export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): Co
}
}
const validated = CorpConfigSchema.parse(merged);
writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`);
return validated;
// Keep `active` explicit on disk after any config update (including ones that
// predate the field), matching the materialized value from loadCorpConfigs().
const normalized: CorpConfig = { ...validated, active: validated.active ?? true };
writeSecureFile(filePath, `${JSON.stringify(normalized, null, 2)}\n`);
return normalized;
}
+81
View File
@@ -1,4 +1,6 @@
import { describe, expect, test } from "bun:test";
import { CliError } from "../errors.js";
import { isCorpActive } from "./active.js";
import { CorpConfig } from "./types.js";
import { CorpContext, resolveCorpConfig } from "./manager.js";
@@ -99,3 +101,82 @@ describe("resolveCorpConfig", () => {
).id).toBe("corp-b");
});
});
describe("resolveCorpConfig tenant gate", () => {
const variants: Array<{ label: string; source: CorpConfig["source"] }> = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://off.sealai.cc",
expiresIn: 3600,
staffId: "seal"
}
}
];
const withSource = (id: string, source: CorpConfig["source"], active?: boolean): CorpConfig =>
({ ...corp(id), source, active });
for (const { label, source } of variants) {
test(`${label}: blocks an explicitly disabled corp with exit 14 and a recovery hint`, () => {
const disabled = withSource("off", source, false);
expect(isCorpActive(disabled)).toBe(false);
let caught: unknown;
try {
resolveCorpConfig([disabled], { stateful: false, corpId: "off" });
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(CliError);
expect((caught as CliError).exitCode).toBe(14);
expect((caught as CliError).message).toContain("已禁用");
expect((caught as CliError).nextAction).toContain("seal-use corps enable off");
});
test(`${label}: blocks case-insensitive and by-name resolution of a disabled corp`, () => {
const disabled = { ...withSource("Off-Corp", source, false), name: "Disabled Corp" };
expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "off-corp" })).toThrow("已禁用");
expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "disabled corp" })).toThrow("已禁用");
});
test(`${label}: blocks a disabled stateful default and first-corp fallback`, () => {
const disabled = withSource("off", source, false);
expect(() => resolveCorpConfig(
[disabled, corp("on")],
{ stateful: true, defaultCorpId: "off" }
)).toThrow("已禁用");
expect(() => resolveCorpConfig([disabled, corp("on")], { stateful: true })).toThrow("已禁用");
});
test(`${label}: allowDisabled resolves a disabled corp for status management only`, () => {
const disabled = withSource("off", source, false);
expect(resolveCorpConfig(
[disabled], { stateful: false, corpId: "off", allowDisabled: true }
).id).toBe("off");
});
test(`${label}: an active corp is unaffected by a disabled one in the same directory`, () => {
const disabled = withSource("off", source, false);
const enabled = withSource("on", source, true);
expect(resolveCorpConfig(
[disabled, enabled], { stateful: false, corpId: "on" }
).id).toBe("on");
expect(resolveCorpConfig([corp("legacy")], { stateful: false, corpId: "legacy" }).id).toBe("legacy");
});
}
});
+20 -5
View File
@@ -1,11 +1,26 @@
import { validationError } from "../errors.js";
import { assertCorpActive } from "./active.js";
import { CorpConfig, GlobalConfig } from "./types.js";
export type CorpResolveOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId"> & {
corpId?: string;
/** Only the tenant status-management commands (`corps enable/disable`) may resolve a disabled corp. */
allowDisabled?: boolean;
};
export function resolveCorpConfig(
corps: CorpConfig[],
options: Pick<GlobalConfig, "stateful" | "defaultCorpId"> & { corpId?: string },
options: CorpResolveOptions,
candidates: string[] = []
): CorpConfig {
// Every successful lookup passes through the same gate. This is the single
// choke point for CLI commands, MCP gateway commands, replay source/target
// resolution and background workers — a disabled tenant is never executable.
const accept = (found: CorpConfig): CorpConfig => {
if (!options.allowDisabled) assertCorpActive(found);
return found;
};
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
? options.defaultCorpId?.trim() || undefined
@@ -14,11 +29,11 @@ export function resolveCorpConfig(
if (selectedCorpId) {
const exact = corps.find((item) => item.id === selectedCorpId);
if (exact) return exact;
if (exact) return accept(exact);
const caseInsensitive = corps.find((item) => item.id.toLowerCase() === selectedCorpId.toLowerCase());
if (caseInsensitive) return caseInsensitive;
if (caseInsensitive) return accept(caseInsensitive);
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
if (byName) return byName;
if (byName) return accept(byName);
throw validationError(`No enterprise config found for ${selectedCorpId}`);
}
@@ -28,7 +43,7 @@ export function resolveCorpConfig(
}
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
if (firstCorp) return accept(firstCorp);
throw validationError("No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories"));
+67
View File
@@ -5,6 +5,7 @@ import {
SealCookieMapSchema,
SealHeaderMapSchema
} from "./types.js";
import { isCorpActive } from "./active.js";
describe("CorpConfigSchema", () => {
test("accepts Hose key/password aliases", () => {
@@ -180,6 +181,72 @@ describe("CorpConfigSchema", () => {
});
});
describe("CorpConfigSchema.active (parity across sources)", () => {
const variants = [
{
label: "hose",
source: {
type: "hose" as const,
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal" as const,
token: "seal-token",
sealUrl: "https://seal.sealai.cc"
}
}
];
for (const { label, source } of variants) {
test(`${label}: a legacy config without active stays enabled`, () => {
const config = CorpConfigSchema.parse({
id: `${label}-legacy`,
name: "Legacy Corp",
source
});
expect(String(config.source.type)).toBe(label);
expect(config.active).toBeUndefined();
expect(isCorpActive(config)).toBe(true);
});
test(`${label}: accepts explicit active true and false`, () => {
const enabled = CorpConfigSchema.parse({
id: `${label}-on`, name: "Enabled Corp", source, active: true
});
const disabled = CorpConfigSchema.parse({
id: `${label}-off`, name: "Disabled Corp", source, active: false
});
expect(enabled.active).toBe(true);
expect(isCorpActive(enabled)).toBe(true);
expect(disabled.active).toBe(false);
expect(isCorpActive(disabled)).toBe(false);
});
test(`${label}: a malformed active value fails closed to disabled instead of dropping the config`, () => {
for (const malformed of ["false", "true", null, 0, 1, {}, []]) {
const result = CorpConfigSchema.safeParse({
id: `${label}-bad`, name: "Bad Corp", source, active: malformed
});
if (!result.success) {
throw new Error(`config rejected for active=${JSON.stringify(malformed)}`);
}
expect(result.data.active).toBe(false);
expect(isCorpActive(result.data)).toBe(false);
}
});
}
});
describe("Seal custom header schemas", () => {
test("rejects an Authorization header supplied through config", () => {
expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false);
+11
View File
@@ -112,6 +112,17 @@ export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("pro
export const CorpConfigSchema = z.object({
id: z.string(),
name: z.string(),
// Tenant availability gate. It lives on the enterprise, NOT on a source, so
// `hose` and `seal` sources share exactly one switch and cannot diverge.
// Fail-closed three-way semantics:
// - absent -> undefined -> enabled (legacy configs, hand-built
// CorpConfig objects; materialized to true on read)
// - explicit boolean -> used as-is
// - malformed value -> `.catch(false)` -> DISABLED, never silently enabled
// A bad value must not drop the whole file (which would hide the enterprise
// from search and surface as a misleading "no enterprise config found").
// Disabling never affects `corps list/search` visibility.
active: z.boolean().optional().catch(false),
seal: SealEndpointSchema,
source: SealSourceSchema,
auth: CorpAuthConfigSchema,
+5 -2
View File
@@ -27,7 +27,8 @@ import file23 from "../../skills/seal-use/references/rule-lightweight.md" with {
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/tenant-status.md" with { type: "text" };
import file28 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -51,7 +52,8 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/rule-lint.md": file24,
"references/sealai-browser-rum.md": file25,
"references/staging-simulation-workflow.md": file26,
"references/webhook-resource-pack.md": file27,
"references/tenant-status.md": file27,
"references/webhook-resource-pack.md": file28,
};
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
@@ -91,5 +93,6 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/rule-lint.md",
"references/sealai-browser-rum.md",
"references/staging-simulation-workflow.md",
"references/tenant-status.md",
"references/webhook-resource-pack.md",
];
+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(),
+64
View File
@@ -1,7 +1,9 @@
import { describe, expect, test } from "bun:test";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
createServer,
@@ -207,6 +209,68 @@ describe("seal-use MCP server", () => {
}
});
test("both MCP gateways refuse commands naming a disabled tenant", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-mcp-disabled-tenant-"));
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
writeFileSync(join(enterprises, "off.json"), JSON.stringify({
id: "off",
name: "Disabled Corp",
active: false,
seal: { url: "https://off.sealai.cc" },
source: { type: "seal", token: "seal-token", sealUrl: "https://off.sealai.cc" },
auth: { refreshTtl: 300 }
}));
const envKeys = [
"SEAL_USE_ENTERPRISES_DIR",
"SEAL_USE_CONFIG_FILE",
"SEAL_USE_TOKEN_STORE",
"SEAL_DISABLE_BG_UPDATE"
] as const;
const originals = Object.fromEntries(envKeys.map((key) => [key, process.env[key]]));
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_DISABLE_BG_UPDATE = "1";
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-use-disabled-tenant-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const read = await client.callTool({
name: SEAL_USE_MCP_TOOL_NAME,
arguments: { command: "seal-use corps get off" }
});
expect(read.isError).toBe(true);
const readText = (read.content as Array<{ type: "text"; text: string }>)[0]?.text ?? "";
expect(readText).toContain("已禁用");
expect(readText).toContain("seal-use corps enable off");
const write = await client.callTool({
name: SEAL_USE_MCP_WRITE_TOOL_NAME,
arguments: { command: "seal-use rules list --corp off" }
});
expect(write.isError).toBe(true);
const writeText = (write.content as Array<{ type: "text"; text: string }>)[0]?.text ?? "";
expect(writeText).toContain("已禁用");
} finally {
await Promise.allSettled([client.close(), server.close()]);
for (const key of envKeys) {
const value = originals[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
rmSync(root, { recursive: true, force: true });
}
});
test("does not advertise tools when MCP is disabled", async () => {
const server = createServer({ enableCli: false });
const client = new Client({ name: "seal-home-disabled-test", version: "1.0.0" });