Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6da8d54794 | ||
|
|
972eff1436 | ||
|
|
9060a28d8b | ||
|
|
9b5e668f09 | ||
|
|
255f6a3c28 | ||
|
|
b5e6cc0282 | ||
|
|
7bbddd7aba | ||
|
|
f02c5a3b5f | ||
|
|
00566c043e | ||
|
|
2116bf6141 | ||
|
|
483e4d9423 | ||
|
|
fb673f754e | ||
|
|
ee4cb332d9 | ||
|
|
eb77ca1aef | ||
|
|
12bc376bd6 | ||
|
|
916ba9465e |
No files matched your search
@@ -301,3 +301,58 @@ jobs:
|
||||
fi
|
||||
done
|
||||
echo "✓ Gitea publishing step completed!"
|
||||
|
||||
update-brew-tap:
|
||||
name: 🍺 Update Homebrew Tap
|
||||
needs: [build-and-publish-github, publish-gitea]
|
||||
if: ${{ !cancelled() && needs.build-and-publish-github.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout Homebrew Tap
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
repository: yunyingk/homebrew-tap
|
||||
token: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
path: tap
|
||||
|
||||
- name: Download checksums from GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
TAG_NAME="${{ github.event.inputs.tag || github.ref_name }}"
|
||||
gh release download "${TAG_NAME}" \
|
||||
--repo "${GITHUB_REPOSITORY}" \
|
||||
--pattern 'checksums.txt' \
|
||||
--dir . \
|
||||
--clobber
|
||||
|
||||
- name: Update Formula
|
||||
run: |
|
||||
RAW_TAG="${{ github.event.inputs.tag || github.ref_name }}"
|
||||
VERSION="${RAW_TAG#v}"
|
||||
ARM64_SHA=$(grep 'seal-use-darwin-arm64.tar.gz' checksums.txt | awk '{print $1}')
|
||||
|
||||
if [ -z "$ARM64_SHA" ]; then
|
||||
echo "::error::Could not find sha256 for seal-use-darwin-arm64.tar.gz"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Updating Formula to version ${VERSION} with sha256 ${ARM64_SHA}"
|
||||
|
||||
FORMULA_FILE="tap/Formula/seal-use.rb"
|
||||
sed -i -E "s/version \"[^\"]+\"/version \"${VERSION}\"/" "$FORMULA_FILE"
|
||||
sed -i -E "s/sha256 \"[^\"]+\"/sha256 \"${ARM64_SHA}\"/" "$FORMULA_FILE"
|
||||
|
||||
cd tap
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
if git diff --quiet; then
|
||||
echo "No changes to Formula, skipping commit."
|
||||
else
|
||||
git add Formula/seal-use.rb
|
||||
git commit -m "chore(release): bump seal-use to ${VERSION}"
|
||||
git push origin main
|
||||
echo "✓ Homebrew Tap formula updated successfully!"
|
||||
fi
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.29",
|
||||
"version": "0.10.32",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"skill": {
|
||||
"/Users/yingqing/.agents/skills/dws/SKILL.md": { "enable": false },
|
||||
"/Users/yingqing/.agents/skills/lark-suite/SKILL.md": { "enable": false }
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.10.32] - 2026-09-20
|
||||
|
||||
### Added
|
||||
- **Semantic Approval Run Web Links (`approval-runs link`)**:
|
||||
- Replaced un-semantic `approval-runs url` command with standard `approval-runs link` (preserving `url` as backwards-compatible alias).
|
||||
- Added `--type <seal-result|hose-document>` parameter (defaulting to `seal-result`) to cleanly distinguish between the Seal AI audit page and the Hose/source original form.
|
||||
- Standardized `--auto-login` (with aliases `--sso` and `--hose-sso`) for generating temporary auto-login OAuth delegation links with safety warnings.
|
||||
- Structured return payload into Form 1: `{ url, type, mode, sealResultUrl, hoseDocumentUrl, recordId, sourceDocumentSN, ... }`.
|
||||
- Added `seal-use auth link` (alias `seal-link`) for Seal AI console auto-login delegation links, clearly decoupled from `auth hose-link` for external Hose workbenches.
|
||||
- Hardened `approval-runs export` against extension confusion: rejects non-`.xlsx` extensions (such as `.csv`) with explicit error guidance.
|
||||
|
||||
### Removed
|
||||
- **Eliminated Ambiguous URL Fields & Super-Merged Enterprise Links**:
|
||||
- Completely purged vague `ssoUrl` and `documentUrl` fields from skill documentation, CLI `--help`, and OpenAPI schemas in favor of `sealResultUrl` and `hoseDocumentUrl`.
|
||||
- Stripped redundant enterprise console links (`enterpriseAssistUrl`, `enterpriseUrl`, `hoseEnterpriseUrl`, `missing.enterpriseAssistUrl`) from single-document `approval-runs link` command.
|
||||
|
||||
## [0.10.31] - 2026-09-20
|
||||
|
||||
### Added
|
||||
- **Top-Level Mandatory Business Vocabulary & Output Contract**: Elevated terminology and presentation rules to Chapter 0 of `SKILL.md` as mandatory red lines across all agent output channels (rules list, rule detail, diff review, doctor tenant, feedback remediation, and conversational dialogue).
|
||||
- Enforced business terms: `scope` ➔ `适用场景` (strictly prohibited: 适用范围, 适用模版), `strictness` ➔ `遵守程度` (`MUST_FOLLOW` ➔ `必须遵守`, `SHOULD_FOLLOW` ➔ `建议遵守`, `SUGGESTION` ➔ `提示参考`), `code` ➔ `规则编号` (e.g. `#0038`), `status` ➔ `启用状态`.
|
||||
- Machine UUID & Internal Fields Redaction: Strictly prohibited exposing raw persistence UUIDs (`01a00f...`, `cly...`) and internal technical names (`boundCorpRole`, `permissions: ["*"]`, `tenantSlug`) to users.
|
||||
- **Mandatory Image Presentation Contract for First-Time Onboarding**: Hardcoded rule in `SKILL.md` and `first-time-user.md` requiring agents to proactively render step-by-step visual screenshots using Markdown image syntax during onboarding, forbidding text-only descriptions.
|
||||
- **Clean Administrator Candidate Directory with Privacy Masking**: When multiple candidate administrators exist, the CLI formats a clean, numbered directory with standard Chinese mobile masking (`138****5678`), strips raw internal IDs and technical noise, provides friendly selection guidance (by name keyword, by last 4 digits of phone, or `--force`), and retains all candidates without omission.
|
||||
- **Automated Enterprise Name Resolution on Onboarding**: `corps add-hose`, `add-link`, and `extract-keys --save` now automatically query the live Seal tenant during verification and persist the human-readable enterprise name, preventing enterprises from being registered with raw machine IDs (e.g. `ID01LG7ksGroB1`).
|
||||
- **Doctor Tenant Diagnosis Humanization**: Added `boundCorpRoleDescription` and `permissionLevel` to provide clear, business-friendly status summaries without exposing raw internal arrays and enums.
|
||||
- **Business-Focused Rule Summary Fields**: Refined `RULE_SUMMARY_FIELDS` to prioritize `["code", "status", "strictness", "scope", "updatedAt"]`, eliminating raw UUIDs from default summaries.
|
||||
|
||||
## [0.10.30] - 2026-09-18
|
||||
|
||||
### Added
|
||||
- **Multi-Host AI Agent Skill Bridging**: Decoupled multi-host agent bridge (`src/core/agent-hosts/`) supporting Google Antigravity 2.0, WorkBuddy, Claude, and Qoder:
|
||||
- **Antigravity 2.0**: Automatically configures `~/.gemini/config/skills.json` using the client's concrete absolute home directory path. Prepends target path if absent, auto-upgrades legacy `~` tilde paths to absolute paths, and safely avoids touching valid existing entries.
|
||||
- **WorkBuddy, Claude, Qoder**: Automatically detects host installations and creates/manages `skills/seal-use` symlinks under `~/.workbuddy`, `~/.claude`, and `~/.qoder`. Detects parent directory symlinks (`skills -> ~/.agents/skills`) without mutating, heals broken symlinks, safely upgrades stale legacy directories containing `SKILL.md` to prevent version drift, and uses Windows Directory Junctions for non-admin permission compatibility.
|
||||
- **Zero-Pollution Guard**: Skips bridge creation if the host application root directory does not exist on the client machine.
|
||||
- **CLI Diagnostics**: Exposes host discovery and configuration state in both `seal-use skill install` and `seal-use skill status`.
|
||||
- **Doctor Rule Linter Health Check & Proactive Guidance**: Added `rule_linter` audit item in `seal-use doctor` to display current linter status, providing actionable hints (`seal-use config lint enable`), and updated skill documentation to instruct agents to proactively inquire before writing rule drafts.
|
||||
|
||||
## [0.10.29] - 2026-09-18
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# Bug Report: Seal Use CLI 演示流程体验问题清单
|
||||
|
||||
> 日期:2026-09-20
|
||||
> 版本:v0.10.30-dev
|
||||
> 场景:新用户接入演示 + 规则同步 + 回归测试全流程
|
||||
> 整理人:谢子豪
|
||||
|
||||
---
|
||||
|
||||
## 🔴 P0 级(功能硬伤,报错提示与实际行为不符)
|
||||
|
||||
### Bug 1:`approval-runs replay --sn` 参数不生效
|
||||
|
||||
**现象**:
|
||||
执行 `seal-use approval-runs replay --sn B26002326 --source-corp LyG3iezucw03fs --target-corp xiezihao --webhook "谢子豪测试"`
|
||||
|
||||
预期:重放指定单号 B26002326 的单据
|
||||
|
||||
实际:重放的是 B26002488(最新的一张单据),完全忽略了 `--sn` 参数,自动选择了最新记录。
|
||||
|
||||
**复现步骤**:
|
||||
1. 确保生产环境有多条历史单据
|
||||
2. 执行 replay 并指定 --sn 为较早的单据号
|
||||
3. 观察实际重放的单据号与指定不符
|
||||
|
||||
**影响**:用户无法精确重放指定单据,只能用 recordId 定位,对业务用户极不友好。
|
||||
|
||||
**建议**:
|
||||
- 修复 `--sn` 参数的解析逻辑
|
||||
- 或者在帮助文档里明确说明:--sn 仅用于查找 recordId,实际重放需要结合其他参数
|
||||
|
||||
---
|
||||
|
||||
### Bug 2:`corps regression` / `corps replay-test` 的 `--webhook` 参数无效
|
||||
|
||||
**现象**:
|
||||
测试环境存在多个 Webhook 通道时,执行回归测试报错:
|
||||
```
|
||||
当前租户存在多个 Webhook 通道 ["谢子豪测试", "啊 11"],请通过 --webhook <idOrName> 指定目标通道。
|
||||
```
|
||||
|
||||
但追加 `--webhook "谢子豪测试"` 或 `--webhook integration-xxx` 后,仍然报同样的错误。
|
||||
|
||||
**复现步骤**:
|
||||
1. 测试环境配置至少 2 个 Webhook 通道
|
||||
2. 执行 `seal-use corps regression --corp <prodCorpId>`
|
||||
3. 按提示追加 `--webhook <name>` 参数
|
||||
4. 仍然报相同错误
|
||||
|
||||
**临时绕过方案**:删除多余的 Webhook 通道,只保留 1 个。
|
||||
|
||||
**影响**:用户有多个测试通道时,无法通过参数指定使用哪个,只能删除配置。
|
||||
|
||||
**建议**:
|
||||
- 支持 `--webhook` 参数指定目标通道
|
||||
- 或者帮助文档里明确列出该参数
|
||||
|
||||
---
|
||||
|
||||
## 🟡 P1 级(体验问题,增加操作步骤)
|
||||
|
||||
### Bug 3:`corps add-hose` 管理员选择参数位置不一致
|
||||
|
||||
**现象**:
|
||||
新接入企业时,报错提示:
|
||||
```
|
||||
请指定要作为审计身份绑定的管理员:
|
||||
• 按姓名选择:追加 --staffName <姓名>
|
||||
• 按手机选择:追加 --staffPhone <手机号>
|
||||
```
|
||||
|
||||
但在命令行追加 `--staffName 叶文倩` 不生效,仍然报错。
|
||||
必须把 `staffName` 放到 `--json` 的 JSON 字符串内部才能生效。
|
||||
|
||||
**复现步骤**:
|
||||
1. 执行 `seal-use corps add-hose --json '{"appKey":"...","appSecurity":"..."}'`
|
||||
2. 按提示追加 `--staffName 张三`
|
||||
3. 仍然报"需要指定管理员"
|
||||
|
||||
**影响**:用户按照报错提示操作完全无效,需要试错多次才能搞对。
|
||||
|
||||
**建议**:
|
||||
- 要么修复命令行参数解析,让 `--staffName` 真正生效
|
||||
- 要么修改报错提示,明确说明参数需要放在 JSON 内部
|
||||
|
||||
---
|
||||
|
||||
### Bug 4:导出文件后缀名与实际格式不符
|
||||
|
||||
**现象**:
|
||||
执行 `seal-use approval-runs export --out records.csv`
|
||||
生成的文件实际是 xlsx 格式(Microsoft Excel 2007+),但后缀名是 .csv。
|
||||
|
||||
用户双击打开时可能因为后缀名不对而打开失败,或者 Excel 打开时弹格式不匹配警告。
|
||||
|
||||
**复现步骤**:
|
||||
1. 导出记录,指定 .csv 后缀
|
||||
2. 用 `file` 命令检查实际格式
|
||||
3. 发现是 xlsx 格式
|
||||
|
||||
**影响**:后缀名误导,用户预期是 CSV 实际是 Excel。
|
||||
|
||||
**建议**:
|
||||
- 根据实际格式自动选择正确的后缀名(.xlsx 或 .csv)
|
||||
- 或者在导出完成后明确提示用户实际文件格式
|
||||
|
||||
---
|
||||
|
||||
### Bug 5:缺少 `corps rename` 命令
|
||||
|
||||
**现象**:
|
||||
新接入企业时,企业名称默认为"待识别企业"。
|
||||
想改成真实名称,但没有 `corps rename` 命令。
|
||||
只能手动编辑配置文件。
|
||||
|
||||
**复现步骤**:
|
||||
1. 新接入一个企业
|
||||
2. 想修改企业名称
|
||||
3. 找不到 rename 相关命令
|
||||
|
||||
**影响**:新接入的企业名称不对,用户无法直接修改。
|
||||
|
||||
**建议**:
|
||||
- 新增 `seal-use corps rename <corpId> --name "新名称"` 命令
|
||||
- 接入完成后自动反查企业真实名称(从合思 OpenAPI 获取),不用用户手动改
|
||||
|
||||
---
|
||||
|
||||
### Bug 6:Seal 原生测试环境无法生成协助链接
|
||||
|
||||
**现象**:
|
||||
对于 Seal 原生类型的测试企业(sourceType: seal),执行 `auth hose-link` 报错:
|
||||
```
|
||||
Unsupported Seal source: seal
|
||||
```
|
||||
|
||||
只能拿到测试环境的基础 URL,但无法生成免密登录的协助链接。
|
||||
|
||||
**影响**:演示测试环境时,无法直接给用户一个可点击打开的链接。
|
||||
|
||||
**建议**:
|
||||
- 新增 `auth seal-link` 命令,支持 Seal 原生环境生成临时登录链接
|
||||
- 或者在 corps get 输出中直接提供一键访问链接
|
||||
|
||||
---
|
||||
|
||||
## 🟢 P2 级(小优化项)
|
||||
|
||||
### Bug 7:规则编号格式不统一
|
||||
|
||||
**现象**:
|
||||
- `rules list --summary` 输出的规则编号是纯数字(0, 1, 2...)
|
||||
- 但 Skill 文档和业务术语规范里说规则编号是 `#0038` 格式
|
||||
- 实际用 `rules get --code '#0038'` 时,传纯数字或带 # 号都可以,但展示时不统一
|
||||
|
||||
**影响**:小的体验不一致,不影响功能。
|
||||
|
||||
**建议**:统一对外展示格式,比如列表里也显示 `#0001` 这种带 # 号的格式。
|
||||
|
||||
---
|
||||
|
||||
### Bug 8:`corps add-hose` 重复接入时 overwrite 提示不明显
|
||||
|
||||
**现象**:
|
||||
如果企业已经配置过,再次执行 add-hose 会报:
|
||||
```
|
||||
Enterprise config already exists. Pass "overwrite": true to replace it.
|
||||
```
|
||||
|
||||
但这个提示在 JSON 内部参数里,用户不容易注意到。
|
||||
而且第一次失败后,第二次才想到要加 overwrite。
|
||||
|
||||
**影响**:小的体验问题。
|
||||
|
||||
**建议**:报错时更明显地提示"如需覆盖请在 JSON 中添加 overwrite: true"。
|
||||
|
||||
---
|
||||
|
||||
## 📋 总结
|
||||
|
||||
| 级别 | 数量 | 说明 |
|
||||
|------|------|------|
|
||||
| P0(硬伤) | 2 | 报错提示与实际行为不符,严重影响使用 |
|
||||
| P1(体验) | 4 | 增加操作步骤,需要试错 |
|
||||
| P2(优化) | 2 | 小的体验不一致 |
|
||||
|
||||
**优先修复建议**:
|
||||
1. 先修 P0 的两个参数问题(replay --sn 无效、regression --webhook 无效)
|
||||
2. 再修 P1 的 add-hose 参数位置问题
|
||||
3. 其他体验优化可以排到后面
|
||||
Vendored
+338
-397
File diff suppressed because it is too large.
Load diff
Vendored
+19
-7
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "seal-use Wrapped API",
|
||||
"version": "0.10.29",
|
||||
"version": "0.10.32",
|
||||
"description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"
|
||||
},
|
||||
"servers": [
|
||||
@@ -2206,7 +2206,7 @@
|
||||
],
|
||||
"operationId": "getApprovalRunUrl",
|
||||
"x-implementation-status": "implemented",
|
||||
"summary": "Get enterprise assist URL and optional source document URL",
|
||||
"summary": "Get Seal AI result URL and optional source document URL",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "corpId",
|
||||
@@ -2240,22 +2240,28 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Enterprise and document URLs.",
|
||||
"description": "Seal AI result URL and source document URL.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
"enterpriseAssistUrl": {
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"enterpriseUrl": {
|
||||
"sealResultUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"ssoUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"documentUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"hoseDocumentUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"recordId": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -3575,15 +3581,21 @@
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
"enterpriseAssistUrl": {
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"enterpriseUrl": {
|
||||
"sealResultUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"ssoUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"documentUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"hoseDocumentUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"recordId": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -376,12 +376,16 @@ RunUrlResponse:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
properties:
|
||||
enterpriseAssistUrl:
|
||||
url:
|
||||
type: string
|
||||
enterpriseUrl:
|
||||
sealResultUrl:
|
||||
type: string
|
||||
ssoUrl:
|
||||
type: string
|
||||
documentUrl:
|
||||
type: string
|
||||
hoseDocumentUrl:
|
||||
type: string
|
||||
recordId:
|
||||
type: string
|
||||
sourceDocumentSN:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: seal-use Wrapped API
|
||||
version: 0.10.29
|
||||
version: 0.10.32
|
||||
description: |
|
||||
HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter
|
||||
(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).
|
||||
|
||||
@@ -225,7 +225,7 @@ paths:
|
||||
tags: [Approval Runs]
|
||||
operationId: getApprovalRunUrl
|
||||
x-implementation-status: implemented
|
||||
summary: Get enterprise assist URL and optional source document URL
|
||||
summary: Get Seal AI result URL and optional source document URL
|
||||
parameters:
|
||||
- $ref: ../components/parameters.yaml#/CorpId
|
||||
- name: recordId
|
||||
@@ -242,7 +242,7 @@ paths:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: Enterprise and document URLs.
|
||||
description: Seal AI result URL and source document URL.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.10.29",
|
||||
"version": "0.10.32",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
+100
-179
@@ -1,211 +1,132 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.10.29: 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.32: 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.29
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.29)
|
||||
version: 0.10.32
|
||||
short-description: Seal tenant and Hose approval automation (v0.10.32)
|
||||
---
|
||||
|
||||
# Seal Use (v0.10.29)
|
||||
# Seal Use (v0.10.32)
|
||||
|
||||
**The CLI is the primary path; the MCP server is an optional extra that is off by default.** Prefer the global `seal-use` CLI, and only use MCP when it is actually available in the current session. If no `seal_cli*` tool is present, that is the normal default — do not try to enable it or treat it as a fault; just use the CLI. Enabling it is the user's choice in the plugin settings (插件配置中的「启用 MCP 服务」,默认关闭,打开后需重连该插件的 MCP 服务).
|
||||
> CLI 是主执行通道,MCP 默认关闭(插件配置可选开启)。机器通道 (`stdout`) 必须输出纯净 JSON,诊断日志与下一步建议统一输出在 `stderr`。
|
||||
|
||||
When MCP *is* available, two tools are exposed:
|
||||
---
|
||||
|
||||
- `seal_cli` — **read-only only.** Reads tenant state without changing it. It is annotated `readOnlyHint: true`, so clients may auto-approve it.
|
||||
- `seal_cli_write` — everything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server. Annotated `destructiveHint: true`; **confirm the exact command with the user before calling it.**
|
||||
## 0. 全局业务术语与对外输出契约(Mandatory Vocabulary Contract)⚠️ 核心红线
|
||||
|
||||
The boundary is enforced, not merely advertised: `seal_cli` refuses any command that is not on its read-only allow-list, and unclassified commands fail closed. A refusal names `seal_cli_write` as the follow-up. `seal-use tool <name>` is allowed through `seal_cli` only for tools the registry classifies as read-only (`SEAL_READ_ONLY_TOOLS`); the rest need `seal_cli_write`.
|
||||
**所有场景强制生效**(包括规则列表、规则详情、规则修补与 Diff、单据核对、体检诊断、客诉排查及所有日常对话):
|
||||
|
||||
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.
|
||||
### 1.1 业务术语强制映射与违禁词红线
|
||||
| 系统字段 / 英文枚举 | 强制使用的业务术语 | 严禁自创 / 违禁词(红线) |
|
||||
| :--- | :--- | :--- |
|
||||
| `scope` | **适用场景** | ❌ 适用范围、适用模版、触发条件、触发范围 |
|
||||
| `strictness` | **遵守程度** | ❌ 严格度、执行力度、严重性、级别 |
|
||||
| `MUST_FOLLOW` | **必须遵守** | ❌ 必须执行、强阻断、必须遵守(系统) |
|
||||
| `SHOULD_FOLLOW`| **建议遵守** | ❌ 建议执行、弱提示、建议参考 |
|
||||
| `SUGGESTION` | **提示参考** | ❌ 参考、建议、提示 |
|
||||
| `code` | **规则编号** (如 `#0038`) | ❌ 规则代码、code、系统code |
|
||||
| `status` | **启用状态** (`已启用` / `已停用` / `草稿`) | ❌ active/inactive、生效状态 |
|
||||
| `description` | **规则内容 / 审核要求** | ❌ 规则描述、说明文案 |
|
||||
|
||||
## Bootstrap & Installation (环境安装与自愈)
|
||||
### 1.2 隐藏内部机器标识与脱敏原则
|
||||
- **严禁向用户直接暴露系统底层存储 UUID**(如 `01a00f34...`、`cly...` 等机器哈希),对外交流与呈现统一使用用户与管理后台唯一认知的业务编号:`规则编号: #xxxx`。
|
||||
- **严禁暴露内部技术参数名**:严禁向用户直接输出 `boundCorpRole: testTarget`、`tenantSlug`、`permissions: ["*"]` 等生硬技术字段,一律转化为业务中文表述(如“测试靶场环境”、“具备全部超级管理员权限”)。
|
||||
- **手机号脱敏**:凡涉及员工或管理员手机号,必须脱敏中间 4 位(`138****5678`),严防信息泄露。
|
||||
|
||||
Agent 必须确保使用最新版本的 `seal-use` CLI、Skill 与 Agent 插件。在执行任何配置或业务任务前,优先核验版本状态:
|
||||
---
|
||||
|
||||
```bash
|
||||
seal-use version
|
||||
seal-use corps list
|
||||
```
|
||||
## 1. 首次接入图文引导(Newbie 3-Step & Mandatory Image Rule)
|
||||
|
||||
如果 CLI 或 Skill 尚未安装或落后于发布版本,通过以下命令一键安装或升级:
|
||||
> **【强制执行契约】**:当用户首次使用、询问如何接入、或需要用户提供凭证材料时,**Agent 必须主动使用 Markdown 图片语法将对应步骤的截图呈现给用户,绝对禁止只发干瘪文字!**
|
||||
|
||||
```bash
|
||||
# 方式 1:CLI 自更新(已安装时推荐)
|
||||
seal-use update
|
||||
### 新手接入 3 步走:
|
||||
1. **确认材料类型**:向用户自然询问拥有的材料(合思开放平台凭据、协助链接、或网页 cURL)。
|
||||
2. **图文指导获取(必须贴图)**:
|
||||
- **路径一:合思开放平台(推荐·永久开发者凭据)**
|
||||
1. 进入「应用中心」搜索“接口”,进入「开放接口(新)」:
|
||||

|
||||
2. 点击「商品配置」:
|
||||

|
||||
3. 复制「接入账号」(`appKey`) 与「接入密码」(`appSecurity`):
|
||||

|
||||
- **路径二:从已登录网页复制 cURL(零门槛·会话快照或自动提权)**
|
||||
1. 在企业网页右键选择「检查」打开开发者工具:
|
||||

|
||||
2. 切换到「网络」-「Fetch/XHR」,刷新或点击任一列表:
|
||||

|
||||
3. 找到任一正常业务请求,右键「复制」-「以 cURL 格式复制」:
|
||||

|
||||
3. **无感接入**:Agent 接收材料后自动执行 `corps add-hose`、`corps add-link` 或 `corps extract-keys --save`,系统自动反查拉取真实企业中文名,自动绑定管理员,完成接入。无需用户手动查找 `corpId` 或 `staffId`。详阅 `references/first-time-user.md` 与 `references/enterprise-onboarding.md`。
|
||||
|
||||
# 方式 2:国内高速一键安装与自愈(Gitea 镜像源,免代理、秒级完成)
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
---
|
||||
|
||||
# 方式 3:Global / GitHub Direct
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
|
||||
```
|
||||
## 2. 80% 日常业务运维场景(Daily High-Frequency Operations)
|
||||
|
||||
安装或升级后,验证系统连通性:
|
||||
```bash
|
||||
seal-use version
|
||||
seal-use corps list
|
||||
```
|
||||
日常 80% 的工作聚焦在企业切换、规则查验、单据定位与运行大盘:
|
||||
|
||||
## First Rules
|
||||
### 2.1 企业定位与直达访问
|
||||
- 关键字智能搜索(支持同音字/拼音/简拼/容错):`seal-use corps search <keyword>`
|
||||
- 常用企业列表(默认展示 7 天使用频次最高的 10 家):`seal-use corps list`
|
||||
- 查看企业详情(富属性安全脱敏查看):`seal-use corps get <corpId>`
|
||||
- 生成 Seal AI 审核后台免密直达链接:`seal-use auth link [--corp <corpId>]`
|
||||
- 生成合思主系统工作台免密链接:`seal-use auth hose-link [--corp <corpId>]`
|
||||
|
||||
- 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, 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/first-time-user.md` for the plain-language, screenshot-based path first, then 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 ...]` for temporary session access, or elevate privileges to permanent developer credentials using `seal-use corps extract-keys <url> --save` (or `seal-use corps add-link <url> --as-hose`). This Hose-exclusive capability extracts `appKey`/`appSecurity`. If the enterprise has multiple keys, specify `--app-key <key>` or `--key-id <id>`.
|
||||
- **同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a cURL copied from an authenticated **Hose admin** page are both Hose web frontend sessions — structurally different in format only, carrying the same `accesstoken`/`corpid` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting `accesstoken`+`corpid`+`baseUrl` from the cURL and invoking the Hose key interface (`/api/innerapi/v1/key`) to retrieve permanent `appKey`/`appSecurity`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
|
||||
- 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. Calling key extraction or `keys` on native Seal enterprises is strictly blocked.
|
||||
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
|
||||
- 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, `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. Always follow the Presentation & Report Contract in `references/customer-feedback-rule-remediation.md`: hide internal UUIDs, use standard business terms (适用场景, 遵守程度), present unmodified fields cleanly without colloquial fluff, format description changes as standard Git Diff, and avoid repeating full report text in chat context once structured HTML/PDF artifacts are delivered (guide users to external browsers/viewers instead).
|
||||
- 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`.
|
||||
- If output may be large, use `--summary`, `--fields`, `--count`, or `--output-file`; use `--full` only when the user really needs full payloads.
|
||||
- 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, 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 应主动提示并建议在测试环境中验证,但最终操作权与决策权在用户手中,绝不代替用户做决定。若用户明确要求直接在生产环境发布,尊重用户意图并严格执行。
|
||||
- 在对企业执行高风险操作、批量审批或发布前,优先运行 `seal-use doctor tenant --corp <corpId>` 校验租户健康契约:验证身份管理权限、AI 审核扣费点数余量(`balance` 与 `deductionAmount`)、活跃规则与未发布草稿箱、Webhook 通道以及测试环境绑定。
|
||||
- 在测试企业完成规则同步后,强烈推荐运行 `seal-use test regression --corp <corpId> [--samples 10]` 执行自动化回归测试矩阵:自动采样生产历史单据并在测试靶场重放对比决策,核验决策翻转率(Flips)与一致率,确保 `safeToPublish: true` 后再行投产。硬性红线:回归测试严禁直接在纯生产企业运行(必须下挂测试靶场),且测试环境点数余额必须充足。
|
||||
- 单据 Webhook 重放安全与用户自主权策略:单据重放建议优先在绑定的测试企业中验证(CLI 与 MCP 默认拦截向生产环境重放以防污染真实审批流或产生实际外发回调)。Agent 应主动向用户解释风险并优先建议在测试环境模拟;但工具绝不反客为主,最终决策权在用户手中。若用户未绑定测试企业,或明确要求直接向生产环境重放,Agent 应向用户客观说明可能污染生产审批流或触发真实外部回调的风险;在确认用户明确意图后,通过追加 `--force`(或 MCP `force: true`)严格执行,绝不擅自拒绝用户要求。
|
||||
- 测试环境合思模拟安全隔离:`corps sync-test` 自动将生产企业合思凭证以 `assisted` 模式注入测试企业,名称格式为 `{企业名前缀}(Seal测)`。该配置仅保存在测试 Seal 侧,绝对不执行 `deploy hosecloud sync`,杜绝向生产合思费控推送 EBot 节点或创建外发 webhook。
|
||||
### 2.2 规则查验(遵循术语契约,使用规则编号 #xxxx)
|
||||
- 规则总数快速感知:`seal-use rules count --corp <corpId>`
|
||||
- 规则精简列表(聚焦业务字段,不漏底层 UUID):`seal-use rules list --corp <corpId> --summary`
|
||||
- 查看单条规则详情:`seal-use rules get --corp <corpId> --code '#0038'`
|
||||
|
||||
## Route By Intent
|
||||
### 2.3 单据定位与审核追踪
|
||||
- 单号秒级定位:`seal-use approval-runs pick --corp <corpId> --sn <单据编号> --latest`
|
||||
- 单据摘要与审核结论:`seal-use approval-runs get <recordId> --corp <corpId> --summary`
|
||||
- 单据引用规则速查:`seal-use approval-runs cited-rules <recordId> --corp <corpId>`
|
||||
- 生成业务审批单直达链接:`seal-use approval-runs link <recordId> --corp <corpId>`
|
||||
|
||||
- 生产规则安全演进、搭配配置与测试模拟闭环: read `references/staging-simulation-workflow.md`. 适用于:用户提出规则变更需求/客诉修复、生产与测试企业搭配接入与 1 对 1 绑定、生产环境仅改草稿隔离风险、`seal-use corps sync-test` 一键同步测试环境(含合思集成免配同步)、测试靶场运行自动化规则回归测试矩阵(`test regression`)或真实单据模拟验证、验证通过后才在生产正式发布的完整安全生命周期。
|
||||
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/first-time-user.md` and `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.
|
||||
- 自动化规则回归测试矩阵 (Automated Rule Regression Test Matrix): `seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips] [--prod-corp <id>] [--test-corp <id>]` (快捷别名 `seal-use corps regression`)。采样生产企业历史已完成单据,通过出站 HTTPS 轮询重放到配对测试靶场执行 AI 审核并对比双端决策,计算一致率(Concordance Rate),识别决策翻转(Decision Flips),给出 `safeToPublish` 综合判定。硬性红线:目标环境必须为测试企业且测试点数余额充足,严禁在纯生产环境发起。
|
||||
- 模拟测试发布闭环: `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>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict]` (列表与轻量检索,默认展示 7 天使用频次最高的 10 个租户;`--all` 展示全量;`--sort usage|name|id` 切换排序), `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 corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]` (将绑定的生产企业历史审批记录批量或单条重放到测试企业 Webhook 并做环境隔离与自动通道补齐;若未绑定测试企业可加 `--force` 直接重放), `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|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,文件名强制追加精确到分钟的 `_YYYYMMDD_HHmm` 时间戳后缀防止覆盖;支持 `--sn <SN1,SN2>` 定向筛选极速导出并跳过全量分页;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。
|
||||
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]`; 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 审核后台】委托授权链接): `seal-use delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `revoke <tokenId> --corp <corpId>`. 注意:此处管理 Seal AI 智能审核后台的委托令牌,不包含合思主站免密链接(后者走 `auth hose-link`,不可在 `delegation list` 中查询)。
|
||||
- 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|risks|performance --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>` 检查企业环境、租户连通性、已激活通道与资源包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
|
||||
- Webhook 资源包管理 (Webhook Resource Pack): `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` 从线上审核记录直接打包导出为标准 Webhook 资源包(包含根目录 `信息表.xlsx` 与下载好的单据附件),便于通过邮件/微信等第三方渠道离线分发;`seal-use webhook resource-pack preview <资源包.zip> --corp <corpId>` 本地预检单据与附件;`seal-use webhook resource-pack push <资源包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。CLI 简写别名 `pack`,旧名 `material-pack` 完整向下兼容保留。每个 Webhook 可配置资源包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。资源包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明附件的单据必须有对应根目录,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Webhook Resource Pack Workflow" 一节。它与 Seal 官方在模拟测试中使用的 `simulation material_pack` 流程相互独立,避免混淆。
|
||||
- 审批记录转 Webhook 重放 (Universal Record Replay): `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` 以及生产测专用快捷命令 `seal-use corps replay-test [<prodCorpId>] [--force]`。通用支持从历史审批记录(Webhook 来源、Hose 来源等)汲取结构化表单与明细字段,自动清洗规范化字段类型,支持按状态/数量批量重放到目标企业 Webhook 触发审批。默认推荐并导向测试企业(测试企业无 Webhook 时自动开通辅助模式通道并锁定环境隔离);若用户未绑定测试企业或明确要求向生产企业重放,支持通过 `--force` 显式执行,方便环境回归验证与 Bad Case 靶向调试。
|
||||
### 2.4 审核大盘与健康体检
|
||||
- 审核大盘统计(按单据去重):`seal-use approval-runs stats --corp <corpId> --dedupe-by sourceDocumentSN`
|
||||
- 企业健康契约体检(点数余额、管理员身份、规则状态):`seal-use doctor tenant --corp <corpId>`
|
||||
|
||||
- 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 tenant [--corp <corpId>] [--quiet]` (企业租户级健康契约探针:身份/管理员角色、AI 审批点数余额与单次扣费、活跃规则数、草稿安全性、Webhook 通道与环境配对), `seal-use doctor guide` (纯内存只读输出内嵌白皮书与目录规范), `seal-use doctor paths` (紧凑型核心目录健康检查)。
|
||||
- Full CLI inventory: read `references/cli.md`.
|
||||
---
|
||||
|
||||
## Material-pack Webhook policy and recovery
|
||||
## 3. 生产规则变更安全闭环(Rule Remediation & Change Cycle)
|
||||
|
||||
材料包附件策略保存在目标入站 Webhook 的 `materialPackFilePolicy` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 `500` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。`信息表.xlsx` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 `references/cli.md`。
|
||||
生产环境规则修改必须遵守安全演进闭环:
|
||||
`生产改草稿 -> 同步测试企业 -> 靶场模拟/回归矩阵验证 -> 生产确认发布`
|
||||
|
||||
这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理:
|
||||
1. **草稿修改与规范 Diff 呈现**:
|
||||
- 规则客诉修复与修改详阅 `references/customer-feedback-rule-remediation.md`;
|
||||
- 必须向用户呈现统一 Git Diff,展示业务字段(适用场景、遵守程度、规则编号),隐藏内部 UUID;
|
||||
- 生产修改时默认仅保存为**草稿态**,绝不直接线上生效。
|
||||
2. **一键同步测试环境**:
|
||||
- 运行 `seal-use corps sync-test <prodCorpId>`,自动将草稿规则发布到绑定的测试靶场 `[Prod vN · #M -> Test vM]`,同时自动同步免配的合思测试通道。
|
||||
3. **测试靶场自动化验证**:
|
||||
- 运行 `seal-use test regression --corp <testCorpId> --samples 10` 执行自动化规则回归测试矩阵;
|
||||
- 重放生产历史单据,检验决策一致率(Concordance Rate)与决策翻转(Flips),确保 `safeToPublish: true`。
|
||||
4. **用户授权确认与生产发布**:
|
||||
- 严禁代替用户决策,只有在用户明确确认批准后,方可在生产环境正式发布。
|
||||
|
||||
1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。
|
||||
2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。
|
||||
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置:`seal-use webhook get`/`webhook list`,或等价的 `seal-use tool seal_webhook_get`/`seal_webhook_list`(MCP 下经 `seal_cli` 执行)。
|
||||
4. 修改最小值、最大值或完整后缀白名单:`seal-use webhook update`,或等价的 `seal-use tool seal_webhook_update`(MCP 下经 `seal_cli_write` 执行,需用户确认)。写入后重新读取核对,再重试原来的材料包 push。
|
||||
---
|
||||
|
||||
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 `stderr` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
|
||||
## 4. 进阶能力路由(Advanced Capabilities & References)
|
||||
|
||||
注意:直接执行本地 `material-pack preview` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;`webhook ready --file`(指定 Webhook 时)和 `material-pack push` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 `ready --file --webhook ...`,或直接重试 push。
|
||||
需要执行进阶或专项目标时,按需查阅对应子文档:
|
||||
- **新手首次接入图文说明**:详阅 `references/first-time-user.md`(面向小白用户的看图指南)
|
||||
- **企业认证凭证模型与提权机制**:详阅 `references/enterprise-onboarding.md`(同等凭据原则、OpenAPI 开发者密钥提取)
|
||||
- **生产与测试环境搭配与模拟全流程**:详阅 `references/staging-simulation-workflow.md`(生产改草稿、测试验证闭环)
|
||||
- **客诉定界排查与最小规则 Patch 规范**:详阅 `references/customer-feedback-rule-remediation.md`(差旅、费用争议的标准报告闭环)
|
||||
- **合思 EBot 审核节点发布与部署**:详阅 `references/hose-enterprise-deploy.md`
|
||||
- **合思企业配置、认证诊断与授权链接**:详阅 `references/hose-enterprise-auth.md`
|
||||
- **单据附件与发票争议 Langfuse 追踪**:详阅 `references/approval-attachment-trace.md`
|
||||
- **规则质量校验器 (Linter)**:详阅 `references/rule-lint.md`(builtin / strict / hlab 规则质检规范)
|
||||
- **Webhook 资源包导出与离线重放**:详阅 `references/cli.md` (Webhook Resource Pack 章节)
|
||||
- **完整 CLI 命令全景**:详阅 `references/cli.md`
|
||||
|
||||
## High-Value Commands
|
||||
---
|
||||
|
||||
```bash
|
||||
seal-use doctor
|
||||
seal-use doctor tenant --corp <corpId>
|
||||
seal-use doctor guide
|
||||
seal-use test regression --corp <corpId> --dry-run
|
||||
seal-use test regression --corp <corpId> --samples 10 --fail-on-flips
|
||||
seal-use corps list [query] [--env production|test] [--limit 10] [--all] [--sort usage|name|id]
|
||||
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
|
||||
seal-use approval-runs get <recordId> --corp <corpId> --fields metadata,document.fields,result.summary
|
||||
seal-use approval-runs document-summary <recordId> --corp <corpId>
|
||||
seal-use approval-runs cited-rules <recordId> --corp <corpId>
|
||||
seal-use approval-runs attachments <recordId> --corp <corpId> --summary
|
||||
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'
|
||||
seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
|
||||
seal-use simulation create --corp <corpId> --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high]
|
||||
seal-use simulation create --corp <corpId> --mode material_pack --package-ids <materialPackageId> [--schema-config file.json]
|
||||
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
|
||||
# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s):
|
||||
seal-use approval-runs export --corp <corpId> --downloads --with-flow
|
||||
# Target specific document SNs for instant export without full pagination:
|
||||
seal-use approval-runs export --corp <corpId> --sn B26002307,B26002144 --with-flow --downloads
|
||||
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"]}'
|
||||
```
|
||||
## 5. 安全守则与参数责任(Safety Guardrails & Parameter Ownership)
|
||||
|
||||
## Important Fields
|
||||
|
||||
- `sourceDocumentSN`: external document number, often the easiest 合思/易快报 lookup key.
|
||||
- `sourceDocumentId`: external source document ID.
|
||||
- `recordId`: Seal approval run record ID.
|
||||
- `simulationBatchId`: simulation batch identifier.
|
||||
- `status`: run status.
|
||||
- `taskMode` / `finalExecutionMode`: execution mode information.
|
||||
- `ruleSetVersionNumber`: approval rule version used by a run.
|
||||
- `langfuseTraceId`: direct Langfuse trace lookup key.
|
||||
- `langfuseSessionFallback`: fallback session key, usually `hosecloud-{sourceDocumentSN}`.
|
||||
|
||||
## References
|
||||
|
||||
- `references/first-time-user.md`: 面向完全新手的首次接入图文说明,包含合思开放接口密钥和浏览器 cURL 两条路径;配套图片在同级 `assets/` 目录。
|
||||
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
|
||||
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
|
||||
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
|
||||
- `references/rule-lint.md`: 规则质量检查器(Linter,含 builtin / strict / hlab 官方规范)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
|
||||
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
|
||||
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
|
||||
- `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
|
||||
|
||||
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real `enterprises/*.json` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
|
||||
- **参数责任原则**:绝不向普通用户索要 `corpId`、`staffId`、`proxyStaffBizId`、`tenantId` 等底层机器 ID。所有参数必须由 Agent 自动发现与解析。若有多位管理员,展示脱敏手机号与姓名让用户抉择。
|
||||
- **链接安全规范**:
|
||||
- 返回授权、协助或委托链接时,必须同时提供代码块(便于复制)与可点击链接;
|
||||
- 审批单链接默认提供只读 Deep Link(`type: 'deep_link'`);仅在用户明确需要免密时才使用 `--sso` 并声明四项安全告知。
|
||||
- **高危写操作防线**:规则推送(`rules push`)、清空(`rules clear`)、发布(`rules publish`)等破坏性写操作必须先通过 `--dry-run` 预览 diff 并获得用户明确批准后方可执行。
|
||||
@@ -84,27 +84,36 @@ 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
|
||||
## Approval Run Web Links & Auto-Login 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>
|
||||
# 默认推荐:生成 Seal AI 审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)
|
||||
seal-use approval-runs link <recordId> --corp <corpId>
|
||||
seal-use approval-runs link --sn <sourceDocumentSN> --corp <corpId>
|
||||
|
||||
# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带单次临时票据的 SSO 直登链接
|
||||
seal-use approval-runs url <recordId> --sso [--expire 7200] --corp <corpId>
|
||||
# 生成合思主系统原始单据页面链接
|
||||
seal-use approval-runs link <recordId> --type hose-document --corp <corpId>
|
||||
|
||||
# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接
|
||||
seal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>
|
||||
```
|
||||
|
||||
### SSO 链接安全与声明规范
|
||||
当向用户返回 `--sso` 链接时,Agent **必须**在回答中明确说明以下 4 点:
|
||||
### 返回字段说明与语义规范
|
||||
- `sealResultUrl`: Seal AI 单据智能审核结果页
|
||||
- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页
|
||||
- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`
|
||||
- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)
|
||||
|
||||
### 免登链接安全与声明规范
|
||||
当向用户返回 `--auto-login` 链接时,Agent **必须**在回答中明确说明以下 4 点:
|
||||
1. **身份主体**:该链接代表哪个具体员工身份(如管理员姓名)登录。
|
||||
2. **权限范围**:该身份在 Seal AI 平台的全部权限范围(如完全操作权限)。
|
||||
3. **时效性**:临时 Ticket 换票时效(默认 2 小时,换票登录后会话有效 30 天)。
|
||||
4. **安全与防扩散边界**:该链接仅在 Seal AI 租户内生效,不代表合思主系统权限;严禁在公开或外部群聊中传播。
|
||||
|
||||
> **链接输出要求**:无论返回普通深度链接还是 SSO 链接,必须同时提供纯文本代码块(` ```text ... ``` `)防止默认浏览器误点重定向,以及可点击的 Markdown 超链接。
|
||||
> **链接输出要求**:无论返回普通深度链接还是免登链接,必须同时提供纯文本代码块(` ```text ... ``` `)防止默认浏览器误点重定向,以及可点击的 Markdown 超链接。
|
||||
|
||||
## Replay Run into Webhook for Regression Testing
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ seal-use corps keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>] [--
|
||||
seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
|
||||
seal-use auth keys [--corp <corpId>] [--reveal]
|
||||
seal-use auth diagnose [--corp <corpId>]
|
||||
seal-use auth link [--corp <corpId>] [--note <note>]
|
||||
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
|
||||
seal-use delegation list [--corp <corpId>]
|
||||
seal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
|
||||
@@ -160,10 +161,11 @@ 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 <recordId> --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 link <recordId> --corp <corpId>
|
||||
seal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>
|
||||
seal-use approval-runs link <recordId> --type hose-document --corp <corpId>
|
||||
seal-use approval-runs link --sn <documentSN> [--auto-login] --corp <corpId>
|
||||
# 兼容别名:seal-use approval-runs url <recordId>
|
||||
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>
|
||||
|
||||
@@ -157,6 +157,13 @@ State the target enterprise, target rule code, changed fields, preserved fields,
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### 规则质量预检与主动询问 (Proactive Linting & Quality Assurance)
|
||||
|
||||
- 规则质量校验器(Linter)在系统中**默认关闭**以避免对普通流程产生无端噪音。
|
||||
- 在起草补丁或写入草稿时,Agent **建议主动向用户告知并询问是否需要开启自动校验**:
|
||||
> “系统内置了审批规则质量校验器(可实时拦截‘适当’、‘酌情’等主观模糊词或悬空例外,防止大模型判定波动)。当前全局默认关闭,请问是否需要为您开启?(可通过 `seal-use config lint enable` 开启)”
|
||||
- 校验器定位为**辅助排雷与风险揭示**,绝非硬性阻断。若用户决定开启,则后续草稿写入将享有实时质量扫描;若用户暂不需要,Agent 亦可在必要时单次运行 `seal-use rules lint --code <code>` 辅助体检,把最终决策权始终留给用户。
|
||||
|
||||
## 7. Mutation gate and concurrency check
|
||||
|
||||
Do not update until the user explicitly approves the exact diff.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Enterprise Onboarding
|
||||
|
||||
Read this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.
|
||||
> 💡 **新手接入指引分工**:
|
||||
> - 若是引导无技术背景的用户找凭证材料、找按钮,**必须直接使用 `references/first-time-user.md` 并渲染其中的指引截图**;
|
||||
> - 本文档用于 Agent 理解企业身份源划分、标准凭证/协助链接/cURL 的后台凭据生命周期、合思子域 OpenAPI 提权机制与参数自动发现。
|
||||
|
||||
## Start With Discovery
|
||||
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
# 第一次接入:看图找到材料
|
||||
|
||||
> **【Agent 呈现铁律(Mandatory Image Rule)】**:
|
||||
> 当向用户提供接入指引或引导用户获取材料时,**Agent 必须将本文档中对应的截图主动按顺序渲染到 Markdown 对话中**(使用图片语法 ``),**绝不允许只讲纯文字步骤!** 真实业务用户必须对照图片界面才能准确找到按钮。
|
||||
|
||||
这份说明给第一次使用 Seal Use、还不熟悉“合思”“Seal”“appKey”“cURL”等词的用户。
|
||||
|
||||
用户不需要先知道 `corpId`、`staffId`、域名或内部命令。只要能进入企业网页,助手会负责识别企业和接入方式。
|
||||
|
||||
## 路径一:从合思开放接口取得接入账号和接入密码
|
||||
## 路径一:从合思开放接口取得接入账号和接入密码(推荐·永久配置)
|
||||
|
||||
这条路径适用于有合思开放平台或应用管理权限的用户。
|
||||
|
||||
在合思网页中依次完成:
|
||||
|
||||
1. 打开「应用中心」或「应用商店」。
|
||||
2. 搜索“接口”。
|
||||
3. 进入「开放接口(新)」。
|
||||
4. 点击「商品配置」。
|
||||
5. 在配置面板中找到:
|
||||
1. 打开「应用中心」或「应用商店」,搜索“接口”,进入「开放接口(新)」:
|
||||

|
||||
|
||||
2. 点击「商品配置」:
|
||||

|
||||
|
||||
3. 在配置面板中找到:
|
||||
- **接入账号**:这就是 `appKey`。
|
||||
- **接入密码**:这就是 `appSecurity`。需要先点击「显示」再复制。
|
||||
6. 将这两项只交给当前本地助手,不要发到群聊、工单、公共文档或代码仓库。
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
4. 将这两项直接发送给当前本地助手,不要发到外部群聊、工单、公共文档或代码仓库。
|
||||
|
||||
助手拿到这两项后,会自动探测合思环境、识别企业、发现管理员绑定,并验证 Seal 会话。用户不需要填写 `corpId`、`staffId` 或域名。
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ Use this reference when analyzing, validating, or linting Seal AI approval rules
|
||||
## Key Principles
|
||||
|
||||
- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.
|
||||
- **Doctor Visibility**: `seal-use doctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-use config lint enable`) when disabled.
|
||||
- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.
|
||||
- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.
|
||||
- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.
|
||||
|
||||
@@ -194,6 +194,8 @@ flowchart TD
|
||||
# 获取详细判决与命中规则
|
||||
seal-use simulation batch-records <batchId> --corp <testCorpId>
|
||||
```
|
||||
> 提示:亦可在前端控制台实时监控测试批次大盘与判定看板:`https://<testCorp>.staging.sealai.cc/audit/deploy/simulation`。
|
||||
|
||||
核对:
|
||||
- 期望通过的单据是否正确通过;
|
||||
- 期望拦截或预警的单据是否命中了预期的规则(对照 `rules map`);
|
||||
|
||||
@@ -302,20 +302,35 @@ export async function handleApprovalRunsCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "url") {
|
||||
const sso = booleanOption(args.options.sso) ?? false;
|
||||
if (action === "link" || action === "url") {
|
||||
const autoLogin =
|
||||
booleanOption(args.options["auto-login"]) ??
|
||||
booleanOption(args.options.autoLogin) ??
|
||||
booleanOption(args.options["hose-sso"]) ??
|
||||
booleanOption(args.options.hoseSso) ??
|
||||
booleanOption(args.options.sso) ??
|
||||
false;
|
||||
const type = stringOption(args.options.type);
|
||||
const expiresIn = numberOption(args.options.expire) ?? numberOption(args.options.expiresIn) ?? 7200;
|
||||
const recordId = maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId);
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
|
||||
const sourceDocumentId = stringOption(args.options.sourceDocumentId);
|
||||
|
||||
if (!recordId && !sn && !sourceDocumentId) {
|
||||
throw new Error("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
|
||||
}
|
||||
|
||||
await runTool(
|
||||
"seal_approval_run_url_get",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
recordId: maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId),
|
||||
recordId,
|
||||
sourceDocumentSN: sn,
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId),
|
||||
sso,
|
||||
sourceDocumentId,
|
||||
type,
|
||||
autoLogin,
|
||||
sso: autoLogin,
|
||||
expiresIn
|
||||
},
|
||||
outputOptions(args.options)
|
||||
@@ -395,7 +410,11 @@ export async function handleApprovalRunsCommand(
|
||||
booleanOption(args.options["exclude-deleted"]) ??
|
||||
(booleanOption(args.options["include-deleted"]) ? false : undefined),
|
||||
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
|
||||
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"])
|
||||
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]),
|
||||
includeSimulation:
|
||||
booleanOption(args.options["include-simulation"]) ??
|
||||
booleanOption(args.options.includeSimulation) ??
|
||||
booleanOption(args.options["simulation"])
|
||||
});
|
||||
console.error(`👉 查看导出文件: open "${result.filePath}"`);
|
||||
if (!args.options["with-flow"] && corp.source.type === "hose") {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getMe } from "../../domains/seal/api.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, redactSensitiveText } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { runToolResult } from "../helpers.js";
|
||||
import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
|
||||
|
||||
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
|
||||
@@ -38,6 +39,22 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp.source.type === "seal")) {
|
||||
const client = await createSealClient(corp);
|
||||
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
||||
const delegation = await runToolResult(
|
||||
"seal_delegation_create",
|
||||
client,
|
||||
corp,
|
||||
{ note }
|
||||
);
|
||||
if (action === "hose-link") {
|
||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||
}
|
||||
printJson(delegation);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "hose-link") {
|
||||
const rawExpire = args.options.expire;
|
||||
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
|
||||
|
||||
@@ -841,4 +841,61 @@ describe("Hose OpenAPI key extraction from assistance link", () => {
|
||||
expect(authResult.exitCode).toBe(2);
|
||||
expect(authResult.stderr).toContain("合思子域专享能力");
|
||||
});
|
||||
|
||||
test("corps rename updates enterprise name successfully", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
writeFileSync(
|
||||
join(enterprises, "corp-rename.json"),
|
||||
JSON.stringify({
|
||||
id: "corp-rename",
|
||||
name: "待识别企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://seal.example.com" },
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.example.com",
|
||||
token: "token-123"
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const result = await runCli(["corps", "rename", "corp-rename", "--name", "已识别真实企业"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed).toEqual({
|
||||
id: "corp-rename",
|
||||
previousName: "待识别企业",
|
||||
name: "已识别真实企业",
|
||||
success: true
|
||||
});
|
||||
|
||||
const updated = JSON.parse(readFileSync(join(enterprises, "corp-rename.json"), "utf-8"));
|
||||
expect(updated.name).toBe("已识别真实企业");
|
||||
});
|
||||
|
||||
test("corps rename rejects missing --name parameter", async () => {
|
||||
setupConfigEnv();
|
||||
const result = await runCli(["corps", "rename", "some-corp"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("Usage: seal-use corps rename <corpId> --name <newName>");
|
||||
});
|
||||
|
||||
test("maskCellphone masks standard 11-digit mobile and non-standard phones safely", async () => {
|
||||
const { maskCellphone } = await import("./corps.js");
|
||||
expect(maskCellphone("13812345678")).toBe("138****5678");
|
||||
expect(maskCellphone("19988887777")).toBe("199****7777");
|
||||
expect(maskCellphone(undefined)).toBe("未绑定手机");
|
||||
expect(maskCellphone("")).toBe("未绑定手机");
|
||||
expect(maskCellphone("010123456")).toBe("010****3456");
|
||||
});
|
||||
|
||||
test("RULE_SUMMARY_FIELDS excludes raw internal UUID and prioritizes business fields", async () => {
|
||||
const { RULE_SUMMARY_FIELDS } = await import("../printer.js");
|
||||
expect(RULE_SUMMARY_FIELDS).not.toContain("id");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("code");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("status");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("strictness");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("scope");
|
||||
});
|
||||
});
|
||||
+94
-12
@@ -270,6 +270,31 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "rename") {
|
||||
const targetCorpId =
|
||||
maybeName ??
|
||||
stringOption(args.options.corp) ??
|
||||
stringOption(args.options.id);
|
||||
const newName =
|
||||
stringOption(args.options.name) ??
|
||||
stringOption(args.options.to) ??
|
||||
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
|
||||
|
||||
if (!targetCorpId || !newName) {
|
||||
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
|
||||
}
|
||||
|
||||
const corp = selectCorp(targetCorpId);
|
||||
const updated = updateCorpConfig(corp.id, { name: newName });
|
||||
printJson({
|
||||
success: true,
|
||||
id: updated.id,
|
||||
name: updated.name,
|
||||
previousName: corp.name
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "bind-test") {
|
||||
let prodId: string | undefined;
|
||||
let testId: string | undefined;
|
||||
@@ -954,12 +979,40 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
}
|
||||
|
||||
if (action === "add-hose") {
|
||||
await addHoseCorp(jsonObject(args.json));
|
||||
const jsonPayload = jsonObject(args.json);
|
||||
const merged = {
|
||||
...jsonPayload,
|
||||
...(args.options.staffName ? { staffName: stringOption(args.options.staffName) } : {}),
|
||||
...(args.options["staff-name"] ? { staffName: stringOption(args.options["staff-name"]) } : {}),
|
||||
...(args.options.staffPhone ? { staffPhone: stringOption(args.options.staffPhone) } : {}),
|
||||
...(args.options["staff-phone"] ? { staffPhone: stringOption(args.options["staff-phone"]) } : {}),
|
||||
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
|
||||
...(args.options.domain ? { domain: stringOption(args.options.domain) } : {}),
|
||||
...(args.options.corpId ? { corpId: stringOption(args.options.corpId) } : {}),
|
||||
...(args.options["corp-id"] ? { corpId: stringOption(args.options["corp-id"]) } : {}),
|
||||
...(args.options.appKey ? { appKey: stringOption(args.options.appKey) } : {}),
|
||||
...(args.options["app-key"] ? { appKey: stringOption(args.options["app-key"]) } : {}),
|
||||
...(args.options.appSecurity ? { appSecurity: stringOption(args.options.appSecurity) } : {}),
|
||||
...(args.options["app-security"] ? { appSecurity: stringOption(args.options["app-security"]) } : {}),
|
||||
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
|
||||
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
|
||||
};
|
||||
await addHoseCorp(merged);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "add-seal") {
|
||||
await addSealCorp(jsonObject(args.json));
|
||||
const jsonPayload = jsonObject(args.json);
|
||||
const merged = {
|
||||
...jsonPayload,
|
||||
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
|
||||
...(args.options.token ? { token: stringOption(args.options.token) } : {}),
|
||||
...(args.options.sealUrl ? { sealUrl: stringOption(args.options.sealUrl) } : {}),
|
||||
...(args.options.url ? { sealUrl: stringOption(args.options.url) } : {}),
|
||||
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
|
||||
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
|
||||
};
|
||||
await addSealCorp(merged);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1038,6 +1091,25 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers & Sanitizers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function maskCellphone(phone: string | undefined | null): string {
|
||||
if (!phone) return "未绑定手机";
|
||||
const cleaned = phone.trim();
|
||||
if (cleaned.length === 11) {
|
||||
return `${cleaned.slice(0, 3)}****${cleaned.slice(7)}`;
|
||||
}
|
||||
if (cleaned.length >= 7) {
|
||||
return `${cleaned.slice(0, 3)}****${cleaned.slice(-4)}`;
|
||||
}
|
||||
if (cleaned.length > 4) {
|
||||
return `${cleaned.slice(0, 2)}****${cleaned.slice(-2)}`;
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hosecloud integration sync helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1326,12 +1398,16 @@ async function addHoseCorp(input: Record<string, unknown>) {
|
||||
);
|
||||
}
|
||||
} else if (!force) {
|
||||
const candidates = staffDetails
|
||||
.map((s) => `${s.name} (${s.cellphone || "no-phone"}, id: ${s.id}, active: ${s.active})`)
|
||||
.join("\n - ");
|
||||
const candidateLines = staffDetails
|
||||
.map((s, idx) => ` [${idx + 1}] ${s.name} (${maskCellphone(s.cellphone)})`)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
`Missing required parameter: staffId. Found ${staffDetails.length} candidate administrators:\n - ${candidates}\n` +
|
||||
`Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`
|
||||
`Missing required parameter: staffId. 当前企业共配置了 ${staffDetails.length} 位管理员账号(手机号已脱敏):\n\n` +
|
||||
`${candidateLines}\n\n` +
|
||||
`👉 请指定要作为审计身份绑定的管理员:\n` +
|
||||
` • 按姓名选择:追加 --staffName <姓名>(支持关键字,如: --staffName 谢子豪)\n` +
|
||||
` • 按手机选择:追加 --staffPhone <手机号>(支持手机后4位,如: --staffPhone 5678)\n` +
|
||||
` • 或传 force:true / --force 自动使用默认首位管理员。`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1348,7 +1424,7 @@ async function addHoseCorp(input: Record<string, unknown>) {
|
||||
}
|
||||
|
||||
const id = optionalString(input, "id") ?? corpId;
|
||||
const name = corpName ?? corpId;
|
||||
let name = nameInput ?? corpName ?? corpId;
|
||||
const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
const config: CorpConfig = {
|
||||
@@ -1376,14 +1452,20 @@ async function addHoseCorp(input: Record<string, unknown>) {
|
||||
|
||||
if (verify) {
|
||||
clearCorpTokenCache(id);
|
||||
await resolveLiveSealEnterpriseConfig(config);
|
||||
const live = await resolveLiveSealEnterpriseConfig(config);
|
||||
if ((!nameInput || nameInput === corpId) && live.tenantName && live.tenantName !== corpId) {
|
||||
name = live.tenantName;
|
||||
config.name = live.tenantName;
|
||||
}
|
||||
}
|
||||
|
||||
const enterprisesDir = resolveWritableEnterprisesDir();
|
||||
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
|
||||
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
|
||||
if (existsSync(file) && input.overwrite !== true) {
|
||||
throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
|
||||
throw new Error(
|
||||
`Enterprise config already exists: ${file}。如需覆盖已有配置,请在命令行追加 --overwrite 或在 JSON 参数中添加 "overwrite": true。`
|
||||
);
|
||||
}
|
||||
|
||||
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
||||
@@ -1529,7 +1611,7 @@ async function addLinkAsHoseCorp(
|
||||
appKey: selectedKey.appKey,
|
||||
appSecurity: selectedKey.appSecurity,
|
||||
corpId: result.corpId,
|
||||
name: name ?? result.corpName ?? result.corpId,
|
||||
name: name ?? result.corpName,
|
||||
staffId: result.staffId,
|
||||
overwrite,
|
||||
force
|
||||
@@ -1566,7 +1648,7 @@ export async function extractKeysFromLinkAction(
|
||||
appKey: selectedKey.appKey,
|
||||
appSecurity: selectedKey.appSecurity,
|
||||
corpId: result.corpId,
|
||||
name: options.name ?? result.corpName ?? result.corpId,
|
||||
name: options.name ?? result.corpName,
|
||||
staffId: result.staffId,
|
||||
overwrite: options.overwrite,
|
||||
force: options.force
|
||||
|
||||
@@ -18,11 +18,13 @@ describe("seal-use doctor CLI", () => {
|
||||
expect(data.enterprises).toBeDefined();
|
||||
expect(data.knowledge).toBeDefined();
|
||||
expect(data.knowledge.guideCommand).toBe("seal-use doctor guide");
|
||||
expect(data.checks.some((c: any) => c.id === "rule_linter")).toBe(true);
|
||||
|
||||
// stderr must contain human-friendly dashboard
|
||||
expect(result.stderr).toContain("Seal Use Doctor");
|
||||
expect(result.stderr).toContain("【运行环境】");
|
||||
expect(result.stderr).toContain("【核心路径状态】");
|
||||
expect(result.stderr).toContain("规则质量校验器");
|
||||
});
|
||||
|
||||
test("doctor guide dumps embedded documentation in Markdown", async () => {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
getAllLinkableHostsStatus,
|
||||
getAntigravitySkillsStatus,
|
||||
syncAllLinkableHosts,
|
||||
syncAntigravitySkillsConfig
|
||||
} from "../../core/agent-hosts/index.js";
|
||||
import {
|
||||
getDefaultGlobalSkillDir,
|
||||
getSkillContent,
|
||||
@@ -25,11 +31,17 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
|
||||
: getDefaultGlobalSkillDir();
|
||||
|
||||
const result = installSkillFiles(targetDir);
|
||||
const isGlobal = !isLocal && !customDir;
|
||||
const antigravity = isGlobal ? syncAntigravitySkillsConfig() : undefined;
|
||||
const hosts = isGlobal ? syncAllLinkableHosts() : undefined;
|
||||
|
||||
printJson({
|
||||
installed: true,
|
||||
targetDir: result.targetDir,
|
||||
fileCount: result.files.length,
|
||||
files: result.files
|
||||
files: result.files,
|
||||
...(antigravity ? { antigravity } : {}),
|
||||
...(hosts ? { hosts } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -37,6 +49,8 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
|
||||
if (action === "status" || action === "get" || !action) {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
const localDir = join(process.cwd(), ".agents", "skills", "seal-use");
|
||||
const antigravity = getAntigravitySkillsStatus();
|
||||
const hosts = getAllLinkableHostsStatus();
|
||||
printJson({
|
||||
global: {
|
||||
dir: globalDir,
|
||||
@@ -45,7 +59,9 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
|
||||
local: {
|
||||
dir: localDir,
|
||||
installed: existsSync(join(localDir, "SKILL.md"))
|
||||
}
|
||||
},
|
||||
antigravity,
|
||||
hosts
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -228,4 +228,26 @@ describe("seal-use test regression CLI", () => {
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
|
||||
test("test regression accepts --webhook option and succeeds in dry-run", async () => {
|
||||
setupTestEnv();
|
||||
mockApiFetch();
|
||||
|
||||
const result = await runCli([
|
||||
"test",
|
||||
"regression",
|
||||
"--corp",
|
||||
"corp-test",
|
||||
"--samples",
|
||||
"2",
|
||||
"--dry-run",
|
||||
"--webhook",
|
||||
"自定义通道"
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,7 @@ export async function handleTestCommand(
|
||||
const pollIntervalMs = numberOption(args.options["poll-interval"]) ?? 2000;
|
||||
const timeoutMs = numberOption(args.options.timeout) ?? 45000;
|
||||
const snPrefix = stringOption(args.options["sn-prefix"]) ?? "REG_";
|
||||
const webhookSelector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
|
||||
const result = await runRegressionTest({
|
||||
sourceCorp,
|
||||
@@ -85,7 +86,8 @@ export async function handleTestCommand(
|
||||
pollIntervalMs,
|
||||
timeoutMs,
|
||||
snPrefix,
|
||||
failOnFlips
|
||||
failOnFlips,
|
||||
webhookSelector
|
||||
});
|
||||
|
||||
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
|
||||
|
||||
+43
-8
@@ -77,6 +77,15 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
],
|
||||
description: "Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."
|
||||
},
|
||||
{
|
||||
name: "rename",
|
||||
summary: "Rename an enterprise display name",
|
||||
usage: ["seal-use corps rename <corpId> --name <newName>"],
|
||||
options: [
|
||||
{ flag: "--name <newName>", description: "New human-readable enterprise name (required)" }
|
||||
],
|
||||
description: "Safely updates the display name of a configured enterprise without modifying underlying files manually."
|
||||
},
|
||||
{
|
||||
name: "bind-test",
|
||||
summary: "Bind a production enterprise to a test enterprise (1-to-1 association)",
|
||||
@@ -449,13 +458,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
usage: ["seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
summary: "Get web console URL for approval run (default deep link, or --sso for auto-login link)",
|
||||
name: "link",
|
||||
aliases: ["url"],
|
||||
summary: "Get web console link for an approval run (Seal AI audit result or Hose original document)",
|
||||
usage: [
|
||||
"seal-use approval-runs url <recordId> [--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 link <recordId> [--corp <corpId>]",
|
||||
"seal-use approval-runs link <recordId> --auto-login [--expire 7200] [--corp <corpId>]",
|
||||
"seal-use approval-runs link <recordId> --type hose-document [--corp <corpId>]",
|
||||
"seal-use approval-runs link --sn <documentSN> [--auto-login] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{
|
||||
flag: "--type <seal-result|hose-document>",
|
||||
description: "Link type: 'seal-result' (Seal AI audit result page, default) or 'hose-document' (Hose original form)"
|
||||
},
|
||||
{
|
||||
flag: "--auto-login",
|
||||
description: "Generate auto-login ticketed link (for seal-result type, valid for --expire seconds)"
|
||||
},
|
||||
{
|
||||
flag: "--expire <seconds>",
|
||||
description: "Auto-login ticket expiration in seconds (default: 7200)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -674,16 +698,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
summary: "Diagnose auth session and platform connectivity",
|
||||
usage: ["seal-use auth diagnose [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "link",
|
||||
aliases: ["seal-link"],
|
||||
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
||||
usage: ["seal-use auth link [--note <note>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" }
|
||||
],
|
||||
description:
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核台,等价于快捷生成 delegation 委托访问链接。"
|
||||
},
|
||||
{
|
||||
name: "hose-link",
|
||||
summary: "【合思主站】生成免密登录/第三方协助入口链接",
|
||||
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
|
||||
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
|
||||
options: [
|
||||
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
|
||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。凭证独立生成,不读取亦不污染 CLI 内部会话。注意:此链接不可通过 'seal-use delegation list' 查询(后者仅管理 Seal 审核后台的委托令牌)。"
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "extract-keys",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import type { OutputOptions } from "./types.js";
|
||||
|
||||
const RULE_LIST_FULL_COUNT_LIMIT = 100;
|
||||
const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
|
||||
export const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"];
|
||||
export const RULE_SUMMARY_FIELDS = ["code", "status", "strictness", "scope", "updatedAt"];
|
||||
const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
export function formatConsoleOutput(values: unknown[]): string {
|
||||
|
||||
@@ -23,7 +23,12 @@ describe("CLI read-only classification", () => {
|
||||
const ACTIONS_WITHOUT_REGISTRY_ENTRY = new Set(["approval-runs search"]);
|
||||
|
||||
test("every allow-listed command exists in the help registry", () => {
|
||||
const byArea = new Map(HELP_REGISTRY.map((area) => [area.area, area.commands.map((c) => c.name)]));
|
||||
const byArea = new Map(
|
||||
HELP_REGISTRY.map((area) => [
|
||||
area.area,
|
||||
area.commands.flatMap((c) => [c.name, ...(c.aliases ?? [])])
|
||||
])
|
||||
);
|
||||
|
||||
for (const { area, action } of listReadOnlyCommands()) {
|
||||
if (ACTIONS_WITHOUT_REGISTRY_ENTRY.has(`${area} ${action}`)) continue;
|
||||
|
||||
@@ -46,6 +46,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"document-summary",
|
||||
"attachments",
|
||||
"result",
|
||||
"link",
|
||||
"url"
|
||||
],
|
||||
simulation: [
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
getAllAgentHostsStatus,
|
||||
getAllLinkableHostsStatus,
|
||||
getAntigravitySkillsStatus,
|
||||
getHostSkillsStatus,
|
||||
KNOWN_LINKABLE_HOSTS,
|
||||
syncAllAgentHosts,
|
||||
syncAntigravitySkillsConfig,
|
||||
syncHostSkills
|
||||
} from "./index.js";
|
||||
|
||||
describe("antigravity skills config sync", () => {
|
||||
test("creates skills.json when it does not exist", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "agy-config-"));
|
||||
const configFile = join(tmp, "skills.json");
|
||||
const targetDir = "/custom/test/path/.agents/skills";
|
||||
|
||||
try {
|
||||
const res = syncAntigravitySkillsConfig({ configFile, targetSkillsDir: targetDir });
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.action).toBe("created");
|
||||
expect(res.targetDir).toBe(targetDir);
|
||||
|
||||
const status = getAntigravitySkillsStatus({ configFile, targetSkillsDir: targetDir });
|
||||
expect(status.configured).toBe(true);
|
||||
|
||||
const content = JSON.parse(readFileSync(configFile, "utf8"));
|
||||
expect(content.entries).toEqual([{ path: targetDir }]);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("does nothing when target directory is already present", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "agy-config-"));
|
||||
const configFile = join(tmp, "skills.json");
|
||||
const targetDir = "/custom/test/path/.agents/skills";
|
||||
|
||||
try {
|
||||
const initial = {
|
||||
entries: [
|
||||
{ path: "/other/skill/dir" },
|
||||
{ path: targetDir }
|
||||
]
|
||||
};
|
||||
writeFileSync(configFile, JSON.stringify(initial, null, 2));
|
||||
|
||||
const res = syncAntigravitySkillsConfig({ configFile, targetSkillsDir: targetDir });
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.action).toBe("already_present");
|
||||
|
||||
const content = JSON.parse(readFileSync(configFile, "utf8"));
|
||||
expect(content.entries.length).toBe(2);
|
||||
expect(content.entries[1].path).toBe(targetDir);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepends target directory to first position when absent", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "agy-config-"));
|
||||
const configFile = join(tmp, "skills.json");
|
||||
const targetDir = "/custom/test/path/.agents/skills";
|
||||
|
||||
try {
|
||||
const initial = {
|
||||
entries: [
|
||||
{ path: "/existing/first/dir" },
|
||||
{ path: "/existing/second/dir" }
|
||||
]
|
||||
};
|
||||
writeFileSync(configFile, JSON.stringify(initial, null, 2));
|
||||
|
||||
const res = syncAntigravitySkillsConfig({ configFile, targetSkillsDir: targetDir });
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.action).toBe("prepended");
|
||||
|
||||
const content = JSON.parse(readFileSync(configFile, "utf8"));
|
||||
expect(content.entries.length).toBe(3);
|
||||
expect(content.entries[0].path).toBe(targetDir);
|
||||
expect(content.entries[1].path).toBe("/existing/first/dir");
|
||||
expect(content.entries[2].path).toBe("/existing/second/dir");
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("updates legacy tilde path to absolute target directory", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "agy-config-"));
|
||||
const configFile = join(tmp, "skills.json");
|
||||
const targetDir = "/custom/test/path/.agents/skills";
|
||||
|
||||
try {
|
||||
const initial = {
|
||||
entries: [
|
||||
{ path: "~/.agents/skills" },
|
||||
{ path: "/other/dir" }
|
||||
]
|
||||
};
|
||||
writeFileSync(configFile, JSON.stringify(initial, null, 2));
|
||||
|
||||
const res = syncAntigravitySkillsConfig({ configFile, targetSkillsDir: targetDir });
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.action).toBe("updated_tilde");
|
||||
|
||||
const content = JSON.parse(readFileSync(configFile, "utf8"));
|
||||
expect(content.entries.length).toBe(2);
|
||||
expect(content.entries[0].path).toBe(targetDir);
|
||||
expect(content.entries[1].path).toBe("/other/dir");
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("symlink-based host skill bridge", () => {
|
||||
const host = KNOWN_LINKABLE_HOSTS.find((h) => h.id === "workbuddy")!;
|
||||
|
||||
test("skips host cleanly if host root directory does not exist", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "host-test-"));
|
||||
try {
|
||||
const res = syncHostSkills(host, { baseHomeDir: tmp });
|
||||
expect(res.detected).toBe(false);
|
||||
expect(res.configured).toBe(false);
|
||||
expect(res.mode).toBe("skipped_not_detected");
|
||||
|
||||
const status = getHostSkillsStatus(host, { baseHomeDir: tmp });
|
||||
expect(status.detected).toBe(false);
|
||||
expect(status.mode).toBe("not_detected");
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("detects parent directory symlink (~/<host>/skills -> ~/.agents/skills) and does not mutate", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "host-parent-"));
|
||||
try {
|
||||
const agentsSkillsDir = join(tmp, ".agents", "skills");
|
||||
const sourceSkill = join(agentsSkillsDir, "seal-use");
|
||||
mkdirSync(sourceSkill, { recursive: true });
|
||||
|
||||
const hostRoot = join(tmp, host.rootDirName);
|
||||
mkdirSync(hostRoot, { recursive: true });
|
||||
const hostSkills = join(hostRoot, "skills");
|
||||
|
||||
symlinkSync(agentsSkillsDir, hostSkills, "dir");
|
||||
|
||||
const res = syncHostSkills(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(res.detected).toBe(true);
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.mode).toBe("parent_symlinked");
|
||||
|
||||
const status = getHostSkillsStatus(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(status.configured).toBe(true);
|
||||
expect(status.mode).toBe("parent_symlinked");
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("creates child symlink when host skills is an independent directory", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "host-child-"));
|
||||
try {
|
||||
const sourceSkill = join(tmp, ".agents", "skills", "seal-use");
|
||||
mkdirSync(sourceSkill, { recursive: true });
|
||||
writeFileSync(join(sourceSkill, "SKILL.md"), "# Seal Skill");
|
||||
|
||||
const hostRoot = join(tmp, host.rootDirName);
|
||||
mkdirSync(join(hostRoot, "skills"), { recursive: true });
|
||||
|
||||
const res = syncHostSkills(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(res.detected).toBe(true);
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.mode).toBe("linked");
|
||||
|
||||
const linkPath = join(hostRoot, "skills", "seal-use");
|
||||
expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
|
||||
expect(realpathSync(linkPath)).toBe(realpathSync(sourceSkill));
|
||||
|
||||
// Running sync again should be idempotent
|
||||
const resAgain = syncHostSkills(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(resAgain.mode).toBe("already_linked");
|
||||
|
||||
const status = getHostSkillsStatus(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(status.configured).toBe(true);
|
||||
expect(status.mode).toBe("single_symlinked");
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("heals broken dead symlinks by unlinking and recreating", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "host-broken-"));
|
||||
try {
|
||||
const sourceSkill = join(tmp, ".agents", "skills", "seal-use");
|
||||
mkdirSync(sourceSkill, { recursive: true });
|
||||
|
||||
const hostRoot = join(tmp, host.rootDirName);
|
||||
const hostSkills = join(hostRoot, "skills");
|
||||
mkdirSync(hostSkills, { recursive: true });
|
||||
|
||||
// Create broken link
|
||||
const targetLink = join(hostSkills, "seal-use");
|
||||
symlinkSync(join(tmp, "non-existent-old-target"), targetLink, "dir");
|
||||
|
||||
const res = syncHostSkills(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(res.detected).toBe(true);
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.mode).toBe("linked");
|
||||
expect(realpathSync(targetLink)).toBe(realpathSync(sourceSkill));
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("safely replaces legacy real directory with symlink to prevent version drift", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "host-realdir-"));
|
||||
try {
|
||||
const sourceSkill = join(tmp, ".agents", "skills", "seal-use");
|
||||
mkdirSync(sourceSkill, { recursive: true });
|
||||
|
||||
const hostRoot = join(tmp, host.rootDirName);
|
||||
const targetDir = join(hostRoot, "skills", "seal-use");
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
writeFileSync(join(targetDir, "SKILL.md"), "# Old Stale Skill");
|
||||
|
||||
const res = syncHostSkills(host, {
|
||||
baseHomeDir: tmp,
|
||||
sourceSkillDir: sourceSkill
|
||||
});
|
||||
expect(res.detected).toBe(true);
|
||||
expect(res.configured).toBe(true);
|
||||
expect(res.mode).toBe("replaced_real_dir");
|
||||
|
||||
expect(lstatSync(targetDir).isSymbolicLink()).toBe(true);
|
||||
expect(realpathSync(targetDir)).toBe(realpathSync(sourceSkill));
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("syncAllAgentHosts aggregates Antigravity and all known hosts", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "all-hosts-"));
|
||||
try {
|
||||
const result = syncAllAgentHosts({
|
||||
baseHomeDir: tmp,
|
||||
antigravityConfigFile: join(tmp, "gemini-skills.json")
|
||||
});
|
||||
expect(result.antigravity.configured).toBe(true);
|
||||
expect(result.hosts.length).toBe(KNOWN_LINKABLE_HOSTS.length);
|
||||
expect(result.hosts.every((h) => h.mode === "skipped_not_detected")).toBe(true);
|
||||
|
||||
const status = getAllAgentHostsStatus({
|
||||
baseHomeDir: tmp,
|
||||
antigravityConfigFile: join(tmp, "gemini-skills.json")
|
||||
});
|
||||
expect(status.antigravity.configured).toBe(true);
|
||||
expect(status.hosts.length).toBe(KNOWN_LINKABLE_HOSTS.length);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { AntigravitySkillsStatus, AntigravitySkillsSyncResult } from "./types.js";
|
||||
|
||||
export function getGlobalAgentsSkillsDir(): string {
|
||||
return join(homedir(), ".agents", "skills");
|
||||
}
|
||||
|
||||
export function getAntigravitySkillsConfigFile(): string {
|
||||
return join(homedir(), ".gemini", "config", "skills.json");
|
||||
}
|
||||
|
||||
export function isAntigravityDetected(): boolean {
|
||||
const home = homedir();
|
||||
return (
|
||||
existsSync(join(home, ".gemini", "antigravity")) ||
|
||||
existsSync(join(home, ".gemini", "antigravity-cli")) ||
|
||||
existsSync(join(home, ".local", "bin", "agy"))
|
||||
);
|
||||
}
|
||||
|
||||
export function syncAntigravitySkillsConfig(options?: {
|
||||
configFile?: string;
|
||||
targetSkillsDir?: string;
|
||||
}): AntigravitySkillsSyncResult {
|
||||
const targetDir = options?.targetSkillsDir ?? getGlobalAgentsSkillsDir();
|
||||
const configPath = options?.configFile ?? getAntigravitySkillsConfigFile();
|
||||
const detected = isAntigravityDetected();
|
||||
|
||||
if (!existsSync(configPath)) {
|
||||
mkdirSync(dirname(configPath), { recursive: true });
|
||||
const initialConfig = {
|
||||
entries: [{ path: targetDir }]
|
||||
};
|
||||
writeFileSync(configPath, JSON.stringify(initialConfig, null, 2) + "\n", "utf8");
|
||||
return {
|
||||
detected,
|
||||
configured: true,
|
||||
configPath,
|
||||
targetDir,
|
||||
action: "created"
|
||||
};
|
||||
}
|
||||
|
||||
let parsed: { entries?: Array<{ path?: string; [key: string]: unknown }>; [key: string]: unknown } = {};
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(configPath, "utf8"));
|
||||
} catch {
|
||||
parsed = { entries: [] };
|
||||
}
|
||||
|
||||
if (!Array.isArray(parsed.entries)) {
|
||||
parsed.entries = [];
|
||||
}
|
||||
|
||||
const exactIndex = parsed.entries.findIndex(
|
||||
(entry) => entry && typeof entry.path === "string" && entry.path === targetDir
|
||||
);
|
||||
if (exactIndex !== -1) {
|
||||
return {
|
||||
detected,
|
||||
configured: true,
|
||||
configPath,
|
||||
targetDir,
|
||||
action: "already_present"
|
||||
};
|
||||
}
|
||||
|
||||
const tildeIndex = parsed.entries.findIndex(
|
||||
(entry) =>
|
||||
entry &&
|
||||
typeof entry.path === "string" &&
|
||||
(entry.path === "~/.agents/skills" || entry.path === "~/.agents/skills/")
|
||||
);
|
||||
if (tildeIndex !== -1) {
|
||||
parsed.entries[tildeIndex] = { ...parsed.entries[tildeIndex], path: targetDir };
|
||||
writeFileSync(configPath, JSON.stringify(parsed, null, 2) + "\n", "utf8");
|
||||
return {
|
||||
detected,
|
||||
configured: true,
|
||||
configPath,
|
||||
targetDir,
|
||||
action: "updated_tilde"
|
||||
};
|
||||
}
|
||||
|
||||
parsed.entries.unshift({ path: targetDir });
|
||||
writeFileSync(configPath, JSON.stringify(parsed, null, 2) + "\n", "utf8");
|
||||
return {
|
||||
detected,
|
||||
configured: true,
|
||||
configPath,
|
||||
targetDir,
|
||||
action: "prepended"
|
||||
};
|
||||
}
|
||||
|
||||
export function getAntigravitySkillsStatus(options?: {
|
||||
configFile?: string;
|
||||
targetSkillsDir?: string;
|
||||
}): AntigravitySkillsStatus {
|
||||
const targetDir = options?.targetSkillsDir ?? getGlobalAgentsSkillsDir();
|
||||
const configPath = options?.configFile ?? getAntigravitySkillsConfigFile();
|
||||
const detected = isAntigravityDetected();
|
||||
let configured = false;
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(configPath, "utf8"));
|
||||
if (Array.isArray(parsed?.entries)) {
|
||||
configured = parsed.entries.some(
|
||||
(e: { path?: string }) => e?.path === targetDir
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
detected,
|
||||
configured,
|
||||
configPath,
|
||||
targetDir
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
export * from "./types.js";
|
||||
export * from "./antigravity.js";
|
||||
export * from "./symlink-hosts.js";
|
||||
|
||||
import {
|
||||
getAntigravitySkillsStatus,
|
||||
syncAntigravitySkillsConfig
|
||||
} from "./antigravity.js";
|
||||
import {
|
||||
getAllLinkableHostsStatus,
|
||||
syncAllLinkableHosts
|
||||
} from "./symlink-hosts.js";
|
||||
import type { AllAgentHostsStatus, AllAgentHostsSyncResult } from "./types.js";
|
||||
|
||||
export function syncAllAgentHosts(options?: {
|
||||
baseHomeDir?: string;
|
||||
sourceSkillDir?: string;
|
||||
antigravityConfigFile?: string;
|
||||
}): AllAgentHostsSyncResult {
|
||||
const antigravity = syncAntigravitySkillsConfig({
|
||||
configFile: options?.antigravityConfigFile,
|
||||
targetSkillsDir: options?.sourceSkillDir
|
||||
? undefined
|
||||
: undefined
|
||||
});
|
||||
const hosts = syncAllLinkableHosts(options);
|
||||
|
||||
return {
|
||||
antigravity,
|
||||
hosts
|
||||
};
|
||||
}
|
||||
|
||||
export function getAllAgentHostsStatus(options?: {
|
||||
baseHomeDir?: string;
|
||||
sourceSkillDir?: string;
|
||||
antigravityConfigFile?: string;
|
||||
}): AllAgentHostsStatus {
|
||||
const antigravity = getAntigravitySkillsStatus({
|
||||
configFile: options?.antigravityConfigFile
|
||||
});
|
||||
const hosts = getAllLinkableHostsStatus(options);
|
||||
|
||||
return {
|
||||
antigravity,
|
||||
hosts
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
unlinkSync
|
||||
} from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type {
|
||||
HostSkillsStatus,
|
||||
HostSkillsSyncResult,
|
||||
LinkableHostDefinition
|
||||
} from "./types.js";
|
||||
|
||||
export const KNOWN_LINKABLE_HOSTS: LinkableHostDefinition[] = [
|
||||
{ id: "workbuddy", name: "WorkBuddy", rootDirName: ".workbuddy" },
|
||||
{ id: "claude", name: "Claude", rootDirName: ".claude" },
|
||||
{ id: "qoder", name: "Qoder", rootDirName: ".qoder" }
|
||||
];
|
||||
|
||||
export function syncHostSkills(
|
||||
host: LinkableHostDefinition,
|
||||
options?: { baseHomeDir?: string; sourceSkillDir?: string }
|
||||
): HostSkillsSyncResult {
|
||||
const home = options?.baseHomeDir ?? homedir();
|
||||
const hostRootDir = join(home, host.rootDirName);
|
||||
const sourceSkill = options?.sourceSkillDir ?? join(home, ".agents", "skills", "seal-use");
|
||||
const agentsSkillsDir = dirname(sourceSkill);
|
||||
const hostSkillsDir = join(hostRootDir, "skills");
|
||||
const targetSkillLink = join(hostSkillsDir, "seal-use");
|
||||
|
||||
// Rule 1: No dotfile pollution. Skip if host root directory doesn't exist.
|
||||
if (!existsSync(hostRootDir)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: false,
|
||||
configured: false,
|
||||
mode: "skipped_not_detected"
|
||||
};
|
||||
}
|
||||
|
||||
// Rule 2: Check parent directory symlink (~/<host>/skills -> ~/.agents/skills)
|
||||
if (existsSync(hostSkillsDir) && existsSync(agentsSkillsDir)) {
|
||||
try {
|
||||
if (realpathSync(hostSkillsDir) === realpathSync(agentsSkillsDir)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "parent_symlinked",
|
||||
targetPath: hostSkillsDir
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure ~/<host>/skills directory exists
|
||||
mkdirSync(hostSkillsDir, { recursive: true });
|
||||
|
||||
// Rule 3: Inspect child entry ~/<host>/skills/seal-use (dead symlink, real dir, etc.)
|
||||
let stat: ReturnType<typeof lstatSync> | undefined;
|
||||
try {
|
||||
stat = lstatSync(targetSkillLink);
|
||||
} catch {
|
||||
stat = undefined;
|
||||
}
|
||||
|
||||
let replacedRealDir = false;
|
||||
|
||||
if (stat) {
|
||||
if (stat.isSymbolicLink()) {
|
||||
try {
|
||||
if (realpathSync(targetSkillLink) === realpathSync(sourceSkill)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "already_linked",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Dead symlink: target disappeared or broken
|
||||
}
|
||||
try {
|
||||
unlinkSync(targetSkillLink);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
} else if (stat.isDirectory()) {
|
||||
// Rule 4: Existing real directory: replace with symlink to prevent version drift
|
||||
rmSync(targetSkillLink, { recursive: true, force: true });
|
||||
replacedRealDir = true;
|
||||
} else {
|
||||
// Stray file or other artifact
|
||||
unlinkSync(targetSkillLink);
|
||||
}
|
||||
}
|
||||
|
||||
// Rule 5: Create symlink with Windows junction fallback for non-admin privileges
|
||||
const symlinkType = process.platform === "win32" ? "junction" : "dir";
|
||||
try {
|
||||
symlinkSync(sourceSkill, targetSkillLink, symlinkType);
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: replacedRealDir ? "replaced_real_dir" : "linked",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
} catch {
|
||||
try {
|
||||
cpSync(sourceSkill, targetSkillLink, { recursive: true });
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "fallback_copied",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
} catch (cpErr: any) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: false,
|
||||
mode: "error",
|
||||
targetPath: targetSkillLink,
|
||||
error: cpErr?.message || String(cpErr)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getHostSkillsStatus(
|
||||
host: LinkableHostDefinition,
|
||||
options?: { baseHomeDir?: string; sourceSkillDir?: string }
|
||||
): HostSkillsStatus {
|
||||
const home = options?.baseHomeDir ?? homedir();
|
||||
const hostRootDir = join(home, host.rootDirName);
|
||||
const sourceSkill = options?.sourceSkillDir ?? join(home, ".agents", "skills", "seal-use");
|
||||
const agentsSkillsDir = dirname(sourceSkill);
|
||||
const hostSkillsDir = join(hostRootDir, "skills");
|
||||
const targetSkillLink = join(hostSkillsDir, "seal-use");
|
||||
|
||||
if (!existsSync(hostRootDir)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: false,
|
||||
configured: false,
|
||||
mode: "not_detected"
|
||||
};
|
||||
}
|
||||
|
||||
if (existsSync(hostSkillsDir) && existsSync(agentsSkillsDir)) {
|
||||
try {
|
||||
if (realpathSync(hostSkillsDir) === realpathSync(agentsSkillsDir)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "parent_symlinked",
|
||||
targetPath: hostSkillsDir
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
let stat: ReturnType<typeof lstatSync> | undefined;
|
||||
try {
|
||||
stat = lstatSync(targetSkillLink);
|
||||
} catch {
|
||||
stat = undefined;
|
||||
}
|
||||
|
||||
if (stat) {
|
||||
if (stat.isSymbolicLink()) {
|
||||
try {
|
||||
if (realpathSync(targetSkillLink) === realpathSync(sourceSkill)) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "single_symlinked",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// dead symlink
|
||||
}
|
||||
} else if (stat.isDirectory()) {
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: true,
|
||||
mode: "real_directory",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: host.id,
|
||||
name: host.name,
|
||||
detected: true,
|
||||
configured: false,
|
||||
mode: "not_configured",
|
||||
targetPath: targetSkillLink
|
||||
};
|
||||
}
|
||||
|
||||
export function syncAllLinkableHosts(options?: {
|
||||
baseHomeDir?: string;
|
||||
sourceSkillDir?: string;
|
||||
}): HostSkillsSyncResult[] {
|
||||
return KNOWN_LINKABLE_HOSTS.map((host) => syncHostSkills(host, options));
|
||||
}
|
||||
|
||||
export function getAllLinkableHostsStatus(options?: {
|
||||
baseHomeDir?: string;
|
||||
sourceSkillDir?: string;
|
||||
}): HostSkillsStatus[] {
|
||||
return KNOWN_LINKABLE_HOSTS.map((host) => getHostSkillsStatus(host, options));
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
export type AntigravitySkillsSyncResult = {
|
||||
detected: boolean;
|
||||
configured: boolean;
|
||||
configPath: string;
|
||||
targetDir: string;
|
||||
action: "created" | "prepended" | "already_present" | "updated_tilde";
|
||||
};
|
||||
|
||||
export type AntigravitySkillsStatus = {
|
||||
detected: boolean;
|
||||
configured: boolean;
|
||||
configPath: string;
|
||||
targetDir: string;
|
||||
};
|
||||
|
||||
export type LinkableHostId = "workbuddy" | "claude" | "qoder";
|
||||
|
||||
export type LinkableHostDefinition = {
|
||||
id: LinkableHostId;
|
||||
name: string;
|
||||
rootDirName: string;
|
||||
};
|
||||
|
||||
export type HostSkillsSyncResult = {
|
||||
id: LinkableHostId;
|
||||
name: string;
|
||||
detected: boolean;
|
||||
configured: boolean;
|
||||
mode:
|
||||
| "skipped_not_detected"
|
||||
| "parent_symlinked"
|
||||
| "linked"
|
||||
| "already_linked"
|
||||
| "replaced_real_dir"
|
||||
| "fallback_copied"
|
||||
| "error";
|
||||
targetPath?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type HostSkillsStatus = {
|
||||
id: LinkableHostId;
|
||||
name: string;
|
||||
detected: boolean;
|
||||
configured: boolean;
|
||||
mode: "not_detected" | "parent_symlinked" | "single_symlinked" | "real_directory" | "not_configured";
|
||||
targetPath?: string;
|
||||
};
|
||||
|
||||
export type AllAgentHostsSyncResult = {
|
||||
antigravity: AntigravitySkillsSyncResult;
|
||||
hosts: HostSkillsSyncResult[];
|
||||
};
|
||||
|
||||
export type AllAgentHostsStatus = {
|
||||
antigravity: AntigravitySkillsStatus;
|
||||
hosts: HostSkillsStatus[];
|
||||
};
|
||||
@@ -299,6 +299,24 @@ export function diagnoseSystem(): DoctorDiagnosis {
|
||||
: `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}`
|
||||
});
|
||||
|
||||
// Check 6: Rule Linter configuration
|
||||
const lintConfig = globalConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 };
|
||||
if (lintConfig.enabled) {
|
||||
checks.push({
|
||||
id: "rule_linter",
|
||||
title: "规则质量校验器",
|
||||
status: "ok",
|
||||
message: `已开启 (校验器: ${lintConfig.activeLinter}, 最低门槛分: ${lintConfig.minScore})`
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "rule_linter",
|
||||
title: "规则质量校验器",
|
||||
status: "ok",
|
||||
message: `未开启 (默认关闭,可运行 seal-use config lint enable 开启)`
|
||||
});
|
||||
}
|
||||
|
||||
const hasWarning = checks.some((c) => c.status === "warn" || c.status === "error");
|
||||
|
||||
const engine = typeof (globalThis as any).Bun !== "undefined"
|
||||
@@ -388,6 +406,10 @@ export function formatDoctorDashboard(diagnosis: DoctorDiagnosis): string {
|
||||
lines.push("─────────────────────────────────────────────────────────────");
|
||||
lines.push("👉 查阅内嵌白皮书与目录规范: seal-use doctor guide");
|
||||
lines.push("👉 检索企业: seal-use corps search <keyword>");
|
||||
const linterCheck = diagnosis.checks.find((c) => c.id === "rule_linter");
|
||||
if (linterCheck && linterCheck.message.includes("未开启")) {
|
||||
lines.push("👉 开启规则自动质量校验: seal-use config lint enable");
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -141,8 +141,8 @@ export const EMBEDDED_DOMAIN_CAPABILITIES: DomainCapabilitySpec[] = [
|
||||
},
|
||||
{
|
||||
domain: "approval-runs (审核大盘)",
|
||||
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、免登 SSO 深度链接",
|
||||
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs url"]
|
||||
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、单据直达链接与免登",
|
||||
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs link"]
|
||||
},
|
||||
{
|
||||
domain: "rules (规则治理)",
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface TenantDoctorDiagnosis {
|
||||
sourceType: string;
|
||||
boundCorpId?: string;
|
||||
boundCorpRole?: "prodParent" | "testTarget";
|
||||
boundCorpRoleDescription?: string;
|
||||
};
|
||||
summary: {
|
||||
totalChecks: number;
|
||||
@@ -58,6 +59,11 @@ export async function diagnoseTenantContract(
|
||||
const environment = corp.environment === "test" ? "test" : "production";
|
||||
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
|
||||
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
|
||||
const boundCorpRoleDescription = boundCorpId
|
||||
? environment === "test"
|
||||
? "已绑定生产母企业 (上游配置与样本源)"
|
||||
: "已绑定测试靶场 (下游隔离演练环境)"
|
||||
: undefined;
|
||||
|
||||
// 1. Auth & Admin Probe
|
||||
let userDetail: any = null;
|
||||
@@ -78,6 +84,8 @@ export async function diagnoseTenantContract(
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: true,
|
||||
permissionLevel: "超级管理员(具备完整操作权限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
tenantSlug: tenantDetail?.tenantSlug,
|
||||
permissions: userDetail.permissions
|
||||
}
|
||||
@@ -92,6 +100,8 @@ export async function diagnoseTenantContract(
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: false,
|
||||
permissionLevel: "普通用户(部分管理配置受限)",
|
||||
tenantName: tenantDetail?.name,
|
||||
permissions: userDetail.permissions
|
||||
},
|
||||
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
|
||||
@@ -301,7 +311,7 @@ export async function diagnoseTenantContract(
|
||||
name: "测试环境配对契约",
|
||||
status: "pass",
|
||||
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
|
||||
details: { environment, boundCorpId, boundCorpRole }
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
@@ -320,7 +330,7 @@ export async function diagnoseTenantContract(
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "pass",
|
||||
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
|
||||
details: { environment, boundCorpId, boundCorpRole }
|
||||
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
@@ -356,7 +366,8 @@ export async function diagnoseTenantContract(
|
||||
environment,
|
||||
sourceType: corp.source?.type ?? "native",
|
||||
boundCorpId,
|
||||
boundCorpRole
|
||||
boundCorpRole,
|
||||
boundCorpRoleDescription
|
||||
},
|
||||
summary: {
|
||||
totalChecks: checks.length,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
@@ -44,10 +44,6 @@ describe("embedded-skill", () => {
|
||||
});
|
||||
|
||||
describe("embedded-skill version contract", () => {
|
||||
// A version-tagged document that nothing asserts on drifts silently: `seal-use update` shipped
|
||||
// the previous release's skill for several versions, because "the file was written" looked like
|
||||
// success from every angle. Keeping the skill and the package in step is a failing test now
|
||||
// rather than a discovery.
|
||||
test("the skill's version matches the package version", () => {
|
||||
expect(EMBEDDED_SKILL_VERSION).toBe(packageJson.version);
|
||||
});
|
||||
|
||||
@@ -104,3 +104,6 @@ export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: strin
|
||||
|
||||
return { synced: false };
|
||||
}
|
||||
|
||||
// Re-export agent host skill bridging capabilities
|
||||
export * from "./agent-hosts/index.js";
|
||||
@@ -65,6 +65,21 @@ describe("approval-runs-export helpers", () => {
|
||||
});
|
||||
expect(custom).toBe("/tmp/custom-export.xlsx");
|
||||
|
||||
expect(() =>
|
||||
resolveOutputFilePath({
|
||||
outputFile: "/tmp/custom-export.csv",
|
||||
corpName: "TestCorp",
|
||||
recordCount: 10
|
||||
})
|
||||
).toThrow("本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx");
|
||||
|
||||
const noExtPath = resolveOutputFilePath({
|
||||
outputFile: "/tmp/custom-export",
|
||||
corpName: "TestCorp",
|
||||
recordCount: 10
|
||||
});
|
||||
expect(noExtPath).toBe("/tmp/custom-export.xlsx");
|
||||
|
||||
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
|
||||
const dl = resolveOutputFilePath({
|
||||
toDownloads: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { existsSync, mkdirSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { dirname, extname, resolve } from "node:path";
|
||||
import ExcelJS from "exceljs";
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
@@ -33,6 +33,7 @@ export interface ApprovalRunsExportOptions {
|
||||
taskMode?: string;
|
||||
sourceSystem?: string;
|
||||
sns?: string[];
|
||||
includeSimulation?: boolean;
|
||||
exportTime?: Date;
|
||||
}
|
||||
|
||||
@@ -294,7 +295,16 @@ export function resolveOutputFilePath(options: {
|
||||
exportTime?: Date;
|
||||
}): string {
|
||||
if (options.outputFile) {
|
||||
const p = resolve(options.outputFile);
|
||||
let p = resolve(options.outputFile);
|
||||
const ext = extname(p).toLowerCase();
|
||||
if (ext && ext !== ".xlsx") {
|
||||
throw new Error(
|
||||
`导出路径错误: 本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx(当前指定为 "${ext}")。请使用 .xlsx 后缀,例如: ${p.slice(0, -ext.length)}.xlsx`
|
||||
);
|
||||
}
|
||||
if (!ext) {
|
||||
p = `${p}.xlsx`;
|
||||
}
|
||||
const dir = dirname(p);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
@@ -429,7 +439,11 @@ export async function exportApprovalRunsToExcel(
|
||||
});
|
||||
const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn);
|
||||
for (const r of matched) {
|
||||
if (r.taskMode === "simulation") {
|
||||
const allowSimulation =
|
||||
options.taskMode === "simulation" ||
|
||||
options.includeSimulation === true ||
|
||||
corp.environment === "test";
|
||||
if (!allowSimulation && r.taskMode === "simulation") {
|
||||
excludedSimulationCount++;
|
||||
continue;
|
||||
}
|
||||
@@ -495,8 +509,12 @@ export async function exportApprovalRunsToExcel(
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤测试任务(仅保留真实审批任务)
|
||||
if (r.taskMode === "simulation") {
|
||||
// 过滤测试任务(默认仅保留真实审批任务;测试环境或显式指定时放行)
|
||||
const allowSimulation =
|
||||
options.taskMode === "simulation" ||
|
||||
options.includeSimulation === true ||
|
||||
corp.environment === "test";
|
||||
if (!allowSimulation && r.taskMode === "simulation") {
|
||||
excludedSimulationCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface RegressionTestOptions {
|
||||
timeoutMs?: number;
|
||||
snPrefix?: string;
|
||||
failOnFlips?: boolean;
|
||||
webhookSelector?: string;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
@@ -191,7 +192,7 @@ export async function runRegressionTest(
|
||||
}
|
||||
|
||||
// 4. Resolve Target Webhook Channel in Test Corp
|
||||
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp);
|
||||
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp, options.webhookSelector);
|
||||
|
||||
// 5. Execute Batch Replay & HTTPS Run Polling
|
||||
const records: RegressionSampleRecord[] = [];
|
||||
|
||||
@@ -194,7 +194,7 @@ describe("sealTools", () => {
|
||||
expect(result.rules).toEqual([
|
||||
{
|
||||
id: "rule-1",
|
||||
code: 29,
|
||||
code: "#0029",
|
||||
status: "active",
|
||||
strictness: "MUST_FOLLOW",
|
||||
scope: "travel"
|
||||
@@ -645,10 +645,9 @@ describe("sealTools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("approval run url returns Hose enterprise and document links by recordId", async () => {
|
||||
test("approval run url returns Seal result and Hose document links by recordId", 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(
|
||||
@@ -656,50 +655,74 @@ describe("sealTools", () => {
|
||||
{ recordId: "run-1" },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
url?: string;
|
||||
sealResultUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
hoseDomain?: string;
|
||||
documentUrl?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
hoseEnterpriseUrl?: string;
|
||||
};
|
||||
|
||||
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",
|
||||
type: "seal_result",
|
||||
mode: "direct",
|
||||
hoseDomain: "https://app.ekuaibao.com",
|
||||
documentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
||||
hoseDocumentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
||||
recordId: "run-1",
|
||||
sourceDocumentSN: "B26001965"
|
||||
});
|
||||
expect(result.enterpriseAssistUrl).toBeUndefined();
|
||||
expect(result.enterpriseUrl).toBeUndefined();
|
||||
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url returns enterprise assist link without a document lookup", async () => {
|
||||
test("approval run url supports type=hose-document", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", type: "hose-document" },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
url?: string;
|
||||
sealResultUrl?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("hose_document");
|
||||
expect(result.mode).toBe("direct");
|
||||
expect(result.url).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
||||
});
|
||||
|
||||
test("approval run url throws error without a document lookup", 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 requests: string[] = [];
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(requests),
|
||||
{},
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
documentUrl?: string;
|
||||
};
|
||||
|
||||
await expect(
|
||||
handler(
|
||||
fakeApprovalRunsClient(requests),
|
||||
{},
|
||||
fakeHoseContext()
|
||||
)
|
||||
).rejects.toThrow("recordId, sourceDocumentSN, or sourceDocumentId is required");
|
||||
expect(requests).toEqual([]);
|
||||
expect(result).toMatchObject({
|
||||
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token"
|
||||
});
|
||||
expect(result.documentUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url can resolve by sourceDocumentSN", async () => {
|
||||
@@ -713,16 +736,17 @@ describe("sealTools", () => {
|
||||
fakeApprovalRunsClient(requests),
|
||||
{ sourceDocumentSN: "B26001965" },
|
||||
fakeHoseContext()
|
||||
) as { documentUrl?: string; url?: string; type?: string };
|
||||
) as { documentUrl?: string; url?: string; type?: string; mode?: 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.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("direct");
|
||||
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 () => {
|
||||
test("approval run url returns auto_login link with identity, expiration, and warning when autoLogin=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");
|
||||
@@ -730,18 +754,20 @@ describe("sealTools", () => {
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = (await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", sso: true, expiresIn: 3600 },
|
||||
{ recordId: "run-1", autoLogin: true, expiresIn: 3600 },
|
||||
fakeHoseContext()
|
||||
)) as {
|
||||
url?: string;
|
||||
ssoUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
expiresIn?: number;
|
||||
warning?: string;
|
||||
identity?: { staffId?: string };
|
||||
};
|
||||
|
||||
expect(result.type).toBe("sso_link");
|
||||
expect(result.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("auto_login");
|
||||
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");
|
||||
@@ -749,6 +775,31 @@ describe("sealTools", () => {
|
||||
expect(result.identity?.staffId).toBe("staff-a");
|
||||
});
|
||||
|
||||
test("approval run url supports legacy hoseSso=true with explicit hose attribute naming", 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", hoseSso: true },
|
||||
fakeHoseContext()
|
||||
)) as {
|
||||
type?: string;
|
||||
mode?: string;
|
||||
url?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
hoseEnterpriseUrl?: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("auto_login");
|
||||
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
||||
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -760,7 +811,7 @@ describe("sealTools", () => {
|
||||
{ recordId: "run-1", sso: true },
|
||||
fakeContext()
|
||||
)
|
||||
).rejects.toThrow("SSO direct links currently support Hose-integrated enterprises");
|
||||
).rejects.toThrow("direct links currently support Hose-integrated enterprises");
|
||||
});
|
||||
|
||||
test("approval run summary filters by local date and returns compact aggregates", async () => {
|
||||
|
||||
+60
-31
@@ -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, ensureHoseCloseApiToken, getHoseEnterpriseUrl, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../core/config/manager.js";
|
||||
@@ -834,7 +834,7 @@ export const sealTools = [
|
||||
await api.deleteApprovalRule(client, rule.id);
|
||||
}
|
||||
|
||||
const created: Array<{ id: string; description: string; code?: number }> = [];
|
||||
const created: Array<{ id: string; description: string; code?: string | number }> = [];
|
||||
for (const rule of plan.created) {
|
||||
const newRule = await api.createApprovalRule(client, {
|
||||
description: rule.description,
|
||||
@@ -1739,13 +1739,16 @@ export const sealTools = [
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_url_get",
|
||||
description: "获取审批单的 Web 控制台直达链接或合思企业协助链接,支持纯深度链接与带安全警告的免密 SSO 链接",
|
||||
description: "获取审批单的 Web 链接(支持 seal-result 审核页与 hose-document 原单据页,支持 --auto-login 免密直达)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional().describe("Seal approval run record ID"),
|
||||
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
|
||||
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
|
||||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (SSO link)"),
|
||||
expiresIn: z.number().optional().describe("SSO 免密凭证有效秒数,默认 7200 (2小时)")
|
||||
type: z.string().optional().describe("链接类型:'seal-result' (Seal AI 审核页,默认) 或 'hose-document' (合思原单据页)"),
|
||||
autoLogin: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接"),
|
||||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (兼容别名)"),
|
||||
hoseSso: z.boolean().optional().describe("通过合思 OEM 换票生成直达该单据审核详情的免密直达链接 (兼容别名)"),
|
||||
expiresIn: z.number().optional().describe("免密凭证有效秒数,默认 7200 (2小时)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
@@ -1753,32 +1756,43 @@ export const sealTools = [
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
type?: string;
|
||||
autoLogin?: boolean;
|
||||
sso?: boolean;
|
||||
hoseSso?: boolean;
|
||||
expiresIn?: number;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
|
||||
const record = hasDocumentLookup ? await resolveApprovalRunForUrl(client, params) : undefined;
|
||||
if (!hasDocumentLookup) {
|
||||
throw new Error("recordId, sourceDocumentSN, or sourceDocumentId is required to generate approval run link");
|
||||
}
|
||||
const record = await resolveApprovalRunForUrl(client, params);
|
||||
const source = context.corp.source;
|
||||
const enterpriseAssistUrl = source.type === "hose" ? await getHoseEnterpriseUrl(context.corp) : undefined;
|
||||
const documentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
|
||||
const sealBaseUrl = resolveSealBaseUrl(context.corp);
|
||||
const sealResultUrl = record?.id ? `${sealBaseUrl}/approval-result/${record.id}` : undefined;
|
||||
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
|
||||
|
||||
const rawType = (params.type ?? "seal-result").toLowerCase().replace(/_/g, "-");
|
||||
const isHoseDoc = rawType === "hose-document" || rawType === "source-document" || rawType === "hose";
|
||||
const linkType = isHoseDoc ? "hose_document" : "seal_result";
|
||||
|
||||
const useAutoLogin = Boolean(params.autoLogin ?? params.hoseSso ?? params.sso);
|
||||
const expiresIn = params.expiresIn ?? 7200;
|
||||
|
||||
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 (useAutoLogin) {
|
||||
if (isHoseDoc) {
|
||||
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit link (type: seal-result)");
|
||||
}
|
||||
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.`
|
||||
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1810,7 +1824,7 @@ export const sealTools = [
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
|
||||
console.error(
|
||||
`⚠️ 安全警示 (SSO 强化免密链接):\n` +
|
||||
`⚠️ 安全警示 (免密直达链接):\n` +
|
||||
`• 身份主体:${userName}${roleLabel}\n` +
|
||||
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
|
||||
@@ -1818,25 +1832,28 @@ export const sealTools = [
|
||||
);
|
||||
}
|
||||
|
||||
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
|
||||
const activeMode = useAutoLogin ? "auto_login" : "direct";
|
||||
|
||||
return {
|
||||
url: params.sso ? ssoUrl : sealResultUrl,
|
||||
url: activeUrl,
|
||||
type: linkType,
|
||||
mode: activeMode,
|
||||
sealResultUrl,
|
||||
hoseDocumentUrl,
|
||||
// Legacy compatibility fields
|
||||
documentUrl: hoseDocumentUrl,
|
||||
ssoUrl,
|
||||
type: params.sso ? "sso_link" : "deep_link",
|
||||
expiresIn: params.sso ? expiresIn : undefined,
|
||||
expiresIn: useAutoLogin ? expiresIn : undefined,
|
||||
identity,
|
||||
warning,
|
||||
enterpriseAssistUrl,
|
||||
enterpriseUrl: enterpriseAssistUrl,
|
||||
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
|
||||
documentUrl,
|
||||
recordId: record?.id,
|
||||
sourceDocumentSN: record?.sourceDocumentSN,
|
||||
sourceDocumentId: record?.sourceDocumentId,
|
||||
sourceSystem: record?.sourceSystem,
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
sourceSystem: record.sourceSystem,
|
||||
missing: {
|
||||
enterpriseAssistUrl: enterpriseAssistUrl ? undefined : "Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",
|
||||
documentUrl: hasDocumentLookup && !documentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
hoseDocumentUrl: !hoseDocumentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1999,9 +2016,9 @@ export const sealTools = [
|
||||
next: {
|
||||
status: `seal-use simulation status ${result.batchId}`,
|
||||
wait: `seal-use simulation wait ${result.batchId}`,
|
||||
getBatch: "seal-home simulation get <batchId>",
|
||||
getRecords: "seal-home simulation batch-records <batchId>",
|
||||
listBatches: "seal-home simulation list"
|
||||
getBatch: `seal-use simulation get ${result.batchId}`,
|
||||
getRecords: `seal-use simulation batch-records ${result.batchId}`,
|
||||
listBatches: "seal-use simulation list"
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -2892,7 +2909,19 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
|
||||
const output: Partial<ApprovalRule> = {};
|
||||
for (const field of fields) {
|
||||
if (rule[field] !== undefined) {
|
||||
output[field] = rule[field] as never;
|
||||
if (field === "code") {
|
||||
const val = rule.code;
|
||||
if (typeof val === "number") {
|
||||
output.code = formatRuleCode(val) as never;
|
||||
} else if (typeof val === "string") {
|
||||
const digits = val.match(/\d+/)?.[0];
|
||||
output.code = (digits ? formatRuleCode(Number(digits)) : val) as never;
|
||||
} else {
|
||||
output.code = val as never;
|
||||
}
|
||||
} else {
|
||||
output[field] = rule[field] as never;
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
|
||||
@@ -74,7 +74,7 @@ export const SealSessionDataSchema = z.object({
|
||||
export const ApprovalRuleSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string().optional(),
|
||||
code: z.number().optional(),
|
||||
code: z.union([z.number(), z.string()]).optional(),
|
||||
description: z.string(),
|
||||
scope: z.string(),
|
||||
strictness: z.string(),
|
||||
|
||||
@@ -360,4 +360,120 @@ describe("webhook-replay domain", () => {
|
||||
expect(savedIntegration.name).toBe("(Seal测-回放通道)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("executeApprovalRunsReplay sn matching", () => {
|
||||
test("matches exact sourceDocumentSN even if search returns multiple candidates", async () => {
|
||||
const sourceCorp = {
|
||||
id: "source-corp",
|
||||
name: "源企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://source.sealai.cc" },
|
||||
source: { type: "seal", sealUrl: "https://source.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const targetCorp = {
|
||||
id: "target-corp",
|
||||
name: "目标测试企业",
|
||||
environment: "test",
|
||||
seal: { url: "https://target.sealai.cc" },
|
||||
source: { type: "seal", sealUrl: "https://target.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const mockSourceClient: any = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/v1/approvals")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run-001",
|
||||
sourceDocumentSN: "SN12345-OTHER",
|
||||
sourceDocumentId: "DOC-OTHER",
|
||||
status: "APPROVED"
|
||||
},
|
||||
{
|
||||
id: "run-002",
|
||||
sourceDocumentSN: "SN12345",
|
||||
sourceDocumentId: "DOC-EXACT",
|
||||
status: "TERMINATED"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ data: {} }) };
|
||||
}
|
||||
};
|
||||
|
||||
const mockTargetClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: { integrations: [mockWebhookIntegration] } })
|
||||
})
|
||||
};
|
||||
|
||||
const result = await executeApprovalRunsReplay({
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
query: { sn: "SN12345" },
|
||||
dryRun: true
|
||||
});
|
||||
|
||||
expect(result.totalCount).toBe(1);
|
||||
expect(result.records[0]?.originalRecord.id).toBe("run-002");
|
||||
expect(result.records[0]?.originalRecord.sourceDocumentSN).toBe("SN12345");
|
||||
});
|
||||
|
||||
test("throws clear error when sn is not found in search results", async () => {
|
||||
const sourceCorp = {
|
||||
id: "source-corp",
|
||||
name: "源企业",
|
||||
environment: "production",
|
||||
source: { type: "seal", sealUrl: "https://source.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const targetCorp = {
|
||||
id: "target-corp",
|
||||
name: "目标测试企业",
|
||||
environment: "test",
|
||||
source: { type: "seal", sealUrl: "https://target.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const mockSourceClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run-001",
|
||||
sourceDocumentSN: "SN99999",
|
||||
status: "APPROVED"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
const mockTargetClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: { integrations: [mockWebhookIntegration] } })
|
||||
})
|
||||
};
|
||||
|
||||
expect(
|
||||
executeApprovalRunsReplay({
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
query: { sn: "SN-NOT-FOUND" },
|
||||
dryRun: true
|
||||
})
|
||||
).rejects.toThrow("在企业「源企业」中未找到单据编号为「SN-NOT-FOUND」的审批记录。");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -423,18 +423,40 @@ export async function executeApprovalRunsReplay(
|
||||
runs.push(await api.getApprovalRun(sourceClient, id));
|
||||
}
|
||||
} else if (query.sn) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: query.sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
search: query.sn,
|
||||
sourceDocumentSN: query.sn,
|
||||
limit: 20
|
||||
});
|
||||
const matched = search.records.find(
|
||||
(r) =>
|
||||
r.sourceDocumentSN === query.sn ||
|
||||
r.sourceDocumentId === query.sn ||
|
||||
(r.document as any)?.sourceDocumentSN === query.sn ||
|
||||
(r.document as any)?.sn === query.sn
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${query.sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
runs.push(matched);
|
||||
} else if (query.sns && query.sns.length > 0) {
|
||||
for (const sn of query.sns) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
search: sn,
|
||||
sourceDocumentSN: sn,
|
||||
limit: 20
|
||||
});
|
||||
const matched = search.records.find(
|
||||
(r) =>
|
||||
r.sourceDocumentSN === sn ||
|
||||
r.sourceDocumentId === sn ||
|
||||
(r.document as any)?.sourceDocumentSN === sn ||
|
||||
(r.document as any)?.sn === sn
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
runs.push(matched);
|
||||
}
|
||||
} else if (query.limit !== undefined) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
|
||||
Reference in new issue
Block a user