Compare commits
55
Commits
23f12f17c5
..
v0.9.7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62b47f5ad7 | ||
|
|
83dacf90c4 | ||
|
|
1c5d6153a2 | ||
|
|
6ba748e531 | ||
|
|
9cf247fe45 | ||
|
|
4f572ad9c1 | ||
|
|
448dd438ff | ||
|
|
cfd0c48a8b | ||
|
|
b7fda124fd | ||
|
|
e00adbe5a8 | ||
|
|
75a0611f0e | ||
|
|
75740c4ec3 | ||
|
|
22215eb317 | ||
|
|
0c9eb27f85 | ||
|
|
ea5eb22c51 | ||
|
|
e588416a5f | ||
|
|
de88e218e7 | ||
|
|
020e4a2761 | ||
|
|
e7e856bbb0 | ||
|
|
bfbf6cf55f | ||
|
|
f3caebfd8a | ||
|
|
1eeb288143 | ||
|
|
4272dd8e60 | ||
|
|
7666db9f1d | ||
|
|
f9de8337b2 | ||
|
|
4beafe40cc | ||
|
|
3710f50ea4 | ||
|
|
55573de6a8 | ||
|
|
50362c2937 | ||
|
|
36e21e5dc2 | ||
|
|
b51152276d | ||
|
|
901fa072d3 | ||
|
|
ecab64477f | ||
|
|
13c47d7569 | ||
|
|
d772ff0164 | ||
|
|
8375445bcb | ||
|
|
876dcc7175 | ||
|
|
a71f1675b8 | ||
|
|
384f611a26 | ||
|
|
f465979ec3 | ||
|
|
6fef188f2f | ||
|
|
417be3ef54 | ||
|
|
46fa2597d0 | ||
|
|
957cb04324 | ||
|
|
19d8fd3c59 | ||
|
|
dfb464605e | ||
|
|
fb29ff630a | ||
|
|
c8adf0e051 | ||
|
|
e58841e164 | ||
|
|
e562ae9227 | ||
|
|
07a8a792af | ||
|
|
731e67377c | ||
|
|
4be87d448a | ||
|
|
a1cc808717 | ||
|
|
bb60053072 |
No files matched your search
@@ -10,7 +10,9 @@
|
||||
| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 |
|
||||
| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 |
|
||||
| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 |
|
||||
| [troubleshooting-and-investigation.md](./troubleshooting-and-investigation.md) | 业务排障诊断、探针环境隔离,以及沉淀优先原则 |
|
||||
| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 |
|
||||
|
||||
| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 |
|
||||
|
||||
## 维护边界
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: "排障诊断、探针环境与正式环境隔离,以及沉淀优先原则"
|
||||
globs: "src/**/*.{ts,md}"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 业务排障与系统探查铁律(Troubleshooting & Investigation Rules)
|
||||
|
||||
本规则总结自多租户、工作流与审批流联动真实排障过程中的典型教训,面向所有在此仓库进行业务排查与功能迭代的 AI Agent。
|
||||
|
||||
---
|
||||
|
||||
## 1. 探针环境与业务目标企业严格隔离(Probe vs. Target Boundary)
|
||||
|
||||
在面对未知系统接口、未逆向的页面交互或存在破坏性风险的操作时,用户常会引导 Agent「先去测试企业(如沈玥妍测试企业)摸一下/探查一下」:
|
||||
|
||||
1. **明确行为性质是“探针(Probe)”而非“诊断结论”**:
|
||||
- 访问测试企业的**唯一目的**是:安全抓包、获取底层 API 路径、探明请求/响应 JSON Schema 或验证逆向结论。
|
||||
- **绝对禁止将探针环境的现状当作业务问题的根因**:例如测试企业的出站规则停用,绝不代表目标正式企业的单据卡住是因为规则停用。
|
||||
2. **探针完毕后必须立即主动切回业务企业**:
|
||||
- 一旦在测试企业摸清 API 契约与数据结构,必须**自动、毫不犹豫地切换回用户最初声明的问题主体(目标正式企业与员工身份)**执行只读验证;
|
||||
- 绝不能等用户反问“你在说什么、为什么不看某某所在的正式企业”才被动纠正。
|
||||
|
||||
---
|
||||
|
||||
## 2. 沉淀优先于临时脚本(Productization First)
|
||||
|
||||
在排障过程中,当发现需要调用尚未被 CLI 封装的系统内部接口(如系统出站消息规则 `GET api/outbound/v1/message`、投递日志 `POST api/outbound/v1/message/messageLog` 等)时:
|
||||
|
||||
1. **严禁随手编写 ad-hoc 一次性脚本(`scratch_*.ts`)解决眼前问题**:
|
||||
- 一次性脚本容易陷入路径引用、未导出函数、临时编译报错等低价值泥潭;
|
||||
- 一次性脚本无法给用户留下可复现、可交付的资产。
|
||||
2. **标准研发流:边排障边沉淀到工程体系**:
|
||||
- 按照分层架构规范,第一时间将接口接入:
|
||||
$$\text{transport/ (API 校验)} \rightarrow \text{services.ts (业务门面)} \rightarrow \text{cli/commands/ (用户命令)} \rightarrow \text{command-metadata.ts (参数契约)}$$
|
||||
- 补齐最小单元测试,保证 `bun test` 与 `bun run check` 通过;
|
||||
- **直接使用自身编译/运行的官方 CLI 命令(例如 `hose-use workflow outbound logs ...`)为用户输出排查结果**。
|
||||
3. **闭环 PR 与本地重载**:
|
||||
- 查完问题后,主动通过标准 PR 流程将能力合入主分支;
|
||||
- 执行 `bun run dev:override` 重新编译安装本地开发二进制与 Skill,保持环境资产最新。
|
||||
|
||||
---
|
||||
|
||||
## 3. 合思审批流与工作流联动排障心智模型(Mental Model)
|
||||
|
||||
当遇到“新提交的单据卡在工作流计算节点,且工作流运行日志没有任何记录”时,必须建立**全链路事件下发**的全局排查视角:
|
||||
|
||||
$$\text{单据提交审批} \xrightarrow{\text{审批流出站节点}} \text{系统出站规则 (Outbound)} \xrightarrow{\text{HTTP Webhook}} \text{工作流触发器 (Piper)} \xrightarrow{\text{OpenAPI}} \text{回写/推进节点}$$
|
||||
|
||||
排查漏斗四步法:
|
||||
1. **看出站规则列表(`workflow outbound list`)**:
|
||||
- 检查企业内是否存在类型为 `flow` 的出站规则;
|
||||
- 检查规则是否启用(`enable: true`),且其 `callbackUrl` 是否指向目标工作流的 Webhook 路径。
|
||||
2. **看出站投递日志(`workflow outbound logs <单号>`)**:
|
||||
- 若**完全无记录**:说明单据流转时未匹配上任何出站规则(常见原因:审批流中的出站节点未关联出站规则,或单据模板类型不在出站规则适用范围);
|
||||
- 若**有记录但状态为 FAILED**:查看日志中的 `request` 与目标服务器返回的 `response`(错误码、超时或 404 等)。
|
||||
3. **看工作流日志(`workflow logs <workflowId>`)**:
|
||||
- 若出站日志记录为 SUCCESS,但工作流日志为 0,排查 Webhook 载荷格式与工作流触发器入参映射是否脱节。
|
||||
4. **看单据类型契约(`formSpecification`)**:
|
||||
- 检查历史成功单据与卡住单据的表单规范(如「商机费用报销」vs「差旅费报销单」),核对工作流内代码节点或查询节点是否写死了特定单据模板 ID。
|
||||
@@ -21,3 +21,19 @@
|
||||
|
||||
# MCP Server 总开关(默认关闭)
|
||||
# HOSE_USE_MCP_ENABLED=true
|
||||
|
||||
# Piper / ScriptEngine 集群地址(默认 piper.ekuaibao.com / piper-test.ekuaibao.net)
|
||||
# 私有化或多集群部署可覆盖;影响工作流引擎客户端、Webhook 触发 URL 与灰度节点开通。
|
||||
# HOSE_PIPER_BASE_URL=https://piper.ekuaibao.com
|
||||
# HOSE_PIPER_TEST_BASE_URL=https://piper-test.ekuaibao.net
|
||||
|
||||
# AI PRO 离线凭证(默认 ~/.config/hose-use/aipro-license.token,0600)
|
||||
# 仅 hose-aipro 需要凭证;hose-use 是免费功能,不受凭证管辖。
|
||||
# HOSE_AIPRO_LICENSE_FILE=~/.config/hose-use/aipro-license.token
|
||||
|
||||
# 签发方专用(只在本机签发凭证时使用,客户端运行不需要)
|
||||
# HOSE_AIPRO_LICENSE_PRIVATE_KEY=<PEM 文本,切勿提交仓库>
|
||||
# HOSE_AIPRO_LICENSE_PRIVATE_FILE=~/.config/hose-use/license/private.pem
|
||||
|
||||
# 灰度节点开通的可选管理员密码(设置后需 --password)
|
||||
# HOSE_ADMIN_PASSWORD=<管理员密码>
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
@@ -183,9 +183,9 @@ jobs:
|
||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||
filename=$(basename "$file")
|
||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||
for attempt in 1 2 3; do
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/5)..."
|
||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||
continue
|
||||
fi
|
||||
@@ -212,24 +212,16 @@ jobs:
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
echo "::error::Failed to upload ${filename} after 5 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
# 串行上传:Gitea 维护期并发推大文件容易把重试窗口耗光,宁可慢也不要丢资产。
|
||||
# 配合 job 超时 60 分钟与单资产 5 次重试,给服务端抖动留出余量。
|
||||
failed=0
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
if [ "${#pids[@]}" -eq 2 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
pids=()
|
||||
fi
|
||||
upload_asset "$file" || failed=1
|
||||
done
|
||||
if [ "${#pids[@]}" -gt 0 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
|
||||
@@ -59,3 +59,10 @@ exports/
|
||||
|
||||
# Local API captures may contain tenant business data
|
||||
/specs/hose-close-api/_tmp-captured/
|
||||
|
||||
# 排障时临时下载的截图,通常带有客户名称与业务数据,不得入库
|
||||
/downloads/
|
||||
|
||||
# Vue 控制台的 Vite 中间产物;最终单文件产物在 src/packaging/generated/ 并提交
|
||||
/.webui-dist/
|
||||
/web/dist/
|
||||
@@ -185,3 +185,47 @@ C 组与任子行真实形态同构,前后缀完整保留,多出的 `}` 不
|
||||
`set -f` 关闭 glob 展开,避免文件名里的 `[` 被当通配符。
|
||||
- 验证三例:中文名放行 / 含冒号拦截 / 保留设备名拦截。
|
||||
- **本地 `core.quotepath` 已恢复默认(unset)**,不需要再靠本地配置绕过。
|
||||
|
||||
## 任子行条件节点空值保护已上线(2026-11-04 16:59,生产流程,用户授权)
|
||||
|
||||
流程 `905035646304378890`(任子行-方案一),tasksVersion 32 → 33,state 保持 1。
|
||||
|
||||
### 两个关键实测结论(务必记住)
|
||||
|
||||
1. **合思条件节点的 `AND` 不短路**。`AND(列表非空, 额度 < 0)` 在列表为空时照样报
|
||||
`condition 参数的解析结果必须为 Boolean 类型` —— 引擎是逐叶子求值再合并,
|
||||
`null < 0` 求出来是 null,合并阶段类型校验失败。**所以「靠布尔短路做空值保护」这条路是死的**,
|
||||
只有「流程控制级短路」(条件为 false 时不进子节点)才可靠。
|
||||
2. **`notNull` 对空数组 `[]` 返回 false**(即空数组算「为空」),对非空数组返回 true。
|
||||
HAB 实测:`{"list":[]}` → 不进子节点;`{"list":[1,2]}` → 进入。所以判断列表非空可以放心用 `notNull`。
|
||||
3. 条件节点为 false 时:节点 COMPLETED、子节点不执行、流程继续 —— 不报错不中断。
|
||||
|
||||
比较符枚举(前端 bundle 里挖出来的):`eq` / `neq` / `gt` / `lt` / `gte` / `lte` /
|
||||
`isNull` / `notNull` / `include` / `dynamicRange` / `givenRange`。其中 `isNull`/`notNull`
|
||||
**不需要 value 字段**(前端会把 value 输入框隐藏)。
|
||||
|
||||
### 改法
|
||||
|
||||
在 every 循环体里插了一层守卫条件节点 `control_bla5u1`,把原条件节点 `control_ay9mon`
|
||||
整个挪进它的 true 分支:
|
||||
|
||||
```
|
||||
every (control_0qqpqu)
|
||||
├── action_5yt4ko 查找业务对象数据
|
||||
└── control_bla5u1 条件:结果列表 notNull ← 新增
|
||||
└── control_ay9mon 条件:OR(差旅<0, 招待<0) ← 原样未动
|
||||
├── 修改单据 → 延迟 → http → 终止
|
||||
```
|
||||
|
||||
列表为空 → 守卫为 false → ay9mon 根本不被求值,`null < 0` 永不发生。
|
||||
|
||||
### 实施与验证
|
||||
|
||||
- 用 `workflow get --full` 备份 → 本地改 JSON 树(重算 levelIndex/orderIndex、按节点名重映射
|
||||
`$snapshot` 路径)→ `workflow save --file` 整体写入。差异比对确认 22 处变更全部落在被替换的
|
||||
子树内,其余节点零改动。
|
||||
- 回读确认:state=1、两个 http URL 完好、snapshot 路径已修正为
|
||||
`tasks.3.tasks.1.tasks.0.tasks.2.url-snapshot`、`workflow analyze` 0 门禁。
|
||||
- 备份留在 `.drafts/rzx-cond-backup/{before,after}.json`(.drafts 已 gitignore),回滚方式:
|
||||
`workflow save 905035646304378890 --file=.drafts/rzx-cond-backup/before.json --force-write --yes`。
|
||||
- HAB 上的两个临时验证流程已全部删除,163 条恢复原样。
|
||||
@@ -15,6 +15,11 @@
|
||||
- 已发布流程的改动用 `node add` / `node edit`(PUT 即生效),**不要再 publish**,否则报「流程已发布,建议刷新页面重新加载」。
|
||||
- 删除流程前必须先 `workflow toggle <id> --state=0` 停用。
|
||||
|
||||
## 功能授权边界(用户 2026-11-05 明确)
|
||||
|
||||
- **`hose-use` 是免费功能**,不需要凭证、不受任何激活门禁管辖。
|
||||
- **AI PRO 离线凭证只管 `hose-aipro`**,门禁挂在 `runAiProCli`。不要把「`hose-use` 写命令未受凭证约束」当成安全缺口或待办——这是设计,不是漏实现。需要凭证的是 AI PRO 审批能力,不是企业平台 CLI。
|
||||
|
||||
## 仓库协作
|
||||
|
||||
- 双远端:`origin` = GitHub(主),`home` = Gitea(git.ying-qing.cn)。发布顺序先 `home` 再 `origin`。
|
||||
@@ -22,7 +27,8 @@
|
||||
|
||||
## 已知基础设施
|
||||
|
||||
- New API 端点已从 Sealos 的 `sealosgzg.site` 迁移至 `api.ying-qing.cn`;代码里残留的 `*.sealosgzg.site` 硬编码属于待清理项(workflow 灰度开通网关)。
|
||||
- New API(LLM 代理)端点为 `api.ying-qing.cn`;原 Sealos 实例 `sealosgzg.site` 已回收,属用户本地基础设施,与本仓库代码无关。
|
||||
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/script-engine-client.ts:19` 与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
|
||||
|
||||
## 工作流与 Piper 核心契约(2026-11-02 固化)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.7",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.0)
|
||||
# hose-use (v0.9.7)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -32,6 +32,31 @@ hose-use version
|
||||
|
||||
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
|
||||
|
||||
### AI PRO 激活(默认关闭)
|
||||
|
||||
`hose-aipro` 与 `hose-use` 是同一个二进制的两个入口,安装脚本会自动软链出 `hose-aipro`。AI PRO 默认**不激活**:
|
||||
|
||||
1. 跑 `hose-aipro version --json` 记下当前版本;
|
||||
2. 把**版本号 + 期望到期日 + 客户名**通过微信 / 邮件 / 工单等离线渠道发给服务方申请凭证;
|
||||
3. 拿到凭证后**直接粘贴给你的 AI 助手**,由助手执行 `hose-aipro login '<凭证>'`(纯本地验签,不联网);
|
||||
4. 助手跑 `hose-aipro scopes --json` 能返回场景数据即激活成功。
|
||||
|
||||
凭证有两条约束:当前二进制版本不得高于其 `maxVersion`,当前时间不得晚于其 `exp`。完整流程与失败处理见 [hose-aipro Skill](./skills/hose-aipro/SKILL.md) 的「首次安装与激活」章节——Agent 自行安装时以该文档为准。
|
||||
|
||||
**`hose-use` 是免费功能,不需要凭证、不受任何激活门禁管辖;凭证只作用于 `hose-aipro`。**
|
||||
|
||||
### 环境变量
|
||||
|
||||
全部可选,完整清单见 [.env.example](./.env.example)。几个与发布相关的:
|
||||
|
||||
| 变量 | 作用 |
|
||||
|---|---|
|
||||
| `HOSE_PIPER_BASE_URL` / `HOSE_PIPER_TEST_BASE_URL` | 覆盖标准 / 测试 Piper 集群地址,影响工作流引擎客户端、Webhook 触发 URL 与灰度节点开通 |
|
||||
| `HOSE_AIPRO_LICENSE_FILE` | AI PRO 凭证文件路径(默认 `~/.config/hose-use/aipro-license.token`,0600) |
|
||||
| `HOSE_AIPRO_LICENSE_PRIVATE_KEY` / `HOSE_AIPRO_LICENSE_PRIVATE_FILE` | 仅签发方使用,客户端运行不需要 |
|
||||
|
||||
AI PRO 常驻服务启动后,浏览器打开 `http://127.0.0.1:8889/report` 即为本地 Web 控制台(Vue 单页、资源全内嵌、不依赖 CDN)。前端源码在 `web/`,构建产物由 `bun run web:build` 生成并内嵌进二进制。`GET /docs` 的交互式 API 文档同样全离线——Scalar 运行时由 `GET /static/scalar.js` 本地提供,仅在升级版本时才需要 `bun run docs:fetch` 联网刷新。
|
||||
|
||||
---
|
||||
|
||||
### CLI 常用命令速查 (`hose-use`)
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.7",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -29,6 +29,9 @@
|
||||
"openapi:bundle": "bun run scripts/generate/bundle-openapi.ts",
|
||||
"openapi:generate-raw": "bun run scripts/generate/generate-raw-openapi.ts",
|
||||
"openapi:all": "bun run scripts/generate/generate-raw-openapi.ts && bun run scripts/generate/bundle-openapi.ts",
|
||||
"docs:fetch": "node scripts/build/build-docs.mjs",
|
||||
"web:dev": "bun --cwd web run dev",
|
||||
"web:build": "node scripts/build/build-webui.mjs",
|
||||
"build:binary": "node scripts/build/build-binary.mjs",
|
||||
"build:plugin": "node scripts/build/build-plugin.mjs",
|
||||
"package:plugin": "node scripts/build/package-plugin.mjs",
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 构建脚本
|
||||
|
||||
| 脚本 | 职责 |
|
||||
|---|---|
|
||||
| `build-binary.mjs` | 用 `bun build --compile` 编译各平台单二进制,注入 `HOSE_BUILD_*` 版本元数据,并创建 `hose-aipro` multicall 软链 |
|
||||
| `build-plugin.mjs` | 打包 `dist/mcp/server.js`(MCP 单文件产物) |
|
||||
| `package-plugin.mjs` | 生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz` 完整插件包 |
|
||||
| `build-webui.mjs` | 构建 `web/` 的 Vue 控制台,把 JS/CSS 内联成 `src/packaging/generated/webui.txt` 供二进制内嵌 |
|
||||
| `build-docs.mjs` | 拉取固定版本 Scalar standalone 并校验 SHA-256,生成 `src/packaging/generated/scalar-standalone.js.txt` |
|
||||
|
||||
`build-webui.mjs` 需要开发机先执行 `bun install --cwd web`;生成物随 git 提交,CI 与编译二进制不需要前端依赖。其余三个脚本只依赖根仓库的 `bun install`。
|
||||
|
||||
对应根命令:`build:binary`、`build:plugin`、`package:plugin`、`web:build`。
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 刷新 /docs 页面使用的 Scalar 浏览器运行时。
|
||||
*
|
||||
* 固定版本 + SHA-256 校验,产物写到 src/packaging/generated/ 并随 git 提交,
|
||||
* 因此运行时完全离线,编译二进制与 CI 都不需要访问 CDN。
|
||||
* 用法:bun run docs:fetch(仅在升级 Scalar 版本时需要)
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
const SCALAR_VERSION = "1.25.101";
|
||||
const SOURCE = `https://cdn.jsdelivr.net/npm/@scalar/api-reference@${SCALAR_VERSION}/dist/browser/standalone.js`;
|
||||
const EXPECTED_SHA256 = "045c6a1ffa88167ea7f8adb8359cdfe2d2233faead3ebe1d2ec0b1e7975d3fdc";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const target = join(root, "src", "packaging", "generated", "scalar-standalone.js.txt");
|
||||
|
||||
console.log(`[build:docs] fetching @scalar/api-reference@${SCALAR_VERSION} ...`);
|
||||
const response = await fetch(SOURCE);
|
||||
if (!response.ok) {
|
||||
console.error(`[build:docs] 下载失败: HTTP ${response.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const actual = createHash("sha256").update(bytes).digest("hex");
|
||||
if (actual !== EXPECTED_SHA256) {
|
||||
console.error(`[build:docs] SHA-256 不匹配,拒绝写入`);
|
||||
console.error(` expected=${EXPECTED_SHA256}`);
|
||||
console.error(` actual =${actual}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 后缀 .txt:Bun 对 .js 的 text import 可能被当成模块;内容仍是完整 JS。
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, bytes);
|
||||
console.log(`[build:docs] ✓ ${target} (${(bytes.length / 1024 / 1024).toFixed(2)} MiB, sha256 ${actual.slice(0, 12)}…)`);
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 构建 web/ 下的 Vue 控制台,并把 JS/CSS 内联成单个 HTML 供二进制内嵌。
|
||||
*
|
||||
* 前置:bun install --cwd web(仅开发机需要;生成物随 git 提交,CI 不需要)
|
||||
* 用法:bun run web:build
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const webDir = join(root, "web");
|
||||
const outDir = join(root, ".webui-dist");
|
||||
// 后缀用 .txt 而非 .html:Bun 对 .html 的 text import 会推断成 HTMLBundle,
|
||||
// 导致 tsc 报错;内容仍是完整 HTML,由 HTTP 层按 text/html 返回。
|
||||
const target = join(root, "src", "packaging", "generated", "webui.txt");
|
||||
|
||||
if (!existsSync(join(webDir, "node_modules"))) {
|
||||
console.error("[build:webui] web/ 依赖未安装,请先执行: bun install --cwd web");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("[build:webui] building Vue app...");
|
||||
execFileSync("bun", ["run", "build"], { cwd: webDir, stdio: "inherit" });
|
||||
|
||||
const indexPath = join(outDir, "index.html");
|
||||
if (!existsSync(indexPath)) {
|
||||
console.error(`[build:webui] 找不到构建产物: ${indexPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let html = readFileSync(indexPath, "utf8");
|
||||
const files = readdirSync(outDir);
|
||||
|
||||
for (const file of files.filter((name) => name.endsWith(".css"))) {
|
||||
const css = readFileSync(join(outDir, file), "utf8");
|
||||
html = html.replace(/<link[^>]+href="[^"]*\.css"[^>]*>/g, () => `<style>${css}</style>`);
|
||||
}
|
||||
|
||||
for (const file of files.filter((name) => name.endsWith(".js"))) {
|
||||
const js = readFileSync(join(outDir, file), "utf8").replaceAll("</script>", "<\\/script>");
|
||||
html = html.replace(/<script[^>]+src="[^"]*\.js"[^>]*><\/script>/g, () => `<script type="module">${js}</script>`);
|
||||
}
|
||||
|
||||
if (/<script[^>]+src=/.test(html) || /<link[^>]+href="[^"]*\.css"/.test(html)) {
|
||||
console.warn("[build:webui] 警告: 仍有外链资源未被内联,页面在纯本地环境可能加载失败");
|
||||
}
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, html, "utf8");
|
||||
console.log(`[build:webui] ✓ ${target} (${(html.length / 1024).toFixed(1)} KiB)`);
|
||||
+3
-1
@@ -263,5 +263,7 @@ echo " 2. List corps: hose-use corps list"
|
||||
echo " 3. List workflows: hose-use workflow list"
|
||||
echo " 4. Switch mode: hose-use config mode stateless"
|
||||
echo " 5. Self-update: hose-use update"
|
||||
echo " AI PRO alias: hose-aipro"
|
||||
echo " AI PRO alias: hose-aipro (默认未激活)"
|
||||
echo " AI PRO 申请凭证: 把版本号与期望到期日发给服务方,拿到凭证后直接粘贴给你的 AI 助手"
|
||||
echo " AI PRO 激活: 由 AI 助手执行,无需手动敲命令"
|
||||
echo ""
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* AI PRO 离线凭证签发工具(仅签发方本地使用,不参与二进制构建)。
|
||||
*
|
||||
* 用法:
|
||||
* bun run scripts/license/issue.ts --sub "客户名称" --exp 2027-12-31 --max-version 0.9.99
|
||||
*
|
||||
* 私钥来源(优先级):
|
||||
* 1. HOSE_AIPRO_LICENSE_PRIVATE_KEY 环境变量(PEM 文本)
|
||||
* 2. HOSE_AIPRO_LICENSE_PRIVATE_FILE 环境变量(PEM 文件路径)
|
||||
* 3. ~/.config/hose-use/license/private.pem
|
||||
*
|
||||
* 私钥绝不进入仓库。exp 是绝对到期时间,脚本不施加任何时长上限。
|
||||
*/
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { randomBytes, sign } from "node:crypto";
|
||||
|
||||
const DEFAULT_PRIVATE_FILE = join(homedir(), ".config", "hose-use", "license", "private.pem");
|
||||
|
||||
function option(name: string): string | undefined {
|
||||
const prefix = `--${name}=`;
|
||||
const inline = process.argv.slice(2).find((arg) => arg.startsWith(prefix));
|
||||
if (inline) return inline.slice(prefix.length).trim();
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
return index >= 0 ? process.argv[index + 1]?.trim() : undefined;
|
||||
}
|
||||
|
||||
function loadPrivateKeyPem(): string {
|
||||
const inline = process.env.HOSE_AIPRO_LICENSE_PRIVATE_KEY?.trim();
|
||||
if (inline) return inline.replace(/\\n/g, "\n");
|
||||
const configured = process.env.HOSE_AIPRO_LICENSE_PRIVATE_FILE?.trim();
|
||||
const file = configured || DEFAULT_PRIVATE_FILE;
|
||||
if (!existsSync(file)) {
|
||||
throw new Error(`找不到签发私钥: ${file}\n请设置 HOSE_AIPRO_LICENSE_PRIVATE_KEY 或 HOSE_AIPRO_LICENSE_PRIVATE_FILE`);
|
||||
}
|
||||
return readFileSync(file, "utf-8");
|
||||
}
|
||||
|
||||
function parseExpiry(raw: string | undefined): number {
|
||||
if (!raw) throw new Error("缺少 --exp(绝对到期时间,如 2027-12-31 或 Unix 秒)");
|
||||
if (/^\d+$/.test(raw)) return Number(raw);
|
||||
const parsed = Date.parse(raw);
|
||||
if (Number.isNaN(parsed)) throw new Error(`无法解析到期时间: ${raw}`);
|
||||
return Math.floor(parsed / 1000);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const sub = option("sub");
|
||||
const maxVersion = option("max-version");
|
||||
if (!sub) throw new Error("缺少 --sub(授权对象标识)");
|
||||
if (!maxVersion || !/^\d+\.\d+\.\d+$/.test(maxVersion)) {
|
||||
throw new Error("缺少或非法的 --max-version(应为 x.y.z)");
|
||||
}
|
||||
|
||||
const exp = parseExpiry(option("exp"));
|
||||
const payload = {
|
||||
v: 1 as const,
|
||||
sub,
|
||||
exp,
|
||||
maxVersion,
|
||||
features: ["aipro"],
|
||||
nonce: randomBytes(12).toString("base64url"),
|
||||
};
|
||||
|
||||
const payloadBytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, loadPrivateKeyPem());
|
||||
const token = `${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
|
||||
console.log(`授权对象 : ${sub}`);
|
||||
console.log(`到期时间 : ${new Date(exp * 1000).toISOString().slice(0, 10)}`);
|
||||
console.log(`版本上限 : v${maxVersion}`);
|
||||
console.log(`凭证编号 : ${payload.nonce}`);
|
||||
console.log("");
|
||||
console.log(token);
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`[签发失败] ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -162,7 +162,7 @@ for arg in "$@"; do
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 40_000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
@@ -173,7 +173,7 @@ exit 22
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||
expect(result.stdout).toContain("attempt 2/3");
|
||||
expect(result.stdout).toContain("attempt 2/5");
|
||||
}, 60_000);
|
||||
|
||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||
@@ -189,7 +189,7 @@ exit 22
|
||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||
}, 60_000);
|
||||
|
||||
test("asset transfers never exceed two concurrent workers", () => {
|
||||
test("asset transfers are serialized to a single worker", () => {
|
||||
const f = mirrorFixture("concurrency");
|
||||
expect(f.run().status).toBe(0);
|
||||
let active = 0, peak = 0;
|
||||
@@ -198,6 +198,6 @@ exit 22
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
expect(active).toBe(0);
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
expect(peak).toBe(1);
|
||||
}, 60_000);
|
||||
});
|
||||
+108
-2
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
version: 0.9.7
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.0)
|
||||
# hose-aipro (v0.9.7)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
@@ -32,6 +32,95 @@ metadata:
|
||||
|
||||
---
|
||||
|
||||
## 首次安装与激活(Agent 操作序列)
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AI PRO **默认不激活**。装完二进制后,业务命令一律返回 `AIPRO_NOT_ACTIVATED`。
|
||||
> **客户不碰命令行**:客户只会把凭证粘贴到与 Agent 的对话框里;申请引导、执行激活、验证结果全部由 Agent 完成。
|
||||
> **凭证只作用于 `hose-aipro`**;`hose-use` 是免费功能,无需凭证、不受此门禁管辖。
|
||||
> 凭证**不能由 Agent 自行生成**——客户端只内嵌验签公钥,私钥在服务方手里。
|
||||
> 不要尝试绕过门禁、不要改系统时间、不要伪造或拼接凭证。
|
||||
|
||||
### 步骤 0 · 安装二进制(若尚未安装)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
脚本下载 Release 二进制并校验 SHA-256 清单,安装同一个 `hose-use` 后软链出 `hose-aipro`,同时把两份 Skill 装到 `~/.agents/skills/`。升级用 `hose-use update`。
|
||||
|
||||
### 步骤 1 · 确认版本(申请凭证的必要信息)
|
||||
|
||||
```bash
|
||||
hose-aipro version --json
|
||||
```
|
||||
|
||||
记下 `version` 字段。步骤 3 里由 Agent 直接把这个版本号写进给用户的消息,用户转给服务方,服务方据此设定凭证的 `maxVersion`。
|
||||
|
||||
### 步骤 2 · 判断是否已激活
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
- 返回场景数组 → 已激活,直接跳到步骤 5。
|
||||
- 返回 `{"code":"AIPRO_NOT_ACTIVATED","reason":"missing"}` → 未激活,继续步骤 3。
|
||||
|
||||
`status` / `help` / `version` 属自省命令,未激活也能运行;`scopes` 等业务命令一律受统一门禁管辖。
|
||||
|
||||
### 步骤 3 · 向用户索取凭证(Agent 在此等待)
|
||||
|
||||
在对话框里用一句话请用户提供凭证,并说明申请方式:向服务方提供**版本号(步骤 1 已查到,直接写进消息)+ 期望到期日 + 客户名 / 用途**,通过微信 / 邮件 / 工单等离线渠道申请,拿到后**把凭证直接粘贴回对话框**。
|
||||
|
||||
| 申请时需要的信息 | 由谁提供 |
|
||||
|---|---|
|
||||
| 当前二进制版本 | Agent 从步骤 1 读出并写进消息里 |
|
||||
| 期望到期日 | 用户决定,凭证里是绝对到期时间 `exp` |
|
||||
| 客户名 / 用途标识 | 用户决定,会写进凭证的 `sub` |
|
||||
|
||||
**不要让用户执行命令、不要让用户找配置文件、不要让用户自己敲 `login`。** 用户只做两件事:申请、粘贴。
|
||||
|
||||
### 步骤 4 · Agent 接住凭证并自行激活
|
||||
|
||||
用户粘贴后,从对话内容里**只提取那串 `xxx.yyy` 凭证文本**(`base64url(payload).base64url(签名)`),去掉前后的说明文字、引号、换行与空格,然后由 Agent 自己执行:
|
||||
|
||||
```bash
|
||||
hose-aipro login '<凭证>'
|
||||
# 等价写法
|
||||
hose-aipro login --token='<凭证>'
|
||||
```
|
||||
|
||||
- 原样传递,**不要生成、拼接、改写、重新编码或截断**这串文本;用单引号包裹,避免 shell 解析点号与特殊字符。
|
||||
- 不要把凭证回显到对话、不要写进日志、不要存到项目文件或笔记里。工具会落盘到 `~/.config/hose-use/aipro-license.token`(0600);可用 `HOSE_AIPRO_LICENSE_FILE` 指向别处。
|
||||
- 纯本地验签,**不联网**。
|
||||
|
||||
### 步骤 5 · Agent 验证并继续任务
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
返回真实场景数据即激活成功,直接继续原本的审批任务。`hose-aipro login --json` 会输出授权对象、到期时间与版本上限。
|
||||
|
||||
### 失败原因与处理
|
||||
|
||||
| `reason` | 含义 | 处理 |
|
||||
|---|---|---|
|
||||
| `missing` | 未激活 | 走步骤 3 请用户把凭证粘贴回对话框,Agent 自行激活 |
|
||||
| `expired` | 已超过 `exp` 绝对到期时间 | 重新申请凭证 |
|
||||
| `version_exceeded` | 当前版本高于 `maxVersion` | **不要降级二进制**,重新申请更高 `maxVersion` 的凭证 |
|
||||
| `bad_signature` | 凭证被篡改或复制不完整 | 重新复制完整凭证,检查引号与换行 |
|
||||
| `no_feature` / `malformed` | 凭证不含 AI PRO 授权或格式错误 | 重新申请凭证 |
|
||||
|
||||
### 两条约束
|
||||
|
||||
- 当前二进制版本不得高于凭证的 `maxVersion`(三段数字比较,忽略 `-dev` 后缀)。**升级二进制超过上限会立刻失效**,需重新申请。
|
||||
- 当前时间不得晚于凭证的 `exp`(绝对到期时间)。客户端不做设备绑定、不做时钟防篡改。
|
||||
|
||||
凭证是 Ed25519 签名数据,不是二进制变体:所有客户下载的是**同一个二进制**,区别只在本地有没有凭证文件。新增任意 AI PRO 命令自动受统一门禁管辖。
|
||||
|
||||
---
|
||||
|
||||
## 快速自省与运行上下文 (Zero-Source-Reading)
|
||||
|
||||
在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文:
|
||||
@@ -101,6 +190,23 @@ hose-aipro logs S26000001
|
||||
|
||||
---
|
||||
|
||||
## 本地 Web 控制台
|
||||
|
||||
常驻 HTTP 服务自带一个离线可用的 Vue 控制台,把审批会话、规则库、审核要点、审计流水与命令终端放到网页里看:
|
||||
|
||||
```bash
|
||||
hose-aipro service start # 默认 127.0.0.1:8889
|
||||
# 浏览器打开 http://127.0.0.1:8889/report
|
||||
```
|
||||
|
||||
- 页面资源全部内嵌在二进制里,**不请求任何 CDN**;只监听回环地址。是否映射成公网地址由使用者自行决定,工具不提供也不建议。
|
||||
- `GET /report` 返回页面;页面通过 `POST /api/cli` 调用现有 CLI 命令,`report --json` 是聚合数据源(场景 / 规则 / 会话 / 要点 / 流水 / 授权状态)。
|
||||
- 若设置了 `HOSE_HTTP_TOKEN`,浏览器请求需带 Bearer Token;默认本地使用不需要。
|
||||
- 控制台属于 AI PRO 能力,未激活时 `report --json` 会被统一门禁拦截。
|
||||
- 前端源码在 `web/`,改动后执行 `bun install --cwd web` 与 `bun run web:build` 重新生成 `src/packaging/generated/webui.txt`。生成物随 git 提交,CI 与编译二进制不需要安装前端依赖。
|
||||
|
||||
---
|
||||
|
||||
## 本机常驻服务与跨进程管理 (Daemon & Peer Control)
|
||||
|
||||
`hose-aipro` 拥有独立的常驻 HTTP 守护进程(默认端口 `8889`),并能直接启停本机的 `hose-use` 服务(默认端口 `8888`):
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
version: 0.9.7
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.0)
|
||||
# hose-use (v0.9.7)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -256,7 +256,8 @@ hose-use workflow check --json --fail-on-alert # 扫描错误管道
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
||||
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
||||
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
|
||||
hose-use workflow nodes grant code-js2 --dry-run # 预览灰度开通变更(含固定附带开关)
|
||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业硬拦截,可选 --password 管理员保护
|
||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
|
||||
|
||||
@@ -13,39 +13,35 @@ description: |
|
||||
|
||||
## 参数提取
|
||||
|
||||
用户通常会贴浏览器请求(curl),从请求中自动提取参数:
|
||||
使用本机已配置的企业和认证信息,不需要浏览器 curl、手工提取 token 或调用第三方网关:
|
||||
|
||||
| 参数 | 提取位置 | 说明 |
|
||||
|------|----------|------|
|
||||
| token | Header `accesstoken` 或 Cookie `ekb-access-token` | accessToken |
|
||||
| corpId | Header `corpid` 或 URL query `corpId` | 企业 ID |
|
||||
| baseUrl | URL 协议+域名部分(如 `https://dd2.hosecloud.com`) | 自定义合思地址 |
|
||||
| nodes | 向用户确认 | 节点名,逗号分隔 |
|
||||
| 参数 | 来源 | 说明 |
|
||||
|------|------|------|
|
||||
| 企业 | `hose-use corps list` | 用 `--corp=<id>` 指定目标企业;遵循企业环境标记 |
|
||||
| 节点类型 | 本文件中的灰度节点清单 | 传 `type` 值,不传中文显示名 |
|
||||
|
||||
**域名判断**:URL 不是 `*.hosecloud.com` 而是 `dd2.hosecloud.com` 这类就是自定义域名,必须提取为 `baseUrl`。
|
||||
CLI 使用本地企业配置中的 `accessToken`、员工 ID 和 `baseUrl` 完成 EASO 换票与 Piper 请求;凭证不需要复制到 shell 命令或聊天中。
|
||||
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
# 网关地址优先取环境变量 HOSE_GRAY_GATEWAY_URL(尾部斜杠会自动忽略),未配置时用内置默认地址
|
||||
GATEWAY="${HOSE_GRAY_GATEWAY_URL:-https://d9jxeccs5j.sealosgzg.site}"
|
||||
curl -s -X POST "${GATEWAY%/}/hose-workflow-node" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
||||
```
|
||||
|
||||
> 网关托管在第三方域,实例可能被回收或迁移。CLI 侧同样支持 `HOSE_GRAY_GATEWAY_URL` 覆盖;
|
||||
> 网关不可用时不要自行改用其他地址,先确认变量指向的实例仍然有效。
|
||||
工作流节点开通的默认 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
**每个企业的工作流只对应一个 Piper 环境**:标准 Piper(默认)与测试 Piper(`--is-test`)二选一,不会同时可用,也不会在请求失败时自动切换。若某企业通过标准 Piper 成功开通,说明它的工作流在标准环境;同一企业再通过测试 Piper 开通应失败,反之亦然。企业名称、本地 `env=test` 标记和企业 `baseUrl` 都不能用来推断 Piper 环境。
|
||||
|
||||
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
|
||||
|
||||
**生产企业硬拦截**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)直接拒绝,且**没有 `--force` 逃生口**。灰度节点开通是不可逆的企业级写操作,只能切换到测试企业执行。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
|
||||
|
||||
## 结果处理
|
||||
|
||||
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
|
||||
**成功**:CLI 根据 Piper 业务响应中的 `code` 确认开通结果,并显示新开通或已开通的节点。
|
||||
|
||||
**失败排查**:
|
||||
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
|
||||
- `认证失败` + 其他 — token 过期,让用户重新获取
|
||||
- 认证失败 — 检查本地企业凭证是否有效,并按 CLI 提示重新登录或刷新认证
|
||||
- Piper 业务码失败 — 依据 CLI 返回的业务错误信息排查企业或节点配置
|
||||
- 节点名错误 — 核对名称拼写
|
||||
@@ -184,8 +184,9 @@ hose-use workflow nodes
|
||||
# 2. 与官方全量 108 个灰度节点清单进行完整对照
|
||||
hose-use workflow nodes --all
|
||||
|
||||
# 3. 申请开通灰度节点(支持节点拼音与中文名)
|
||||
hose-use workflow nodes grant code-js2
|
||||
# 3. 申请开通灰度节点(支持中文名归一化;同名节点需改用明确的 type)
|
||||
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关
|
||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业一律被硬拦截
|
||||
```
|
||||
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
@@ -503,6 +504,33 @@ result;
|
||||
|
||||
将代码保存为独立 `.mvel` 文件,通过 `--code-file` 同步,节点说明保留 `agent use:` 标识。条件节点引用代码结果的 `hasDetails`,与布尔选择器 `@{value('{"key":true,"label":"是"}')}` 比较;创单和成功回写均放在该条件内部。至少验证空数组与非空数组,代码规范参见 [MVEL 参考](../multi/ekuaibao-mvel/SKILL.md)。
|
||||
|
||||
### 列表取数字段参与比较,必须先判空
|
||||
|
||||
上一节处理的是「数组本身参与比较」;这里处理另一个更常见的坑:**取值链要先穿过列表再往下取字段**,例如「查找业务对象数据 → 结果列表 → 首条数据 → 剩余额度」。上游查到 0 条时取值为 `null`,而 `null < 0` 在 MVEL 里返回 `null` 而不是 `false`,引擎对 `condition` 做 Boolean 强校验,直接抛:
|
||||
|
||||
```
|
||||
if 节点(control_xxx)的 condition 参数的解析结果必须为 Boolean 类型
|
||||
```
|
||||
|
||||
流程**中断**,不是安静走 false 分支。这条报错信息看不出是取值拿到 null,实际排查成本很高。
|
||||
|
||||
两条实测结论决定了正确写法:
|
||||
|
||||
1. **`AND` 不短路**。`AND(列表不为空, 额度 < 0)` 在列表为空时照样报同一个错——引擎是逐叶子求值再合并,`null < 0` 一定被算出来。所以「在同一个条件节点里加一层非空判断」这条路是死的。
|
||||
2. **`notNull` 对空数组 `[]` 返回 false**,对非空数组返回 true;条件为 false 时节点 COMPLETED、子节点不执行、流程继续。所以判断列表非空可以直接用 `notNull`,且**不需要 `value` 字段**。
|
||||
|
||||
可靠写法是把守卫上提一层,用流程控制短路:
|
||||
|
||||
```text
|
||||
条件节点A 条件:结果列表 notNull ← 新增守卫
|
||||
└─(满足) 条件节点B 条件:OR(额差<0, 招待<0) ← 原条件,表达式不动
|
||||
└─ 真正的处理动作
|
||||
```
|
||||
|
||||
列表为空时 A 为 false,B 根本不被求值。`workflow analyze` 对「列表取数 + `gt/gte/lt/lte` 比较 + 祖先链上没有同列表守卫」的情况给 `CONDITION_NULL_UNSAFE_COMPARE` 软提示,不推断数据是否真的非空、不改写配置。
|
||||
|
||||
比较符完整枚举:`eq` / `neq` / `gt` / `lt` / `gte` / `lte` / `isNull` / `notNull` / `include` / `dynamicRange` / `givenRange`。其中 `isNull` / `notNull` 不需要 `value` 字段。
|
||||
|
||||
### 调试成功必须回读单据
|
||||
|
||||
核对实际新单号、明细条数、每条金额、合计、源单关联与逐项入库关联;同时核对 Job 的错误节点和回写内容。草稿创建成功只证明此次草稿落库,不能据此声称提交送审、审批或付款成功;未验证的收款方、法人实体等字段应明确列出。关联引用次数耗尽可能自动停用源记录,不得为了重跑擅自重置引用次数、启用记录或重复创单。
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"version":"1.0.0","updatedAt":"2026-11-16T08:08:21.159Z","sourceUrl":"https://docs.ekuaibao.com/search-index.json","totalDocs":330,"totalEndpoints":279,"items":[{"id":3788,"title":"下载附件","category":"附件","url":"/docs/open-api/attachment/attachment-download","permalink":"https://docs.ekuaibao.com/docs/open-api/attachment/attachment-download","method":"POST","path":"/api/openapi/v2/attachment/downloadurls","breadcrumbs":["Open API","附件"],"headings":["Query Parameters","Body Parameters","CURL","成功响应","失败响应","钉盘附件下载","阿里云OSS CURL"],"sections":[{"title":"下载附件","content":"通过附件的 id、key 去获取附件的下载链接。 POST/api/openapi/v2/attachment/downloadurls 更新日志 2.3.1 🚀 优化了接口,支持ISV应用钉盘附件下载。 1.6.3 🐞 优化了接口 HTTP 500 错误,输出报错信息。"},{"title":"Query Parameters","content":"名称 类型 描述 是否必填 默认值 备注 accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken"},{"title":"Body Parameters","content":"名称 类型 描述 是否必填 默认值 备注 -- Array 数组参数 必填 - 数组参数,最大支持 100 个参数 ∟ id String 文件fileId 必填 - 上传附件 接口返回的 fileId 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 fileId 值 ∟ key String 文件key 必填 - 上传附件 接口返回的 key 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 key 值,注意: key 值前缀是 DP:时,表示该附件是钉盘附件 。 ∟ expiration Number 下载链接有效时间 必填 - 下载链接在多长时间内有效,单位:秒,最大 1800 秒 ,钉盘附件该值无效"},{"title":"CURL","content":"curl --location --request POST 'https://app.ekuaibao.com/api/openapi/v2/attachment/downloadurls?accessToken=UvsbtOEHTsk000' \\ --header 'Content-Type: application/json' \\ --data-raw '[ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"expiration\": 1000 }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"expiration\": 1000 } ]'"},{"title":"成功响应","content":"tip url 是文件下载路径,thumbUrl 是指缩略图的下载路径。 thumbUrl 只针对图片有效,PDF文件生成的链接是不可用的。 key 下载钉盘附件时,url 和 thumbUrl 都是 阿里OSS 文件链接,保存文件时需要根据key值内的 fileType 值来判断文件类型。 headers 只针对钉盘附件有效,下载文件时需要将 headers传入,否则会下载失败。 [ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"url\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=wTRfcimdrHhXbL3efe8MftOSOmo%3D&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\", \"thumbUrl\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=evQnFfd4YhL5zkFMovDl9ZfVdlw%3D&x-oss-process=image%2Fresize%2Cw_120%2Ch_120&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\" }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"url\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXNrMATOITK4JgXNEKcGzTyBB85mF5ENCM24VQ.file\", \"thumbUrl\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXLine truncated
|
||||
@@ -57,8 +57,8 @@ specs/hose-close-api/
|
||||
| `EKB` | `https://app.ekuaibao.com`(按企业集群可能是 `wx2` 等) | 主站业务、模板、OpenAPI、自建应用列表 |
|
||||
| `EASO` | `https://unity.ekuaibao.com` | EASO 平台、协助平台网关 |
|
||||
| `PIPER` | `https://piper.ekuaibao.com` | 工作流(pipeline)与 Job 执行 |
|
||||
| `PIPER_TEST` | `https://piper-test.ekuaibao.net` | 显式 `isTest: true` 时使用的工作流测试环境 |
|
||||
| `ASSIST` | `https://unity.ekuaibao.com/api` | 协助平台客户端前缀 |
|
||||
| `GW` | `https://d9jxeccs5j.sealosgzg.site` | 灰度节点开通网关(非合思域名) |
|
||||
|
||||
## 响应包装约定
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
|
||||
| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/workflow/transport/debug/api.ts:28` | 否 |
|
||||
| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:<jobId>|{id}|{jobId}}` | `src/domains/platform/workflow/transport/debug/api.ts:43` | 否 |
|
||||
| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/workflow/transport/catalog/api.ts:57` | 否 |
|
||||
| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/transport/catalog/api.ts:74` | 否 |
|
||||
| P30 | POST | `PIPER` / `PIPER_TEST` `/api/easo/dsl/corporation` | `{corporationId,dslTypes:[type],"recalculate-the-approval-flow":true,"ui-notification":true,start:0}`;Authorization: Bearer EASO JWT;`--is-test` 选择 `PIPER_TEST` | `{code,msg,data?}`;成功必须 `code:200` | `src/domains/platform/workflow/transport/catalog/api.ts:134` | 否 |
|
||||
|
||||
`Platform` 代码字段(`src/domains/platform/workflow/models/nodes.ts:5`):
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.0
|
||||
version: 0.9.7
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.7",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
import { COMMAND_METADATA } from "./cli/command-metadata.js";
|
||||
import { setAiProLicenseDeps, resetAiProLicenseDeps, saveAiProLicenseToken } from "./cli/aipro-license.js";
|
||||
import {
|
||||
AIPRO_COMMAND_REGISTRY,
|
||||
findAiProCommand,
|
||||
@@ -12,7 +17,28 @@ import {
|
||||
} from "./cli/aipro-registry.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
let licenseDir = "";
|
||||
|
||||
beforeEach(() => {
|
||||
// 门禁默认关闭:注入临时密钥对与有效凭证,让原有全链路用例无需改动
|
||||
licenseDir = mkdtempSync(join(tmpdir(), "hose-aipro-cli-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(licenseDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
const privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
const licensePayload = {
|
||||
v: 1,
|
||||
sub: "集成测试",
|
||||
exp: Math.floor(Date.now() / 1000) + 86_400,
|
||||
maxVersion: "99.99.99",
|
||||
features: ["aipro"],
|
||||
nonce: "integration",
|
||||
};
|
||||
const payloadBytes = Buffer.from(JSON.stringify(licensePayload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, privateKeyPem);
|
||||
saveAiProLicenseToken(`${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`);
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1" });
|
||||
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
@@ -31,6 +57,9 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
resetAiProLicenseDeps();
|
||||
rmSync(licenseDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("version/help --json only emit machine-readable stdout", async () => {
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import { handleAiProReport } from "./cli/commands/aipro/report.js";
|
||||
import { assertAiProEnabled, handleAiProLogin } from "./cli/aipro-license.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -38,6 +40,8 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
// multicall 二进制的 argv0 不进 parsed.raw,显式标注入口身份供命令层判断
|
||||
runtime.app = "hose-aipro";
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
@@ -97,11 +101,27 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "login" || command === "activate") {
|
||||
return handleAiProLogin(rawArgs, jsonMode);
|
||||
}
|
||||
if (booleanOption(parsed.options, ["version", "v"])) {
|
||||
const versionDef = findAiProCommand("version");
|
||||
if (versionDef) return await versionDef.handler(ctx);
|
||||
}
|
||||
|
||||
// 统一门禁:除只读自省命令外,其余 AI PRO 命令一律要求有效凭证。
|
||||
// 以后新增命令只需照常注册,自动被此处拦截,无需改动授权代码。
|
||||
const readOnly = new Set(["status", "whoami", "context", "info", "help", "version", "v"]);
|
||||
if (!readOnly.has(command)) {
|
||||
const licenseGate = assertAiProEnabled(jsonMode);
|
||||
if (licenseGate) return licenseGate;
|
||||
}
|
||||
|
||||
// 本地 Web 控制台的聚合数据源(只读,不进命令注册表)
|
||||
if (command === "report") {
|
||||
return handleAiProReport(ctx);
|
||||
}
|
||||
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertAiProEnabled,
|
||||
checkAiProLicense,
|
||||
compareBaseVersion,
|
||||
handleAiProLogin,
|
||||
resetAiProLicenseDeps,
|
||||
saveAiProLicenseToken,
|
||||
setAiProLicenseDeps,
|
||||
verifyAiProLicenseToken,
|
||||
} from "./aipro-license.js";
|
||||
|
||||
let tempDir = "";
|
||||
let privateKeyPem = "";
|
||||
|
||||
function issue(overrides: Record<string, unknown> = {}): string {
|
||||
const payload = {
|
||||
v: 1,
|
||||
sub: "测试客户",
|
||||
exp: 4_102_444_800,
|
||||
maxVersion: "0.9.99",
|
||||
features: ["aipro"],
|
||||
nonce: "test-nonce",
|
||||
...overrides,
|
||||
};
|
||||
const bytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, bytes, privateKeyPem);
|
||||
return `${bytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-aipro-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(tempDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1", nowSeconds: 1_700_000_000 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetAiProLicenseDeps();
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("版本上限", () => {
|
||||
test("三段数字比较,dev 后缀被忽略", () => {
|
||||
expect(compareBaseVersion("0.9.1-dev.2+gabc", "0.9.99")).toBe(-1);
|
||||
expect(compareBaseVersion("0.10.0", "0.9.99")).toBe(1);
|
||||
expect(compareBaseVersion("0.9.99-dev.3+gXXX", "0.9.99")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("双约束校验", () => {
|
||||
test("有效凭证放行", () => {
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("签名被篡改拒绝", () => {
|
||||
const [payload] = issue().split(".");
|
||||
const forged = `${payload}.${Buffer.from("bad").toString("base64url")}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("payload 改动后签名失配", () => {
|
||||
const [payload, signature] = issue().split(".");
|
||||
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
||||
decoded.exp = 9_999_999_999;
|
||||
const forged = `${Buffer.from(JSON.stringify(decoded)).toString("base64url")}.${signature}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("超过绝对到期时间拒绝", () => {
|
||||
setAiProLicenseDeps({ nowSeconds: 4_102_444_801 });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "expired" });
|
||||
});
|
||||
|
||||
test("当前版本超过上限拒绝,等于上限放行", () => {
|
||||
setAiProLicenseDeps({ version: "0.10.0" });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "version_exceeded" });
|
||||
setAiProLicenseDeps({ version: "0.9.99" });
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("缺少 aipro feature 拒绝", () => {
|
||||
expect(verifyAiProLicenseToken(issue({ features: ["other"] }))).toMatchObject({ ok: false, reason: "no_feature" });
|
||||
});
|
||||
|
||||
test("格式错误与非法版本上限拒绝", () => {
|
||||
expect(verifyAiProLicenseToken("not-a-token")).toMatchObject({ ok: false, reason: "malformed" });
|
||||
expect(verifyAiProLicenseToken(issue({ maxVersion: "latest" }))).toMatchObject({ ok: false, reason: "malformed" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("统一门禁与激活", () => {
|
||||
test("默认无凭证即未激活,门禁拦截", () => {
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
const blocked = assertAiProEnabled(false);
|
||||
expect(blocked?.exitCode).toBe(1);
|
||||
expect(blocked?.stderr).toContain("尚未激活");
|
||||
});
|
||||
|
||||
test("login 激活后门禁放行", () => {
|
||||
const result = handleAiProLogin(["login", issue()], false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("已激活");
|
||||
expect(assertAiProEnabled(false)).toBeNull();
|
||||
});
|
||||
|
||||
test("无效凭证激活失败且不落盘", () => {
|
||||
const result = handleAiProLogin(["login", "forged.token"], false);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
});
|
||||
|
||||
test("缺少凭证返回用法提示", () => {
|
||||
expect(handleAiProLogin(["login"], false).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("json 模式拦截返回结构化错误", () => {
|
||||
const blocked = assertAiProEnabled(true);
|
||||
expect(blocked?.stderr).toBe("");
|
||||
expect(JSON.parse(blocked?.stdout ?? "{}")).toMatchObject({ code: "AIPRO_NOT_ACTIVATED", reason: "missing" });
|
||||
});
|
||||
|
||||
test("凭证文件权限为 0600", () => {
|
||||
saveAiProLicenseToken(issue());
|
||||
expect(statSync(join(tempDir, "license.token")).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* AI PRO 离线授权:单文件,唯一门禁入口由 aipro-cli.ts 调用。
|
||||
*
|
||||
* 新增任意 AI PRO 命令都不需要改动本文件——门禁在分发层统一拦截。
|
||||
* 唯一例外是 login / activate,在门禁之前分流。
|
||||
*
|
||||
* 凭证:base64url(payload).base64url(Ed25519 签名)
|
||||
* payload:{ v, sub, exp, maxVersion, features, nonce }
|
||||
* 两条约束:当前版本 <= maxVersion;当前时间 <= exp(绝对到期,Unix 秒)。
|
||||
* 刻意不做:设备绑定、时钟防篡改、激活时间锚点、相对时长上限。
|
||||
*/
|
||||
import { createPublicKey, verify } from "node:crypto";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { VERSION } from "../version.js";
|
||||
import { parseArgs, stringOption } from "./parser.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { CliResult } from "./types.js";
|
||||
|
||||
/** 验签公钥(随源码编译进二进制)。私钥由签发方离线保管,绝不进仓库。
|
||||
* SHA-256(SPKI DER): f5ead0d75667c259afae00474040177012fa2de4509e6dfa9c2eb7c25f1ad403
|
||||
* 更换此公钥会使所有已签发凭证失效,发版后不得随意变更。
|
||||
*/
|
||||
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEA0e0mcz9TnKnVJAEmr96mOc+9OineoekA3tY/UhGE7mo=
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export const AIPRO_LICENSE_FILE_ENV = "HOSE_AIPRO_LICENSE_FILE";
|
||||
|
||||
interface LicensePayload {
|
||||
v: 1;
|
||||
sub: string;
|
||||
exp: number;
|
||||
maxVersion: string;
|
||||
features: string[];
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export type LicenseCheck =
|
||||
| { ok: true; payload: LicensePayload }
|
||||
| { ok: false; reason: "missing" | "malformed" | "bad_signature" | "no_feature" | "expired" | "version_exceeded"; message: string };
|
||||
|
||||
interface LicenseDeps {
|
||||
publicKeyPem: string;
|
||||
version: string;
|
||||
nowSeconds?: number;
|
||||
}
|
||||
|
||||
const defaults: LicenseDeps = { publicKeyPem: PUBLIC_KEY.trim(), version: VERSION };
|
||||
let deps: LicenseDeps = { ...defaults };
|
||||
|
||||
/** 进程内依赖注入,仅供单元测试使用;CLI 运行时不暴露。 */
|
||||
export function setAiProLicenseDeps(partial: Partial<LicenseDeps>): void {
|
||||
deps = { ...deps, ...partial };
|
||||
}
|
||||
|
||||
export function resetAiProLicenseDeps(): void {
|
||||
deps = { ...defaults };
|
||||
}
|
||||
|
||||
export function resolveAiProLicenseFile(): string {
|
||||
const explicit = process.env[AIPRO_LICENSE_FILE_ENV]?.trim();
|
||||
if (explicit) return explicit;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "aipro-license.token");
|
||||
return join(homedir(), ".config", "hose-use", "aipro-license.token");
|
||||
}
|
||||
|
||||
export function saveAiProLicenseToken(token: string): string {
|
||||
const file = resolveAiProLicenseFile();
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(file, token.trim(), { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(file, 0o600);
|
||||
} catch {
|
||||
// 写入时的 mode 已生效
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
function loadToken(): string | null {
|
||||
try {
|
||||
const file = resolveAiProLicenseFile();
|
||||
return existsSync(file) ? readFileSync(file, "utf-8").trim() || null : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 只取 x.y.z 三段数字,忽略 -dev.N+gXXX 等后缀。 */
|
||||
export function compareBaseVersion(a: string, b: string): number {
|
||||
const parse = (v: string): [number, number, number] | null => {
|
||||
const m = v.match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
||||
};
|
||||
const left = parse(a);
|
||||
const right = parse(b);
|
||||
if (!left || !right) throw new Error(`非法版本号: ${a} 或 ${b}`);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function parsePayload(text: string): LicensePayload | null {
|
||||
try {
|
||||
const p = JSON.parse(text);
|
||||
if (p.v !== 1 || typeof p.sub !== "string" || !p.sub) return null;
|
||||
if (!Number.isInteger(p.exp) || p.exp <= 0) return null;
|
||||
if (typeof p.maxVersion !== "string" || !/^\d+\.\d+\.\d+$/.test(p.maxVersion)) return null;
|
||||
if (!Array.isArray(p.features) || !p.features.every((f: unknown) => typeof f === "string")) return null;
|
||||
if (typeof p.nonce !== "string" || !p.nonce) return null;
|
||||
return p as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyAiProLicenseToken(token: string): LicenseCheck {
|
||||
const parts = token.trim().split(".");
|
||||
if (parts.length !== 2 || !parts[0] || !parts[1]) {
|
||||
return { ok: false, reason: "malformed", message: "凭证格式错误:应为 <payload>.<signature> 两段" };
|
||||
}
|
||||
|
||||
let payloadBytes: Buffer;
|
||||
let signature: Buffer;
|
||||
try {
|
||||
payloadBytes = Buffer.from(parts[0], "base64url");
|
||||
signature = Buffer.from(parts[1], "base64url");
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: "凭证编码错误:无法按 base64url 解码" };
|
||||
}
|
||||
|
||||
let valid = false;
|
||||
try {
|
||||
valid = verify(null, payloadBytes, createPublicKey(deps.publicKeyPem), signature);
|
||||
} catch {
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return { ok: false, reason: "bad_signature", message: "凭证签名无效,可能被篡改或并非本工具签发" };
|
||||
|
||||
const payload = parsePayload(payloadBytes.toString("utf-8"));
|
||||
if (!payload) return { ok: false, reason: "malformed", message: "凭证内容无效:字段缺失或格式不符" };
|
||||
if (!payload.features.includes("aipro")) {
|
||||
return { ok: false, reason: "no_feature", message: "该凭证未包含 AI PRO 授权" };
|
||||
}
|
||||
|
||||
const now = deps.nowSeconds ?? Math.floor(Date.now() / 1000);
|
||||
if (now > payload.exp) {
|
||||
const date = new Date(payload.exp * 1000).toISOString().slice(0, 10);
|
||||
return { ok: false, reason: "expired", message: `授权凭证已于 ${date} 到期,请重新申请凭证` };
|
||||
}
|
||||
|
||||
try {
|
||||
if (compareBaseVersion(deps.version, payload.maxVersion) > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "version_exceeded",
|
||||
message: `当前版本 v${deps.version} 超出授权上限 v${payload.maxVersion},请重新申请凭证`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: `凭证版本上限非法: ${payload.maxVersion}` };
|
||||
}
|
||||
|
||||
return { ok: true, payload };
|
||||
}
|
||||
|
||||
export function checkAiProLicense(): LicenseCheck {
|
||||
const token = loadToken();
|
||||
if (!token) {
|
||||
return { ok: false, reason: "missing", message: "AI PRO 尚未激活。凭证需向服务方离线申请,拿到后直接粘贴给 AI 助手完成激活" };
|
||||
}
|
||||
return verifyAiProLicenseToken(token);
|
||||
}
|
||||
|
||||
/** 统一门禁:返回拦截结果,null 表示放行。 */
|
||||
export function assertAiProEnabled(jsonMode: boolean): CliResult | null {
|
||||
const status = checkAiProLicense();
|
||||
if (status.ok) return null;
|
||||
const hint = status.reason === "missing"
|
||||
? "\n下一步: 向服务方申请凭证(提供 hose-aipro version 的版本号与期望到期日),把凭证粘贴给 AI 助手,或自行运行 hose-aipro login '<凭证>'"
|
||||
: "\n下一步: 联系服务方重新申请凭证";
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, code: "AIPRO_NOT_ACTIVATED", reason: status.reason, message: status.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 未激活] ${status.message}${hint}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/** login 不进注册表,由分发层在门禁之前直接分流,避免任何注册表/元数据同步。 */
|
||||
export function handleAiProLogin(rawArgs: string[], jsonMode: boolean): CliResult {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const token =
|
||||
stringOption(parsed.options, ["token", "license", "credential", "code"]) ||
|
||||
parsed.positional?.slice(1).find((part) => part && !part.startsWith("-")) ||
|
||||
"";
|
||||
|
||||
if (!token.trim()) {
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ error: true, message: "缺少凭证" }) + "\n" : "",
|
||||
stderr: jsonMode
|
||||
? ""
|
||||
: "[AI PRO 激活] 缺少凭证。\n用法: hose-aipro login <凭证>\n 或: hose-aipro login --token=<凭证>\n",
|
||||
exitCode: 2,
|
||||
};
|
||||
}
|
||||
|
||||
const result = verifyAiProLicenseToken(token.trim());
|
||||
if (!result.ok) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, activated: false, reason: result.reason, message: result.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 激活失败] ${result.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const file = saveAiProLicenseToken(token.trim());
|
||||
const { sub, exp, maxVersion } = result.payload;
|
||||
const expiresAt = new Date(exp * 1000).toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ activated: true, subject: sub, expiresAt, maxVersion, licenseFile: file }) + "\n"
|
||||
: `AI PRO 已激活。\n 授权对象: ${sub}\n 到期时间: ${expiresAt}\n 版本上限: v${maxVersion}\n 凭证文件: ${file} (0600)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)",
|
||||
"outbound": "查询合思系统出站消息规则与投递日志 (list|logs)"
|
||||
},
|
||||
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
@@ -286,6 +288,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--is-test 选择测试 Piper;每个企业的工作流只在标准/测试环境之一,不会自动回退",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
@@ -332,9 +335,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"webhook-send": "webhook",
|
||||
"webhooks": "webhook",
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
"web": "link",
|
||||
"outbounds": "outbound",
|
||||
"outbound-message": "outbound"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -897,6 +904,41 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||
...flagList("status", "boolean-or-value")
|
||||
}
|
||||
},
|
||||
"docs": {
|
||||
"summary": "合思开放平台官方接口文档与端点规范检索",
|
||||
"usage": "hose-use docs <search|show|categories|sync> [关键词|路径] [--json]",
|
||||
"commands": {
|
||||
"search": "按关键词、分类或方法检索开放平台 HTTP 接口",
|
||||
"show": "查看指定接口的完整规范、参数定义、CURL 与响应示例",
|
||||
"categories": "查看开放平台所有业务模块分类与端点统计",
|
||||
"sync": "强制与线上文档中心全量同步最新索引"
|
||||
},
|
||||
"aliases": [
|
||||
"doc",
|
||||
"api-doc",
|
||||
"api-docs"
|
||||
],
|
||||
"commandAliases": {
|
||||
"find": "search",
|
||||
"list": "search",
|
||||
"ls": "search",
|
||||
"get": "show",
|
||||
"info": "show",
|
||||
"cat": "show",
|
||||
"read": "show",
|
||||
"detail": "show",
|
||||
"category": "categories",
|
||||
"cats": "categories",
|
||||
"modules": "categories",
|
||||
"groups": "categories",
|
||||
"update": "sync",
|
||||
"refresh": "sync"
|
||||
},
|
||||
flags: {
|
||||
...flagList("keyword query q category cat module method m path p target id name url limit count n", "value"),
|
||||
...flagList("refresh sync force", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# AI PRO 命令层
|
||||
|
||||
`hose-aipro` 专属命令的 handler,由 `src/cli/aipro-registry.ts` 注册,经 `src/aipro-cli.ts` 的统一凭证门禁后分发。只读自省命令(`status` / `version` / `help` 等)豁免门禁,其余一律要求有效离线凭证。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `status.ts` | 网关运行上下文、企业信息与帮助页 |
|
||||
| `rules.ts` | 规约场景、审核要点、核验清单 |
|
||||
| `bind.ts` | 单据挂载与会话初始化 |
|
||||
| `review.ts` | 事实证据核验打标(PASS / FAIL / SKIP) |
|
||||
| `decide.ts` | 确定性仲裁与流转 |
|
||||
| `logs.ts` | 审计流水查询 |
|
||||
| `service.ts` | 常驻服务控制 |
|
||||
| `report.ts` | `report --json` 聚合数据源,供本地 Web 控制台一次拉取场景 / 规则 / 会话 / 要点 / 流水 / 授权状态 |
|
||||
|
||||
`types.ts` 定义 `AiProExecutionContext` 与命令结果类型;`index.ts` 汇总导出。新增命令照常注册即可自动受门禁管辖,不需要改授权代码。
|
||||
|
||||
**边界**:凭证只作用于 `hose-aipro`;`hose-use` 是免费功能,不受任何激活门禁约束。
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "../../../core/db/index.js";
|
||||
import { ApprovalRepository } from "../../../domains/approval/repository.js";
|
||||
import { handleAiProReport } from "./report.js";
|
||||
|
||||
describe("handleAiProReport 聚合数据", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("返回场景/规则/会话/要点/流水与授权状态", () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传真实发票]{硬性},[建议填写详细事由]{建议}。",
|
||||
});
|
||||
|
||||
const result = handleAiProReport({
|
||||
repo,
|
||||
corp: null,
|
||||
corpId: undefined,
|
||||
operator: "tester",
|
||||
} as never);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.summary.rules).toBe(1);
|
||||
expect(payload.summary.scopes).toBeGreaterThanOrEqual(1);
|
||||
expect(Array.isArray(payload.scopes)).toBe(true);
|
||||
expect(Array.isArray(payload.rules)).toBe(true);
|
||||
expect(Array.isArray(payload.runs)).toBe(true);
|
||||
expect(Array.isArray(payload.findings)).toBe(true);
|
||||
expect(Array.isArray(payload.logs)).toBe(true);
|
||||
expect(payload.license).toBeDefined();
|
||||
expect(payload.generatedAt).toBeTruthy();
|
||||
// 单据快照等大字段不应出现在报表里
|
||||
expect(result.stdout).not.toContain("documentSnapshot");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { printJson } from "../../printer.js";
|
||||
import { VERSION } from "../../../version.js";
|
||||
import { checkAiProLicense } from "../../aipro-license.js";
|
||||
import type { AiProCommandResult, AiProExecutionContext } from "./types.js";
|
||||
|
||||
/**
|
||||
* hose-aipro report --json:本地 Web 控制台的聚合数据源。
|
||||
* 只读、不联网;单据快照等大字段不返回,避免撑爆浏览器。
|
||||
*/
|
||||
export function handleAiProReport(ctx: AiProExecutionContext): AiProCommandResult {
|
||||
const { repo, corp, corpId, operator } = ctx;
|
||||
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = repo.listRuns({ corpId, limit: 500 });
|
||||
const logs = repo.listAiProLogs(undefined, 200);
|
||||
const license = checkAiProLicense();
|
||||
|
||||
const runRows = runs.map((run) => ({
|
||||
id: run.id,
|
||||
shortId: run.shortId,
|
||||
documentSn: run.documentSn,
|
||||
corpId: run.corpId,
|
||||
decision: run.decision,
|
||||
createdAt: run.createdAt,
|
||||
updatedAt: run.updatedAt,
|
||||
findingsCount: repo.getFindingsByRunId(run.id).length,
|
||||
}));
|
||||
|
||||
const findings = runs.flatMap((run) =>
|
||||
repo.getFindingsByRunId(run.id).map((finding) => ({
|
||||
runId: run.shortId || run.id,
|
||||
documentSn: run.documentSn,
|
||||
ruleCode: finding.ruleCode,
|
||||
status: finding.checkStatus,
|
||||
strictness: finding.strictness,
|
||||
content: finding.clauseText,
|
||||
evidence: finding.evidence,
|
||||
reasoning: finding.reasoning,
|
||||
}))
|
||||
);
|
||||
|
||||
const payload = {
|
||||
version: VERSION,
|
||||
generatedAt: new Date().toISOString(),
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corp.credentials?.staffId || corp.staffId || null,
|
||||
baseUrl: corp.baseUrl || null,
|
||||
source: corp.source || null,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
license: license.ok
|
||||
? {
|
||||
activated: true,
|
||||
subject: license.payload.sub,
|
||||
expiresAt: new Date(license.payload.exp * 1000).toISOString(),
|
||||
maxVersion: license.payload.maxVersion,
|
||||
}
|
||||
: { activated: false, reason: license.reason, message: license.message },
|
||||
summary: {
|
||||
scopes: scopes.length,
|
||||
rules: rules.length,
|
||||
runs: runRows.length,
|
||||
pending: runRows.filter((run) => run.decision === "PENDING").length,
|
||||
findings: findings.length,
|
||||
logs: logs.length,
|
||||
},
|
||||
scopes,
|
||||
rules,
|
||||
runs: runRows,
|
||||
findings,
|
||||
logs,
|
||||
};
|
||||
|
||||
return { stdout: printJson(payload) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
describe("CLI - 开放平台官方接口文档域 (docs / openapi-docs)", () => {
|
||||
test("hose-use docs 输出开放平台文档概览与端点总数", async () => {
|
||||
const res = await runCli(["docs"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台官方文档中心");
|
||||
expect(res.stdout).toContain("文档总数:");
|
||||
expect(res.stdout).toContain("端点总数:");
|
||||
expect(res.stdout).toContain("hose-use docs search");
|
||||
});
|
||||
|
||||
test("hose-use docs --json 输出概览结构化元数据", async () => {
|
||||
const res = await runCli(["docs", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.totalDocs).toBeGreaterThan(100);
|
||||
expect(data.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
test("hose-use docs search roleDefGroups 能检索出角色组接口", async () => {
|
||||
const res = await runCli(["docs", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
});
|
||||
|
||||
test("hose-use docs search 角色组 --json 输出精准结构化搜索结果", async () => {
|
||||
const res = await runCli(["docs", "search", "角色组", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.total).toBeGreaterThanOrEqual(1);
|
||||
expect(data.items.some((i: any) => i.path === "/api/openapi/v1/roleDefGroups")).toBe(true);
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups 展示完整接口规格与 CURL 示范", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("CURL 请求示范");
|
||||
expect(res.stdout).toContain("成功响应示例");
|
||||
expect(res.stdout).toContain("accessToken");
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups --json 返回全量结构化文档项", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const doc = JSON.parse(res.stdout);
|
||||
expect(doc.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(doc.method).toBe("GET");
|
||||
expect(doc.category).toBe("企业通讯录");
|
||||
expect(doc.permalink).toContain("get-roles-group");
|
||||
});
|
||||
|
||||
test("hose-use docs show 未知目标时返回友好错误", async () => {
|
||||
const res = await runCli(["docs", "show", "non_existing_api_path_xyz"]);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("NOT FOUND");
|
||||
});
|
||||
|
||||
test("hose-use docs categories 输出所有业务分类与端点分布", async () => {
|
||||
const res = await runCli(["docs", "categories"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台业务模块分类");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
expect(res.stdout).toContain("预算");
|
||||
expect(res.stdout).toContain("单据");
|
||||
});
|
||||
|
||||
test("hose-use doc 别名也能正常调用", async () => {
|
||||
const res = await runCli(["doc", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
syncDocsCatalog,
|
||||
} from "../../domains/docs/tools.js";
|
||||
|
||||
export async function handleDocsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "";
|
||||
const forceRefresh =
|
||||
booleanOption(parsed.options, ["refresh", "force", "sync"]) ||
|
||||
action === "sync";
|
||||
|
||||
// 1. 同步命令: hose-use docs sync
|
||||
if (action === "sync") {
|
||||
const res = await syncDocsCatalog();
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 开放平台文档同步完成 ======\n文档总数: ${res.totalDocs}\n接口端点: ${res.totalEndpoints}\n数据源: ${res.source}\n更新时间: ${res.updatedAt}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 分类列表: hose-use docs categories
|
||||
if (["categories", "category", "cats", "modules"].includes(action)) {
|
||||
const cats = await listCategories({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: cats.length, categories: cats }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = cats.map((c, i) => [
|
||||
i + 1,
|
||||
c.name,
|
||||
`${c.count} 篇`,
|
||||
`${c.endpointsCount} 个`,
|
||||
]);
|
||||
const table = printTable(["#", "业务分类", "文档篇数", "HTTP 端点数"], rows);
|
||||
return {
|
||||
stdout: `====== 合思开放平台业务模块分类 (共 ${cats.length} 个) ======\n\n${table}\n\n提示: 运行 hose-use docs search --category=<模块名> 可查看该模块下的所有接口\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 详情命令: hose-use docs show <target>
|
||||
if (["show", "get", "info", "cat", "read"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["path", "url", "id", "name", "target"]);
|
||||
if (!target) {
|
||||
throw new Error("请指定要查看的接口路径、文档 URL 或名称: hose-use docs show <接口或URL>");
|
||||
}
|
||||
|
||||
const doc = await getDocDetail(target, { forceRefresh });
|
||||
if (!doc) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到匹配的文档或接口: ${target}\n提示: 可以先运行 hose-use docs search ${target} 检索相近接口。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(doc, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let out = `====== ${doc.title} ======\n`;
|
||||
out += printKeyValue({
|
||||
"业务模块": doc.category,
|
||||
"HTTP 方法": doc.method || "非端点/指南页面",
|
||||
"接口路径": doc.path || "-",
|
||||
"在线文档": doc.permalink,
|
||||
"文档标识": `#${doc.id}`,
|
||||
});
|
||||
|
||||
if (doc.parameters) {
|
||||
out += `\n\n### 参数规格与定义\n${doc.parameters}\n`;
|
||||
}
|
||||
|
||||
if (doc.curl) {
|
||||
out += `\n### CURL 请求示范\n\`\`\`bash\n${doc.curl}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
if (doc.responseSample) {
|
||||
out += `\n### 成功响应示例\n\`\`\`json\n${doc.responseSample}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 4. 搜索命令 (默认行为): hose-use docs search <keyword> 或 hose-use docs <keyword>
|
||||
const isSearchAction = ["search", "find", "list", "ls", ""].includes(action);
|
||||
if (isSearchAction) {
|
||||
const keyword =
|
||||
(action === "search" || action === "find" ? parsed.args[0] : action || parsed.args[0]) ||
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
|
||||
const category = stringOption(parsed.options, ["category", "cat", "module"]);
|
||||
const method = stringOption(parsed.options, ["method", "m"]);
|
||||
const path = stringOption(parsed.options, ["path", "p"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n", "count"], 25);
|
||||
|
||||
// 如果没有任何搜索条件且没有关键词,展示全局概览
|
||||
if (!keyword && !category && !method && !path && !action) {
|
||||
const catalog = await getDocsCatalog({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
sourceUrl: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 合思开放平台官方文档中心 ======
|
||||
文档总数: ${catalog.totalDocs} 篇
|
||||
端点总数: ${catalog.totalEndpoints} 个
|
||||
数据来源: ${catalog.sourceUrl}
|
||||
更新时间: ${catalog.updatedAt}
|
||||
|
||||
常用子命令:
|
||||
hose-use docs search <关键词> 检索开放平台 HTTP 接口与文档
|
||||
hose-use docs show <路径|名称|URL> 查看单篇接口规格、参数表格与 CURL 响应
|
||||
hose-use docs categories 查看 26+ 个业务分类及其端点数
|
||||
hose-use docs sync 强制与线上最新文档中心全量同步
|
||||
`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const searchRes = await searchDocs(
|
||||
{
|
||||
keyword,
|
||||
category,
|
||||
method,
|
||||
path,
|
||||
limit,
|
||||
},
|
||||
{ forceRefresh }
|
||||
);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const summaryItems = searchRes.items.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
category: item.category,
|
||||
method: item.method,
|
||||
path: item.path,
|
||||
url: item.url,
|
||||
permalink: item.permalink,
|
||||
matchReason: item.matchReason || undefined,
|
||||
}));
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
total: searchRes.total,
|
||||
count: summaryItems.length,
|
||||
keyword: searchRes.keyword,
|
||||
category: searchRes.category,
|
||||
method: searchRes.method,
|
||||
items: summaryItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (searchRes.items.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配的文档或接口 (关键词: ${keyword || "-"}, 分类: ${category || "-"}, 方法: ${method || "-"})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const hasKeyword = Boolean(keyword);
|
||||
const headers = hasKeyword
|
||||
? ["Method", "Path / URL", "标题", "分类", "匹配依据"]
|
||||
: ["Method", "Path / URL", "标题", "分类"];
|
||||
|
||||
const rows = searchRes.items.map((item) => {
|
||||
const base = [
|
||||
item.method || "DOC",
|
||||
item.path || item.url,
|
||||
item.title,
|
||||
item.category,
|
||||
];
|
||||
if (hasKeyword) {
|
||||
base.push(item.matchReason || "-");
|
||||
}
|
||||
return base;
|
||||
});
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const filterDesc = [
|
||||
keyword ? `关键词: '${keyword}'` : "",
|
||||
category ? `分类: '${category}'` : "",
|
||||
method ? `方法: '${method}'` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
stdout: `====== 开放平台接口搜索结果 (找到 ${searchRes.total} 条${filterDesc ? ` | ${filterDesc}` : ""}) ======\n\n${table}\n\n提示: 运行 hose-use docs show <Path> 可查看对应接口的完整参数和 CURL 示范\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知的 docs 子命令: ${action}。支持: search <关键词>, show <路径|URL>, categories, sync`
|
||||
);
|
||||
}
|
||||
@@ -572,5 +572,85 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
|
||||
it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
// 按应用名称查未找到
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
// 列出所有平台
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "platform-lease", name: "租赁摊销业务" } as any,
|
||||
{ id: "platform-other", name: "其他应用" } as any,
|
||||
]));
|
||||
// 模拟应用详情与对象列表
|
||||
spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({
|
||||
id: "platform-lease",
|
||||
name: "租赁摊销业务",
|
||||
} as any));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
if (platformId === "platform-lease") {
|
||||
return [
|
||||
{ id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any,
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 1,
|
||||
data: [
|
||||
{
|
||||
id: "rec-1",
|
||||
dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("记录1");
|
||||
});
|
||||
|
||||
it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
{ id: "app-2", name: "应用二" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any];
|
||||
}));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称");
|
||||
});
|
||||
|
||||
it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([]));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -243,8 +243,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameField = resolved.entity.fields?.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields?.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js";
|
||||
import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
@@ -19,16 +22,81 @@ export function cell(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId
|
||||
*/
|
||||
async function resolveEntityGlobally(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> {
|
||||
const platforms = await listPlatforms(client, corpId);
|
||||
const matches: Array<{ platform: any; entity: DatalinkEntity }> = [];
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
platforms.map(async (p) => {
|
||||
const entities = await listPlatformEntities(client, corpId, p.id);
|
||||
const found = entities.find((e) =>
|
||||
[e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase())
|
||||
);
|
||||
if (found) {
|
||||
return { platform: p, entity: found };
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
matches.push(r.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length === 1) {
|
||||
const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id);
|
||||
return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity };
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", ");
|
||||
throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const targetA = parsed.args[appIndex]?.trim();
|
||||
const targetB = parsed.args[entityIndex]?.trim();
|
||||
|
||||
if (!targetA) {
|
||||
throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>");
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
// 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析
|
||||
if (targetB) {
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`);
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
// 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等)
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (platform) {
|
||||
return { clients, corpId, platform, entity: undefined };
|
||||
}
|
||||
|
||||
// 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search)
|
||||
const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA);
|
||||
if (globalMatch) {
|
||||
return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity };
|
||||
}
|
||||
|
||||
throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleSkillCommand } from "./skill.js";
|
||||
import { getAiProSkillContent, getSkillContent } from "../../packaging/embedded-skill.js";
|
||||
|
||||
const parsed = {
|
||||
area: "skill",
|
||||
action: "dump",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["skill", "dump"],
|
||||
};
|
||||
|
||||
const baseRuntime = {
|
||||
selectedCorp: null,
|
||||
corpContext: {},
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
describe("skill dump 的 multicall 入口识别", () => {
|
||||
test("hose-aipro 入口返回 AI PRO Skill(不依赖 argv0 猜测)", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-aipro" } as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-aipro (v");
|
||||
});
|
||||
|
||||
test("hose-use 入口返回平台 Skill", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-use" } as never);
|
||||
expect(result.stdout).toBe(`${getSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-use (v");
|
||||
});
|
||||
|
||||
test("兼容历史:未标注 app 时仍按 parsed.raw 里的 aipro 标记识别", async () => {
|
||||
const legacyParsed = { ...parsed, raw: ["skill", "dump", "aipro"] };
|
||||
const result = await handleSkillCommand(legacyParsed as never, baseRuntime as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ export async function handleSkillCommand(
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "status";
|
||||
const isAiProCaller =
|
||||
runtime.app === "hose-aipro" ||
|
||||
parsed.area === "hose-aipro" ||
|
||||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import { parseArgs } from "../parser.js";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
|
||||
test("node grant previews without a gateway call and requires explicit confirmation", async () => {
|
||||
const runtime = { selectedCorp: { id: "corp", credentials: { corpId: "corp" } }, jsonMode: true } as any;
|
||||
test("node grant previews without a Piper call and requires explicit confirmation", async () => {
|
||||
const runtime = { selectedCorp: { id: "corp", isTest: true, credentials: { corpId: "corp" } }, jsonMode: true } as any;
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: true, saved: ["code-js2"], skipped: [], rawMessage: "ok" });
|
||||
try {
|
||||
await expect(handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2"]), runtime)).rejects.toThrow("--yes");
|
||||
@@ -12,7 +12,12 @@ test("node grant previews without a gateway call and requires explicit confirmat
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).changes.nodes).toEqual(["code-js2"]);
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
const testPreview = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code", "--is-test", "--dry-run", "--yes"]), runtime);
|
||||
expect(JSON.parse(testPreview.stdout).changes.isTest).toBe(true);
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--confirm"]), runtime);
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code", "--is-test", "--yes"]), runtime);
|
||||
expect(grant).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ nodes: ["code"], isTest: true }));
|
||||
} finally { grant.mockRestore(); }
|
||||
});
|
||||
@@ -2,11 +2,11 @@ import { expect, spyOn, test } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
test("failed grants retain gateway details and never report success", async () => {
|
||||
test("failed grants retain Piper details and never report success", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: false, saved: [], skipped: [], rawMessage: "permission denied" });
|
||||
try {
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--yes"]), { selectedCorp: { id: "corp", name: "test" }, jsonMode } as any);
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--yes"]), { selectedCorp: { id: "corp", name: "test", isTest: true }, jsonMode } as any);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).not.toContain("节点权限已生效");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout)).toMatchObject({ success: false, rawMessage: "permission denied" });
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
|
||||
test("production corp is blocked before any grant request or confirmation", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const runtime = {
|
||||
selectedCorp: {
|
||||
id: "prod-corp",
|
||||
name: "正式生产企业",
|
||||
env: "prod",
|
||||
credentials: { corpId: "prod-corp", accessToken: "token" },
|
||||
},
|
||||
jsonMode: false,
|
||||
} as any;
|
||||
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("生产环境安全阻断");
|
||||
expect(result.stderr).toContain("未提供 --force 逃生口");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("env-unmarked corp is conservatively treated as production", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: [], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
||||
{ selectedCorp: { id: "corp", name: "浙江麦瑞克科技有限公司" }, jsonMode: true } as any
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout).code).toBe("PROD_GRANT_BLOCKED");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -11,6 +11,7 @@ const mockCorp: CorpConfig = {
|
||||
name: "浙江麦瑞克科技有限公司",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
env: "test",
|
||||
credentials: {
|
||||
accessToken: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
@@ -135,10 +136,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
it("workflow nodes grant: 免密模式下成功发起灰度节点开通", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
code: 200,
|
||||
msg: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
@@ -159,7 +158,7 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
payload: expect.objectContaining({ dslTypes: ["code-js2"] }),
|
||||
token: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
})
|
||||
@@ -168,10 +167,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
it("workflow nodes grant: 节点名称自动中文归一化 (如 'JS节点(新)' 映射为 'code-js2')", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
code: 200,
|
||||
msg: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
@@ -189,12 +186,12 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
payload: expect.objectContaining({ dslTypes: ["code-js2"] }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 管理员密码保护预留生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
it("workflow nodes grant: 可选管理员密码保护生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
process.env.HOSE_ADMIN_PASSWORD = "secret_admin_pass";
|
||||
|
||||
// 1. 无密码调用被拒绝
|
||||
@@ -214,10 +211,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
// 3. 正确密码调用放行
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "开通成功",
|
||||
code: 200,
|
||||
msg: "开通成功",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { EkbError } from "../../../core/errors.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
|
||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
|
||||
import {
|
||||
@@ -99,6 +99,22 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
|
||||
// 保存前静态代码健康度检查
|
||||
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
|
||||
const scriptWarnings: string[] = [];
|
||||
if (scriptLintReport.totalCodeNodes > 0) {
|
||||
for (const node of scriptLintReport.reports) {
|
||||
if (node.issues.length > 0) {
|
||||
for (const iss of node.issues) {
|
||||
const icon = iss.level === "error" ? "❌" : "⚠️";
|
||||
const loc = iss.line ? `(L${iss.line})` : "";
|
||||
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -112,6 +128,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
tasksVersion: parsedWorkflow.tasksVersion,
|
||||
forceWrite,
|
||||
syncFile,
|
||||
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
|
||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查)
|
||||
const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]);
|
||||
if (flowFilter) {
|
||||
const corpId = runtime.selectedCorp?.credentials.corpId || "";
|
||||
const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, {
|
||||
maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(searchResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: searchResult.found ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!searchResult.found) {
|
||||
return {
|
||||
stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`,
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const job = searchResult.job!;
|
||||
const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存";
|
||||
const out = [
|
||||
`====== 工作流单据定位成功 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"定位来源": hitInfo,
|
||||
"触发单号": searchResult.flowCode || "-",
|
||||
"实例 ID (jobId)": job.id,
|
||||
"运行状态 (status)": job.status || "-",
|
||||
"提交人": job.inputs?.userInfo?.name || "-",
|
||||
"创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-",
|
||||
}),
|
||||
"",
|
||||
`提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
|
||||
@@ -17,6 +17,8 @@ import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import { handleWorkflowLink } from "./link.js";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -126,11 +128,16 @@ export async function handleWorkflowCommand(
|
||||
case "url":
|
||||
case "web":
|
||||
return handleWorkflowLink(parsed, runtime);
|
||||
case "outbound":
|
||||
case "outbounds":
|
||||
case "outbound-message":
|
||||
return handleOutboundCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link, outbound\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { getWorkflowAvailableNodes, grantWorkflowNodes } from "../../../domains/platform/workflow/services.js";
|
||||
import { GRAY_NODES_CATALOG, findGrayNode } from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { getWorkflowAvailableNodes, grantWorkflowNodes, GRANT_ATTACHED_OPTIONS } from "../../../domains/platform/workflow/services.js";
|
||||
import { GRAY_NODES_CATALOG, normalizeGrayNodes } from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { isCorpProd } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -19,7 +20,7 @@ export async function handleListAvailableNodes(
|
||||
|
||||
const showAll = Boolean(parsed.options.all || parsed.options.compare || parsed.options.diff);
|
||||
const filterKw = (
|
||||
parsed.args[1] ||
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["keyword", "query", "filter"]) ||
|
||||
""
|
||||
).toLowerCase();
|
||||
@@ -112,18 +113,43 @@ export async function handleGrantNodes(
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
|
||||
// 生产环境硬拦截:灰度节点开通属于不可逆企业级写操作,本项目禁止对生产企业执行。
|
||||
// 与 workflow/test.ts 的调试阻断不同,这里不提供 --force 逃生口。
|
||||
if (isCorpProd(corp)) {
|
||||
return {
|
||||
stdout: runtime.jsonMode
|
||||
? printJson({ error: true, code: "PROD_GRANT_BLOCKED", message: "禁止对正式生产企业开通灰度节点" }) + "\n"
|
||||
: "",
|
||||
stderr: runtime.jsonMode
|
||||
? ""
|
||||
: [
|
||||
"🛑 生产环境安全阻断 (Production Safeguard):",
|
||||
`当前工作企业 [${corp.name || corp.id}] 被判定为【正式生产环境】。`,
|
||||
"灰度节点开通是不可逆的企业级写操作,本项目禁止对生产企业执行,且未提供 --force 逃生口。",
|
||||
"",
|
||||
"请切换到测试企业后重试:",
|
||||
" hose-use corps switch <测试企业ID>",
|
||||
"若企业环境标记有误,请检查 ~/.config/hose-use/enterprises/ 下的 env / isTest 字段。",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const rawNodes = parsed.args.slice(1);
|
||||
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
|
||||
const targetNodes: string[] = [];
|
||||
const collected: string[] = [];
|
||||
|
||||
if (optionNodes) {
|
||||
targetNodes.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
collected.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
for (const arg of rawNodes) {
|
||||
if (arg && !arg.startsWith("-")) {
|
||||
targetNodes.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
collected.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
}
|
||||
// 去重,避免同一节点被重复提交;不做白名单硬校验(灰度清单不是全集)。
|
||||
const targetNodes = Array.from(new Set(collected));
|
||||
|
||||
if (targetNodes.length === 0) {
|
||||
return {
|
||||
@@ -134,9 +160,12 @@ export async function handleGrantNodes(
|
||||
}
|
||||
|
||||
requireMutationConfirmation(parsed, runtime, "开通企业工作流灰度节点", "hose-use workflow nodes grant <type...> --yes");
|
||||
const isTest = booleanOption(parsed.options, ["is-test"]);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
|
||||
nodes: targetNodes.map(node => findGrayNode(node)?.type || node.trim()),
|
||||
nodes: normalizeGrayNodes(targetNodes),
|
||||
isTest,
|
||||
attachedOptions: GRANT_ATTACHED_OPTIONS,
|
||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||
});
|
||||
}
|
||||
@@ -146,6 +175,7 @@ export async function handleGrantNodes(
|
||||
const result = await grantWorkflowNodes(corp, {
|
||||
nodes: targetNodes,
|
||||
password,
|
||||
isTest,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -156,16 +186,18 @@ export async function handleGrantNodes(
|
||||
};
|
||||
}
|
||||
if (!result.success) {
|
||||
return { stdout: "", stderr: `灰度节点开通失败: ${result.rawMessage || "网关拒绝了开通请求"}\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `灰度节点开通失败: ${result.rawMessage || "Piper 拒绝了开通请求"}\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"申请开通节点": targetNodes.join(", "),
|
||||
"Piper 环境": result.isTest ? "测试 Piper" : "标准 Piper",
|
||||
"新开通成功": result.saved.length ? result.saved.join(", ") : "无 (已处于开通状态)",
|
||||
"跳过(已开通)": result.skipped.length ? result.skipped.join(", ") : "无",
|
||||
"网关反馈": result.rawMessage || "处理成功",
|
||||
"附带固定开关": Object.keys(GRANT_ATTACHED_OPTIONS).join(", "),
|
||||
"Piper 反馈": result.rawMessage || "处理成功",
|
||||
}),
|
||||
"",
|
||||
"✅ 节点权限已生效!工作流设计器与 hose-use workflow analyze 将立即支持该节点。",
|
||||
|
||||
@@ -27,7 +27,6 @@ async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0],
|
||||
}
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -89,12 +88,13 @@ export async function handleNodeCommand(
|
||||
"",
|
||||
"子命令 (企业灰度节点级别):",
|
||||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||||
" nodes grant <type...> 为当前企业开通灰度节点",
|
||||
" nodes grant <type...> [--is-test] 为当前企业开通灰度节点(标准/测试 Piper 二选一)",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow nodes",
|
||||
" hose-use workflow nodes --all",
|
||||
" hose-use workflow nodes grant code-js2",
|
||||
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
|
||||
" hose-use workflow node list 896398895352487950",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
describe("handleOutboundCommand", () => {
|
||||
it("rejects when no corp selected", async () => {
|
||||
const result = await handleOutboundCommand(
|
||||
{ args: ["list"], options: {}, raw: [] },
|
||||
{ selectedCorp: null, jsonMode: false } as unknown as CliRuntime
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未选中企业");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { stringOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { getOutboundMessages, queryOutboundMessageLogs } from "../../../domains/platform/workflow/services.js";
|
||||
|
||||
function formatTime(timestamp: number | undefined): string {
|
||||
if (!timestamp) return "-";
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
export async function handleOutboundCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const sub = parsed.args[0] || "list";
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
|
||||
if (sub === "list" || sub === "rules") {
|
||||
const rules = await getOutboundMessages(client, corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corpId, total: rules.length, items: rules }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "规则名称", "类型", "状态", "目标回调 URL", "监听事件"];
|
||||
const rows = rules.map((r, i) => [
|
||||
String(i + 1),
|
||||
r.messageName || "-",
|
||||
r.messageType || "-",
|
||||
r.enable ? "🟢 启用" : "⚪ 停用",
|
||||
r.callbackUrl || "-",
|
||||
r.actionEvent && r.actionEvent.length ? r.actionEvent.join(", ") : "全部/默认",
|
||||
]);
|
||||
|
||||
const title = `====== [${corp.name}] 出站消息规则列表 (共 ${rules.length} 条) ======\n`;
|
||||
return {
|
||||
stdout: title + (rules.length ? printTable(headers, rows) : " (暂无配置)\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (sub === "logs" || sub === "log") {
|
||||
const code = stringOption(parsed.options, ["code", "sn", "flow", "bill"]) || (parsed.args[1] && !parsed.args[1].startsWith("-") ? parsed.args[1] : undefined);
|
||||
const messageType = stringOption(parsed.options, ["type", "message-type"]) || "flow";
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||
|
||||
const result = await queryOutboundMessageLogs(client, corpId, {
|
||||
messageType,
|
||||
code,
|
||||
start,
|
||||
count,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corpId, code, total: result.count, items: result.items }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单号", "规则名", "动作/阶段", "状态", "投递时间", "目标 URL / 响应详情"];
|
||||
const rows = result.items.map((item, i) => {
|
||||
const sn = item.flowId?.form?.code || item.request?.code || "-";
|
||||
const statusIcon = item.state === "SUCCESS" ? "✅ 成功" : item.state === "FAILED" ? "❌ 失败" : item.state;
|
||||
const respPreview = typeof item.response === "object" && item.response !== null
|
||||
? JSON.stringify(item.response).slice(0, 60)
|
||||
: String(item.response ?? "-").slice(0, 60);
|
||||
|
||||
return [
|
||||
String(i + 1),
|
||||
sn,
|
||||
item.name || "-",
|
||||
`${item.type} (${item.nodeName || "-"})`,
|
||||
statusIcon,
|
||||
formatTime(item.createTime),
|
||||
respPreview,
|
||||
];
|
||||
});
|
||||
|
||||
const filterDesc = code ? ` | 单号筛选: ${code}` : "";
|
||||
const title = `====== [${corp.name}] 出站消息投递日志 (类型: ${messageType}${filterDesc} | 匹配: ${result.count} | 返回: ${result.items.length}) ======\n`;
|
||||
return {
|
||||
stdout: title + (result.items.length ? printTable(headers, rows) : " (暂无匹配日志)\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 outbound 子命令: ${sub}。支持: list (别名: rules), logs [单号] [--type=flow|message]\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js";
|
||||
import { handleDocsCommand } from "./commands/docs.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
@@ -206,6 +207,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
...COMMAND_METADATA["assist-platform"],
|
||||
handler: (parsed, runtime) => handleAssistPlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "docs",
|
||||
...COMMAND_METADATA.docs,
|
||||
handler: (parsed, runtime) => handleDocsCommand(parsed, runtime),
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||
|
||||
@@ -162,6 +162,7 @@ async function dispatchParsedCli(
|
||||
launcher: options.launcher,
|
||||
});
|
||||
runtime.writeStdout = options.writeStdout;
|
||||
runtime.app = "hose-use";
|
||||
|
||||
try {
|
||||
if (!parsed.area) {
|
||||
|
||||
@@ -44,6 +44,8 @@ export interface CliRuntime {
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
/** 入口身份,由 runCli / runAiProCli 显式标注,供命令层区分 multicall 调用方。 */
|
||||
app?: "hose-use" | "hose-aipro";
|
||||
launcher?: {
|
||||
command: string;
|
||||
args?: string[];
|
||||
|
||||
@@ -28,8 +28,9 @@ src/core/
|
||||
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
||||
│ └── types.ts
|
||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ ├── workflow-job-cache.ts # 工作流 Job 索引缓存与单据触发单号秒级检索
|
||||
│ └── types.ts
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
expect(tableNames.has("observed_events")).toBe(true);
|
||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||
expect(tableNames.has("workflow_job_index")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
@@ -55,6 +56,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_wf_jobs_corp_pipeline_code")).toBe(true);
|
||||
expect(indexNames.has("idx_wf_jobs_code_upper")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./types.js";
|
||||
export * from "./connection.js";
|
||||
export * from "./migrations.js";
|
||||
export * from "./workflow-job-cache.js";
|
||||
@@ -242,6 +242,30 @@ export const migrations: DatabaseMigration[] = [
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 5,
|
||||
name: "005_workflow_job_cache",
|
||||
up(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS workflow_job_index (
|
||||
corp_id TEXT NOT NULL,
|
||||
pipeline_id TEXT NOT NULL,
|
||||
job_id TEXT NOT NULL,
|
||||
flow_code TEXT,
|
||||
flow_id TEXT,
|
||||
execute_time INTEGER,
|
||||
status TEXT,
|
||||
user_name TEXT,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (corp_id, pipeline_id, job_id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code ON workflow_job_index(corp_id, flow_code);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_pipeline ON workflow_job_index(corp_id, pipeline_id);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_corp_pipeline_code ON workflow_job_index(corp_id, pipeline_id, flow_code);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_wf_jobs_code_upper ON workflow_job_index(corp_id, pipeline_id, UPPER(flow_code));");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "./connection.js";
|
||||
import {
|
||||
getCachedWorkflowJobByCode,
|
||||
upsertWorkflowJobIndex,
|
||||
type WorkflowJobCacheRecord,
|
||||
} from "./workflow-job-cache.js";
|
||||
|
||||
describe("Core DB - Workflow Job 本地缓存与索引检索 (workflow_job_index)", () => {
|
||||
let db: Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
test("批量插入 Job 缓存并支持单号精准与大小写不敏感检索", () => {
|
||||
const records: WorkflowJobCacheRecord[] = [
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
flowCode: "XZ2610474",
|
||||
flowId: "flow_abc",
|
||||
executeTime: 1700000000000,
|
||||
status: "COMPLETED",
|
||||
userName: "欧阳亚玲",
|
||||
},
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_002",
|
||||
flowCode: "XZ2610475",
|
||||
status: "RUNNING",
|
||||
},
|
||||
];
|
||||
|
||||
upsertWorkflowJobIndex(records, ":memory:");
|
||||
|
||||
// 精确匹配
|
||||
const hitExact = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hitExact).not.toBeNull();
|
||||
expect(hitExact?.jobId).toBe("job_001");
|
||||
expect(hitExact?.userName).toBe("欧阳亚玲");
|
||||
expect(hitExact?.status).toBe("COMPLETED");
|
||||
|
||||
// 小写模糊匹配
|
||||
const hitLower = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "xz2610474", ":memory:");
|
||||
expect(hitLower).not.toBeNull();
|
||||
expect(hitLower?.jobId).toBe("job_001");
|
||||
|
||||
// 不存在的单号或不同企业/工作流应返回 null
|
||||
expect(getCachedWorkflowJobByCode("corp_winner", "pipe_101", "NON_EXISTENT", ":memory:")).toBeNull();
|
||||
expect(getCachedWorkflowJobByCode("other_corp", "pipe_101", "XZ2610474", ":memory:")).toBeNull();
|
||||
expect(getCachedWorkflowJobByCode("corp_winner", "other_pipe", "XZ2610474", ":memory:")).toBeNull();
|
||||
});
|
||||
|
||||
test("同单号存在多笔记录时,按 execute_time DESC 优先返回最新执行的一笔", () => {
|
||||
const records: WorkflowJobCacheRecord[] = [
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_old",
|
||||
flowCode: "XZ2610474",
|
||||
executeTime: 1000,
|
||||
status: "FAILED",
|
||||
},
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_new",
|
||||
flowCode: "XZ2610474",
|
||||
executeTime: 2000,
|
||||
status: "COMPLETED",
|
||||
},
|
||||
];
|
||||
|
||||
upsertWorkflowJobIndex(records, ":memory:");
|
||||
|
||||
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit?.jobId).toBe("job_new");
|
||||
expect(hit?.status).toBe("COMPLETED");
|
||||
});
|
||||
|
||||
test("相同主键冲突时,执行增量更新并保持已有非空字段 (COALESCE)", () => {
|
||||
upsertWorkflowJobIndex(
|
||||
[
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
flowCode: "XZ2610474",
|
||||
userName: "欧阳亚玲",
|
||||
status: "RUNNING",
|
||||
executeTime: 1000,
|
||||
},
|
||||
],
|
||||
":memory:"
|
||||
);
|
||||
|
||||
// 再次写入,只更新 status,未传 userName
|
||||
upsertWorkflowJobIndex(
|
||||
[
|
||||
{
|
||||
corpId: "corp_winner",
|
||||
pipelineId: "pipe_101",
|
||||
jobId: "job_001",
|
||||
status: "COMPLETED",
|
||||
},
|
||||
],
|
||||
":memory:"
|
||||
);
|
||||
|
||||
const hit = getCachedWorkflowJobByCode("corp_winner", "pipe_101", "XZ2610474", ":memory:");
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit?.jobId).toBe("job_001");
|
||||
expect(hit?.status).toBe("COMPLETED");
|
||||
// userName 依然保留
|
||||
expect(hit?.userName).toBe("欧阳亚玲");
|
||||
});
|
||||
|
||||
test("空数组调用 upsert 不抛异常", () => {
|
||||
expect(() => upsertWorkflowJobIndex([], ":memory:")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { getDatabase } from "./connection.js";
|
||||
|
||||
export interface WorkflowJobCacheRecord {
|
||||
corpId: string;
|
||||
pipelineId: string;
|
||||
jobId: string;
|
||||
flowCode?: string;
|
||||
flowId?: string;
|
||||
executeTime?: number;
|
||||
status?: string;
|
||||
userName?: string;
|
||||
updatedAt?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按企业 + 工作流 + 单号快速从本地 SQLite 缓存中检索匹配的 Job 记录
|
||||
*/
|
||||
export function getCachedWorkflowJobByCode(
|
||||
corpId: string,
|
||||
pipelineId: string,
|
||||
flowCode: string,
|
||||
dbPath?: string
|
||||
): WorkflowJobCacheRecord | null {
|
||||
const db = getDatabase(dbPath);
|
||||
const normalizedCode = flowCode.trim();
|
||||
const row = db
|
||||
.query(
|
||||
`SELECT corp_id AS corpId, pipeline_id AS pipelineId, job_id AS jobId,
|
||||
flow_code AS flowCode, flow_id AS flowId, execute_time AS executeTime,
|
||||
status, user_name AS userName, updated_at AS updatedAt
|
||||
FROM workflow_job_index
|
||||
WHERE corp_id = ? AND pipeline_id = ? AND (flow_code = ? OR UPPER(flow_code) = UPPER(?))
|
||||
ORDER BY execute_time DESC, updated_at DESC
|
||||
LIMIT 1`
|
||||
)
|
||||
.get(corpId, pipelineId, normalizedCode, normalizedCode) as WorkflowJobCacheRecord | null;
|
||||
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新 Job 缓存索引
|
||||
*/
|
||||
export function upsertWorkflowJobIndex(
|
||||
records: WorkflowJobCacheRecord[],
|
||||
dbPath?: string
|
||||
): void {
|
||||
if (!records.length) return;
|
||||
const db = getDatabase(dbPath);
|
||||
const now = Date.now();
|
||||
|
||||
const insertStmt = db.prepare(`
|
||||
INSERT INTO workflow_job_index (
|
||||
corp_id, pipeline_id, job_id, flow_code, flow_id, execute_time, status, user_name, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(corp_id, pipeline_id, job_id) DO UPDATE SET
|
||||
flow_code = COALESCE(excluded.flow_code, workflow_job_index.flow_code),
|
||||
flow_id = COALESCE(excluded.flow_id, workflow_job_index.flow_id),
|
||||
execute_time = COALESCE(excluded.execute_time, workflow_job_index.execute_time),
|
||||
status = COALESCE(excluded.status, workflow_job_index.status),
|
||||
user_name = COALESCE(excluded.user_name, workflow_job_index.user_name),
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const r of records) {
|
||||
insertStmt.run(
|
||||
r.corpId,
|
||||
r.pipelineId,
|
||||
r.jobId,
|
||||
r.flowCode || null,
|
||||
r.flowId || null,
|
||||
r.executeTime || null,
|
||||
r.status || null,
|
||||
r.userName || null,
|
||||
now
|
||||
);
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { resolvePiperBaseUrl } from "./piper-endpoints.js";
|
||||
|
||||
const KEYS = ["HOSE_PIPER_BASE_URL", "HOSE_PIPER_TEST_BASE_URL"] as const;
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of KEYS) delete process.env[key];
|
||||
});
|
||||
|
||||
describe("Piper 集群地址", () => {
|
||||
test("未设置环境变量时使用默认地址", () => {
|
||||
expect(resolvePiperBaseUrl()).toBe("https://piper.ekuaibao.com");
|
||||
expect(resolvePiperBaseUrl(true)).toBe("https://piper-test.ekuaibao.net");
|
||||
});
|
||||
|
||||
test("HOSE_PIPER_BASE_URL 覆盖标准集群并去掉尾部斜线", () => {
|
||||
process.env.HOSE_PIPER_BASE_URL = "https://piper.internal.example///";
|
||||
expect(resolvePiperBaseUrl()).toBe("https://piper.internal.example");
|
||||
expect(resolvePiperBaseUrl(true)).toBe("https://piper-test.ekuaibao.net");
|
||||
});
|
||||
|
||||
test("HOSE_PIPER_TEST_BASE_URL 只覆盖测试集群", () => {
|
||||
process.env.HOSE_PIPER_TEST_BASE_URL = "https://piper-test.internal.example/";
|
||||
expect(resolvePiperBaseUrl(true)).toBe("https://piper-test.internal.example");
|
||||
expect(resolvePiperBaseUrl()).toBe("https://piper.ekuaibao.com");
|
||||
});
|
||||
|
||||
test("空白值回退默认", () => {
|
||||
process.env.HOSE_PIPER_BASE_URL = " ";
|
||||
expect(resolvePiperBaseUrl()).toBe("https://piper.ekuaibao.com");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Piper / ScriptEngine 集群地址收口。
|
||||
*
|
||||
* 保持轻量(不依赖 ky、不触发网络),供 core、domains 各层共用。
|
||||
* 旧版 HOSE_GRAY_GATEWAY_URL 逃生口在 e562ae9 移除后一直缺位,这里补齐。
|
||||
*/
|
||||
const DEFAULT_PIPER_BASE_URL = "https://piper.ekuaibao.com";
|
||||
const DEFAULT_PIPER_TEST_BASE_URL = "https://piper-test.ekuaibao.net";
|
||||
|
||||
function envBaseUrl(value: string | undefined, fallback: string): string {
|
||||
const normalized = value?.trim().replace(/\/+$/, "");
|
||||
return normalized || fallback;
|
||||
}
|
||||
|
||||
/** 运行时解析,每次读取环境变量,便于私有化/多集群部署与测试覆盖。 */
|
||||
export function resolvePiperBaseUrl(isTest = false): string {
|
||||
return isTest
|
||||
? envBaseUrl(process.env.HOSE_PIPER_TEST_BASE_URL, DEFAULT_PIPER_TEST_BASE_URL)
|
||||
: envBaseUrl(process.env.HOSE_PIPER_BASE_URL, DEFAULT_PIPER_BASE_URL);
|
||||
}
|
||||
|
||||
/** 兼容历史常量导入;值为进程启动时的解析结果。 */
|
||||
export const SCRIPT_ENGINE_BASE_URL = resolvePiperBaseUrl(false);
|
||||
export const SCRIPT_ENGINE_TEST_BASE_URL = resolvePiperBaseUrl(true);
|
||||
@@ -16,7 +16,17 @@ import {
|
||||
setCorpTokens,
|
||||
} from "../auth/token-store.js";
|
||||
|
||||
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
|
||||
import {
|
||||
resolvePiperBaseUrl,
|
||||
SCRIPT_ENGINE_BASE_URL,
|
||||
SCRIPT_ENGINE_TEST_BASE_URL,
|
||||
} from "./piper-endpoints.js";
|
||||
|
||||
export {
|
||||
resolvePiperBaseUrl,
|
||||
SCRIPT_ENGINE_BASE_URL,
|
||||
SCRIPT_ENGINE_TEST_BASE_URL,
|
||||
} from "./piper-endpoints.js";
|
||||
|
||||
// 兼容历史常量名
|
||||
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
||||
@@ -117,7 +127,7 @@ export async function getScriptEngineClient(
|
||||
const cachedJwt = mem.jwt;
|
||||
const cachedHoseToken = mem.hoseToken;
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
prefixUrl: resolvePiperBaseUrl(),
|
||||
getHeaders: () => {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域(共 14 个)
|
||||
## 当前域(共 15 个)
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
@@ -20,10 +20,11 @@
|
||||
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | [README.message.md](./message/README.message.md) |
|
||||
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | [README.task.md](./task/README.task.md) |
|
||||
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | [README.events.md](./events/README.events.md) |
|
||||
| `docs/` | `api / tools / types` | 合思开放平台官方文档中心(270+ API 端点)在线实时拉取、离线缓存与参数规格检索 | [README.docs.md](./docs/README.docs.md) |
|
||||
|
||||
## 分层与形态规则
|
||||
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `docs`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
||||
- `types.ts`:Zod schema 与类型定义
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Docs 开放平台文档域说明
|
||||
|
||||
本域提供合思/易快报开放平台官方文档中心(`docs.ekuaibao.com`)全量 API 规范、请求方法、URL 路径、参数表格、CURL 示例与响应 JSON 的结构化离线/在线检索与详情提取能力。
|
||||
|
||||
## 架构
|
||||
|
||||
- `api.ts`:传输层,负责实时拉取线上 `https://docs.ekuaibao.com/search-index.json` 并解析出包含 270+ 接口的结构化目录(DocCatalog)。
|
||||
- `tools.ts`:业务层,提供多级缓存(L1 内存 + L2 SQLite + `specs/docs-catalog.json` 静态预编译保底)、关键词评分加权检索、按 URL/Path/标题精确解析文档详情及业务模块分类汇总。
|
||||
- `types.ts`:Zod 模式与 TypeScript 类型定义(`OpenApiDocItem`, `DocCatalog`, `DocSearchQuery`, `DocSearchResult`)。
|
||||
|
||||
## 核心接口
|
||||
|
||||
- `searchDocs(query, options)`: 按关键词、分类(`category`)、HTTP 方法(`method`)与接口路径(`path`)智能打分检索
|
||||
- `getDocDetail(target, options)`: 快速按 ID、Path、URL 或中文标题检索出完整的接口定义
|
||||
- `listCategories(options)`: 汇总开放平台 26+ 个业务分类及对应的文档和端点总数
|
||||
- `syncDocsCatalog(options)`: 强制与线上文档站点执行全量同步并更新本地缓存
|
||||
@@ -0,0 +1,181 @@
|
||||
import ky from "ky";
|
||||
import { EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
DocCatalogSchema,
|
||||
type DocCatalog,
|
||||
type OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
export const DEFAULT_DOCS_BASE_URL = "https://docs.ekuaibao.com";
|
||||
|
||||
interface RawSearchDoc {
|
||||
i: number;
|
||||
t: string;
|
||||
u: string;
|
||||
b?: string[];
|
||||
h?: string;
|
||||
p?: number;
|
||||
s?: string;
|
||||
}
|
||||
|
||||
interface RawSearchSection {
|
||||
documents?: RawSearchDoc[];
|
||||
index?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function parseRawSearchIndexToCatalog(
|
||||
rawSections: RawSearchSection[],
|
||||
baseUrl = DEFAULT_DOCS_BASE_URL
|
||||
): DocCatalog {
|
||||
const rawDocs = rawSections[0]?.documents || [];
|
||||
const rawHeadings = rawSections[1]?.documents || [];
|
||||
const rawParagraphs = rawSections[2]?.documents || [];
|
||||
|
||||
const apiDocs = rawDocs.filter((d) => d.u?.startsWith("/docs/open-api/"));
|
||||
const items: OpenApiDocItem[] = [];
|
||||
|
||||
for (const doc of apiDocs) {
|
||||
const headings = rawHeadings
|
||||
.filter((h) => h.p === doc.i)
|
||||
.map((h) => h.t)
|
||||
.filter(Boolean);
|
||||
const paragraphs = rawParagraphs.filter((p) => p.p === doc.i);
|
||||
|
||||
let method: string | undefined;
|
||||
let path: string | undefined;
|
||||
let curl: string | undefined;
|
||||
let responseSample: string | undefined;
|
||||
let parameters: string | undefined;
|
||||
const sections: Array<{ title: string; content: string }> = [];
|
||||
|
||||
for (const p of paragraphs) {
|
||||
const sectionTitle = p.s || "概述";
|
||||
const text = (p.t || "").trim();
|
||||
if (!text) continue;
|
||||
|
||||
// Extract HTTP method and path from paragraph text
|
||||
if (!method || !path) {
|
||||
const methodMatch = text.match(
|
||||
/\b(GET|POST|PUT|DELETE|PATCH)\s*(\/api\/[^\s]+)/i
|
||||
);
|
||||
if (methodMatch) {
|
||||
method = methodMatch[1].toUpperCase();
|
||||
path = methodMatch[2];
|
||||
}
|
||||
}
|
||||
|
||||
// Extract CURL
|
||||
if (
|
||||
sectionTitle === "CURL" ||
|
||||
text.startsWith("curl ") ||
|
||||
text.includes("curl --location")
|
||||
) {
|
||||
curl = text;
|
||||
// Fallback method/path extraction from curl if not found yet
|
||||
if (!method || !path) {
|
||||
const curlMatch = text.match(
|
||||
/--request\s+(GET|POST|PUT|DELETE|PATCH)\s+['"][^'"]*?(\/api\/[^?'"\s]+)/i
|
||||
);
|
||||
if (curlMatch) {
|
||||
method = curlMatch[1].toUpperCase();
|
||||
path = curlMatch[2];
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
sectionTitle === "成功响应" ||
|
||||
sectionTitle === "Response" ||
|
||||
(text.startsWith("{") && text.endsWith("}"))
|
||||
) {
|
||||
responseSample = text;
|
||||
} else if (
|
||||
sectionTitle.includes("Parameter") ||
|
||||
sectionTitle.includes("参数") ||
|
||||
sectionTitle.includes("Body")
|
||||
) {
|
||||
parameters = parameters ? `${parameters}\n${text}` : text;
|
||||
}
|
||||
|
||||
sections.push({
|
||||
title: sectionTitle,
|
||||
content: text,
|
||||
});
|
||||
}
|
||||
|
||||
const category = doc.b?.[1] || "未分类";
|
||||
const cleanUrl = doc.u || "";
|
||||
|
||||
items.push({
|
||||
id: doc.i,
|
||||
title: doc.t || "未命名文档",
|
||||
category,
|
||||
url: cleanUrl,
|
||||
permalink: `${baseUrl.replace(/\/+$/, "")}${cleanUrl}`,
|
||||
method,
|
||||
path,
|
||||
breadcrumbs: doc.b || [],
|
||||
headings,
|
||||
sections,
|
||||
parameters,
|
||||
curl,
|
||||
responseSample,
|
||||
});
|
||||
}
|
||||
|
||||
const catalog: DocCatalog = {
|
||||
version: "1.0.0",
|
||||
updatedAt: new Date().toISOString(),
|
||||
sourceUrl: `${baseUrl.replace(/\/+$/, "")}/search-index.json`,
|
||||
totalDocs: items.length,
|
||||
totalEndpoints: items.filter((i) => i.method && i.path).length,
|
||||
items,
|
||||
};
|
||||
|
||||
return DocCatalogSchema.parse(catalog);
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时从线上文档站点获取最新接口定义索引
|
||||
*/
|
||||
export async function fetchLiveDocsCatalog(options?: {
|
||||
baseUrl?: string;
|
||||
timeoutMs?: number;
|
||||
}): Promise<DocCatalog> {
|
||||
const baseUrl = options?.baseUrl || DEFAULT_DOCS_BASE_URL;
|
||||
const timeoutMs = options?.timeoutMs ?? 15000;
|
||||
const targetUrl = `${baseUrl.replace(/\/+$/, "")}/search-index.json`;
|
||||
|
||||
try {
|
||||
const response = await ky.get(targetUrl, {
|
||||
timeout: timeoutMs,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "hose-use/docs-client",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new EkbApiError(
|
||||
`获取开放平台文档索引失败: HTTP ${response.status}`,
|
||||
"DOCS_FETCH_FAILED",
|
||||
response.status
|
||||
);
|
||||
}
|
||||
|
||||
const raw = (await response.json()) as RawSearchSection[];
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new EkbApiError(
|
||||
"开放平台文档索引数据异常: 返回格式不是有效的分区数组",
|
||||
"DOCS_INVALID_DATA"
|
||||
);
|
||||
}
|
||||
|
||||
return parseRawSearchIndexToCatalog(raw, baseUrl);
|
||||
} catch (error: any) {
|
||||
if (error instanceof EkbApiError) throw error;
|
||||
throw new EkbApiError(
|
||||
`请求开放平台文档站点 (${targetUrl}) 失败: ${error?.message || String(error)}`,
|
||||
"DOCS_NETWORK_ERROR",
|
||||
502
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { parseRawSearchIndexToCatalog } from "./api.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
} from "./tools.js";
|
||||
|
||||
const mockRawSections = [
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 1001,
|
||||
t: "查询角色组和角色",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
b: ["Open API", "企业通讯录"],
|
||||
},
|
||||
{
|
||||
i: 1002,
|
||||
t: "下载附件",
|
||||
u: "/docs/open-api/attachment/attachment-download",
|
||||
b: ["Open API", "附件"],
|
||||
},
|
||||
{
|
||||
i: 1003,
|
||||
t: "其他非 API 页面",
|
||||
u: "/blog/archive",
|
||||
b: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 2001,
|
||||
t: "Query Parameters",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#query-parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 2002,
|
||||
t: "CURL",
|
||||
u: "/docs/open-api/corporation/get-roles-group",
|
||||
h: "#curl",
|
||||
p: 1001,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
documents: [
|
||||
{
|
||||
i: 3001,
|
||||
t: "GET /api/openapi/v1/roleDefGroups 更新日志 0.7.135 🆕 新增了本接口。",
|
||||
s: "查询角色组和角色",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3002,
|
||||
t: "accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken",
|
||||
s: "Query Parameters",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3003,
|
||||
t: "curl --location --request GET 'https://app.ekuaibao.com/api/openapi/v1/roleDefGroups?accessToken=TOKEN'",
|
||||
s: "CURL",
|
||||
p: 1001,
|
||||
},
|
||||
{
|
||||
i: 3004,
|
||||
t: "POST /api/openapi/v2/attachment/downloadurls",
|
||||
s: "下载附件",
|
||||
p: 1002,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("Docs Domain - 开放平台文档域", () => {
|
||||
it("parseRawSearchIndexToCatalog 正确解析原始搜索索引并提取 HTTP 属性", () => {
|
||||
const catalog = parseRawSearchIndexToCatalog(mockRawSections as any);
|
||||
expect(catalog.totalDocs).toBe(2);
|
||||
expect(catalog.totalEndpoints).toBe(2);
|
||||
|
||||
const roleGroupDoc = catalog.items.find((i) => i.id === 1001);
|
||||
expect(roleGroupDoc).toBeDefined();
|
||||
expect(roleGroupDoc?.title).toBe("查询角色组和角色");
|
||||
expect(roleGroupDoc?.category).toBe("企业通讯录");
|
||||
expect(roleGroupDoc?.method).toBe("GET");
|
||||
expect(roleGroupDoc?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.curl).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(roleGroupDoc?.parameters).toContain("accessToken");
|
||||
|
||||
const attachmentDoc = catalog.items.find((i) => i.id === 1002);
|
||||
expect(attachmentDoc?.method).toBe("POST");
|
||||
expect(attachmentDoc?.path).toBe("/api/openapi/v2/attachment/downloadurls");
|
||||
});
|
||||
|
||||
it("getDocsCatalog 在测试环境中能安全加载预编译/内嵌规格", async () => {
|
||||
const catalog = await getDocsCatalog();
|
||||
expect(catalog.items.length).toBeGreaterThan(100);
|
||||
expect(catalog.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("searchDocs 按关键词检索接口并正确排序", async () => {
|
||||
const res = await searchDocs({ keyword: "roleDefGroups" });
|
||||
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||
expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.items[0]?.title).toBe("查询角色组和角色");
|
||||
expect(res.items[0]?.matchReason).toBeDefined();
|
||||
});
|
||||
|
||||
it("searchDocs 支持多词分词与跨正文/参数模糊检索", async () => {
|
||||
const res = await searchDocs({ keyword: "员工 手机" });
|
||||
expect(res.total).toBeGreaterThanOrEqual(1);
|
||||
expect(res.items.some((i) => i.title.includes("员工"))).toBe(true);
|
||||
expect(res.items[0]?.matchReason).toBeDefined();
|
||||
});
|
||||
|
||||
it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => {
|
||||
const res = await searchDocs({
|
||||
category: "企业通讯录",
|
||||
method: "GET",
|
||||
});
|
||||
expect(res.items.length).toBeGreaterThanOrEqual(1);
|
||||
for (const item of res.items) {
|
||||
expect(item.category).toBe("企业通讯录");
|
||||
expect(item.method).toBe("GET");
|
||||
}
|
||||
});
|
||||
|
||||
it("getDocDetail 能按路径、URL、标题或 ID 精准定位文档", async () => {
|
||||
const byPath = await getDocDetail("/api/openapi/v1/roleDefGroups");
|
||||
expect(byPath).toBeDefined();
|
||||
expect(byPath?.title).toBe("查询角色组和角色");
|
||||
|
||||
const byUrl = await getDocDetail("/docs/open-api/corporation/get-roles-group");
|
||||
expect(byUrl).toBeDefined();
|
||||
expect(byUrl?.id).toBe(byPath?.id);
|
||||
|
||||
const byTitle = await getDocDetail("查询角色组和角色");
|
||||
expect(byTitle?.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
|
||||
it("listCategories 能够统计分类列表与端点总数", async () => {
|
||||
const cats = await listCategories();
|
||||
expect(cats.length).toBeGreaterThanOrEqual(10);
|
||||
const corpCat = cats.find((c) => c.name === "企业通讯录");
|
||||
expect(corpCat).toBeDefined();
|
||||
expect(corpCat?.count).toBeGreaterThan(0);
|
||||
expect(corpCat?.endpointsCount).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import embeddedCatalog from "../../../specs/docs-catalog.json" with { type: "json" };
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { fetchLiveDocsCatalog } from "./api.js";
|
||||
import type {
|
||||
DocCatalog,
|
||||
DocCategoryInfo,
|
||||
DocSearchQuery,
|
||||
DocSearchResult,
|
||||
OpenApiDocItem,
|
||||
} from "./types.js";
|
||||
|
||||
const CACHE_KEY = "docs:catalog:v1";
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24小时缓存
|
||||
|
||||
/**
|
||||
* 获取接口文档目录(具备实时拉取 + L1/L2 缓存 + 静态内嵌保底能力)
|
||||
*/
|
||||
export async function getDocsCatalog(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCatalog> {
|
||||
const cache = getGlobalCache();
|
||||
|
||||
if (!options?.forceRefresh) {
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试从线上获取最新规范
|
||||
try {
|
||||
const liveCatalog = await fetchLiveDocsCatalog({ baseUrl: options?.baseUrl });
|
||||
cache.set(CACHE_KEY, liveCatalog, {
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
namespace: "docs",
|
||||
});
|
||||
return liveCatalog;
|
||||
} catch (error) {
|
||||
// 若强制刷新失败且存在历史缓存,则返回历史缓存
|
||||
const cached = cache.get<DocCatalog>(CACHE_KEY, "docs");
|
||||
if (cached && Array.isArray(cached.items) && cached.items.length > 0) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 线上无法连通且无历史缓存时,安全降级至本地内嵌预编译规格
|
||||
return embeddedCatalog as unknown as DocCatalog;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文档项与搜索关键词的相关度得分,并生成高亮命中摘要
|
||||
*/
|
||||
function evaluateDocMatch(
|
||||
item: OpenApiDocItem,
|
||||
rawKeyword: string
|
||||
): { item: OpenApiDocItem; score: number } | null {
|
||||
const queryLower = rawKeyword.trim().toLowerCase();
|
||||
if (!queryLower) return null;
|
||||
|
||||
const tokens = queryLower.split(/[\s,+/]+/).filter(Boolean);
|
||||
if (tokens.length === 0) return null;
|
||||
|
||||
let score = 0;
|
||||
const matchReasons: string[] = [];
|
||||
|
||||
const pathLower = (item.path || "").toLowerCase();
|
||||
const titleLower = item.title.toLowerCase();
|
||||
const categoryLower = item.category.toLowerCase();
|
||||
const paramLower = (item.parameters || "").toLowerCase();
|
||||
const curlLower = (item.curl || "").toLowerCase();
|
||||
const respLower = (item.responseSample || "").toLowerCase();
|
||||
const allSectionsText = item.sections.map((s) => s.content).join(" ");
|
||||
const sectionsLower = allSectionsText.toLowerCase();
|
||||
|
||||
// 1. 完整短语匹配加分 (Phrase match)
|
||||
if (queryLower.length > 1) {
|
||||
if (pathLower === queryLower) {
|
||||
score += 120;
|
||||
matchReasons.push("路径完全匹配");
|
||||
} else if (pathLower.includes(queryLower)) {
|
||||
score += 80;
|
||||
matchReasons.push(`路径包含 "${queryLower}"`);
|
||||
}
|
||||
|
||||
if (titleLower === queryLower) {
|
||||
score += 100;
|
||||
matchReasons.push("标题完全匹配");
|
||||
} else if (titleLower.includes(queryLower)) {
|
||||
score += 60;
|
||||
matchReasons.push(`标题包含 "${queryLower}"`);
|
||||
}
|
||||
|
||||
if (categoryLower.includes(queryLower)) {
|
||||
score += 40;
|
||||
matchReasons.push(`模块: ${item.category}`);
|
||||
}
|
||||
|
||||
if (paramLower.includes(queryLower)) {
|
||||
score += 45;
|
||||
const idx = paramLower.indexOf(queryLower);
|
||||
const snippet = (item.parameters || "")
|
||||
.substring(Math.max(0, idx - 12), Math.min(item.parameters?.length || 0, idx + 30))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`参数规格: ...${snippet}...`);
|
||||
}
|
||||
|
||||
if (sectionsLower.includes(queryLower)) {
|
||||
score += 35;
|
||||
const idx = sectionsLower.indexOf(queryLower);
|
||||
const snippet = allSectionsText
|
||||
.substring(Math.max(0, idx - 12), Math.min(allSectionsText.length, idx + 30))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`正文段落: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Token 分词逐项匹配 (Multi-token match)
|
||||
let tokensMatched = 0;
|
||||
for (const token of tokens) {
|
||||
let tokenMatched = false;
|
||||
|
||||
if (pathLower.includes(token)) {
|
||||
score += 30;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`路径含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (titleLower.includes(token)) {
|
||||
score += 25;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`标题含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (categoryLower.includes(token)) {
|
||||
score += 20;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`分类含 "${token}"`);
|
||||
}
|
||||
}
|
||||
if (paramLower.includes(token)) {
|
||||
score += 20;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
const idx = paramLower.indexOf(token);
|
||||
const snippet = (item.parameters || "")
|
||||
.substring(Math.max(0, idx - 10), Math.min(item.parameters?.length || 0, idx + 25))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`参数: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
if (sectionsLower.includes(token)) {
|
||||
score += 15;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
const idx = sectionsLower.indexOf(token);
|
||||
const snippet = allSectionsText
|
||||
.substring(Math.max(0, idx - 10), Math.min(allSectionsText.length, idx + 25))
|
||||
.replace(/\s+/g, " ");
|
||||
matchReasons.push(`正文: ...${snippet}...`);
|
||||
}
|
||||
}
|
||||
if (curlLower.includes(token) || respLower.includes(token)) {
|
||||
score += 15;
|
||||
tokenMatched = true;
|
||||
if (!matchReasons.some((r) => r.includes(token))) {
|
||||
matchReasons.push(`请求/响应含 "${token}"`);
|
||||
}
|
||||
}
|
||||
|
||||
if (tokenMatched) tokensMatched++;
|
||||
}
|
||||
|
||||
// 多词全部命中奖励 (All-tokens match bonus)
|
||||
if (tokens.length > 1 && tokensMatched === tokens.length) {
|
||||
score += 50;
|
||||
}
|
||||
|
||||
if (score <= 0 || tokensMatched === 0) return null;
|
||||
|
||||
const matchReason = matchReasons.slice(0, 2).join(" | ");
|
||||
return {
|
||||
item: {
|
||||
...item,
|
||||
matchReason,
|
||||
},
|
||||
score,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索开放平台接口与指南文档
|
||||
*/
|
||||
export async function searchDocs(
|
||||
query: DocSearchQuery = {},
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<DocSearchResult> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
let items = catalog.items;
|
||||
|
||||
// 1. 分类过滤
|
||||
if (query.category) {
|
||||
const catLower = query.category.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
item.category.toLowerCase().includes(catLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 2. HTTP 方法过滤
|
||||
if (query.method) {
|
||||
const methodUpper = query.method.trim().toUpperCase();
|
||||
items = items.filter((item) => item.method === methodUpper);
|
||||
}
|
||||
|
||||
// 3. 接口路径匹配过滤
|
||||
if (query.path) {
|
||||
const pathLower = query.path.trim().toLowerCase();
|
||||
items = items.filter((item) =>
|
||||
(item.path || "").toLowerCase().includes(pathLower)
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 关键词打分与排序
|
||||
const rawKeyword = query.keyword?.trim();
|
||||
if (rawKeyword) {
|
||||
const scored = items
|
||||
.map((item) => evaluateDocMatch(item, rawKeyword))
|
||||
.filter((entry): entry is { item: OpenApiDocItem; score: number } => entry !== null)
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
items = scored.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
const total = items.length;
|
||||
const limit = Math.max(1, Math.min(query.limit ?? 20, 100));
|
||||
const pagedItems = items.slice(0, limit);
|
||||
|
||||
return {
|
||||
total,
|
||||
keyword: rawKeyword,
|
||||
category: query.category,
|
||||
method: query.method,
|
||||
items: pagedItems,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 ID、Path、URL 或文档标题精确解析单篇文档详情
|
||||
*/
|
||||
export async function getDocDetail(
|
||||
target: string,
|
||||
options?: { forceRefresh?: boolean; baseUrl?: string }
|
||||
): Promise<OpenApiDocItem | undefined> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const cleanTarget = target.trim();
|
||||
if (!cleanTarget) return undefined;
|
||||
|
||||
const targetLower = cleanTarget.toLowerCase();
|
||||
|
||||
// 1. 按数字 ID 精确查找
|
||||
const idNum = Number(cleanTarget);
|
||||
if (!Number.isNaN(idNum)) {
|
||||
const byId = catalog.items.find((item) => item.id === idNum);
|
||||
if (byId) return byId;
|
||||
}
|
||||
|
||||
// 2. 按接口 Path 精确查找 (如 /api/openapi/v1/roleDefGroups)
|
||||
const byExactPath = catalog.items.find(
|
||||
(item) => (item.path || "").toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactPath) return byExactPath;
|
||||
|
||||
// 3. 按文档 URL 精确查找 (如 /docs/open-api/corporation/get-roles-group)
|
||||
const byExactUrl = catalog.items.find(
|
||||
(item) => item.url.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactUrl) return byExactUrl;
|
||||
|
||||
// 4. 按标题精确查找
|
||||
const byExactTitle = catalog.items.find(
|
||||
(item) => item.title.toLowerCase() === targetLower
|
||||
);
|
||||
if (byExactTitle) return byExactTitle;
|
||||
|
||||
// 5. 模糊前缀/子串匹配(取最相似的第一个)
|
||||
return (
|
||||
catalog.items.find((item) => (item.path || "").toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.url.toLowerCase().includes(targetLower)) ||
|
||||
catalog.items.find((item) => item.title.toLowerCase().includes(targetLower))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取开放平台所有业务模块分类与文档数量汇总
|
||||
*/
|
||||
export async function listCategories(options?: {
|
||||
forceRefresh?: boolean;
|
||||
baseUrl?: string;
|
||||
}): Promise<DocCategoryInfo[]> {
|
||||
const catalog = await getDocsCatalog(options);
|
||||
const map = new Map<string, { count: number; endpointsCount: number }>();
|
||||
|
||||
for (const item of catalog.items) {
|
||||
const cat = item.category || "未分类";
|
||||
const current = map.get(cat) || { count: 0, endpointsCount: 0 };
|
||||
current.count += 1;
|
||||
if (item.method && item.path) {
|
||||
current.endpointsCount += 1;
|
||||
}
|
||||
map.set(cat, current);
|
||||
}
|
||||
|
||||
const result: DocCategoryInfo[] = [];
|
||||
for (const [name, stats] of map.entries()) {
|
||||
result.push({
|
||||
name,
|
||||
count: stats.count,
|
||||
endpointsCount: stats.endpointsCount,
|
||||
});
|
||||
}
|
||||
|
||||
return result.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动强制同步线上文档中心索引并重载本地持久化缓存
|
||||
*/
|
||||
export async function syncDocsCatalog(options?: {
|
||||
baseUrl?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
totalDocs: number;
|
||||
totalEndpoints: number;
|
||||
source: string;
|
||||
updatedAt: string;
|
||||
}> {
|
||||
const catalog = await getDocsCatalog({
|
||||
forceRefresh: true,
|
||||
baseUrl: options?.baseUrl,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
source: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DocSectionSchema = z.object({
|
||||
title: z.string().default("概述"),
|
||||
content: z.string().default(""),
|
||||
});
|
||||
|
||||
export const OpenApiDocItemSchema = z.object({
|
||||
id: z.number(),
|
||||
title: z.string().default(""),
|
||||
category: z.string().default("未分类"),
|
||||
url: z.string().default(""),
|
||||
permalink: z.string().default(""),
|
||||
method: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
breadcrumbs: z.array(z.string()).default([]),
|
||||
headings: z.array(z.string()).default([]),
|
||||
sections: z.array(DocSectionSchema).default([]),
|
||||
parameters: z.string().optional(),
|
||||
curl: z.string().optional(),
|
||||
responseSample: z.string().optional(),
|
||||
matchReason: z.string().optional(),
|
||||
});
|
||||
|
||||
export const DocCatalogSchema = z.object({
|
||||
version: z.string().default("1.0.0"),
|
||||
updatedAt: z.string(),
|
||||
sourceUrl: z.string().default("https://docs.ekuaibao.com/search-index.json"),
|
||||
totalDocs: z.number(),
|
||||
totalEndpoints: z.number(),
|
||||
items: z.array(OpenApiDocItemSchema),
|
||||
});
|
||||
|
||||
export type DocSection = z.infer<typeof DocSectionSchema>;
|
||||
export type OpenApiDocItem = z.infer<typeof OpenApiDocItemSchema>;
|
||||
export type DocCatalog = z.infer<typeof DocCatalogSchema>;
|
||||
|
||||
export interface DocSearchQuery {
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
path?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface DocSearchResult {
|
||||
total: number;
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
method?: string;
|
||||
items: OpenApiDocItem[];
|
||||
}
|
||||
|
||||
export interface DocCategoryInfo {
|
||||
name: string;
|
||||
count: number;
|
||||
endpointsCount: number;
|
||||
}
|
||||
@@ -33,7 +33,7 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform records [应用 ID|名称] <对象 ID|名称> [--page <页码>] [--count <每页条数>] [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||
@@ -47,6 +47,8 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
- `records <业务对象>`(单参数免应用查询):当企业自建应用较多时,无需事先查询 platformId。直接输入业务对象名称或编码,CLI 自动遍历企业全量自建应用进行智能反查与寻址;若跨应用重名则抛出精准候选项提示,避免人工心智负担。
|
||||
|
||||
- `records --ndjson`(或 `--stream`):针对万级~十万级海量记录,采用 AsyncGenerator 分页流式生成,逐行向 `stdout` 发射 NDJSON。内存恒定为 $O(\text{pageSize})$,严防大报文撑爆内存或终端,无缝对接下游 `jq`、Python 处理流水线。
|
||||
- 终端入口提供显式输出回调并等待写入完成以响应背压;`--ndjson -o <path>` 写入真正的 NDJSON 文件,返回文件路径、字节数和记录数摘要。
|
||||
- MCP / HTTP 默认不提供终端输出通道;未指定文件时拒绝直接流式输出,避免污染协议 stdout 或返回空的成功响应。输出逐行执行统一脱敏。
|
||||
|
||||
@@ -19,7 +19,7 @@ hose-use workflow list [--platform-id=<id>|--app-id=<id>] [-q|--keyword=<关键
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow logs <pipelineId> [--flow=<单号>] [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
|
||||
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
@@ -30,7 +30,7 @@ hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flo
|
||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||
hose-use workflow nodes [list] [--all]
|
||||
hose-use workflow nodes grant <type...> [--password=<pwd>] [--dry-run|--yes]
|
||||
hose-use workflow nodes grant <type...> [--password=<pwd>] [--is-test] [--dry-run|--yes]
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --display-name="清洗节点" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
@@ -44,6 +44,7 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
```
|
||||
|
||||
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||
- `workflow logs <pipelineId> --flow=<单号>`:按业务单号(如报销单/销账单号)秒级定位对应的 Job 实例。由于外部 Piper API 原生无单号索引,CLI 引入「本地 SQLite 缓存 + 流式探查早停熔断」机制:首次探查边扫描边建立本地单号索引,后续命中直接 0ms 返回,避免全表盲目拉取。
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
@@ -169,9 +170,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。
|
||||
|
||||
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。网关既没有返回 `success`、也没有返回可识别的 `code` 时,同样判为失败而非成功——谎报开通会让下游继续报 `PERMISSION_MISSING_NODE`,比如实报错更难排查。
|
||||
灰度节点开通以 Piper 响应中的业务 `code` 判定结果;非 200 业务码时 CLI 保留失败详情并返回非零退出码,HTTP 200 本身不会被视为成功。这样可以避免开通未生效却误报成功、下游仍报 `PERMISSION_MISSING_NODE` 的情况。
|
||||
|
||||
网关地址不再硬编码:可用环境变量 `HOSE_GRAY_GATEWAY_URL` 覆盖内置默认地址(原本固定的第三方托管域曾出现实例回收风险),请求路径统一为 `/hose-workflow-node`,详见 [transport/README.transport.md](./transport/README.transport.md)。传入的 `baseUrl` 只是目标租户地址,不是网关地址。
|
||||
灰度节点开通不再依赖第三方网关:CLI 使用企业 `baseUrl` 换取 EASO JWT,再直连 Piper 的 `/api/easo/dsl/corporation`。每个企业的工作流只对应标准 Piper 或测试 Piper 之一;默认选择标准 Piper,需要测试 Piper 时显式添加 `--is-test`,请求不会自动切换或回退。若一个企业通过标准 Piper 成功开通,其工作流就在标准环境,通过测试 Piper 开通应失败,反之亦然。企业名称、本地 `env=test` 和 `baseUrl` 不用于推断 Piper 环境。`--dry-run` 仅预览,不会探测环境;成功开通可确认路由,失败还需结合错误内容判断。详见 [transport/README.transport.md](./transport/README.transport.md)。
|
||||
|
||||
监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。
|
||||
|
||||
@@ -185,6 +186,8 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
业务对象查询的 `gte/lte` 会产生 `DATALINK_FILTER_COMPARISON_COMPATIBILITY` 软提示:本地条件解释器支持通用比较符,不代表真实设计器的日期字段支持同一枚举。分析器不会自动改为 `gt/lt`,因为这会改变端点是否包含的业务语义;采用严格比较时需同时核对月初、下月月初等毫秒边界。保存成功及静态门禁通过均不等于前端配置校验或租户实际运行通过。
|
||||
|
||||
条件节点对「先穿过列表再取数」的字段(取值链含 `DATA_LINK_LIST` 且后面还有层级)做 `gt/gte/lt/lte` 比较时产生 `CONDITION_NULL_UNSAFE_COMPARE` 软提示:上游列表为空时该字段取值是 `null`,而 `null < 0` 返回 `null` 而非 `false`,引擎会因 condition 参数不是 Boolean 直接中断流程。判定只看**祖先链上有没有对同一列表做过 `notNull` 守卫**,不推断数据是否真的非空,也不改写配置。注意:在同一个条件节点里用 `AND` 组合「列表不为空」无效——实测引擎逐叶子求值、不做短路,`null` 比较照样会被算出来;唯一可靠的写法是在外层再套一个条件节点,把原节点放进它的满足分支。实现见 [condition-null-safety.ts](./analysis/condition-null-safety.ts)。
|
||||
|
||||
原生 `every` 的条件筛选(`mode: "specified"`)区分左侧物理字段键与右侧选择器。费用类型等于/不等于条件的示例为 `{"key":"feeTypeId","compare":"eq","value":"@{value('{\"key\":\"实际费用类型ID\",\"label\":\"实际费用类型名称\"}')}"}`。分析器提供以下软提示,不改写工作流、不查询或猜测显示名称:
|
||||
|
||||
| 诊断码 | 检查范围 |
|
||||
@@ -347,3 +350,16 @@ hose-use --corp=<企业ID> workflow get <pipelineId> --json \
|
||||
已有流程若 `$snapshot` 为空(例如由 CLI 复制/创建产生),需要用全量保存补齐快照条目:读取 `workflow get --json`、在 `$snapshot` 中按 `<taskPath>.url-snapshot` 追加富文本模型,再 `workflow save --file=<json> --yes`。
|
||||
|
||||
富文本模型形如:`root → paragraph → [text, context-tag(choose), text]`,三段的拼接结果必须等同于 `url` 字段。
|
||||
|
||||
## 上游官方规范与参考依据 (Upstream References)
|
||||
|
||||
本域在解析底层数据格式、变量选择树与灰度节点规范时,参考了合思/易快报官方公开的开源仓库定义:
|
||||
|
||||
1. **HoseCloud Hab 任务插件框架**:[`ekuaibao/Hab-Plugin`](https://github.com/ekuaibao/Hab-Plugin)
|
||||
- **底层数据类型**:定义了 39 类官方底层字段数据类型(`com.hosecloud.hab.plugin.DataType`,如 `TEXT`, `MONEY`, `FLOW_FORM`, `DATA_LINK`, `REQUISITION_ITEMS` 等)与 8 种选择项类型(`Choose.ItemType`),收录于 `catalog/enums.ts`(`WORKFLOW_DATA_TYPES` 与 `WORKFLOW_CHOOSE_ITEM_TYPES`);
|
||||
- **动态任务节点机制**:阐明了合思工作流中 `task-dynamic-*`(如官方延迟等待节点 `task-dynamic-delay`)的 PF4J 插件化容器与执行生命周期;
|
||||
- **架构边界说明**:`hose-use` 仅作为合思平台工作流的客户端 CLI、SDK 编排与诊断工具,**不开发或篡改其服务端底层运行时,亦不违规在客户端捏造服务端未支持的自造节点类型**。所有节点类型必须严格对齐服务端或官方灰度清单(`GRAY_NODES_CATALOG`)。
|
||||
|
||||
2. **开放平台接口文档中心**:[`ekuaibao/open-platform-docs`](https://github.com/ekuaibao/open-platform-docs)
|
||||
- 包含开放平台 23 大类、249 篇接口规范,作为工作流 HTTP 节点 (`http`) 与 OpenAPI 任务节点 (`task-openapi`) 的调用路径、参数规格与应用权限映射基准。
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
- [analyzer.ts](./analyzer.ts):`analyzeWorkflow(detail, options)` 与关联表单规格 ID 提取。
|
||||
- [every.ts](./every.ts):循环筛选、选择器和批次配置检查;[diagnostics.ts](./diagnostics.ts) 统一诊断分类。
|
||||
- [openapi-app-requirements.ts](./openapi-app-requirements.ts):开放接口 → 所需企业应用的映射表,以及从 URL 提取**静态路径**的判定入口。用于在保存/分析阶段提前发现「企业未开通某应用,运行时必然 403」的问题。
|
||||
- [condition-null-safety.ts](./condition-null-safety.ts):条件节点的空值安全判断。识别「先穿过列表再取数」的字段参与有序比较(`gt/gte/lt/lte`)却没有外层 `notNull` 守卫的情况,产出 `CONDITION_NULL_UNSAFE_COMPARE`。判定只依赖祖先链上的条件节点,不推断数据是否真的非空。
|
||||
- [types.ts](./types.ts):AST、依赖、诊断分类、统计摘要和外部分析上下文。
|
||||
- 同级测试覆盖条件/循环、选择器引用、公式边界和诊断行为。
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from "./types.js";
|
||||
import { isKnownGrayNodeType } from "../nodes/gray-nodes-catalog.js";
|
||||
import { matchAppRequirement } from "./openapi-app-requirements.js";
|
||||
import { checkConditionNullSafety } from "./condition-null-safety.js";
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
@@ -452,7 +453,7 @@ export function analyzeWorkflow(
|
||||
|
||||
const taskNameMap = buildTaskNameMap(detail.tasks);
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false, ancestors: WorkflowTask[] = []) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
@@ -692,6 +693,9 @@ export function analyzeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 5.3 条件节点空值安全(CONDITION_NULL_UNSAFE_COMPARE)
|
||||
checkConditionNullSafety(task, path, ancestors, diagnostics);
|
||||
|
||||
// 诊断 6: HTTP 节点域名、中括号与功能权限校验
|
||||
if (task.type === "http") {
|
||||
const url = String((task as Record<string, unknown>).url || "");
|
||||
@@ -909,7 +913,7 @@ export function analyzeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every", [...ancestors, task]);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./index.js";
|
||||
import { goesThroughList, readChoosePath } from "./condition-null-safety.js";
|
||||
|
||||
const LIST_LEAF =
|
||||
"@{choose('{\"key\":\"action_find\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"},{\"key\":\"0\",\"label\":\"首条数据\",\"type\":\"DATA_LINK\"},{\"key\":\"E_x\",\"label\":\"差旅费剩余额度\",\"type\":\"MONEY\"}],\"label\":\"查找业务数据.结果列表.首条数据.差旅费剩余额度\"}')}";
|
||||
|
||||
const LIST_SELF =
|
||||
"@{choose('{\"key\":\"action_find\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"}],\"label\":\"查找业务数据.结果列表\"}')}";
|
||||
|
||||
const OTHER_LIST_LEAF =
|
||||
"@{choose('{\"key\":\"action_other\",\"properties\":[{\"key\":\"$this\",\"label\":\"结果列表\",\"type\":\"DATA_LINK_LIST\"},{\"key\":\"0\",\"label\":\"首条数据\",\"type\":\"DATA_LINK\"}],\"label\":\"别的查询.结果列表.首条数据\"}')}";
|
||||
|
||||
const FLAT_MONEY =
|
||||
"@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"amount\",\"label\":\"金额\",\"type\":\"MONEY\"}],\"label\":\"金额\"}')}";
|
||||
|
||||
function leaf(key: string, compare: string, value?: unknown) {
|
||||
return value === undefined ? { key, compare } : { key, compare, value };
|
||||
}
|
||||
|
||||
function group(filters: unknown[], condition = "and") {
|
||||
return { condition, filters };
|
||||
}
|
||||
|
||||
function condition(name: string, filters: unknown, children: unknown[] = []) {
|
||||
return { name, type: "condition", label: "条件节点", combineFilters: filters, tasks: children };
|
||||
}
|
||||
|
||||
function wf(tasks: unknown[]) {
|
||||
return { id: "wf-null", label: "空值安全", state: 1, version: "1", tasks } as any;
|
||||
}
|
||||
|
||||
describe("choose 路径解析", () => {
|
||||
it("识别穿过列表的取值链", () => {
|
||||
const parsed = readChoosePath(LIST_LEAF);
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.root).toBe("action_find");
|
||||
expect(goesThroughList(parsed!)).toBe(true);
|
||||
});
|
||||
|
||||
it("列表位于最后一层时不算穿过", () => {
|
||||
expect(goesThroughList(readChoosePath(LIST_SELF)!)).toBe(false);
|
||||
});
|
||||
|
||||
it("单层字段取值不算穿过", () => {
|
||||
expect(goesThroughList(readChoosePath(FLAT_MONEY)!)).toBe(false);
|
||||
});
|
||||
|
||||
it("兼容前端多一个右花括号的形态", () => {
|
||||
const tail = "}')}";
|
||||
const doubled = LIST_LEAF.slice(0, LIST_LEAF.lastIndexOf(tail)) + "}}" + "')}";
|
||||
const parsed = readChoosePath(doubled);
|
||||
expect(parsed?.root).toBe("action_find");
|
||||
expect(goesThroughList(parsed!)).toBe(true);
|
||||
});
|
||||
|
||||
it("非 choose 表达式一律忽略", () => {
|
||||
expect(readChoosePath("trigger_1.amount")).toBeNull();
|
||||
expect(readChoosePath(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CONDITION_NULL_UNSAFE_COMPARE", () => {
|
||||
it("列表取数 + 数值比较 + 无守卫 → 告警", () => {
|
||||
const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, "lt", 0)])]))]));
|
||||
const diag = result.diagnostics.find((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE");
|
||||
expect(diag).toBeDefined();
|
||||
expect(diag?.severity).toBe("warning");
|
||||
expect(diag?.category).toBe("soft_advice");
|
||||
expect(diag?.message).toContain("差旅费剩余额度");
|
||||
expect(diag?.message).toContain("Boolean");
|
||||
// 必须明确否掉「AND 兜住」这个直觉解法
|
||||
expect(diag?.message).toContain("不做短路");
|
||||
});
|
||||
|
||||
it("同一节点内用 AND 组合了列表非空判断 → 仍然告警(引擎不短路)", () => {
|
||||
const result = analyzeWorkflow(
|
||||
wf([
|
||||
condition(
|
||||
"control_a",
|
||||
group([group([leaf(LIST_SELF, "notNull")]), group([leaf(LIST_LEAF, "lt", 0)])])
|
||||
),
|
||||
])
|
||||
);
|
||||
const diags = result.diagnostics.filter((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE");
|
||||
expect(diags).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("外层套了列表非空守卫 → 不告警", () => {
|
||||
const inner = condition("control_b", group([group([leaf(LIST_LEAF, "lt", 0)])]));
|
||||
const outer = condition("control_guard", group([group([leaf(LIST_SELF, "notNull")])]), [inner]);
|
||||
const result = analyzeWorkflow(wf([outer]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false);
|
||||
});
|
||||
|
||||
it("守卫判断的是另一个列表 → 仍然告警", () => {
|
||||
const inner = condition("control_b", group([group([leaf(LIST_LEAF, "lt", 0)])]));
|
||||
const outer = condition(
|
||||
"control_guard",
|
||||
group([group([leaf(OTHER_LIST_LEAF.replace("action_other", "action_zzz"), "notNull")])]),
|
||||
[inner]
|
||||
);
|
||||
const result = analyzeWorkflow(wf([outer]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(true);
|
||||
});
|
||||
|
||||
it("单层字段比较 → 不告警", () => {
|
||||
const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(FLAT_MONEY, "lt", 0)])]))]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false);
|
||||
});
|
||||
|
||||
it("只判列表本身 → 不告警", () => {
|
||||
const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_SELF, "notNull")])]))]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false);
|
||||
});
|
||||
|
||||
it("gte / lte / gt 同样覆盖", () => {
|
||||
for (const compare of ["gt", "gte", "lte"]) {
|
||||
const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, compare, 0)])]))]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("eq 不属于有序比较 → 不告警", () => {
|
||||
const result = analyzeWorkflow(wf([condition("control_a", group([group([leaf(LIST_LEAF, "eq", 0)])]))]));
|
||||
expect(result.diagnostics.some((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toBe(false);
|
||||
});
|
||||
|
||||
it("同一路径重复出现只报一次", () => {
|
||||
const result = analyzeWorkflow(
|
||||
wf([
|
||||
condition(
|
||||
"control_a",
|
||||
group([
|
||||
group([leaf(LIST_LEAF, "lt", 0)]),
|
||||
group([leaf(LIST_LEAF, "gt", 100)]),
|
||||
])
|
||||
),
|
||||
])
|
||||
);
|
||||
expect(result.diagnostics.filter((d) => d.code === "CONDITION_NULL_UNSAFE_COMPARE")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 条件节点的空值安全校验(CONDITION_NULL_UNSAFE_COMPARE)。
|
||||
*
|
||||
* ── 要解决的问题 ────────────────────────────────────────────────────
|
||||
*
|
||||
* 条件节点里对一个「先经过列表取数」的字段做数值/日期比较时,如果上游列表
|
||||
* 为空,取值结果是 null。而 MVEL 中 `null < 0` 返回的是 **null 而不是 false**,
|
||||
* 引擎对 condition 参数做 Boolean 强校验,于是直接抛:
|
||||
*
|
||||
* if 节点(xxx)的 condition 参数的解析结果必须为 Boolean 类型
|
||||
*
|
||||
* 流程到这里**中断**,而不是安静地走 false 分支。真实案例里这类报错排查成本
|
||||
* 极高,因为报错信息完全看不出是哪一次取值拿到 null。
|
||||
*
|
||||
* ── 为什么不能靠 AND 兜住(实测结论)────────────────────────────────
|
||||
*
|
||||
* 直觉写法是 `AND(列表非空, 额度 < 0)`,指望布尔短路跳过后面的比较。
|
||||
* 但合思引擎是**逐叶子求值再合并**,不做短路:`null < 0` 照样被算出来,
|
||||
* 合并阶段类型校验失败,一样报错。
|
||||
*
|
||||
* 唯一可靠的写法是把守卫**上提一层**,用流程控制短路:
|
||||
*
|
||||
* 条件节点A:结果列表 不为空
|
||||
* └─(满足) 条件节点B:OR(差旅 < 0, 招待 < 0)
|
||||
* └─ 真正的处理动作
|
||||
*
|
||||
* 列表为空时 A 为 false,B 根本不会被求值。
|
||||
*
|
||||
* 本模块只做「有没有守卫」的静态判断,不尝试推断数据是否真的非空。
|
||||
*/
|
||||
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
import { extractLeafFilters } from "./every.js";
|
||||
import { parseChoosePayloadLoose } from "../models/choose-serialization.js";
|
||||
import { addDiagnostic } from "./diagnostics.js";
|
||||
import type { WorkflowDiagnostic } from "./types.js";
|
||||
|
||||
/** 需要另一侧提供有序值的比较符;左边是 null 时结果不是布尔。 */
|
||||
const ORDERING_COMPARES = new Set(["gt", "gte", "lt", "lte"]);
|
||||
|
||||
/** 「为空 / 不为空」这一对只有它们不要求 value,也不产生 null 污染。 */
|
||||
const NULL_CHECKS = new Set(["isnull", "notnull"]);
|
||||
|
||||
interface ChoosePath {
|
||||
/** 取值链的根节点 key(如 action_5yt4ko) */
|
||||
root: string;
|
||||
/** properties 链,按层级顺序 */
|
||||
properties: Array<{ key?: string; type?: string; label?: string }>;
|
||||
/** 展示用的最后一段标签 */
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface ChooseProperty {
|
||||
key?: unknown;
|
||||
type?: unknown;
|
||||
label?: unknown;
|
||||
}
|
||||
|
||||
function unquote(raw: string): string | null {
|
||||
const text = raw.trim();
|
||||
if (text.length < 2) return null;
|
||||
if (text.startsWith('"') && text.endsWith('"')) {
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
return typeof parsed === "string" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (text.startsWith("'") && text.endsWith("'")) {
|
||||
return text.slice(1, -1).replace(/\\'/g, "'");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 解析 `@{choose('{...}')}` 里的描述对象;不是这个形态就返回 null。 */
|
||||
export function readChoosePath(key: unknown): ChoosePath | null {
|
||||
if (typeof key !== "string") return null;
|
||||
const match = /^@\{\s*choose\s*\(([\s\S]*)\)\s*\}\s*$/.exec(key.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const payloadText = unquote(match[1]);
|
||||
if (payloadText === null) return null;
|
||||
|
||||
const normalized = parseChoosePayloadLoose(payloadText);
|
||||
if (!normalized) return null;
|
||||
|
||||
let payload: Record<string, unknown>;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(normalized);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
||||
payload = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = typeof payload.key === "string" ? payload.key : "";
|
||||
if (!root) return null;
|
||||
|
||||
const properties = Array.isArray(payload.properties)
|
||||
? payload.properties
|
||||
.filter((item): item is ChooseProperty => Boolean(item) && typeof item === "object")
|
||||
.map((item) => ({
|
||||
key: typeof item.key === "string" ? item.key : undefined,
|
||||
type: typeof item.type === "string" ? item.type : undefined,
|
||||
label: typeof item.label === "string" ? item.label : undefined,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const label =
|
||||
typeof payload.label === "string" ? payload.label : properties.at(-1)?.label ?? properties.at(-1)?.key ?? root;
|
||||
|
||||
return { root, properties, label };
|
||||
}
|
||||
|
||||
/**
|
||||
* 取值链是否「先穿过一个列表,再继续往下取」。
|
||||
*
|
||||
* - `结果列表.首条数据.额度` → 穿过 DATA_LINK_LIST 后还有两层 → 有风险
|
||||
* - `金额字段` → 单层取值 → 无风险
|
||||
* - `结果列表`(只判列表本身)→ 列表在最后一层 → 无风险
|
||||
*/
|
||||
export function goesThroughList(path: ChoosePath): boolean {
|
||||
const index = path.properties.findIndex((item) => item.type === "DATA_LINK_LIST");
|
||||
return index !== -1 && index < path.properties.length - 1;
|
||||
}
|
||||
|
||||
function compareOf(raw: unknown): string {
|
||||
return typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
||||
}
|
||||
|
||||
function filterSourceOf(task: WorkflowTask): unknown {
|
||||
const raw = task as Record<string, unknown>;
|
||||
return raw.combineFilters ?? raw.filters ?? raw.conditions;
|
||||
}
|
||||
|
||||
/** 祖先链上是否存在「对同一列表做过不为空判断」的条件节点。 */
|
||||
function hasAncestorListGuard(ancestors: WorkflowTask[], root: string): boolean {
|
||||
for (let i = ancestors.length - 1; i >= 0; i -= 1) {
|
||||
const ancestor = ancestors[i];
|
||||
if (ancestor?.type !== "condition") continue;
|
||||
for (const leaf of extractLeafFilters(filterSourceOf(ancestor))) {
|
||||
if (compareOf(leaf.compare) !== "notnull") continue;
|
||||
const guarded = readChoosePath(leaf.key);
|
||||
if (guarded && guarded.root === root) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查单个条件节点。命中「列表取数 + 有序比较 + 上游没有非空守卫」时产出软建议。
|
||||
*
|
||||
* 刻意不产出硬门禁:静态分析无法确定上游列表一定为空,误判会让合法流程
|
||||
* 无法发布;但这个消息本身必须把「AND 兜不住」讲清楚,否则作者会按直觉改错。
|
||||
*/
|
||||
export function checkConditionNullSafety(
|
||||
task: WorkflowTask,
|
||||
path: string,
|
||||
ancestors: WorkflowTask[],
|
||||
diagnostics: WorkflowDiagnostic[]
|
||||
): void {
|
||||
if (task.type !== "condition") return;
|
||||
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const leaf of extractLeafFilters(filterSourceOf(task))) {
|
||||
if (!ORDERING_COMPARES.has(compareOf(leaf.compare))) continue;
|
||||
if (NULL_CHECKS.has(compareOf(leaf.compare))) continue;
|
||||
|
||||
const choosePath = readChoosePath(leaf.key);
|
||||
if (!choosePath || !goesThroughList(choosePath)) continue;
|
||||
if (hasAncestorListGuard(ancestors, choosePath.root)) continue;
|
||||
if (seen.has(choosePath.label)) continue;
|
||||
seen.add(choosePath.label);
|
||||
|
||||
const compareLabel = { gt: "大于", gte: "大于等于", lt: "小于", lte: "小于等于" }[
|
||||
compareOf(leaf.compare) as "gt" | "gte" | "lt" | "lte"
|
||||
];
|
||||
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
category: "soft_advice",
|
||||
code: "CONDITION_NULL_UNSAFE_COMPARE",
|
||||
path,
|
||||
message:
|
||||
`条件节点 [${task.label || task.name}] (${task.name}) 对字段 [${choosePath.label}] 做「${compareLabel}」比较,` +
|
||||
`而该字段的取值链要先穿过列表(${choosePath.properties.map((p) => p.label || p.key).join(" → ")})。` +
|
||||
`上游列表为空时取值是 null,null 参与比较返回的不是布尔,引擎会直接抛「condition 参数的解析结果必须为 Boolean 类型」并中断流程。` +
|
||||
`注意:把「列表不为空」放进同一个条件节点用 AND 组合没有用 —— 实测引擎逐叶子求值,不做短路,null 比较照样会被算出来。` +
|
||||
`请在该节点外层再套一个条件节点,先判断「列表不为空」,把本节点放进它的满足分支。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../../../core/config/types.js";
|
||||
import * as api from "../api.js";
|
||||
import { PermissionError, ValidationError } from "../../../../core/errors.js";
|
||||
import { normalizeGrayNodes } from "../nodes/gray-nodes-catalog.js";
|
||||
|
||||
|
||||
export function listDsl(...args: Parameters<typeof api.listDsl>) {
|
||||
@@ -80,6 +81,24 @@ export async function getWorkflowAvailableNodes(
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 随开通请求附带的固定开关,属于 Piper 历史接口契约。
|
||||
* 显式定义在编排层,dry-run 与成功输出都会展示,避免"预览与实发不一致"。
|
||||
*/
|
||||
export const GRANT_ATTACHED_OPTIONS = {
|
||||
"recalculate-the-approval-flow": true,
|
||||
"ui-notification": true,
|
||||
start: 0,
|
||||
} as const;
|
||||
|
||||
function parseNodeNames(message: string): string[] {
|
||||
const match = message.match(/(?:新开通的节点|以下节点已开通[^::]*|已开通[^::]*节点)[::]\s*(.+)$/);
|
||||
return match?.[1]
|
||||
.split(/[,,、\s]+/)
|
||||
.map((node) => node.trim())
|
||||
.filter(Boolean) ?? [];
|
||||
}
|
||||
|
||||
export async function grantWorkflowNodes(
|
||||
corp: CorpConfig,
|
||||
options: import("../types.js").GrantWorkflowNodesOptions
|
||||
@@ -88,7 +107,7 @@ export async function grantWorkflowNodes(
|
||||
throw new ValidationError("必须指定至少一个需要开通的节点名称或类型");
|
||||
}
|
||||
|
||||
// 1. 管理员密码保护预留设计
|
||||
// 1. 管理员密码保护(可选启用)
|
||||
const adminPassword = process.env.HOSE_ADMIN_PASSWORD;
|
||||
if (adminPassword) {
|
||||
if (!options.password || options.password !== adminPassword) {
|
||||
@@ -98,29 +117,48 @@ export async function grantWorkflowNodes(
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type)
|
||||
const { findGrayNode } = await import("../nodes/gray-nodes-catalog.js");
|
||||
const normalizedNodes = options.nodes.map((node) => {
|
||||
const matched = findGrayNode(node);
|
||||
return matched ? matched.type : node.trim();
|
||||
});
|
||||
// 2. 节点清洗与归一化(中文名 -> type,同名多类型时要求改用明确 type)
|
||||
const normalizedNodes = normalizeGrayNodes(options.nodes);
|
||||
|
||||
const token = corp.credentials?.accessToken;
|
||||
const corpId = corp.corpId || corp.credentials?.corpId || corp.id;
|
||||
const staffId = corp.staffId || corp.credentials?.staffId || "";
|
||||
const baseUrl = corp.baseUrl;
|
||||
|
||||
if (!token) {
|
||||
throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请");
|
||||
}
|
||||
|
||||
// 3. 调用开通 API
|
||||
const result = await api.grantWorkflowNodesApi({
|
||||
// 3. 组装 payload 并调用传输层(传输层不再组装业务字段)
|
||||
const record = await api.grantWorkflowNodesApi({
|
||||
token,
|
||||
corpId,
|
||||
nodes: normalizedNodes,
|
||||
staffId,
|
||||
baseUrl,
|
||||
gatewayUrl: options.gatewayUrl,
|
||||
isTest: options.isTest,
|
||||
payload: {
|
||||
corporationId: corpId,
|
||||
dslTypes: normalizedNodes,
|
||||
...GRANT_ATTACHED_OPTIONS,
|
||||
},
|
||||
});
|
||||
|
||||
return result;
|
||||
// 4. 业务码判定与结果映射(编排层职责)
|
||||
return mapGrantResult(record, Boolean(options.isTest));
|
||||
}
|
||||
|
||||
/** 纯函数,便于单测覆盖业务码与中文文案两种结果形态。 */
|
||||
export function mapGrantResult(
|
||||
record: import("../transport/catalog/api.js").WorkflowNodeGrantResponse,
|
||||
isTest: boolean
|
||||
): import("../types.js").GrantWorkflowNodesResult {
|
||||
const success = Number(record.code ?? 200) === 200;
|
||||
const rawMessage = record.msg || "";
|
||||
const saved = record.data?.saved ?? (success && rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
const skipped = record.data?.skipped ?? (success && rawMessage.includes("已开通") && !rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
return { success, saved, skipped, rawMessage, isTest };
|
||||
}
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
isWorkflowActionCode,
|
||||
matchWorkflowAction,
|
||||
resolveWorkflowEnumOptions,
|
||||
WORKFLOW_DATA_TYPES,
|
||||
WORKFLOW_CHOOSE_ITEM_TYPES,
|
||||
isWorkflowDataType,
|
||||
isWorkflowChooseItemType,
|
||||
} from "../services.js";
|
||||
import { analyzeWorkflow } from "../analysis/index.js";
|
||||
|
||||
@@ -182,4 +186,25 @@ describe("Workflow Action Enums & Diagnostics", () => {
|
||||
expect(codes).not.toContain("DEADLOCK_CONDITION_STATE_FILTER");
|
||||
expect(codes).not.toContain("INVALID_ACTION_ENUM_TEXT_VALUE");
|
||||
});
|
||||
|
||||
it("verifies official workflow DataType definitions from Hab-Plugin", () => {
|
||||
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.DataType)
|
||||
expect(WORKFLOW_DATA_TYPES).toHaveLength(39);
|
||||
expect(isWorkflowDataType("TEXT")).toBe(true);
|
||||
expect(isWorkflowDataType("MONEY")).toBe(true);
|
||||
expect(isWorkflowDataType("FLOW_FORM")).toBe(true);
|
||||
expect(isWorkflowDataType("DATA_LINK")).toBe(true);
|
||||
expect(isWorkflowDataType("REQUISITION_ITEMS")).toBe(true);
|
||||
expect(isWorkflowDataType("NOT_A_REAL_TYPE")).toBe(false);
|
||||
});
|
||||
|
||||
it("verifies official workflow Choose ItemType definitions from Hab-Plugin", () => {
|
||||
// 官方参考: https://github.com/ekuaibao/Hab-Plugin (com.hosecloud.hab.plugin.Choose.ItemType)
|
||||
expect(WORKFLOW_CHOOSE_ITEM_TYPES).toHaveLength(8);
|
||||
expect(isWorkflowChooseItemType("TEXT")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("NUMBER")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("MONEY")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("BOOLEAN")).toBe(true);
|
||||
expect(isWorkflowChooseItemType("UNKNOWN")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -57,3 +57,86 @@ export function matchWorkflowAction(query: string): WorkflowActionEnumItem | und
|
||||
(item) => item.code.toLowerCase() === trimmed.toLowerCase() || item.label === trimmed || item.name === trimmed
|
||||
);
|
||||
}
|
||||
|
||||
// ── 工作流底层官方字段类型与 Choose 类型枚举 ────────────────────────────────────
|
||||
// 来源于 HoseCloud Hab 官方插件框架底层定义 (https://github.com/ekuaibao/Hab-Plugin)
|
||||
// 参考规范:com.hosecloud.hab.plugin.DataType 与 com.hosecloud.hab.plugin.Choose.ItemType
|
||||
// 说明:仅作为客户端变量解析、字段类型断言与 Schema 校验依据,不侵入平台服务端内部插件实现。
|
||||
|
||||
/**
|
||||
* 合思/易快报工作流官方字段底层数据类型枚举(共 39 类)
|
||||
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.DataType (https://github.com/ekuaibao/Hab-Plugin)
|
||||
*/
|
||||
export const WORKFLOW_DATA_TYPES = [
|
||||
"TEXT",
|
||||
"AUTO_NUMBER",
|
||||
"NUMBER",
|
||||
"MONEY",
|
||||
"BOOLEAN",
|
||||
"SWITCH",
|
||||
"DATE",
|
||||
"DATE_RANGE",
|
||||
"DEPARTMENT",
|
||||
"FEISHU_DEPARTMENT",
|
||||
"STAFF",
|
||||
"STAFF_LIST",
|
||||
"DATA_LINK",
|
||||
"DATA_LINK_LIST",
|
||||
"PAYEE_INFO",
|
||||
"DIMENSION",
|
||||
"DIMENSION_LIST",
|
||||
"ENUM",
|
||||
"LIST",
|
||||
"MAP",
|
||||
"FLOW_TEMPLATE",
|
||||
"CITY",
|
||||
"_SELECT_INVOICE_TYPE_",
|
||||
"ATTACHMENT",
|
||||
"REQUISITION_ITEMS",
|
||||
"FEE_DETAIL",
|
||||
"FEE_DETAIL_ITEM",
|
||||
"FLOW_FORM",
|
||||
"FLOW_FORM_ITEM",
|
||||
"RECORD_LINK",
|
||||
"RECORD_LINK_LIST",
|
||||
"VISIBILITY",
|
||||
"ROLE",
|
||||
"ZS_TYPE",
|
||||
"ZS_LIST",
|
||||
"SELECT_INVOICE_CORPORATION",
|
||||
"FREQUENCY",
|
||||
"DATALINK_FILTERS",
|
||||
"UNDEFINED",
|
||||
] as const;
|
||||
|
||||
export type WorkflowDataType = (typeof WORKFLOW_DATA_TYPES)[number];
|
||||
|
||||
const WORKFLOW_DATA_TYPES_SET = new Set<string>(WORKFLOW_DATA_TYPES);
|
||||
|
||||
export function isWorkflowDataType(type: string): type is WorkflowDataType {
|
||||
return WORKFLOW_DATA_TYPES_SET.has(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合思/易快报工作流 Choose 选择项官方基础类型
|
||||
* 对应 HoseCloud Hab 插件框架 com.hosecloud.hab.plugin.Choose.ItemType
|
||||
*/
|
||||
export const WORKFLOW_CHOOSE_ITEM_TYPES = [
|
||||
"TEXT",
|
||||
"NUMBER",
|
||||
"BOOLEAN",
|
||||
"DATE",
|
||||
"DATA_RANGE",
|
||||
"LIST",
|
||||
"MAP",
|
||||
"MONEY",
|
||||
] as const;
|
||||
|
||||
export type WorkflowChooseItemType = (typeof WORKFLOW_CHOOSE_ITEM_TYPES)[number];
|
||||
|
||||
const WORKFLOW_CHOOSE_ITEM_TYPES_SET = new Set<string>(WORKFLOW_CHOOSE_ITEM_TYPES);
|
||||
|
||||
export function isWorkflowChooseItemType(type: string): type is WorkflowChooseItemType {
|
||||
return WORKFLOW_CHOOSE_ITEM_TYPES_SET.has(type);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "../../../../core/db/connection.js";
|
||||
import {
|
||||
extractJobFlowCode,
|
||||
searchWorkflowJobByFlowCode,
|
||||
} from "./search-by-flow.js";
|
||||
|
||||
describe("Workflow - 按单号查找运行实例 (searchWorkflowJobByFlowCode)", () => {
|
||||
const originalDbEnv = process.env.HOSE_APPROVAL_DB;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
getDatabase(":memory:");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
if (originalDbEnv !== undefined) {
|
||||
process.env.HOSE_APPROVAL_DB = originalDbEnv;
|
||||
} else {
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
}
|
||||
});
|
||||
|
||||
test("extractJobFlowCode 能准确从各类 inputs 结构或顶层字段解析出单号", () => {
|
||||
expect(extractJobFlowCode(null)).toBeUndefined();
|
||||
expect(extractJobFlowCode({})).toBeUndefined();
|
||||
expect(extractJobFlowCode({ inputs: { code: " XZ2610474 " } })).toBe("XZ2610474");
|
||||
expect(extractJobFlowCode({ inputs: { flowCode: "BX20261101" } })).toBe("BX20261101");
|
||||
expect(extractJobFlowCode({ code: "JK20260901" })).toBe("JK20260901");
|
||||
});
|
||||
|
||||
test("空单号直接返回未找到", async () => {
|
||||
const dummyClient = {} as any;
|
||||
const res = await searchWorkflowJobByFlowCode(dummyClient, "corp1", "pipe1", " ");
|
||||
expect(res.found).toBe(false);
|
||||
});
|
||||
|
||||
test("流式翻页探查:命中目标单号并自动写入本地 SQLite 缓存,后续查询秒级命中缓存", async () => {
|
||||
const mockJobsDetail: Record<string, any> = {
|
||||
job_001: {
|
||||
id: "job_001",
|
||||
status: "COMPLETED",
|
||||
inputs: {
|
||||
code: "XZ2610474",
|
||||
flowId: "flow_xz_01",
|
||||
userInfo: { name: "欧阳亚玲" },
|
||||
},
|
||||
},
|
||||
job_002: {
|
||||
id: "job_002",
|
||||
status: "RUNNING",
|
||||
inputs: {
|
||||
code: "OTHER_999",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let logCalls = 0;
|
||||
let jobCalls = 0;
|
||||
|
||||
const mockClient = {
|
||||
get: async (path: string, options?: any) => {
|
||||
if (path.includes("/log")) {
|
||||
logCalls++;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
totalCount: 2,
|
||||
totalPages: 1,
|
||||
jobList: [
|
||||
{ jobId: "job_002", status: "RUNNING", executeTime: 1700000000000 },
|
||||
{ jobId: "job_001", status: "COMPLETED", executeTime: 1700000050000 },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (path.includes("/jobs/")) {
|
||||
jobCalls++;
|
||||
const jobId = path.split("/jobs/")[1]?.split("?")[0];
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: mockJobsDetail[jobId] || { id: jobId },
|
||||
})
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 404 }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
// 第一次调用:缓存未命中,执行流式远端嗅探
|
||||
const res1 = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp_winner",
|
||||
"pipe_win",
|
||||
"XZ2610474",
|
||||
{ maxScanPages: 5 }
|
||||
);
|
||||
|
||||
expect(res1.found).toBe(true);
|
||||
expect(res1.source).toBe("scan");
|
||||
expect(res1.jobId).toBe("job_001");
|
||||
expect(res1.job?.id).toBe("job_001");
|
||||
expect(logCalls).toBe(1);
|
||||
expect(jobCalls).toBe(2);
|
||||
|
||||
// 第二次调用:应当直接命中本地 SQLite 缓存,不调 /log 接口
|
||||
const prevLogCalls = logCalls;
|
||||
const prevJobCalls = jobCalls;
|
||||
|
||||
const res2 = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp_winner",
|
||||
"pipe_win",
|
||||
"xz2610474" // 测试大小写模糊命中
|
||||
);
|
||||
|
||||
expect(res2.found).toBe(true);
|
||||
expect(res2.source).toBe("cache");
|
||||
expect(res2.jobId).toBe("job_001");
|
||||
// 不应再请求 /log
|
||||
expect(logCalls).toBe(prevLogCalls);
|
||||
// 仅通过 getJob 校验最新状态
|
||||
expect(jobCalls).toBe(prevJobCalls + 1);
|
||||
});
|
||||
|
||||
test("扫描达最大页数仍未找到时安全熔断并返回未找到", async () => {
|
||||
const mockClient = {
|
||||
get: async (path: string) => {
|
||||
if (path.includes("/log")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
totalCount: 10,
|
||||
totalPages: 10,
|
||||
jobList: [
|
||||
{ jobId: "job_x", status: "COMPLETED" },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (path.includes("/jobs/")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: { id: "job_x", inputs: { code: "NO_MATCH" } },
|
||||
})
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 404 }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
const res = await searchWorkflowJobByFlowCode(
|
||||
mockClient,
|
||||
"corp1",
|
||||
"pipe1",
|
||||
"WANT_THIS",
|
||||
{ maxScanPages: 2 }
|
||||
);
|
||||
|
||||
expect(res.found).toBe(false);
|
||||
expect(res.scannedPages).toBe(2);
|
||||
expect(res.totalScanned).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { getCachedWorkflowJobByCode, upsertWorkflowJobIndex, type WorkflowJobCacheRecord } from "../../../../core/db/index.js";
|
||||
import { getJob } from "./queries.js";
|
||||
import { listWorkflowLogs } from "../transport/pipeline/api.js";
|
||||
import type { WorkflowJobDetail } from "../types.js";
|
||||
|
||||
export interface SearchJobByFlowOptions {
|
||||
maxScanPages?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface SearchJobByFlowResult {
|
||||
found: boolean;
|
||||
source?: "cache" | "scan";
|
||||
job?: WorkflowJobDetail;
|
||||
jobId?: string;
|
||||
flowCode?: string;
|
||||
scannedPages?: number;
|
||||
totalScanned?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取工作流 Job 内部携带的触发单号
|
||||
*/
|
||||
export function extractJobFlowCode(job: any): string | undefined {
|
||||
if (!job) return undefined;
|
||||
const inputs = job.inputs || {};
|
||||
if (inputs.code && typeof inputs.code === "string") return inputs.code.trim();
|
||||
if (inputs.flowCode && typeof inputs.flowCode === "string") return inputs.flowCode.trim();
|
||||
if (job.code && typeof job.code === "string") return job.code.trim();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据单据编号 (flowCode) 高效查找对应的工作流运行实例 (Job)
|
||||
* 采用【本地 SQLite 缓存命中 ➔ 未命中流式翻页探查并写入缓存】的双层机制
|
||||
*/
|
||||
export async function searchWorkflowJobByFlowCode(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
pipelineId: string,
|
||||
flowCode: string,
|
||||
options: SearchJobByFlowOptions = {}
|
||||
): Promise<SearchJobByFlowResult> {
|
||||
const targetCode = flowCode.trim();
|
||||
if (!targetCode) {
|
||||
return { found: false, flowCode: targetCode };
|
||||
}
|
||||
|
||||
// 1. 本地 SQLite 缓存优先探查 (0ms 命中)
|
||||
try {
|
||||
const cached = getCachedWorkflowJobByCode(corpId, pipelineId, targetCode);
|
||||
if (cached?.jobId) {
|
||||
try {
|
||||
const fullJob = await getJob(client, cached.jobId);
|
||||
if (fullJob) {
|
||||
return {
|
||||
found: true,
|
||||
source: "cache",
|
||||
job: fullJob,
|
||||
jobId: cached.jobId,
|
||||
flowCode: targetCode,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// 若远程已清理或失效,平滑回退至实时扫描
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// 2. 本地未命中,启动流式嗅探拉取(带本地边拉边存与早停熔断)
|
||||
const maxPages = options.maxScanPages ?? 10;
|
||||
const pageSize = options.pageSize ?? 20;
|
||||
let totalScanned = 0;
|
||||
|
||||
for (let page = 1; page <= maxPages; page++) {
|
||||
const logPage = await listWorkflowLogs(client, pipelineId, {
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
|
||||
const jobs = logPage.jobList || [];
|
||||
if (!jobs.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
// 并发提取当前页所有 Job 详情以解析其单号
|
||||
const batchDetails = await Promise.allSettled(
|
||||
jobs.map(async (j) => {
|
||||
try {
|
||||
const detail = await getJob(client, j.jobId);
|
||||
return { summary: j, detail };
|
||||
} catch {
|
||||
return { summary: j, detail: null };
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const cacheBatch: WorkflowJobCacheRecord[] = [];
|
||||
let matchedJob: WorkflowJobDetail | null = null;
|
||||
|
||||
for (const item of batchDetails) {
|
||||
if (item.status !== "fulfilled") continue;
|
||||
const { summary, detail } = item.value;
|
||||
totalScanned++;
|
||||
|
||||
const parsedCode = detail ? extractJobFlowCode(detail) : undefined;
|
||||
const parsedFlowId = detail?.inputs?.flowId || undefined;
|
||||
const userName = detail?.inputs?.userInfo?.name || undefined;
|
||||
|
||||
let recordTime: number | undefined;
|
||||
if (summary.executeTime) {
|
||||
const t = typeof summary.executeTime === "number" ? summary.executeTime : new Date(summary.executeTime).getTime();
|
||||
recordTime = Number.isNaN(t) ? undefined : t;
|
||||
} else if (detail?.startTime) {
|
||||
const t = typeof detail.startTime === "number" ? detail.startTime : new Date(detail.startTime).getTime();
|
||||
recordTime = Number.isNaN(t) ? undefined : t;
|
||||
}
|
||||
|
||||
cacheBatch.push({
|
||||
corpId,
|
||||
pipelineId,
|
||||
jobId: summary.jobId,
|
||||
flowCode: parsedCode,
|
||||
flowId: parsedFlowId,
|
||||
executeTime: recordTime,
|
||||
status: summary.status || detail?.status,
|
||||
userName,
|
||||
});
|
||||
|
||||
if (
|
||||
parsedCode &&
|
||||
(parsedCode === targetCode || parsedCode.toUpperCase() === targetCode.toUpperCase())
|
||||
) {
|
||||
matchedJob = detail;
|
||||
}
|
||||
}
|
||||
|
||||
// 将拉取到的索引批量落盘至本地 SQLite 缓存
|
||||
try {
|
||||
upsertWorkflowJobIndex(cacheBatch);
|
||||
} catch {}
|
||||
|
||||
// 一旦命中立即短路熔断,返回目标单据的完整 Job 记录
|
||||
if (matchedJob) {
|
||||
return {
|
||||
found: true,
|
||||
source: "scan",
|
||||
job: matchedJob,
|
||||
jobId: matchedJob.id,
|
||||
flowCode: targetCode,
|
||||
scannedPages: page,
|
||||
totalScanned,
|
||||
};
|
||||
}
|
||||
|
||||
if (page >= (logPage.totalPages || 0)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
found: false,
|
||||
flowCode: targetCode,
|
||||
scannedPages: maxPages,
|
||||
totalScanned,
|
||||
};
|
||||
}
|
||||
@@ -46,8 +46,8 @@ export interface AvailableWorkflowNodes {
|
||||
export interface GrantWorkflowNodesOptions {
|
||||
nodes: string[];
|
||||
password?: string;
|
||||
/** 覆盖灰度开通网关地址;缺省使用环境变量 HOSE_GRAY_GATEWAY_URL。 */
|
||||
gatewayUrl?: string;
|
||||
/** 显式选择 piper-test.ekuaibao.net;默认使用标准 Piper。 */
|
||||
isTest?: boolean;
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesResult {
|
||||
@@ -55,6 +55,7 @@ export interface GrantWorkflowNodesResult {
|
||||
saved: string[];
|
||||
skipped: string[];
|
||||
rawMessage: string;
|
||||
isTest?: boolean;
|
||||
}
|
||||
|
||||
// ── 员工 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ValidationError } from "../../../../core/errors.js";
|
||||
|
||||
export interface GrayNodeItem {
|
||||
displayName: string;
|
||||
name: string;
|
||||
@@ -121,16 +123,44 @@ export const GRAY_NODES_CATALOG: readonly GrayNodeItem[] = [
|
||||
];
|
||||
|
||||
const typeMap = new Map<string, GrayNodeItem>();
|
||||
const nameMap = new Map<string, GrayNodeItem>();
|
||||
const nameCandidates = new Map<string, GrayNodeItem[]>();
|
||||
|
||||
for (const item of GRAY_NODES_CATALOG) {
|
||||
typeMap.set(item.type.toLowerCase(), item);
|
||||
nameMap.set(item.displayName.toLowerCase(), item);
|
||||
const key = item.displayName.toLowerCase();
|
||||
const bucket = nameCandidates.get(key) ?? [];
|
||||
bucket.push(item);
|
||||
nameCandidates.set(key, bucket);
|
||||
}
|
||||
|
||||
export function findGrayNode(query: string): GrayNodeItem | undefined {
|
||||
export function findGrayNodeCandidates(query: string): GrayNodeItem[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
return typeMap.get(q) || nameMap.get(q);
|
||||
const byType = typeMap.get(q);
|
||||
if (byType) return [byType];
|
||||
return nameCandidates.get(q) ?? [];
|
||||
}
|
||||
|
||||
/** 同名中文节点存在多个类型时返回 undefined,避免静默选中最后一个。 */
|
||||
export function findGrayNode(query: string): GrayNodeItem | undefined {
|
||||
const candidates = findGrayNodeCandidates(query);
|
||||
return candidates.length === 1 ? candidates[0] : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化节点输入:中文名 -> type;同名多类型时抛 ValidationError,
|
||||
* 要求调用方改用明确的 type。清单外的 type 原样保留(灰度清单不是全集)。
|
||||
*/
|
||||
export function normalizeGrayNodes(nodes: string[]): string[] {
|
||||
return nodes.map((raw) => {
|
||||
const q = raw.trim();
|
||||
const candidates = findGrayNodeCandidates(q);
|
||||
if (candidates.length > 1) {
|
||||
throw new ValidationError(
|
||||
`节点名称「${q}」对应多个灰度类型: ${candidates.map((c) => c.type).join(", ")};请改用明确的 type`
|
||||
);
|
||||
}
|
||||
return candidates[0]?.type ?? q;
|
||||
});
|
||||
}
|
||||
|
||||
export function isKnownGrayNodeType(type: string): boolean {
|
||||
|
||||
@@ -89,6 +89,59 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
|
||||
expect(res.issues).toHaveLength(0);
|
||||
expect(res.referencedNodes[0].exists).toBe(true);
|
||||
});
|
||||
|
||||
it("flags unscoped block assignment in MVEL conditional branches", () => {
|
||||
const badCode = `
|
||||
var upstream = action_calc;
|
||||
while (upstream != null) {
|
||||
if (upstream > 0) {
|
||||
pEnd = 100;
|
||||
} else {
|
||||
pEnd = 200;
|
||||
}
|
||||
}
|
||||
return pEnd;
|
||||
`;
|
||||
const existing = new Set(["action_calc"]);
|
||||
const res = lintMvelCode(badCode, existing);
|
||||
const branchIssue = res.issues.find((i) => i.rule === "mvel-unscoped-block-assignment");
|
||||
expect(branchIssue).toBeDefined();
|
||||
expect(branchIssue?.message).toContain("pEnd");
|
||||
expect(branchIssue?.level).toBe("warning");
|
||||
});
|
||||
|
||||
it("passes MVEL code when branch variable is initialized at outer scope or uses ternary", () => {
|
||||
const safeCode = `
|
||||
var upstream = action_calc;
|
||||
pEnd = 0;
|
||||
while (upstream != null) {
|
||||
if (upstream > 0) {
|
||||
pEnd = 100;
|
||||
}
|
||||
}
|
||||
return pEnd;
|
||||
`;
|
||||
const existing = new Set(["action_calc"]);
|
||||
const res = lintMvelCode(safeCode, existing);
|
||||
expect(res.issues.some((i) => i.rule === "mvel-unscoped-block-assignment")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects unsupported break keyword in MVEL code", () => {
|
||||
const codeWithBreak = `
|
||||
var upstream = action_calc;
|
||||
while (upstream != null) {
|
||||
if (upstream > 10) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return upstream;
|
||||
`;
|
||||
const res = lintMvelCode(codeWithBreak, new Set(["action_calc"]));
|
||||
const breakIssue = res.issues.find((i) => i.rule === "mvel-unsupported-break");
|
||||
expect(breakIssue).toBeDefined();
|
||||
expect(breakIssue?.level).toBe("error");
|
||||
expect(breakIssue?.message).toContain("break");
|
||||
});
|
||||
});
|
||||
|
||||
describe("lintWorkflowScripts", () => {
|
||||
|
||||
@@ -154,9 +154,96 @@ export function lintMvelCode(
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 检查条件分支块 (if / else / switch / case / catch) 内部首次赋值但未在外部作用域预先声明的变量
|
||||
// 杜绝 MVEL2 ReflectiveAccessorOptimizer 误将局部变量当属性反射而触发 unresolvable property or identifier 运行时异常
|
||||
checkMvelUnscopedBlockAssignments(executableCode, issues);
|
||||
|
||||
// 4. 检查 MVEL2 不支持的 break 控制流关键字
|
||||
// MVEL2 解释器在循环中不支持 break,会误触发属性查找并抛出 unresolvable property or identifier: break
|
||||
const breakRegex = /\bbreak\b/g;
|
||||
let breakMatch: RegExpExecArray | null;
|
||||
while ((breakMatch = breakRegex.exec(executableCode)) !== null) {
|
||||
const textBefore = executableCode.slice(0, breakMatch.index);
|
||||
const lineNum = textBefore.split("\n").length;
|
||||
const lastNewline = textBefore.lastIndexOf("\n");
|
||||
const colNum = breakMatch.index - (lastNewline >= 0 ? lastNewline : 0);
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: lineNum,
|
||||
column: colNum,
|
||||
rule: "mvel-unsupported-break",
|
||||
message: "MVEL2 运行时不支持 break 关键字,在循环内使用 break 会被解析器当成未声明属性查找而抛出 'unresolvable property or identifier: break' 致命异常;请改用 boolean 标志位条件控制循环终止",
|
||||
});
|
||||
}
|
||||
|
||||
return { issues, referencedNodes, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查条件分支块内部首次赋值但未在外部预先初始化的变量
|
||||
*/
|
||||
function checkMvelUnscopedBlockAssignments(executableCode: string, issues: ScriptIssue[]): void {
|
||||
const lines = executableCode.split(/\r?\n/);
|
||||
const knownVars = new Set([
|
||||
"bill", "result", "items", "success", "message", "System",
|
||||
"true", "false", "null", "Double", "Integer", "Long", "Float", "String", "Math", "Calendar", "Date",
|
||||
]);
|
||||
|
||||
let inBranchBlock = 0;
|
||||
const branchBraceDepths: number[] = [];
|
||||
let pendingBranch = false;
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const line = lines[l];
|
||||
|
||||
if (/\b(if|else|catch|switch|case)\b/.test(line)) {
|
||||
pendingBranch = true;
|
||||
}
|
||||
|
||||
for (let c = 0; c < line.length; c++) {
|
||||
const ch = line[c];
|
||||
if (ch === "{") {
|
||||
if (pendingBranch) {
|
||||
branchBraceDepths.push(branchBraceDepths.length + 1);
|
||||
inBranchBlock++;
|
||||
pendingBranch = false;
|
||||
} else {
|
||||
branchBraceDepths.push(0);
|
||||
}
|
||||
} else if (ch === "}") {
|
||||
if (branchBraceDepths.length > 0) {
|
||||
const depth = branchBraceDepths.pop();
|
||||
if (depth && depth > 0) inBranchBlock--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const assignRegex = /(?:^|[^\w$.])([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=(?!=)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = assignRegex.exec(line)) !== null) {
|
||||
const varName = m[1];
|
||||
if (["if", "else", "while", "for", "return", "new", "throw", "try", "catch", "finally", "switch", "case"].includes(varName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inBranchBlock > 0) {
|
||||
if (!knownVars.has(varName)) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
line: l + 1,
|
||||
column: m.index + 1,
|
||||
rule: "mvel-unscoped-block-assignment",
|
||||
message: `变量 [${varName}] 在条件分支块内部首次被赋值,但在外层作用域未预先声明或初始化;在 MVEL2 优化编译模式下极易触发 'unresolvable property or identifier' 运行时异常,建议在外部提前声明/初始化 (如: ${varName} = null;) 或改用三元表达式`,
|
||||
});
|
||||
knownVars.add(varName);
|
||||
}
|
||||
} else {
|
||||
knownVars.add(varName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集工作流任务树中所有节点标识
|
||||
*/
|
||||
|
||||
@@ -18,6 +18,12 @@ export {
|
||||
getJobExecutionLevel,
|
||||
getExecutionLogs,
|
||||
} from "./execution/queries.js";
|
||||
export {
|
||||
searchWorkflowJobByFlowCode,
|
||||
extractJobFlowCode,
|
||||
type SearchJobByFlowOptions,
|
||||
type SearchJobByFlowResult,
|
||||
} from "./execution/search-by-flow.js";
|
||||
export type {
|
||||
WorkflowClients,
|
||||
ListAllWorkflowsOptions,
|
||||
@@ -44,6 +50,7 @@ export {
|
||||
resolveWorkflowEnumOptions,
|
||||
getWorkflowAvailableNodes,
|
||||
grantWorkflowNodes,
|
||||
GRANT_ATTACHED_OPTIONS,
|
||||
} from "./catalog/catalog.js";
|
||||
export {
|
||||
getWebhookInfo,
|
||||
@@ -81,3 +88,11 @@ export {
|
||||
|
||||
export * from "./index.js";
|
||||
export { webhookTriggerUrl } from "./triggers/index.js";
|
||||
export {
|
||||
getOutboundMessages,
|
||||
queryOutboundMessageLogs,
|
||||
type OutboundMessageConfig,
|
||||
type OutboundMessageLogItem,
|
||||
type OutboundLogQueryOptions,
|
||||
} from "./transport/outbound/index.js";
|
||||
|
||||
@@ -10,15 +10,22 @@
|
||||
|
||||
## 写入结果判定
|
||||
|
||||
所有写操作(保存、刷新 chooses、删除、启停)统一走 `readEasoWriteResponse`:先按 HTTP 状态,再解析 body 中的业务码 `code`。
|
||||
- 无返回体的写操作(保存、刷新 chooses、删除、启停)走 `readEasoWriteResponse`。
|
||||
- 有返回体的写操作(灰度节点开通)走 `assertNoAuthFailure` 做统一认证判定;业务码判定与 `saved`/`skipped` 映射属于编排层 `catalog/catalog.ts`,不放在传输层。
|
||||
- 两者都先按 HTTP 状态、再解析 body 业务码 `code`,且 401/403 一律转成 `AuthenticationError`(CLI 退出码 11)。
|
||||
|
||||
**HTTP 200 不等于业务成功**,只看状态码会把未生效的写操作报成成功。
|
||||
|
||||
## 灰度开通网关 (grantWorkflowNodesApi)
|
||||
## 灰度节点开通 (grantWorkflowNodesApi)
|
||||
|
||||
| 项目 | 说明 |
|
||||
|---|---|
|
||||
| 请求地址 | `resolveGrayGatewayUrl()`:显式 `gatewayUrl` 参数 > 环境变量 `HOSE_GRAY_GATEWAY_URL` > 内置默认 `DEFAULT_GRAY_GATEWAY_URL` |
|
||||
| 环境变量用途 | 网关托管在第三方域,实例可能被回收或迁移;配置环境变量可在不改代码的情况下切换网关 |
|
||||
| `baseUrl` 参数 | 目标合思租户地址,作为 body 字段交给网关定位企业,与网关自身地址无关 |
|
||||
| 成功判定 | 优先取显式 `success` 布尔值,其次取 `code === 200`;**两者都缺失时判为失败**,不默认成功 |
|
||||
| 失败信息 | 传输异常抛 `EkbApiError`(`GATEWAY_ERROR`),消息带上实际请求的网关地址 |
|
||||
| 换票 | 通过企业 `baseUrl` 的 `/api/engine/realm/$EASO/actions/jwt` 获取 EASO JWT;复用 `fetchEasoJwt`,去除 `baseUrl` 末尾斜线 |
|
||||
| 开通请求 | 携带 EASO JWT 直接 POST 到 Piper 的 `/api/easo/dsl/corporation`;地址经 `resolvePiperBaseUrl(isTest)` 解析,可用 `HOSE_PIPER_BASE_URL` / `HOSE_PIPER_TEST_BASE_URL` 覆盖,常量收口在 `core/http/piper-endpoints.ts`。每个企业的工作流只在其中一个 Piper 环境,不会同时支持两者;请求失败时不自动切换 |
|
||||
| payload | 由编排层 `catalog/catalog.ts` 显式构造;固定附带 `recalculate-the-approval-flow`、`ui-notification`、`start`,dry-run 与成功输出均会展示 |
|
||||
| 成功判定 | 传输层只做响应与认证校验;业务码 `code === 200`、`saved`/`skipped` 由编排层判定,HTTP 200 本身不作为成功依据 |
|
||||
| 生产拦截 | CLI 层 `handleGrantNodes` 对 `isCorpProd` 企业直接拒绝,无 `--force` 逃生口;`--is-test` 只是 Piper 域名开关,不构成环境授权 |
|
||||
| 结果 | 保留服务端消息,并将新开通节点映射到 `saved`、已开通节点映射到 `skipped` |
|
||||
| 凭证 | access token 与 EASO JWT 只用于本机直连请求,不写入日志或返回结果 |
|
||||
|
||||
环境由调用方显式选择:`isTest` 只切换 Piper 目标地址,不由企业名称、本地 `env=test` 或 EASO 换票使用的 `baseUrl` 推断。通过某一环境成功开通能确认企业对应的工作流环境;另一环境对同一企业不适用。`--dry-run` 不会发请求或探测环境,失败响应还需结合认证与业务错误判断,不能仅凭失败认定环境选错。
|
||||
@@ -1,8 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { EkbApiError } from "../../../../../core/errors.js";
|
||||
import { EkbApiError, EkbError } from "../../../../../core/errors.js";
|
||||
import { fetchEasoJwt, resolvePiperBaseUrl } from "../../../../../core/http/script-engine-client.js";
|
||||
import { EKB_BASE_URL } from "../../../../../core/http/unity-client.js";
|
||||
import { WorkflowDslSchema, WorkflowDslCatalogSchema, StaffSchema, WorkflowEnumItemSchema, type WorkflowEnumItem } from "../../types.js";
|
||||
import { unwrap } from "../response.js";
|
||||
import { unwrap, assertNoAuthFailure } from "../response.js";
|
||||
|
||||
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -69,71 +71,74 @@ export async function getWorkflowEnumOptions(
|
||||
return unwrap(response, z.array(WorkflowEnumItemSchema));
|
||||
}
|
||||
|
||||
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
|
||||
// ── 灰度节点开通 (EASO -> Piper) ─────────────────────────────────────────────
|
||||
|
||||
/** 网关地址环境变量。网关托管在第三方域,实例可能被回收或迁移,必须允许覆盖。 */
|
||||
export const GRAY_GATEWAY_URL_ENV = "HOSE_GRAY_GATEWAY_URL";
|
||||
export const DEFAULT_GRAY_GATEWAY_URL = "https://d9jxeccs5j.sealosgzg.site";
|
||||
export const GRAY_GATEWAY_PATH = "/hose-workflow-node";
|
||||
const WorkflowNodeGrantResponseSchema = z.object({
|
||||
code: z.union([z.number(), z.string()]).optional(),
|
||||
msg: z.string().optional(),
|
||||
data: z.object({
|
||||
saved: z.array(z.string()).optional(),
|
||||
skipped: z.array(z.string()).optional(),
|
||||
}).passthrough().nullable().optional(),
|
||||
}).passthrough();
|
||||
|
||||
/**
|
||||
* 解析网关请求地址:显式参数 > 环境变量 > 内置默认。
|
||||
* 网关默认地址指向第三方托管实例(`.sealosgzg.site`),同类实例曾被回收;
|
||||
* 硬编码且无逃生口会导致 `workflow nodes grant` 全线瘫痪且无从切换。
|
||||
*/
|
||||
export function resolveGrayGatewayUrl(explicit?: string): string {
|
||||
const candidate = (
|
||||
explicit ??
|
||||
process.env[GRAY_GATEWAY_URL_ENV] ??
|
||||
DEFAULT_GRAY_GATEWAY_URL
|
||||
).trim();
|
||||
return `${candidate.replace(/\/+$/, "")}${GRAY_GATEWAY_PATH}`;
|
||||
// 兼容历史导入路径;常量已收敛到 core/http/piper-endpoints.ts
|
||||
export { SCRIPT_ENGINE_TEST_BASE_URL } from "../../../../../core/http/piper-endpoints.js";
|
||||
|
||||
function normalizeEkbBaseUrl(baseUrl?: string): string {
|
||||
return (baseUrl || EKB_BASE_URL).trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定网关是否真的开通成功。缺字段不默认为成功:开通未生效会让下游
|
||||
* `analyze` 依旧报 PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
*/
|
||||
export function interpretGatewayOutcome(json: any): boolean {
|
||||
if (typeof json?.success === "boolean") return json.success;
|
||||
if (json?.code !== undefined && json?.code !== null) return Number(json.code) === 200;
|
||||
// 缺少明确成功/失败标记时不默认成功:开通未生效会让下游 analyze 依旧报
|
||||
// PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
return false;
|
||||
}
|
||||
export type WorkflowNodeGrantResponse = z.infer<typeof WorkflowNodeGrantResponseSchema>;
|
||||
|
||||
/**
|
||||
* 传输层只负责换票、POST 与响应校验。
|
||||
* payload 组装、业务码判定与 saved/skipped 映射属于业务编排,见 catalog/catalog.ts。
|
||||
*/
|
||||
export async function grantWorkflowNodesApi(options: {
|
||||
token: string;
|
||||
corpId: string;
|
||||
nodes: string[];
|
||||
/** 目标合思租户地址,网关据此定位要开通的企业。 */
|
||||
staffId: string;
|
||||
payload: Record<string, unknown>;
|
||||
isTest?: boolean;
|
||||
/** 目标企业合思地址,用于 EASO JWT 换票。 */
|
||||
baseUrl?: string;
|
||||
/** 网关自身地址;缺省依次使用环境变量 HOSE_GRAY_GATEWAY_URL 与内置默认地址。 */
|
||||
gatewayUrl?: string;
|
||||
}): Promise<import("../../types.js").GrantWorkflowNodesResult> {
|
||||
const payload = {
|
||||
token: options.token,
|
||||
corpId: options.corpId,
|
||||
nodes: options.nodes.join(","),
|
||||
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
||||
};
|
||||
const gatewayUrl = resolveGrayGatewayUrl(options.gatewayUrl);
|
||||
}): Promise<WorkflowNodeGrantResponse> {
|
||||
const baseUrl = normalizeEkbBaseUrl(options.baseUrl);
|
||||
let easoJwt: string;
|
||||
try {
|
||||
easoJwt = await fetchEasoJwt(
|
||||
options.token,
|
||||
options.corpId,
|
||||
options.staffId,
|
||||
baseUrl,
|
||||
);
|
||||
} catch (err: any) {
|
||||
if (err instanceof EkbError) throw err;
|
||||
throw new EkbApiError(
|
||||
`灰度节点开通 EASO 换票失败: ${err?.message || String(err)}`,
|
||||
"EASO_ERROR",
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await ky.post(gatewayUrl, {
|
||||
json: payload,
|
||||
timeout: 30000,
|
||||
// 每个企业的工作流只对应标准或测试 Piper 之一;显式选择,不探测或自动回退。
|
||||
const piperBaseUrl = resolvePiperBaseUrl(options.isTest);
|
||||
const response = await ky.post(`${piperBaseUrl}/api/easo/dsl/corporation`, {
|
||||
json: options.payload,
|
||||
headers: { Authorization: `Bearer ${easoJwt}` },
|
||||
timeout: 15000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
return {
|
||||
success: interpretGatewayOutcome(json),
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
};
|
||||
const raw = await response.json();
|
||||
const record = raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>)
|
||||
: undefined;
|
||||
// 401/403 统一交给 EASO 响应体系转成 AuthenticationError(CLI 退出码 11)
|
||||
assertNoAuthFailure(record, response as unknown as Response);
|
||||
return WorkflowNodeGrantResponseSchema.parse(raw);
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败 (${gatewayUrl}): ${message}`, "GATEWAY_ERROR", 502);
|
||||
if (err instanceof EkbError) throw err;
|
||||
throw new EkbApiError(`灰度节点开通 Piper 请求失败: ${err?.message || String(err)}`, "PIPER_ERROR", 502);
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
|
||||
/**
|
||||
* 灰度开通网关的行为测试。网关地址托管在第三方域,且历史实例曾被回收,
|
||||
* 必须保证「地址可覆盖」与「成功判定不默认为真」这两件事被固化下来。
|
||||
*
|
||||
* 这里刻意只用纯函数断言 + 对 ky.post 的可恢复 spy:
|
||||
* `mock.module("ky")` 会污染同进程其他用例的 ky 引用。
|
||||
*/
|
||||
const {
|
||||
grantWorkflowNodesApi,
|
||||
resolveGrayGatewayUrl,
|
||||
interpretGatewayOutcome,
|
||||
GRAY_GATEWAY_URL_ENV,
|
||||
DEFAULT_GRAY_GATEWAY_URL,
|
||||
GRAY_GATEWAY_PATH,
|
||||
} = await import("./catalog/api.js");
|
||||
|
||||
const ORIGINAL_ENV = process.env[GRAY_GATEWAY_URL_ENV];
|
||||
|
||||
function restoreEnv(): void {
|
||||
if (ORIGINAL_ENV === undefined) delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
else process.env[GRAY_GATEWAY_URL_ENV] = ORIGINAL_ENV;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv();
|
||||
});
|
||||
|
||||
describe("gray gateway address resolution", () => {
|
||||
it("falls back to the built-in default host", () => {
|
||||
delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
expect(resolveGrayGatewayUrl()).toBe(`${DEFAULT_GRAY_GATEWAY_URL}${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("prefers the environment override and normalizes trailing slashes", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com///";
|
||||
expect(resolveGrayGatewayUrl()).toBe(`https://gw.example.com${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("lets the explicit argument win over the environment", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://ignored.example.com";
|
||||
expect(resolveGrayGatewayUrl("https://explicit.example.com")).toBe(
|
||||
`https://explicit.example.com${GRAY_GATEWAY_PATH}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gray gateway outcome interpretation", () => {
|
||||
it("honours an explicit success flag", () => {
|
||||
expect(interpretGatewayOutcome({ success: true })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ success: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a non-200 business code as failure", () => {
|
||||
expect(interpretGatewayOutcome({ code: 200 })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ code: 500 })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not assume success when the gateway omits any verdict", () => {
|
||||
expect(interpretGatewayOutcome({ msg: "ok" })).toBe(false);
|
||||
expect(interpretGatewayOutcome({})).toBe(false);
|
||||
expect(interpretGatewayOutcome(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("grantWorkflowNodesApi request contract", () => {
|
||||
it("posts to the resolved gateway and keeps tenant baseUrl in the payload", async () => {
|
||||
let requestedUrl = "";
|
||||
let payload: Record<string, unknown> = {};
|
||||
spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
|
||||
requestedUrl = String(url);
|
||||
payload = options?.json ?? {};
|
||||
return { ok: true, status: 200, json: async () => ({ success: true, data: { saved: ["code-js2"], skipped: [] } }) };
|
||||
}) as never);
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "tok",
|
||||
corpId: "corp-1",
|
||||
nodes: ["code-js2"],
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.saved).toEqual(["code-js2"]);
|
||||
expect(requestedUrl).toContain("/hose-workflow-node");
|
||||
expect(payload.corpId).toBe("corp-1");
|
||||
expect(payload.baseUrl).toBe("https://app.ekuaibao.com");
|
||||
});
|
||||
|
||||
it("includes the gateway url in transport failures", async () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com";
|
||||
spyOn(ky, "post").mockImplementation((async () => {
|
||||
throw new Error("connect ETIMEDOUT");
|
||||
}) as never);
|
||||
|
||||
await expect(
|
||||
grantWorkflowNodesApi({ token: "tok", corpId: "corp-1", nodes: ["code-js2"] })
|
||||
).rejects.toThrow(/https:\/\/gw\.example\.com\/hose-workflow-node/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
import { grantWorkflowNodesApi, SCRIPT_ENGINE_TEST_BASE_URL } from "./catalog/api.js";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import { GRANT_ATTACHED_OPTIONS, grantWorkflowNodes, mapGrantResult } from "../catalog/catalog.js";
|
||||
import { normalizeGrayNodes } from "../nodes/gray-nodes-catalog.js";
|
||||
|
||||
describe("grantWorkflowNodesApi transport", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
spies = [];
|
||||
});
|
||||
|
||||
function mockJwt(): void {
|
||||
spies.push(spyOn(ky, "get").mockImplementation((() => ({
|
||||
json: async () => ({ id: "business-jwt" }),
|
||||
})) as never));
|
||||
}
|
||||
|
||||
it("exchanges EASO JWT and posts the caller-supplied payload unchanged", async () => {
|
||||
mockJwt();
|
||||
let requestedUrl = "";
|
||||
let requestOptions: any;
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
|
||||
requestedUrl = url;
|
||||
requestOptions = options;
|
||||
return { json: async () => ({ code: 200, msg: "新开通的节点:code" }) };
|
||||
}) as never));
|
||||
|
||||
const payload = {
|
||||
corporationId: "corp-1",
|
||||
dslTypes: ["code"],
|
||||
...GRANT_ATTACHED_OPTIONS,
|
||||
};
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
baseUrl: "https://app.ekuaibao.com///",
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ code: 200, msg: "新开通的节点:code" });
|
||||
expect(ky.get).toHaveBeenCalledWith(
|
||||
"https://app.ekuaibao.com/api/engine/realm/$EASO/actions/jwt",
|
||||
expect.objectContaining({
|
||||
searchParams: { corpId: "corp-1" },
|
||||
headers: expect.objectContaining({
|
||||
accesstoken: "access-token",
|
||||
corpid: "corp-1",
|
||||
staffid: "corp-1:staff-1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(requestedUrl).toBe("https://piper.ekuaibao.com/api/easo/dsl/corporation");
|
||||
expect(requestOptions.headers).toEqual({ Authorization: "Bearer business-jwt" });
|
||||
expect(requestOptions.json).toEqual(payload);
|
||||
});
|
||||
|
||||
it("uses the test Piper endpoint only when isTest is explicitly enabled", async () => {
|
||||
mockJwt();
|
||||
let requestedUrl = "";
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async (url: string) => {
|
||||
requestedUrl = url;
|
||||
return { json: async () => ({ code: 200, msg: "新开通的节点:code" }) };
|
||||
}) as never));
|
||||
|
||||
await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
payload: { dslTypes: ["code"] },
|
||||
isTest: true,
|
||||
});
|
||||
|
||||
expect(requestedUrl).toBe(`${SCRIPT_ENGINE_TEST_BASE_URL}/api/easo/dsl/corporation`);
|
||||
});
|
||||
|
||||
it("maps 401/403 business codes to AuthenticationError for CLI exit code 11", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 403, msg: "无该自建应用权限" }),
|
||||
})) as never));
|
||||
|
||||
await expect(grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
payload: { dslTypes: ["code"] },
|
||||
})).rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
|
||||
it("returns the raw failing business code so the orchestrator can report success:false", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 500, msg: "JWT 签名无效" }),
|
||||
})) as never));
|
||||
|
||||
const record = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
payload: { dslTypes: ["code"] },
|
||||
});
|
||||
|
||||
expect(mapGrantResult(record, false)).toEqual({
|
||||
success: false, saved: [], skipped: [], rawMessage: "JWT 签名无效", isTest: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps EASO exchange transport failures to a domain API error", async () => {
|
||||
spies.push(spyOn(ky, "get").mockImplementation((() => {
|
||||
throw new Error("Request failed with status code 404");
|
||||
}) as never));
|
||||
|
||||
await expect(grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
payload: { dslTypes: ["code"] },
|
||||
})).rejects.toThrow("灰度节点开通 EASO 换票失败: Request failed with status code 404");
|
||||
});
|
||||
|
||||
it("surfaces Piper transport failures without exposing credentials", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => {
|
||||
throw new Error("connect ETIMEDOUT");
|
||||
}) as never));
|
||||
|
||||
await expect(grantWorkflowNodesApi({
|
||||
token: "secret-access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
payload: { dslTypes: ["code"] },
|
||||
})).rejects.toThrow("灰度节点开通 Piper 请求失败: connect ETIMEDOUT");
|
||||
});
|
||||
});
|
||||
|
||||
describe("grantWorkflowNodes orchestration", () => {
|
||||
it("maps saved/skipped from structured data and from Chinese fallback messages", () => {
|
||||
expect(mapGrantResult({ code: 200, data: { saved: ["code"], skipped: ["risk"] } }, true)).toEqual({
|
||||
success: true, saved: ["code"], skipped: ["risk"], rawMessage: "", isTest: true,
|
||||
});
|
||||
expect(mapGrantResult({ code: 200, msg: "新开通的节点:code, risk" }, false).saved).toEqual(["code", "risk"]);
|
||||
expect(mapGrantResult({ code: 200, msg: "以下节点已开通,不再重复开通:code" }, false).skipped).toEqual(["code"]);
|
||||
expect(mapGrantResult({ code: 500, msg: "拒绝" }, false).success).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes Chinese names and rejects ambiguous ones instead of silently picking one", () => {
|
||||
expect(normalizeGrayNodes(["JS节点(新)"])).toEqual(["code-js2"]);
|
||||
expect(normalizeGrayNodes(["mapping", "dmn"])).toEqual(["mapping", "dmn"]);
|
||||
expect(() => normalizeGrayNodes(["数据映射"])).toThrow("多个灰度类型");
|
||||
});
|
||||
|
||||
it("rejects an ambiguous Chinese node before issuing any request", async () => {
|
||||
const corp = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
env: "test",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff" },
|
||||
} as any;
|
||||
await expect(grantWorkflowNodes(corp, { nodes: ["数据映射"] })).rejects.toThrow("多个灰度类型");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { OutboundMessageConfig, OutboundMessageLogItem, OutboundLogQueryOptions } from "./types.js";
|
||||
|
||||
/**
|
||||
* 传输层:查询指定企业配置的出站消息列表
|
||||
* 对应合思底层接口:GET api/outbound/v1/message
|
||||
*/
|
||||
export async function getOutboundMessages(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<OutboundMessageConfig[]> {
|
||||
const response = await client.get("api/outbound/v1/message", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return (json.items ?? []) as OutboundMessageConfig[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 传输层:分页查询出站消息投递执行日志
|
||||
* 对应合思底层接口:POST api/outbound/v1/message/messageLog
|
||||
*/
|
||||
export async function queryOutboundMessageLogs(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: OutboundLogQueryOptions = {}
|
||||
): Promise<{ count: number; items: OutboundMessageLogItem[] }> {
|
||||
const messageType = options.messageType ?? "flow";
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
limit: { start, count },
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,type,createTime,messageType",
|
||||
};
|
||||
|
||||
if (options.filterBy) {
|
||||
body.filterBy = options.filterBy;
|
||||
} else if (options.code) {
|
||||
body.filterBy = `(flowId.form.code==("${options.code.replace(/"/g, '\\"')}"))`;
|
||||
}
|
||||
|
||||
const response = await client.post("api/outbound/v1/message/messageLog", {
|
||||
searchParams: {
|
||||
messageType,
|
||||
corpId,
|
||||
},
|
||||
json: body,
|
||||
});
|
||||
|
||||
const json = (await response.json()) as { count?: number; items?: OutboundMessageLogItem[] };
|
||||
return {
|
||||
count: json.count ?? json.items?.length ?? 0,
|
||||
items: json.items ?? [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./api.js";
|
||||
export * from "./types.js";
|
||||
@@ -0,0 +1,60 @@
|
||||
export interface OutboundMessageConfig {
|
||||
id: string;
|
||||
messageName?: string;
|
||||
messageType?: "flow" | "message" | "InternalMessage" | "dataLink" | string;
|
||||
enable?: boolean;
|
||||
callbackUrl?: string;
|
||||
signKey?: string;
|
||||
actionEvent?: string[] | null;
|
||||
formFields?: string[];
|
||||
conditions?: Array<{
|
||||
left?: string;
|
||||
operator?: string;
|
||||
right?: { type?: string; value?: unknown };
|
||||
}> | null;
|
||||
remark?: string | null;
|
||||
corporationId?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface OutboundMessageLogItem {
|
||||
id: string;
|
||||
name: string;
|
||||
type: "INVOKING" | "CALLBACK" | string;
|
||||
state: "SUCCESS" | "FAILED" | string;
|
||||
flowId?: {
|
||||
id?: string;
|
||||
form?: {
|
||||
code?: string;
|
||||
};
|
||||
};
|
||||
nodeName?: string;
|
||||
createTime: number;
|
||||
messageType?: string;
|
||||
request?: {
|
||||
code?: string;
|
||||
flowId?: string;
|
||||
nodeId?: string;
|
||||
messageId?: string;
|
||||
corporationId?: string;
|
||||
action?: string;
|
||||
comment?: string;
|
||||
signKey?: string;
|
||||
formSpecification?: {
|
||||
specificationId?: string;
|
||||
specificationName?: string;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
};
|
||||
response?: unknown;
|
||||
}
|
||||
|
||||
export interface OutboundLogQueryOptions {
|
||||
messageType?: string;
|
||||
code?: string;
|
||||
filterBy?: string;
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
@@ -44,6 +44,22 @@ export async function readEasoWriteResponse(response: Response): Promise<void> {
|
||||
checkEasoResponse(response, raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* 有返回体的写接口(如灰度节点开通)复用统一认证判定:
|
||||
* 业务码 / HTTP 401、403 一律转成 AuthenticationError,交给 CLI 映射退出码 11。
|
||||
* 其余业务失败留给编排层按自身契约判定(例如返回 success: false)。
|
||||
*/
|
||||
export function assertNoAuthFailure(
|
||||
record: Record<string, unknown> | undefined,
|
||||
response: Response
|
||||
): void {
|
||||
const code = record?.code;
|
||||
const status = response.status || (typeof code === "number" ? code : 500);
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throwEasoResponseError(response, record);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const { raw, record } = await readEasoResponse(response);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { WorkflowTask } from "../types.js";
|
||||
import { resolvePiperBaseUrl } from "../../../../core/http/piper-endpoints.js";
|
||||
|
||||
/** 复制的工作流需要独立的 Webhook 地址和样本。 */
|
||||
export function resetCopiedWebhookTrigger(task?: WorkflowTask): void {
|
||||
@@ -14,5 +15,7 @@ export function ensureWebhookTriggerPath(task: WorkflowTask): void {
|
||||
export function webhookTriggerUrl(task: WorkflowTask): string | undefined {
|
||||
const rawPath = [task.urlPath, task.url, task.path].find((value) => typeof value === "string" && value);
|
||||
if (typeof rawPath !== "string") return undefined;
|
||||
return rawPath.startsWith("http") ? rawPath : `https://piper.ekuaibao.com/api/webhook/${rawPath.replace(/^\/+/, "")}`;
|
||||
return rawPath.startsWith("http")
|
||||
? rawPath
|
||||
: `${resolvePiperBaseUrl()}/api/webhook/${rawPath.replace(/^\/+/, "")}`;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
import { handleHttpRequest } from "./routes.js";
|
||||
import { getScalarStandaloneJs } from "../packaging/embedded-docs.js";
|
||||
|
||||
describe("离线 API 文档", () => {
|
||||
test("HTML 不引用任何 CDN,指向本地路由", () => {
|
||||
const html = renderDocsHtml();
|
||||
expect(html).toContain('src="/static/scalar.js"');
|
||||
expect(html).toContain('data-url="/openapi.json"');
|
||||
expect(html).toContain('id="api-reference"');
|
||||
expect(html).not.toContain("cdn.jsdelivr.net");
|
||||
expect(html).not.toMatch(/src="https?:\/\//);
|
||||
expect(html).toContain("connect-src 'self'");
|
||||
expect(html).toContain("Content-Security-Policy");
|
||||
});
|
||||
|
||||
test("内嵌运行时是完整的 Scalar standalone", () => {
|
||||
const js = getScalarStandaloneJs();
|
||||
expect(js.length).toBeGreaterThan(1_000_000);
|
||||
expect(js).toContain("Scalar");
|
||||
expect(js).not.toContain("</script>");
|
||||
});
|
||||
|
||||
test("GET /static/scalar.js 返回 JS 且与内嵌产物一致", async () => {
|
||||
let status = 0;
|
||||
let headers: Record<string, string> = {};
|
||||
let body = "";
|
||||
const res = {
|
||||
setHeader: (key: string, value: unknown) => { headers[key] = String(value); },
|
||||
writeHead: (code: number, next: Record<string, string>) => {
|
||||
status = code;
|
||||
headers = { ...headers, ...next };
|
||||
},
|
||||
end: (value?: string) => { body = value ?? ""; },
|
||||
headersSent: false,
|
||||
};
|
||||
|
||||
await handleHttpRequest(
|
||||
{ method: "GET", url: "/static/scalar.js", headers: { host: "localhost" } } as never,
|
||||
res as never,
|
||||
{ app: "hose-use" }
|
||||
);
|
||||
|
||||
expect(status).toBe(200);
|
||||
expect(headers["Content-Type"]).toContain("application/javascript");
|
||||
expect(body).toBe(getScalarStandaloneJs());
|
||||
});
|
||||
});
|
||||
+3
-1
@@ -6,6 +6,8 @@ export function renderDocsHtml(): string {
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<!-- 运行时全部资源来自本地:即使 Scalar 内置的"示例规范"分支被触发也发不出外网请求 -->
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:;" />
|
||||
<title>hose-use API Reference (v${VERSION})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
|
||||
<style>
|
||||
@@ -22,7 +24,7 @@ export function renderDocsHtml(): string {
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
src="/static/scalar.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
@@ -4,6 +4,8 @@ import { runCli } from "../cli/runner.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
||||
import { getAiProWebUiHtml } from "../packaging/embedded-webui.js";
|
||||
import { getScalarStandaloneJs } from "../packaging/embedded-docs.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
@@ -118,6 +120,18 @@ export async function handleHttpRequest(
|
||||
return;
|
||||
}
|
||||
|
||||
// AI PRO 本地 Web 控制台:单文件内嵌,仅监听 127.0.0.1
|
||||
if (isAiPro && method === "GET" && (pathname === "/report" || pathname.startsWith("/report/"))) {
|
||||
sendHtml(res, 200, getAiProWebUiHtml());
|
||||
return;
|
||||
}
|
||||
|
||||
// /docs 的 Scalar 运行时由本地提供,彻底去掉 CDN 依赖
|
||||
if (method === "GET" && pathname === "/static/scalar.js") {
|
||||
sendJavascript(res, 200, getScalarStandaloneJs());
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
@@ -228,6 +242,16 @@ function sendHtml(res: ServerResponse, status: number, html: string): void {
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
function sendJavascript(res: ServerResponse, status: number, source: string): void {
|
||||
if (res.headersSent) return;
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "application/javascript; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(source, "utf-8"),
|
||||
"Cache-Control": "public, max-age=86400",
|
||||
});
|
||||
res.end(source);
|
||||
}
|
||||
|
||||
function sendError(res: ServerResponse, status: number, message: string): void {
|
||||
sendJson(res, status, { error: true, message });
|
||||
}
|
||||
|
||||
+2
-1
@@ -48,7 +48,8 @@ export async function startHttpServer(options: HttpServerOptions = {}): Promise<
|
||||
if (!isAiPro) {
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
} else {
|
||||
console.error(` 网关状态接口: GET http://${host}:${port}/v1/status\n`);
|
||||
console.error(` 网关状态接口: GET http://${host}:${port}/v1/status`);
|
||||
console.error(` Web 控制台: http://${host}:${port}/report\n`);
|
||||
}
|
||||
}
|
||||
resolve(server);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Server } from "node:http";
|
||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||
import { startHttpServer } from "./server.js";
|
||||
import { handleHttpRequest } from "./routes.js";
|
||||
import { getAiProWebUiHtml } from "../packaging/embedded-webui.js";
|
||||
|
||||
const PORT = 18989;
|
||||
const BASE = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
describe("AI PRO HTTP daemon Web 控制台", () => {
|
||||
let server: Server | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await startHttpServer({ app: "hose-aipro", port: PORT, silent: true });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server?.close();
|
||||
});
|
||||
|
||||
test("GET /report 返回完整的内嵌 HTML", async () => {
|
||||
const response = await fetch(`${BASE}/report`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("text/html");
|
||||
const html = await response.text();
|
||||
expect(html).toContain('<div id="app">');
|
||||
expect(html).toContain("合思 AI PRO 控制台");
|
||||
expect(html).not.toContain('src="/static/');
|
||||
});
|
||||
|
||||
test("带子路径的 /report/ 同样返回控制台(hash 路由兜底)", async () => {
|
||||
const response = await fetch(`${BASE}/report/sessions`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toBe(getAiProWebUiHtml());
|
||||
});
|
||||
|
||||
test("hose-use 路由不暴露 /report", async () => {
|
||||
// 直接调路由处理器,避免 Bun fetch 在同一 host 跨端口复用连接造成误判
|
||||
let body = "";
|
||||
const res = {
|
||||
setHeader: () => undefined,
|
||||
writeHead: () => undefined,
|
||||
end: (value?: string) => { body = value ?? ""; },
|
||||
headersSent: false,
|
||||
};
|
||||
await handleHttpRequest(
|
||||
{ method: "GET", url: "/report", headers: { host: "localhost" } } as never,
|
||||
res as never,
|
||||
{ app: "hose-use" }
|
||||
);
|
||||
expect(body).not.toContain('<div id="app">');
|
||||
expect(body).toContain("Cannot GET /report");
|
||||
});
|
||||
});
|
||||
@@ -6,8 +6,36 @@
|
||||
|
||||
- `embedded-openapi.ts`:内嵌 `specs/openapi.json`(包装层)与 `specs/openapi.raw.json`(原生下游)两份 OpenAPI 规范,供 `hose-use openapi` 命令与 HTTP 文档页读取;产物由 `scripts/generate/bundle-openapi.ts` / `scripts/generate/generate-raw-openapi.ts` 生成。
|
||||
- `embedded-skill.ts`:内嵌 `skills/hose-use/` 全量 Skill 文件(`EMBEDDED_SKILL_FILES`),支持 `hose-use skill install --yes` 一键安装到全局目录,并在编译二进制运行时自动同步(`syncGlobalSkillIfPresent`)。
|
||||
- `embedded-webui.ts`:内嵌 AI PRO 本地 Web 控制台的单文件 HTML,供 `GET /report` 返回。
|
||||
- `embedded-docs.ts`:内嵌 `/docs` 交互式文档使用的 Scalar 浏览器运行时,供 `GET /static/scalar.js` 返回。
|
||||
- `runtime.ts`:二进制运行态自省——`isCompiledBinary` 判定编译态、`resolveAppRoot` 解析应用根目录、`resolveDefaultLauncher` 解析启动配置。
|
||||
|
||||
## Web 控制台内嵌产物
|
||||
|
||||
`web/` 是 Vue 3 + Vite 子工程。`scripts/build/build-webui.mjs` 调 `bun run build` 后把产物的 JS/CSS 内联成单个 HTML,写到 `src/packaging/generated/webui.txt`:
|
||||
|
||||
```bash
|
||||
bun install --cwd web # 仅开发机需要,生成 web/bun.lock
|
||||
bun run web:build # 生成 src/packaging/generated/webui.txt
|
||||
```
|
||||
|
||||
- 后缀用 `.txt` 而非 `.html`:Bun 对 `.html` 的 `with { type: "text" }` 导入会推断成 `HTMLBundle`,导致 `tsc` 报错。内容仍是完整 HTML,由 HTTP 层按 `text/html` 返回。
|
||||
- 该生成物**必须随 git 提交**,与 `specs/*.json` 同理——编译二进制与 CI 不需要安装前端依赖。
|
||||
- `.webui-dist/` 是 Vite 中间产物,已被 `.gitignore` 忽略。
|
||||
|
||||
## 离线 API 文档运行时
|
||||
|
||||
`GET /docs` 的 Scalar 交互式文档不再引用 CDN。`scripts/build/build-docs.mjs` 固定 `@scalar/api-reference@1.25.101`,下载后按 SHA-256 校验,生成 `src/packaging/generated/scalar-standalone.js.txt`:
|
||||
|
||||
```bash
|
||||
bun run docs:fetch # 仅升级 Scalar 版本时需要联网
|
||||
```
|
||||
|
||||
- 生成物随 git 提交;daemon 的 `GET /static/scalar.js` 返回它,`/docs` 用相对路径加载,运行时完全离线。
|
||||
- 后缀用 `.txt` 与 webui 同理,避开 Bun 对 `.js` / `.html` 的非字符串类型推断。
|
||||
- `renderDocsHtml()` 里加了 CSP(`connect-src 'self'`):Scalar 内置一个"加载示例规范"分支会 `fetch` jsdelivr 的 galaxy.yaml,我们的页面用 `data-url="/openapi.json"` 不走该分支,CSP 再兜一层,保证任何情况下都发不出外网请求。
|
||||
- 生成物约 2.7 MiB,二进制体积因此增加约 2.9 MB。
|
||||
|
||||
## 依赖约束
|
||||
|
||||
- 仅可被入口层与 `cli/` 导入;不得反向依赖 `domains/`。
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user