Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce066206df | ||
|
|
f4929abb0c | ||
|
|
f67e689463 | ||
|
|
4c8389bf0c | ||
|
|
76d288b882 | ||
|
|
b6aa4efd09 | ||
|
|
5a5c0c11a9 | ||
|
|
acdc2a301a | ||
|
|
34c4ecfbaa | ||
|
|
1297c56f3d | ||
|
|
9ba049a85f | ||
|
|
bdb4a1dd9e | ||
|
|
d672ba447e | ||
|
|
770fd9d672 | ||
|
|
4adecf990d | ||
|
|
8b2230e0aa | ||
|
|
8773122a61 | ||
|
|
c6224407be | ||
|
|
6812ddd697 | ||
|
|
f5bedbbbae | ||
|
|
bdeca88354 | ||
|
|
0794f319b0 | ||
|
|
b00ba57313 | ||
|
|
b5df52875d | ||
|
|
bf1888ec90 | ||
|
|
c2d3c119f2 | ||
|
|
9d74b40991 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.16",
|
||||
"version": "0.10.18",
|
||||
"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,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.10.18] - 2026-09-11
|
||||
|
||||
### Added & Enhanced
|
||||
- **System Diagnostic Doctor & Embedded Specification Whitepaper**:
|
||||
- Added `seal-use doctor` for unified system health diagnostics, inspecting executable runtime, 8 core filesystem paths, enterprise assets, and health checks.
|
||||
- Implemented `seal-use doctor guide` to output the full system architecture, 10-tier directory specifications, security guarantees, and capability matrix directly from binary memory with zero additional disk writes.
|
||||
- Added `seal-use doctor paths` for compact JSON inspection of core directory status and descriptions.
|
||||
- Adheres strictly to dual-channel protocol: typed JSON on `stdout` and terminal diagnostic dashboard on `stderr`.
|
||||
- **Intelligent Soft Fuzzy Search for Enterprise Discovery**:
|
||||
- Introduced dedicated fuzzy engine (`src/core/search/fuzzy.ts`) supporting case-insensitivity, Chinese homophones/allophones, pinyin initials (简拼), full pinyin, nasal/retroflex normalization, and Levenshtein typo tolerance.
|
||||
- Enabled soft fuzzy search by default on `seal-use corps search <keyword>` and `seal-use corps list`, with `--strict` option for exact substring matching.
|
||||
- Enforced `corps search` in Agent Skill guidelines over dumping entire enterprise lists when names or hints are known.
|
||||
- **Dedicated Enterprise Lookup & Compatibility Alias**:
|
||||
- Added `seal-use corps get <idOrName>` to inspect a single enterprise by ID, exact name, or unique prefix.
|
||||
- Added `corp` as a first-class CLI compatibility alias for `corps` across command dispatching and help registry.
|
||||
- **Approval Run Deep Link & SSO URL Generation**:
|
||||
- Added `seal-use runs url <runId> [--sso] [--corp <corpId>]` to generate direct Web UI links and security-guarded SSO links for approval runs.
|
||||
- **Approval Run to Webhook Replay**:
|
||||
- Added `seal-use runs replay <runId> [--corp <corpId>] [--target <url>]` to reconstruct webhook payloads from historical runs for deterministic regression testing.
|
||||
|
||||
## [0.10.17] - 2026-09-11
|
||||
|
||||
### Added & Enhanced
|
||||
- **Automatic Hosecloud Integration Synchronization for Staging Test**:
|
||||
- `seal-use corps sync-test` automatically syncs Hosecloud (合思) integrations from production to bound test Seal enterprises.
|
||||
- Generates standardized outbound name `{企业名前缀}(Seal测)` capped at 13 characters to satisfy platform limits.
|
||||
- Automatically overrides mode to `assisted` in test environments regardless of production mode.
|
||||
- Reuses production `apiOrigin` and `customApiUrl`, while extracting credentials directly from local enterprise source config (`appKey`/`appSecurity` with `key`/`password` fallback).
|
||||
- Automatically deduplicates multiple production integrations belonging to the same enterprise into a single test integration.
|
||||
- Retains existing `signKey` when updating for idempotency; skips outbound sync to Hosecloud to guarantee zero impact on production approval workflows.
|
||||
- Added `hosecloudSyncPlan` to `--dry-run` output and `hosecloudSync` result to execution summary.
|
||||
- **Comprehensive Staging Simulation & Production Rule Evolution Guide**:
|
||||
- Added `skills/seal-use/references/staging-simulation-workflow.md` covering enterprise pairing, auto-sync, staging simulation validation, and production rule rollout.
|
||||
- Enhanced `skills/seal-use/SKILL.md` with version verification mandates, self-update instructions (`seal-use update`), and staging-first safety guidelines.
|
||||
- **Complete Dispatchable Area CLI Help Coverage**:
|
||||
- Registered missing `service` and `stop` help entries, aliased `server` to `mcp` help, and resolved `config status` aliases.
|
||||
- Dynamically generated global help from `HELP_REGISTRY`, eliminating drift and redundant usage blocks.
|
||||
- Only emit subcommand footers for areas that have subcommands.
|
||||
- Added automated coverage tests across all `KNOWN_AREAS`.
|
||||
- **Skill Documentation & Routing Expansion**:
|
||||
- Updated `SKILL.md` and `references/cli.md` covering read-only discovery, rule workspace, analytics/export, async simulation, and knowledge document lifecycle capabilities.
|
||||
|
||||
## [0.10.16] - 2026-09-11
|
||||
|
||||
### Added & Enhanced
|
||||
|
||||
Vendored
+447
-326
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "seal-use Wrapped API",
|
||||
"version": "0.10.16",
|
||||
"version": "0.10.18",
|
||||
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: seal-use Wrapped API
|
||||
version: 0.10.16
|
||||
version: 0.10.18
|
||||
description: |
|
||||
Planned HTTP contract for the seal-use wrapped backend API.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.16",
|
||||
"version": "0.10.18",
|
||||
"type": "module",
|
||||
"module": "src/server.ts",
|
||||
"bin": {
|
||||
|
||||
+60
-17
@@ -1,28 +1,38 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.10.16: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.10.18: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.10.16
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.16)
|
||||
version: 0.10.18
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.18)
|
||||
---
|
||||
|
||||
# Seal Use (v0.10.16)
|
||||
# Seal Use (v0.10.18)
|
||||
|
||||
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
|
||||
|
||||
## Bootstrap & Installation (环境安装与自愈)
|
||||
|
||||
If `seal-use` or `seal_cli` is not installed on the system, the Agent should automatically install it via:
|
||||
Agent 必须确保使用最新版本的 `seal-use` CLI、Skill 与 Agent 插件。在执行任何配置或业务任务前,优先核验版本状态:
|
||||
|
||||
```bash
|
||||
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
|
||||
seal-use version
|
||||
seal-use corps list
|
||||
```
|
||||
|
||||
如果 CLI 或 Skill 尚未安装或落后于发布版本,通过以下命令一键安装或升级:
|
||||
|
||||
```bash
|
||||
# 方式 1:CLI 自更新(已安装时推荐)
|
||||
seal-use update
|
||||
|
||||
# 方式 2:国内高速一键安装与自愈(Gitea 镜像源,免代理、秒级完成)
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
|
||||
# Global / GitHub Direct
|
||||
# 方式 3:Global / GitHub Direct
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
After installation, verify with:
|
||||
安装或升级后,验证系统连通性:
|
||||
```bash
|
||||
seal-use version
|
||||
seal-use corps list
|
||||
@@ -31,7 +41,7 @@ seal-use corps list
|
||||
## First Rules
|
||||
|
||||
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
|
||||
- Before asking for enterprise parameters, run `seal-use corps list`. If the target is already configured, resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`.
|
||||
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search <keyword>` (or `seal-use corps get <corpId>` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env <test|production>`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get <corpId>` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
|
||||
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
|
||||
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
|
||||
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
|
||||
@@ -39,8 +49,8 @@ seal-use corps list
|
||||
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
|
||||
- Parse JSON stdout. Do not scrape human text.
|
||||
- Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`.
|
||||
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
|
||||
- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate `contentType` and `scenarios` before creating, and use `enabled: false` when the document should be withdrawn.
|
||||
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, `corps sync-test`, preference updates, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
|
||||
- Knowledge document creation and deletion are now supported. Validate `contentType` and `scenarios` before creating; use `enabled: false` when the document should be withdrawn without deletion. For an explicit deletion, re-read the document and obtain confirmation before using the low-level `seal_approval_delete_document` tool.
|
||||
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise.
|
||||
- Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
|
||||
- For date questions, use explicit dates and `--timezone Asia/Shanghai`.
|
||||
@@ -48,30 +58,47 @@ seal-use corps list
|
||||
- When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
|
||||
- For delegation links, always prefer `seal-use delegation create` over `users delegation` for link generation to ensure persistent token tracking.
|
||||
- Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands.
|
||||
- For approval run links (`seal-use approval-runs url <recordId> [--corp <corpId>]`):
|
||||
- Always default to returning the clean deep link (`type: 'deep_link'`), which contains no credentials and requires no sensitive access. Users in their authorized browsers open it directly with zero token leakage risk.
|
||||
- ONLY provide an SSO link (`--sso`) when the user explicitly requests an unauthenticated/cross-browser/no-login/免密 link and acknowledges risks.
|
||||
- When returning an `--sso` link, the Agent MUST:
|
||||
1. Declare the 4 mandatory security disclosures:
|
||||
- 身份主体(Identity attribution: name and admin status)
|
||||
- 权限范围(Full Seal AI operation permissions under this user)
|
||||
- 时效性(2-hour provisional ticket TTL, 30-day session after opening)
|
||||
- 安全与防扩散边界(No Hose main system access, strictly internal, never share to public/external groups)
|
||||
2. Provide BOTH a code block (` ```text ... ``` `) and a clickable hyperlink.
|
||||
- In the default stateless mode, every enterprise command requires `--corp <corpId>`. In stateful mode, omitting `--corp` uses the configured default enterprise and is unsafe for an explicitly named enterprise.
|
||||
- For an explicitly named enterprise, first resolve it with `seal-use corps list`, then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
|
||||
- For an explicitly named enterprise, resolve it directly with `seal-use corps search <name>` (or `seal-use corps get <corpId>` if given an exact ID) rather than dumping all enterprises with `seal-use corps list`. Then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
|
||||
- 生产规则变更建议优先遵循“生产改草稿 -> 同步测试企业 -> 真实单据模拟验证 -> 生产发布投产”安全闭环;Agent 应主动提示并建议在测试环境中验证,但最终操作权与决策权在用户手中,绝不代替用户做决定。若用户明确要求直接在生产环境发布,尊重用户意图并严格执行。
|
||||
- 测试环境合思模拟安全隔离:`corps sync-test` 自动将生产企业合思凭证以 `assisted` 模式注入测试企业,名称格式为 `{企业名前缀}(Seal测)`。该配置仅保存在测试 Seal 侧,绝对不执行 `deploy hosecloud sync`,杜绝向生产合思费控推送 EBot 节点或创建外发 webhook。
|
||||
|
||||
## Route By Intent
|
||||
|
||||
- 生产规则安全演进、搭配配置与测试模拟闭环: read `references/staging-simulation-workflow.md`. 适用于:用户提出规则变更需求/客诉修复、生产与测试企业搭配接入与 1 对 1 绑定、生产环境仅改草稿隔离风险、`seal-use corps sync-test` 一键同步测试环境(含合思集成免配同步)、测试环境跑真实单据模拟验证、验证通过后才在生产正式发布的完整安全生命周期。
|
||||
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
|
||||
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
|
||||
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
|
||||
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
|
||||
- 测试企业标记、关联与配置规则同步: `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好和草稿规则覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M]`,输出并本地缓存 `ruleMapping`,正式企业规则保持草稿态不发布), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
|
||||
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation approval-definitions` 查询飞书审批定义, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
|
||||
- 企业检索、详情查看、环境标记、关联与配置规则同步: `seal-use corps list [query] [--env <production|test>] [--strict]` (列表与轻量检索), `seal-use corps search <query> [--env <production|test>] [--strict]` (跨字段智能软搜索:默认支持同音字、前后鼻音、平翘舌音、拼音与简拼、拼音或字母缺漏容错;`--strict` 切换为严格子串匹配), `seal-use corps get <corpId>` (富属性安全查看,敏感信息脱敏), `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好、草稿规则和知识文档覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M -> Test vM]`,输出并本地缓存 `versionMapping`/`ruleMapping`,正式企业规则保持草稿态不发布), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
|
||||
- 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。
|
||||
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
|
||||
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
|
||||
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
|
||||
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。
|
||||
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
|
||||
- Delegation links management: `seal-use delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `revoke <tokenId> --corp <corpId>`.
|
||||
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `reset-password <userId> --corp <corpId>`, `get <userId> --corp <corpId>`, `delete <userId> --corp <corpId>`.
|
||||
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `users reset-password <userId> --corp <corpId>`, `users get <userId> --corp <corpId>`, `users delete <userId> --corp <corpId>`.
|
||||
- 只读业务数据与组织发现: `seal-use contacts departments|children|users|sync-time --corp <corpId>`, `seal-use data expenses|invoices --corp <corpId>`, `seal-use analytics insight --corp <corpId>`, `seal-use context --corp <corpId>`, `seal-use source config --corp <corpId>`;这些查询优先用于定位企业结构、原始费用/发票和当前审核知识,不要把结果误当成写操作。
|
||||
- LLM Model Config & Providers: `seal-use llm config --corp <corpId>`, `seal-use llm providers --corp <corpId>`.
|
||||
- System Permissions Config: `seal-use permissions available --corp <corpId>`, `seal-use permissions configs --corp <corpId>`.
|
||||
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
|
||||
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` (别名 `status`) 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
|
||||
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
|
||||
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
|
||||
- 审批记录转 Webhook 重放 (Universal Record Replay): `seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]` (支持 `--sn <documentSN>` 反查与跨企业 `--source-corp <corpId>` 提取)。通用支持从任何历史审批记录(Webhook 来源、Hose 来源等)汲取结构化表单与明细字段,自动清洗规范化字段类型,再次通过 Webhook 通道重复触发全新审批实例,方便测试环境回归验证与 Bad Case 靶向调试。
|
||||
|
||||
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
|
||||
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
|
||||
- 系统自检、环境体检与内嵌架构规范白皮书: `seal-use doctor` (整机环境、目录状态、企业资产统计与健康自检,零磁盘写入), `seal-use doctor guide` (纯内存只读输出内嵌白皮书与目录规范), `seal-use doctor paths` (紧凑型核心目录健康检查)。
|
||||
- Full CLI inventory: read `references/cli.md`.
|
||||
|
||||
## Material-pack Webhook policy and recovery
|
||||
@@ -92,6 +119,12 @@ push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附
|
||||
## High-Value Commands
|
||||
|
||||
```bash
|
||||
seal-use doctor
|
||||
seal-use doctor guide
|
||||
seal-use corps list [query] [--env production|test] [--strict]
|
||||
seal-use corps search <keyword> [--env production|test] [--strict]
|
||||
seal-use corps get <corpId>
|
||||
seal-use approval-runs url <recordId> --corp <corpId>
|
||||
seal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest
|
||||
seal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
|
||||
seal-use approval-runs get <recordId> --corp <corpId> --summary
|
||||
@@ -103,6 +136,9 @@ seal-use approval-runs result <recordId> --corp <corpId> --summary
|
||||
seal-use rules count --corp <corpId>
|
||||
seal-use rules list --corp <corpId> --summary
|
||||
seal-use rules lint --corp <corpId> --summary
|
||||
seal-use rules pull --corp <corpId> --out ./rules.local.json
|
||||
seal-use rules push --corp <corpId> --file ./rules.local.json --dry-run
|
||||
seal-use rules map --corp <corpId> --version latest
|
||||
seal-use rules clear --corp <corpId> --dry-run
|
||||
seal-use rules clear --corp <corpId> --yes
|
||||
seal-use rules get --corp <corpId> --version 16 --code '#0038'
|
||||
@@ -113,6 +149,12 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
|
||||
seal-use simulation list --corp <corpId>
|
||||
seal-use simulation get <batchId> --corp <corpId>
|
||||
seal-use simulation batch-records <batchId> --corp <corpId>
|
||||
seal-use simulation status <batchId> --corp <corpId>
|
||||
seal-use simulation approval-definitions --corp <corpId>
|
||||
seal-use approval-runs export --corp <corpId> --downloads --completed-only
|
||||
seal-use analytics insight --corp <corpId>
|
||||
seal-use contacts departments --corp <corpId>
|
||||
seal-use data invoices --corp <corpId> --limit 20
|
||||
seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}'
|
||||
```
|
||||
|
||||
@@ -139,6 +181,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
|
||||
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
|
||||
- `references/hose-enterprise-deploy.md`: Seal AI 智能审核发布到合思费控(添加/编辑配置、平台自动探测、一键同步与 EBot 节点发布)。
|
||||
- `references/approval-attachment-trace.md`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。
|
||||
- `references/staging-simulation-workflow.md`: 生产与测试环境搭配配置、合思集成免配自动同步、单据模拟测试验证与生产规则安全演进闭环指南。
|
||||
- `references/cli.md`: 完整 CLI 命令清单。
|
||||
|
||||
## Safety
|
||||
|
||||
@@ -84,6 +84,43 @@ seal-use approval-runs result <recordId> --corp <corpId> --summary
|
||||
|
||||
This is for decision, summary, risk point count, matched rule count, trace ID, and record ID.
|
||||
|
||||
## Approval Run Web Links & SSO Links
|
||||
|
||||
Use this when the user asks for a link to an approval run or wants to open the run directly in their browser:
|
||||
|
||||
```bash
|
||||
# 默认推荐:生成干净的深度链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)
|
||||
seal-use approval-runs url <recordId> --corp <corpId>
|
||||
seal-use approval-runs url --sn <sourceDocumentSN> --corp <corpId>
|
||||
|
||||
# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带单次临时票据的 SSO 直登链接
|
||||
seal-use approval-runs url <recordId> --sso [--expire 7200] --corp <corpId>
|
||||
```
|
||||
|
||||
### SSO 链接安全与声明规范
|
||||
当向用户返回 `--sso` 链接时,Agent **必须**在回答中明确说明以下 4 点:
|
||||
1. **身份主体**:该链接代表哪个具体员工身份(如管理员姓名)登录。
|
||||
2. **权限范围**:该身份在 Seal AI 平台的全部权限范围(如完全操作权限)。
|
||||
3. **时效性**:临时 Ticket 换票时效(默认 2 小时,换票登录后会话有效 30 天)。
|
||||
4. **安全与防扩散边界**:该链接仅在 Seal AI 租户内生效,不代表合思主系统权限;严禁在公开或外部群聊中传播。
|
||||
|
||||
> **链接输出要求**:无论返回普通深度链接还是 SSO 链接,必须同时提供纯文本代码块(` ```text ... ``` `)防止默认浏览器误点重定向,以及可点击的 Markdown 超链接。
|
||||
|
||||
## Replay Run into Webhook for Regression Testing
|
||||
|
||||
When diagnosing a bad case or verifying rule fixes, replay the historic run's structured fields and items back through a Webhook channel:
|
||||
|
||||
```bash
|
||||
# 预览重放单据(无网络请求,清洗并规范化表单与明细类型)
|
||||
seal-use webhook replay <recordId> --dry-run --corp <corpId>
|
||||
|
||||
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
|
||||
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId>
|
||||
|
||||
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
|
||||
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId>
|
||||
```
|
||||
|
||||
## Output Discipline
|
||||
|
||||
If a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.
|
||||
@@ -9,8 +9,11 @@ seal-use <command>
|
||||
Enterprise config lookup:
|
||||
|
||||
- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.
|
||||
- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.
|
||||
- User-level configs override same-ID local configs.
|
||||
- Otherwise the user-level `~/.config/seal-use/enterprises` directory is loaded. A configured
|
||||
`testEnterprisesDir` is loaded first for test-tenant workflows. The current working directory's
|
||||
`./enterprises` directory is not loaded implicitly.
|
||||
- Set `SEAL_USE_ENTERPRISES_DIR` to use one explicit directory instead. Legacy
|
||||
`~/.config/seal-home/enterprises` files are migrated to the primary directory when possible.
|
||||
|
||||
Enterprise selection is stateless by default. Commands that access an enterprise require
|
||||
`--corp <corpId>` unless stateful mode is explicitly enabled:
|
||||
@@ -39,15 +42,40 @@ seal-use config get
|
||||
seal-use config mode <stateful|stateless> [--corp <corpId>]
|
||||
seal-use config test-dir [<path>|--clear]
|
||||
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
|
||||
seal-use rules count [--corp <corpId>]
|
||||
seal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]
|
||||
seal-use rules clear [--corp <corpId>] [--dry-run|--yes]
|
||||
seal-use rules versions [--corp <corpId>]
|
||||
seal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]
|
||||
seal-use rules get --corp <corpId> --version <number|latest> --code '#0038'
|
||||
seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
|
||||
seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]
|
||||
seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
|
||||
seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]
|
||||
seal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]
|
||||
seal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]
|
||||
seal-use http [--port 8787] [--host 127.0.0.1]
|
||||
seal-use serve [--port 8787]
|
||||
seal-use update
|
||||
seal-use update [--check] [--force] [--version <v>]
|
||||
seal-use update check
|
||||
seal-use update changelog [--limit <n>]
|
||||
seal-use changelog [--limit <n>]
|
||||
seal-use mcp
|
||||
seal-use mcp config
|
||||
seal-use mcp-config
|
||||
seal-use skill dump
|
||||
seal-use skill install [--dir <path>|--local]
|
||||
seal-use skill status
|
||||
seal-use openapi
|
||||
seal-use doctor [--quiet]
|
||||
seal-use doctor guide
|
||||
seal-use doctor paths
|
||||
seal-use probe [<corpId>]
|
||||
seal-use tools list
|
||||
seal-use corps list [--corp <corpId>]
|
||||
seal-use corps list [query] [--env <production|test>] [--strict] [--corp <corpId>]
|
||||
seal-use corps search <query> [--env <production|test>] [--strict]
|
||||
seal-use corps get <corpId>
|
||||
seal-use corps current [--corp <corpId>]
|
||||
seal-use corps switch <corpId>
|
||||
seal-use corps mark <corpId> --env <production|test> [--confirm]
|
||||
@@ -63,6 +91,9 @@ seal-use delegation list [--corp <corpId>]
|
||||
seal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
|
||||
seal-use delegation revoke <tokenId> [--corp <corpId>]
|
||||
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
|
||||
seal-use users search <keyword> [--corp <corpId>]
|
||||
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
|
||||
seal-use users activate <userId> [--corp <corpId>]
|
||||
seal-use users reset-password <userId> [--corp <corpId>]
|
||||
seal-use users get <userId> [--corp <corpId>]
|
||||
seal-use users delete <userId> [--corp <corpId>]
|
||||
@@ -79,14 +110,18 @@ seal-use permissions configs [--corp <corpId>]
|
||||
seal-use billing status [--corp <corpId>]
|
||||
seal-use billing plans [--corp <corpId>]
|
||||
seal-use billing features [--corp <corpId>]
|
||||
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
|
||||
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
|
||||
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
|
||||
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use webhook replay <recordId> [--sn <documentSN>] [--webhook <idOrName>] [--source-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]
|
||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||
seal-use deploy hosecloud list [--corp <corpId>]
|
||||
seal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]
|
||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||
seal-use deploy hosecloud status [--corp <corpId>]
|
||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
|
||||
@@ -96,6 +131,7 @@ seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--co
|
||||
seal-use preference thinking-depth policies list [--corp <corpId>]
|
||||
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
|
||||
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
|
||||
seal-use source config [--corp <corpId>]
|
||||
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
|
||||
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
|
||||
@@ -108,9 +144,10 @@ seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|documen
|
||||
seal-use approval-runs attachments <recordId> --corp <corpId>
|
||||
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>
|
||||
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
|
||||
seal-use approval-runs url --corp <corpId>
|
||||
seal-use approval-runs url <recordId> --corp <corpId>
|
||||
seal-use approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
|
||||
seal-use approval-runs url <recordId> --sso [--expire 7200] --corp <corpId>
|
||||
seal-use approval-runs url --sn <documentSN> [--sso] --corp <corpId>
|
||||
seal-use approval-runs url --corp <corpId>
|
||||
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
|
||||
seal-use simulation batch-records <batchId> --corp <corpId>
|
||||
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp <corpId>
|
||||
@@ -143,11 +180,28 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
|
||||
|
||||
`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.
|
||||
|
||||
Identity and session:
|
||||
System diagnostic & embedded architecture specifications:
|
||||
|
||||
- `seal-use doctor [--quiet]` executes a comprehensive read-only environment diagnostic health check (runtime executable, filesystem paths health, enterprise assets summary, daemon status) with zero disk footprint.
|
||||
- `seal-use doctor guide` reads the complete embedded system architecture & directory specification whitepaper directly from binary memory without touching disk.
|
||||
- `seal-use doctor paths` outputs compact JSON audit of all filesystem paths touched by the CLI.
|
||||
|
||||
Enterprise and tenant management:
|
||||
|
||||
- `seal-use corps list [query] [--env <production|test>] [--strict] [--corp <corpId>]`
|
||||
- `seal-use corps search <query> [--env <production|test>] [--strict]` (intelligent soft search by default: case-insensitive, Chinese homophones, front/back nasal vowels, flat/retroflex consonants, initials, typo/missing letter tolerance; pass `--strict` for exact substring match)
|
||||
- `seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
|
||||
- `seal-use corps current [--corp <corpId>]`
|
||||
- `seal-use corps switch <corpId>`
|
||||
- `seal-use auth diagnose --corp <corpId>`
|
||||
- `seal-use corps list`
|
||||
- `seal-use corps current`
|
||||
|
||||
Read-only discovery:
|
||||
|
||||
- `seal-use contacts departments|children|users|sync-time --corp <corpId>` queries the tenant's organization tree and last directory sync time.
|
||||
- `seal-use data expenses|invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]` queries paginated raw expense or invoice records.
|
||||
- `seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]` queries risk-tag statistics; omitted dates use the current month.
|
||||
- `seal-use context --corp <corpId> [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50]` aggregates rules, knowledge documents, and style preferences.
|
||||
- `seal-use source config --corp <corpId>` resolves the live source-system configuration without changing it.
|
||||
|
||||
Test Enterprise Binding & Staging Synchronization:
|
||||
|
||||
@@ -191,13 +245,17 @@ Approval run lightweight queries:
|
||||
|
||||
Approval knowledge documents & style:
|
||||
|
||||
- `seal-use tool seal_approval_documents_list --corp <corpId> --json '{"limit":50}'`
|
||||
- `seal-use tool seal_approval_document_get --corp <corpId> --json '{"documentId":"doc-id"}'`
|
||||
- `seal-use tool seal_approval_document_create --corp <corpId> --json '{"title":"标题","purpose":"用途","content":"Markdown 内容","contentType":"policy","scenarios":["audit"]}'`
|
||||
- `seal-use tool seal_approval_document_update --corp <corpId> --json '{"documentId":"doc-id","enabled":false}'`
|
||||
- `seal-use tool seal_approval_delete_document --corp <corpId> --json '{"documentId":"doc-id"}'` (删除前必须重新读取并确认)
|
||||
- `seal-use rules get --corp <corpId> --version <number> --code '#0038'`
|
||||
- `seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205`
|
||||
|
||||
Webhook integrations:
|
||||
|
||||
- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook <idOrName>] [--corp <corpId>]`
|
||||
- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp <corpId>]`
|
||||
- `seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]`
|
||||
- `seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
|
||||
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]`
|
||||
@@ -205,10 +263,11 @@ Webhook integrations:
|
||||
- `seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]`
|
||||
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
|
||||
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>`
|
||||
- `seal-use webhook replay <recordId> [--sn <documentSN>] [--webhook <idOrName>] [--source-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]` (从历史单据汲取结构化表单与明细并清洗规范化字段类型,重新通过 Webhook 触发审批)
|
||||
|
||||
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
|
||||
|
||||
All supported configuration writes accept `--dry-run`: rules clear/push, preference updates, thinking-depth policy changes, HoseCloud configure, and Webhook add/update/delete. Preview mode performs read-only discovery and returns JSON with `preview: true`, the exact `targetUrl`, a redacted `changesDiff` (`before`/`after`), and `impactCount`. It never sends the mutation request and does not require `--yes`; use the same command with `--yes` only after reviewing the preview.
|
||||
All supported configuration writes accept `--dry-run`: rules clear/push, `corps sync-test`, preference updates, thinking-depth policy changes, HoseCloud configure, and Webhook add/update/delete. Preview mode performs read-only discovery and returns JSON with `preview: true`, the exact `targetUrl`, a redacted `changesDiff` (`before`/`after`), and `impactCount`. It never sends the mutation request and does not require `--yes`; use the same command with `--yes` only after reviewing the preview.
|
||||
|
||||
Approval runs, simulations, and Langfuse bridge:
|
||||
|
||||
@@ -217,6 +276,7 @@ Approval runs, simulations, and Langfuse bridge:
|
||||
- `seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sn>]`
|
||||
- `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` returns immediately with an `asyncTicket` (creation is non-blocking by default for compatibility).
|
||||
- `seal-use simulation status <batchId> --corp <corpId>` performs one non-blocking status check and returns `QUEUED`/`RUNNING`/`COMPLETED`/`FAILED`-style state plus counters.
|
||||
- `seal-use simulation approval-definitions --corp <corpId>` lists available Feishu approval definitions so an `approvalCode` can be selected before creating a batch.
|
||||
- `seal-use simulation wait <batchId> --corp <corpId>`
|
||||
- `seal-use simulation clean <batchId> --corp <corpId>`
|
||||
- `seal-use simulation list --corp <corpId>`
|
||||
@@ -355,7 +415,7 @@ Create a document:
|
||||
|
||||
`contentType` 必须是 `document`、`video`、`pdf`、`feishu_doc` 或 `policy` 之一;`scenarios` 必填且至少包含一个 `fill`(智能填单)或 `audit`(智能审核)。这里的 `scenarios` 是产品能力开关,不是费用类别或业务场景名。
|
||||
|
||||
知识文档创建后当前 API 没有删除接口,创建操作不可逆;请在写入前确认标题、正文、内容类型和能力场景。需要撤下内容时,优先使用更新操作并设置 `enabled: false`(如果上游支持该字段),不要通过试探性创建来验证参数。规则支持删除,但知识文档与规则的生命周期能力并不对称。
|
||||
知识文档支持通过 `seal_approval_delete_document` 删除,且 `corps sync-test` 会在按标题对账时删除测试企业中多余的文档;删除仍是破坏性写操作,必须在写入前重新读取并确认标题/ID。若只是暂时撤下内容,优先使用更新操作并设置 `enabled: false`。
|
||||
|
||||
Update a document:
|
||||
|
||||
|
||||
@@ -34,9 +34,13 @@ Treat chat text as the customer's expected behavior, not proof of the current Se
|
||||
|
||||
## 2. Resolve and lock the enterprise
|
||||
|
||||
List configured enterprises first:
|
||||
When the customer feedback mentions or hints at the enterprise name, resolve it directly with targeted search rather than dumping the full enterprise list:
|
||||
|
||||
```bash
|
||||
# 优先:按已知企业名称/关键字精确定位目标企业
|
||||
seal-use corps search <enterpriseName>
|
||||
|
||||
# 仅当企业名称完全未知且没有任何线索时才回退至全量列表
|
||||
seal-use corps list
|
||||
```
|
||||
|
||||
|
||||
@@ -8,11 +8,21 @@ Run this before asking for setup parameters (if `seal-use` is not installed, fir
|
||||
|
||||
```bash
|
||||
seal-use version
|
||||
|
||||
# 当用户已提及企业名称或关键字时,优先运行精准搜索:
|
||||
seal-use corps search <keyword> [--env production|test]
|
||||
|
||||
# 仅在完全没有企业线索或初次安装引导时运行全量列表:
|
||||
seal-use corps list
|
||||
|
||||
# 查看目标企业完整富属性(含 Seal 域名、租户 Slug、合思域名、配置来源路径等,安全脱敏):
|
||||
seal-use corps get <corpId>
|
||||
```
|
||||
|
||||
- If `seal-use` is not installed on the system, run the curl install script above to install it.
|
||||
- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
|
||||
- If the user provided an enterprise name or keyword, prioritize `seal-use corps search <keyword>` to locate it without dumping all enterprises. Match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
|
||||
- If zero enterprise context is known, run `seal-use corps list`.
|
||||
- To inspect full endpoint URLs, tenant slug, config file location, and staff bindings of a configured enterprise, run `seal-use corps get <corpId>`.
|
||||
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
|
||||
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# 生产与测试环境搭配配置、模拟测试与生产规则安全演进指南 (Staging Simulation & Rule Evolution)
|
||||
|
||||
本文档面向 AI Agent 与运维人员,规范从**生产/测试环境搭配接入**、**配置与合思集成自动同步**、**测试环境单据模拟验证**,到**生产规则安全投产**的端到端标准工作流。
|
||||
|
||||
---
|
||||
|
||||
## 核心原则 (Core Rules)
|
||||
|
||||
1. **强版本基线 (Latest Version Mandate)**:
|
||||
- 必须确保运行的是最新版本的 `seal-use` CLI、Skill 与 ZCode/Agent 插件。
|
||||
- 在开始引导或执行任何企业操作前,先执行 `seal-use version` 核验。若版本过旧或缺失新特性,优先运行 `seal-use update` 或重新执行安装脚本:
|
||||
```bash
|
||||
# 国内镜像源秒级自愈与升级
|
||||
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测)`。
|
||||
- **严禁向合思执行同步 (`deploy hosecloud sync`)**:测试环境的合思配置只保存在 Seal 端,绝不向合思生产系统推送 EBot 节点或创建真实出站消息,保障生产费控审批流的绝对安全。
|
||||
|
||||
---
|
||||
|
||||
## 端到端标准演进闭环 (The 4-Stage Lifecycle)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Stage 1: 生产与测试环境接入与绑定"] --> B["Stage 2: 生产规则草稿修改 (Draft Only)"]
|
||||
B --> C["Stage 3: 一键安全同步测试环境 (corps sync-test)"]
|
||||
C --> D["Stage 4: 测试环境单据模拟验证 (simulation create)"]
|
||||
D --> E{"验证是否符合预期?"}
|
||||
E -- 存在偏差/误伤 --> B
|
||||
E -- 验证通过 --> F["Stage 5: 生产环境正式发布 (rules publish)"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第一阶段:生产与测试企业搭配配置 (Pairing & Setup)
|
||||
|
||||
1. **定位并识别生产与测试企业**:
|
||||
```bash
|
||||
# 优先使用关键字搜索精准定位目标企业(避免全量列表冗余输出)
|
||||
seal-use corps search <prodOrTestKeyword>
|
||||
|
||||
# 或在完全未知任何企业时查看全量列表
|
||||
seal-use corps list
|
||||
```
|
||||
识别生产企业(`sourceType: "hose"` 或 `"seal"`)与测试企业(如专用的测试环境)。
|
||||
|
||||
2. **如果尚未接入企业**:
|
||||
- 合思标准凭证接入生产企业:`seal-use corps add-hose --json '{"appKey":"...","appSecurity":"...","domain":"..."}'`
|
||||
- 或通过协助链接接入:`seal-use corps add-link <url>`
|
||||
|
||||
3. **环境严格标记与 1 对 1 绑定**:
|
||||
```bash
|
||||
# 1. 明确标记企业环境属性
|
||||
seal-use corps mark <prodCorpId> --env production --confirm
|
||||
seal-use corps mark <testCorpId> --env test --confirm
|
||||
|
||||
# 2. 建立 1 对 1 关联绑定(禁止多层级串联)
|
||||
seal-use corps bind-test <prodCorpId> <testCorpId> --confirm
|
||||
```
|
||||
绑定成功后,执行 `seal-use corps list` 可确认双方已包含 `testCorpId` 与 `prodCorpId` 互斥映射字段。
|
||||
|
||||
---
|
||||
|
||||
### 第二阶段:生产环境规则安全修改 (Production Draft Mutation)
|
||||
|
||||
当用户提出审核规则新增、修改或依据客诉反馈进行修复时,Agent 应遵循以下规范:
|
||||
|
||||
1. **锁定目标企业与规则定位**:
|
||||
```bash
|
||||
# 查询生产企业当前生效规则与草稿规则
|
||||
seal-use rules list --corp <prodCorpId> --summary
|
||||
# 精确读取某条目标规则
|
||||
seal-use rules get --corp <prodCorpId> --code '<ruleCode>'
|
||||
```
|
||||
2. **仅修改草稿(保持生产未发布)**:
|
||||
- 提取最小修改建议(只改动必要的描述语句,保留 `scope` 与 `strictness`)。
|
||||
- 使用规则更新或创建接口修改生产企业草稿:
|
||||
```bash
|
||||
seal-use tool seal_approval_rules_update --corp <prodCorpId> --json '{"ruleId":"...","description":"..."}'
|
||||
```
|
||||
- **最佳安全建议**:修改草稿后,建议先不调用 `seal-use rules publish --corp <prodCorpId>`,而是先引导用户同步至测试企业进行单据模拟验证;若用户明确要求直接投产,则严格遵从用户指示执行发布。
|
||||
|
||||
---
|
||||
|
||||
### 第三阶段:一键安全同步测试环境 (Staging Auto-Sync)
|
||||
|
||||
通过 `corps sync-test` 命令,一键将生产企业的全部变更投影到测试环境:
|
||||
|
||||
1. **预览差异 (`--dry-run`)**:
|
||||
```bash
|
||||
seal-use corps sync-test <prodCorpId> --dry-run
|
||||
```
|
||||
检查输出的 JSON:
|
||||
- `rulesPlan`:生产草稿规则数、测试待替换规则数。
|
||||
- `documentsPlan`:知识库文章的新增、更新与多余清理。
|
||||
- `hosecloudSyncPlan`:合思集成注入计划(显示将自动生成的出站名称与 `assisted` 模式)。
|
||||
|
||||
2. **正式同步与发布 (`--yes`)**:
|
||||
```bash
|
||||
seal-use corps sync-test <prodCorpId> --yes
|
||||
```
|
||||
该命令会在测试企业中全自动完成:
|
||||
- 更新审核风格与偏好设置;
|
||||
- 对账知识库文档(覆盖更新已有文档、创建新文档、删除测试环境多余文档);
|
||||
- 清空测试环境旧草稿规则,灌入生产企业当前草稿规则并重算 code;
|
||||
- 在测试企业自动发布语义版本(格式形如 `[Prod v22 · #1 -> Test v3]`),并保存本地规则映射快照;
|
||||
- **自动同步合思集成**:
|
||||
- 从本地 source 读入 `appKey`/`appSecurity`(兼容 `key`/`password`);
|
||||
- 截取企业名前缀并附加 `(Seal测)`(严格受控于 13 字符限制,例如 `钰泰半导体(Seal测)`);
|
||||
- 强制将审批模式设为 `assisted`;
|
||||
- 自动去重:若生产有多个相同 `corporationId` 的集成(如全自动与辅助),在测试环境自动合并为单条辅助集成;
|
||||
- **不同步至合思**:仅保存在测试环境 Seal,保证合思生产费控零改动。
|
||||
|
||||
3. **速查规则映射**:
|
||||
```bash
|
||||
seal-use rules map --corp <testCorpId> --version latest
|
||||
```
|
||||
查看生产规则 ID/code 与测试规则 ID/code 的对应关系。
|
||||
|
||||
---
|
||||
|
||||
### 第四阶段:测试环境模拟验证与投产闭环 (Simulation & Production Release)
|
||||
|
||||
1. **核验测试环境合思集成已就绪**:
|
||||
```bash
|
||||
seal-use simulation integrations --corp <testCorpId>
|
||||
```
|
||||
确认返回的 `hosecloudIntegrations` 中包含目标企业的测试配置项(如 `钰泰半导体(Seal测)`)。
|
||||
|
||||
2. **创建模拟测试任务**:
|
||||
针对目标真实单据号(或客诉单据)在测试环境发起模拟:
|
||||
```bash
|
||||
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>"
|
||||
```
|
||||
Seal 服务器会自动使用测试环境中保存的合思凭证,直接调用合思 OpenAPI 拉取单据详情,并通过测试环境中刚发布的规则版本执行 AI 预审判断。
|
||||
|
||||
3. **轮询并检查判定结果**:
|
||||
```bash
|
||||
# 查看状态与进度
|
||||
seal-use simulation status <batchId> --corp <testCorpId>
|
||||
# 等待批次完成
|
||||
seal-use simulation wait <batchId> --corp <testCorpId>
|
||||
# 获取详细判决与命中规则
|
||||
seal-use simulation batch-records <batchId> --corp <testCorpId>
|
||||
```
|
||||
核对:
|
||||
- 期望通过的单据是否正确通过;
|
||||
- 期望拦截或预警的单据是否命中了预期的规则(对照 `rules map`);
|
||||
- 是否存在规则描述歧义导致的误判。
|
||||
|
||||
4. **生产环境最终投产 (Final Production Release)**:
|
||||
仅当测试环境所有单据的模拟判定结果完全符合预期时,才在生产企业执行正式发布:
|
||||
```bash
|
||||
seal-use tool seal_approval_rules_publish --corp <prodCorpId> --json '{"versionName":"审核规则 版本N"}'
|
||||
```
|
||||
发布后核实版本状态,完成业务安全闭环。
|
||||
@@ -10,6 +10,7 @@ import { runTool, runToolResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
|
||||
export async function handleApprovalRunsCommand(
|
||||
action: string | undefined,
|
||||
@@ -18,6 +19,11 @@ export async function handleApprovalRunsCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "replay") {
|
||||
await handleWebhookCommand("replay", maybeName, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "summary") {
|
||||
const result = await runToolResult(
|
||||
"seal_approval_runs_summary",
|
||||
@@ -272,14 +278,20 @@ export async function handleApprovalRunsCommand(
|
||||
}
|
||||
|
||||
if (action === "url") {
|
||||
const sso = booleanOption(args.options.sso) ?? false;
|
||||
const expiresIn = numberOption(args.options.expire) ?? numberOption(args.options.expiresIn) ?? 7200;
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
|
||||
|
||||
await runTool(
|
||||
"seal_approval_run_url_get",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
recordId: maybeName,
|
||||
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId)
|
||||
recordId: maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId),
|
||||
sourceDocumentSN: sn,
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId),
|
||||
sso,
|
||||
expiresIn
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
|
||||
@@ -402,6 +402,371 @@ describe("corps sync-test", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTestHosecloudOutboundName", () => {
|
||||
test("appends (Seal测) suffix, using up to 6 chars of corp name", async () => {
|
||||
const { buildTestHosecloudOutboundName } = await import("./corps.js");
|
||||
// Short name — all chars fit
|
||||
expect(buildTestHosecloudOutboundName("钰泰半导体")).toBe("钰泰半导体(Seal测)");
|
||||
// Exactly 6-char prefix
|
||||
expect(buildTestHosecloudOutboundName("美年大健康产业控股")).toBe("美年大健康产(Seal测)");
|
||||
// Long name — truncated to 6 chars prefix
|
||||
expect(buildTestHosecloudOutboundName("钰泰半导体股份有限公司")).toBe("钰泰半导体股(Seal测)");
|
||||
// Total is always ≤ 13 chars
|
||||
const name = buildTestHosecloudOutboundName("一二三四五六七八九十");
|
||||
expect([...name].length).toBeLessThanOrEqual(13);
|
||||
expect(name.endsWith("(Seal测)")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sync-test hosecloud integration auto-sync", () => {
|
||||
function setupHoseTestEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-hose-sync-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
const mappings = join(root, "mappings");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
mkdirSync(mappings, { recursive: true });
|
||||
tempDirs.push(root);
|
||||
|
||||
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_MAPPINGS_DIR = mappings;
|
||||
|
||||
// Prod corp is hose-sourced (has appKey/appSecurity)
|
||||
const prodCorp: CorpConfig = {
|
||||
id: "hose-prod",
|
||||
name: "钰泰半导体股份有限公司",
|
||||
environment: "production",
|
||||
testCorpId: "hose-test",
|
||||
seal: {
|
||||
url: "https://hose-prod.sealai.cc",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://wx2.ekuaibao.com",
|
||||
appKey: "test-app-key-123",
|
||||
appSecurity: "test-app-secret-456",
|
||||
staffId: "hose-prod:staffid",
|
||||
corpId: "hose-prod"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
const testCorp: CorpConfig = {
|
||||
id: "hose-test",
|
||||
name: "谢子豪测试环境",
|
||||
environment: "test",
|
||||
prodCorpId: "hose-prod",
|
||||
seal: {
|
||||
url: "https://hose-test.sealai.cc",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "test-token",
|
||||
sealUrl: "https://hose-test.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "seal"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorp, null, 2));
|
||||
writeFileSync(join(enterprises, "hose-test.json"), JSON.stringify(testCorp, null, 2));
|
||||
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
function mockHoseSyncRequests(options: {
|
||||
prodHosecloudIntegrations?: any[];
|
||||
testHosecloudIntegrations?: any[];
|
||||
onConfigWrite?: (isProd: boolean, body: unknown) => void;
|
||||
} = {}) {
|
||||
const prodIntegrations = options.prodHosecloudIntegrations ?? [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: "prod-sign-key",
|
||||
outboundName: "钰泰正式审批",
|
||||
mode: "fully_automatic",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "custom",
|
||||
customApiUrl: "https://wx2.ekuaibao.com",
|
||||
corporationId: "hose-prod"
|
||||
}
|
||||
];
|
||||
const testIntegrations = options.testHosecloudIntegrations ?? [];
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === "string" ? input
|
||||
: input instanceof URL ? input.toString() : input.url;
|
||||
const method = (
|
||||
init?.method ??
|
||||
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
|
||||
).toUpperCase();
|
||||
const url = new URL(requestUrl);
|
||||
const isProd = url.host.includes("prod");
|
||||
|
||||
let rawBody = typeof init?.body === "string" ? init.body : undefined;
|
||||
if (!rawBody && typeof input === "object" && "text" in input) {
|
||||
rawBody = await (input as Request).clone().text().catch(() => "{}");
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
|
||||
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "hose-prod" : "hose-test" }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Hose → Seal SSO token exchange (used when prod corp is hose-sourced)
|
||||
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
|
||||
return jsonResponse({ token: "mock-hose-seal-token", expiresIn: 3600 });
|
||||
}
|
||||
|
||||
// Hose openapi token exchange
|
||||
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||
return jsonResponse({ value: { accessToken: "mock-hose-openapi-token" } });
|
||||
}
|
||||
|
||||
// Hose provisional auth URL (getProvisionalAuth) — must return a URL with accessToken param
|
||||
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
|
||||
return jsonResponse({ value: { message: "https://mock.ekuaibao.com/provisional?accessToken=mock-closeapi-token" } });
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
tone: "formal",
|
||||
language: "zh-CN",
|
||||
decisionPreferences: { explicitApprove: "", explicitReject: "", exemptApprove: "", review: "" },
|
||||
thinkingDepthPreference: { defaultLevel: "medium", routingPolicies: [] },
|
||||
integrations: isProd ? prodIntegrations : testIntegrations
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
|
||||
const body = JSON.parse(rawBody || "{}");
|
||||
options.onConfigWrite?.(isProd, body);
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
// Minimal stubs for rules/docs/versions
|
||||
if (url.pathname === "/api/v1/knowledge/articles") {
|
||||
return jsonResponse({ data: { articles: [], total: 0 } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rules") {
|
||||
return jsonResponse({ data: { rules: [], hasPendingDeletes: false } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rule-set-versions") {
|
||||
return jsonResponse({ data: [] });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rule-set-versions/publish") {
|
||||
return jsonResponse({ data: { version: { id: "v1", versionNumber: 1, versionName: "v1", rules: [] }, rulesCount: 0 } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rules/batch-recode") {
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
return jsonResponse({ error: `Unexpected: ${method} ${url.pathname}` }, 404);
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
test("hose-sourced prod corp auto-syncs hosecloud integration with assisted mode and naming convention", async () => {
|
||||
setupHoseTestEnv();
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
let capturedTestConfigBody: any;
|
||||
mockHoseSyncRequests({
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedTestConfigBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync).toBeDefined();
|
||||
expect(parsed.hosecloudSync.skipped).toBe(false);
|
||||
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
||||
|
||||
const synced = parsed.hosecloudSync.synced[0];
|
||||
expect(synced.outboundName).toBe("钰泰半导体股(Seal测)");
|
||||
expect(synced.corporationId).toBe("hose-prod");
|
||||
expect(synced.action).toBe("created");
|
||||
|
||||
// Verify the written integration has assisted mode regardless of prod mode
|
||||
expect(capturedTestConfigBody).toBeDefined();
|
||||
const writtenIntegration = capturedTestConfigBody.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.mode).toBe("assisted");
|
||||
expect(writtenIntegration?.apiOrigin).toBe("custom");
|
||||
expect(writtenIntegration?.customApiUrl).toBe("https://wx2.ekuaibao.com");
|
||||
expect(writtenIntegration?.outboundName).toBe("钰泰半导体股(Seal测)");
|
||||
});
|
||||
|
||||
test("preserves existing test signKey when re-syncing (idempotent)", async () => {
|
||||
setupHoseTestEnv();
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
const existingSignKey = "existing-test-sign-key";
|
||||
let capturedBody: any;
|
||||
mockHoseSyncRequests({
|
||||
testHosecloudIntegrations: [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: existingSignKey,
|
||||
outboundName: "钰泰半导体股(Seal测)",
|
||||
mode: "assisted",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "custom",
|
||||
customApiUrl: "https://wx2.ekuaibao.com",
|
||||
corporationId: "hose-prod"
|
||||
}
|
||||
],
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.synced[0].action).toBe("updated");
|
||||
expect(parsed.hosecloudSync.synced[0].signKey).toBe(existingSignKey);
|
||||
|
||||
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.signKey).toBe(existingSignKey);
|
||||
});
|
||||
|
||||
test("skips hosecloud sync for non-hose-sourced prod corps", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-skip-hose-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
tempDirs.push(root);
|
||||
|
||||
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_MAPPINGS_DIR = join(root, "mappings");
|
||||
mkdirSync(join(root, "mappings"), { recursive: true });
|
||||
|
||||
const sealProd: CorpConfig = {
|
||||
id: "seal-prod",
|
||||
name: "Acme Seal Native",
|
||||
environment: "production",
|
||||
testCorpId: "seal-test",
|
||||
seal: { url: "https://seal-prod.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
||||
source: { type: "seal", token: "tok", sealUrl: "https://seal-prod.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
const sealTest: CorpConfig = {
|
||||
id: "seal-test",
|
||||
name: "Acme Test",
|
||||
environment: "test",
|
||||
prodCorpId: "seal-prod",
|
||||
seal: { url: "https://seal-test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
||||
source: { type: "seal", token: "tok2", sealUrl: "https://seal-test.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
writeFileSync(join(enterprises, "seal-prod.json"), JSON.stringify(sealProd, null, 2));
|
||||
writeFileSync(join(enterprises, "seal-test.json"), JSON.stringify(sealTest, null, 2));
|
||||
|
||||
mockHoseSyncRequests({});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "seal-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.skipped).toBe(true);
|
||||
expect(parsed.hosecloudSync.reason).toContain("not hose");
|
||||
});
|
||||
|
||||
test("deduplicates multiple prod integrations for the same corporationId into one test integration", async () => {
|
||||
setupHoseTestEnv();
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
let capturedBody: any;
|
||||
// Prod has TWO integrations for the same corporationId (e.g. assisted and fully_automatic)
|
||||
mockHoseSyncRequests({
|
||||
prodHosecloudIntegrations: [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: "prod-assisted-key",
|
||||
outboundName: "辅助审批",
|
||||
mode: "assisted",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "wechat",
|
||||
corporationId: "hose-prod"
|
||||
},
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: "prod-auto-key",
|
||||
outboundName: "全自动审批",
|
||||
mode: "fully_automatic",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "wechat",
|
||||
corporationId: "hose-prod"
|
||||
}
|
||||
],
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
// Synced array should contain exactly 1 entry, not 2
|
||||
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
||||
expect(parsed.hosecloudSync.synced[0].corporationId).toBe("hose-prod");
|
||||
|
||||
const writtenIntegrations = (capturedBody?.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegrations).toHaveLength(1);
|
||||
expect(writtenIntegrations[0].mode).toBe("assisted");
|
||||
expect(writtenIntegrations[0].apiOrigin).toBe("wechat");
|
||||
});
|
||||
|
||||
test("supports key/password fallback in source config when appKey/appSecurity are omitted", async () => {
|
||||
const { enterprises } = setupHoseTestEnv();
|
||||
// Overwrite hose-prod.json to use key / password instead of appKey / appSecurity
|
||||
const prodCorpWithKeyPassword = JSON.parse(readFileSync(join(enterprises, "hose-prod.json"), "utf-8"));
|
||||
delete prodCorpWithKeyPassword.source.appKey;
|
||||
delete prodCorpWithKeyPassword.source.appSecurity;
|
||||
prodCorpWithKeyPassword.source.key = "fallback-key-789";
|
||||
prodCorpWithKeyPassword.source.password = "fallback-secret-012";
|
||||
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorpWithKeyPassword, null, 2));
|
||||
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
let capturedBody: any;
|
||||
mockHoseSyncRequests({
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.skipped).toBe(false);
|
||||
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
||||
|
||||
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.apiKey).toBe("fallback-key-789");
|
||||
expect(writtenIntegration?.apiSecret).toBe("fallback-secret-012");
|
||||
});
|
||||
});
|
||||
|
||||
describe("corps list & current", () => {
|
||||
test("outputs environment, testCorpId, and prodCorpId", async () => {
|
||||
setupTestEnv();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
@@ -108,6 +108,226 @@ describe("corps link onboarding", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("corp compatibility alias", () => {
|
||||
test("seal-use corp list executes and resolves cleanly like seal-use corps", async () => {
|
||||
setupConfigEnv();
|
||||
const result = await runCli(["corp", "list"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toEqual([]);
|
||||
});
|
||||
|
||||
test("seal-use corp --help executes and resolves cleanly like seal-use corps", async () => {
|
||||
const result = await runCli(["corp", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
|
||||
expect(result.stdout).toContain("seal-use corps list");
|
||||
expect(result.stdout).not.toContain("seal-use webhook");
|
||||
});
|
||||
});
|
||||
|
||||
describe("corps get and search", () => {
|
||||
test("corps get retrieves rich details with sensitive secrets safely redacted", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "demo-hose.json"),
|
||||
JSON.stringify({
|
||||
id: "demo-hose",
|
||||
name: "演示合思企业",
|
||||
environment: "test",
|
||||
seal: {
|
||||
url: "https://demo-hose.sealai.cc",
|
||||
tenantSlug: "demo-hose",
|
||||
headers: { "x-custom-env": "staging" }
|
||||
},
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://dd2.hosecloud.com",
|
||||
appKey: "myAppKey123456",
|
||||
appSecurity: "superSecretAppSecurityValue",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-xiezihao"
|
||||
},
|
||||
auth: { refreshTtl: 600 },
|
||||
testCorpId: "demo-hose",
|
||||
prodCorpId: "demo-prod"
|
||||
})
|
||||
);
|
||||
|
||||
const result = await runCli(["corps", "get", "demo-hose"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).not.toContain("superSecretAppSecurityValue");
|
||||
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.id).toBe("demo-hose");
|
||||
expect(data.name).toBe("演示合思企业");
|
||||
expect(data.environment).toBe("test");
|
||||
expect(data.configFile).toContain("demo-hose.json");
|
||||
expect(data.seal.url).toBe("https://demo-hose.sealai.cc");
|
||||
expect(data.seal.tenantSlug).toBe("demo-hose");
|
||||
expect(data.seal.customHeaderNames).toEqual(["x-custom-env"]);
|
||||
expect(data.source.type).toBe("hose");
|
||||
expect(data.source.corpId).toBe("ID01VAdCnJEdFd");
|
||||
expect(data.source.staffId).toBe("staff-xiezihao");
|
||||
expect(data.source.hasAppSecurity).toBe(true);
|
||||
expect(data.source.appKey).toContain("...");
|
||||
expect(data.source.appKey).not.toBe("myAppKey123456");
|
||||
expect(data.relations.prodCorpId).toBe("demo-prod");
|
||||
expect(data.auth.refreshTtl).toBe(600);
|
||||
});
|
||||
|
||||
test("corps show works as alias for corps get", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "native-seal.json"),
|
||||
JSON.stringify({
|
||||
id: "native-seal",
|
||||
name: "原生Seal租户",
|
||||
environment: "production",
|
||||
seal: {
|
||||
url: "https://native.sealai.cc",
|
||||
tenantSlug: "native-slug"
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://native.sealai.cc",
|
||||
token: "veryLongSecretBearerToken1234567890",
|
||||
expiresIn: 3600,
|
||||
tenantSlug: "native-slug",
|
||||
tenantName: "原生租户",
|
||||
provider: "feishu"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
|
||||
const result = await runCli(["corps", "show", "native-seal"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).not.toContain("veryLongSecretBearerToken1234567890");
|
||||
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.id).toBe("native-seal");
|
||||
expect(data.source.type).toBe("seal");
|
||||
expect(data.source.provider).toBe("feishu");
|
||||
expect(data.source.hasToken).toBe(true);
|
||||
expect(data.source.tokenMasked).toContain("...");
|
||||
});
|
||||
|
||||
test("corps search filters across name, staffId, environment, and keywords", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "corp-prod.json"),
|
||||
JSON.stringify({
|
||||
id: "corp-prod",
|
||||
name: "生产正式企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://prod.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key1",
|
||||
appSecurity: "sec1",
|
||||
corpId: "PROD001",
|
||||
staffId: "admin-zhangsan"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "corp-test.json"),
|
||||
JSON.stringify({
|
||||
id: "corp-test",
|
||||
name: "测试演练企业",
|
||||
environment: "test",
|
||||
seal: { url: "https://test.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://dd2.hosecloud.com",
|
||||
appKey: "key2",
|
||||
appSecurity: "sec2",
|
||||
corpId: "TEST002",
|
||||
staffId: "tester-lisi"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
|
||||
// Search by name
|
||||
const searchName = await runCli(["corps", "search", "演练"]);
|
||||
expect(searchName.exitCode).toBe(0);
|
||||
const resultsName = JSON.parse(searchName.stdout);
|
||||
expect(resultsName.length).toBe(1);
|
||||
expect(resultsName[0].id).toBe("corp-test");
|
||||
expect(resultsName[0].staffId).toBe("tester-lisi");
|
||||
|
||||
// Search by staffId
|
||||
const searchStaff = await runCli(["corps", "search", "zhangsan"]);
|
||||
expect(searchStaff.exitCode).toBe(0);
|
||||
const resultsStaff = JSON.parse(searchStaff.stdout);
|
||||
expect(resultsStaff.length).toBe(1);
|
||||
expect(resultsStaff[0].id).toBe("corp-prod");
|
||||
|
||||
// Search with --env test
|
||||
const searchEnv = await runCli(["corps", "search", "--env", "test"]);
|
||||
expect(searchEnv.exitCode).toBe(0);
|
||||
const resultsEnv = JSON.parse(searchEnv.stdout);
|
||||
expect(resultsEnv.length).toBe(1);
|
||||
expect(resultsEnv[0].id).toBe("corp-test");
|
||||
|
||||
// corps find alias
|
||||
const findResult = await runCli(["corps", "find", "PROD001"]);
|
||||
expect(findResult.exitCode).toBe(0);
|
||||
expect(JSON.parse(findResult.stdout).length).toBe(1);
|
||||
|
||||
// corps list with query positional arg
|
||||
const listWithQuery = await runCli(["corps", "list", "演练"]);
|
||||
expect(listWithQuery.exitCode).toBe(0);
|
||||
expect(JSON.parse(listWithQuery.stdout).length).toBe(1);
|
||||
|
||||
// Soft search by homophone (盛产 -> 生产正式企业)
|
||||
const softHomophone = await runCli(["corps", "search", "盛产"]);
|
||||
expect(softHomophone.exitCode).toBe(0);
|
||||
const softHResults = JSON.parse(softHomophone.stdout);
|
||||
expect(softHResults.length).toBe(1);
|
||||
expect(softHResults[0].id).toBe("corp-prod");
|
||||
|
||||
// Soft search by initials (sc -> 生产)
|
||||
const softInitials = await runCli(["corps", "search", "sc"]);
|
||||
expect(softInitials.exitCode).toBe(0);
|
||||
const softIResults = JSON.parse(softInitials.stdout);
|
||||
expect(softIResults.length).toBe(1);
|
||||
expect(softIResults[0].id).toBe("corp-prod");
|
||||
|
||||
// Soft search with missing letter / typo (zhangsa -> admin-zhangsan)
|
||||
const softTypo = await runCli(["corps", "search", "zhangsa"]);
|
||||
expect(softTypo.exitCode).toBe(0);
|
||||
const softTResults = JSON.parse(softTypo.stdout);
|
||||
expect(softTResults.length).toBe(1);
|
||||
expect(softTResults[0].id).toBe("corp-prod");
|
||||
|
||||
// Strict mode rejects fuzzy matches
|
||||
const strictFuzzy = await runCli(["corps", "search", "盛产", "--strict"]);
|
||||
expect(strictFuzzy.exitCode).toBe(0);
|
||||
expect(JSON.parse(strictFuzzy.stdout).length).toBe(0);
|
||||
expect(strictFuzzy.stderr).toContain("智能软搜索");
|
||||
|
||||
// Strict mode accepts exact substring
|
||||
const strictExact = await runCli(["corps", "search", "生产", "--strict"]);
|
||||
expect(strictExact.exitCode).toBe(0);
|
||||
expect(JSON.parse(strictExact.stdout).length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
function setupConfigEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-link-cli-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
|
||||
+278
-7
@@ -1,7 +1,9 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertHoseAssistTenantMatches,
|
||||
defaultSealUrl,
|
||||
exchangeHoseAssistLink,
|
||||
fetchHoseRoleDefGroups,
|
||||
fetchHoseRoleStaffs,
|
||||
@@ -12,14 +14,16 @@ import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import {
|
||||
findCorpConfigFile,
|
||||
loadCorpConfigs,
|
||||
loadGlobalConfig,
|
||||
resolveWritableEnterprisesDir,
|
||||
saveGlobalConfig,
|
||||
updateCorpConfig
|
||||
} from "../../core/config/loader.js";
|
||||
import { filterCorpsFuzzy } from "../../core/search/fuzzy.js";
|
||||
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
|
||||
import type { CorpConfig, CorpEnvironment } from "../../core/config/types.js";
|
||||
import type { CorpConfig, CorpEnvironment, SealSource } from "../../core/config/types.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { getMe } from "../../domains/seal/api.js";
|
||||
import {
|
||||
@@ -44,25 +48,110 @@ import {
|
||||
import { printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
function maskSecret(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
if (value.length <= 8) return "****";
|
||||
return `${value.slice(0, 4)}...${value.slice(-4)}`;
|
||||
}
|
||||
|
||||
function resolveCorpSealUrl(corp: CorpConfig): string | undefined {
|
||||
if (corp.source.type === "hose") {
|
||||
return defaultSealUrl(corp, corp.source);
|
||||
}
|
||||
return corp.seal.url ?? (corp.source as any).sealUrl;
|
||||
}
|
||||
|
||||
function formatSafeSourceDetail(source: SealSource) {
|
||||
if (source.type === "hose") {
|
||||
const key = source.appKey ?? source.key;
|
||||
return {
|
||||
type: "hose",
|
||||
provider: "hosecloud",
|
||||
domain: source.domain,
|
||||
corpId: source.corpId,
|
||||
staffId: source.staffId,
|
||||
appKey: maskSecret(key),
|
||||
hasAppSecurity: Boolean(source.appSecurity ?? source.password),
|
||||
sealUrl: source.sealUrl
|
||||
};
|
||||
}
|
||||
|
||||
if (source.type === "seal") {
|
||||
return {
|
||||
type: "seal",
|
||||
provider: source.provider ?? "seal",
|
||||
tenantId: source.tenantId,
|
||||
tenantSlug: source.tenantSlug,
|
||||
tenantName: source.tenantName,
|
||||
providerUserId: source.providerUserId,
|
||||
staffId: source.staffId,
|
||||
corpId: source.corpId,
|
||||
sealUrl: source.sealUrl,
|
||||
hasToken: Boolean(source.token),
|
||||
tokenMasked: maskSecret(source.token),
|
||||
expiresIn: source.expiresIn
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "direct",
|
||||
provider: "direct",
|
||||
staffId: source.staffId,
|
||||
corpId: source.corpId,
|
||||
sealUrl: source.sealUrl,
|
||||
hasToken: Boolean(source.token),
|
||||
tokenMasked: maskSecret(source.token),
|
||||
expiresIn: source.expiresIn
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
|
||||
if (action === "list") {
|
||||
if (!action || action === "list" || action === "search" || action === "find") {
|
||||
const rawQuery = (
|
||||
maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.q)
|
||||
)?.trim();
|
||||
const isStrict = booleanOption(args.options.strict) === true;
|
||||
|
||||
const envFilter = (
|
||||
stringOption(args.options.env) ?? stringOption(args.options.environment)
|
||||
)?.trim().toLowerCase();
|
||||
|
||||
if ((action === "search" || action === "find") && !rawQuery && !envFilter) {
|
||||
throw usageError("Usage: seal-use corps search <query> [--env <production|test>] [--strict]");
|
||||
}
|
||||
|
||||
const corpId = stringOption(args.options.corp);
|
||||
const corps = loadCorpConfigs();
|
||||
const allCorps = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorpId = corpId ?? (
|
||||
globalConfig.stateful
|
||||
? globalConfig.defaultCorpId ?? corps[0]?.id
|
||||
? globalConfig.defaultCorpId ?? allCorps[0]?.id
|
||||
: undefined
|
||||
);
|
||||
if (corps.length === 0) {
|
||||
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。");
|
||||
|
||||
let filtered = allCorps;
|
||||
|
||||
if (envFilter) {
|
||||
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
|
||||
}
|
||||
printJson(corps.map((item) => ({
|
||||
|
||||
if (rawQuery) {
|
||||
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict });
|
||||
}
|
||||
|
||||
if (allCorps.length === 0) {
|
||||
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。");
|
||||
} else if (isStrict && filtered.length === 0 && (action === "search" || action === "find") && rawQuery) {
|
||||
console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`);
|
||||
}
|
||||
|
||||
printJson(filtered.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
environment: item.environment ?? "production",
|
||||
sourceType: item.source.type,
|
||||
provider: (item.source as any).provider ?? item.source.type,
|
||||
staffId: item.source.staffId,
|
||||
testCorpId: item.testCorpId,
|
||||
prodCorpId: item.prodCorpId,
|
||||
current: item.id === currentCorpId
|
||||
@@ -70,6 +159,39 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "get" || action === "show") {
|
||||
const targetCorpId = maybeName ?? stringOption(args.options.corp);
|
||||
if (!targetCorpId) {
|
||||
throw usageError("Usage: seal-use corps get <corpId>");
|
||||
}
|
||||
const corp = selectCorp(targetCorpId);
|
||||
const configFile = findCorpConfigFile(corp.id);
|
||||
const sealUrl = resolveCorpSealUrl(corp);
|
||||
|
||||
printJson({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
environment: corp.environment ?? "production",
|
||||
configFile,
|
||||
seal: {
|
||||
url: sealUrl,
|
||||
tenantSlug: corp.seal.tenantSlug ?? (corp.source as any).tenantSlug,
|
||||
customHeaderNames: corp.seal.headers ? Object.keys(corp.seal.headers) : [],
|
||||
customCookieNames: corp.seal.cookies ? Object.keys(corp.seal.cookies) : [],
|
||||
endpoints: corp.seal.endpoints
|
||||
},
|
||||
source: formatSafeSourceDetail(corp.source),
|
||||
relations: {
|
||||
testCorpId: corp.testCorpId,
|
||||
prodCorpId: corp.prodCorpId
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: corp.auth.refreshTtl
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "current") {
|
||||
const corp = selectCorp(stringOption(args.options.corp));
|
||||
printJson({
|
||||
@@ -78,6 +200,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
environment: corp.environment ?? "production",
|
||||
sourceType: corp.source.type,
|
||||
provider: (corp.source as any).provider ?? corp.source.type,
|
||||
staffId: corp.source.staffId,
|
||||
testCorpId: corp.testCorpId,
|
||||
prodCorpId: corp.prodCorpId
|
||||
});
|
||||
@@ -451,6 +574,34 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
publishVersionName: versionName,
|
||||
publishTarget: "test"
|
||||
},
|
||||
hosecloudSyncPlan: (() => {
|
||||
if (prodCorp.source.type !== "hose") {
|
||||
return {
|
||||
sourceType: prodCorp.source.type,
|
||||
skipped: true,
|
||||
reason: "prod source is not hose; no hosecloud credentials available"
|
||||
};
|
||||
}
|
||||
const rawHose = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
const seen = new Set<string>();
|
||||
const distinct = rawHose.filter((i: any) => {
|
||||
const cid = i.corporationId ?? prodCorp.id;
|
||||
if (seen.has(cid)) return false;
|
||||
seen.add(cid);
|
||||
return true;
|
||||
});
|
||||
return {
|
||||
sourceType: "hose",
|
||||
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
|
||||
targetMode: "assisted",
|
||||
integrationsCount: distinct.length,
|
||||
integrations: distinct.map((i: any) => ({
|
||||
corporationId: i.corporationId,
|
||||
apiOrigin: i.apiOrigin,
|
||||
customApiUrl: i.customApiUrl
|
||||
}))
|
||||
};
|
||||
})(),
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
@@ -574,6 +725,11 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
});
|
||||
} catch {}
|
||||
|
||||
// 7. Sync hosecloud integrations from prod to test (hose-source corps only)
|
||||
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient).catch(
|
||||
(err) => ({ skipped: true, reason: `error: ${err?.message ?? String(err)}` } as HosecloudSyncResult)
|
||||
);
|
||||
|
||||
printJson({
|
||||
success: true,
|
||||
syncedAt: new Date().toISOString(),
|
||||
@@ -614,6 +770,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
versionMapping,
|
||||
ruleMapping,
|
||||
...(mappingSavedTo ? { mappingSavedTo } : {}),
|
||||
hosecloudSync,
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
@@ -676,6 +833,120 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hosecloud integration sync helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build the outboundName for a test-env hosecloud integration.
|
||||
* Format: {企业名前7字}(Seal测) — capped at 13 chars total.
|
||||
*/
|
||||
export function buildTestHosecloudOutboundName(corpName: string): string {
|
||||
// "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix.
|
||||
const suffix = "(Seal测)"
|
||||
const maxPrefix = 13 - suffix.length // 6
|
||||
const prefix = [...corpName].slice(0, maxPrefix).join("")
|
||||
return prefix + suffix
|
||||
}
|
||||
|
||||
interface HosecloudSyncResult {
|
||||
skipped: boolean
|
||||
reason?: string
|
||||
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hosecloud integrations from the production Seal enterprise into the
|
||||
* test Seal enterprise. Rules:
|
||||
* - Only runs when prodCorp.source.type === "hose" (credentials available locally)
|
||||
* - outboundName: buildTestHosecloudOutboundName(prodCorp.name)
|
||||
* - mode: always "assisted"
|
||||
* - apiKey/apiSecret: from prodCorp.source.appKey / appSecurity
|
||||
* - apiOrigin/customApiUrl: copied verbatim from the production integration config
|
||||
* - signKey: existing test integration keeps its key; new ones get a fresh random key
|
||||
* - Does NOT call syncHosecloudOutbound (no sync to 合思)
|
||||
*/
|
||||
async function syncHosecloudIntegrationsToTest(
|
||||
prodCorp: import("../../core/config/types.js").CorpConfig,
|
||||
testCorp: import("../../core/config/types.js").CorpConfig,
|
||||
prodClient: import("ky").KyInstance,
|
||||
testClient: import("ky").KyInstance
|
||||
): Promise<HosecloudSyncResult> {
|
||||
if (prodCorp.source.type !== "hose") {
|
||||
return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" }
|
||||
}
|
||||
|
||||
const appKey = (((prodCorp.source as any).appKey ?? (prodCorp.source as any).key) as string | undefined)?.trim()
|
||||
const appSecurity = (((prodCorp.source as any).appSecurity ?? (prodCorp.source as any).password) as string | undefined)?.trim()
|
||||
if (!appKey || !appSecurity) {
|
||||
return { skipped: true, reason: "prod hose source missing appKey/appSecurity (or key/password)" }
|
||||
}
|
||||
|
||||
const [prodPref, testPref] = await Promise.all([
|
||||
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
|
||||
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any))
|
||||
])
|
||||
|
||||
const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud")
|
||||
if (prodIntegrations.length === 0) {
|
||||
return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" }
|
||||
}
|
||||
|
||||
// Deduplicate prod integrations by corporationId:
|
||||
// Production enterprises may have multiple integrations (e.g. "assisted" + "fully_automatic")
|
||||
// with the same corporationId. For the test environment, exactly one assisted integration per
|
||||
// corporationId is needed.
|
||||
const seenCorpIds = new Set<string>()
|
||||
const distinctProdIntegrations: any[] = []
|
||||
for (const item of prodIntegrations) {
|
||||
const cid = item.corporationId ?? prodCorp.id
|
||||
if (!seenCorpIds.has(cid)) {
|
||||
seenCorpIds.add(cid)
|
||||
distinctProdIntegrations.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
const testIntegrations: any[] = (testPref.integrations ?? [])
|
||||
const testByCorpId = new Map<string, any>(
|
||||
testIntegrations.filter((i: any) => i.type === "hosecloud").map((i: any) => [i.corporationId, i])
|
||||
)
|
||||
|
||||
const outboundName = buildTestHosecloudOutboundName(prodCorp.name)
|
||||
const synced: HosecloudSyncResult["synced"] = []
|
||||
|
||||
const nextHosecloudIntegrations: any[] = distinctProdIntegrations.map((prodInt: any) => {
|
||||
const existing = testByCorpId.get(prodInt.corporationId)
|
||||
const signKey = existing?.signKey ?? randomBytes(6).toString("hex")
|
||||
synced!.push({
|
||||
signKey,
|
||||
outboundName,
|
||||
corporationId: prodInt.corporationId,
|
||||
action: existing ? "updated" : "created"
|
||||
})
|
||||
return {
|
||||
type: "hosecloud",
|
||||
signKey,
|
||||
outboundName,
|
||||
mode: "assisted",
|
||||
apiKey: appKey,
|
||||
apiSecret: appSecurity,
|
||||
apiOrigin: prodInt.apiOrigin,
|
||||
...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}),
|
||||
corporationId: prodInt.corporationId
|
||||
}
|
||||
})
|
||||
|
||||
// Merge: keep non-hosecloud entries + newly built hosecloud entries
|
||||
const otherIntegrations = testIntegrations.filter((i: any) => i.type !== "hosecloud")
|
||||
const nextConfig = {
|
||||
...testPref,
|
||||
integrations: [...otherIntegrations, ...nextHosecloudIntegrations]
|
||||
}
|
||||
await api.updateApprovalStylePreferences(testClient, nextConfig, testCorp.seal.endpoints.approvalStylePreferences)
|
||||
|
||||
return { skipped: false, synced }
|
||||
}
|
||||
|
||||
async function probeHoseCorp(input: Record<string, unknown>) {
|
||||
const appKey = requiredString(input, "appKey");
|
||||
const appSecurity = requiredString(input, "appSecurity");
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
describe("seal-use doctor CLI", () => {
|
||||
test("runs full system diagnosis and outputs JSON to stdout and dashboard to stderr", async () => {
|
||||
const result = await runCli(["doctor"]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
// stdout must be clean, parseable JSON
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(["ok", "warning"]).toContain(data.doctor);
|
||||
expect(data.runtime).toBeDefined();
|
||||
expect(data.runtime.version).toBeDefined();
|
||||
expect(data.directories).toBeDefined();
|
||||
expect(data.directories.configDir).toBeDefined();
|
||||
expect(data.enterprises).toBeDefined();
|
||||
expect(data.knowledge).toBeDefined();
|
||||
expect(data.knowledge.guideCommand).toBe("seal-use doctor guide");
|
||||
|
||||
// stderr must contain human-friendly dashboard
|
||||
expect(result.stderr).toContain("Seal Use Doctor");
|
||||
expect(result.stderr).toContain("【运行环境】");
|
||||
expect(result.stderr).toContain("【核心路径状态】");
|
||||
});
|
||||
|
||||
test("doctor guide dumps embedded documentation in Markdown", async () => {
|
||||
const result = await runCli(["doctor", "guide"]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("# Seal Use 系统架构与运行规范白皮书");
|
||||
expect(result.stdout).toContain("系统目录全景规范");
|
||||
expect(result.stdout).toContain("安全与数据隐私保证");
|
||||
expect(result.stderr).toContain("纯内存只读");
|
||||
});
|
||||
|
||||
test("doctor paths outputs compact directory specifications JSON", async () => {
|
||||
const result = await runCli(["doctor", "paths"]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const paths = JSON.parse(result.stdout);
|
||||
expect(paths.configDir).toBeDefined();
|
||||
expect(paths.enterprisesDir).toBeDefined();
|
||||
expect(paths.tokenStore).toBeDefined();
|
||||
expect(paths.agentSkillDir).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { diagnoseSystem, formatDoctorDashboard } from "../../core/doctor/diagnose.js";
|
||||
import { getEmbeddedGuideMarkdown } from "../../core/doctor/knowledge.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleDoctorCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const subAction = (action ?? maybeName ?? "").toLowerCase();
|
||||
|
||||
// 1. Output embedded guide / documentation
|
||||
if (subAction === "guide" || subAction === "doc" || subAction === "knowledge" || subAction === "book") {
|
||||
console.error("📖 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...\n");
|
||||
console.log(getEmbeddedGuideMarkdown());
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Output compact directory specifications
|
||||
if (subAction === "paths" || subAction === "dirs" || subAction === "directories") {
|
||||
const diagnosis = diagnoseSystem();
|
||||
printJson(diagnosis.directories);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Default: Full system diagnostic inspection
|
||||
const diagnosis = diagnoseSystem();
|
||||
|
||||
// If quiet or json-only is not explicitly disabled, output formatted dashboard on stderr
|
||||
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
|
||||
if (!isQuiet) {
|
||||
console.error(formatDoctorDashboard(diagnosis));
|
||||
}
|
||||
|
||||
// Machine channel (stdout): clean, structured JSON
|
||||
printJson(diagnosis);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
config: process.env.SEAL_USE_CONFIG_FILE,
|
||||
tokenStore: process.env.SEAL_USE_TOKEN_STORE
|
||||
};
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
||||
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
|
||||
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function setupMockEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-replay-cli-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
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");
|
||||
|
||||
// Create enterprises dir
|
||||
const fs = require("node:fs");
|
||||
fs.mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
// Write test enterprise config
|
||||
const corpConfig = {
|
||||
id: "test-corp-replay",
|
||||
name: "测试企业重放",
|
||||
sourceType: "seal",
|
||||
seal: {
|
||||
url: "https://test-replay.sealai.cc",
|
||||
tenantSlug: "test-replay",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/system/preferences/approval-style",
|
||||
sourceStatus: "api/v1/source/status",
|
||||
token: "api/v1/auth/token"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "mock-token-xyz",
|
||||
sealUrl: "https://test-replay.sealai.cc"
|
||||
}
|
||||
};
|
||||
writeFileSync(join(enterprises, "test-corp-replay.json"), JSON.stringify(corpConfig, null, 2));
|
||||
|
||||
// Write global config
|
||||
writeFileSync(
|
||||
join(root, "config.json"),
|
||||
JSON.stringify({ defaultCorpId: "test-corp-replay", stateful: true }, null, 2)
|
||||
);
|
||||
|
||||
return enterprises;
|
||||
}
|
||||
|
||||
const mockApprovalRun = {
|
||||
id: "run-001",
|
||||
status: "completed",
|
||||
sourceSystem: "hosecloud",
|
||||
sourceDocumentSN: "BX9990001",
|
||||
sourceDocumentId: "DOC-999",
|
||||
createdAt: 1789115000000,
|
||||
document: {
|
||||
id: "DOC-999",
|
||||
sn: "BX9990001",
|
||||
fields: [
|
||||
{ key: "cost_type", label: "费用类型", type: "TEXT", value: "打车" },
|
||||
{ key: "amount", label: "金额", type: "AMOUNT", value: { amount: 120 } },
|
||||
{ key: "ref_doc", label: "关联申请", type: "REFERENCE", value: "SQ001" }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
const mockWebhookIntegrations = [
|
||||
{
|
||||
type: "webhook",
|
||||
id: "wh-integration-1",
|
||||
name: "默认重放通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: {
|
||||
id: "wh_endpoint_1",
|
||||
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/document"
|
||||
},
|
||||
outgoingResultWebhook: "https://example.com/result",
|
||||
incomingManualResultWebhook: {
|
||||
id: "wh_endpoint_1",
|
||||
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/manual-result"
|
||||
},
|
||||
secret: "mock-secret-456"
|
||||
}
|
||||
];
|
||||
|
||||
describe("seal-use webhook replay CLI", () => {
|
||||
test("fails with usage error if neither recordId nor sn is provided", async () => {
|
||||
setupMockEnv();
|
||||
const result = await runCli(["webhook", "replay"]);
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.stderr).toContain("Usage: seal-use webhook replay");
|
||||
});
|
||||
|
||||
test("executes dry-run preview and strips unallowed types like REFERENCE", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli([
|
||||
"webhook",
|
||||
"replay",
|
||||
"run-001",
|
||||
"--dry-run",
|
||||
"--sn-suffix",
|
||||
"_replay"
|
||||
]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toContain("预览模式");
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
expect(parsed.originalRecord.sourceDocumentSN).toBe("BX9990001");
|
||||
expect(parsed.document.documentSN).toBe("BX9990001_replay");
|
||||
expect(parsed.document.documentId).toBe("DOC-999_replay");
|
||||
// REFERENCE must be normalized to TEXT
|
||||
const refField = parsed.document.fields.find((f: any) => f.key === "ref_doc");
|
||||
expect(refField.type).toBe("TEXT");
|
||||
});
|
||||
|
||||
test("executes live webhook replay with successful response", async () => {
|
||||
setupMockEnv();
|
||||
let pushedBody: any = null;
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (requestUrl.includes("/integrations/webhook/wh_endpoint_1/document")) {
|
||||
let rawBody = init?.body;
|
||||
if (typeof rawBody !== "string" && typeof input === "object" && "text" in input) {
|
||||
rawBody = await (input as Request).clone().text();
|
||||
}
|
||||
pushedBody = JSON.parse(String(rawBody));
|
||||
return new Response(
|
||||
JSON.stringify({ data: { success: true, documentId: "spawned-run-doc-123" } }),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["webhook", "replay", "run-001"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toContain("成功重放单据");
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.pushResult.data.success).toBe(true);
|
||||
expect(pushedBody.documentSN).toBe("BX9990001");
|
||||
});
|
||||
|
||||
test("approval-runs replay routes to webhook replay", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["approval-runs", "replay", "run-001", "--dry-run"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
});
|
||||
});
|
||||
+117
-2
@@ -1,10 +1,16 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { createSealClient as createNewSealClient } from "../../core/http/factory.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { runTool } from "../helpers.js";
|
||||
import { runTool, selectCorp } from "../helpers.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { findWebhookIntegration } from "../../domains/seal/api.js";
|
||||
import type { WebhookIntegration } from "../../domains/seal/types.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "../../domains/seal/types.js";
|
||||
import {
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
transformApprovalRunToWebhookDocument
|
||||
} from "../../domains/seal/webhook-replay.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
@@ -76,6 +82,115 @@ export async function handleWebhookCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "replay") {
|
||||
const recordId =
|
||||
maybeName ??
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.id);
|
||||
const sn =
|
||||
stringOption(args.options.sn) ??
|
||||
stringOption(args.options.documentSn) ??
|
||||
stringOption(args.options["document-sn"]);
|
||||
|
||||
if (!recordId && !sn) {
|
||||
throw new Error(
|
||||
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--webhook <idOrName>] [--source-corp <corpId>] [--sn-suffix <str>] [--dry-run]"
|
||||
);
|
||||
}
|
||||
|
||||
const sourceCorpId = stringOption(args.options.sourceCorp) ?? stringOption(args.options["source-corp"]);
|
||||
const sourceCorp = sourceCorpId ? selectCorp(sourceCorpId) : corp;
|
||||
const sourceClient = sourceCorp.id === corp.id ? client : await createNewSealClient(sourceCorp);
|
||||
|
||||
let run: ApprovalRun;
|
||||
if (recordId) {
|
||||
run = await api.getApprovalRun(sourceClient, recordId);
|
||||
} else {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
|
||||
}
|
||||
run = search.records[0]!;
|
||||
}
|
||||
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
const integration = selectWebhookIntegration(integrations, selector, corp.id);
|
||||
|
||||
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
|
||||
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
|
||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||
const doc = transformApprovalRunToWebhookDocument(run, {
|
||||
snSuffix,
|
||||
snPrefix,
|
||||
docIdSuffix,
|
||||
docIdPrefix
|
||||
});
|
||||
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
if (dryRun) {
|
||||
const dryRunOutput = {
|
||||
dryRun: true,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name },
|
||||
targetCorp: { id: corp.id, name: corp.name },
|
||||
targetWebhook: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
mode: integration.mode,
|
||||
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
|
||||
},
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
document: doc
|
||||
};
|
||||
console.error(
|
||||
`[webhook-replay] 预览模式:已成功从 ${sourceCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
|
||||
);
|
||||
console.log(JSON.stringify(dryRunOutput, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
process.stderr.write(`[webhook-replay] 正在向 Webhook 通道「${integration.name}」推送单据: ${doc.documentSN}...\n`);
|
||||
const pushResult = await pushWebhookDocument(
|
||||
integration.incomingDocumentWebhook.url,
|
||||
integration.secret,
|
||||
doc
|
||||
);
|
||||
const result = {
|
||||
success: true,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name },
|
||||
targetCorp: { id: corp.id, name: corp.name },
|
||||
targetWebhook: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
mode: integration.mode,
|
||||
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
|
||||
},
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
replayedDocument: {
|
||||
documentSN: doc.documentSN,
|
||||
documentId: doc.documentId,
|
||||
fieldCount: doc.fields.length
|
||||
},
|
||||
pushResult
|
||||
};
|
||||
console.error(`🟢 成功重放单据「${doc.documentSN}」至 ${corp.name} (${integration.name})`);
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${corp.id} --limit 1`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "material-pack" || action === "material-pack-push") {
|
||||
const operation = action === "material-pack-push" ? "push" : maybeName;
|
||||
const filePath = action === "material-pack-push"
|
||||
|
||||
+87
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { extractHelpRequest, renderHelp } from "./help.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { KNOWN_AREAS, runCli } from "./runner.js";
|
||||
|
||||
describe("extractHelpRequest", () => {
|
||||
test("detects global help from empty command or help option", () => {
|
||||
@@ -119,6 +119,35 @@ describe("CLI help execution via runCli", () => {
|
||||
expect(result.stdout).not.toContain("seal-use simulation");
|
||||
});
|
||||
|
||||
test("seal-use corp --help resolves to corps domain commands with exitCode 0", async () => {
|
||||
const result = await runCli(["corp", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
|
||||
expect(result.stdout).toContain("seal-use corps list");
|
||||
expect(result.stdout).toContain("seal-use corps bind-test");
|
||||
expect(result.stdout).not.toContain("seal-use webhook");
|
||||
expect(result.stdout).not.toContain("seal-use simulation");
|
||||
});
|
||||
|
||||
test("seal-use webhook replay --help renders replay usage and options with exitCode 0", async () => {
|
||||
const result = await runCli(["webhook", "replay", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use webhook replay");
|
||||
expect(result.stdout).toContain("--sn-suffix");
|
||||
expect(result.stdout).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("seal-use approval-runs replay --help renders replay usage and options with exitCode 0", async () => {
|
||||
const result = await runCli(["approval-runs", "replay", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use approval-runs replay");
|
||||
expect(result.stdout).toContain("--sn-suffix");
|
||||
expect(result.stdout).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("seal-use corps unknown-cmd --help exits with code 2", async () => {
|
||||
const result = await runCli(["corps", "unknown-cmd", "--help"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
@@ -126,3 +155,60 @@ describe("CLI help execution via runCli", () => {
|
||||
expect(result.stderr).toContain("Unknown corps command: unknown-cmd");
|
||||
});
|
||||
});
|
||||
|
||||
describe("help coverage", () => {
|
||||
test("every dispatchable area resolves to help without throwing", () => {
|
||||
for (const area of KNOWN_AREAS) {
|
||||
expect(() => renderHelp([area])).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test("service lifecycle exposes area and command help", () => {
|
||||
const area = renderHelp(["service"]);
|
||||
expect(area).toContain("seal-use service - Background HTTP service lifecycle");
|
||||
expect(area).toContain("seal-use service start");
|
||||
expect(area).toContain("seal-use service logs");
|
||||
expect(renderHelp(["service", "logs"])).toContain("seal-use service logs");
|
||||
});
|
||||
|
||||
test("stop shortcut and server alias resolve to help", () => {
|
||||
expect(renderHelp(["stop"])).toContain("seal-use stop");
|
||||
expect(renderHelp(["server"])).toContain("seal-use mcp");
|
||||
});
|
||||
|
||||
test("global help is generated from the registry and lists lifecycle commands", () => {
|
||||
const help = renderHelp([]);
|
||||
expect(help).toContain("seal-use CLI");
|
||||
expect(help).toContain("seal-use version");
|
||||
expect(help).toContain("seal-use service start");
|
||||
expect(help).toContain("seal-use stop");
|
||||
});
|
||||
|
||||
test("config aliases resolve to the documented commands", () => {
|
||||
expect(renderHelp(["config", "status"])).toContain("seal-use config get");
|
||||
expect(renderHelp(["config", "test-enterprises-dir"])).toContain("seal-use config test-dir");
|
||||
});
|
||||
|
||||
test("singleton areas do not advertise a nonexistent subcommand help", () => {
|
||||
expect(renderHelp(["http"])).not.toContain("<command> --help");
|
||||
expect(renderHelp(["stop"])).not.toContain("<command> --help");
|
||||
expect(renderHelp(["corps"])).toContain("Run 'seal-use corps <command> --help'");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI help execution for lifecycle commands", () => {
|
||||
test("seal-use service --help prints service commands with exitCode 0", async () => {
|
||||
const result = await runCli(["service", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use service start");
|
||||
expect(result.stdout).toContain("seal-use service status");
|
||||
});
|
||||
|
||||
test("seal-use stop --help prints stop help with exitCode 0", async () => {
|
||||
const result = await runCli(["stop", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use stop");
|
||||
});
|
||||
});
|
||||
+161
-129
@@ -31,7 +31,29 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
name: "list",
|
||||
summary: "List all configured enterprises",
|
||||
usage: ["seal-use corps list [--corp <corpId>]"]
|
||||
usage: ["seal-use corps list [query] [--env <production|test>] [--strict] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--env <production|test>", description: "Filter enterprises by environment ('production' or 'test')" },
|
||||
{ flag: "--strict", description: "Use strict exact substring matching instead of default soft fuzzy search" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "search",
|
||||
aliases: ["find"],
|
||||
summary: "Search configured enterprises with intelligent soft fuzzy matching",
|
||||
usage: ["seal-use corps search <query> [--env <production|test>] [--strict]"],
|
||||
options: [
|
||||
{ flag: "--env <production|test>", description: "Filter enterprises by environment ('production' or 'test')" },
|
||||
{ flag: "--strict", description: "Use strict exact substring matching instead of default soft fuzzy search" }
|
||||
],
|
||||
description: "Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."
|
||||
},
|
||||
{
|
||||
name: "get",
|
||||
aliases: ["show"],
|
||||
summary: "Get rich details and configuration of an enterprise",
|
||||
usage: ["seal-use corps get <corpId>"],
|
||||
description: "Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."
|
||||
},
|
||||
{
|
||||
name: "current",
|
||||
@@ -222,6 +244,24 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "material-pack push",
|
||||
summary: "Upload and push a material pack to webhook endpoint",
|
||||
usage: ["seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "replay",
|
||||
summary: "Replay an existing approval record into a Webhook channel",
|
||||
usage: [
|
||||
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID to replay" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN if recordId not given" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration (auto-locks if only one exists)" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where the approval record resides (default: active)" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
|
||||
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
|
||||
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" }
|
||||
],
|
||||
description: "Extracts structured form fields from any historical approval record (Webhook or Hose source), sanitizes field types, and pushes a new document to the target Webhook channel."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -291,17 +331,34 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
summary: "Get web console URL for approval run",
|
||||
summary: "Get web console URL for approval run (default deep link, or --sso for auto-login link)",
|
||||
usage: [
|
||||
"seal-use approval-runs url [--corp <corpId>]",
|
||||
"seal-use approval-runs url <recordId> [--corp <corpId>]",
|
||||
"seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]"
|
||||
"seal-use approval-runs url <recordId> --sso [--expire 7200] [--corp <corpId>]",
|
||||
"seal-use approval-runs url --sn <documentSN> [--sso] [--corp <corpId>]",
|
||||
"seal-use approval-runs url [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "bridge",
|
||||
summary: "Inspect browser bridge integration payload",
|
||||
usage: ["seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "replay",
|
||||
summary: "Replay approval run record into a Webhook integration",
|
||||
usage: [
|
||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where the approval record resides" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -462,6 +519,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "get",
|
||||
aliases: ["status"],
|
||||
summary: "Display current global configuration",
|
||||
usage: ["seal-use config get"]
|
||||
},
|
||||
@@ -472,6 +530,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "test-dir",
|
||||
aliases: ["test-enterprises-dir"],
|
||||
summary: "Set or clear global test enterprises directory",
|
||||
usage: ["seal-use config test-dir [<path>|--clear]"]
|
||||
},
|
||||
@@ -802,6 +861,55 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
title: "Background HTTP service lifecycle",
|
||||
description: "Start, stop, restart, inspect, and read logs from the standalone seal-use HTTP service daemon.",
|
||||
commands: [
|
||||
{
|
||||
name: "start",
|
||||
summary: "Start the background service daemon",
|
||||
usage: ["seal-use service start [--port 8787] [--host 127.0.0.1]"]
|
||||
},
|
||||
{
|
||||
name: "stop",
|
||||
summary: "Stop the background service daemon",
|
||||
usage: ["seal-use service stop"]
|
||||
},
|
||||
{
|
||||
name: "restart",
|
||||
summary: "Restart the background service daemon",
|
||||
usage: ["seal-use service restart [--port 8787] [--host 127.0.0.1]"]
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
summary: "Show service daemon status",
|
||||
usage: ["seal-use service status"]
|
||||
},
|
||||
{
|
||||
name: "logs",
|
||||
summary: "Print recent service daemon logs",
|
||||
usage: ["seal-use service logs [--lines 50]"]
|
||||
},
|
||||
{
|
||||
name: "run",
|
||||
summary: "Run the service in the foreground",
|
||||
usage: ["seal-use service run [--port 8787] [--host 127.0.0.1]"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "stop",
|
||||
title: "Stop the background service",
|
||||
description: "Shortcut for stopping the background seal-use HTTP service daemon.",
|
||||
commands: [
|
||||
{
|
||||
name: "",
|
||||
summary: "Stop the background service daemon",
|
||||
usage: ["seal-use stop"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
title: "OpenAPI specification",
|
||||
@@ -813,6 +921,33 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
usage: ["seal-use openapi"]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "doctor",
|
||||
title: "System diagnostic and environment health check",
|
||||
description: "Inspects runtime executable, filesystem paths, enterprise assets, and embedded specifications without modifying any files.",
|
||||
commands: [
|
||||
{
|
||||
name: "",
|
||||
summary: "Run complete system diagnostic health check",
|
||||
usage: ["seal-use doctor [--quiet]"],
|
||||
options: [
|
||||
{ flag: "--quiet", description: "Suppress formatted human dashboard on stderr" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "guide",
|
||||
aliases: ["doc", "knowledge"],
|
||||
summary: "Read embedded system architecture & directory specification whitepaper",
|
||||
usage: ["seal-use doctor guide"]
|
||||
},
|
||||
{
|
||||
name: "paths",
|
||||
aliases: ["dirs"],
|
||||
summary: "Inspect core filesystem paths and directory health",
|
||||
usage: ["seal-use doctor paths"]
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
@@ -820,7 +955,7 @@ export function extractHelpRequest(args: ParsedArgs): { isHelp: boolean; target:
|
||||
const hasHelpOption = Boolean(args.options.help || args.options.h);
|
||||
|
||||
if (!args.command.length) {
|
||||
return hasHelpOption ? { isHelp: true, target: [] } : { isHelp: true, target: [] };
|
||||
return { isHelp: true, target: [] };
|
||||
}
|
||||
|
||||
if (args.command[0] === "help") {
|
||||
@@ -873,11 +1008,13 @@ export function renderHelp(target: string[] = []): string {
|
||||
|
||||
function normalizeArea(area: string): string {
|
||||
const lower = area.toLowerCase();
|
||||
if (lower === "corp") return "corps";
|
||||
if (lower === "webhooks") return "webhook";
|
||||
if (lower === "preferences") return "preference";
|
||||
if (lower === "changelog") return "update";
|
||||
if (lower === "serve") return "http";
|
||||
if (lower === "mcp-config") return "mcp";
|
||||
if (lower === "server") return "mcp";
|
||||
return lower;
|
||||
}
|
||||
|
||||
@@ -945,132 +1082,27 @@ function renderAreaHelp(areaEntry: AreaHelp): string {
|
||||
lines.push(` ${usage}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push(`Run 'seal-use ${areaEntry.area} <command> --help' for details on a specific command.`);
|
||||
if (areaEntry.commands.some((cmd) => cmd.name)) {
|
||||
lines.push("");
|
||||
lines.push(`Run 'seal-use ${areaEntry.area} <command> --help' for details on a specific command.`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function renderGlobalHelp(): string {
|
||||
return `seal-use CLI
|
||||
|
||||
Usage:
|
||||
seal-use version
|
||||
seal-use mcp
|
||||
seal-use mcp config
|
||||
seal-use mcp-config
|
||||
seal-use skill dump
|
||||
seal-use skill install [--dir <path>|--local]
|
||||
seal-use skill status
|
||||
seal-use http [--port 8787] [--host 127.0.0.1]
|
||||
seal-use serve [--port 8787]
|
||||
seal-use openapi
|
||||
seal-use probe [<corpId>]
|
||||
seal-use config paths
|
||||
seal-use config get
|
||||
seal-use config mode <stateful|stateless> [--corp <corpId>]
|
||||
seal-use config test-dir [<path>|--clear]
|
||||
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
|
||||
seal-use update [--check] [--force] [--version <v>]
|
||||
seal-use update check
|
||||
seal-use update changelog [--limit <n>]
|
||||
seal-use changelog [--limit <n>]
|
||||
seal-use tools list
|
||||
seal-use corps list [--corp <corpId>]
|
||||
seal-use corps current [--corp <corpId>]
|
||||
seal-use corps switch <corpId>
|
||||
seal-use corps mark <corpId> --env <production|test> [--confirm]
|
||||
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
|
||||
seal-use corps unbind-test [<corpId>] [--confirm]
|
||||
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
|
||||
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
|
||||
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
|
||||
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
|
||||
seal-use auth diagnose [--corp <corpId>]
|
||||
seal-use auth hose-link [--corp <corpId>] [--expire 7200]
|
||||
seal-use delegation list [--corp <corpId>]
|
||||
seal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
|
||||
seal-use delegation revoke <tokenId> [--corp <corpId>]
|
||||
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
|
||||
seal-use users search <keyword> [--corp <corpId>]
|
||||
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
|
||||
seal-use users reset-password <userId> [--corp <corpId>]
|
||||
seal-use users get <userId> [--corp <corpId>]
|
||||
seal-use users delete <userId> [--corp <corpId>]
|
||||
seal-use contacts departments [<departmentId>] [--corp <corpId>]
|
||||
seal-use contacts children <departmentId> [--corp <corpId>]
|
||||
seal-use contacts users <departmentId> [--corp <corpId>]
|
||||
seal-use contacts sync-time [--corp <corpId>]
|
||||
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use llm config [--corp <corpId>]
|
||||
seal-use llm providers [--corp <corpId>]
|
||||
seal-use permissions available [--corp <corpId>]
|
||||
seal-use permissions configs [--corp <corpId>]
|
||||
seal-use billing status [--corp <corpId>]
|
||||
seal-use billing plans [--corp <corpId>]
|
||||
seal-use billing features [--corp <corpId>]
|
||||
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
|
||||
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
|
||||
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
|
||||
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
|
||||
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
|
||||
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||
seal-use deploy hosecloud list [--corp <corpId>]
|
||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||
seal-use deploy hosecloud status [--corp <corpId>]
|
||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
||||
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
|
||||
seal-use preference get [--corp <corpId>]
|
||||
seal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth policies list [--corp <corpId>]
|
||||
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
|
||||
seal-use source config [--corp <corpId>]
|
||||
seal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']
|
||||
seal-use rules count [--corp <corpId>]
|
||||
seal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]
|
||||
seal-use rules clear [--corp <corpId>] [--dry-run|--yes]
|
||||
seal-use rules versions [--corp <corpId>]
|
||||
seal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]
|
||||
seal-use rules get --corp <corpId> --version <number|latest> --code '#0038'
|
||||
seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
|
||||
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
|
||||
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
|
||||
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
|
||||
seal-use approval-runs count [--status APPROVED] [--corp <corpId>]
|
||||
seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]
|
||||
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
|
||||
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
|
||||
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
|
||||
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
|
||||
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
|
||||
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
|
||||
seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
|
||||
seal-use approval-runs url [--corp <corpId>]
|
||||
seal-use approval-runs url <recordId> [--corp <corpId>]
|
||||
seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
|
||||
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
|
||||
seal-use simulation batch-records <batchId> [--corp <corpId>]
|
||||
seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp <corpId>]
|
||||
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
|
||||
seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]
|
||||
seal-use simulation status <batchId> [--corp <corpId>]
|
||||
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
|
||||
seal-use simulation clean <batchId> [--corp <corpId>]
|
||||
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
|
||||
seal-use simulation approval-definitions [--corp <corpId>]
|
||||
seal-use simulation list [--limit 50] [--corp <corpId>]
|
||||
seal-use simulation get <batchId> [--corp <corpId>]
|
||||
seal-use simulation templates [--corp <corpId>]
|
||||
seal-use simulation integrations [--corp <corpId>]
|
||||
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
|
||||
`;
|
||||
const lines: string[] = [];
|
||||
lines.push("seal-use CLI");
|
||||
lines.push("");
|
||||
lines.push("Usage:");
|
||||
lines.push(" seal-use version");
|
||||
for (const area of HELP_REGISTRY) {
|
||||
for (const command of area.commands) {
|
||||
for (const usage of command.usage) {
|
||||
lines.push(` ${usage}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("Run 'seal-use <command> --help' for details on a specific command.");
|
||||
return lines.join("\n");
|
||||
}
|
||||
+10
-2
@@ -16,6 +16,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
|
||||
import { handleDeployCommand } from "./commands/deploy.js";
|
||||
import { handleDoctorCommand } from "./commands/doctor.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleLlmCommand } from "./commands/llm.js";
|
||||
import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js";
|
||||
@@ -53,7 +54,7 @@ import {
|
||||
import type { CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
||||
const KNOWN_AREAS = new Set([
|
||||
export const KNOWN_AREAS = new Set([
|
||||
"config",
|
||||
"service",
|
||||
"stop",
|
||||
@@ -62,6 +63,7 @@ const KNOWN_AREAS = new Set([
|
||||
"update",
|
||||
"tools",
|
||||
"corps",
|
||||
"corp",
|
||||
"tool",
|
||||
"source",
|
||||
"auth",
|
||||
@@ -88,6 +90,7 @@ const KNOWN_AREAS = new Set([
|
||||
"skill",
|
||||
"openapi",
|
||||
"probe",
|
||||
"doctor",
|
||||
"changelog"
|
||||
]);
|
||||
|
||||
@@ -220,6 +223,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "doctor") {
|
||||
await handleDoctorCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "config") {
|
||||
handleConfigCommand(action, maybeName, args);
|
||||
return;
|
||||
@@ -274,7 +282,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "corps") {
|
||||
if (area === "corps" || area === "corp") {
|
||||
await handleCorpsCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -401,12 +401,25 @@ export async function getHoseProvisionalAuthLink(
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
url: string;
|
||||
token?: string;
|
||||
expiresIn: number;
|
||||
}> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
|
||||
const cache = getHoseAuthCache(corp.id);
|
||||
if (isFresh(cache.closeapi) && cache.closeapi.url && cache.closeapi.token) {
|
||||
const remainingSeconds = Math.max(60, Math.floor((cache.closeapi.expiresAt - Date.now()) / 1000));
|
||||
return {
|
||||
corpId: corp.source.corpId,
|
||||
staffId: corp.source.staffId,
|
||||
url: cache.closeapi.url,
|
||||
token: cache.closeapi.token,
|
||||
expiresIn: Math.min(expiresIn, remainingSeconds)
|
||||
};
|
||||
}
|
||||
|
||||
const openapiToken = await ensureHoseOpenapiToken(corp);
|
||||
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
|
||||
if (!provisional.url) {
|
||||
@@ -417,6 +430,7 @@ export async function getHoseProvisionalAuthLink(
|
||||
corpId: corp.source.corpId,
|
||||
staffId: corp.source.staffId,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,6 +85,13 @@ describe("resolveCorpConfig", () => {
|
||||
).id).toBe("corp-b");
|
||||
});
|
||||
|
||||
test("resolves an explicit corp case-insensitively and by enterprise name", () => {
|
||||
const corpA = { ...corp("corp-a"), name: "Alpha Corp" };
|
||||
const corpB = { ...corp("corp-b"), name: "Beta Corp" };
|
||||
expect(resolveCorpConfig([corpA, corpB], { stateful: false, corpId: "CORP-B" }).id).toBe("corp-b");
|
||||
expect(resolveCorpConfig([corpA, corpB], { stateful: false, corpId: "alpha corp" }).id).toBe("corp-a");
|
||||
});
|
||||
|
||||
test("resolves the configured default corp in stateful mode", () => {
|
||||
expect(resolveCorpConfig(
|
||||
[corp("corp-a"), corp("corp-b")],
|
||||
|
||||
@@ -12,8 +12,12 @@ export function resolveCorpConfig(
|
||||
const selectedCorpId = requestedCorpId ?? configuredCorpId;
|
||||
|
||||
if (selectedCorpId) {
|
||||
const corp = corps.find((item) => item.id === selectedCorpId);
|
||||
if (corp) return corp;
|
||||
const exact = corps.find((item) => item.id === selectedCorpId);
|
||||
if (exact) return exact;
|
||||
const caseInsensitive = corps.find((item) => item.id.toLowerCase() === selectedCorpId.toLowerCase());
|
||||
if (caseInsensitive) return caseInsensitive;
|
||||
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
|
||||
if (byName) return byName;
|
||||
throw new Error(`No enterprise config found for ${selectedCorpId}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { diagnoseSystem, formatDoctorDashboard } from "./diagnose.js";
|
||||
import {
|
||||
EMBEDDED_DIRECTORY_SPECS,
|
||||
EMBEDDED_DOMAIN_CAPABILITIES,
|
||||
EMBEDDED_SECURITY_POLICIES,
|
||||
getEmbeddedGuideMarkdown
|
||||
} from "./knowledge.js";
|
||||
|
||||
describe("Doctor Embedded Knowledge", () => {
|
||||
test("EMBEDDED_DIRECTORY_SPECS defines core paths", () => {
|
||||
expect(EMBEDDED_DIRECTORY_SPECS.length).toBeGreaterThanOrEqual(8);
|
||||
const names = EMBEDDED_DIRECTORY_SPECS.map((s) => s.name);
|
||||
expect(names).toContain("配置与状态根目录");
|
||||
expect(names).toContain("企业配置文件目录");
|
||||
expect(names).toContain("全局命令行程序");
|
||||
expect(names).toContain("AI Agent 技能主目录");
|
||||
});
|
||||
|
||||
test("EMBEDDED_SECURITY_POLICIES contains core privacy guarantees", () => {
|
||||
expect(EMBEDDED_SECURITY_POLICIES.length).toBeGreaterThanOrEqual(3);
|
||||
const topics = EMBEDDED_SECURITY_POLICIES.map((p) => p.topic);
|
||||
expect(topics).toContain("敏感凭据脱敏保护");
|
||||
expect(topics).toContain("正式环境与测试环境严格隔离");
|
||||
});
|
||||
|
||||
test("EMBEDDED_DOMAIN_CAPABILITIES covers main CLI areas", () => {
|
||||
const domains = EMBEDDED_DOMAIN_CAPABILITIES.map((d) => d.domain);
|
||||
expect(domains.some((d) => d.startsWith("corps"))).toBe(true);
|
||||
expect(domains.some((d) => d.startsWith("approval-runs"))).toBe(true);
|
||||
expect(domains.some((d) => d.startsWith("rules"))).toBe(true);
|
||||
expect(domains.some((d) => d.startsWith("doctor"))).toBe(true);
|
||||
});
|
||||
|
||||
test("getEmbeddedGuideMarkdown renders complete Markdown documentation", () => {
|
||||
const md = getEmbeddedGuideMarkdown();
|
||||
expect(md).toContain("# Seal Use 系统架构与运行规范白皮书");
|
||||
expect(md).toContain("系统目录全景规范");
|
||||
expect(md).toContain("安全与数据隐私保证");
|
||||
expect(md).toContain("业务域能力图谱");
|
||||
expect(md).toContain("seal-use doctor guide");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Doctor Diagnosis Engine", () => {
|
||||
test("diagnoseSystem returns valid read-only diagnostic object without throwing", () => {
|
||||
const diagnosis = diagnoseSystem();
|
||||
|
||||
expect(["ok", "warning"]).toContain(diagnosis.doctor);
|
||||
expect(diagnosis.runtime.version).toBe(VERSION);
|
||||
expect(diagnosis.runtime.executablePath.length).toBeGreaterThan(0);
|
||||
expect(diagnosis.runtime.platform.length).toBeGreaterThan(0);
|
||||
|
||||
expect(diagnosis.directories.configDir).toBeDefined();
|
||||
expect(diagnosis.directories.configDir!.path).toContain(".config");
|
||||
expect(diagnosis.directories.enterprisesDir).toBeDefined();
|
||||
expect(diagnosis.directories.agentSkillDir).toBeDefined();
|
||||
|
||||
expect(diagnosis.checks.length).toBeGreaterThanOrEqual(3);
|
||||
expect(diagnosis.knowledge.directorySpecsCount).toBe(EMBEDDED_DIRECTORY_SPECS.length);
|
||||
});
|
||||
|
||||
test("formatDoctorDashboard renders human-readable summary dashboard", () => {
|
||||
const diagnosis = diagnoseSystem();
|
||||
const dashboard = formatDoctorDashboard(diagnosis);
|
||||
|
||||
expect(dashboard).toContain("Seal Use Doctor");
|
||||
expect(dashboard).toContain("【运行环境】");
|
||||
expect(dashboard).toContain("【核心路径状态】");
|
||||
expect(dashboard).toContain("【企业资产概览】");
|
||||
expect(dashboard).toContain("【健康自检】");
|
||||
expect(dashboard).toContain("seal-use doctor guide");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { accessSync, constants, existsSync, readdirSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
|
||||
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
|
||||
import {
|
||||
EMBEDDED_DIRECTORY_SPECS,
|
||||
EMBEDDED_DOMAIN_CAPABILITIES,
|
||||
EMBEDDED_SECURITY_POLICIES
|
||||
} from "./knowledge.js";
|
||||
|
||||
export interface DirectoryHealth {
|
||||
name: string;
|
||||
path: string;
|
||||
exists: boolean;
|
||||
writable?: boolean;
|
||||
fileCount?: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface HealthCheckItem {
|
||||
id: string;
|
||||
title: string;
|
||||
status: "ok" | "warn" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface DoctorDiagnosis {
|
||||
doctor: "ok" | "warning";
|
||||
timestamp: string;
|
||||
runtime: {
|
||||
version: string;
|
||||
executablePath: string;
|
||||
platform: string;
|
||||
engine: string;
|
||||
};
|
||||
directories: Record<string, DirectoryHealth>;
|
||||
enterprises: {
|
||||
total: number;
|
||||
productionCount: number;
|
||||
testCount: number;
|
||||
activeCorpId?: string;
|
||||
activeCorpName?: string;
|
||||
};
|
||||
checks: HealthCheckItem[];
|
||||
knowledge: {
|
||||
summary: string;
|
||||
directorySpecsCount: number;
|
||||
securityPoliciesCount: number;
|
||||
domainCapabilitiesCount: number;
|
||||
guideCommand: string;
|
||||
};
|
||||
}
|
||||
|
||||
function countJsonFiles(dir: string): number {
|
||||
if (!existsSync(dir)) return 0;
|
||||
try {
|
||||
return readdirSync(dir).filter((file) => file.endsWith(".json")).length;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function isPathWritable(path: string): boolean {
|
||||
try {
|
||||
accessSync(path, constants.W_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, read-only system diagnostic and health inspection.
|
||||
* Never creates, mutates, or deletes any files on the filesystem.
|
||||
*/
|
||||
export function diagnoseSystem(): DoctorDiagnosis {
|
||||
const home = homedir();
|
||||
const configDir = join(home, ".config", "seal-use");
|
||||
const enterprisesDir = join(configDir, "enterprises");
|
||||
const globalConfigFile = join(configDir, "config.json");
|
||||
const tokenStore = join(configDir, "seal_tokens.json");
|
||||
const mappingsDir = join(configDir, "mappings");
|
||||
const agentSkillDir = getDefaultGlobalSkillDir();
|
||||
const exportDir = join(home, "Downloads");
|
||||
|
||||
const globalBinaryCandidates = [
|
||||
"/opt/homebrew/bin/seal-use",
|
||||
"/usr/local/bin/seal-use",
|
||||
join(home, ".local", "bin", "seal-use"),
|
||||
join(home, "bin", "seal-use")
|
||||
];
|
||||
const detectedBinary = globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
|
||||
|
||||
const directories: Record<string, DirectoryHealth> = {
|
||||
configDir: {
|
||||
name: "配置根目录",
|
||||
path: configDir,
|
||||
exists: existsSync(configDir),
|
||||
writable: existsSync(configDir) ? isPathWritable(configDir) : false,
|
||||
description: "用户持久化配置与企业状态根目录"
|
||||
},
|
||||
enterprisesDir: {
|
||||
name: "企业配置目录",
|
||||
path: enterprisesDir,
|
||||
exists: existsSync(enterprisesDir),
|
||||
writable: existsSync(enterprisesDir) ? isPathWritable(enterprisesDir) : false,
|
||||
fileCount: countJsonFiles(enterprisesDir),
|
||||
description: "企业连接配置(JSON)保存路径"
|
||||
},
|
||||
globalConfigFile: {
|
||||
name: "全局配置文件",
|
||||
path: globalConfigFile,
|
||||
exists: existsSync(globalConfigFile),
|
||||
description: "全局工作模式与默认企业配置"
|
||||
},
|
||||
tokenStore: {
|
||||
name: "凭据缓存",
|
||||
path: tokenStore,
|
||||
exists: existsSync(tokenStore),
|
||||
description: "会话凭据与令牌缓存"
|
||||
},
|
||||
mappingsDir: {
|
||||
name: "规则版本映射快照",
|
||||
path: mappingsDir,
|
||||
exists: existsSync(mappingsDir),
|
||||
fileCount: countJsonFiles(mappingsDir),
|
||||
description: "生产与测试规则版本映射对照表"
|
||||
},
|
||||
agentSkillDir: {
|
||||
name: "AI Agent 技能目录",
|
||||
path: agentSkillDir,
|
||||
exists: existsSync(join(agentSkillDir, "SKILL.md")),
|
||||
description: "本地 Agent 技能主目录"
|
||||
},
|
||||
exportDefaultDir: {
|
||||
name: "报表默认导出目录",
|
||||
path: exportDir,
|
||||
exists: existsSync(exportDir),
|
||||
writable: existsSync(exportDir) ? isPathWritable(exportDir) : false,
|
||||
description: "审核大盘报表默认写入目录"
|
||||
},
|
||||
globalBinary: {
|
||||
name: "全局命令行二进制",
|
||||
path: detectedBinary,
|
||||
exists: existsSync(detectedBinary),
|
||||
description: "系统全局命令执行入口"
|
||||
}
|
||||
};
|
||||
|
||||
// Safe read of loaded corps without side-effects
|
||||
let corps: ReturnType<typeof loadCorpConfigs> = [];
|
||||
try {
|
||||
corps = loadCorpConfigs();
|
||||
} catch {
|
||||
corps = [];
|
||||
}
|
||||
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorpId = globalConfig.defaultCorpId ?? corps[0]?.id;
|
||||
const currentCorp = corps.find((c) => c.id === currentCorpId);
|
||||
|
||||
const testCount = corps.filter((c) => (c.environment ?? "production").toLowerCase() === "test").length;
|
||||
const prodCount = corps.length - testCount;
|
||||
|
||||
// Build health checks
|
||||
const checks: HealthCheckItem[] = [];
|
||||
|
||||
// Check 1: Executable
|
||||
checks.push({
|
||||
id: "executable",
|
||||
title: "命令行二进制",
|
||||
status: "ok",
|
||||
message: `当前执行路径: ${process.execPath}`
|
||||
});
|
||||
|
||||
// Check 2: Config Directory
|
||||
if (directories.configDir?.exists && directories.configDir.writable) {
|
||||
checks.push({
|
||||
id: "config_dir",
|
||||
title: "配置目录访问",
|
||||
status: "ok",
|
||||
message: `${configDir} (正常读写)`
|
||||
});
|
||||
} else if (directories.configDir?.exists) {
|
||||
checks.push({
|
||||
id: "config_dir",
|
||||
title: "配置目录访问",
|
||||
status: "warn",
|
||||
message: `${configDir} (存在但可能不可写)`
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "config_dir",
|
||||
title: "配置目录访问",
|
||||
status: "warn",
|
||||
message: `未检测到配置目录 ${configDir},首次运行配置命令时将自动创建`
|
||||
});
|
||||
}
|
||||
|
||||
// Check 3: Enterprises Configured
|
||||
if (corps.length > 0) {
|
||||
checks.push({
|
||||
id: "enterprises",
|
||||
title: "企业接入状态",
|
||||
status: "ok",
|
||||
message: `已接入 ${corps.length} 家企业 (正式: ${prodCount}, 测试: ${testCount})`
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "enterprises",
|
||||
title: "企业接入状态",
|
||||
status: "warn",
|
||||
message: "当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"
|
||||
});
|
||||
}
|
||||
|
||||
// Check 4: Agent Skill
|
||||
if (directories.agentSkillDir?.exists) {
|
||||
checks.push({
|
||||
id: "agent_skill",
|
||||
title: "AI Agent 技能",
|
||||
status: "ok",
|
||||
message: `已就绪于 ${agentSkillDir}`
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "agent_skill",
|
||||
title: "AI Agent 技能",
|
||||
status: "warn",
|
||||
message: `未在 ${agentSkillDir} 检测到技能,可运行 'seal-use skill sync' 安装`
|
||||
});
|
||||
}
|
||||
|
||||
const hasWarning = checks.some((c) => c.status === "warn" || c.status === "error");
|
||||
|
||||
const engine = typeof (globalThis as any).Bun !== "undefined"
|
||||
? `Bun ${(globalThis as any).Bun.version}`
|
||||
: `Node ${process.version}`;
|
||||
|
||||
return {
|
||||
doctor: hasWarning ? "warning" : "ok",
|
||||
timestamp: new Date().toISOString(),
|
||||
runtime: {
|
||||
version: VERSION,
|
||||
executablePath: process.execPath,
|
||||
platform: `${process.platform} (${process.arch})`,
|
||||
engine
|
||||
},
|
||||
directories,
|
||||
enterprises: {
|
||||
total: corps.length,
|
||||
productionCount: prodCount,
|
||||
testCount,
|
||||
activeCorpId: currentCorp?.id,
|
||||
activeCorpName: currentCorp?.name
|
||||
},
|
||||
checks,
|
||||
knowledge: {
|
||||
summary: "内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",
|
||||
directorySpecsCount: EMBEDDED_DIRECTORY_SPECS.length,
|
||||
securityPoliciesCount: EMBEDDED_SECURITY_POLICIES.length,
|
||||
domainCapabilitiesCount: EMBEDDED_DOMAIN_CAPABILITIES.length,
|
||||
guideCommand: "seal-use doctor guide"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a terminal-friendly, human-readable diagnostic dashboard for stderr.
|
||||
*/
|
||||
export function formatDoctorDashboard(diagnosis: DoctorDiagnosis): string {
|
||||
const lines: string[] = [];
|
||||
const symbol = diagnosis.doctor === "ok" ? "✨" : "⚠️";
|
||||
|
||||
lines.push(`🩺 [Seal Use Doctor] 系统健康诊断看板 ${symbol}`);
|
||||
lines.push("─────────────────────────────────────────────────────────────");
|
||||
|
||||
// Runtime section
|
||||
lines.push("【运行环境】");
|
||||
lines.push(` 版本号: ${diagnosis.runtime.version}`);
|
||||
lines.push(` 程序路径: ${diagnosis.runtime.executablePath}`);
|
||||
lines.push(` 操作系统: ${diagnosis.runtime.platform}`);
|
||||
lines.push(` 执行引擎: ${diagnosis.runtime.engine}`);
|
||||
lines.push("");
|
||||
|
||||
// Directory section
|
||||
lines.push("【核心路径状态】");
|
||||
for (const [, dir] of Object.entries(diagnosis.directories)) {
|
||||
const icon = dir.exists ? "✓" : "○";
|
||||
const statusText = dir.exists
|
||||
? dir.fileCount !== undefined
|
||||
? `(${dir.fileCount} 个文件)`
|
||||
: dir.writable
|
||||
? "(就绪/可写)"
|
||||
: "(存在)"
|
||||
: "(未创建)";
|
||||
lines.push(` ${icon} ${dir.name.padEnd(16, " ")}: ${dir.path} ${statusText}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Enterprise section
|
||||
lines.push("【企业资产概览】");
|
||||
lines.push(` 接入企业总计: ${diagnosis.enterprises.total} 家 (生产: ${diagnosis.enterprises.productionCount}, 测试: ${diagnosis.enterprises.testCount})`);
|
||||
if (diagnosis.enterprises.activeCorpId) {
|
||||
lines.push(` 当前激活企业: ${diagnosis.enterprises.activeCorpName} (${diagnosis.enterprises.activeCorpId})`);
|
||||
} else {
|
||||
lines.push(" 当前激活企业: 无默认企业 (无状态模式)");
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Health checks section
|
||||
lines.push("【健康自检】");
|
||||
for (const c of diagnosis.checks) {
|
||||
const icon = c.status === "ok" ? "✓" : c.status === "warn" ? "⚠️" : "✗";
|
||||
lines.push(` ${icon} [${c.title}]: ${c.message}`);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
// Next steps hint
|
||||
lines.push("─────────────────────────────────────────────────────────────");
|
||||
lines.push("👉 查阅内嵌白皮书与目录规范: seal-use doctor guide");
|
||||
lines.push("👉 检索企业: seal-use corps search <keyword>");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Embedded System Knowledge & Architectural Specifications
|
||||
*
|
||||
* This file contains static, read-only documentation and system contracts
|
||||
* bundled directly into the standalone binary. It requires zero network access
|
||||
* and performs zero disk writes.
|
||||
*/
|
||||
|
||||
export interface DirectorySpec {
|
||||
name: string;
|
||||
category: "config" | "binary" | "skill" | "export" | "temp";
|
||||
standardPath: string;
|
||||
purpose: string;
|
||||
accessMode: "read-write" | "executable" | "transient";
|
||||
retention: "persistent" | "cache" | "ephemeral";
|
||||
}
|
||||
|
||||
export interface SecurityPolicySpec {
|
||||
topic: string;
|
||||
guarantee: string;
|
||||
enforcement: string;
|
||||
}
|
||||
|
||||
export interface DomainCapabilitySpec {
|
||||
domain: string;
|
||||
summary: string;
|
||||
primaryCommands: string[];
|
||||
}
|
||||
|
||||
export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
|
||||
{
|
||||
name: "配置与状态根目录",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use",
|
||||
purpose: "用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "企业配置文件目录",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/enterprises",
|
||||
purpose: "存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "全局配置文件",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/config.json",
|
||||
purpose: "维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "会话凭据安全缓存",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/seal_tokens.json",
|
||||
purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",
|
||||
accessMode: "read-write",
|
||||
retention: "cache"
|
||||
},
|
||||
{
|
||||
name: "规则版本映射快照",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/mappings",
|
||||
purpose: "存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "后台守护服务日志",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/service.log",
|
||||
purpose: "常驻后台 HTTP 服务守护进程运行输出日志。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "全局命令行程序",
|
||||
category: "binary",
|
||||
standardPath: "/opt/homebrew/bin/seal-use",
|
||||
purpose: "macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",
|
||||
accessMode: "executable",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "AI Agent 技能主目录",
|
||||
category: "skill",
|
||||
standardPath: "~/.agents/skills/seal-use",
|
||||
purpose: "面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "报表默认导出目录",
|
||||
category: "export",
|
||||
standardPath: "~/Downloads",
|
||||
purpose: "执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "系统隔离临时目录",
|
||||
category: "temp",
|
||||
standardPath: "/tmp 或 /var/folders/.../T",
|
||||
purpose: "自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",
|
||||
accessMode: "transient",
|
||||
retention: "ephemeral"
|
||||
}
|
||||
];
|
||||
|
||||
export const EMBEDDED_SECURITY_POLICIES: SecurityPolicySpec[] = [
|
||||
{
|
||||
topic: "敏感凭据脱敏保护",
|
||||
guarantee: "appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",
|
||||
enforcement: "CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"
|
||||
},
|
||||
{
|
||||
topic: "正式环境与测试环境严格隔离",
|
||||
guarantee: "正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",
|
||||
enforcement: "corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"
|
||||
},
|
||||
{
|
||||
topic: "跨环境规则同步安全基线",
|
||||
guarantee: "corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",
|
||||
enforcement: "规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"
|
||||
},
|
||||
{
|
||||
topic: "只读诊断无副作用原则",
|
||||
guarantee: "doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",
|
||||
enforcement: "核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"
|
||||
}
|
||||
];
|
||||
|
||||
export const EMBEDDED_DOMAIN_CAPABILITIES: DomainCapabilitySpec[] = [
|
||||
{
|
||||
domain: "corps (企业管理)",
|
||||
summary: "多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同步",
|
||||
primaryCommands: ["corps list", "corps search <query>", "corps get <corpId>", "corps mark", "corps bind-test", "corps sync-test"]
|
||||
},
|
||||
{
|
||||
domain: "approval-runs (审核大盘)",
|
||||
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、免登 SSO 深度链接",
|
||||
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs url"]
|
||||
},
|
||||
{
|
||||
domain: "rules (规则治理)",
|
||||
summary: "审核规则拉取、本地 Lint 质量检查、增量差量推送、离线版本与编号对照映射速查",
|
||||
primaryCommands: ["rules pull", "rules lint", "rules push", "rules map", "rules count"]
|
||||
},
|
||||
{
|
||||
domain: "preference (决策偏好)",
|
||||
summary: "AI 审核偏好读取与更新、全局与分品类思考深度策略(medium/high)配置",
|
||||
primaryCommands: ["preference get", "preference decision update", "preference thinking-depth set"]
|
||||
},
|
||||
{
|
||||
domain: "simulation (模拟演练)",
|
||||
summary: "合思单据指定、材料包导入、飞书/泛微三方审批定义演练、批次轮询等待与数据清理",
|
||||
primaryCommands: ["simulation create", "simulation status", "simulation wait", "simulation clean"]
|
||||
},
|
||||
{
|
||||
domain: "webhook (通道与重放)",
|
||||
summary: "Webhook 回调通道配置、材料包校验推送、线上单据向 Webhook 通道测试重放",
|
||||
primaryCommands: ["webhook list", "webhook add", "webhook replay", "webhook material-pack push"]
|
||||
},
|
||||
{
|
||||
domain: "deploy (费控集成)",
|
||||
summary: "Seal AI 智能审核能力发布到合思费控企业、对接要求检测与配置同步",
|
||||
primaryCommands: ["deploy hosecloud requirements", "deploy hosecloud status", "deploy hosecloud sync"]
|
||||
},
|
||||
{
|
||||
domain: "doctor (系统诊断)",
|
||||
summary: "整机环境健康自检、目录全景体检看板、内置架构与规范白皮书离线查阅",
|
||||
primaryCommands: ["doctor", "doctor guide", "doctor paths"]
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* Generates the full formatted embedded documentation in Markdown.
|
||||
*/
|
||||
export function getEmbeddedGuideMarkdown(): string {
|
||||
return `# Seal Use 系统架构与运行规范白皮书
|
||||
|
||||
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
|
||||
|
||||
---
|
||||
|
||||
## 1. 系统定位与设计哲学
|
||||
|
||||
\`seal-use\` 是合思与 Seal AI 体系的企业级智能审核、规则治理与模拟演练 CLI 工具包,兼具人类工程师命令行使用与 AI Agent Harness 自动化集成能力。
|
||||
|
||||
### 核心交互契约
|
||||
- **机器通道 (\`stdout\`)**:所有命令默认在标准输出返回干净、严格类型化的 JSON 载荷,供自动化脚本及 AI Agent 解析。
|
||||
- **指导与诊断通道 (\`stderr\`)**:标准错误专用于输出运行状态、网络探测日志、自愈指引以及显式的下一步动作建议(如 \`👉 Next action: seal-use ...\`)。
|
||||
- **退出码契约**:成功为 \`0\`,参数校验失败、未确认拦截或上游 API 报错均赋予非零退出码(如 \`1\`、\`2\`、\`10\`),杜绝盲目吞错。
|
||||
|
||||
---
|
||||
|
||||
## 2. 系统目录全景规范
|
||||
|
||||
\`seal-use\` 在用户计算机上的所有文件访问严格收敛于以下明确定义的目录中:
|
||||
|
||||
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
${EMBEDDED_DIRECTORY_SPECS.map(
|
||||
(s) => `| **${s.name}** | \`${s.category}\` | \`${s.standardPath}\` | ${s.purpose} (${s.retention}) |`
|
||||
).join("\n")}
|
||||
|
||||
---
|
||||
|
||||
## 3. 安全与数据隐私保证
|
||||
|
||||
${EMBEDDED_SECURITY_POLICIES.map(
|
||||
(p, idx) => `### 3.${idx + 1} ${p.topic}
|
||||
- **安全承诺**:${p.guarantee}
|
||||
- **实现约束**:${p.enforcement}
|
||||
`
|
||||
).join("\n")}
|
||||
|
||||
---
|
||||
|
||||
## 4. 业务域能力图谱
|
||||
|
||||
${EMBEDDED_DOMAIN_CAPABILITIES.map(
|
||||
(c) => `### \`seal-use ${c.domain}\`
|
||||
* **能力定位**:${c.summary}
|
||||
* **核心命令**:${c.primaryCommands.map((cmd) => `\`seal-use ${cmd}\``).join("、")}
|
||||
`
|
||||
).join("\n")}
|
||||
|
||||
---
|
||||
|
||||
## 5. 快速排错与健康诊断指引
|
||||
|
||||
- **环境自检**:运行 \`seal-use doctor\`,一键检查当前运行时版本、本地目录健康度、企业资产接入数量以及守护服务状态。
|
||||
- **查看企业配置源文件**:运行 \`seal-use corps get <corpId>\`,可直接查看指定企业的本地 JSON 存储绝对路径。
|
||||
- **查阅完整操作手册**:运行 \`seal-use doctor guide\` 随时在离线状态下查看本文档。
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import {
|
||||
filterCorpsFuzzy,
|
||||
fuzzyMatchString,
|
||||
levenshteinDistance,
|
||||
matchCorp,
|
||||
minSubstringLevenshtein,
|
||||
normalizeFuzzyPinyin
|
||||
} from "./fuzzy.js";
|
||||
|
||||
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
environment: "production",
|
||||
seal: {
|
||||
tenantSlug: `${id}-slug`,
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "direct",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe("fuzzy search utilities", () => {
|
||||
describe("levenshteinDistance", () => {
|
||||
test("calculates distance correctly", () => {
|
||||
expect(levenshteinDistance("", "")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "abc")).toBe(0);
|
||||
expect(levenshteinDistance("abc", "ab")).toBe(1);
|
||||
expect(levenshteinDistance("abc", "abcd")).toBe(1);
|
||||
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("minSubstringLevenshtein", () => {
|
||||
test("detects exact substring with distance 0", () => {
|
||||
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
|
||||
});
|
||||
|
||||
test("detects missing letter with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
|
||||
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
|
||||
});
|
||||
|
||||
test("detects single substitution typo with distance 1", () => {
|
||||
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeFuzzyPinyin", () => {
|
||||
test("normalizes retroflex to flat consonants", () => {
|
||||
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
|
||||
expect(normalizeFuzzyPinyin("超")).toContain("cao");
|
||||
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
|
||||
});
|
||||
|
||||
test("normalizes front and back nasals", () => {
|
||||
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
|
||||
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
|
||||
});
|
||||
|
||||
test("normalizes homophones to identical representations", () => {
|
||||
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
|
||||
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("fuzzyMatchString", () => {
|
||||
test("exact match", () => {
|
||||
const res = fuzzyMatchString("谢子豪", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("exact");
|
||||
expect(res.score).toBe(1.0);
|
||||
});
|
||||
|
||||
test("substring match", () => {
|
||||
const res = fuzzyMatchString("谢子", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.95);
|
||||
});
|
||||
|
||||
test("initials match (简拼)", () => {
|
||||
const res = fuzzyMatchString("xzh", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("initials");
|
||||
expect(res.score).toBe(0.9);
|
||||
});
|
||||
|
||||
test("pinyin match (全拼)", () => {
|
||||
const res = fuzzyMatchString("xiezihao", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("pinyin");
|
||||
});
|
||||
|
||||
test("homophones (同音字)", () => {
|
||||
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
expect(res1.reason).toBe("fuzzy_pinyin");
|
||||
|
||||
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
|
||||
expect(res2.matched).toBe(true);
|
||||
expect(res2.reason).toBe("fuzzy_pinyin");
|
||||
});
|
||||
|
||||
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
|
||||
const res1 = fuzzyMatchString("詹三", "张三");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
});
|
||||
|
||||
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
|
||||
const res1 = fuzzyMatchString("xieziha", "谢子豪");
|
||||
expect(res1.matched).toBe(true);
|
||||
|
||||
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
|
||||
expect(res2.matched).toBe(true);
|
||||
|
||||
const res3 = fuzzyMatchString("acme", "acm corp");
|
||||
expect(res3.matched).toBe(true);
|
||||
expect(res3.reason).toBe("levenshtein");
|
||||
});
|
||||
|
||||
test("strict mode rejects fuzzy / homophone / typo matches", () => {
|
||||
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
|
||||
|
||||
// But exact substring is allowed in strict mode
|
||||
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects completely unrelated terms", () => {
|
||||
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
|
||||
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
|
||||
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterCorpsFuzzy", () => {
|
||||
const corp1 = makeCorp("xiezihao", "谢子豪", {
|
||||
testCorpId: "test-xzh"
|
||||
});
|
||||
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
|
||||
source: {
|
||||
type: "hose",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-channel",
|
||||
domain: "https://app.ekuaibao.com"
|
||||
} as any
|
||||
});
|
||||
const corp3 = makeCorp("acme-corp", "Acme Global", {
|
||||
environment: "test"
|
||||
});
|
||||
|
||||
const corps = [corp1, corp2, corp3];
|
||||
|
||||
test("finds enterprise by homophone", () => {
|
||||
const results = filterCorpsFuzzy(corps, "鞋子豪");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by initials", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xzh");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by missing letter query", () => {
|
||||
const results = filterCorpsFuzzy(corps, "xieziha");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("finds enterprise by pinyin of Chinese name", () => {
|
||||
const results = filterCorpsFuzzy(corps, "qudao");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("finds enterprise by hose corpId or staffId", () => {
|
||||
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
|
||||
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
|
||||
expect(staffResults.length).toBe(1);
|
||||
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
|
||||
});
|
||||
|
||||
test("strict mode filtering excludes fuzzy homophone matches", () => {
|
||||
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
|
||||
expect(fuzzyRes.length).toBe(1);
|
||||
|
||||
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
|
||||
expect(strictRes.length).toBe(0);
|
||||
|
||||
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
|
||||
expect(strictExact.length).toBe(1);
|
||||
});
|
||||
|
||||
test("ranks exact match higher than fuzzy matches", () => {
|
||||
const cExact = makeCorp("test-qudao", "渠道");
|
||||
const cFuzzy = makeCorp("test-other", "渠到另外一家");
|
||||
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
|
||||
expect(ranked[0]!.id).toBe("test-qudao");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { pinyin, match as pinyinMatch } from "pinyin-pro";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
export interface FuzzyMatchOptions {
|
||||
/**
|
||||
* If true, disables fuzzy/soft matching and requires exact substring matching.
|
||||
* Defaults to false (soft search by default).
|
||||
*/
|
||||
strict?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum edit distance allowed for typo / missing letter tolerance.
|
||||
* Defaults based on query length:
|
||||
* - length <= 2: 0 (no fuzzy edits)
|
||||
* - length 3..5: 1 (missing 1 letter or 1 typo)
|
||||
* - length >= 6: 2 (missing 1-2 letters)
|
||||
*/
|
||||
maxDistance?: number;
|
||||
}
|
||||
|
||||
export type MatchReason =
|
||||
| "exact"
|
||||
| "substring"
|
||||
| "initials"
|
||||
| "pinyin"
|
||||
| "fuzzy_pinyin"
|
||||
| "levenshtein"
|
||||
| "subsequence"
|
||||
| "none";
|
||||
|
||||
export interface MatchScoreResult {
|
||||
matched: boolean;
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Levenshtein distance between two strings.
|
||||
*/
|
||||
export function levenshteinDistance(a: string, b: string): number {
|
||||
const m = a.length;
|
||||
const n = b.length;
|
||||
if (m === 0) return n;
|
||||
if (n === 0) return m;
|
||||
|
||||
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
|
||||
let currRow = new Array<number>(n + 1).fill(0);
|
||||
|
||||
for (let i = 1; i <= m; i += 1) {
|
||||
currRow[0] = i;
|
||||
for (let j = 1; j <= n; j += 1) {
|
||||
if (a[i - 1] === b[j - 1]) {
|
||||
currRow[j] = prevRow[j - 1] ?? 0;
|
||||
} else {
|
||||
const sub = prevRow[j - 1] ?? 0;
|
||||
const ins = currRow[j - 1] ?? 0;
|
||||
const del = prevRow[j] ?? 0;
|
||||
currRow[j] = Math.min(sub, ins, del) + 1;
|
||||
}
|
||||
}
|
||||
const temp = prevRow;
|
||||
prevRow = currRow;
|
||||
currRow = temp;
|
||||
}
|
||||
return prevRow[n] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
|
||||
* Supports queries missing a letter, having an extra letter, or having an internal typo.
|
||||
*/
|
||||
export function minSubstringLevenshtein(query: string, target: string): number {
|
||||
if (!query || !target) return 999;
|
||||
if (target.includes(query)) return 0;
|
||||
|
||||
const qLen = query.length;
|
||||
if (target.length < qLen - 2) {
|
||||
return levenshteinDistance(query, target);
|
||||
}
|
||||
|
||||
let min = 999;
|
||||
const minWindow = Math.max(1, qLen - 2);
|
||||
const maxWindow = Math.min(target.length, qLen + 2);
|
||||
|
||||
for (let len = minWindow; len <= maxWindow; len += 1) {
|
||||
for (let i = 0; i <= target.length - len; i += 1) {
|
||||
const sub = target.slice(i, i + len);
|
||||
const dist = levenshteinDistance(query, sub);
|
||||
if (dist < min) min = dist;
|
||||
if (min === 0) return 0;
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
|
||||
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
|
||||
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
|
||||
* - Strips non-alphanumeric whitespace
|
||||
*/
|
||||
export function normalizeFuzzyPinyin(str: string): string {
|
||||
if (!str) return "";
|
||||
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
|
||||
return pyTokens
|
||||
.map((token) =>
|
||||
token
|
||||
.toLowerCase()
|
||||
.replace(/zh/g, "z")
|
||||
.replace(/ch/g, "c")
|
||||
.replace(/sh/g, "s")
|
||||
.replace(/iang/g, "ian")
|
||||
.replace(/uang/g, "uan")
|
||||
.replace(/ang/g, "an")
|
||||
.replace(/eng/g, "en")
|
||||
.replace(/ing/g, "in")
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all characters of `query` appear in order inside `target` (subsequence).
|
||||
*/
|
||||
export function isSubsequence(query: string, target: string): boolean {
|
||||
if (!query || !target) return false;
|
||||
let qIdx = 0;
|
||||
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
|
||||
if (query[qIdx] === target[tIdx]) {
|
||||
qIdx += 1;
|
||||
}
|
||||
}
|
||||
return qIdx === query.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Core fuzzy string match engine:
|
||||
* Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin,
|
||||
* sliding-window edit distance (missing/typo tolerance), and character subsequence.
|
||||
*/
|
||||
export function fuzzyMatchString(
|
||||
query: string,
|
||||
target: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const normQuery = query.trim().toLowerCase();
|
||||
const normTarget = target.trim().toLowerCase();
|
||||
|
||||
if (!normQuery || !normTarget) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
// 1. Exact match
|
||||
if (normTarget === normQuery) {
|
||||
return { matched: true, score: 1.0, reason: "exact" };
|
||||
}
|
||||
|
||||
// 2. Substring match
|
||||
if (normTarget.includes(normQuery)) {
|
||||
return { matched: true, score: 0.95, reason: "substring" };
|
||||
}
|
||||
|
||||
// If strict mode is requested, only exact or substring matches are accepted.
|
||||
if (options.strict) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
|
||||
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
|
||||
|
||||
// 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产")
|
||||
if (targetHasChinese && normQuery.length >= 2) {
|
||||
const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" })
|
||||
.join("")
|
||||
.toLowerCase();
|
||||
if (targetInitials.includes(normQuery)) {
|
||||
return { matched: true, score: 0.9, reason: "initials" };
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets)
|
||||
if (targetHasChinese) {
|
||||
try {
|
||||
const pm = pinyinMatch(normTarget, normQuery, { precision: "start" });
|
||||
if (pm && pm.length > 0) {
|
||||
return { matched: true, score: 0.88, reason: "pinyin" };
|
||||
}
|
||||
} catch {
|
||||
// ignore match errors if non-standard regex chars
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音)
|
||||
let targetFuzzyPinyin = "";
|
||||
let queryFuzzyPinyin = "";
|
||||
if (targetHasChinese || queryHasChinese) {
|
||||
targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget);
|
||||
queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery);
|
||||
|
||||
if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) {
|
||||
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Missing letter / Typo tolerance (Levenshtein Distance)
|
||||
// Determine allowed distance based on query length:
|
||||
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
|
||||
// - 3..5: 1 (missing 1 letter or 1 typo)
|
||||
// - >= 6: 2 (missing 1-2 letters)
|
||||
const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2;
|
||||
const maxAllowedDist = options.maxDistance ?? defaultMaxDist;
|
||||
|
||||
if (maxAllowedDist > 0) {
|
||||
// Check raw string distance
|
||||
const rawDist = minSubstringLevenshtein(normQuery, normTarget);
|
||||
if (rawDist <= maxAllowedDist) {
|
||||
return {
|
||||
matched: true,
|
||||
score: Math.max(0.6, 0.8 - rawDist * 0.1),
|
||||
reason: "levenshtein"
|
||||
};
|
||||
}
|
||||
|
||||
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
|
||||
if (
|
||||
(targetHasChinese || queryHasChinese) &&
|
||||
queryFuzzyPinyin.length >= 3 &&
|
||||
targetFuzzyPinyin.length >= 3
|
||||
) {
|
||||
const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin);
|
||||
if (pinyinDist <= maxAllowedDist) {
|
||||
return {
|
||||
matched: true,
|
||||
score: Math.max(0.6, 0.78 - pinyinDist * 0.1),
|
||||
reason: "levenshtein"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Subsequence match (loose character order, min query length 3)
|
||||
if (normQuery.length >= 3) {
|
||||
if (
|
||||
isSubsequence(normQuery, normTarget) ||
|
||||
((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin))
|
||||
) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
}
|
||||
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
|
||||
* returning the highest match score and reason.
|
||||
*/
|
||||
export function matchCorp(
|
||||
corp: CorpConfig,
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const fields: Array<{ text: string | undefined; weight: number }> = [
|
||||
{ text: corp.name, weight: 1.2 },
|
||||
{ text: corp.id, weight: 1.1 },
|
||||
{ text: corp.source.staffId, weight: 1.0 },
|
||||
{ text: (corp.source as any).domain, weight: 1.0 },
|
||||
{ text: (corp.source as any).corpId, weight: 1.0 },
|
||||
{ text: corp.seal.tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
|
||||
{ text: (corp.source as any).tenantName, weight: 1.1 },
|
||||
{ text: corp.testCorpId, weight: 1.0 },
|
||||
{ text: corp.prodCorpId, weight: 1.0 },
|
||||
{ text: corp.environment ?? "production", weight: 0.8 },
|
||||
{ text: corp.source.type, weight: 0.8 },
|
||||
{ text: (corp.source as any).provider, weight: 0.8 }
|
||||
];
|
||||
|
||||
let bestScore = 0;
|
||||
let bestReason: MatchReason = "none";
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = fuzzyMatchString(query, field.text, options);
|
||||
if (res.matched) {
|
||||
const weightedScore = res.score * field.weight;
|
||||
if (weightedScore > bestScore) {
|
||||
bestScore = weightedScore;
|
||||
bestReason = res.reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
matched: bestScore > 0,
|
||||
score: bestScore,
|
||||
reason: bestReason
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
|
||||
* and automatically sorts the matching results from highest relevance to lowest.
|
||||
*/
|
||||
export function filterCorpsFuzzy(
|
||||
corps: CorpConfig[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): CorpConfig[] {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return corps;
|
||||
|
||||
const scored: Array<{ corp: CorpConfig; score: number }> = [];
|
||||
|
||||
for (const corp of corps) {
|
||||
const res = matchCorp(corp, trimmed, options);
|
||||
if (res.matched) {
|
||||
scored.push({ corp, score: res.score });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by match score descending (highest confidence first)
|
||||
scored.sort((a, b) => b.score - a.score);
|
||||
|
||||
return scored.map((item) => item.corp);
|
||||
}
|
||||
@@ -660,6 +660,9 @@ describe("sealTools", () => {
|
||||
};
|
||||
|
||||
expect(result).toMatchObject({
|
||||
url: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
||||
sealResultUrl: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
||||
type: "deep_link",
|
||||
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
hoseDomain: "https://app.ekuaibao.com",
|
||||
@@ -705,11 +708,54 @@ describe("sealTools", () => {
|
||||
fakeApprovalRunsClient(requests),
|
||||
{ sourceDocumentSN: "B26001965" },
|
||||
fakeHoseContext()
|
||||
) as { documentUrl?: string };
|
||||
) as { documentUrl?: string; url?: string; type?: string };
|
||||
|
||||
expect(requests[0]).toContain("search=B26001965");
|
||||
expect(requests[1]).toBe("api/v1/approvals/run-1");
|
||||
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.type).toBe("deep_link");
|
||||
expect(result.url).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
||||
});
|
||||
|
||||
test("approval run url returns SSO link with identity, expiration, and warning when sso=true", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = (await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", sso: true, expiresIn: 3600 },
|
||||
fakeHoseContext()
|
||||
)) as {
|
||||
url?: string;
|
||||
ssoUrl?: string;
|
||||
type?: string;
|
||||
expiresIn?: number;
|
||||
warning?: string;
|
||||
identity?: { staffId?: string };
|
||||
};
|
||||
|
||||
expect(result.type).toBe("sso_link");
|
||||
expect(result.expiresIn).toBe(3600);
|
||||
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
||||
expect(result.url).toContain("path=%2Fapproval-result%2Frun-1");
|
||||
expect(result.warning).toContain("安全警示");
|
||||
expect(result.identity?.staffId).toBe("staff-a");
|
||||
});
|
||||
|
||||
test("approval run url throws clear error when sso=true is used on non-hose enterprise", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
await expect(
|
||||
handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", sso: true },
|
||||
fakeContext()
|
||||
)
|
||||
).rejects.toThrow("SSO direct links currently support Hose-integrated enterprises");
|
||||
});
|
||||
|
||||
test("approval run summary filters by local date and returns compact aggregates", async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "./api.js";
|
||||
import { defaultSealUrl, getHoseEnterpriseUrl, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { defaultSealUrl, getHoseEnterpriseUrl, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { createSealClientForToken } from "../../core/http/factory.js";
|
||||
@@ -1450,15 +1450,23 @@ export const sealTools = [
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_url_get",
|
||||
description: "获取合思企业协助链接,按需附带单据链接;支持只取企业协助链接,或按 Seal recordId/合思 sourceDocumentSN 查询单据链接",
|
||||
description: "获取审批单的 Web 控制台直达链接或合思企业协助链接,支持纯深度链接与带安全警告的免密 SSO 链接",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional().describe("Seal approval run record ID"),
|
||||
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
|
||||
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID")
|
||||
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
|
||||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (SSO link)"),
|
||||
expiresIn: z.number().optional().describe("SSO 免密凭证有效秒数,默认 7200 (2小时)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string },
|
||||
params: {
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
sso?: boolean;
|
||||
expiresIn?: number;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
|
||||
@@ -1467,7 +1475,68 @@ export const sealTools = [
|
||||
const enterpriseAssistUrl = source.type === "hose" ? await getHoseEnterpriseUrl(context.corp) : undefined;
|
||||
const documentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
|
||||
const sealBaseUrl = resolveSealBaseUrl(context.corp);
|
||||
const sealResultUrl = record?.id ? `${sealBaseUrl}/approval-result/${record.id}` : undefined;
|
||||
|
||||
let ssoUrl: string | undefined;
|
||||
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
|
||||
let warning: string | undefined;
|
||||
const expiresIn = params.expiresIn ?? 7200;
|
||||
|
||||
if (params.sso) {
|
||||
if (!record?.id) {
|
||||
throw new Error("recordId or sourceDocumentSN is required to generate an SSO approval result URL");
|
||||
}
|
||||
if (source.type !== "hose") {
|
||||
throw new Error(
|
||||
`SSO direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use delegation create' for authorized access.`
|
||||
);
|
||||
}
|
||||
|
||||
const linkInfo = await getHoseProvisionalAuthLink(context.corp, expiresIn);
|
||||
const provisionalToken = new URL(linkInfo.url).searchParams.get("accessToken");
|
||||
if (!provisionalToken) {
|
||||
throw new Error("Failed to obtain Hose provisional authentication token");
|
||||
}
|
||||
|
||||
const targetPath = `/approval-result/${record.id}`;
|
||||
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
|
||||
|
||||
try {
|
||||
const me = await api.getMe(client);
|
||||
identity = {
|
||||
name: me.user.name,
|
||||
staffId: source.staffId,
|
||||
isAdmin: me.user.isAdmin,
|
||||
providerUserId: me.user.providerUserId
|
||||
};
|
||||
} catch {
|
||||
identity = {
|
||||
staffId: source.staffId
|
||||
};
|
||||
}
|
||||
|
||||
const userName = identity.name ?? "企业成员";
|
||||
const roleLabel = identity.isAdmin ? " (管理员)" : "";
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
|
||||
console.error(
|
||||
`⚠️ 安全警示 (SSO 强化免密链接):\n` +
|
||||
`• 身份主体:${userName}${roleLabel}\n` +
|
||||
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
|
||||
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
url: params.sso ? ssoUrl : sealResultUrl,
|
||||
sealResultUrl,
|
||||
ssoUrl,
|
||||
type: params.sso ? "sso_link" : "deep_link",
|
||||
expiresIn: params.sso ? expiresIn : undefined,
|
||||
identity,
|
||||
warning,
|
||||
enterpriseAssistUrl,
|
||||
enterpriseUrl: enterpriseAssistUrl,
|
||||
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
|
||||
@@ -3218,6 +3287,15 @@ async function resolveApprovalRunForUrl(
|
||||
return api.getApprovalRun(client, record.id);
|
||||
}
|
||||
|
||||
function resolveSealBaseUrl(corp: CorpConfig): string {
|
||||
if (corp.seal?.url) return corp.seal.url.replace(/\/+$/, "");
|
||||
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source).replace(/\/+$/, "");
|
||||
if ("sealUrl" in corp.source && typeof corp.source.sealUrl === "string" && corp.source.sealUrl) {
|
||||
return corp.source.sealUrl.replace(/\/+$/, "");
|
||||
}
|
||||
return `https://${corp.id.toLowerCase()}.sealai.cc`;
|
||||
}
|
||||
|
||||
function normalizeUrl(value: string): string {
|
||||
return value.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
transformApprovalRunToWebhookDocument,
|
||||
sanitizeFieldForWebhook,
|
||||
extractWebhookInfo,
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
ALLOWED_WEBHOOK_FIELD_TYPES
|
||||
} from "./webhook-replay.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
|
||||
describe("webhook-replay domain", () => {
|
||||
const mockWebhookIntegration: WebhookIntegration = {
|
||||
type: "webhook",
|
||||
id: "wh-int-1",
|
||||
name: "测试通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: {
|
||||
id: "wh_hook_abc123",
|
||||
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/document"
|
||||
},
|
||||
outgoingResultWebhook: "https://example.com/callback",
|
||||
incomingManualResultWebhook: {
|
||||
id: "wh_hook_abc123",
|
||||
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/manual-result"
|
||||
},
|
||||
secret: "test-secret-key-xyz",
|
||||
materialPackFilePolicy: {
|
||||
minFileSizeBytes: 500,
|
||||
allowedExtensions: [".pdf"]
|
||||
}
|
||||
};
|
||||
|
||||
test("sanitizeFieldForWebhook preserves allowed types and normalizes unknown types", () => {
|
||||
// Known allowed types
|
||||
for (const type of ALLOWED_WEBHOOK_FIELD_TYPES) {
|
||||
const field = { key: "f1", label: "F1", type, value: "val" };
|
||||
expect(sanitizeFieldForWebhook(field, 0)).toEqual({
|
||||
key: "f1",
|
||||
label: "F1",
|
||||
type,
|
||||
value: "val"
|
||||
});
|
||||
}
|
||||
|
||||
// Hose REFERENCE type -> TEXT
|
||||
const refField = {
|
||||
key: "ref",
|
||||
label: "关联单据",
|
||||
type: "REFERENCE",
|
||||
value: "DOC123"
|
||||
};
|
||||
expect(sanitizeFieldForWebhook(refField, 1)).toEqual({
|
||||
key: "ref",
|
||||
label: "关联单据",
|
||||
type: "TEXT",
|
||||
value: "DOC123"
|
||||
});
|
||||
|
||||
// Object value with unknown type -> OBJECT
|
||||
const objField = {
|
||||
key: "extra",
|
||||
label: "附加信息",
|
||||
type: "CUSTOM_UNKNOWN",
|
||||
value: { foo: "bar" }
|
||||
};
|
||||
expect(sanitizeFieldForWebhook(objField, 2)).toEqual({
|
||||
key: "extra",
|
||||
label: "附加信息",
|
||||
type: "OBJECT",
|
||||
value: { foo: "bar" }
|
||||
});
|
||||
|
||||
// Recursive LIST fields normalization
|
||||
const listField = {
|
||||
key: "items",
|
||||
label: "明细列表",
|
||||
type: "LIST",
|
||||
value: [
|
||||
[
|
||||
{ key: "cost", label: "金额", type: "AMOUNT", value: { amount: 50 } },
|
||||
{ key: "subRef", label: "引用", type: "REFERENCE", value: "R1" }
|
||||
]
|
||||
]
|
||||
};
|
||||
const sanitizedList = sanitizeFieldForWebhook(listField, 3);
|
||||
expect(sanitizedList.type).toBe("LIST");
|
||||
const rows = sanitizedList.value as any[][];
|
||||
expect(rows[0]![0].type).toBe("AMOUNT");
|
||||
expect(rows[0]![1].type).toBe("TEXT");
|
||||
});
|
||||
|
||||
test("transformApprovalRunToWebhookDocument builds clean document payload with prefix/suffix support", () => {
|
||||
const run: ApprovalRun = {
|
||||
id: "run-uuid-1",
|
||||
status: "failed",
|
||||
sourceSystem: "hosecloud",
|
||||
sourceDocumentSN: "BX2026090001",
|
||||
sourceDocumentId: "ID01DocABC",
|
||||
createdAt: 1789115000000,
|
||||
document: {
|
||||
id: "doc-uuid-1",
|
||||
sn: "BX2026090001",
|
||||
fields: [
|
||||
{ key: "title", label: "标题", type: "TEXT", value: "出差报销" },
|
||||
{ key: "supplement", label: "补充说明", type: "REFERENCE", value: "none" }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
// Default transformation
|
||||
const doc = transformApprovalRunToWebhookDocument(run);
|
||||
expect(doc.type).toBe("document");
|
||||
expect(doc.documentSN).toBe("BX2026090001");
|
||||
expect(doc.documentId).toBe("ID01DocABC");
|
||||
expect(doc.startTime).toBe(1789115000);
|
||||
expect(doc.fields.length).toBe(2);
|
||||
expect(doc.fields[0]!.type).toBe("TEXT");
|
||||
expect(doc.fields[1]!.type).toBe("TEXT");
|
||||
|
||||
// With prefix and suffix
|
||||
const modified = transformApprovalRunToWebhookDocument(run, {
|
||||
snPrefix: "TEST_",
|
||||
snSuffix: "_v2"
|
||||
});
|
||||
expect(modified.documentSN).toBe("TEST_BX2026090001_v2");
|
||||
expect(modified.documentId).toBe("TEST_ID01DocABC_v2");
|
||||
});
|
||||
|
||||
test("extractWebhookInfo extracts webhookId, baseUrl, and documentEndpoint", () => {
|
||||
const info = extractWebhookInfo("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
|
||||
expect(info.baseUrl).toBe("https://staging.sealai.cc");
|
||||
expect(info.webhookId).toBe("wh_abc_123");
|
||||
expect(info.documentEndpoint).toBe("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
|
||||
|
||||
expect(() => extractWebhookInfo("https://staging.sealai.cc/invalid/path")).toThrow(
|
||||
/Webhook URL 必须包含/
|
||||
);
|
||||
});
|
||||
|
||||
test("pushWebhookDocument signs and posts payload", async () => {
|
||||
let capturedUrl = "";
|
||||
let capturedMethod = "";
|
||||
let capturedHeaders: Record<string, string> = {};
|
||||
let capturedBody = "";
|
||||
|
||||
const mockFetch = (async (url: any, init: any) => {
|
||||
capturedUrl = String(url);
|
||||
capturedMethod = init.method;
|
||||
capturedHeaders = init.headers;
|
||||
capturedBody = init.body;
|
||||
return new Response(JSON.stringify({ data: { success: true, documentId: "doc-out-1" } }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}) as any;
|
||||
|
||||
const doc = {
|
||||
type: "document" as const,
|
||||
documentId: "doc-1",
|
||||
documentSN: "SN-1",
|
||||
startTime: 123456,
|
||||
fields: [{ key: "f1", label: "L1", type: "TEXT", value: "v1" }]
|
||||
};
|
||||
|
||||
const res = await pushWebhookDocument(
|
||||
mockWebhookIntegration.incomingDocumentWebhook.url,
|
||||
mockWebhookIntegration.secret,
|
||||
doc,
|
||||
mockFetch
|
||||
);
|
||||
|
||||
expect(capturedUrl).toBe(mockWebhookIntegration.incomingDocumentWebhook.url);
|
||||
expect(capturedMethod).toBe("POST");
|
||||
expect(capturedHeaders["Authorization"]).toBe(`Bearer ${mockWebhookIntegration.secret}`);
|
||||
expect(capturedHeaders["x-webhook-signature"]).toBeDefined();
|
||||
expect(capturedHeaders["x-webhook-timestamp"]).toBeDefined();
|
||||
expect(capturedHeaders["x-webhook-nonce"]).toBeDefined();
|
||||
expect(JSON.parse(capturedBody)).toEqual(doc);
|
||||
expect(res).toEqual({ data: { success: true, documentId: "doc-out-1" } });
|
||||
});
|
||||
|
||||
test("pushWebhookDocument throws error when endpoint returns failure status", async () => {
|
||||
const mockFetch = (async () => {
|
||||
return new Response("Invalid parameter: missing field", { status: 400 });
|
||||
}) as any;
|
||||
|
||||
const doc = {
|
||||
type: "document" as const,
|
||||
documentId: "doc-1",
|
||||
documentSN: "SN-1",
|
||||
startTime: null,
|
||||
fields: []
|
||||
};
|
||||
|
||||
expect(
|
||||
pushWebhookDocument(
|
||||
mockWebhookIntegration.incomingDocumentWebhook.url,
|
||||
mockWebhookIntegration.secret,
|
||||
doc,
|
||||
mockFetch
|
||||
)
|
||||
).rejects.toThrow(/Webhook 单据推送失败 \(400\)/);
|
||||
});
|
||||
|
||||
test("selectWebhookIntegration auto-locks single integration and selects by query", () => {
|
||||
// Single integration
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration])).toBe(mockWebhookIntegration);
|
||||
|
||||
// Multiple integrations - select by name
|
||||
const second: WebhookIntegration = {
|
||||
...mockWebhookIntegration,
|
||||
id: "wh-int-2",
|
||||
name: "备用通道"
|
||||
};
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration, second], "备用通道")).toBe(second);
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration, second], "wh-int-1")).toBe(mockWebhookIntegration);
|
||||
|
||||
// Ambiguous without selector
|
||||
expect(() => selectWebhookIntegration([mockWebhookIntegration, second])).toThrow(/存在多个 Webhook 通道/);
|
||||
|
||||
// Empty integrations
|
||||
expect(() => selectWebhookIntegration([])).toThrow(/未配置任何 Webhook 集成通道/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
import type { MaterialField } from "./material-pack/types.js";
|
||||
import { webhookHeaders } from "./material-pack/signature.js";
|
||||
import { CliError } from "../../cli/errors.js";
|
||||
|
||||
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
|
||||
"TEXT",
|
||||
"NUMBER",
|
||||
"DATE",
|
||||
"AMOUNT",
|
||||
"PERSON",
|
||||
"ATTACHMENT",
|
||||
"DATE_RANGE",
|
||||
"DEPARTMENT",
|
||||
"LIST",
|
||||
"CITY",
|
||||
"OBJECT"
|
||||
]);
|
||||
|
||||
export interface WebhookReplayDocument {
|
||||
type: "document";
|
||||
documentId: string;
|
||||
documentSN: string;
|
||||
startTime: number | null;
|
||||
fields: MaterialField[];
|
||||
}
|
||||
|
||||
export interface WebhookReplayTransformOptions {
|
||||
snSuffix?: string;
|
||||
snPrefix?: string;
|
||||
docIdSuffix?: string;
|
||||
docIdPrefix?: string;
|
||||
}
|
||||
|
||||
export function sanitizeFieldForWebhook(field: unknown, index: number): MaterialField {
|
||||
const f = field && typeof field === "object" ? (field as Record<string, unknown>) : {};
|
||||
const rawType = typeof f.type === "string" ? f.type.toUpperCase().trim() : "";
|
||||
const key =
|
||||
typeof f.key === "string" && f.key.trim()
|
||||
? f.key.trim()
|
||||
: typeof f.label === "string" && f.label.trim()
|
||||
? f.label.trim()
|
||||
: `field_${index}`;
|
||||
const label = typeof f.label === "string" && f.label.trim() ? f.label.trim() : key;
|
||||
|
||||
let value = f.value !== undefined ? f.value : null;
|
||||
|
||||
// Recursively sanitize rows inside LIST fields
|
||||
if (rawType === "LIST" && Array.isArray(value)) {
|
||||
value = value.map((row) => {
|
||||
if (Array.isArray(row)) {
|
||||
return row.map((nested, nestedIdx) => sanitizeFieldForWebhook(nested, nestedIdx));
|
||||
}
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
let type = rawType;
|
||||
if (!ALLOWED_WEBHOOK_FIELD_TYPES.has(type)) {
|
||||
if (Array.isArray(value)) {
|
||||
type = "LIST";
|
||||
} else if (value && typeof value === "object") {
|
||||
type = "OBJECT";
|
||||
} else if (typeof value === "number") {
|
||||
type = "NUMBER";
|
||||
} else {
|
||||
type = "TEXT";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
type,
|
||||
value
|
||||
};
|
||||
}
|
||||
|
||||
export function transformApprovalRunToWebhookDocument(
|
||||
record: ApprovalRun,
|
||||
options: WebhookReplayTransformOptions = {}
|
||||
): WebhookReplayDocument {
|
||||
const rawDoc = record.document as Record<string, unknown> | undefined;
|
||||
|
||||
const originalSN =
|
||||
record.sourceDocumentSN ??
|
||||
(typeof rawDoc?.sn === "string" ? rawDoc.sn : undefined) ??
|
||||
(typeof rawDoc?.sourceDocumentSN === "string" ? rawDoc.sourceDocumentSN : undefined) ??
|
||||
record.id;
|
||||
|
||||
const originalDocId =
|
||||
record.sourceDocumentId ??
|
||||
(typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ??
|
||||
(typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ??
|
||||
record.documentId ??
|
||||
record.id;
|
||||
|
||||
const snPrefix = options.snPrefix ?? "";
|
||||
const snSuffix = options.snSuffix ?? "";
|
||||
const docIdPrefix = options.docIdPrefix ?? snPrefix;
|
||||
const docIdSuffix = options.docIdSuffix ?? snSuffix;
|
||||
|
||||
const documentSN = `${snPrefix}${originalSN}${snSuffix}`;
|
||||
const documentId = `${docIdPrefix}${originalDocId}${docIdSuffix}`;
|
||||
|
||||
const startTime =
|
||||
typeof rawDoc?.sourceStartTime === "number"
|
||||
? rawDoc.sourceStartTime
|
||||
: typeof record.createdAt === "number"
|
||||
? Math.floor(record.createdAt / 1000)
|
||||
: null;
|
||||
|
||||
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
|
||||
const fields = rawFields.map((field, idx) => sanitizeFieldForWebhook(field, idx));
|
||||
|
||||
return {
|
||||
type: "document",
|
||||
documentId,
|
||||
documentSN,
|
||||
startTime,
|
||||
fields
|
||||
};
|
||||
}
|
||||
|
||||
export function extractWebhookInfo(url: string): { baseUrl: string; webhookId: string; documentEndpoint: string } {
|
||||
const parsed = new URL(url);
|
||||
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
|
||||
if (!match) {
|
||||
throw new Error(`Webhook URL 必须包含 /webhook/{webhookId}/document,收到: ${url}`);
|
||||
}
|
||||
const webhookId = match[1]!;
|
||||
const baseUrl = `${parsed.protocol}//${parsed.host}`;
|
||||
const documentEndpoint = `${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`;
|
||||
return { baseUrl, webhookId, documentEndpoint };
|
||||
}
|
||||
|
||||
export async function pushWebhookDocument(
|
||||
endpointUrl: string,
|
||||
secret: string,
|
||||
document: WebhookReplayDocument,
|
||||
fetchFn: typeof fetch = fetch
|
||||
): Promise<unknown> {
|
||||
const { webhookId, documentEndpoint } = extractWebhookInfo(endpointUrl);
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
...webhookHeaders({ webhookId, ...document }, secret)
|
||||
};
|
||||
|
||||
const response = await fetchFn(documentEndpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(document)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Webhook 单据推送失败 (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function selectWebhookIntegration(
|
||||
integrations: WebhookIntegration[],
|
||||
selector?: string,
|
||||
corpId?: string
|
||||
): WebhookIntegration {
|
||||
if (selector) {
|
||||
const normalized = selector.trim().toLowerCase();
|
||||
const found = integrations.find(
|
||||
(item) =>
|
||||
item.id.toLowerCase() === normalized ||
|
||||
item.name.toLowerCase() === normalized ||
|
||||
item.incomingDocumentWebhook.id.toLowerCase() === normalized
|
||||
);
|
||||
if (!found) {
|
||||
const available = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`未找到匹配 "${selector}" 的 Webhook 集成通道。可用通道: [${available}]`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
if (integrations.length === 1) {
|
||||
return integrations[0]!;
|
||||
}
|
||||
|
||||
if (integrations.length > 1) {
|
||||
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
"当前租户未配置任何 Webhook 集成通道。",
|
||||
1,
|
||||
`seal-use webhook add --name <name> --result-url <url>${corpId ? ` --corp ${corpId}` : ""}`
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user