Compare commits

..
10 Commits
Author SHA1 Message Date
yunyingk d26c4358c5 Merge pull request #241 from yunyingk/codex/release-v0.11.9
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.9: Automated release bump
2026-10-16 11:43:54 +08:00
gitea d127e80c1b Release v0.11.9: Automated release bump 2026-10-16 11:42:28 +08:00
yunyingk e52654fec7 Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add hose-ebot command for Hose outbound discovery and approval callback
2026-10-16 11:22:48 +08:00
gitea bbff9338a0 Add hose-ebot command for Hose outbound discovery and approval callback 2026-10-16 11:19:50 +08:00
yunyingk 21e1a9d27a Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add tool installation to skill and Git mirror sync to WSL worker
2026-10-16 09:54:15 +08:00
gitea e9eb8095fc Add tool installation to skill and Git mirror sync to WSL worker 2026-10-16 09:52:24 +08:00
yunyingk 2749d765b3 Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add auth hose-openapi-token command for Hose enterprises
2026-10-15 17:07:52 +08:00
gitea 6e4a8cb088 Add auth hose-openapi-token command for Hose enterprises 2026-10-15 17:05:55 +08:00
yunyingk 55ead68a06 Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
Refine pkg/report README and clean external docstrings
2026-10-15 17:01:00 +08:00
gitea 41d5b175a6 Refine pkg/report README and clean external docstrings 2026-10-15 16:58:49 +08:00
33 changed files with 1692 additions and 141 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.8",
"version": "0.11.9",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+2 -2
View File
@@ -76,7 +76,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
4. Release branch creation (`codex/release-vX.Y.Z`), commit, and push to `origin`.
5. GitHub PR creation, CI monitoring, and merge.
6. Main branch fast-forward (`git pull --ff-only origin main`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`), with synchronous best-effort mirror to `home` (Gitea).
8. Clean removal of temporary release branch.
2. **Manual Protected-Branch Release & Workspace Isolation (Reference)**:
@@ -104,7 +104,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
git push origin refs/tags/vX.Y.Z
```
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
- **Gitea Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea (`wsl-infra/systemd/`).
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`wsl-infra/systemd/`).
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
## Security & Configuration Tips
+13
View File
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.9] - 2026-10-16
### Added
- Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
- Add hose-ebot command for Hose outbound discovery and approval callback
- Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
- Add tool installation to skill and Git mirror sync to WSL worker
- Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
- Add auth hose-openapi-token command for Hose enterprises
- Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
- Refine pkg/report README and clean external docstrings
## [0.11.8] - 2026-10-15
### Added
+1 -1
View File
@@ -260,7 +260,7 @@ For test tenants that need a clean slate before importing another rule set, use
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. For a raw Hose OpenAPI access token from persisted `appKey/appSecurity`, run `seal-use auth hose-openapi-token --corp <corpId>`; stdout returns `token`, `expiresAt`, and `cached`, and `--force` skips the local cache to mint a new token.
## Approval Run To Langfuse Bridge
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.8",
"version": "0.11.9",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+42 -98
View File
@@ -1,120 +1,64 @@
# AI 审核报告(Markdown)独立编制与校验套件
# AI 审核报告编制与校验规范
本套件是面向**外部交付、客户协作与第三方审核团队**的独立版 AI 审核报告验证工具包。
本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。
---
## 一、核心定位与特点
## 一、标准模板与章节规范
1. **零环境依赖**:基于纯 Python 标准库编写(Python 3.8+),无需安装 `seal-use`,无需 Node.js / Bun,跨平台(macOS / Linux / Windows)开箱即用。
2. **纯粹面向 Markdown**:专注于 Markdown 报告文档本身的格式纯净度、结构严密性与数学总账守恒;**不强求本地 Excel 伴生台账**,**无需手动填写任何技术跳转链接**。
3. **核心章节硬匹配,自定义章节完全放行**:核心论证章节按大标题名称硬匹配认领;中间任意插入的部门专项分析、整改排期等章节,校验器一律视为纯叙述业务章节,不施加任何教条规则,直接绿色放行!
报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。
### 1. 核心必填章节(按大标题名称识别)
核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块:
| 核心大标题名称 | 说明与要求 |
| :--- | :--- |
| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 |
| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 |
| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 |
| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 |
| **`支撑数据与交付材料`** | 分模板统计表与说明。 |
### 2. 中间自定义插入章节
* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。
* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。
---
## 二、目录结构
## 二、核心格式规范
```text
pkg/report/
├── README.md # 本使用指南与规范手册
├── validate.py # 独立离线校验脚本(纯标准库)
├── example-report.md # 100% 格式合规的标准示例月报
└── assets/ # 示例配图资产
└── 图1-准确率对比.svg
```
为保证文档严谨自洽,报告编写需满足以下格式守则:
1. **纯净 Markdown 语法**:
* 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中;
* 严禁残留草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等);
* 代码块(```)必须成对闭合。
2. **表格结构**:
* 表格每行单元格数量必须严格与表头对齐;
* 表头文字保持纯文本,禁止包含加粗符号(`**`);
* 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。
3. **数学总账守恒**:
* 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$);
* 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致;
* LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。
---
## 三、快速上手
## 三、校验脚本使用说明
### 1. 快速校验一份 Markdown 报告
同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。
### 运行校验
```bash
# 进入本目录
cd pkg/report
# 执行校验
python3 validate.py example-report.md
```
**校验通过输出示例**:
```text
✅ 报告文件: /path/to/example-report.md
📊 识别表格: 14 个 | 配图资产: 1 个
🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。
```
### 2. 输出机器可读的 JSON 结构(方便接入 CI/CD 或自动化流水线)
* **校验通过**:终端输出绿色通过提示,退出码为 `0`;
* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。
支持输出 JSON 格式供程序化调用:
```bash
python3 validate.py example-report.md --json
```
---
## 四、报告大纲与编写原则
一份合格的 AI 审核商业月度报告,遵循**“骨架刚性、血肉自适应”**的设计理念:
### 1. 核心必选骨架(通过大标题名称硬匹配)
无论章节编号是第几章,系统只要匹配到大标题名称,就会认领对应的业务校验:
| 核心大标题名称 | 核心作用与定位 | 必须遵守的业务守恒 |
| :--- | :--- | :--- |
| **开篇「报告信息」表** | 抬头身份证明 | 必含 5 字段:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 核心业绩表态 | 包含样本总量、AI/人工准确率结论、LaTeX 准确率公式(`\frac{A}{B} = C\%`)及对比图。 |
| **`AI 失准分析`** | 坦白 AI 误判与偏差 | 包含失准构成总览表、TOP 1~N 典型案例表格与针对性调优解决方案。 |
| **`AI 发现的潜在风险`** | 力证风控拦截价值 | 包含潜在风险总览表、TOP 1~N 凭证缺失、比价缺失、超期等真实拦截案例。 |
| **`综合效益`** | 总结人效与风控收益 | 时效、准确度、风险拦截笔数宏观总结表(纯内部对账时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧深度定性 | 分类统计表(线上规则未覆盖 vs 模型偏差)与口头管控标准线上化管理建议。 |
| **`支撑数据与交付材料`** | 分模板细分数据 | 分模板准确率与自动化率汇总表,说明底层流水交付物。 |
### 2. 中间随意插入的自定义章节(完全自由放行)
如果针对具体企业的特定管理需要,想在报告中间插入业务专属章节(例如在第 1 章后插入 `## 2. 营销大区差旅合规专项穿透`):
* **系统处理方式**:大标题名称不在核心名单里的章节,校验器一律视为**纯叙述业务章节**;
* **自由度**:不限制表格列数、不限制行数、不强制要求数学守恒,写什么内容都直接放行!
* **唯一要求**:大章节使用 `##`,章节编号从 1 开始自然连续递增(1, 2, 3, 4, 5...),子小节使用 `###` 且不跳级。
### 3. 表格案例与链接约定
* 案例表格推荐使用纯净紧凑的 **2 列规范**(`| 单号 | 问题描述 |`);
* 编写 Markdown 时**无需手动查询或粘贴长串后台技术 URL**,专注于业务事实描述即可。
---
## 五、校验规则与错误代码速查表
`validate.py` 内部内置了以下质量红线校验门禁。如果报告校验未通过,终端会指出具体问题行号与代码:
| 错误代码 | 校验类别 | 规则说明与修复指南 |
| :--- | :--- | :--- |
| **`FM001`** | 格式纯净 | 严禁以 YAML Frontmatter(`---`)开头;元数据请写在正文开头的「报告信息」表中。 |
| **`MK001`** | 格式纯净 | 严禁残留模板草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等)。 |
| **`MD001`** | 格式规范 | 代码围栏(反引号 ```)必须成对闭合,不可出现单数个。 |
| **`TB001`** | 表格对齐 | 每行数据单元格按 `\|` 拆分后的列数,必须严格等于表头列数。 |
| **`TB002`** | 表格规范 | 表头文字必须保持纯文本,禁止包含 `**` 加粗符号。 |
| **`HD001`** | 标题层级 | 禁止跳级(如 `#` 一级标题直接跳到 `###` 三级标题)。 |
| **`HD002`** | 标题序号 | 二级大章节编号(`## \d+\.`)必须从 1 开始连续递增,不得跳号。 |
| **`INFO001`** | 头部元数据 | 开篇「报告信息」表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 |
| **`INFO002`** | 头部元数据 | 开篇「报告信息」表的 5 项元数据值均不能为空白。 |
| **`IMG001`** | 资产存活 | 文档中引用的本地相对路径图片(如 `.svg` / `.png`)在磁盘必须真实存在。 |
| **`NM001`** | 数学守恒 | 【失准分析】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM002`** | 数学守恒 | 【潜在风险】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM003`** | 数学守恒 | 分类总览表中声明的占比百分比与 `单数 / 合计` 计算误差不得超过 0.15%。 |
| **`NM004`** | 数学守恒 | 【分歧归因】分类表各原因单数相加必须等于分歧总数,且与正文叙述一致。 |
| **`NM005`** | 数学守恒 | LaTeX 公式 `\frac{A}{B} = C\%` 算术必须成立,且公式中的数字在正文中有数据来源。 |
---
## 六、常见问题解答 (FAQ)
**Q:编写报告时,出现失准或风险分类不是 3 种怎么办?**
A:完全自由!如果有 2 种就列 TOP 1~2,有 4 种就列 TOP 1~4,只要总览表中这几项的单数加起来等于合计行、百分比加起来等于 100% 即可通过校验。
**Q:案例表格必须放 3 行吗?**
A:不需要。可放 1 行典型单据,也可放 5 行全量单据,表格行数完全由业务深度决定。
**Q:为什么提示公式算术不成立(`NM005`)?**
A:请检查 LaTeX 公式中的分子除以分母计算出的百分比,与等号右边的数值是否一致(如 $221 / 240 = 92.0833\% \approx 92.08\%$,如果写成 95% 则会被拦截)。
+2 -3
View File
@@ -4,9 +4,8 @@ AI 审核报告(Markdown)独立校验器
Independent Markdown Validator for AI Audit Reports
特点:
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用
- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行
- 严格守护格式合规与数学总账守恒
用法:
+15 -2
View File
@@ -90,7 +90,11 @@ console.log("🔍 步骤 1/8: 执行发布前置条件核验...");
// Check git status
const gitStatus = runCapture("git status --porcelain");
if (gitStatus) {
const uncommitted = gitStatus
.split("\n")
.map((l) => l.trim())
.filter((l) => l && !l.endsWith("scripts/release.ts"));
if (uncommitted.length > 0) {
console.error("❌ 工作区存在未提交的修改,请先提交或暂存后再发布:\n");
console.error(gitStatus);
process.exit(1);
@@ -112,7 +116,7 @@ if (!remotes.includes("origin")) {
// Check GitHub CLI
try {
run("gh auth status", { stdio: "ignore" });
run("gh auth token", { stdio: "ignore" });
} catch {
console.error("❌ GitHub CLI (gh) 未登录或不可用。请先运行 'gh auth login'。");
process.exit(1);
@@ -203,6 +207,15 @@ try {
console.log(`📤 推送 Tag ${tag} 到 origin (GitHub,触发 Release 构建)...`);
run(`git push origin refs/tags/${tag}`);
try {
console.log(`📤 同步推送主干分支与 Tag ${tag} 到 home (Gitea)...`);
run("git push home main");
run(`git push home refs/tags/${tag}`);
console.log("✓ Gitea 镜像主干与 Tag 已同步!");
} catch (err) {
console.warn("⚠️ 同步 Gitea 镜像失败(非致命,将由 WSL 定时服务兜底):", err);
}
// 9. Cleanup
console.log("\n🧹 步骤 8/8: 清理临时发布分支...");
run(`git branch -d ${releaseBranch}`);
+36 -3
View File
@@ -1,15 +1,48 @@
---
name: seal-use
description: "v0.11.8: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.9: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.8
short-description: Seal tenant and Hose approval automation (v0.11.8)
version: 0.11.9
short-description: Seal tenant and Hose approval automation (v0.11.9)
---
# Seal Use
CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
## 工具就绪检测与安装 (Bootstrap & Installation)
在执行具体业务前,先通过 `command -v seal-use` 检查 CLI 是否已就绪。若命令未安装或需要升级:
### 1. 一键免环境安装(推荐)
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS Apple Silicon/Intel、Linux x64/arm64):
```bash
# 国内高速镜像(免代理推荐,秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# GitHub 直连
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
```
### 2. 下载预编译原生二进制
亦可从 Releases 页面直接下载对应平台可执行文件并放入 PATH:
- **Gitea Releases(国内高速)**:`https://git.ying-qing.cn/gitea/seal-use/releases`
- **GitHub Releases**:`https://github.com/yunyingk/seal-use/releases/latest`
### 3. 安装后初始化与激活
```bash
seal-use version # 校验安装版本与架构
seal-use skill install # 同步/安装 Agent Skill 到 ~/.agents/skills/seal-use(支持 Codex / Cursor / Antigravity)
seal-use mcp-config # 输出 MCP 配置 JSON 片段(供 Cursor / Claude Desktop 使用)
seal-use update # 在线自升级至最新版本
seal-use doctor # 运行环境与已接入租户健康诊断
```
### 4. 开发者源码覆盖(本地开发环境)
```bash
bun run dev:override # 编译本机二进制、打版本号并原子覆盖全局命令与本地 Skill
```
## 时间与输出
- 机器字段统一使用带 `+08:00` 北京时间偏移的 ISO 8601 秒级格式,不带毫秒,例如 `2026-09-28T11:51:09+08:00`。
+11
View File
@@ -118,6 +118,7 @@ seal-use auth link --from-link <url> [--note <note>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
@@ -156,6 +157,9 @@ seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]
seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]
seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
@@ -246,6 +250,13 @@ Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSec
- `seal-use corps hose-extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). The old `extract-keys`/`extract-key`/`extract-hose-keys` forms remain aliases. **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
- `seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). The old `keys` form remains an alias. Rejects non-Hose/native-Seal tenants with exit code 2.
- `seal-use auth hose-extract-keys <url>` and `seal-use auth hose-keys [--corp <corpId>]` are the explicit Hose auth-domain commands. The old `extract-keys`/`extract-key`/`extract-hose-keys` and `keys` forms remain aliases.
- `seal-use auth hose-openapi-token [--corp <corpId>] [--force]` exchanges the persisted Hose `appKey/appSecurity` for an OpenAPI `accessToken` and prints it as machine JSON (`token`, `expiresAt`, `cached`; aliases `openapi-token`, `hose-token`). A still-fresh cached token is reused by default (`cached: true`, with a stderr notice); `--force` mints a new one. Unlike `auth check`, the token is intentionally unredacted. Rejects non-Hose tenants with exit code 2; missing credentials exit 13.
Hose outbound discovery & EBot callback (first-level `hose-ebot` command; Hose-only):
- `seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal]` is the default entry: it searches the Hose outbound message log by document SN and returns records that each carry a unique `id` (`INVOKING`=出站触发, `CALLBACK`=回调), plus the `flowId`/`nodeId`/`messageId`/`rejectionNum` a callback needs. Read-only; any `signKey` inside records is masked unless `--reveal`.
- `seal-use hose-ebot messages [--type flow|message] [--reveal]` lists every outbound message config on the Hose side (`messageName`, `signKey`, `callbackUrl`, `enable`, …). `signKey` is the `config_id` embedded in the callback URL; masked unless `--reveal`. Read-only.
- `seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> …` runs the EBot approval callback (`POST /api/openapi/v1/approval`) and writes the result into the approval flow; success is `value.code=204`. Requires `--dry-run` (masked preview) or `--yes/--confirm` (otherwise exit 10). `--sign-key` is optional when the enterprise has exactly one Seal Hose integration. Upstream business codes map to exit codes: 401→11, 400→13, 412/500→1. Only EBot-node approvals are supported upstream.
Read-only discovery:
@@ -34,6 +34,8 @@ Read the JSON `stages` in order:
Do not expect tokens in the output; the command intentionally redacts or omits them.
When the caller needs the actual OpenAPI `accessToken` itself (for example to call Hose OpenAPI from their own script), use `seal-use auth hose-openapi-token --corp <corpId> [--force]`. It prints the unredacted token as JSON together with `expiresAt` and `cached` (`cached: true` means a still-fresh local token was reused; pass `--force` to mint a new one). Non-Hose enterprises are rejected with exit 2, and a Hose enterprise without persisted `appKey/appSecurity` exits 13.
## Get a Hose authorization link
When the user asks for a 合思/易快报授权链接、登录链接、入口链接, or says "来一个授权链接" for a Hose sourced enterprise, return the Hose provisional/CloseAPI URL from `getProvisionalAuth`'s `value.message`.
@@ -91,6 +91,31 @@ seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
### 出站发现与 EBot 回调(一级命令 `hose-ebot`)
`sync` 之后,出站消息的发现与回调审批走独立的一级命令 `seal-use hose-ebot`(Hose 专属,非合思租户拒绝,退出码 13):
```text
# 9. 按单号搜索出站/回调记录(默认入口;每条记录带唯一 id)
seal-use hose-ebot search <sn> --corp <corpId>
seal-use hose-ebot search <sn> --type invoking --corp <corpId> # 只看 出站触发
seal-use hose-ebot search <sn> --type callback --corp <corpId> # 只看 回调
# 10. 列出全部出站消息配置,发现 signKey(即回调地址中的 config_id)
seal-use hose-ebot messages --corp <corpId>
seal-use hose-ebot messages --reveal --type flow --corp <corpId> # 明文 signKey
# 11. 回调审批(写入审批流;先 --dry-run 预览,正式执行必须 --yes)
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --dry-run
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --yes
```
- `hose-ebot search` 返回记录的唯一 `id`,回调所需的 `flowId`/`nodeId` 直接来自记录的 `request` 字段;`--type invoking|callback` 区分出站触发与回调,`--limit` 控制条数(默认 20)。
- `hose-ebot messages --reveal` 输出的 `signKey` 就是 `hose-ebot callback --sign-key` 的入参;企业仅有一个 Seal 合思集成时可省略 `--sign-key` 自动解析。
- 回调成功返回 `value.code=204`;上游业务码映射退出码:401(signKey 错误)→11、400(参数错误)→13、412/500 →1。缺少 `--yes`/`--confirm` 且无 `--dry-run` 时退出码 10。accessToken 在回调前实时换取,不复用缓存;仅支持 EBot 节点的审批回调。
---
## 4. 关键配置参数定义
+156
View File
@@ -385,6 +385,162 @@ describe("auth links", () => {
});
});
describe("auth hose-openapi-token", () => {
function setupRoot(name: string) {
const root = mkdtempSync(join(tmpdir(), name));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
return { root, enterprises };
}
function writeHoseCorp(enterprises: string, sourceOverride: Record<string, unknown> = {}) {
writeFileSync(
join(enterprises, "hose-corp.json"),
JSON.stringify({
id: "hose-corp",
name: "合思测试企业",
environment: "production",
seal: { url: "https://hose-corp.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
corpId: "HOSE-CORP",
staffId: "HOSE-CORP:STAFF-1",
...sourceOverride
},
auth: { refreshTtl: 300 }
})
);
}
function mockGetAccessToken(counter: { count: number }, token = "fresh-openapi-token") {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
counter.count += 1;
return new Response(JSON.stringify({ value: { accessToken: token, expireTime: 7200 } }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
}
test("mints a fresh OpenAPI token from persisted keys and prints it as machine JSON", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-");
writeHoseCorp(enterprises);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(false);
expect(counter.count).toBe(1);
const parsed = JSON.parse(result.stdout);
expect(parsed).toMatchObject({
corpId: "HOSE-CORP",
corpName: "合思测试企业",
domain: "https://app.ekuaibao.com",
token: "fresh-openapi-token",
cached: false
});
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("reuses a fresh cached token by default and mints a new one with --force", async () => {
const { root, enterprises } = setupRoot("seal-use-auth-openapi-token-force-");
writeHoseCorp(enterprises);
writeFileSync(
join(root, "tokens.json"),
JSON.stringify({
"hose-corp": {
hose: {
openapi: { token: "cached-openapi-token", expiresAt: Date.now() + 3600_000 }
}
}
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const cachedResult = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(cachedResult.isError).toBe(false);
expect(counter.count).toBe(0);
const cachedParsed = JSON.parse(cachedResult.stdout);
expect(cachedParsed).toMatchObject({ token: "cached-openapi-token", cached: true });
expect(cachedResult.stderr).toContain("复用本地仍有效的 accessToken");
const forcedResult = await runCli(["auth", "openapi-token", "--corp", "hose-corp", "--force"]);
expect(forcedResult.isError).toBe(false);
expect(counter.count).toBe(1);
const forcedParsed = JSON.parse(forcedResult.stdout);
expect(forcedParsed).toMatchObject({ token: "fresh-openapi-token", cached: false });
});
test("rejects a native Seal enterprise with exit code 2", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-native-");
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生 Seal 企业",
environment: "production",
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://native.seal.test",
expiresIn: 3600,
corpId: "native-corp",
staffId: "native-staff"
},
auth: { refreshTtl: 300 }
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "native-seal"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("非合思");
expect(counter.count).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-nocreds-");
writeHoseCorp(enterprises, {
appKey: undefined,
appSecurity: undefined,
closeToken: "web-session-token",
expiresAt: "2099-01-01T00:00:00+08:00"
});
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(13);
expect(result.stderr).toContain("缺少合思凭证");
expect(counter.count).toBe(0);
});
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
+46 -1
View File
@@ -1,7 +1,14 @@
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
normalizeBaseUrl
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
@@ -147,6 +154,44 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
if (
action === "hose-openapi-token" ||
action === "openapi-token" ||
action === "hose-token"
) {
if (corp.source.type !== "hose") {
throw new CliError(
`【合思专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
"OpenAPI accessToken 签发能力专属于合思生态租户(使用持久化的 appKey/appSecurity 向合思 OpenAPI 换取 token),非合思渠道企业不支持此命令。",
2
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
);
}
const force =
booleanOption(args.options.force) === true ||
booleanOption(args.options.refresh) === true ||
booleanOption(args.options.f) === true;
const entry = await getHoseOpenapiToken(corp, { force });
if (entry.cached) {
console.error("ℹ️ [合思 OpenAPI] 复用本地仍有效的 accessToken 缓存,追加 --force 可强制签发全新 token。");
}
printJson({
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
domain: normalizeBaseUrl(corp.source.domain),
token: entry.token,
expiresAt: formatBeijingIso(entry.expiresAt),
cached: entry.cached
});
return;
}
if (action === "keys" || action === "hose-keys") {
const reveal =
booleanOption(args.options.reveal) === true ||
+580
View File
@@ -0,0 +1,580 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { KyInstance } from "ky";
import { CorpConfigSchema } from "../../core/config/types.js";
import { classifyCliError } from "../../core/errors.js";
import { parseArgs } from "../parser.js";
import { handleHoseEbotCommand } from "./hose-ebot.js";
const ORIGINAL_ENV = {
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const ORIGINAL_LOG = console.log;
const ORIGINAL_ERROR = console.error;
let tempDir: string | undefined;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-"));
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json");
});
afterEach(() => {
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
console.log = ORIGINAL_LOG;
console.error = ORIGINAL_ERROR;
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
tempDir = undefined;
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
const hoseCorp = CorpConfigSchema.parse({
id: "hose-ebot",
name: "合思 EBot 测试企业",
environment: "test",
seal: { url: "https://hose-ebot.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({
...hoseCorp,
id: "hose-ebot-nocreds",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const sealCorp = CorpConfigSchema.parse({
id: "seal-ebot",
name: "原生 Seal 企业",
environment: "test",
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
source: {
type: "seal",
sealUrl: "https://seal.test",
token: "mock-token",
staffId: "seal-staff",
corpId: "seal-corp"
}
});
const messageFixture = {
items: [
{
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true,
signKey: "Q4H15lpixMyE7secretvalue",
callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["backlog.processed"],
formFields: ["action", "flowId", "nodeId"]
},
{
id: "ID01Vj4VDa8CGH",
messageName: "完成回调",
messageType: "message",
enable: false,
signKey: "Q4H15lpixOtherSecret",
callbackUrl: "https://sealai.cc/api/hosecloud/complete",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["flow.completed"]
}
]
};
const logFixture = {
items: [
{
id: "log-1",
name: "出站调用",
type: "INVOKING",
state: "SUCCESS",
createTime: 1727764000000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
messageId: "MSG-1",
rejectionNum: 0
}
},
{
id: "log-2",
name: "审批回调",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1727764010000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
signKey: "Q4H15lpixMyE7secretvalue",
action: "accept",
comment: "AI 审核通过"
}
}
]
};
function mockFetch(responses: {
messages?: unknown;
logs?: unknown;
token?: unknown;
approval?: unknown;
}) {
const record: {
calls: number;
messageUrl?: string;
logUrl?: string;
logBody?: unknown;
tokenUrl?: string;
tokenBody?: unknown;
approvalUrl?: string;
approvalBody?: unknown;
} = { calls: 0 };
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
record.calls++;
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
let bodyText: string | undefined;
if (init?.body) {
bodyText = String(init.body);
} else if (input && typeof input === "object" && "clone" in input) {
bodyText = await (input as Request).clone().text().catch(() => undefined);
}
if (url.includes("/api/outbound/v1/message/messageLog")) {
record.logUrl = url;
record.logBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(JSON.stringify(responses.logs ?? logFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/outbound/v1/message")) {
record.messageUrl = url;
return new Response(JSON.stringify(responses.messages ?? messageFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) {
record.tokenUrl = url;
record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(
JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.includes("/api/openapi/v1/approval")) {
record.approvalUrl = url;
record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined;
const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } };
return new Response(JSON.stringify(resp), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 });
}) as typeof fetch;
return record;
}
function fakeClient(integrations: Array<Record<string, unknown>> = []) {
return {
get: async () => ({
json: async () => ({ integrations })
})
} as unknown as KyInstance;
}
async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) {
const lines: string[] = [];
console.log = (line: string) => lines.push(String(line));
console.error = () => {};
const args = parseArgs(argv);
await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args);
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
}
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
try {
await action();
} catch (error) {
return error;
}
throw new Error("expected action to throw, but it succeeded");
}
describe("hose-ebot messages", () => {
test("lists configured outbound messages with a masked signKey by default", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]);
expect(output.count).toBe(2);
expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1");
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages[0]).toMatchObject({
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true
});
// maskHoseSecurity keeps the first 8 and last 4 characters.
expect(messages[0]!.signKey).toBe("Q4H15lpi...alue");
expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue");
expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue");
expect(output.revealed).toBe(false);
});
test("filters by type and reveals the signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "messages", "--type", "flow", "--reveal"
]);
expect(output.count).toBe(1);
expect(output.revealed).toBe(true);
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages).toHaveLength(1);
expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue");
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"])
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
});
describe("hose-ebot search", () => {
test("requires an SN and lists records with their unique ids", async () => {
const usageError = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"])
);
expect(classifyCliError(usageError).exitCode).toBe(2);
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--limit", "5"
]);
expect(output.count).toBe(2);
expect(output.sn).toBe("SN123");
expect(output.type).toBe("all");
expect(record.logBody).toMatchObject({
limit: { start: 0, count: 5 },
filterBy: '(flowId.form.code==("SN123"))'
});
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
// Callback records embed signKey; masked unless --reveal.
expect((records[1]!.request as Record<string, unknown>).signKey).not.toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("filters to invoking or callback records with --type", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "callback"
]);
expect(output.type).toBe("callback");
expect(output.count).toBe(1);
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]!.type).toBe("CALLBACK");
// The client-side filter over-fetches first so the page stays full.
expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } });
// Also accepts uppercase --type CALLBACK
const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "CALLBACK"
]);
expect(outputUpper.count).toBe(1);
});
test("reveals the record signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--reveal"
]);
const records = output.records as Array<Record<string, unknown>>;
expect((records[1]!.request as Record<string, unknown>).signKey).toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("rejects an unknown verb with exit code 2", async () => {
const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"]));
expect(classifyCliError(error).exitCode).toBe(2);
expect(String((error as Error).message)).toContain("Unknown hose-ebot command");
});
});
describe("hose-ebot callback", () => {
const callbackArgv = (extra: string[] = []) => [
"hose-ebot", "callback",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "accept",
"--comment", "同意",
...extra
];
test("refuses to run without --yes/--confirm before any network call", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"]))
);
expect(classifyCliError(error).exitCode).toBe(10);
expect(record.calls).toBe(0);
expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback");
});
test("previews a masked payload with --dry-run without minting a token", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
...callbackArgv(["--sign-key", "sig-1", "--dry-run"])
]);
expect(output.preview).toBe(true);
expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval");
const payload = output.payload as Record<string, unknown>;
expect(payload).toMatchObject({
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
expect(payload.signKey).not.toBe("sig-1");
expect(record.calls).toBe(0);
});
test("mints a fresh accessToken and posts the callback on a confirmed run", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([
"--sign-key", "sig-1",
"--yes"
]));
expect(output).toMatchObject({
ok: true,
code: "204",
message: "EBot执行完成",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept"
});
expect(record.approvalUrl).toContain("/api/openapi/v1/approval");
expect(record.approvalUrl).toContain("accessToken=live-openapi-token");
expect(record.approvalBody).toMatchObject({
signKey: "sig-1",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
});
test("normalizes action aliases like agree/approve/reject", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "agree",
"--comment", "口语化同意",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "accept" });
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "reject",
"--comment", "口语化驳回",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "refuse" });
});
test("passes optional callback fields through to the wire payload with camelCase support", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "refuse",
"--comment", "驳回",
"--policy", "ALL",
"--addApproverIds", "staff-1,staff-2",
"--rejectTo", "NODE-0",
"--resubmitMethod", "TO_REJECTOR",
"--yes"
]);
expect(record.approvalBody).toMatchObject({
action: "refuse",
policy: "ALL",
addApproverIds: ["staff-1", "staff-2"],
rejectTo: "NODE-0",
resubmitMethod: "TO_REJECTOR"
});
});
test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => {
const record = mockFetch({});
const client = fakeClient([
{ type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" }
]);
await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"]));
expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" });
});
test("maps upstream business codes to exit codes and references hose-ebot messages", async () => {
mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } });
const error401 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error401).exitCode).toBe(11);
expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal");
mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } });
const error412 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error412).exitCode).toBe(1);
expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search");
mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } });
const error400 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error400).exitCode).toBe(13);
});
test("validates preAdd and aftAdd approver and policy requirements before network call", async () => {
const record = mockFetch({});
const preAddError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"])
)
);
expect(classifyCliError(preAddError).exitCode).toBe(13);
expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人");
expect(record.calls).toBe(0);
const aftAddPolicyError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--sign-key",
"sig-1",
"--yes"
])
)
);
expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13);
expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL");
expect(record.calls).toBe(0);
});
test("normalizes lowercase policy and kebab-case resubmit-method", async () => {
const record = mockFetch({
approval: { value: { code: "204", message: "success" } }
});
await callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--policy",
"all",
"--resubmit-method",
"from-start",
"--sign-key",
"sig-1",
"--yes"
])
);
expect(record.approvalBody).toMatchObject({
action: "aftAdd",
addApproverIds: ["user1", "user2"],
policy: "ALL",
resubmitMethod: "FROM_START"
});
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(String((error as Error).message)).toContain("缺少合思凭证");
expect(record.calls).toBe(0);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
const USAGE =
"Usage:\n" +
" seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
function normalizeEbotAction(raw: string | undefined): string | undefined {
if (!raw) return undefined;
const lower = raw.trim().toLowerCase();
if (lower === "accept" || lower === "agree" || lower === "approve") return "accept";
if (lower === "refuse" || lower === "reject") return "refuse";
if (lower === "preadd" || lower === "pre-add") return "preAdd";
if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd";
return raw;
}
function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined {
if (!raw) return undefined;
const upper = raw.trim().toUpperCase();
if (upper === "ALL" || upper === "ANY") return upper;
return raw as "ALL" | "ANY";
}
function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined {
if (!raw) return undefined;
const norm = raw.trim().toUpperCase().replace(/-/g, "_");
if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm;
return raw as "FROM_START" | "TO_REJECTOR";
}
/**
* First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop:
* search is the default entry (discover records by document SN), `messages`
* discovers outbound message configs and their signKey, and `callback` runs
* the approval callback.
*/
export async function handleHoseEbotCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) {
throw new CliError(USAGE, 2);
}
if (action === "search") {
const sn = maybeName ?? stringOption(args.options.sn);
if (!sn) {
throw new CliError(`Missing document SN.\n\n${USAGE}`, 2);
}
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundSearch",
client,
corp,
{
sn,
type: rawType,
limit: numberOption(args.options.limit),
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true
},
outputOptions(args.options)
);
return;
}
if (action === "messages") {
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundMessages",
client,
corp,
{
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true,
type: rawType
},
outputOptions(args.options)
);
return;
}
if (action === "callback") {
const addApproverIdsRaw =
stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds);
await runCapability(
"sealHoseApprovalCallback",
client,
corp,
{
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]),
nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]),
action: normalizeEbotAction(stringOption(args.options.action)),
comment: stringOption(args.options.comment),
policy: normalizeEbotPolicy(stringOption(args.options.policy)),
addApproverIds: addApproverIdsRaw
? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
: undefined,
rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo),
resubmitMethod: normalizeResubmitMethod(
stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod)
),
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
},
outputOptions(args.options)
);
return;
}
throw new CliError(
`Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`,
2
);
}
+61
View File
@@ -855,6 +855,56 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "hose-ebot",
title: "Hose EBot outbound discovery & callback (合思 EBot 出站发现与审批回调)",
description: "按单号搜索出站/回调记录、列出出站消息配置(signKey),并执行 EBot 审批回调。",
commands: [
{
name: "search",
summary: "【出站发现·默认入口】按单号搜索出站消息调用记录(只读)",
usage: ["seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <invoking|callback>", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" },
{ flag: "--limit <n>", description: "返回条数上限(默认 20,最大 100)" },
{ flag: "--reveal, -r", description: "明文展示记录中的 signKey(默认脱敏)" }
],
description:
"在合思 CloseAPI 出站消息日志中按单号 (SN) 搜索,返回带唯一 id 的记录列表(INVOKING 出站触发 / CALLBACK 回调),含 flowId/nodeId/messageId/rejectionNum 等回调上下文。"
},
{
name: "messages",
summary: "【出站配置】列出全部出站消息配置,发现 signKey 与回调地址(只读)",
usage: ["seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <flow|message>", description: "按类型过滤:flow=审批流 EBot 出站,message=完成回调/通知" },
{ flag: "--reveal, -r", description: "明文展示 signKey(默认脱敏为 8...4 形式)" }
],
description:
"经合思 CloseAPI 只读查询本企业全部出站消息配置(messageName、signKey、callbackUrl、enable 等)。signKey 即出站回调地址中的 config_id,可直接用于 'hose-ebot callback'。"
},
{
name: "callback",
summary: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签)",
usage: [
"seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]"
],
options: [
{ flag: "--comment <text>", description: "审批意见(必填)" },
{ flag: "--sign-key <key>", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" },
{ flag: "--action <accept|refuse|preAdd|aftAdd>", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" },
{ flag: "--policy <ALL|ANY>", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" },
{ flag: "--add-approver-ids <id,id>", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" },
{ flag: "--reject-to <nodeId>", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" },
{ flag: "--resubmit-method <FROM_START|TO_REJECTOR>", description: "驳回后重提方式;缺省按 EBot 节点配置" },
{ flag: "--dry-run", description: "仅预览回调请求(signKey 脱敏),不执行" },
{ flag: "--yes, --confirm", description: "正式执行必需;届时实时换取 accessToken 后回调" }
],
description:
"调用合思开放接口 POST /api/openapi/v1/approval,向审批流回写 EBot 节点审批结果,成功返回 value.code=204。仅支持 EBot 节点的审批;signKey 可通过 'seal-use hose-ebot messages --reveal' 发现。"
}
]
},
{
area: "preference",
title: "Audit preferences and thinking depth",
@@ -973,6 +1023,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
description:
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
},
{
name: "hose-openapi-token",
aliases: ["openapi-token", "hose-token"],
summary: "【合思】用持久化密钥签发合思 OpenAPI accessToken",
usage: ["seal-use auth hose-openapi-token [--corp <corpId>] [--force]"],
options: [
{ flag: "--force, --refresh, -f", description: "跳过本地缓存,强制向合思 OpenAPI 签发全新 token" }
],
description:
"专用于合思 (Hose) 来源企业。使用已持久化的 appKey/appSecurity 调用 /api/openapi/v1/auth/getAccessToken 换取 OpenAPI accessToken(约 1 小时有效),stdout 输出含 token、expiresAt 与 cached 字段(cached=true 表示复用了本地仍有效的缓存)。"
},
{
name: "hose-extract-keys",
aliases: ["extract-keys", "extract-key", "extract-hose-keys"],
+10 -10
View File
@@ -40,9 +40,9 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
@@ -60,12 +60,12 @@ export const VALUE_FLAGS = new Set([
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum",
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
"repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window",
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
@@ -86,11 +86,11 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"code", "comment", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
@@ -114,12 +114,12 @@ export const KNOWN_FLAGS = new Set([
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
+6
View File
@@ -60,6 +60,8 @@ describe("CLI read-only classification", () => {
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"],
["hose-ebot", "messages", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["langfuse", "check"],
@@ -91,6 +93,8 @@ describe("CLI read-only classification", () => {
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
// The EBot approval callback writes accept/refuse into the live approval flow.
["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"],
["webhook", "delete", "hook-1"],
["webhook", "replay"],
["users", "reset-password", "corp-a:u1"],
@@ -100,6 +104,8 @@ describe("CLI read-only classification", () => {
["mcp"],
["update"],
["auth", "keys"],
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
["auth", "hose-openapi-token"],
["analytics", "analyze", "record-1"],
["tool", "sealApprovalRuleCreate", "--json", "{}"],
["langfuse", "unknown-verb"],
+3
View File
@@ -64,6 +64,9 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"integrations"
],
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
// `hose-ebot callback` is deliberately absent: it mints an accessToken and writes an
// approval action into the live flow. Only the two discovery verbs read.
"hose-ebot": ["search", "messages"],
preference: ["get", "thinking-depth policies list"],
// `config mode`/`config lint` are omitted: classification is token-prefix based, so their
// read forms cannot be separated from the value-taking write forms. `config get` returns
+6
View File
@@ -39,6 +39,7 @@ export const KNOWN_AREAS = new Set([
"corps",
"corp",
"source",
"hose-ebot",
"auth",
"users",
"contacts",
@@ -416,6 +417,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "hose-ebot") {
await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
+59
View File
@@ -10,6 +10,7 @@ import {
exchangeHoseAssistLink,
fetchHoseStaffDetails,
getHoseEnterpriseUrl,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
getHoseSealSession,
normalizeBaseUrl,
@@ -402,4 +403,62 @@ describe("hose auth helpers", () => {
expect(getHoseProvisionalAuthLink(corp, -100)).rejects.toThrow("Invalid expire seconds");
expect(getHoseProvisionalAuthLink(corp, 0)).rejects.toThrow("Invalid expire seconds");
});
test("getHoseOpenapiToken serves a fresh cached token and mints a new one under force", async () => {
setupTokenStore({
"corp-test": {
hose: {
openapi: {
token: "cached-openapi-token",
expiresAt: Date.now() + 3600_000
}
}
}
});
const corp: CorpConfig = {
id: "corp-test",
name: "Corp Test",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff-1",
corpId: "CORP-TEST"
},
auth: { refreshTtl: 300 }
};
let mintCount = 0;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (new URL(urlStr).pathname === "/api/openapi/v1/auth/getAccessToken") {
mintCount += 1;
return new Response(JSON.stringify({ value: { accessToken: "minted-openapi-token" } }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const cached = await getHoseOpenapiToken(corp);
expect(cached.cached).toBe(true);
expect(cached.token).toBe("cached-openapi-token");
expect(mintCount).toBe(0);
const forced = await getHoseOpenapiToken(corp, { force: true });
expect(forced.cached).toBe(false);
expect(forced.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
expect(getHoseAuthCache("corp-test").openapi?.token).toBe("minted-openapi-token");
const reused = await getHoseOpenapiToken(corp);
expect(reused.cached).toBe(true);
expect(reused.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
});
});
+22 -9
View File
@@ -113,7 +113,10 @@ export type HoseProbeResult = {
expireTime?: number;
};
const openapiTokenRequests = new Map<string, Promise<string>>();
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */
export type HoseOpenapiTokenResult = TokenEntry & { cached: boolean };
const openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
export function normalizeBaseUrl(url: string): string {
@@ -298,17 +301,20 @@ async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry
};
}
export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
export async function getHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<HoseOpenapiTokenResult> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.openapi)) {
return cache.openapi.token;
if (!options?.force && isFresh(cache.openapi)) {
return { ...cache.openapi, cached: true };
}
const pending = openapiTokenRequests.get(corp.id);
if (pending) return pending;
if (pending) return { ...(await pending), cached: false };
const request = fetchHoseOpenapiToken(corp.source)
.then((openapi) => {
@@ -316,11 +322,18 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string>
...getHoseAuthCache(corp.id),
openapi
});
return openapi.token;
return openapi;
})
.finally(() => openapiTokenRequests.delete(corp.id));
openapiTokenRequests.set(corp.id, request);
return request;
return { ...(await request), cached: false };
}
export async function ensureHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<string> {
return (await getHoseOpenapiToken(corp, options)).token;
}
export async function fetchHoseCloseApiToken(
@@ -415,7 +428,7 @@ export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
export async function getHoseProvisionalAuthLink(
corp: CorpConfig,
expiresIn = 7200,
_options?: { force?: boolean }
options?: { force?: boolean }
): Promise<{
corpId: string;
staffId: string;
@@ -431,7 +444,7 @@ export async function getHoseProvisionalAuthLink(
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
}
const openapiToken = await ensureHoseOpenapiToken(corp);
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
if (!provisional.url) {
throw new Error("Hose provisional auth URL was not available");
+81 -5
View File
@@ -36,13 +36,88 @@ export interface HoseOutboundLogItem {
response?: unknown;
}
/**
* A configured outbound message on the Hose side (EBot push or completion
* callback). Only the fields seal-use surfaces are kept; Hose returns more.
*/
export interface HoseOutboundMessageConfig {
id: string;
messageName?: string;
messageType?: string;
enable?: boolean;
signKey?: string;
callbackUrl?: string;
corporationId?: string;
actionEvent?: string[];
formFields?: string[];
remark?: string;
createTime?: number;
updateTime?: number;
}
function parseOutboundMessage(item: unknown): HoseOutboundMessageConfig | undefined {
if (!item || typeof item !== "object" || Array.isArray(item)) return undefined;
const raw = item as Record<string, unknown>;
if (typeof raw.id !== "string" || !raw.id) return undefined;
const stringList = (value: unknown): string[] | undefined =>
Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string")
: undefined;
return {
id: raw.id,
messageName: typeof raw.messageName === "string" ? raw.messageName : undefined,
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
enable: typeof raw.enable === "boolean" ? raw.enable : undefined,
signKey: typeof raw.signKey === "string" ? raw.signKey : undefined,
callbackUrl: typeof raw.callbackUrl === "string" ? raw.callbackUrl : undefined,
corporationId: typeof raw.corporationId === "string" ? raw.corporationId : undefined,
actionEvent: stringList(raw.actionEvent),
formFields: stringList(raw.formFields),
remark: typeof raw.remark === "string" ? raw.remark : undefined,
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined
};
}
/**
* List every configured outbound message for the tenant via the read-only
* CloseAPI `GET api/outbound/v1/message`. Each row carries the `signKey` that
* the EBot callback URL embeds as `config_id`, which is how operators find
* which signature key belongs to which message.
*/
export async function fetchHoseOutboundMessages(
sourceCorp: CorpConfig
): Promise<HoseOutboundMessageConfig[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
`企业「${sourceCorp.name}」非合思(hose)租户,无法查询合思出站消息配置。`
);
}
const client = await createHoseCloseClient(sourceCorp);
const response = (await client
.get("api/outbound/v1/message", {
searchParams: { corpId: sourceCorp.source.corpId }
})
.json()) as { items?: unknown };
if (!Array.isArray(response.items)) {
throw new Error("合思出站消息接口未返回 items 列表,响应结构与预期不符");
}
return response.items
.map(parseOutboundMessage)
.filter((message): message is HoseOutboundMessageConfig => message !== undefined);
}
/**
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
*/
export async function searchOutboundMessageLogs(
client: KyInstance,
corpId: string,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
const response = (await client
.post("api/outbound/v1/message/messageLog", {
@@ -51,10 +126,10 @@ export async function searchOutboundMessageLogs(
corpId
},
json: {
limit: { start: 0, count: 20 },
limit: { start: 0, count: options?.limit ?? 20 },
orderBy: [{ value: "createTime", order: "DESC" }],
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
filterBy: `(flowId.form.code==("${sn}"))`
filterBy: `(flowId.form.code==("${sn.replace(/"/g, '\\"')}"))`
}
})
.json()) as { items?: HoseOutboundLogItem[] };
@@ -67,7 +142,8 @@ export async function searchOutboundMessageLogs(
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
@@ -76,5 +152,5 @@ export async function fetchHoseOutboundLogs(
}
const client = await createHoseCloseClient(sourceCorp);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn, options);
}
+123
View File
@@ -0,0 +1,123 @@
import { HTTPError } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { CliError, validationError } from "../../../core/errors.js";
import { createHoseOpenClient } from "./client.js";
/**
* EBot approval callback (`POST api/openapi/v1/approval`) — the OpenAPI call an
* external service makes after processing an outbound message, so the EBot node
* can advance (accept/refuse) or add approvers. Only EBot-node approvals are
* supported upstream; everything else comes back as business code 412.
*/
export const EBOT_APPROVAL_ACTIONS = ["accept", "refuse", "preAdd", "aftAdd"] as const;
export type EbotApprovalAction = (typeof EBOT_APPROVAL_ACTIONS)[number];
export const EBOT_RESUBMIT_METHODS = ["FROM_START", "TO_REJECTOR"] as const;
export type EbotApprovalCallbackParams = {
signKey: string;
flowId: string;
nodeId: string;
action: EbotApprovalAction;
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
};
export type EbotApprovalCallbackResult = {
code: string;
message: string;
};
export async function executeEbotApprovalCallback(
corp: CorpConfig,
params: EbotApprovalCallbackParams
): Promise<EbotApprovalCallbackResult> {
if (corp.source.type !== "hose") {
throw validationError(
`企业「${corp.name}」非合思(hose)租户,无法调用合思 OpenAPI 审批回调。`
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法换取 accessToken 执行审批回调。`
);
}
if ((params.action === "preAdd" || params.action === "aftAdd") && (!params.addApproverIds || params.addApproverIds.length === 0)) {
throw validationError(
`执行${params.action === "preAdd" ? "前加签 (preAdd)" : "后加签 (aftAdd)"}时,必须通过 --add-approver-ids 指定加签审批人 ID 列表。`
);
}
if (params.action === "aftAdd" && (params.addApproverIds?.length ?? 0) > 1 && !params.policy) {
throw validationError(
"后加签审批人超过 1 人时,必须指定会签方式 --policy ALL (会签) 或 --policy ANY (或签)。"
);
}
// The manual requires a token minted right before the callback: accessToken
// expires quickly and stale reuse is not worth the risk on a flow write.
const client = await createHoseOpenClient(corp, undefined, { force: true });
let response: unknown;
try {
response = await client.post("api/openapi/v1/approval", {
json: {
signKey: params.signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
}
}).json();
} catch (error) {
// HTTP 400 means our request body was rejected — an input problem, so the
// caller gets exit 13 with the upstream body; HTTP 401/403 fall through to
// the shared classifier (exit 11).
if (error instanceof HTTPError && error.response.status === 400) {
throw validationError(`合思审批回调参数被上游拒绝 (HTTP 400):${error.message}`);
}
throw error;
}
const rawObj = (response && typeof response === "object") ? (response as Record<string, unknown>) : {};
const valueObj = rawObj.value && typeof rawObj.value === "object" ? (rawObj.value as Record<string, unknown>) : rawObj;
const rawCode = valueObj.code ?? rawObj.code;
const code = rawCode !== undefined ? String(rawCode) : undefined;
const message = (typeof valueObj.message === "string" ? valueObj.message : (typeof rawObj.message === "string" ? rawObj.message : "")) || "";
if (code === "204") {
return { code, message };
}
if (code === "401") {
throw new CliError(
"合思审批回调失败:签名秘钥 signKey 错误 (401)。" +
"请核对出站消息配置中的 signKey(seal-use hose-ebot messages --reveal 可查看)。",
11
);
}
if (code === "400") {
throw validationError(`合思审批回调参数错误 (400):${message || "请求参数错误"}`);
}
if (code === "412") {
throw new CliError(
`合思审批回调失败:业务前置条件不满足 (412):${message || "当前节点不可审批或已被处理"}。\n` +
"👉 建议:运行 seal-use hose-ebot search <单号SN> 核对单据当前节点与出站记录。",
1
);
}
if (!code) {
throw new Error(`合思审批回调未返回业务码,响应与预期不符:${JSON.stringify(response)}`);
}
throw new Error(`合思审批回调失败 (${code}):${message || "未知错误"}`);
}
+3 -2
View File
@@ -38,13 +38,14 @@ export function createHoseOpenClientWithCredentials(
export async function createHoseOpenClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
customHeaders?: Record<string, string>,
options?: { force?: boolean }
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp);
const token = await ensureHoseOpenapiToken(corp, { force: options?.force });
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
+1
View File
@@ -1,3 +1,4 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./approval.js";
+217
View File
@@ -0,0 +1,217 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { maskHoseSecurity, normalizeBaseUrl } from "../../../core/auth/hose.js";
import { confirmationRequired, validationError } from "../../../core/errors.js";
import { fetchHoseOutboundLogs, fetchHoseOutboundMessages } from "../../hose/close/outbound.js";
import { executeEbotApprovalCallback } from "../../hose/open/approval.js";
import { listHoseIntegrations, selectHoseIntegration } from "../outbound/push.js";
import type { CapabilityContext } from "./helpers.js";
/**
* The niche Hose outbound loop, exposed under the first-level `seal-use hose-ebot`
* command: discover outbound records by document SN, discover the outbound
* message configs (and their signKey), then write the EBot approval callback.
*/
export const hoseCapabilities = [
{
name: "sealHoseOutboundSearch",
description: "按单号搜索合思出站消息调用记录(出站触发 INVOKING / 回调 CALLBACK),返回含唯一 id 的记录列表",
parameters: z.object({
sn: z.string().describe("合思单号 (flowId.form.code)"),
type: z
.enum(["invoking", "callback"])
.optional()
.describe("记录类型筛选:invoking=出站触发,callback=回调;缺省全部"),
limit: z
.number()
.int()
.positive()
.max(100)
.optional()
.default(20)
.describe("返回条数上限(默认 20,最大 100)"),
reveal: z.boolean().optional().describe("明文返回记录中的 signKey(默认脱敏)")
}),
handler: async (
_client: KyInstance,
params: { sn: string; type?: "invoking" | "callback"; limit: number; reveal?: boolean },
context: CapabilityContext
) => {
// The type filter applies client-side, so over-fetch first to keep the
// requested page size after filtering.
const serverCount = params.type ? Math.min(params.limit * 4, 100) : params.limit;
const allRecords = await fetchHoseOutboundLogs(context.corp, params.sn, { limit: serverCount });
const filtered = params.type
? allRecords.filter((record) => (record.type ?? "").toLowerCase() === params.type)
: allRecords;
const records = filtered.slice(0, params.limit);
return {
corpId: context.corp.id,
sn: params.sn,
type: params.type ?? "all",
count: records.length,
revealed: params.reveal === true,
records: records.map((record) =>
record.request?.signKey
? {
...record,
request: {
...record.request,
signKey: params.reveal
? record.request.signKey
: maskHoseSecurity(record.request.signKey)
}
}
: record
)
};
}
},
{
name: "sealHoseOutboundMessages",
description: "列出合思侧全部出站消息配置(含 signKey、回调地址、启用状态),用于发现 EBot 出站消息及其签名密钥",
parameters: z.object({
reveal: z.boolean().optional().describe("明文返回 signKey(默认脱敏为 8...4 形式)"),
type: z
.enum(["flow", "message"])
.optional()
.describe("按消息类型过滤:flow=审批流 EBot 出站,message=完成回调/通知")
}),
handler: async (
_client: KyInstance,
params: { reveal?: boolean; type?: "flow" | "message" },
context: CapabilityContext
) => {
const messages = await fetchHoseOutboundMessages(context.corp);
const filtered = params.type
? messages.filter((message) => message.messageType === params.type)
: messages;
return {
corpId: context.corp.id,
corpName: context.corp.name,
count: filtered.length,
revealed: params.reveal === true,
messages: filtered.map((message) => ({
...message,
signKey: message.signKey
? params.reveal
? message.signKey
: maskHoseSecurity(message.signKey)
: undefined
}))
};
}
},
{
name: "sealHoseApprovalCallback",
description: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签),向审批流回写结果;需 --yes/--confirm,或 --dry-run 预览",
parameters: z.object({
signKey: z
.string()
.optional()
.describe("出站消息签名密钥;缺省时从本企业 Seal 合思集成解析(仅一个集成时自动选择)"),
flowId: z.string().describe("单据 ID(出站消息中的 flowId)"),
nodeId: z.string().describe("当前 EBot 节点 ID(出站消息中的 nodeId)"),
action: z
.enum(["accept", "refuse", "preAdd", "aftAdd"])
.describe("accept 同意 / refuse 驳回 / preAdd 前加签 / aftAdd 后加签"),
comment: z.string().describe("审批意见"),
policy: z.enum(["ALL", "ANY"]).optional().describe("会签方式:ALL 会签 / ANY 或签(后加签超过一人时必填)"),
addApproverIds: z.array(z.string()).optional().describe("前后加签审批人 ID 列表(后加签时必填)"),
rejectTo: z.string().optional().describe("驳回目标节点 ID;缺省按 EBot 节点驳回配置"),
resubmitMethod: z
.enum(["FROM_START", "TO_REJECTOR"])
.optional()
.describe("驳回后重提方式:FROM_START 重新走审批流 / TO_REJECTOR 直接送审至此节点"),
dryRun: z.boolean().optional().default(false).describe("仅预览回调请求,不执行"),
confirm: z.boolean().optional().describe("明确确认执行回调;CLI 使用 --yes 或 --confirm")
}),
handler: async (
client: KyInstance,
params: {
signKey?: string;
flowId: string;
nodeId: string;
action: "accept" | "refuse" | "preAdd" | "aftAdd";
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
dryRun?: boolean;
confirm?: boolean;
},
context: CapabilityContext
) => {
if (!params.dryRun && params.confirm !== true) {
throw confirmationRequired(
"Refusing to run the Hose EBot approval callback without --yes or --confirm. Use --dry-run to preview first.",
`seal-use hose-ebot callback --flow-id ${params.flowId} --node-id ${params.nodeId} --action ${params.action} --comment "${params.comment}" --dry-run --corp ${context.corp.id}`
);
}
if (context.corp.source.type !== "hose") {
throw validationError(
`企业「${context.corp.name}」非合思(hose)租户,无法执行合思 EBot 审批回调。`
);
}
// An explicit signKey (typically discovered via `hose-ebot messages --reveal`)
// skips the Seal-side lookup; without one the configured integration decides.
let signKey = params.signKey?.trim();
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const integration = selectHoseIntegration({
integrations: listHoseIntegrations(config),
corpName: context.corp.name,
corpId: context.corp.id
});
signKey = integration.signKey;
}
if (!signKey) {
throw validationError(
`企业「${context.corp.name}」的合思出站配置未保存 signKey,请重新执行 configure。`
);
}
const payload = {
signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
};
if (params.dryRun) {
return {
preview: true,
corpId: context.corp.id,
endpoint: `${normalizeBaseUrl(context.corp.source.domain)}/api/openapi/v1/approval`,
payload: { ...payload, signKey: maskHoseSecurity(signKey) },
note: "仅预览:正式执行需去掉 --dry-run 并追加 --yes(届时实时换取 accessToken 后回调)。"
};
}
const result = await executeEbotApprovalCallback(context.corp, payload);
console.error(`✓ 回调审批成功 (code ${result.code}): ${result.message}`);
console.error(
`👉 Next action: seal-use hose-ebot search <单号SN> --corp ${context.corp.id} 核对该单出站/回调记录`
);
return {
corpId: context.corp.id,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
ok: true,
...result
};
}
}
];
+5
View File
@@ -7,6 +7,7 @@ import { webhookCapabilities } from "./webhook.js";
import { approvalRunsCapabilities } from "./approval-runs.js";
import { simulationCapabilities } from "./simulation.js";
import { deployCapabilities } from "./deploy.js";
import { hoseCapabilities } from "./hose.js";
import { preferenceCapabilities } from "./preference.js";
import { reportCapabilities } from "./reports.js";
@@ -23,6 +24,7 @@ export const sealCapabilities = [
...approvalRunsCapabilities,
...simulationCapabilities,
...deployCapabilities,
...hoseCapabilities,
...preferenceCapabilities,
...reportCapabilities
];
@@ -90,6 +92,8 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudRequirements",
"sealDeployHosecloudStatus",
"sealExpensesList",
"sealHoseOutboundMessages",
"sealHoseOutboundSearch",
"sealInsightExport",
"sealInsightPerformanceGet",
"sealInsightRisksByTagGet",
@@ -138,6 +142,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudConfigure",
"sealDeployHosecloudSync",
"sealDeployHosecloudTestOutbound",
"sealHoseApprovalCallback",
"sealInsightRecordAnalyze",
"sealPreferenceDecisionUpdate",
"sealPreferenceThinkingDepthPoliciesRemove",
@@ -210,6 +210,6 @@ describe("local report CLI", () => {
expect(result.exitCode).toBe(0);
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true);
expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true);
}, 15000);
}, 35000);
});
+1 -1
View File
@@ -13,7 +13,7 @@ Release. On WSL, `seal-use-release-sync.timer` polls the latest release every
The first archive becomes available as soon as it is present in Gitea.
The remaining assets retry idempotently on later timer runs if needed.
Promotion only mirrors release assets; it does not update package-manager repositories.
Promotion mirrors all published release assets as well as Git repository branches and tags to the local Gitea mirror. It does not update package-manager repositories.
The WSL worker uses its local mihomo listener at `http://127.0.0.1:7897` only
for GitHub. It does not enable TUN or expose a LAN listener. Local Gitea
+34
View File
@@ -16,6 +16,7 @@ NO_PROXY_LIST="${NO_PROXY:-127.0.0.1,localhost,100.82.151.105,git.ying-qing.cn}"
GITHUB_TOKEN_FILE="${SEAL_USE_GITHUB_TOKEN_FILE:-$HOME/.config/seal-use/github-token}"
GITEA_TOKEN_FILE="${SEAL_USE_GITEA_TOKEN_FILE:-$HOME/.config/seal-use/gitea-token}"
LOCK_FILE="${SEAL_USE_SYNC_LOCK_FILE:-$STATE_DIR/sync.lock}"
GIT_MIRROR_DIR="${SEAL_USE_SYNC_GIT_MIRROR_DIR:-$STATE_DIR/repo.git}"
mkdir -p "$STATE_DIR" "$WORK_DIR"
exec 9>"$LOCK_FILE"
@@ -67,6 +68,39 @@ gitea_curl() {
return "$rc"
}
sync_git_repo() {
log "synchronizing Git repository refs (branches and tags) to Gitea"
if [ ! -d "$GIT_MIRROR_DIR" ]; then
log "initializing bare mirror repository at $GIT_MIRROR_DIR"
mkdir -p "$GIT_MIRROR_DIR"
git init --bare "$GIT_MIRROR_DIR" >/dev/null
fi
local gh_url="https://github.com/${GITHUB_REPO}.git"
local gitea_url="${GITEA_BASE}/${GITEA_REPO}.git"
log "fetching latest refs from GitHub ($GITHUB_REPO)"
if ! env HTTP_PROXY="$PROXY_URL" HTTPS_PROXY="$PROXY_URL" ALL_PROXY= NO_PROXY="$NO_PROXY_LIST" \
git --git-dir="$GIT_MIRROR_DIR" \
-c http.extraHeader="Authorization: Bearer ${GITHUB_TOKEN}" \
fetch --prune --tags --force "$gh_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
log "warning: failed to fetch Git refs from GitHub; skipping Git mirror push this run"
return 0
fi
log "mirroring refs to Gitea ($GITEA_REPO)"
if ! env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY NO_PROXY="$NO_PROXY_LIST" \
git --git-dir="$GIT_MIRROR_DIR" \
-c http.extraHeader="Authorization: token ${GITEA_TOKEN}" \
push --prune --tags --force "$gitea_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
log "warning: failed to push Git refs to Gitea; will retry next timer"
return 0
fi
log "Git repository refs successfully synchronized to Gitea"
}
sync_git_repo
release_json=$(github_curl -H 'Accept: application/vnd.github+json' \
"https://api.github.com/repos/$GITHUB_REPO/releases/latest") || die "cannot read latest GitHub release"
tag=$(jq -r '.tag_name // empty' <<< "$release_json")
@@ -1,5 +1,5 @@
[Unit]
Description=Promote GitHub releases to Gitea
Description=Promote GitHub releases and mirror repository refs to Gitea
After=network-online.target docker.service mihomo.service
Wants=network-online.target
Requires=mihomo.service