Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e88f472b50 | ||
|
|
1ddf6db9e8 | ||
|
|
4b92d397df | ||
|
|
d25c09c3be | ||
|
|
03189c072d | ||
|
|
1a023f9996 | ||
|
|
0ddd8283fe | ||
|
|
b980c60c3a | ||
|
|
67cd168ed4 | ||
|
|
8bc1401eae | ||
|
|
c572cba842 | ||
|
|
71845c35e7 | ||
|
|
8ecadbb124 | ||
|
|
dec52cf5fa | ||
|
|
b49e3a6ea0 | ||
|
|
0ff3d9a313 | ||
|
|
634f0e2b78 | ||
|
|
9ec46b244e | ||
|
|
cb07fad536 | ||
|
|
f454d62be1 | ||
|
|
382fc1a7ae | ||
|
|
a5b504d7a3 | ||
|
|
0a1eb015fb | ||
|
|
8c9f102931 | ||
|
|
5c46c9bcc4 | ||
|
|
a885d1478e |
No files matched your search
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.17",
|
||||
"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"
|
||||
|
||||
@@ -7,6 +7,45 @@ 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
|
||||
- Merge pull request #278 from yunyingk/mac15/official-rules-export
|
||||
- feat: 增加 SealAI 官方规则 CSV 导出
|
||||
|
||||
|
||||
## [0.11.18] - 2026-11-02
|
||||
|
||||
### Added
|
||||
- Merge pull request #276 from yunyingk/mac15/sqlite-review-and-auth-session-pool
|
||||
- feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环
|
||||
- Merge pull request #275 from yunyingk/mac15/fix-update-clean-test-isolation
|
||||
- test(update): 为 cleanStaleBinaries 增加临时目录沙箱隔离
|
||||
|
||||
|
||||
## [0.11.17] - 2026-10-29
|
||||
|
||||
### Added
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.17",
|
||||
"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",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.17: 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.17
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.17)
|
||||
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`。
|
||||
|
||||
## 规则编号重排:两次调用
|
||||
|
||||
@@ -147,6 +149,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
||||
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
|
||||
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
|
||||
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
|
||||
| SealAI 浏览器会话回放、RUM telemetry 接口 | `references/sealai-browser-rum.md` | 仅在排查浏览器录制/回放采集时读取;不要用于审核业务数据导出 |
|
||||
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
|
||||
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
|
||||
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
|
||||
@@ -154,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` |
|
||||
@@ -162,6 +166,6 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
|
||||
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量、人机分歧日常复核与静音协议 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
@@ -72,7 +74,7 @@ seal-use rules version <versionNumber|latest> [--corp <corpId>]
|
||||
seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]
|
||||
seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]
|
||||
seal-use rules linters [--corp <corpId>]
|
||||
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
|
||||
seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]
|
||||
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
|
||||
seal-use rules push status [--file <path>] [--corp <corpId>]
|
||||
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
|
||||
@@ -129,11 +131,14 @@ seal-use report validate <报告.md>
|
||||
seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]
|
||||
seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]
|
||||
seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]
|
||||
seal-use report review unreviewed [--limit <n>] [--days <n>] [--all] [--corp <corpId>]
|
||||
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>]
|
||||
@@ -367,7 +372,8 @@ Approval rule maintenance:
|
||||
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
|
||||
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
|
||||
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
|
||||
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
|
||||
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]` saves the current draft or selected published snapshot as local JSON.
|
||||
- `seal-use rules pull --official [--out <file>] [--corp <corpId>]` calls the SealAI server's CSV export endpoint and saves its returned CSV unchanged (defaults to Downloads). `--official` cannot be combined with `--version`; this endpoint exports the server's current rules and does not expose historical versions.
|
||||
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
|
||||
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
|
||||
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
|
||||
|
||||
@@ -238,6 +238,49 @@ seal-use report render <输出目录>/审核报告.md --out <输出目录>/审
|
||||
seal-use report review import <输出目录>/明细台账.xlsx --corp <corpId>
|
||||
```
|
||||
|
||||
### 模式 C:日常增量少量多次复核(Daily Incremental Triage & Silence Protocol)
|
||||
|
||||
**核心契约**:终端用户不敲命令,所有 CLI 指令均由 AI Agent 调度执行。Agent 负责向人类温和征求意见,并严格尊重人类的拒绝意愿,绝不重复打扰。拒绝将机制当作黑盒,Agent 必须透彻理解其背后的数据边界与频控协议。
|
||||
|
||||
#### 1. 架构透底:数据资产与时效边界(Agent 上下文认知)
|
||||
- **本地单机存储**:所有分歧单据与人工复核裁决,均物理持久化在用户本机的 SQLite 数据库(`~/.config/seal-use/state/reviews.sqlite`),**绝不向云端、合思 OpenAPI 或 Seal 平台上传**。
|
||||
- **时效窗口(近 30 天活跃期)**:CLI 默认只关注最近 30 天内发生的单据(`maxAgeDays = 30`)。超过 30 天的历史单据自动归入离线沉淀归档,日常命令中完全静默,绝不拿半年前的陈年旧账打扰用户(若审计需要,可显式加 `--all` 或 `--days <n>` 检索)。
|
||||
- **动态频控(5 小时滑动窗口)**:同一个企业距上次提示若不足 5 小时,CLI 绝对静默;满 5 小时后若检测到近期有未整理的分歧,才会在日常企业命令完成后的 `stderr` 信道轻提示一次。
|
||||
|
||||
#### 2. 触发信号(stderr 诊断流)
|
||||
CLI 在执行任意企业相关命令时,若触发条件满足,会在 `stderr` 输出透明指引:
|
||||
```text
|
||||
ℹ️ [review-reminder] 检测到企业「华铁大黄蜂」在近 30 天内有 3 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。
|
||||
👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp <corpId> 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp <corpId>
|
||||
```
|
||||
|
||||
#### 3. Agent 呈报人类的对话规范(轻量顺带,零侵入)
|
||||
必须在**彻底完成用户当前的主要任务后**,在回复末尾顺便以极简、自然、有安全感的语言征求意见:
|
||||
> *“本次任务已完成。另外顺便提一句,检测到「华铁大黄蜂」近 30 天有 3 笔单据人工审批和 AI 判定不一致(数据仅保存在你本机电脑),有空的话要顺手确认一下吗?还是改天再说?”*
|
||||
|
||||
#### 4. 人类拒绝时的静音规范(24 小时绝对抑制,尊重用户意愿)
|
||||
若用户表态 *“今天不想审 / 改天吧 / 稍后 / 别提醒我 / 太忙了”*:
|
||||
- ❌ **Agent 严禁反复复读打扰用户**;
|
||||
- **Agent 必须立即静默执行静音命令**:
|
||||
```bash
|
||||
seal-use report review dismiss --corp <corpId> --hours 24
|
||||
```
|
||||
- 系统将该企业静音 24 小时,在此期间无论 5 小时滑动窗口如何,后续命令都绝对闭嘴,Agent 也绝不再主动提起。
|
||||
|
||||
#### 5. 人类同意时的极速裁决流程(化整为零)
|
||||
若用户表示 *“看看是哪几笔”* 或 *“现在弄一下”*:
|
||||
- Agent 后台拉取未审清单:
|
||||
```bash
|
||||
seal-use report review unreviewed --corp <corpId> --limit 5
|
||||
```
|
||||
- Agent 将单据关键信息(单号、金额、事由、AI决策理由 vs 人工放行/驳回批注)呈报给用户;
|
||||
- 用户口头/打字表态(例如:“第1笔AI对,第2笔人工对”);
|
||||
- Agent 自动调用打标命令回写本地 SQLite 并核销待办:
|
||||
```bash
|
||||
seal-use report review set --corp <corpId> --sn <SN> --verdict ai_correct --note "用户确认发票抬头违规"
|
||||
```
|
||||
- 少量多次,10 秒钟整理完毕,月末出具商业汇报时所有分歧早已提前就绪!
|
||||
|
||||
---
|
||||
|
||||
## 六、标准 6 大章节深度剖析
|
||||
|
||||
@@ -60,6 +60,19 @@ seal-use rules get 0205 --record-id <recordId> --corp <corpId>
|
||||
|
||||
Returns `id`, `code`, `ruleCode`, `runtimeRuleId`, `description`, `scope`, `strictness`, `status`, and version metadata when reading from a published version.
|
||||
|
||||
## Pull the Official Server CSV
|
||||
|
||||
Use `rules pull --official` when the user wants the CSV generated by the SealAI rules page:
|
||||
|
||||
```bash
|
||||
seal-use rules pull --official --corp <corpId>
|
||||
seal-use rules pull --official --out <file.csv> --corp <corpId>
|
||||
```
|
||||
|
||||
This calls `GET /api/v1/rules/export/csv` with the configured Seal session. The observed response is a JSON envelope with a `data.csv` string. The command writes that string unchanged to a UTF-8 CSV file; it does not parse rows, rename or reorder columns, normalize line endings, or rebuild the workbook. The response is the official CSV export, not an XLSX file. The endpoint has no observed version parameter, so `--official` cannot be combined with `--version`; use `rules pull --version latest` for the latest published snapshot as JSON.
|
||||
|
||||
When `--out` is omitted, the CSV is saved to the user's Downloads directory. CLI stdout remains structured JSON with the output path and byte size.
|
||||
|
||||
## Search Rules Compactly
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# SealAI Browser RUM Replay Endpoint
|
||||
|
||||
This reference records the observed browser request to `gc-openway.hosecloud.com` for future diagnostics. It is not an approval or rule-data API.
|
||||
|
||||
## Observed request shape
|
||||
|
||||
- `POST /v1/write/rum/replay?token=...&to_headless=true&precision=ms`
|
||||
- `multipart/form-data` with a binary `segment` part and replay metadata such as `start`, `end`, `creation_reason`, `records_count`, `has_full_snapshot`, `index_in_view`, `source`, `sdk_name`, `sdk_version`, `env`, `service`, `app_id`, `session_id`, `view_id`, and `raw_segment_size`.
|
||||
- The captured request uses `app_id=seal_ai`, `source=browser`, and SDK name `df_web_rum_sdk`.
|
||||
- `x-datadog-*` request headers and the replay-specific fields indicate a Datadog RUM-compatible browser session replay ingestion/relay endpoint. This is an inference from the request shape; the response and server-side implementation have not been inspected.
|
||||
|
||||
## Operational boundary
|
||||
|
||||
- The `token` query value is credential material. Never copy it into source code, documentation, CLI output, or logs.
|
||||
- The uploaded `segment` contains browser replay telemetry. Do not treat it as approval decisions, audit rules, or business documents.
|
||||
- This endpoint is not part of normal Seal Use CLI operation. Do not embed browser fingerprint emulation or replay credentials in the distributed binary. If future diagnostics need browser replay, keep the adapter separate and use an authorized browser/test session.
|
||||
@@ -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`。
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -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>]");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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("已禁用");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { saveCorpConfig } from "../../core/config/repository.js";
|
||||
import {
|
||||
closeReviewsDb,
|
||||
recordDivergences
|
||||
} from "../../domains/seal/reports/pipeline/review-store.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
let tempDir: string;
|
||||
let originalFetch: typeof globalThis.fetch;
|
||||
const testCorp: CorpConfig = {
|
||||
id: "corp-triage-test",
|
||||
name: "测试分歧企业",
|
||||
environment: "production",
|
||||
seal: {
|
||||
url: "https://triage.sealai.cc",
|
||||
tenantSlug: "triage",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "dummy-token",
|
||||
sealUrl: "https://triage.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "u-triage",
|
||||
corpId: "corp-triage-test",
|
||||
tenantId: "t-triage",
|
||||
tenantSlug: "triage",
|
||||
provider: "seal"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
describe("report review CLI: 面向 Agent 的分歧待办查询与静音抑制", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "seal-report-review-cli-test-"));
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = join(tempDir, "enterprises");
|
||||
process.env.SEAL_USE_REVIEWS_STORE = join(tempDir, "reviews.sqlite");
|
||||
process.env.SEAL_USE_REVIEWS_DIR = join(tempDir, "reviews");
|
||||
saveCorpConfig(testCorp, { overwrite: true });
|
||||
|
||||
originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () => {
|
||||
return new Response(JSON.stringify({ rules: [], hasPendingDeletes: false }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
closeReviewsDb();
|
||||
delete process.env.SEAL_USE_ENTERPRISES_DIR;
|
||||
delete process.env.SEAL_USE_REVIEWS_STORE;
|
||||
delete process.env.SEAL_USE_REVIEWS_DIR;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("report review unreviewed 列出待整理分歧单据并附带 Agent 指引", async () => {
|
||||
recordDivergences(testCorp.id, [
|
||||
{
|
||||
corpId: testCorp.id,
|
||||
recordId: "run-div-1",
|
||||
sn: "SN-DIV-001",
|
||||
docTitle: "差旅申请单",
|
||||
amount: "¥800",
|
||||
aiDecision: "驳回",
|
||||
manualDecision: "通过",
|
||||
divergenceType: "AI驳回_人工通过",
|
||||
discoveredAt: Date.now()
|
||||
}
|
||||
]);
|
||||
|
||||
const result = await runCli([
|
||||
"report",
|
||||
"review",
|
||||
"unreviewed",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.corpId).toBe(testCorp.id);
|
||||
expect(parsed.count).toBe(1);
|
||||
expect(parsed.divergences[0].sn).toBe("SN-DIV-001");
|
||||
expect(parsed.guidance).toContain("Agent 上下文说明");
|
||||
expect(parsed.guidance).toContain("5 小时滑动窗口");
|
||||
});
|
||||
|
||||
test("report review dismiss 成功静音并在期限内抑制提示", async () => {
|
||||
recordDivergences(testCorp.id, [
|
||||
{
|
||||
corpId: testCorp.id,
|
||||
recordId: "run-div-1",
|
||||
sn: "SN-DIV-001",
|
||||
discoveredAt: Date.now()
|
||||
}
|
||||
]);
|
||||
|
||||
// 用户表示今天不想看,Agent 调度 dismiss 24小时
|
||||
const dismissRes = await runCli([
|
||||
"report",
|
||||
"review",
|
||||
"dismiss",
|
||||
"--hours",
|
||||
"24",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
expect(dismissRes.exitCode).toBe(0);
|
||||
const parsedDismiss = JSON.parse(dismissRes.stdout);
|
||||
expect(parsedDismiss.dismissed).toBe(true);
|
||||
expect(parsedDismiss.message).toContain("已为企业「测试分歧企业」静音分歧提醒 24 小时");
|
||||
});
|
||||
|
||||
test("stderr 注入:在日常命令完成时提示 Agent,dismiss 后不再提示", async () => {
|
||||
recordDivergences(testCorp.id, [
|
||||
{
|
||||
corpId: testCorp.id,
|
||||
recordId: "run-div-1",
|
||||
sn: "SN-DIV-001",
|
||||
discoveredAt: Date.now()
|
||||
}
|
||||
]);
|
||||
|
||||
// 运行一个常规的企业级数据命令(例如 rules count)
|
||||
const resBefore = await runCli([
|
||||
"rules",
|
||||
"count",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
// stderr 应注入面向 Agent 的提醒
|
||||
expect(resBefore.stderr).toContain("ℹ️ [review-reminder]");
|
||||
expect(resBefore.stderr).toContain("Agent 动作指引");
|
||||
|
||||
// Agent 调用 dismiss 静音
|
||||
await runCli([
|
||||
"report",
|
||||
"review",
|
||||
"dismiss",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
// 再次运行命令,stderr 不再打扰
|
||||
const resAfter = await runCli([
|
||||
"rules",
|
||||
"count",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
expect(resAfter.stderr).not.toContain("ℹ️ [review-reminder]");
|
||||
});
|
||||
|
||||
test("超过 30 天的历史旧单不触发日常命令 stderr 提醒", async () => {
|
||||
const oldTime = Date.now() - 60 * 24 * 3600 * 1000;
|
||||
recordDivergences(testCorp.id, [
|
||||
{
|
||||
corpId: testCorp.id,
|
||||
recordId: "run-old-1",
|
||||
sn: "SN-OLD-001",
|
||||
createdAt: oldTime,
|
||||
discoveredAt: oldTime
|
||||
}
|
||||
]);
|
||||
|
||||
const res = await runCli([
|
||||
"rules",
|
||||
"count",
|
||||
"--corp",
|
||||
testCorp.id
|
||||
]);
|
||||
|
||||
expect(res.stderr).not.toContain("ℹ️ [review-reminder]");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
@@ -16,6 +17,9 @@ import {
|
||||
loadReviews,
|
||||
reviewFilePath,
|
||||
writeReview,
|
||||
countUnreviewedDivergences,
|
||||
listUnreviewedDivergences,
|
||||
dismissDivergencePrompt,
|
||||
type MonthlyReportResult,
|
||||
buildReportLedgerCsv,
|
||||
buildReportLedgerXlsx,
|
||||
@@ -29,13 +33,22 @@ import type { ParsedArgs } from "../types.js";
|
||||
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
|
||||
if (Boolean(args.options.ledger) || action === "review") {
|
||||
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
|
||||
const corp = {
|
||||
corpId,
|
||||
id: corpId,
|
||||
name: corpId,
|
||||
corpName: corpId,
|
||||
source: { source: "seal", sealUrl: "" }
|
||||
} as unknown as CorpConfig;
|
||||
let corp: CorpConfig;
|
||||
try {
|
||||
const { selectCorp } = await import("../helpers.js");
|
||||
corp = selectCorp(corpId);
|
||||
} 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,
|
||||
name: corpId,
|
||||
corpName: corpId,
|
||||
source: { source: "seal", sealUrl: "" }
|
||||
} as unknown as CorpConfig;
|
||||
}
|
||||
await handleReportCommand(action, {} as any, corp, args);
|
||||
return;
|
||||
}
|
||||
@@ -282,6 +295,43 @@ export async function handleReportCommand(
|
||||
if (action === "review") {
|
||||
const sub = args.command[2]; // set | list | import
|
||||
|
||||
if (sub === "unreviewed" || sub === "pending" || sub === "triage") {
|
||||
const limit = numberOption(args.options.limit) ?? 20;
|
||||
const all = booleanOption(args.options.all);
|
||||
const days = all ? 0 : (numberOption(args.options.days) ?? 30);
|
||||
const items = listUnreviewedDivergences(corp.id, limit, days);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
corpName: corp.name,
|
||||
window: {
|
||||
recencyDays: days > 0 ? days : "all",
|
||||
promptThrottleHours: 5,
|
||||
storage: "~/.config/seal-use/state/reviews.sqlite"
|
||||
},
|
||||
count: items.length,
|
||||
totalPending: countUnreviewedDivergences(corp.id, days),
|
||||
divergences: items,
|
||||
guidance:
|
||||
"Agent 上下文说明:\n" +
|
||||
"1. 数据来源:上述分歧来自本地 SQLite (~/.config/seal-use/state/reviews.sqlite),由报表或审批流发现 AI 与人工结论相反,仅保存在用户本机,不上传云端。\n" +
|
||||
"2. 频控规则:CLI 默认只关注近 30 天内单据(排除陈年旧账),且每 5 小时滑动窗口最多提醒一次。\n" +
|
||||
"3. 交互流程:请在完成主任务后以简短摘要向用户征询;用户确认后执行 'seal-use report review set --corp <corpId> --sn <SN> --verdict <ai_correct|manual_correct|both_correct|both_wrong|unclear>' 回写;用户表示暂不处理时,立即执行 'seal-use report review dismiss --corp <corpId> --hours 24' 静音 24 小时,切勿重复打扰。"
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "dismiss") {
|
||||
const hours = numberOption(args.options.hours) ?? 24;
|
||||
const until = dismissDivergencePrompt(corp.id, hours);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
dismissed: true,
|
||||
dismissedUntil: new Date(until).toISOString(),
|
||||
message: `已为企业「${corp.name}」静音分歧提醒 ${hours} 小时。在此期间不会重复向用户提示。`
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "list") {
|
||||
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
|
||||
const reviews = loadReviews(corp.id, scope);
|
||||
@@ -341,7 +391,7 @@ export async function handleReportCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
|
||||
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', 'unreviewed', 'dismiss', or 'import'.`);
|
||||
}
|
||||
|
||||
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
|
||||
|
||||
@@ -327,6 +327,19 @@ export async function handleRulesCommand(
|
||||
if (action === "pull") {
|
||||
const version = resolveVersionOption(args, maybeName);
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
|
||||
if (booleanOption(args.options.official) === true) {
|
||||
if (version) {
|
||||
throw usageError("rules pull --official uses SealAI's official current-rules CSV export and cannot be combined with --version.");
|
||||
}
|
||||
await runCapability(
|
||||
"sealApprovalRulesExportCsv",
|
||||
client!,
|
||||
corp,
|
||||
{ out },
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
await runCapability(
|
||||
"sealApprovalRulesPull",
|
||||
client!,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -349,8 +349,23 @@ describe("update installation modes", () => {
|
||||
expect(SYSTEM_BINARY_PATH).toBe("/usr/local/bin/seal-use");
|
||||
});
|
||||
|
||||
test("cleanStaleBinaries ignores activePath and returns list of cleaned files", () => {
|
||||
const cleaned = cleanStaleBinaries(SYSTEM_BINARY_PATH);
|
||||
expect(Array.isArray(cleaned)).toBe(true);
|
||||
test("cleanStaleBinaries ignores activePath and returns list of cleaned files in isolated sandbox", () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "seal-use-clean-test-"));
|
||||
try {
|
||||
const fakeActive = join(tempDir, "active-bin");
|
||||
const fakeStale = join(tempDir, "stale-bin");
|
||||
const fakeUntouched = join(tempDir, "untouched-bin");
|
||||
writeFileSync(fakeActive, "active");
|
||||
writeFileSync(fakeStale, "stale");
|
||||
writeFileSync(fakeUntouched, "untouched");
|
||||
|
||||
const cleaned = cleanStaleBinaries(fakeActive, [fakeActive, fakeStale]);
|
||||
expect(cleaned).toEqual([fakeStale]);
|
||||
expect(existsSync(fakeActive)).toBe(true);
|
||||
expect(existsSync(fakeStale)).toBe(false);
|
||||
expect(existsSync(fakeUntouched)).toBe(true);
|
||||
} finally {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,7 @@ export function isPathWritable(targetPath: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanStaleBinaries(activePath: string): string[] {
|
||||
export function cleanStaleBinaries(activePath: string, candidateOverrides?: string[]): string[] {
|
||||
const cleaned: string[] = [];
|
||||
const home = homedir();
|
||||
const userBinary = getUserBinaryPath();
|
||||
@@ -49,11 +49,13 @@ export function cleanStaleBinaries(activePath: string): string[] {
|
||||
const homebrewBinary = "/opt/homebrew/bin/seal-use";
|
||||
const homebrewAlias = "/opt/homebrew/bin/seal-home";
|
||||
|
||||
const candidates = [homebrewBinary, homebrewAlias];
|
||||
if (activePath === systemBinary) {
|
||||
candidates.push(userBinary, userAlias);
|
||||
} else if (activePath === userBinary) {
|
||||
candidates.push(systemBinary, systemAlias);
|
||||
const candidates = candidateOverrides ? [...candidateOverrides] : [homebrewBinary, homebrewAlias];
|
||||
if (!candidateOverrides) {
|
||||
if (activePath === systemBinary) {
|
||||
candidates.push(userBinary, userAlias);
|
||||
} else if (activePath === userBinary) {
|
||||
candidates.push(systemBinary, systemAlias);
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
|
||||
+57
-7
@@ -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: "测试配对与验证",
|
||||
@@ -340,8 +362,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "pull",
|
||||
summary: "Export rules to local JSON file",
|
||||
usage: ["seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]"]
|
||||
summary: "Pull rules as local JSON, or use --official for the server-generated CSV",
|
||||
usage: ["seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--official", description: "Call SealAI's official CSV export endpoint and save its returned CSV unchanged; cannot be combined with --version" },
|
||||
{ flag: "--version <number|latest>", description: "Pull a published version as JSON; unavailable with --official" },
|
||||
{ flag: "--out <file>", description: "Output path; defaults to ./rules.local.json for JSON or Downloads for official CSV" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "push",
|
||||
@@ -551,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" }
|
||||
]
|
||||
@@ -766,7 +793,29 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--note <text>", description: "Optional adjudication note" },
|
||||
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
|
||||
],
|
||||
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
|
||||
description: "Local SQLite store with companion JSONL (~/.config/seal-use/state/reviews.sqlite). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
|
||||
},
|
||||
{
|
||||
name: "review unreviewed",
|
||||
summary: "List unreviewed human-AI divergence records for incremental triaging",
|
||||
usage: ["seal-use report review unreviewed [--limit <n>] [--days <n>] [--all] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--limit <n>", description: "Max unreviewed items to return (default 20)" },
|
||||
{ flag: "--days <n>", description: "Only return records created within recent days (default 30)" },
|
||||
{ flag: "--all", description: "Include all historical unreviewed records regardless of age" },
|
||||
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
|
||||
],
|
||||
description: "Returns unadjudicated diverged records from local SQLite (~/.config/seal-use/state/reviews.sqlite). CLI throttles reminder notifications on a 5-hour sliding window and filters to recent 30 days to avoid ancient debt. Use this command to fetch items, present a natural-language summary to the user, and record verdicts with 'report review set'."
|
||||
},
|
||||
{
|
||||
name: "review dismiss",
|
||||
summary: "Suppress divergence reminders for a tenant when the user declines reviewing",
|
||||
usage: ["seal-use report review dismiss [--hours <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--hours <n>", description: "Hours to suppress reminders (default 24)" },
|
||||
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
|
||||
],
|
||||
description: "Mutes CLI divergence prompts for the enterprise for N hours (default 24h) when the user declines reviewing. Agents must call this immediately when the user says 'not now' or 'later' to ensure zero repeated disruption."
|
||||
},
|
||||
{
|
||||
name: "review list",
|
||||
@@ -800,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
@@ -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()
|
||||
);
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -27,6 +27,10 @@ describe("parseArgs flag handling", () => {
|
||||
expect(parseArgs(["corps", "list", "--all"]).options.all).toBe(true);
|
||||
});
|
||||
|
||||
test("rules pull official is parsed as a boolean flag", () => {
|
||||
expect(parseArgs(["rules", "pull", "--official"]).options.official).toBe(true);
|
||||
});
|
||||
|
||||
test("value flags consume exactly one token", () => {
|
||||
const parsed = parseArgs(["approval-runs", "list", "--limit", "25", "--status", "completed"]);
|
||||
|
||||
|
||||
+6
-6
@@ -27,11 +27,11 @@ 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",
|
||||
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||
"no-wait", "noWait", "official", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
@@ -47,15 +47,15 @@ export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
|
||||
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||
"content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "days",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||
"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",
|
||||
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration",
|
||||
"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",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
@@ -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",
|
||||
|
||||
+24
-1
@@ -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",
|
||||
@@ -349,9 +353,27 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
|
||||
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
|
||||
|
||||
const maybePromptDivergences = async () => {
|
||||
if (area === "report" && action === "review") return;
|
||||
try {
|
||||
const { countUnreviewedDivergences, shouldPromptDivergence } = await import(
|
||||
"../domains/seal/reports/pipeline/review-store.js"
|
||||
);
|
||||
const count = countUnreviewedDivergences(corp.id, 30);
|
||||
if (count > 0 && shouldPromptDivergence(corp.id)) {
|
||||
console.error(
|
||||
`ℹ️ [review-reminder] 检测到企业「${corp.name}」在近 30 天内有 ${count} 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。\n👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp ${corp.id} 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp ${corp.id}`
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// 容错降级,不阻断主流程
|
||||
}
|
||||
};
|
||||
|
||||
const corpCommand = CORP_COMMANDS[area];
|
||||
if (corpCommand) {
|
||||
await corpCommand(args, corp);
|
||||
await maybePromptDivergences();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -359,6 +381,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
if (clientCommand) {
|
||||
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
|
||||
await clientCommand(args, corp, client);
|
||||
await maybePromptDivergences();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface SealDelegateSealSession {
|
||||
sealUrl: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
sessionCookie?: string;
|
||||
user: Record<string, unknown>;
|
||||
tenant: Record<string, unknown>;
|
||||
}
|
||||
@@ -199,11 +200,54 @@ export async function exchangeSealDelegateLink(
|
||||
sealUrl,
|
||||
token: bearerToken,
|
||||
expiresIn,
|
||||
sessionCookie: sessionCookie || undefined,
|
||||
user,
|
||||
tenant
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用 SealAI 服务端为当前租户创建新的协助授权链接(最长支持 168 小时 / 7 天)
|
||||
*/
|
||||
export async function createSealDelegationLink(
|
||||
sealUrl: string,
|
||||
options?: {
|
||||
cookie?: string;
|
||||
token?: string;
|
||||
expiresInHours?: number;
|
||||
note?: string;
|
||||
customHeaders?: Record<string, string>;
|
||||
}
|
||||
): Promise<{ link: string; token: string; expiresInHours: number }> {
|
||||
const expiresInHours = options?.expiresInHours ?? 168;
|
||||
const note = options?.note ?? "权限续期";
|
||||
const headers: Record<string, string> = {
|
||||
...options?.customHeaders
|
||||
};
|
||||
if (options?.cookie) {
|
||||
headers.Cookie = options.cookie;
|
||||
}
|
||||
|
||||
const client = createSealClientForUrl(sealUrl, options?.token, headers);
|
||||
const resp = await client
|
||||
.post("api/v1/delegation/create", {
|
||||
json: { expiresInHours, note }
|
||||
})
|
||||
.json<{
|
||||
data?: { link?: string; token?: string };
|
||||
link?: string;
|
||||
token?: string;
|
||||
}>();
|
||||
|
||||
const link = resp.data?.link ?? resp.link;
|
||||
const token = resp.data?.token ?? resp.token;
|
||||
if (!link || !token) {
|
||||
throw new Error("Seal create delegation did not return a valid link/token");
|
||||
}
|
||||
|
||||
return { link, token, expiresInHours };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* Link-type scoring (classification by score)
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import {
|
||||
clearSealToken,
|
||||
getSealSessionForCorp,
|
||||
recoverSealSessionForCorp,
|
||||
renewNativeSealSession
|
||||
} from "./seal.js";
|
||||
import {
|
||||
getSealDelegateAuthCache,
|
||||
getSealSession,
|
||||
setSealDelegateAuthCache
|
||||
} from "./token-store.js";
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
let tempDir: string;
|
||||
let storePath: string;
|
||||
|
||||
const fixtureCorp: CorpConfig = {
|
||||
id: "test-delegate-corp",
|
||||
name: "测试委托租户",
|
||||
environment: "production",
|
||||
seal: {
|
||||
url: "https://mytenant.sealai.cc",
|
||||
tenantSlug: "mytenant",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "initial-static-token",
|
||||
sealUrl: "https://mytenant.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
|
||||
staffId: "u-123",
|
||||
corpId: "test-delegate-corp",
|
||||
tenantId: "t-456",
|
||||
tenantSlug: "mytenant",
|
||||
tenantName: "My Tenant",
|
||||
provider: "seal"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-"));
|
||||
storePath = join(tempDir, "tokens.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = storePath;
|
||||
clearSealToken(fixtureCorp.id);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
clearSealToken(fixtureCorp.id);
|
||||
delete process.env.SEAL_USE_TOKEN_STORE;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("无可用 Cookie 时安全返回 undefined,平滑回退到静态 token", async () => {
|
||||
const renewed = await renewNativeSealSession(fixtureCorp);
|
||||
expect(renewed).toBeUndefined();
|
||||
|
||||
const session = await getSealSessionForCorp(fixtureCorp);
|
||||
expect(session.token).toBe("initial-static-token");
|
||||
});
|
||||
|
||||
test("主 Cookie 有效时成功自动续期换发新 token,并轮转归档历史 Cookie", async () => {
|
||||
setSealDelegateAuthCache(fixtureCorp.id, {
|
||||
cookie: "__Secure-x-seal.session_token=old-cookie-token",
|
||||
backupCookies: []
|
||||
});
|
||||
|
||||
let delegationCreateCalledWithCookie = "";
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = new URL(
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
|
||||
);
|
||||
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
|
||||
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
delegationCreateCalledWithCookie = headers.get("cookie") || "";
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
link: "https://mytenant.sealai.cc/delegate?token=minted-delegation-token",
|
||||
token: "minted-delegation-token"
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/delegation/consume") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
userId: "u-123",
|
||||
userName: "Alice",
|
||||
tenantId: "t-456",
|
||||
tenantName: "My Tenant",
|
||||
delegationId: "del-new"
|
||||
}
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie":
|
||||
"__Secure-x-seal.session_token=fresh-cookie-token.sig; Path=/; HttpOnly; Secure"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/get-session") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
user: { id: "u-123", name: "Alice" },
|
||||
session: {
|
||||
token: "brand-new-bearer-token",
|
||||
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
user: { id: "u-123", name: "Alice" },
|
||||
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const renewed = await renewNativeSealSession(fixtureCorp);
|
||||
expect(renewed).toBeDefined();
|
||||
expect(renewed!.token).toBe("brand-new-bearer-token");
|
||||
expect(delegationCreateCalledWithCookie).toBe(
|
||||
"__Secure-x-seal.session_token=old-cookie-token"
|
||||
);
|
||||
|
||||
// 检查 tokens.json 中更新状态
|
||||
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
|
||||
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=fresh-cookie-token.sig");
|
||||
expect(delegateCache.backupCookies).toEqual(["__Secure-x-seal.session_token=old-cookie-token"]);
|
||||
|
||||
// 再次读取 session 命中新缓存
|
||||
const session = await getSealSessionForCorp(fixtureCorp);
|
||||
expect(session.token).toBe("brand-new-bearer-token");
|
||||
});
|
||||
|
||||
test("主 Cookie 失效时,依次由 backupCookies 兜底救险成功(断电超期场景)", async () => {
|
||||
// 模拟主 Cookie 已在服务端注销失效,但历史 backupCookies 中包含一份 30 天未过期的长效会话
|
||||
setSealDelegateAuthCache(fixtureCorp.id, {
|
||||
cookie: "expired-cookie",
|
||||
backupCookies: ["valid-backup-cookie"]
|
||||
});
|
||||
|
||||
const attemptedCookies: string[] = [];
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = new URL(
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
|
||||
);
|
||||
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
|
||||
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
const cookie = headers.get("cookie") || "";
|
||||
attemptedCookies.push(cookie);
|
||||
if (cookie === "expired-cookie") {
|
||||
return new Response(JSON.stringify({ error: { message: "Session expired" } }), {
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
link: "https://mytenant.sealai.cc/delegate?token=rescued-delegation-token",
|
||||
token: "rescued-delegation-token"
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/delegation/consume") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
userId: "u-123",
|
||||
userName: "Alice",
|
||||
tenantId: "t-456",
|
||||
tenantName: "My Tenant"
|
||||
}
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": "__Secure-x-seal.session_token=rescued-cookie.sig; Path=/; HttpOnly"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/get-session") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
session: {
|
||||
token: "rescued-bearer-token",
|
||||
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
user: { id: "u-123", name: "Alice" },
|
||||
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
const renewed = await renewNativeSealSession(fixtureCorp);
|
||||
expect(renewed).toBeDefined();
|
||||
expect(renewed!.token).toBe("rescued-bearer-token");
|
||||
expect(attemptedCookies).toEqual(["expired-cookie", "valid-backup-cookie"]);
|
||||
|
||||
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
|
||||
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=rescued-cookie.sig");
|
||||
expect(delegateCache.backupCookies).toContain("valid-backup-cookie");
|
||||
});
|
||||
|
||||
test("recoverSealSessionForCorp 在收到 401 时自动触发自愈", async () => {
|
||||
setSealDelegateAuthCache(fixtureCorp.id, {
|
||||
cookie: "valid-cookie",
|
||||
backupCookies: []
|
||||
});
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = new URL(
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
|
||||
);
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
link: "https://mytenant.sealai.cc/delegate?token=recovered-delegation-token",
|
||||
token: "recovered-delegation-token"
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/v1/delegation/consume") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { userId: "u-123", userName: "Alice", tenantId: "t-456", tenantName: "My Tenant" }
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": "__Secure-x-seal.session_token=recovered-cookie.sig"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/auth/get-session") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
session: {
|
||||
token: "recovered-bearer-token",
|
||||
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
user: { id: "u-123", name: "Alice" },
|
||||
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
|
||||
}
|
||||
}),
|
||||
{ headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
|
||||
// 假设当前正在使用 stale-token 遭遇 401
|
||||
const recovered = await recoverSealSessionForCorp(fixtureCorp, "initial-static-token");
|
||||
expect(recovered.token).toBe("recovered-bearer-token");
|
||||
|
||||
const sessionInStore = getSealSession(fixtureCorp.id);
|
||||
expect(sessionInStore?.token).toBe("recovered-bearer-token");
|
||||
});
|
||||
});
|
||||
+106
-2
@@ -1,8 +1,22 @@
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { getNativeSealSession } from "./native.js";
|
||||
import { getHoseSealSession } from "./hose.js";
|
||||
import { clearSealSession, getSealSession, setSealSession } from "./token-store.js";
|
||||
import {
|
||||
clearSealSession,
|
||||
getSealDelegateAuthCache,
|
||||
getSealSession,
|
||||
setSealDelegateAuthCache,
|
||||
setSealSession
|
||||
} from "./token-store.js";
|
||||
import { SealEnterpriseConfig, SealSession } from "./types.js";
|
||||
import {
|
||||
attemptCreateDelegationWithFallback,
|
||||
resolveCandidateCookies,
|
||||
rotateBackupCookies
|
||||
} from "./session-fallback.js";
|
||||
import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js";
|
||||
import { saveCorpConfig } from "../config/repository.js";
|
||||
import { formatBeijingIso } from "../config/timestamps.js";
|
||||
|
||||
const memoryCache = new Map<string, SealSession>();
|
||||
const pendingSessions = new Map<string, Promise<SealSession>>();
|
||||
@@ -11,12 +25,102 @@ function isExpired(session: SealSession, refreshTtl: number): boolean {
|
||||
return Date.now() >= session.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为原生 Seal 租户执行协助授权续期换发。
|
||||
* 优先使用主 Cookie,遇到失效或断电超期时依次由 backupCookies 兜底救险。
|
||||
*/
|
||||
export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSession | undefined> {
|
||||
const source = corp.source;
|
||||
if (source.type !== "seal") return undefined;
|
||||
|
||||
const authCache = getSealDelegateAuthCache(corp.id);
|
||||
const candidateCookies = resolveCandidateCookies(authCache);
|
||||
if (candidateCookies.length === 0) return undefined;
|
||||
|
||||
const sealUrl = corp.seal.url ?? source.sealUrl;
|
||||
|
||||
const delegation = await attemptCreateDelegationWithFallback(
|
||||
candidateCookies,
|
||||
async (candCookie) => {
|
||||
return createSealDelegationLink(sealUrl, {
|
||||
cookie: candCookie,
|
||||
token: source.token,
|
||||
expiresInHours: 168,
|
||||
note: "权限续期"
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const exchanged = await exchangeSealDelegateLink({
|
||||
sealUrl,
|
||||
delegateToken: delegation.token
|
||||
});
|
||||
|
||||
const newCookie = exchanged.sessionCookie;
|
||||
const backupCookies = rotateBackupCookies(authCache, newCookie, authCache.backupCookies, 5);
|
||||
|
||||
setSealDelegateAuthCache(corp.id, {
|
||||
cookie: newCookie ?? authCache.cookie,
|
||||
backupCookies,
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
|
||||
const nextSession: SealSession = {
|
||||
token: exchanged.token,
|
||||
expiresAt: Date.now() + exchanged.expiresIn * 1000,
|
||||
enterprise: {
|
||||
provider: source.provider ?? "seal",
|
||||
corpId: source.corpId ?? corp.id,
|
||||
staffId: source.staffId,
|
||||
sealUrl,
|
||||
tenantId: source.tenantId ?? (exchanged.tenant.id as string | undefined),
|
||||
tenantSlug:
|
||||
corp.seal.tenantSlug ??
|
||||
source.tenantSlug ??
|
||||
(exchanged.tenant.tenantSlug as string | undefined),
|
||||
tenantName: source.tenantName ?? (exchanged.tenant.name as string | undefined),
|
||||
raw: {
|
||||
sourceType: "seal"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 尝试静默同步更新静态租户配置中的 token 与 expiresAt,避免不读缓存时使用陈旧 token
|
||||
try {
|
||||
const updatedCorp: CorpConfig = {
|
||||
...corp,
|
||||
source: {
|
||||
...source,
|
||||
token: exchanged.token,
|
||||
expiresIn: exchanged.expiresIn,
|
||||
expiresAt: formatBeijingIso(nextSession.expiresAt)
|
||||
}
|
||||
};
|
||||
saveCorpConfig(updatedCorp, { overwrite: true });
|
||||
} catch {
|
||||
// 忽略无法写回配置文件的异常(如沙箱环境或只读配置)
|
||||
}
|
||||
|
||||
return nextSession;
|
||||
}
|
||||
|
||||
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||
switch (corp.source.type) {
|
||||
case "hose":
|
||||
return getHoseSealSession(corp);
|
||||
case "seal":
|
||||
case "seal": {
|
||||
const authCache = getSealDelegateAuthCache(corp.id);
|
||||
const candidates = resolveCandidateCookies(authCache);
|
||||
if (candidates.length > 0) {
|
||||
try {
|
||||
const renewed = await renewNativeSealSession(corp);
|
||||
if (renewed) return renewed;
|
||||
} catch {
|
||||
// 续签失败时平滑降级到原有静态凭证
|
||||
}
|
||||
}
|
||||
return getNativeSealSession(corp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
attemptCreateDelegationWithFallback,
|
||||
resolveCandidateCookies,
|
||||
rotateBackupCookies
|
||||
} from "./session-fallback.js";
|
||||
|
||||
describe("session-fallback", () => {
|
||||
test("rotateBackupCookies: 初始无历史 Cookie 时返回空备份", () => {
|
||||
const result = rotateBackupCookies(undefined, "cookie-1");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("rotateBackupCookies: 更新 Cookie 时自动归档上一份会话且排除当前 Cookie", () => {
|
||||
const existing = { cookie: "cookie-1", backupCookies: [] };
|
||||
const result = rotateBackupCookies(existing, "cookie-2");
|
||||
expect(result).toEqual(["cookie-1"]);
|
||||
});
|
||||
|
||||
test("rotateBackupCookies: 连续轮换自动去重并严格限制上限为 5 份", () => {
|
||||
let existing: { cookie?: string; backupCookies?: string[] } = {
|
||||
cookie: "cookie-1",
|
||||
backupCookies: []
|
||||
};
|
||||
|
||||
for (let i = 2; i <= 8; i++) {
|
||||
const newCookie = `cookie-${i}`;
|
||||
const backups = rotateBackupCookies(existing, newCookie);
|
||||
existing = { cookie: newCookie, backupCookies: backups };
|
||||
}
|
||||
|
||||
expect(existing.cookie).toBe("cookie-8");
|
||||
expect(existing.backupCookies?.length).toBe(5);
|
||||
expect(existing.backupCookies).toEqual([
|
||||
"cookie-7",
|
||||
"cookie-6",
|
||||
"cookie-5",
|
||||
"cookie-4",
|
||||
"cookie-3"
|
||||
]);
|
||||
});
|
||||
|
||||
test("resolveCandidateCookies: 优先返回当前主 Cookie 并依次排列历史长效备份", () => {
|
||||
expect(resolveCandidateCookies(undefined)).toEqual([]);
|
||||
expect(resolveCandidateCookies({})).toEqual([]);
|
||||
|
||||
const result = resolveCandidateCookies({
|
||||
cookie: "main-cookie",
|
||||
backupCookies: ["backup-1", "backup-2", "main-cookie"]
|
||||
});
|
||||
expect(result).toEqual(["main-cookie", "backup-1", "backup-2"]);
|
||||
});
|
||||
|
||||
test("attemptCreateDelegationWithFallback: 主 Cookie 成功时直接返回结果", async () => {
|
||||
const tried: (string | undefined)[] = [];
|
||||
const res = await attemptCreateDelegationWithFallback(
|
||||
["cookie-primary", "cookie-backup-1"],
|
||||
async (cookie) => {
|
||||
tried.push(cookie);
|
||||
return { link: "https://seal.cc/delegate?token=new", token: "new-token" };
|
||||
}
|
||||
);
|
||||
|
||||
expect(res.token).toBe("new-token");
|
||||
expect(tried).toEqual(["cookie-primary"]);
|
||||
});
|
||||
|
||||
test("attemptCreateDelegationWithFallback: 主 Cookie 失败时依次由备份 Cookie 兜底救险", async () => {
|
||||
const tried: (string | undefined)[] = [];
|
||||
const res = await attemptCreateDelegationWithFallback(
|
||||
["expired-cookie", "valid-backup-cookie"],
|
||||
async (cookie) => {
|
||||
tried.push(cookie);
|
||||
if (cookie === "expired-cookie") {
|
||||
throw new Error("401 Unauthorized");
|
||||
}
|
||||
return { link: "https://seal.cc/delegate?token=rescued", token: "rescued-token" };
|
||||
}
|
||||
);
|
||||
|
||||
expect(res.token).toBe("rescued-token");
|
||||
expect(tried).toEqual(["expired-cookie", "valid-backup-cookie"]);
|
||||
});
|
||||
|
||||
test("attemptCreateDelegationWithFallback: 全部候选失败时抛出最后的错误", async () => {
|
||||
await expect(
|
||||
attemptCreateDelegationWithFallback(
|
||||
["bad-1", "bad-2"],
|
||||
async (cookie) => {
|
||||
throw new Error(`Failed with ${cookie}`);
|
||||
}
|
||||
)
|
||||
).rejects.toThrow("Failed with bad-2");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* 维护会话 Cookie 备份池:当 Cookie 更新时,旧 Cookie(具备约 30 天长效寿命)推入备份池,最多保留 maxBackups 份
|
||||
*/
|
||||
export function rotateBackupCookies(
|
||||
existing?: { cookie?: string; backupCookies?: string[] },
|
||||
newCookie?: string,
|
||||
incomingBackups?: string[],
|
||||
maxBackups = 5
|
||||
): string[] {
|
||||
const currentCookie = newCookie !== undefined ? newCookie : existing?.cookie;
|
||||
const previousCookies = [
|
||||
...(incomingBackups || []),
|
||||
existing?.cookie,
|
||||
...(existing?.backupCookies || [])
|
||||
].filter((c): c is string => Boolean(c) && c !== currentCookie);
|
||||
return Array.from(new Set(previousCookies)).slice(0, maxBackups);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取候选会话 Cookie 列表(主 Cookie 优先,随后依次尝试历史长效会话,用于断电超期兜底救险)
|
||||
*/
|
||||
export function resolveCandidateCookies(existing?: {
|
||||
cookie?: string;
|
||||
backupCookies?: string[];
|
||||
}): string[] {
|
||||
const list = [existing?.cookie, ...(existing?.backupCookies || [])].filter(
|
||||
(c): c is string => Boolean(c)
|
||||
);
|
||||
return Array.from(new Set(list));
|
||||
}
|
||||
|
||||
export type DelegationCreator = (
|
||||
cookie: string | undefined
|
||||
) => Promise<{ link: string; token: string }>;
|
||||
|
||||
/**
|
||||
* 依次使用候选 Cookie 尝试创建新协助授权(实现断电停机超期后的长效 Session 兜底救险)
|
||||
*/
|
||||
export async function attemptCreateDelegationWithFallback(
|
||||
candidateCookies: string[],
|
||||
createFn: DelegationCreator
|
||||
): Promise<{ link: string; token: string }> {
|
||||
const cookiesToTry = candidateCookies.length > 0 ? candidateCookies : [undefined];
|
||||
let lastError: unknown = null;
|
||||
|
||||
for (const cookie of cookiesToTry) {
|
||||
try {
|
||||
const res = await createFn(cookie);
|
||||
if (res?.link && res?.token) {
|
||||
return res;
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError || new Error("未能成功换发新协助授权链接");
|
||||
}
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
clearSealSession,
|
||||
getCorpTokenCache,
|
||||
getHoseAuthCache,
|
||||
getSealDelegateAuthCache,
|
||||
getSealSession,
|
||||
setHoseAuthCache,
|
||||
setSealDelegateAuthCache,
|
||||
setSealSession
|
||||
} from "./token-store.js";
|
||||
import { SealSession } from "./types.js";
|
||||
@@ -113,6 +115,21 @@ describe("token-store", () => {
|
||||
expect(getCorpTokenCache("corp-hose")).toEqual({});
|
||||
});
|
||||
|
||||
test("sets, retrieves, and updates seal delegate auth cache", () => {
|
||||
makeTempStore();
|
||||
const delegateCache = {
|
||||
cookie: "__Secure-x-seal.session_token=initial-cookie",
|
||||
backupCookies: ["backup-1", "backup-2"],
|
||||
updatedAt: Date.now()
|
||||
};
|
||||
|
||||
setSealDelegateAuthCache("corp-delegate", delegateCache);
|
||||
expect(getSealDelegateAuthCache("corp-delegate")).toEqual(delegateCache);
|
||||
|
||||
clearCorpTokenCache("corp-delegate");
|
||||
expect(getSealDelegateAuthCache("corp-delegate")).toEqual({});
|
||||
});
|
||||
|
||||
test("falls back to reading legacy token store when primary does not exist", () => {
|
||||
const legacyPath = makeTempStore(true);
|
||||
const session: SealSession = {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { SEAL_CONFIG_DIR } from "../paths.js";
|
||||
import {
|
||||
CorpTokenCache,
|
||||
HoseAuthCache,
|
||||
SealDelegateAuthCache,
|
||||
SealSession,
|
||||
TokenStore,
|
||||
TokenStoreSchema
|
||||
@@ -93,6 +94,21 @@ export function setHoseAuthCache(corpId: string, hose: HoseAuthCache): void {
|
||||
});
|
||||
}
|
||||
|
||||
export function getSealDelegateAuthCache(corpId: string): SealDelegateAuthCache {
|
||||
return readStore()[corpId]?.sealDelegate ?? {};
|
||||
}
|
||||
|
||||
export function setSealDelegateAuthCache(corpId: string, sealDelegate: SealDelegateAuthCache): void {
|
||||
const store = readStore();
|
||||
writeStore({
|
||||
...store,
|
||||
[corpId]: {
|
||||
...store[corpId],
|
||||
sealDelegate
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function clearCorpTokenCache(corpId: string): void {
|
||||
const store = readStore();
|
||||
delete store[corpId];
|
||||
|
||||
@@ -28,9 +28,16 @@ export const HoseAuthCacheSchema = z.object({
|
||||
closeapi: TokenEntrySchema.optional()
|
||||
});
|
||||
|
||||
export const SealDelegateAuthCacheSchema = z.object({
|
||||
cookie: z.string().optional(),
|
||||
backupCookies: z.array(z.string()).optional(),
|
||||
updatedAt: z.number().optional()
|
||||
});
|
||||
|
||||
export const CorpTokenCacheSchema = z.object({
|
||||
seal: SealSessionSchema.optional(),
|
||||
hose: HoseAuthCacheSchema.optional()
|
||||
hose: HoseAuthCacheSchema.optional(),
|
||||
sealDelegate: SealDelegateAuthCacheSchema.optional()
|
||||
});
|
||||
|
||||
export const TokenStoreSchema = z.record(z.string(), CorpTokenCacheSchema);
|
||||
@@ -39,5 +46,6 @@ export type TokenEntry = z.infer<typeof TokenEntrySchema>;
|
||||
export type SealEnterpriseConfig = z.infer<typeof SealEnterpriseConfigSchema>;
|
||||
export type SealSession = z.infer<typeof SealSessionSchema>;
|
||||
export type HoseAuthCache = z.infer<typeof HoseAuthCacheSchema>;
|
||||
export type SealDelegateAuthCache = z.infer<typeof SealDelegateAuthCacheSchema>;
|
||||
export type CorpTokenCache = z.infer<typeof CorpTokenCacheSchema>;
|
||||
export type TokenStore = z.infer<typeof TokenStoreSchema>;
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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"));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -25,8 +25,10 @@ import file21 from "../../skills/seal-use/references/langfuse-trace.md" with { t
|
||||
import file22 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
|
||||
import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file25 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file26 from "../../skills/seal-use/references/webhook-resource-pack.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/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,
|
||||
@@ -48,8 +50,10 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/report-templates.md": file22,
|
||||
"references/rule-lightweight.md": file23,
|
||||
"references/rule-lint.md": file24,
|
||||
"references/staging-simulation-workflow.md": file25,
|
||||
"references/webhook-resource-pack.md": file26,
|
||||
"references/sealai-browser-rum.md": file25,
|
||||
"references/staging-simulation-workflow.md": file26,
|
||||
"references/tenant-status.md": file27,
|
||||
"references/webhook-resource-pack.md": file28,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
|
||||
@@ -87,6 +91,8 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/report-templates.md",
|
||||
"references/rule-lightweight.md",
|
||||
"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
@@ -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;
|
||||
|
||||
@@ -47,6 +47,7 @@ export async function onboardAssistanceLink(link: string, input: AssistanceLinkO
|
||||
token: session.token,
|
||||
sealUrl: session.sealUrl,
|
||||
expiresIn: session.expiresIn,
|
||||
sessionCookie: session.sessionCookie,
|
||||
user: session.user,
|
||||
tenant: session.tenant
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
getInsightRisksByTag,
|
||||
getInsightPerformance,
|
||||
getApprovalRunRawJson,
|
||||
exportApprovalRulesCsv,
|
||||
analyzeInsightRecord,
|
||||
listExpenses,
|
||||
listInvoices,
|
||||
@@ -41,6 +42,21 @@ describe("native approval JSON", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("official approval rules CSV export", () => {
|
||||
test("reads the server-generated CSV from the data envelope", async () => {
|
||||
let requestedUrl = "";
|
||||
const client = {
|
||||
get: (url: string) => {
|
||||
requestedUrl = url;
|
||||
return { json: async () => ({ data: { csv: "code,description\r\n001,测试" } }) };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
await expect(exportApprovalRulesCsv(client)).resolves.toBe("code,description\r\n001,测试");
|
||||
expect(requestedUrl).toBe("api/v1/rules/export/csv");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Seal contact API", () => {
|
||||
test("sends the contact search term as query", async () => {
|
||||
let requestedUrl = "";
|
||||
|
||||
@@ -88,6 +88,8 @@ import {
|
||||
SimulationIntegrationStatusSchema,
|
||||
SimulationHosecloudIntegration,
|
||||
SimulationHosecloudIntegrationSchema,
|
||||
SimulationMaycurIntegration,
|
||||
SimulationMaycurIntegrationSchema,
|
||||
MaterialPackage,
|
||||
MaterialPackageSchema,
|
||||
SimulationSpecification,
|
||||
@@ -121,6 +123,12 @@ export async function listApprovalRules(client: KyInstance): Promise<ApprovalRul
|
||||
return unwrap(await client.get("api/v1/rules"), ApprovalRulesDataSchema);
|
||||
}
|
||||
|
||||
export async function exportApprovalRulesCsv(client: KyInstance): Promise<string> {
|
||||
const response = await client.get("api/v1/rules/export/csv");
|
||||
const result = await unwrap(response, z.object({ csv: z.string() }));
|
||||
return result.csv;
|
||||
}
|
||||
|
||||
export async function createApprovalRule(
|
||||
client: KyInstance,
|
||||
params: { description: string; scope: string; strictness: string }
|
||||
@@ -818,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);
|
||||
});
|
||||
});
|
||||
@@ -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}`
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -60,6 +60,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealApprovalRuleVersionsList",
|
||||
"sealApprovalRulesLint",
|
||||
"sealApprovalRulesList",
|
||||
"sealApprovalRulesExportCsv",
|
||||
"sealApprovalRulesPull",
|
||||
"sealApprovalRunAttachmentsGet",
|
||||
"sealApprovalRunCitedRulesGet",
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js";
|
||||
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
|
||||
import { exportOfficialRulesCsv } from "../rules/export-csv.js";
|
||||
import { executeRulePush } from "../rules/push.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||||
@@ -719,6 +720,18 @@ export const rulesCapabilities = [
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "sealApprovalRulesExportCsv",
|
||||
description: "Call the official SealAI rules CSV export endpoint and save its CSV payload unchanged",
|
||||
parameters: z.object({
|
||||
out: z.string().optional().describe("Output file path; defaults to the Downloads directory")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { out?: string },
|
||||
context: CapabilityContext
|
||||
) => exportOfficialRulesCsv(client, context.corp, params.out)
|
||||
},
|
||||
{
|
||||
name: "sealApprovalRulesPush",
|
||||
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../../../core/config/types.js";
|
||||
import { createSealClientForUrl } from "../../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import { setSealDelegateAuthCache } from "../../../core/auth/token-store.js";
|
||||
import { getMe } from "../api.js";
|
||||
|
||||
export type RemoteSealIdentity = {
|
||||
@@ -39,6 +40,7 @@ export type SealDelegateSession = {
|
||||
token: string;
|
||||
sealUrl: string;
|
||||
expiresIn: number;
|
||||
sessionCookie?: string;
|
||||
user: Record<string, unknown>;
|
||||
tenant: Record<string, unknown>;
|
||||
};
|
||||
@@ -100,6 +102,17 @@ export function persistSealDelegateSession(input: {
|
||||
remote: { user: input.session.user, tenant: input.session.tenant }
|
||||
}
|
||||
);
|
||||
if (input.session.sessionCookie) {
|
||||
try {
|
||||
setSealDelegateAuthCache(saved.config.id, {
|
||||
cookie: input.session.sessionCookie,
|
||||
backupCookies: [],
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
} catch {
|
||||
// ignore cache write error
|
||||
}
|
||||
}
|
||||
return { ...saved, tenantId, tenantSlug };
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { formatBeijingIso } from "../../../../core/config/timestamps.js";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import type { ApprovalRun } from "../../types.js";
|
||||
import type { ReportDemand } from "./describe.js";
|
||||
import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
|
||||
import { loadReviews, recordDivergences, ReviewsMap, type ReviewRecord } from "./review-store.js";
|
||||
|
||||
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
|
||||
type Polarity = "pass" | "reject" | "unknown";
|
||||
@@ -307,6 +307,26 @@ export async function collectReportData(
|
||||
|
||||
data.blocks = blocks;
|
||||
fetched.blocks = true;
|
||||
|
||||
const divergedBlocks = blocks.filter((b) => b.agreement === "diverged");
|
||||
if (divergedBlocks.length > 0) {
|
||||
try {
|
||||
recordDivergences(
|
||||
options.corp.id,
|
||||
divergedBlocks.map((b) => ({
|
||||
corpId: options.corp.id,
|
||||
recordId: b.recordId ?? b.sn,
|
||||
sn: b.sn,
|
||||
docTitle: b.title,
|
||||
aiDecision: b.aiDecision,
|
||||
manualDecision: b.humanResult,
|
||||
divergenceType: `${b.aiDecision || "未知"}_${b.humanResult || "未知"}`,
|
||||
createdAt: b.createdAt ? new Date(b.createdAt).getTime() : undefined,
|
||||
discoveredAt: Date.now()
|
||||
}))
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
} catch {
|
||||
// 分块拉取失败:章节保持模板原文
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
closeReviewsDb,
|
||||
countUnreviewedDivergences,
|
||||
dismissDivergencePrompt,
|
||||
isDivergenceDismissed,
|
||||
listUnreviewedDivergences,
|
||||
recordDivergences,
|
||||
shouldPromptDivergence,
|
||||
writeReview
|
||||
} from "./review-store.js";
|
||||
|
||||
describe("review-divergence: 分歧待办与频控提醒机制", () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = mkdtempSync(join(tmpdir(), "seal-reviews-divergence-test-"));
|
||||
process.env.SEAL_USE_REVIEWS_STORE = join(testDir, "reviews.sqlite");
|
||||
process.env.SEAL_USE_REVIEWS_DIR = join(testDir, "reviews");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeReviewsDb();
|
||||
delete process.env.SEAL_USE_REVIEWS_STORE;
|
||||
delete process.env.SEAL_USE_REVIEWS_DIR;
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("录入分歧单据并能正确查询待整理数量", () => {
|
||||
const corpId = "corp-huangfeng";
|
||||
expect(countUnreviewedDivergences(corpId)).toBe(0);
|
||||
|
||||
recordDivergences(corpId, [
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-001",
|
||||
sn: "SN-20261101-01",
|
||||
docTitle: "差旅费报销单",
|
||||
amount: "¥1,200",
|
||||
aiDecision: "驳回",
|
||||
manualDecision: "通过",
|
||||
divergenceType: "AI驳回_人工通过",
|
||||
discoveredAt: Date.now()
|
||||
},
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-002",
|
||||
sn: "SN-20261101-02",
|
||||
docTitle: "办公用品采购",
|
||||
amount: "¥4,500",
|
||||
aiDecision: "通过",
|
||||
manualDecision: "驳回",
|
||||
divergenceType: "AI通过_人工驳回",
|
||||
discoveredAt: Date.now()
|
||||
}
|
||||
]);
|
||||
|
||||
expect(countUnreviewedDivergences(corpId)).toBe(2);
|
||||
const unreviewed = listUnreviewedDivergences(corpId);
|
||||
expect(unreviewed).toHaveLength(2);
|
||||
expect(unreviewed[0]!.sn).toBe("SN-20261101-01");
|
||||
});
|
||||
|
||||
test("进行人工裁决打标后,待整理数量自动减少", () => {
|
||||
const corpId = "corp-huangfeng";
|
||||
recordDivergences(corpId, [
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-001",
|
||||
sn: "SN-001",
|
||||
discoveredAt: Date.now()
|
||||
},
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-002",
|
||||
sn: "SN-002",
|
||||
discoveredAt: Date.now()
|
||||
}
|
||||
]);
|
||||
|
||||
expect(countUnreviewedDivergences(corpId)).toBe(2);
|
||||
|
||||
// 人工整理了 run-001
|
||||
writeReview(corpId, {
|
||||
recordId: "run-001",
|
||||
sn: "SN-001",
|
||||
verdict: "ai_correct",
|
||||
note: "发票确实开错抬头,AI驳回正确"
|
||||
});
|
||||
|
||||
expect(countUnreviewedDivergences(corpId)).toBe(1);
|
||||
const remaining = listUnreviewedDivergences(corpId);
|
||||
expect(remaining).toHaveLength(1);
|
||||
expect(remaining[0]!.sn).toBe("SN-002");
|
||||
});
|
||||
|
||||
test("shouldPromptDivergence 遵守时间频控,避免连续打扰", () => {
|
||||
const corpId = "corp-huangfeng";
|
||||
// 第一次允许提醒
|
||||
expect(shouldPromptDivergence(corpId, 10_000)).toBe(true);
|
||||
|
||||
// 立即再次检查,在 10s 内被频控拦截
|
||||
expect(shouldPromptDivergence(corpId, 10_000)).toBe(false);
|
||||
|
||||
// 另一个企业不受影响
|
||||
expect(shouldPromptDivergence("corp-other", 10_000)).toBe(true);
|
||||
});
|
||||
|
||||
test("dismissDivergencePrompt 在用户拒绝时进入静音抑制期,绝不重复打扰", () => {
|
||||
const corpId = "corp-huangfeng";
|
||||
expect(isDivergenceDismissed(corpId)).toBe(false);
|
||||
|
||||
// 用户说“今天不想审批/别烦我”,Agent 调用 dismiss 24小时
|
||||
dismissDivergencePrompt(corpId, 24);
|
||||
expect(isDivergenceDismissed(corpId)).toBe(true);
|
||||
|
||||
// 在静音期内,无论频控如何都不再提醒
|
||||
expect(shouldPromptDivergence(corpId, 0)).toBe(false);
|
||||
});
|
||||
|
||||
test("自动过滤超过 30 天的陈年旧单,只提示近 30 天的分歧单据", () => {
|
||||
const corpId = "corp-huangfeng";
|
||||
const now = Date.now();
|
||||
const eightyDaysAgo = now - 80 * 24 * 3600 * 1000;
|
||||
|
||||
recordDivergences(corpId, [
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-old-march",
|
||||
sn: "SN-20260315-01",
|
||||
docTitle: "3月份招待费",
|
||||
createdAt: eightyDaysAgo,
|
||||
discoveredAt: eightyDaysAgo
|
||||
},
|
||||
{
|
||||
corpId,
|
||||
recordId: "run-recent-today",
|
||||
sn: "SN-20261102-01",
|
||||
docTitle: "今天差旅费",
|
||||
createdAt: now,
|
||||
discoveredAt: now
|
||||
}
|
||||
]);
|
||||
|
||||
// 默认只统计近 30 天:3月份的陈年旧账自动排除,不打扰当前月份
|
||||
expect(countUnreviewedDivergences(corpId)).toBe(1);
|
||||
const recent = listUnreviewedDivergences(corpId);
|
||||
expect(recent).toHaveLength(1);
|
||||
expect(recent[0]!.sn).toBe("SN-20261102-01");
|
||||
|
||||
// 若显式传入 0 (或 --all),仍可检索历史全量
|
||||
expect(countUnreviewedDivergences(corpId, 0)).toBe(2);
|
||||
const all = listUnreviewedDivergences(corpId, 50, 0);
|
||||
expect(all).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("滑动窗口频控:同一个企业 5 小时内最多主动提醒 1 次", () => {
|
||||
const corpId = "corp-sliding-window";
|
||||
const fiveHoursMs = 5 * 60 * 60 * 1000;
|
||||
|
||||
// 第 1 次:允许提醒
|
||||
expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(true);
|
||||
|
||||
// 5 小时以内再次触发:拦截
|
||||
expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(false);
|
||||
|
||||
// 传入 0 间隔(即超过 5 小时后):再次允许提醒
|
||||
expect(shouldPromptDivergence(corpId, 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,19 @@
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { Database } from "bun:sqlite";
|
||||
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { validationError } from "../../../../core/errors.js";
|
||||
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
|
||||
|
||||
/**
|
||||
* 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。
|
||||
* 人工裁决与分歧待办的本地存储(统一放置在 ~/.config/seal-use/state/)
|
||||
*
|
||||
* 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写,
|
||||
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
|
||||
* 为什么按租户分片:租户天然数据隔离。
|
||||
* 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。
|
||||
* 后写覆盖先写。
|
||||
* 存储模型:
|
||||
* 1. 主存储:~/.config/seal-use/state/reviews.sqlite,支持秒级索引与差集运算(支撑日常命令在 stderr 温和提示);
|
||||
* 2. 伴生与导出存储:~/.config/seal-use/state/reviews/<corpId>[-<scope>].jsonl,作为人类可读与批量台账交互的冷备份;
|
||||
* 3. 为什么是 State 而不是 Cache:人工裁决是用户不可逆的智力决策(谁对谁错、特批备注),不上传云端,属于单机核心资产,
|
||||
* 防止随 ~/.cache 一键清理而丢失。
|
||||
*/
|
||||
|
||||
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
|
||||
export type ReviewVerdict =
|
||||
| "ai_correct" // AI 对,人工错
|
||||
| "human_correct" // 人工对,AI 错
|
||||
@@ -22,21 +22,29 @@ export type ReviewVerdict =
|
||||
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
|
||||
|
||||
export type ReviewRecord = {
|
||||
/** 审核运行记录 ID(精确裁决键) */
|
||||
recordId?: string;
|
||||
/** 合思/源单据 SN(业务自然键) */
|
||||
sn?: string;
|
||||
/** 裁决所属统计周期或月份(可选留痕) */
|
||||
month?: string;
|
||||
scope?: string;
|
||||
verdict: ReviewVerdict;
|
||||
/** 裁决人(可选,留痕用) */
|
||||
reviewedBy?: string;
|
||||
/** 裁决备注(可选):为什么这么判 */
|
||||
note?: string;
|
||||
/** 写入时间(北京时间 ISO 秒) */
|
||||
recordedAt: string;
|
||||
};
|
||||
|
||||
export type DivergenceItem = {
|
||||
corpId: string;
|
||||
recordId: string;
|
||||
sn: string;
|
||||
docTitle?: string;
|
||||
amount?: string;
|
||||
aiDecision?: string;
|
||||
manualDecision?: string;
|
||||
divergenceType?: string;
|
||||
createdAt?: number;
|
||||
discoveredAt: number;
|
||||
};
|
||||
|
||||
const VERDICTS: ReadonlySet<string> = new Set([
|
||||
"ai_correct",
|
||||
"human_correct",
|
||||
@@ -97,20 +105,27 @@ export class ReviewsMap {
|
||||
}
|
||||
|
||||
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
|
||||
const REVIEWS_STORE_ENV = "SEAL_USE_REVIEWS_STORE";
|
||||
|
||||
/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
|
||||
export function reviewsDir(): string {
|
||||
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
return join(SEAL_STATE_DIR, "reviews");
|
||||
}
|
||||
|
||||
/** 分片路径:<reviewsDir>/<corpId>[-<scope>].jsonl */
|
||||
export function reviewFilePath(corpId: string, scope?: string): string {
|
||||
const cleanCorp = sanitizeCorpId(corpId);
|
||||
return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`);
|
||||
}
|
||||
|
||||
export function getReviewStorePath(): string {
|
||||
const configured = process.env[REVIEWS_STORE_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
const legacyDir = process.env[REVIEWS_DIR_ENV]?.trim();
|
||||
if (legacyDir) return join(legacyDir, "reviews.sqlite");
|
||||
return join(SEAL_STATE_DIR, "reviews.sqlite");
|
||||
}
|
||||
|
||||
function sanitizeCorpId(corpId: string): string {
|
||||
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
@@ -123,21 +138,109 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
|
||||
}
|
||||
}
|
||||
|
||||
let dbInstance: Database | null = null;
|
||||
let currentDbPath: string | null = null;
|
||||
|
||||
export function openReviewsDb(path = getReviewStorePath()): Database {
|
||||
if (dbInstance && currentDbPath === path) {
|
||||
return dbInstance;
|
||||
}
|
||||
if (dbInstance) {
|
||||
try {
|
||||
dbInstance.close();
|
||||
} catch {}
|
||||
dbInstance = null;
|
||||
}
|
||||
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const db = new Database(path, { create: true });
|
||||
try {
|
||||
chmodSync(path, 0o600);
|
||||
db.exec("PRAGMA busy_timeout = 5000");
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS reviews (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
corp_id TEXT NOT NULL,
|
||||
record_id TEXT,
|
||||
sn TEXT,
|
||||
month TEXT,
|
||||
scope TEXT,
|
||||
verdict TEXT NOT NULL,
|
||||
reviewed_by TEXT,
|
||||
note TEXT,
|
||||
recorded_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_reviews_lookup ON reviews (corp_id, record_id, sn);
|
||||
CREATE INDEX IF NOT EXISTS idx_reviews_scope ON reviews (corp_id, scope);
|
||||
CREATE INDEX IF NOT EXISTS idx_reviews_month ON reviews (corp_id, month);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS divergences (
|
||||
corp_id TEXT NOT NULL,
|
||||
record_id TEXT NOT NULL,
|
||||
sn TEXT NOT NULL,
|
||||
doc_title TEXT,
|
||||
amount TEXT,
|
||||
ai_decision TEXT,
|
||||
manual_decision TEXT,
|
||||
divergence_type TEXT,
|
||||
created_at INTEGER,
|
||||
discovered_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (corp_id, record_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_divergences_corp ON divergences (corp_id, sn);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS prompt_throttle (
|
||||
corp_id TEXT PRIMARY KEY,
|
||||
last_prompt_date TEXT,
|
||||
prompt_count INTEGER NOT NULL DEFAULT 1,
|
||||
last_prompted_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS review_dismissals (
|
||||
corp_id TEXT PRIMARY KEY,
|
||||
dismissed_until INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
try {
|
||||
db.exec("ALTER TABLE prompt_throttle ADD COLUMN last_prompt_date TEXT");
|
||||
} catch {}
|
||||
try {
|
||||
db.exec("ALTER TABLE prompt_throttle ADD COLUMN prompt_count INTEGER DEFAULT 1");
|
||||
} catch {}
|
||||
dbInstance = db;
|
||||
currentDbPath = path;
|
||||
return db;
|
||||
} catch (error) {
|
||||
db.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function closeReviewsDb(): void {
|
||||
if (dbInstance) {
|
||||
try {
|
||||
dbInstance.close();
|
||||
} catch {}
|
||||
dbInstance = null;
|
||||
currentDbPath = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。
|
||||
* 历史 JSONL 自动平滑迁移或同步到 SQLite
|
||||
*/
|
||||
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
|
||||
const reviews = new ReviewsMap();
|
||||
function syncLegacyJsonlIfPresent(corpId: string, db: Database, targetScope?: string): void {
|
||||
const targetDir = reviewsDir();
|
||||
if (!existsSync(targetDir)) return;
|
||||
const sanitized = sanitizeCorpId(corpId);
|
||||
const targetDir = reviewsDir();
|
||||
if (!existsSync(targetDir)) return reviews;
|
||||
|
||||
const targetFile = reviewFilePath(corpId, scope);
|
||||
const filesToRead: string[] = [];
|
||||
if (scope) {
|
||||
if (existsSync(targetFile)) filesToRead.push(targetFile);
|
||||
if (targetScope) {
|
||||
const scopeFile = reviewFilePath(corpId, targetScope);
|
||||
if (existsSync(scopeFile)) filesToRead.push(scopeFile);
|
||||
} else {
|
||||
if (existsSync(targetFile)) filesToRead.push(targetFile);
|
||||
const primary = reviewFilePath(corpId);
|
||||
if (existsSync(primary)) filesToRead.push(primary);
|
||||
try {
|
||||
const allFiles = readdirSync(targetDir);
|
||||
for (const f of allFiles) {
|
||||
@@ -148,7 +251,20 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
for (const filePath of filesToRead) {
|
||||
const insertStmt = db.prepare(`
|
||||
INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const checkStmt = db.prepare(`
|
||||
SELECT id FROM reviews
|
||||
WHERE corp_id = ? AND (
|
||||
(record_id IS NOT NULL AND record_id = ?) OR
|
||||
(sn IS NOT NULL AND sn = ?)
|
||||
) AND recorded_at = ? LIMIT 1
|
||||
`);
|
||||
|
||||
for (const filePath of new Set(filesToRead)) {
|
||||
try {
|
||||
const lines = readFileSync(filePath, "utf8").split("\n");
|
||||
for (const line of lines) {
|
||||
@@ -157,18 +273,87 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as ReviewRecord;
|
||||
if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) {
|
||||
reviews.set(parsed.recordId ?? parsed.sn!, parsed);
|
||||
const exists = checkStmt.get(
|
||||
corpId,
|
||||
parsed.recordId ?? null,
|
||||
parsed.sn ?? null,
|
||||
parsed.recordedAt
|
||||
);
|
||||
if (!exists) {
|
||||
insertStmt.run(
|
||||
corpId,
|
||||
parsed.recordId ?? null,
|
||||
parsed.sn ?? null,
|
||||
parsed.month ?? null,
|
||||
parsed.scope ?? parsed.month ?? null,
|
||||
parsed.verdict,
|
||||
parsed.reviewedBy ?? null,
|
||||
parsed.note ?? null,
|
||||
parsed.recordedAt
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch {
|
||||
// 跳过损坏行
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片。按后写覆盖先写。
|
||||
*/
|
||||
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
|
||||
const reviews = new ReviewsMap();
|
||||
const db = openReviewsDb();
|
||||
syncLegacyJsonlIfPresent(corpId, db, scope);
|
||||
|
||||
let query = `
|
||||
SELECT record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at
|
||||
FROM reviews
|
||||
WHERE corp_id = ?
|
||||
`;
|
||||
const params: string[] = [corpId];
|
||||
|
||||
if (scope) {
|
||||
query += " AND (scope = ? OR month = ?)";
|
||||
params.push(scope, scope);
|
||||
}
|
||||
query += " ORDER BY id ASC";
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
record_id: string | null;
|
||||
sn: string | null;
|
||||
month: string | null;
|
||||
scope: string | null;
|
||||
verdict: string;
|
||||
reviewed_by: string | null;
|
||||
note: string | null;
|
||||
recorded_at: string;
|
||||
}>;
|
||||
|
||||
for (const row of rows) {
|
||||
if (VERDICTS.has(row.verdict)) {
|
||||
const record: ReviewRecord = {
|
||||
recordId: row.record_id || undefined,
|
||||
sn: row.sn || undefined,
|
||||
month: row.month || undefined,
|
||||
scope: row.scope || undefined,
|
||||
verdict: row.verdict as ReviewVerdict,
|
||||
reviewedBy: row.reviewed_by || undefined,
|
||||
note: row.note || undefined,
|
||||
recordedAt: row.recorded_at
|
||||
};
|
||||
reviews.set(record.recordId ?? record.sn!, record);
|
||||
}
|
||||
}
|
||||
|
||||
return reviews;
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加写一条裁决到磁盘(支持 recordId 与 sn)。
|
||||
* 记录一条裁决到 SQLite 存储,同时双写到伴生 JSONL 文件
|
||||
*/
|
||||
export function writeReview(
|
||||
corpId: string,
|
||||
@@ -193,19 +378,267 @@ export function writeReview(
|
||||
}
|
||||
assertVerdict(input.verdict);
|
||||
|
||||
const recordedAt =
|
||||
input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ");
|
||||
const scope = input.scope ?? input.month;
|
||||
|
||||
const db = openReviewsDb();
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
stmt.run(
|
||||
corpId,
|
||||
recordId ?? null,
|
||||
sn ?? null,
|
||||
input.month ?? null,
|
||||
scope ?? null,
|
||||
input.verdict,
|
||||
input.reviewedBy?.trim() ?? null,
|
||||
input.note?.trim() ?? null,
|
||||
recordedAt
|
||||
);
|
||||
|
||||
const record: ReviewRecord = {
|
||||
...(recordId ? { recordId } : {}),
|
||||
...(sn ? { sn } : {}),
|
||||
...(input.month ? { month: input.month } : {}),
|
||||
...(scope ? { scope } : {}),
|
||||
verdict: input.verdict,
|
||||
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
|
||||
...(input.note?.trim() ? { note: input.note.trim() } : {}),
|
||||
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
|
||||
recordedAt
|
||||
};
|
||||
|
||||
const scope = input.scope ?? input.month;
|
||||
const filePath = reviewFilePath(corpId, scope);
|
||||
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
||||
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
|
||||
// 双写到伴生 JSONL(明文冷备与纯文本兼容)
|
||||
try {
|
||||
const filePath = reviewFilePath(corpId, scope);
|
||||
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
||||
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
|
||||
} catch {}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量同步/保存分歧单据到底层 SQLite
|
||||
*/
|
||||
export function recordDivergences(corpId: string, items: DivergenceItem[]): number {
|
||||
if (items.length === 0) return 0;
|
||||
const db = openReviewsDb();
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO divergences (corp_id, record_id, sn, doc_title, amount, ai_decision, manual_decision, divergence_type, created_at, discovered_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(corp_id, record_id) DO UPDATE SET
|
||||
sn = excluded.sn,
|
||||
doc_title = coalesce(excluded.doc_title, divergences.doc_title),
|
||||
amount = coalesce(excluded.amount, divergences.amount),
|
||||
ai_decision = coalesce(excluded.ai_decision, divergences.ai_decision),
|
||||
manual_decision = coalesce(excluded.manual_decision, divergences.manual_decision),
|
||||
divergence_type = coalesce(excluded.divergence_type, divergences.divergence_type)
|
||||
`);
|
||||
|
||||
let count = 0;
|
||||
db.transaction(() => {
|
||||
for (const item of items) {
|
||||
stmt.run(
|
||||
corpId,
|
||||
item.recordId,
|
||||
item.sn,
|
||||
item.docTitle ?? null,
|
||||
item.amount ?? null,
|
||||
item.aiDecision ?? null,
|
||||
item.manualDecision ?? null,
|
||||
item.divergenceType ?? null,
|
||||
item.createdAt ?? null,
|
||||
item.discoveredAt || Date.now()
|
||||
);
|
||||
count++;
|
||||
}
|
||||
})();
|
||||
return count;
|
||||
}
|
||||
|
||||
export const DEFAULT_RECENCY_DAYS = 30;
|
||||
|
||||
function getLocalDateString(): string {
|
||||
const d = new Date();
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出某企业未完成人工复核的分歧单据(用于少量多次整理)
|
||||
* 默认只检索近 30 天内发生的单据,避免数月前的陈年旧账打扰日常体验
|
||||
*/
|
||||
export function listUnreviewedDivergences(
|
||||
corpId: string,
|
||||
limit = 50,
|
||||
maxAgeDays = DEFAULT_RECENCY_DAYS
|
||||
): DivergenceItem[] {
|
||||
const db = openReviewsDb();
|
||||
syncLegacyJsonlIfPresent(corpId, db);
|
||||
|
||||
let query = `
|
||||
SELECT d.corp_id, d.record_id, d.sn, d.doc_title, d.amount, d.ai_decision, d.manual_decision, d.divergence_type, d.created_at, d.discovered_at
|
||||
FROM divergences d
|
||||
LEFT JOIN reviews r ON r.corp_id = d.corp_id AND (
|
||||
(r.record_id IS NOT NULL AND r.record_id = d.record_id) OR
|
||||
(r.sn IS NOT NULL AND r.sn = d.sn)
|
||||
)
|
||||
WHERE d.corp_id = ? AND r.id IS NULL
|
||||
`;
|
||||
const params: (string | number)[] = [corpId];
|
||||
|
||||
if (maxAgeDays > 0) {
|
||||
const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000;
|
||||
query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`;
|
||||
params.push(cutoff);
|
||||
}
|
||||
|
||||
query += `
|
||||
ORDER BY d.created_at DESC, d.discovered_at DESC
|
||||
LIMIT ?
|
||||
`;
|
||||
params.push(limit);
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
corp_id: string;
|
||||
record_id: string;
|
||||
sn: string;
|
||||
doc_title: string | null;
|
||||
amount: string | null;
|
||||
ai_decision: string | null;
|
||||
manual_decision: string | null;
|
||||
divergence_type: string | null;
|
||||
created_at: number | null;
|
||||
discovered_at: number;
|
||||
}>;
|
||||
|
||||
return rows.map((r) => ({
|
||||
corpId: r.corp_id,
|
||||
recordId: r.record_id,
|
||||
sn: r.sn,
|
||||
docTitle: r.doc_title || undefined,
|
||||
amount: r.amount || undefined,
|
||||
aiDecision: r.ai_decision || undefined,
|
||||
manualDecision: r.manual_decision || undefined,
|
||||
divergenceType: r.divergence_type || undefined,
|
||||
createdAt: r.created_at || undefined,
|
||||
discoveredAt: r.discovered_at
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计某企业待整理分歧单据数量(耗时 < 0.2ms,供日常命令快速探测)
|
||||
* 默认只统计近 30 天内产生的分歧,陈年单据自动归入离线历史池,零打扰
|
||||
*/
|
||||
export function countUnreviewedDivergences(
|
||||
corpId: string,
|
||||
maxAgeDays = DEFAULT_RECENCY_DAYS
|
||||
): number {
|
||||
try {
|
||||
const db = openReviewsDb();
|
||||
syncLegacyJsonlIfPresent(corpId, db);
|
||||
|
||||
let query = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM divergences d
|
||||
LEFT JOIN reviews r ON r.corp_id = d.corp_id AND (
|
||||
(r.record_id IS NOT NULL AND r.record_id = d.record_id) OR
|
||||
(r.sn IS NOT NULL AND r.sn = d.sn)
|
||||
)
|
||||
WHERE d.corp_id = ? AND r.id IS NULL
|
||||
`;
|
||||
const params: (string | number)[] = [corpId];
|
||||
|
||||
if (maxAgeDays > 0) {
|
||||
const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000;
|
||||
query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`;
|
||||
params.push(cutoff);
|
||||
}
|
||||
|
||||
const row = db.prepare(query).get(...params) as { count: number } | undefined;
|
||||
return row?.count ?? 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 抑制该企业的提示(当用户表示当天不想处理时,Agent 调用此函数静音)
|
||||
*/
|
||||
export function dismissDivergencePrompt(corpId: string, hours = 24): number {
|
||||
try {
|
||||
const db = openReviewsDb();
|
||||
const until = Date.now() + Math.max(1, hours) * 3600 * 1000;
|
||||
db.prepare(`
|
||||
INSERT INTO review_dismissals (corp_id, dismissed_until)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(corp_id) DO UPDATE SET dismissed_until = excluded.dismissed_until
|
||||
`).run(corpId, until);
|
||||
return until;
|
||||
} catch {
|
||||
return Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查该企业是否处于人工拒绝的静音抑制期内
|
||||
*/
|
||||
export function isDivergenceDismissed(corpId: string): boolean {
|
||||
try {
|
||||
const db = openReviewsDb();
|
||||
const row = db
|
||||
.prepare("SELECT dismissed_until FROM review_dismissals WHERE corp_id = ?")
|
||||
.get(corpId) as { dismissed_until: number } | undefined;
|
||||
return Boolean(row && row.dismissed_until > Date.now());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_PROMPT_INTERVAL_MS = 5 * 60 * 60 * 1000; // 动态 5 小时滑动窗口
|
||||
|
||||
/**
|
||||
* 频控检查(动态 5 小时滑动窗口与 24 小时人工封禁):
|
||||
* 1. 显式静音优先:若企业处于 dismiss 抑制期内(默认 24 小时),直接返回 false;
|
||||
* 2. 动态滑动窗口:同一个企业默认 5 小时内最多提醒 1 次(5 小时内提醒过则不再提醒);
|
||||
* 3. 满足条件时记录当前时间戳并返回 true。
|
||||
*/
|
||||
export function shouldPromptDivergence(
|
||||
corpId: string,
|
||||
intervalMs = DEFAULT_PROMPT_INTERVAL_MS
|
||||
): boolean {
|
||||
try {
|
||||
if (isDivergenceDismissed(corpId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const db = openReviewsDb();
|
||||
const now = Date.now();
|
||||
|
||||
const row = db
|
||||
.prepare("SELECT last_prompted_at FROM prompt_throttle WHERE corp_id = ?")
|
||||
.get(corpId) as { last_prompted_at?: number } | undefined;
|
||||
|
||||
if (row?.last_prompted_at && now - row.last_prompted_at < intervalMs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO prompt_throttle (corp_id, last_prompt_date, prompt_count, last_prompted_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(corp_id) DO UPDATE SET
|
||||
last_prompt_date = excluded.last_prompt_date,
|
||||
prompt_count = excluded.prompt_count,
|
||||
last_prompted_at = excluded.last_prompted_at
|
||||
`).run(corpId, getLocalDateString(), 1, now);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import type { KyInstance } from "ky";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { writeSecureFile } from "../../../core/secure-file.js";
|
||||
import * as api from "../api.js";
|
||||
import { sanitizeFileName } from "../approval-runs/attachments.js";
|
||||
|
||||
export interface OfficialRulesCsvExportResult {
|
||||
filePath: string;
|
||||
corpName: string;
|
||||
byteLength: number;
|
||||
exportedAt: string;
|
||||
source: "sealai-official-csv-endpoint";
|
||||
}
|
||||
|
||||
export async function exportOfficialRulesCsv(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig,
|
||||
outputFile?: string
|
||||
): Promise<OfficialRulesCsvExportResult> {
|
||||
const exportedAt = formatBeijingIso();
|
||||
const stamp = exportedAt.slice(0, 19).replace(/[-:T]/g, "");
|
||||
const safeCorpName = sanitizeFileName(corp.name || corp.id);
|
||||
const filePath = resolve(
|
||||
outputFile ?? join(homedir(), "Downloads", `${safeCorpName}_审核规则官方导出_${stamp}.csv`)
|
||||
);
|
||||
const csv = await api.exportApprovalRulesCsv(client);
|
||||
|
||||
// The API response is a JSON envelope containing the server-generated CSV string.
|
||||
// Persist that string as UTF-8 without parsing, reordering, normalizing, or rewriting CSV rows.
|
||||
writeSecureFile(filePath, csv);
|
||||
|
||||
return {
|
||||
filePath,
|
||||
corpName: corp.name || corp.id,
|
||||
byteLength: Buffer.byteLength(csv, "utf8"),
|
||||
exportedAt,
|
||||
source: "sealai-official-csv-endpoint"
|
||||
};
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
@@ -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" });
|
||||
|
||||
Reference in new issue
Block a user