Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
384f611a26 | ||
|
|
f465979ec3 | ||
|
|
6fef188f2f | ||
|
|
417be3ef54 | ||
|
|
46fa2597d0 | ||
|
|
957cb04324 | ||
|
|
19d8fd3c59 | ||
|
|
dfb464605e | ||
|
|
fb29ff630a | ||
|
|
c8adf0e051 | ||
|
|
e58841e164 | ||
|
|
e562ae9227 | ||
|
|
07a8a792af | ||
|
|
731e67377c | ||
|
|
4be87d448a | ||
|
|
a1cc808717 | ||
|
|
bb60053072 | ||
|
|
23f12f17c5 | ||
|
|
c46a140ac4 | ||
|
|
8ff0e5ff52 | ||
|
|
7d09a8400a | ||
|
|
f0dde0083e | ||
|
|
7a19fa8337 | ||
|
|
33f3275acb | ||
|
|
362acfba58 | ||
|
|
c3e39fe77a | ||
|
|
cedc4249e5 | ||
|
|
71aa9b54a7 | ||
|
|
a0058c1c66 | ||
|
|
1ee46fd79f | ||
|
|
6dc96a5eb9 |
No files matched your search
@@ -50,12 +50,19 @@ fi
|
||||
# 3. 校验暂存区文件(文件体积与 Windows 文件名合规性)
|
||||
MAX_FILE_SIZE=15728640 # 15MB in bytes
|
||||
|
||||
staged_files=$(git diff --cached --name-only --diff-filter=ACM)
|
||||
# 用 -z(NUL 分隔)取暂存文件列表,再转成换行分隔。
|
||||
# 不能用默认的 --name-only:当 core.quotepath 保持默认值 true 时,它会把非 ASCII
|
||||
# 路径做八进制转义并用双引号包裹(中文名变成 "docs/\344\270\255..."),下面基于
|
||||
# basename 的 Windows 非法字符校验就会把转义带出来的引号当成文件名的一部分,
|
||||
# 将完全合法的中文文件名误判为违规并拒绝提交。
|
||||
staged_files=$(git diff --cached --name-only --diff-filter=ACM -z | tr '\0' '\n')
|
||||
|
||||
if [ -n "$staged_files" ]; then
|
||||
OLD_IFS="$IFS"
|
||||
IFS='
|
||||
'
|
||||
# 关闭 glob 展开:文件名中的 [ * ? 不能被 shell 当作通配符去匹配其它文件
|
||||
set -f
|
||||
for file in $staged_files; do
|
||||
# 3.1 校验单文件体积上限 (15MB)
|
||||
if [ -f "$file" ]; then
|
||||
@@ -118,6 +125,7 @@ if [ -n "$staged_files" ]; then
|
||||
;;
|
||||
esac
|
||||
done
|
||||
set +f
|
||||
IFS="$OLD_IFS"
|
||||
fi
|
||||
|
||||
|
||||
@@ -59,3 +59,6 @@ exports/
|
||||
|
||||
# Local API captures may contain tenant business data
|
||||
/specs/hose-close-api/_tmp-captured/
|
||||
|
||||
# 排障时临时下载的截图,通常带有客户名称与业务数据,不得入库
|
||||
/downloads/
|
||||
@@ -0,0 +1,231 @@
|
||||
# 2026-11-04
|
||||
|
||||
## 任子行 webhook 审批流「URL 不合法」排查(只读,未改配置)
|
||||
|
||||
- 企业:任子行 `dAY3noVGjy4s7w`,🏭 正式,cluster = `wx2`,baseUrl `https://wx2.ekuaibao.com`,员工身份 `dAY3noVGjy4s7w:R5423`(庄绿茵)。
|
||||
- 工作流:`905035646304378890`(未命名流程FTisOH,商机台账,⚪停用,14 节点)。同类参考实现:CSM `Cxa3oOtQi2eS$g` 的 `881196955148578838`(方案一)。
|
||||
- 根因 1:任子行两个 http 节点(`action_zfsw67` 分支内、`action_pyrg` 第13步)的 `url` 只剩变量 `@{choose(...查询单据详情.单据ID...)}`,静态前缀 `https://<host>/api/openapi/v1/backlog/data/[` 与后缀 `]` 丢失 → 报 `URI不合法: no protocol: ID01XzW4ovYvpl`。
|
||||
- 根因 2(更隐蔽):任子行在 wx2 集群,直连 URL 必须用 `https://wx2.ekuaibao.com`,不能照抄 CSM 的 `app.ekuaibao.com`。
|
||||
- 正确 URL 形态:`https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('…action_bv8vyb…properties[id]…')}]`,method POST,params `messageCode=debug` / `powerCode=TICKET_AUDIT_switch`,body raw `{approveId, action:{name:"freeflow.agree", comment}}`。
|
||||
- 次要问题:测试单 `B26005052`(ID `ID01XzW4ovYvpl`)在 2026-11-04 09:14 的调试跑到第5步「修改单据」失败:`HTTP 400 「凭证生成时间」类型应当是Long`。该单据上 `凭证生成时间 = 0`(其他单据无此字段值),疑似脏数据导致后续任何更新被拒。
|
||||
- 调试记录:7 次 DEBUG 全部 FAILED(11-03 16:36 / 16:38,11-04 09:02 / 09:09 / 09:14…),均为生产环境真实执行,未自行派发新调试。
|
||||
|
||||
## 合思 HTTP 节点 URL 形态:结论修正(用户裁定,强制遵守)
|
||||
|
||||
- **平台统一形态就是 `choose()` 内部 JSON 多一个 `}`(`{`/`}` 不配平)**。这是设计器保存与人工填写的稳定产出,CSM 多个工作流、多个租户均如此。**不要判为脏数据、不要"修正"成配平形态。**
|
||||
- 用户长期在 UI 人工填写该形态并正常使用;没有运行日志不等于有问题,多数流程本来就不留日志。以用户实操经验为准,不要用"无观测证据"去否定。
|
||||
- 真正的坏形态只有一种:`url` 只剩 `@{choose(...)}`、静态前缀 `https://<域名>/...` 整段缺失 → 运行时报 `URI不合法: no protocol: <ID>`。
|
||||
- 折叠态显示不可信:纯变量显示变量 label,文本+变量显示「自定义表达式」。判断对错只读 `tasks[i].url`。
|
||||
- 直连 URL 必须用企业自己的 `baseUrl`(CSM=app.ekuaibao.com,任子行=wx2.ekuaibao.com)。
|
||||
- CSM `881196955148578838`(方案一)两个 http 节点已按上述统一形态回写,tasksVersion 64。
|
||||
- 完整说明见 `src/domains/platform/workflow/README.workflow.md` 的「HTTP 节点『请求 URL』的表达式形态」章节。
|
||||
|
||||
## 任子行修复已执行(2026-11-04 11:21)
|
||||
|
||||
- 工作流 `905035646304378890`(未命名流程FTisOH)两个 http 节点 `action_pyrg`(第13步)与 `action_zfsw67`(超标分支内)的 `url` 已补全为:`https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{"key":"action_bv8vyb","properties":[{"key":"id","label":"单据ID","type":"TEXT"}],"label":"查询单据详情.单据ID"}}')}]`
|
||||
- 复核:prefix=True / suffix=True / brace 3-4(平台统一形态)。method=POST、params(messageCode=debug、powerCode=TICKET_AUDIT_switch)、bodyRaw 未变。14 节点结构完整。
|
||||
- 版本 26.11.8(tasksVersion 20),仅存草稿,**未发布、未派发调试**。
|
||||
- 遗留待办:第 5 步「修改单据」仍报 `HTTP 400 「凭证生成时间」类型应当是Long`(测试单 B26005052 上该字段值为 0),属单据脏数据,需换干净单据或清字段后重测。
|
||||
|
||||
## 补充:node edit 不同步富文本快照(2026-11-04 11:24)
|
||||
|
||||
- `workflow node edit --set=url=` 只写扁平 `tasks[i].url`;设计器渲染读 `$snapshot` 里的 `<path>.url-snapshot`。
|
||||
- 任子行流程原本 `$snapshot` 为 0 条,所以改完 url 后设计器显示「请输入 url」(空),看起来像没改。
|
||||
- 解决:读取全量 JSON,在 `$snapshot` 追加 `tasks.6.url-snapshot`、`tasks.3.tasks.1.tasks.2.url-snapshot`(rich text: text/context-tag/text 三段),再 `workflow save --file=... --yes`。已执行,tasksVersion 21,快照 2 条落库,url 未变。
|
||||
- 已写入 `README.workflow.md`「坑 3」。
|
||||
|
||||
## 实证:设计器折叠态零信息量(2026-11-04 11:29 探针实验,已还原)
|
||||
|
||||
- 在任子行「任子行-方案一」第13步 `action_pyrg` 的 `tasks.6.url-snapshot` 注入探针文本(`【探针左】ABC-123` / `XYZ-789【探针右】`),第9步保持原样作对照,保存后让用户在前端观察。
|
||||
- 结果:**两个节点折叠态都只显示「自定义表达式」,外观完全一致**;展开后第13步显示探针文字、第9步显示正常 URL。→ 折叠摘要对"文本+变量"一律显示固定词,零信息量。
|
||||
- 同时验证:仅改 `$snapshot` 不会联动改写 `url`(服务端不从快照反推),两者独立,`url` 才是运行时唯一依据。
|
||||
- 已还原,tasksVersion 24,快照恢复为 `text(前缀) / tag / text(])`,url 未变。
|
||||
- 推论:之前 CSM 折叠态显示「第3步:查询单据详情_单据ID」,说明当时字段内只有纯变量(无静态文本段)——折叠摘要规则得到实证。
|
||||
|
||||
## 抓包实锤:`}}` 由前端序列化产生,且是稳定终态(2026-11-04 11:37)
|
||||
|
||||
用 kimi-webbridge 录制 CSM 设计器(`piper.ekuaibao.com`)的保存请求,做对照实验:
|
||||
|
||||
1. CLI 把 `tasks[*].url` 置为**单 `}`**(`{=2 }=2`),服务端确认。
|
||||
2. 浏览器重载设计器 → 点「放弃」丢弃本地草稿 → 点「保存更新」。
|
||||
3. 抓到 `PUT /api/easo/pipelines/881196955148578838`,payload 中 `url` 为**双 `}`**(`{=2 }=3`)。
|
||||
4. 保存后服务端变成 `{=2 }=3`;**再点一次保存,仍是 `{=2 }=3`,不累加**。
|
||||
|
||||
结论:
|
||||
- **前端是单 `}` → 双 `}` 的转换源头**(富文本序列化时多加一个 `}`),后端只是照存。
|
||||
- `}}` 是前端解析/序列化的稳定不动点:解析回 rich text 再序列化仍是一个 `}}`,不会无限增长。
|
||||
- 因此 **`}}` 就是 UI 的稳定输出形态,长期可用**;CLI 写单 `}` 会被前端在下一次保存时"归一化"成 `}}`。
|
||||
- 保存相关端点:`PUT /api/easo/pipelines/<id>`(主保存)、`PUT /api/easo/pipelines/<id>/chooses`(刷新 chooses)。
|
||||
- CSM 当前 26.11.7 / tasksVersion 69 / 8 tasks / 3 快照,两处 url 均为 `}}` 形态(用户要求的统一形态)。
|
||||
|
||||
## 源码定位:多出的 `}` 是前端模板字符串笔误
|
||||
|
||||
- 文件 `formily-config-NJqcV1rZ.js`(piper 表达式编辑器,Lexical + 自定义 DecoratorNode `context-tag`)。
|
||||
- 原文:`` a+=`@{choose('${JSON.stringify(s.choose)}}')}` `` —— 插值后字面量多余一个 `}`。同一模板在包内出现 3 次。
|
||||
- 正确写法:`` `@{choose('${JSON.stringify(s.choose)}')}` ``。
|
||||
- 解析侧用 `/@{choose\('(.+?)'\)}/g` + `JSON.parse`,遇 `}}` 解析失败走 catch,字段退化为纯文本 → 所以不累加,但变量节点丢失。
|
||||
- 完整报告:`docs/合思前端-表达式序列化缺陷-2026-11-04.md`
|
||||
|
||||
## 实机验证闭环:`}}` 形态引擎侧 100% 可用(2026-11-04 12:55)
|
||||
|
||||
**结论先行**:`}}` 形态在引擎侧完全正常,与单 `}` 行为逐字符一致。用户长期的实操经验正确,我此前「非法 JSON / 序列化 bug」的判定是错的。
|
||||
|
||||
验证过程:
|
||||
1. 首选「沈玥妍测试企业」`ID01ofWoOC1wiX` → `workflow create` 成功,但 `workflow test` 报 `POST /api/easo/jobs ... 您还未开通工作流,或订单已过期`,`publish`(`state=1`)同样被拒;对该企业任一存量流程复现同样报错 → **该企业 Piper 模块整体不可用,需客户侧开通订单**。
|
||||
2. 经用户同意改用 `HAB对公测试环境` `ID01uzxB4x07fh`(🧪 测试),自建应用「测试111111」`ID01LNChXmgamP` 建临时流程 `webhook → http × 3`,跑完即删。
|
||||
3. 调试通道注意:webhook 触发器直接 `workflow test` 会报 `TaskSampleData.getDataJson() ... sampleData is null`;草稿态 `webhook send` 不落样本。**正确姿势:先 `publish`(state=1)→ 再 `webhook send` → 真 webhook 触发执行 → `workflow tail <pipelineId> --once` 看结果。**
|
||||
4. 已发布流程改动直接用 `node add` / `node edit`(PUT 落地即生效,无需再次 publish;再 publish 会报「流程已发布,建议刷新页面重新加载」)。
|
||||
|
||||
三组对照(`choose()` 引用不存在的 `action_probe`,求值为空串):
|
||||
|
||||
| 组 | url 原文 | 引擎求值后(节点日志 `http请求:` 实录) | 状态 |
|
||||
|---|---|---|---|
|
||||
| A 双 `}` | `…/double-@{choose('…}}')}` | `…/double-` | COMPLETED |
|
||||
| B 单 `}` | `…/single-@{choose('…}')}` | `…/single-` | COMPLETED |
|
||||
| C 双 `}` + 后缀 | `…/pre-@{choose('…}}')}/post-tail` | `…/pre-/post-tail` | COMPLETED |
|
||||
|
||||
C 组与任子行真实形态同构,前后缀完整保留,多出的 `}` 不吞任何字符。
|
||||
|
||||
后端行为直接证据:探针把 `properties[0].type` 误写成小写 `"string"`(`DynamicType` 只收 `TEXT` 等大写),Jackson 抛枚举值错误,异常信息 `at [Source: (String)"{…"label":"单据ID"}}"` 里可见尾部 `}}`,且**未报 JSON 语法错误**、精确解析到 `properties[0].type` → `FAIL_ON_TRAILING_TOKENS` 默认关闭,尾随 `}` 被静默忽略。**能跑不是巧合,是 Jackson 宽松策略兜住的。**
|
||||
|
||||
旁证:任子行修复前的 `URI不合法: no protocol: ID01XzW4ovYvpl` 里出现的是**字段值**而非 `@{choose(...)}` 原文,本身即证明引擎解析成功,真实病因是前缀缺失。
|
||||
|
||||
落地:
|
||||
- `docs/合思前端-表达式序列化缺陷-2026-11-04.md` 新增第 8 章(三组对照 + Jackson 证据 + 最终判断)。
|
||||
- `src/domains/platform/workflow/README.workflow.md` 坑 2 增补「为什么引擎能跑:实测证据」,并在「真正的坏形态与报错」补一句「看到 no protocol 去查前缀,别查花括号」。
|
||||
- 两个临时流程(HAB `905801669341192210`、沈玥妍 `905800050880950291`)已删除并 list 复核无残留。
|
||||
|
||||
## CLI 新增 chooseSerialization 开关(2026-11-04 13:20)
|
||||
|
||||
用户裁定:CLI 写出的 `@{choose('…')}` 形态要「百分百模拟真实前端」,并可切换纯净版,默认模拟前端。
|
||||
|
||||
- 配置项:`GlobalConfigSchema.chooseSerialization: "frontend" | "pure"`,默认 `frontend`(`src/core/config/types.ts`,enum `ChooseSerializationSchema`)。
|
||||
- 核心模块 `src/domains/platform/workflow/models/choose-serialization.ts`:
|
||||
- `parseChoosePayloadLoose`:先原样 `JSON.parse`,失败则逐个剥离尾部多余 `}` 再试;非 JSON 载荷(`@{choose('body.details')}`)返回 null,绝不猜测改写。
|
||||
- `serializeChooseTag(json, mode)`:frontend 在 `')}` 前多一个 `}`;pure 配平。
|
||||
- `normalizeChooseTags(text, mode)`:全局替换,原样保留无法解析的标签。
|
||||
- `inspectChooseTags`:统计 balanced / extraBrace / unparsable。
|
||||
- 接入点:`src/cli/commands/workflow/shared.ts` 的 `resolveChooseSerialization` + `normalizeNodeExpressionFields`,在 `node add` / `node edit` 的 `--set=url` 上归一化(`src/cli/commands/workflow/node.ts`)。
|
||||
- 优先级:命令行 `--choose-serialization` > 全局配置 > 默认 frontend。
|
||||
- 配置命令:`hose-use config set chooseSerialization <frontend|pure>`,`config get` 展示当前形态。flag 已登记进 `command-metadata.ts` 的 workflow value 词表(否则 parser.test 的 flag 漂移测试会红)。
|
||||
|
||||
**顺带修掉的隐患**:`branch/explain.ts` 的 `parseChooseTag` 原来直接 `JSON.parse`,遇到设计器产出的 `}}` 静默返回 null,导致分支条件解释、字段引用分析在真实数据上全部失效。已改为走 `parseChoosePayloadLoose`,两种形态都能解析。
|
||||
|
||||
测试:`src/domains/platform/workflow/models/choose-serialization.test.ts` 19 例;全量 1044 pass / 0 fail;typecheck 通过。
|
||||
实测:默认模式输入配平形态 → 输出 `}}`;`--choose-serialization=pure` 输入 `}}` → 输出配平。
|
||||
|
||||
## 对外文档
|
||||
|
||||
- 钉钉在线文档:https://alidocs.dingtalk.com/i/nodes/P7QG4Yx2Jp6LPpnpIpM3jog5W9dEq3XD
|
||||
(已按用户要求改为**纯缺陷版**:标题与正文全部去掉 CLI / hose-use 相关内容,只讲 bug、实机验证、根因、修复建议。源文件 `docs/合思工作流-choose多花括号问题-钉钉文档版.md`,10 章约 5300 字。)
|
||||
**注意**:对外文档不暴露内部工具名,是本项目的固定偏好 —— 给客户/团队看的材料只写缺陷与结论,不写我们用什么工具排查的。
|
||||
- 飞书文档:待办 —— lark-cli 的 user token 已失效(keychain 无 token,仅 bot 可用),已发起 device flow 等用户授权;租户名未确认,需授权后查证是否为「合思汇智」。
|
||||
|
||||
## 飞书 Lark CLI 已卸载(2026-11-04 13:58,用户要求)
|
||||
|
||||
用户明确要求卸载本地飞书 CLI,原因是「飞书这企业太恶心了」。**后续不要再尝试用 lark-cli 做任何事。**
|
||||
|
||||
- 卸载方式:`/opt/homebrew/bin/npm uninstall -g @larksuite/cli`(`removed 7 packages`),`/opt/homebrew/bin/lark-cli` 软链已删除,`command -v lark-cli` 返回不存在。
|
||||
- 空目录 `/opt/homebrew/lib/node_modules/@larksuite` 已 rmdir。
|
||||
- 残留(**已按用户要求全部清理,2026-11-04 14:04,均移入废纸篓可恢复**):
|
||||
- `~/.lark-cli/` 52K → `~/.Trash/lark-cli-20261104`
|
||||
- `~/Library/Application Support/lark-cli/` 80K(含 3 个 appId 的 appsecret 加密文件与 openId token)→ `~/.Trash/lark-cli-appsupport-20261104`
|
||||
- `/opt/homebrew/lib/node_modules/@lark-opdev` 146M → `~/.Trash/lark-opdev-20261104`
|
||||
- 清理后全盘核对:PATH 内无 lark/feishu 命令,全局 node_modules 无 lark 包,keychain 无相关条目。
|
||||
- **未动**:`/Applications/Lark.app` 飞书桌面客户端及其数据(`~/Library/Application Support/LarkShell` 14G、`Caches/LarkShell` 3.9G)—— 属于桌面端不是 CLI,已告知用户由他决定。
|
||||
- **租户名始终未能查明**:user token 一直缺失(keychain 无 token),bot 身份缺 `tenant:tenant:tenant/readonly` 权限,本地配置也没有公司名。用户问的「是不是合思汇智」没有结论。
|
||||
- 飞书文档任务作废,用户改口「放飞书文档不用你来做」。缺陷记录改交付为本地文件:
|
||||
- `~/Downloads/合思工作流-choose多花括号问题-缺陷记录.md`
|
||||
- 仓库副本 `docs/合思工作流-choose多花括号问题-钉钉文档版.md`
|
||||
|
||||
## 保存期「接口 → 应用」权限预检落地(2026-11-04 16:30)
|
||||
|
||||
用户明确纠正了权限校验的粒度:**必须先认定是哪个接口,只有 HTTP 节点、且 URL 能静态读出路径时才判断**;URL 整体由上游节点变量拼接的情况直接跳过,不猜测。
|
||||
|
||||
### 新增/改动
|
||||
- 新建 `src/domains/platform/workflow/analysis/openapi-app-requirements.ts`:接口路径 → 所需应用的映射表(首条:`/^\/api\/openapi\/v1\/backlog\/data\//i` + POST/PUT/PATCH → 「单据审批」`TICKET_AUDIT_switch`,productId `o0hMBw000000g0`);配套 `extractStaticUrlPath`(去域名、截断到第一个 `@{`、去 query/hash,纯变量开头返回 null)与 `matchAppRequirement`。
|
||||
- `analyzer.ts` 6.3 节重构:路径反查优先,显式 `powerCode`(params / URL query)作为并列规则;**显式声明的正是该接口要求的那个**时走路径规则,这样报文能带应用名 + productId + 判定依据路径;显式声明了别的 powerCode 时以声明为准。
|
||||
- 新增保存期 hook:`shared.ts` 的 `preflightNodeAppRequirements` + `renderAppRequirementAlerts`,接到 `node add` / `node edit`,只检查本次写入的 HTTP 节点,未开通就打印 ⛔ 段(JSON 模式落在 `appRequirementAlerts`)。读不到企业清单降级为 ⚠️,**不阻断写入**。
|
||||
- `domains/store/tools.ts` 新增 `isClientGoodOpened`(只看 status,不看 onLineStatus)与 `fetchOpenedPowerCodes`;`analyze.ts` 改为复用,原来内联那份汇总逻辑删除(`isClientGoodOpened` 仍从 analyze.ts re-export,兼容既有测试)。
|
||||
|
||||
### 实机验证(全部只读)
|
||||
- 真实流程 `905035646304378890`(任子行-方案一)两个 HTTP 节点 `action_zfsw67` / `action_pyrg` 均命中「单据审批」。**关键发现:设计器确实会把 `powerCode` 写进节点的 `params`**,所以显式声明与路径反查两条路都要留。
|
||||
- `workflow analyze` 对任子行返回 0 阻断 —— 因为用户已去开通「单据审批」,核对通过。
|
||||
- 模拟 `openedPowerCodes: []` → 精确打出两条硬门禁,path=`3.1.2` / `6`。
|
||||
- 预检实机:任子行 → 已开通 ✅(静默);华铁大黄蜂 `ID01Nl1kQVYbKL`、醉面 `ID01PZkOSEZrEr` → 未开通 ⛔(证明负例真的会触发)。
|
||||
- 回归:`bun test` 1068 pass / 0 fail(新增 17 + 7 例),typecheck 干净,`check:readme` 通过。
|
||||
|
||||
### 遗留
|
||||
- 任子行「工作流」应用 2026/11/05 到期(另有不限量版到 12/31),需提醒客户。
|
||||
- 条件节点空值保护(`AND(结果列表非空, OR(...))`)仍待用户决定是否改生产流程。
|
||||
|
||||
## PR #166 已合并进主分支(2026-11-04 16:46)
|
||||
|
||||
- 分支:`feat/workflow-save-time-guardrails` → 合入 `main`,merge commit `7d09a84`。
|
||||
- `origin/main` 与 `home/main` 均已同步到 `7d09a84`(先 GitHub 合并、再 `git push home main`)。
|
||||
- 两个 commit:`7a19fa8` feat(代码+测试,21 文件 / +1649)→ `f0dde00` docs(README ×3 + 两份缺陷报告 + 工作日志)。
|
||||
- CI `validate` 通过(30s)。
|
||||
|
||||
### 踩到的坑:pre-commit hook 对中文文件名误报
|
||||
|
||||
`.githooks/pre-commit` 用 `git diff --cached --name-only` 取文件名,但没关 `core.quotepath`
|
||||
(默认 true)—— 中文路径被转义成 `"docs/\345\220\210..."` 这种带引号的字符串,
|
||||
`basename` 结果末尾残留一个 `"`,于是撞上「Windows 非法字符 `: * ? " < > |`」的规则,
|
||||
把完全合法的中文文件名拦了下来。
|
||||
|
||||
- 现场解法:本仓库 `git config core.quotepath false`(本地配置,不影响仓库内容)。
|
||||
- **根治方案(尚未实施)**:hook 里把该行改成 `git -c core.quotepath=false diff --cached --name-only --diff-filter=ACM`。
|
||||
没顺手改是因为它在 `.githooks/` 里会影响所有协作者,应单独走一个 PR 评审。
|
||||
|
||||
## pre-commit hook 中文文件名误报已修(2026-11-04 16:5x,PR 待合并)
|
||||
|
||||
- 根因:`git diff --cached --name-only` 在 `core.quotepath=true`(默认)下把非 ASCII
|
||||
路径做八进制转义并加双引号,`basename` 后残留 `"`,撞上 Windows 非法字符规则。
|
||||
- 修复:改用 `-z`(NUL 分隔)+ `tr '\0' '\n'`,彻底绕开 Git 引号转义;并加
|
||||
`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 条恢复原样。
|
||||
@@ -2,11 +2,19 @@
|
||||
|
||||
## 企业租户操作红线(强制)
|
||||
|
||||
- **唯一允许操作的测试企业是「沈玥妍测试企业」**,任何需要真实联调/验证的场景只能在它上面做。
|
||||
- **默认测试企业「沈玥妍测试企业」`ID01ofWoOC1wiX`**,任何需要真实联调/验证的场景优先在它上面做。
|
||||
- **例外:该企业 Piper 模块目前不可用**(2026-11-04 实测:`workflow test` 与 `publish` 均报 `您还未开通工作流,或订单已过期`,整模块拒服务)。需要跑引擎验证时,经用户确认后改用 `HAB对公测试环境` `ID01uzxB4x07fh`(🧪 测试,163 条流程),建临时流程、跑完即删。
|
||||
- **绝对禁止对任何生产企业执行操作**,尤其是不可逆的写操作:工作流保存/发布/启停/删除、调试 Job 派发、单据审批、台账写入、灰度节点开通、Webhook 样本注入。
|
||||
- 合思后端没有调试沙箱,调试 Job 以真实操作员身份在生产环境运行,并会隐式自增 Pipeline 快照版本 —— 在生产企业上一次「调试」就等于一次真实变更。
|
||||
- 代码改动优先用单元测试 + Mock 验证;确需真实接口验证时,先确认当前选中的是测试企业再动手。
|
||||
|
||||
## 工作流调试通道(2026-11-04 实测)
|
||||
|
||||
- **webhook 触发的流程不能直接 `workflow test`**:报 `Cannot invoke TaskSampleData.getDataJson() ... sampleData is null`;草稿态 `webhook send` 也不落样本。
|
||||
- **正确姿势**:`workflow publish`(state=1)→ `workflow webhook send --body=...` → 真 webhook 触发执行 → `workflow tail <pipelineId> --once` 看结果。
|
||||
- 已发布流程的改动用 `node add` / `node edit`(PUT 即生效),**不要再 publish**,否则报「流程已发布,建议刷新页面重新加载」。
|
||||
- 删除流程前必须先 `workflow toggle <id> --state=0` 停用。
|
||||
|
||||
## 仓库协作
|
||||
|
||||
- 双远端:`origin` = GitHub(主),`home` = Gitea(git.ying-qing.cn)。发布顺序先 `home` 再 `origin`。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.22",
|
||||
"version": "0.9.2",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.22)
|
||||
# hose-use (v0.9.2)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -32,6 +32,17 @@ 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. 拿到凭证后执行 `hose-aipro login '<凭证>'`(纯本地验签,不联网);
|
||||
4. `hose-aipro scopes --json` 能返回场景数据即激活成功。
|
||||
|
||||
凭证有两条约束:当前二进制版本不得高于其 `maxVersion`,当前时间不得晚于其 `exp`。完整流程与失败处理见 [hose-aipro Skill](./skills/hose-aipro/SKILL.md) 的「首次安装与激活」章节——Agent 自行安装时以该文档为准。
|
||||
|
||||
---
|
||||
|
||||
### CLI 常用命令速查 (`hose-use`)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# 合思工作流设计器:表达式序列化缺陷报告
|
||||
|
||||
- 发现日期:2026-11-04
|
||||
- 涉及页面:`https://piper.ekuaibao.com/#/workflow/<pipelineId>`(自建应用 → 工作流 → 流程设计)
|
||||
- 涉及字段:HTTP 节点「请求 URL」,以及其他使用「自定义表达式 / 引用字段」的富文本字段
|
||||
- 影响租户:全部(前端代码缺陷,与租户无关)
|
||||
- 证据等级:抓包 + 前端源码双向确认
|
||||
|
||||
## 1. 现象
|
||||
|
||||
在「请求 URL」中引用一个字段变量(如「查询单据详情.单据ID」),字段内容为
|
||||
|
||||
```
|
||||
https://<域名>/api/openapi/v1/backlog/data/[ 变量 ]
|
||||
```
|
||||
|
||||
点击「保存更新」后,服务端保存的 `tasks[i].url` 变成
|
||||
|
||||
```
|
||||
https://<域名>/api/openapi/v1/backlog/data/[@{choose('{"key":"action_xxx","properties":[{"key":"id","label":"单据ID","type":"TEXT"}],"label":"查询单据详情.单据ID"}}')}]
|
||||
```
|
||||
|
||||
即 `choose('…')` 内部的 JSON 多出一个右花括号,`{` 与 `}` 不再配平(`{`=2,`}`=3)。
|
||||
|
||||
用户界面**完全看不出差别**:折叠态只显示「自定义表达式」,展开态的表达式弹窗仍正常显示「文本 + 变量 chip + 文本」。
|
||||
|
||||
## 2. 抓包证据(前端提交即已损坏)
|
||||
|
||||
对照实验:先用接口把服务端 `url` 写为**单** `}` 的合法形态,再在浏览器重载设计器、点「放弃」丢弃本地草稿、点「保存更新」。
|
||||
|
||||
```
|
||||
PUT https://piper.ekuaibao.com/api/easo/pipelines/<pipelineId>
|
||||
"url": "...backlog/data/[@{choose('{\"key\":\"action_e14vcd\",...\"label\":\"查询单据详情.单据ID\"}}')}]"
|
||||
↑↑ 双 }
|
||||
```
|
||||
|
||||
- 保存前服务端:`{=2 }=2`
|
||||
- 前端 PUT payload:`{=2 }=3`
|
||||
- 保存后服务端:`{=2 }=3`
|
||||
|
||||
**结论:损坏发生在浏览器提交之前,服务端只是照存。**
|
||||
|
||||
## 3. 源码定位
|
||||
|
||||
文件:`formily-config-NJqcV1rZ.js`(约 2.5 MB,工作流表单与表达式编辑器打包产物)
|
||||
|
||||
编辑器基于 Lexical(`DecoratorNode` / `createCommand` / `getState`),变量是一个自定义装饰节点:
|
||||
|
||||
```js
|
||||
static getType(){return"context-tag"}
|
||||
```
|
||||
|
||||
序列化(编辑器 JSON → URL 字符串):
|
||||
|
||||
```js
|
||||
const n = e.toJSON(),
|
||||
r = ((l = (o = (i = n?.root)?.children)?.[0])?.children) ?? [];
|
||||
let a = "";
|
||||
r.forEach(s => {
|
||||
s.type === "context-tag" && (a += `@{choose('${JSON.stringify(s.choose)}}')}`),
|
||||
s.type === "linebreak" && (a += ` `),
|
||||
s.type === "text" && (a += s.text)
|
||||
});
|
||||
t?.({ value: a, snapshot: n });
|
||||
```
|
||||
|
||||
**缺陷在模板字符串:**
|
||||
|
||||
```js
|
||||
`@{choose('${JSON.stringify(s.choose)}}')}`
|
||||
^
|
||||
这里多了一个 }
|
||||
```
|
||||
|
||||
插值结束后的字面量是 `` }}')} ``,其中第一个 `}` 是多余的——JSON 对象自身的闭合花括号已由 `JSON.stringify` 输出。
|
||||
|
||||
同一模板在打包产物中出现 **3 次**(多个表达式字段共用同一段逻辑的复制),说明是系统性缺陷。
|
||||
|
||||
## 4. 正确写法
|
||||
|
||||
```js
|
||||
a += `@{choose('${JSON.stringify(s.choose)}')}`;
|
||||
```
|
||||
|
||||
## 5. 为什么不会无限累加
|
||||
|
||||
实测连续保存两次,`url` 稳定在 `{=2 }=3`,不会变成 4 个、5 个。
|
||||
|
||||
解析侧使用正则 `/@{choose\('(.+?)'\)}/g` 捕获后再 `JSON.parse`:
|
||||
|
||||
```js
|
||||
const oe = /@{choose\('(.+?)'\)}/g.exec(n);
|
||||
let te = null;
|
||||
oe && (te = JSON.parse(oe[1]));
|
||||
```
|
||||
|
||||
一旦值变成 `…}}')}`,捕获内容即非法 JSON,`JSON.parse` 抛异常进入 `catch`,该字段退化为普通文本处理,后续序列化按原样透传,因此不再追加。
|
||||
|
||||
**副作用**:首次保存后,该字段在编辑器内部已不再是「变量节点」,而是退化成了纯文本——这会破坏字段与上游节点的关联关系(如「查询单据详情.单据ID」的引用),且用户从界面上无法察觉。
|
||||
|
||||
## 6. 影响与建议
|
||||
|
||||
1. **引擎侧实测完全兼容,不影响运行**(见第 8 节:三组对照实验全部 `COMPLETED`,`}}` 与 `}` 的求值结果逐字符一致)。真正的风险不在当下,而在于该字符串始终处于非法 JSON 状态——任何一侧(前端解析、后端 Jackson 开启 `FAIL_ON_TRAILING_TOKENS`、中间网关加严格校验)收紧校验即会静默失败。
|
||||
2. 编辑器内部变量节点退化为文本,**二次编辑时无法再通过「引用字段」定位变量**,只能手工重填。
|
||||
3. 建议修复模板字符串;同时建议在保存前对 `@{choose('…')}` 内的 JSON 做一次 `JSON.parse` 校验,避免非法结构落库。
|
||||
4. 建议同步排查其余两处相同模板(打包产物中共 3 处)。
|
||||
|
||||
## 7. 复现路径(供研发验证)
|
||||
|
||||
1. 任意停用状态的工作流,HTTP 节点「请求 URL」填写:`https://<域名>/path/[` + 变量 + `]`
|
||||
2. 保存一次 → 读取 `GET /api/easo/pipelines/<id>`,观察 `tasks[i].url`
|
||||
3. 或直接观察 `PUT /api/easo/pipelines/<id>` 的请求体
|
||||
|
||||
## 8. 引擎侧实机验证结论(2026-11-04 补测)
|
||||
|
||||
验证环境:`HAB对公测试环境`(`ID01uzxB4x07fh`,🧪 测试),临时流程 `webhook → http × 3`,跑完即删,未触碰任何生产租户与业务单据。
|
||||
|
||||
**注**:首选环境「沈玥妍测试企业」的 Piper 模块报 `您还未开通工作流,或订单已过期`(调试 `POST /api/easo/jobs` 与发布 `state=1` 均被拒),整模块不可用,故改用 HAB 对公测试环境验证。
|
||||
|
||||
### 8.1 三组对照
|
||||
|
||||
三个 HTTP 节点串联,`choose()` 均引用一个不存在的动作 `action_probe`(求值结果为空串),差别只在表达式形态:
|
||||
|
||||
| 组 | `url` 字段原文 | 引擎求值后的实际 URL(节点日志 `http请求:` 实录) | 状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| A 双 `}` | `https://httpbin.org/anything/double-@{choose('…"type":"TEXT"}}')}` | `https://httpbin.org/anything/double-` | ✅ COMPLETED |
|
||||
| B 单 `}` | `https://httpbin.org/anything/single-@{choose('…"type":"TEXT"}')}` | `https://httpbin.org/anything/single-` | ✅ COMPLETED |
|
||||
| C 双 `}` + 后缀 | `https://httpbin.org/anything/pre-@{choose('…"type":"TEXT"}}')}/post-tail` | `https://httpbin.org/anything/pre-/post-tail` | ✅ COMPLETED |
|
||||
|
||||
C 组是关键:表达式**后面还有静态后缀**(与任子行真实形态 `…/backlog/data/[@{choose('…}}')}]` 同构)。实测 `pre-` 前缀与 `/post-tail` 后缀**完整保留**,多出的 `}` 既没吞掉后缀,也没破坏求值。
|
||||
|
||||
### 8.2 后端解析器行为(直接证据)
|
||||
|
||||
首轮探针里我把 `properties[0].type` 误写成 `"string"`(`DynamicType` 枚举只接受 `TEXT` 等大写值),后端返回:
|
||||
|
||||
```
|
||||
com.fasterxml.jackson.databind.exc.InvalidFormatException:
|
||||
Cannot deserialize value of type `com.hosecloud.hab.enums.DynamicType` from String "string"
|
||||
at [Source: (String)"{"key":"action_probe","properties":[{"key":"id","label":"单据ID","type":"string"}],"label":"单据ID"}}"; line: 1, column: 71]
|
||||
(through reference chain: …ExpressionField["properties"]->java.util.ArrayList[0]->…LabeledValue["type"])
|
||||
```
|
||||
|
||||
这段异常信息证明了三件事:
|
||||
|
||||
1. 后端收到的 JSON 字符串**确实带着尾部多余的 `}`**(`at [Source: (String)"…}}"`)。
|
||||
2. 后端**没有报 JSON 语法错误**,而是精确解析到了 `properties[0].type` 这一层,说明 Jackson 的 `FAIL_ON_TRAILING_TOKENS` 处于默认关闭状态,尾随 `}` 被静默忽略。
|
||||
3. 报错原因是**我的探针数据本身不合法**(枚举值大小写),与花括号无关。
|
||||
|
||||
### 8.3 最终判断
|
||||
|
||||
- **`}}` 形态在引擎侧 100% 可用**,与单 `}` 形态行为一致,不影响任何运行时行为。
|
||||
- 该缺陷的真实危害只剩两类:① 编辑器内部变量节点退化为纯文本,二次编辑丢失变量引用(见第 5 节);② 未来任何一侧收紧 JSON 校验即会静默失败。
|
||||
- 因此 **`}}` 是当前平台的「事实标准形态」**,人工填写、UI 产出、CLI 写入应保持统一,**不要「修正」它**——修正只会让 CLI 的产物与 UI 产物分叉,反而制造认知负担。详见 `src/domains/platform/workflow/README.workflow.md`「HTTP 节点请求 URL 的表达式形态」章节。
|
||||
|
||||
### 8.4 一条重要旁证
|
||||
|
||||
任子行(`dAY3noVGjy4s7w`)修复前的报错是:
|
||||
|
||||
```
|
||||
URI不合法: no protocol: ID01XzW4ovYvpl
|
||||
```
|
||||
|
||||
报错里出现的是**字段值**(`ID01XzW4ovYvpl`)而不是原始的 `@{choose('…')}` 文本——这本身就说明引擎**成功解析了 `}}` 形态**,只是 `url` 字段缺了 `https://wx2.ekuaibao.com/...` 静态前缀,导致最终 URL 退化为裸 ID。**当时的真实病因是前缀缺失,不是花括号。**
|
||||
@@ -0,0 +1,202 @@
|
||||
# 合思工作流 choose 表达式「多一个右花括号」缺陷记录
|
||||
|
||||
> 记录日期:2026-11-04
|
||||
> 涉及系统:合思/易快报 自建应用平台 → 工作流(Piper)设计器
|
||||
> 涉及租户:全部(前端缺陷,与租户无关)
|
||||
> 证据等级:前端源码定位 + 抓包 + 引擎实机验证
|
||||
|
||||
---
|
||||
|
||||
## 一、结论速览
|
||||
|
||||
1. 工作流设计器保存出来的 `@{choose('…')}` 表达式,参数里的 JSON **永远多一个右花括号**,落库形如 `{"key":"action_x","label":"单据ID"}}`(`{` 2 个、`}` 3 个,不配平)。
|
||||
2. 这是**前端序列化的稳定行为**,不是偶发脏数据。
|
||||
3. **后端引擎完全兼容这个形态**。已用实机三组对照验证:双 `}` / 单 `}` / 双 `}` 带后缀,三个节点全部执行成功,求值结果逐字符一致。
|
||||
4. 兼容的原因很具体:choose 载荷最终交给 Jackson 反序列化,而 Jackson 的 `FAIL_ON_TRAILING_TOKENS` 默认关闭,尾随的那个 `}` 被静默忽略。
|
||||
5. 因此 **`}}` 就是当前平台的事实标准形态**。人工填写、UI 产出应保持统一,**不要在配置层面"修正"它**。
|
||||
6. 真正需要修的是前端序列化代码里那个多余的 `}`,以及反序列化侧把变量节点降级为纯文本的副作用。
|
||||
|
||||
---
|
||||
|
||||
## 二、现象
|
||||
|
||||
在 HTTP 节点的「请求 URL」里引用一个上游字段(如「查询单据详情.单据ID」),保存后服务端存的 `tasks[i].url` 变成:
|
||||
|
||||
```
|
||||
https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{"key":"action_pyrg","properties":[{"key":"id","label":"单据ID","type":"TEXT"}],"label":"查询单据详情.单据ID"}}')}]
|
||||
↑↑ 双 }
|
||||
```
|
||||
|
||||
而配平的写法应该只有一个 `}`:
|
||||
|
||||
```
|
||||
…"label":"查询单据详情.单据ID"}}')}] ← 实际落库
|
||||
…"label":"查询单据详情.单据ID"}')}] ← 配平写法
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、界面完全看不出差别(最误导人的部分)
|
||||
|
||||
- **折叠态只显示「自定义表达式」**,纯变量字段和「文本 + 变量」复合字段长得一模一样,零信息量;
|
||||
- **展开后打开的表达式弹窗仍然正常**,显示「文本 + 变量 chip + 文本」,看不出 JSON 层的异常。
|
||||
|
||||
实测做过探针实验:给一个字段塞入无关文本,折叠态显示依然是「自定义表达式」,与正常字段外观完全一致。
|
||||
|
||||
**所以判断配置对错只能读裸 JSON,看界面截图一定会误判。**
|
||||
|
||||
---
|
||||
|
||||
## 四、实机验证:引擎到底认不认这个形态
|
||||
|
||||
### 4.1 验证方式
|
||||
|
||||
在测试租户搭建了一个临时的最小流程 `webhook → http × 3`,跑完即删,不触碰任何业务单据。
|
||||
|
||||
三个 HTTP 节点串联,`choose()` 引用一个不存在的动作(求值为空串),差别只在表达式形态。
|
||||
|
||||
### 4.2 三组对照结果
|
||||
|
||||
| 组 | `url` 字段原文 | 运行后的实际 URL(节点日志实录) | 状态 |
|
||||
|---|---|---|---|
|
||||
| A 双 `}` | `…/double-@{choose('…}}')}` | `…/double-` | 通过 |
|
||||
| B 单 `}` | `…/single-@{choose('…}')}` | `…/single-` | 通过 |
|
||||
| C 双 `}` + 后缀 | `…/pre-@{choose('…}}')}/post-tail` | `…/pre-/post-tail` | 通过 |
|
||||
|
||||
C 组是关键:表达式**后面还有静态后缀**,和真实业务里的 `…/backlog/data/[@{choose('…}}')}]` 完全同构。实测前缀 `pre-` 和后缀 `/post-tail` 都完整保留,多出来的 `}` 没有吞掉任何字符。
|
||||
|
||||
---
|
||||
|
||||
## 五、后端解析器的直接证据
|
||||
|
||||
第一轮探针把 `properties[0].type` 误写成小写 `"string"`(`DynamicType` 枚举只接受 `TEXT` 等大写值),后端返回的异常里贴出了它实际收到的字符串:
|
||||
|
||||
```
|
||||
Cannot deserialize value of type `com.hosecloud.hab.enums.DynamicType` from String "string"
|
||||
at [Source: (String)"{"key":"action_probe","properties":[{"key":"id","label":"单据ID","type":"string"}],"label":"单据ID"}}"; line: 1, column: 71]
|
||||
(through reference chain: …ExpressionField["properties"]->java.util.ArrayList[0]->…LabeledValue["type"])
|
||||
```
|
||||
|
||||
这段信息说明三件事:
|
||||
|
||||
1. 后端收到的 JSON **确实带着尾部多余的 `}`**(`at [Source: (String)"…}}"`);
|
||||
2. 后端**没有报 JSON 语法错误**,而是精确解析到了 `properties[0].type` 这一层 —— 说明尾随的 `}` 被 Jackson 默认策略忽略掉了;
|
||||
3. 报错的原因是探针数据本身不合法(枚举值大小写),跟花括号无关。
|
||||
|
||||
**能跑不是巧合,是宽松序列化策略兜住的。**
|
||||
|
||||
---
|
||||
|
||||
## 六、根因:前端模板字符串多打了一个右花括号
|
||||
|
||||
工作流设计器的表达式编辑器基于 Lexical(`DecoratorNode` / `createCommand`),变量是一个自定义装饰节点,`getType()` 返回 `context-tag`。
|
||||
|
||||
富文本序列化成扁平 URL 字符串时:
|
||||
|
||||
```js
|
||||
r.forEach(s => {
|
||||
s.type === "context-tag" && (a += `@{choose('${JSON.stringify(s.choose)}}')}`),
|
||||
s.type === "linebreak" && (a += ` `),
|
||||
s.type === "text" && (a += s.text)
|
||||
});
|
||||
```
|
||||
|
||||
缺陷就在模板字符串:
|
||||
|
||||
```js
|
||||
`@{choose('${JSON.stringify(s.choose)}}')}`
|
||||
↑
|
||||
这里多了一个 }(JSON.stringify 已经输出对象闭合花括号)
|
||||
```
|
||||
|
||||
正确写法:
|
||||
|
||||
```js
|
||||
`@{choose('${JSON.stringify(s.choose)}')}`
|
||||
```
|
||||
|
||||
同一模板在打包产物中出现 **3 次**,属于系统性缺陷。
|
||||
|
||||
### 6.1 抓包确认:损坏发生在前端提交之前
|
||||
|
||||
对照实验:先用接口把服务端 `url` 写成配平形态,再在浏览器重载设计器、点「放弃」丢弃本地草稿、点「保存更新」。
|
||||
|
||||
```
|
||||
PUT /api/easo/pipelines/<流程ID>
|
||||
"url": "…backlog/data/[@{choose('{\"key\":\"action_e14vcd\",…\"label\":\"查询单据详情.单据ID\"}}')}]"
|
||||
↑↑ 双 }
|
||||
```
|
||||
|
||||
- 保存前服务端:`{=2 }=2`
|
||||
- 前端 PUT payload:`{=2 }=3`
|
||||
- 保存后服务端:`{=2 }=3`
|
||||
|
||||
**损坏发生在浏览器提交之前,服务端只是照存。**
|
||||
|
||||
### 6.2 为什么不累加
|
||||
|
||||
反序列化侧用正则捕获后 `JSON.parse`:
|
||||
|
||||
```js
|
||||
const oe = /@{choose\('(.+?)'\)}/g.exec(n);
|
||||
let te = null;
|
||||
oe && (te = JSON.parse(oe[1]));
|
||||
```
|
||||
|
||||
一旦值是 `…}}`,捕获内容即非法 JSON,`JSON.parse` 抛异常进入 `catch`,该字段退化为普通文本处理,后续序列化按原样透传,因此花括号稳定在一个,不会越加越多。
|
||||
|
||||
**副作用**:首次保存后,该字段在编辑器内部已不再是「变量节点」,而是退化成了纯文本 —— 这会破坏字段与上游节点的关联关系(如「查询单据详情.单据ID」的引用),且用户从界面上完全无法察觉。再次编辑时没法通过「引用字段」定位变量,只能手工重填。
|
||||
|
||||
---
|
||||
|
||||
## 七、一条容易读错的报错
|
||||
|
||||
如果 `url` 字段只剩 `@{choose(...)}`、静态前缀整段缺失,运行时会报:
|
||||
|
||||
```
|
||||
URI不合法: no protocol: ID01XzW4ovYvpl
|
||||
```
|
||||
|
||||
注意报错里出现的是**字段值**,不是原始的 `@{choose('…')}` 文本 —— 这本身就证明引擎**成功解析了 `}}` 形态**。
|
||||
|
||||
**真实病因是前缀缺失,不是花括号。** 看到这个报错,去查 `https://<域名>/…` 前缀在不在,别去数花括号。
|
||||
|
||||
---
|
||||
|
||||
## 八、影响评估
|
||||
|
||||
1. **不影响当前运行时**:引擎侧实测完全兼容,`}}` 与 `}` 的求值结果逐字符一致。
|
||||
2. **真正的风险是脆性**:该字符串始终处于非法 JSON 状态。任何一侧(前端解析、后端 Jackson 开启 `FAIL_ON_TRAILING_TOKENS`、中间网关加严格校验)收紧校验,就会静默失效,而且大概率是"某天突然全挂"这种形态。
|
||||
3. **变量引用会静默丢失**:首次保存后节点在编辑器内部降级为纯文本,用户无感知,二次编辑只能重填。
|
||||
|
||||
---
|
||||
|
||||
## 九、修复建议(给研发)
|
||||
|
||||
1. **修模板字符串**(根因):
|
||||
|
||||
```js
|
||||
a += `@{choose('${JSON.stringify(s.choose)}')}`;
|
||||
```
|
||||
|
||||
2. **同步排查打包产物中其余两处相同模板**(共 3 处,同一段逻辑的复制)。
|
||||
|
||||
3. **反序列化侧改成容错解析**:不要直接 `JSON.parse`,改为「原样解析失败则逐个剥离尾部多余 `}` 后重试」,这样存量数据能正确回读为变量节点,不会退化成文本。
|
||||
|
||||
4. **保存前加一道校验**:对 `@{choose('…')}` 内的 JSON 做一次 `JSON.parse`,解析失败则告警而不是静默落库。
|
||||
|
||||
5. **存量数据不需要批量清洗**:引擎兼容 `}}`,清洗反而会引入「前端下次保存又改回去」的反复。
|
||||
|
||||
---
|
||||
|
||||
## 十、给使用方的实操建议
|
||||
|
||||
1. **看到 `}}` 不要改**。它是平台统一形态,改了反而制造不一致。
|
||||
2. **不要用「JSON 是否合法」当唯一判据**。引擎侧不校验尾部花括号。
|
||||
3. **判断配置对错一律读裸 JSON**,不要相信设计器的折叠态摘要,也不要只信截图。
|
||||
4. **设计器保存后变量节点可能已退化为文本**。如果发现某个字段的变量引用"没了",去读 JSON 看 `@{choose(...)}` 还在不在;不在就得手工重填。
|
||||
5. 判断一个 URL 是否被写坏,看三条就够:
|
||||
- 以 `https://` 开头(缺前缀才是真正的坏形态);
|
||||
- 变量段 `@{choose(...)}` 完整;
|
||||
- 以 `]` 结尾。
|
||||
6. **域名必须用企业自己的集群地址**(`app.` / `wx2.` / `dd2.` 等),跨租户照抄会 404。
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.22",
|
||||
"version": "0.9.2",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -58,7 +58,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac
|
||||
const result = Bun.spawnSync([
|
||||
process.execPath, ...entry, "workflow", "eval-script", "--file", file,
|
||||
"--type", fixture.type, "--corp", "smoke", "--stateless", "--json",
|
||||
], { cwd: pluginRoot, env, timeout: 10000 });
|
||||
], { cwd: pluginRoot, env, timeout: 30000 });
|
||||
expect(result.exitCode).toBe(fixture.error ? 1 : 0);
|
||||
const report = JSON.parse(result.stdout.toString());
|
||||
expect(report.success).toBe(!fixture.error);
|
||||
|
||||
+18
-11
@@ -99,25 +99,30 @@ function installBinary(localBinary: string, targetPath: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function syncAgentSkill(): string | undefined {
|
||||
const source = join(ROOT, "skills", "hose-use");
|
||||
const target = join(homedir(), ".agents", "skills", "hose-use");
|
||||
if (!existsSync(source)) return undefined;
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
cpSync(source, target, { recursive: true, force: true });
|
||||
return target;
|
||||
function syncAgentSkills(): string[] {
|
||||
const synced: string[] = [];
|
||||
for (const name of ["hose-use", "hose-aipro"]) {
|
||||
const source = join(ROOT, "skills", name);
|
||||
const target = join(homedir(), ".agents", "skills", name);
|
||||
if (existsSync(source)) {
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
cpSync(source, target, { recursive: true, force: true });
|
||||
synced.push(target);
|
||||
}
|
||||
}
|
||||
return synced;
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
const options = parseDevOverrideArgs(argv);
|
||||
const targetPath = options.targetPath || resolveTargetBinaryPath();
|
||||
|
||||
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
|
||||
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use / hose-aipro");
|
||||
console.error(` 工作区: ${ROOT}`);
|
||||
console.error(` 目标: ${targetPath}`);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
|
||||
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/{hose-use,hose-aipro}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -132,8 +137,10 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
}
|
||||
|
||||
try {
|
||||
const skillTarget = syncAgentSkill();
|
||||
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
|
||||
const skillTargets = syncAgentSkills();
|
||||
if (skillTargets.length > 0) {
|
||||
console.error(`✓ [dev:override] 已同步 Agent Skills:\n${skillTargets.map((t) => ` ${t}`).join("\n")}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
|
||||
}
|
||||
|
||||
+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 申请凭证: 先跑 hose-aipro version --json,把版本号与期望到期日发给服务方"
|
||||
echo " AI PRO 激活: hose-aipro login '<凭证>'"
|
||||
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);
|
||||
}
|
||||
@@ -58,15 +58,19 @@ export function bumpVersion(ROOT: string, input: string, rebuild = () => {
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
// 3. skills/hose-use/SKILL.md & skills/hose-aipro/SKILL.md
|
||||
for (const subSkill of ["hose-use", "hose-aipro"]) {
|
||||
const skillPath = join(ROOT, "skills", subSkill, "SKILL.md");
|
||||
if (existsSync(skillPath)) {
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(new RegExp(`# ${subSkill} \\(v\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?\\)`, "g"), `# ${subSkill} (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?:/g, `v${nextVersion}:`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log(`✓ Updated skills/${subSkill}/SKILL.md`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. specs/hose-open-api/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "hose-open-api", "openapi.yaml");
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
---
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.2
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.2)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
---
|
||||
|
||||
## 体系架构与协同边界 (Ecosystem & Boundaries)
|
||||
|
||||
`hose-aipro` 与通用平台工具 `hose-use` 保持严格的正交分离与协同:
|
||||
|
||||
| 维度 | `hose-aipro` (本技能) | `hose-use` (配套平台工具) |
|
||||
|---|---|---|
|
||||
| **核心职责** | 确定性审批仲裁、事实证据打标、审核要点清单、硬门禁阻断、审计轨迹 | 企业租户配置、账密登录、单据检索、工作流、DataLink、自定义对象等 |
|
||||
| **命令行** | `hose-aipro <子命令>` | `hose-use <子命令>` |
|
||||
| **Skill 目录** | `~/.agents/skills/hose-aipro` | `~/.agents/skills/hose-use` |
|
||||
| **共享基础设施** | 共享企业租户配置(`~/.config/hose-use/enterprises/`)与凭据体系 | 共享企业租户配置与凭据体系 |
|
||||
| **打包与安装** | 单一二进制(Unix Multicall Binary),安装与自升级自动同步 | 单一二进制(Unix Multicall Binary),安装与自升级自动同步 |
|
||||
| **服务互启互关** | `hose-aipro hose-use <start\|stop\|restart\|status>`(控制 hose-use 进程) | `hose-use aipro <start\|stop\|restart\|status>`(控制 hose-aipro 进程) |
|
||||
| **自升级命令** | `hose-aipro update [check\|--changelog]`(与 hose-use 完全一致) | `hose-use update [check\|--changelog]`(与 hose-aipro 完全一致) |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **强确定性硬条款阻断**:AI 仅负责对事实证据进行核验与状态打标(`PASS` / `FAIL` / `SKIP`);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】硬编码规则进行物理裁决,切断模型幻觉可能导致的违规放行。
|
||||
> 如需管理企业账套、工作流或基础单据数据,请直接使用配套的 `hose-use` 命令行与 `hose-use` Skill。
|
||||
|
||||
---
|
||||
|
||||
## 首次安装与激活(Agent 操作序列)
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AI PRO **默认不激活**。装完二进制后,业务命令一律返回 `AIPRO_NOT_ACTIVATED`。
|
||||
> 凭证**不能由 Agent 自行生成**——客户端只内嵌验签公钥,私钥在服务方手里。
|
||||
> 遇到未激活时,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` 字段。申请凭证时必须把它交给服务方,服务方据此设定凭证的 `maxVersion`。
|
||||
|
||||
### 步骤 2 · 判断是否已激活
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
- 返回场景数组 → 已激活,直接跳到步骤 5。
|
||||
- 返回 `{"code":"AIPRO_NOT_ACTIVATED","reason":"missing"}` → 未激活,继续步骤 3。
|
||||
|
||||
`status` / `help` / `version` 属自省命令,未激活也能运行;`scopes` 等业务命令一律受统一门禁管辖。
|
||||
|
||||
### 步骤 3 · 向服务方申请凭证(Agent 在此停下)
|
||||
|
||||
把下表交给人类用户,由用户通过微信 / 邮件 / 工单等**离线渠道**向服务方申请:
|
||||
|
||||
| 需要提供的信息 | 来源 |
|
||||
|---|---|
|
||||
| 当前二进制版本 | 步骤 1 的 `version` |
|
||||
| 期望到期日 | 用户决定;凭证里是绝对到期时间 `exp` |
|
||||
| 客户名 / 用途标识 | 用户决定;会写进凭证的 `sub` |
|
||||
|
||||
服务方返回一串凭证文本。**Agent 不要自己生成、不要拼接、不要修改、不要截断这串文本**;含点号与特殊字符时务必用单引号包裹。
|
||||
|
||||
### 步骤 4 · 本地激活
|
||||
|
||||
```bash
|
||||
hose-aipro login '<凭证>'
|
||||
# 等价写法
|
||||
hose-aipro login --token='<凭证>'
|
||||
```
|
||||
|
||||
纯本地验签并落盘,**不联网**。凭证写到 `~/.config/hose-use/aipro-license.token`(0600);可用 `HOSE_AIPRO_LICENSE_FILE` 环境变量指向别的位置。
|
||||
|
||||
### 步骤 5 · 验证
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
返回真实场景数据即激活成功。`hose-aipro login --json` 会输出授权对象、到期时间与版本上限。
|
||||
|
||||
### 失败原因与处理
|
||||
|
||||
| `reason` | 含义 | 处理 |
|
||||
|---|---|---|
|
||||
| `missing` | 未激活 | 走步骤 3 申请凭证 |
|
||||
| `expired` | 已超过 `exp` 绝对到期时间 | 重新申请凭证 |
|
||||
| `version_exceeded` | 当前版本高于 `maxVersion` | **不要降级二进制**,重新申请更高 `maxVersion` 的凭证 |
|
||||
| `bad_signature` | 凭证被篡改或复制不完整 | 重新复制完整凭证,检查引号与换行 |
|
||||
| `no_feature` / `malformed` | 凭证不含 AI PRO 授权或格式错误 | 重新申请凭证 |
|
||||
|
||||
### 两条约束
|
||||
|
||||
- 当前二进制版本不得高于凭证的 `maxVersion`(三段数字比较,忽略 `-dev` 后缀)。**升级二进制超过上限会立刻失效**,需重新申请。
|
||||
- 当前时间不得晚于凭证的 `exp`(绝对到期时间)。客户端不做设备绑定、不做时钟防篡改。
|
||||
|
||||
凭证是 Ed25519 签名数据,不是二进制变体:所有客户下载的是**同一个二进制**,区别只在本地有没有凭证文件。新增任意 AI PRO 命令自动受统一门禁管辖。
|
||||
|
||||
---
|
||||
|
||||
## 快速自省与运行上下文 (Zero-Source-Reading)
|
||||
|
||||
在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文:
|
||||
|
||||
```bash
|
||||
# 1. 查看 AI PRO 网关状态与当前连接企业
|
||||
hose-aipro status [--json]
|
||||
# 别名: hose-aipro whoami, hose-aipro context
|
||||
|
||||
# 2. 查看审批规则场景库
|
||||
hose-aipro scopes
|
||||
|
||||
# 3. 查看特定场景下的审核要点清单
|
||||
hose-aipro points 1
|
||||
# 或通过场景名查看: hose-aipro points 差旅报销
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 核心审批仲裁全流程 (End-to-End Workflow)
|
||||
|
||||
```text
|
||||
1. 挂载单据 2. 录入事实证据 3. 确定性仲裁 4. 审计溯源
|
||||
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
|
||||
│ hose-aipro bind │ ───> │ hose-aipro review│ ───> │hose-aipro decide │ ───> │ hose-aipro logs │
|
||||
│ 绑定单号与场景要点 │ │ PASS/FAIL/SKIP │ │ 硬门禁裁决与流转 │ │ 全链路不可篡改审计 │
|
||||
└──────────────────┘ └──────────────────┘ └──────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
### 1. 挂载绑定要点 (`bind`)
|
||||
将目标审批单据与特定审核场景的规则要点关联并初始化会话:
|
||||
```bash
|
||||
hose-aipro bind S26000001 1
|
||||
# 或指定企业: hose-aipro bind S26000001 1 --corp=test-corp
|
||||
```
|
||||
|
||||
### 2. 查看审核清单 (`checklist`)
|
||||
检查当前单据各要点的当前核验状态:
|
||||
```bash
|
||||
hose-aipro checklist S26000001
|
||||
```
|
||||
|
||||
### 3. 事实证据核验与打标 (`review`)
|
||||
针对各项条款录入客观核验证据并打标:
|
||||
```bash
|
||||
# 方式 A: 批量 JSON 打标
|
||||
hose-aipro review S26000001 --findings='[{"index":1,"status":"PASS","evidence":"发票真伪查验通过"},{"index":2,"status":"FAIL","reasoning":"超标200元"}]'
|
||||
|
||||
# 方式 B: 单项打标
|
||||
hose-aipro review S26000001 --point=2 --status=FAIL --reason="住宿费用超出差旅标准 200 元"
|
||||
```
|
||||
|
||||
### 4. 确定性网关仲裁 (`decide`)
|
||||
根据打标结果进行门禁判定:
|
||||
```bash
|
||||
# 预审模拟(Dry Run,仅计算仲裁裁决,不向云端提交真实流转动作)
|
||||
hose-aipro decide S26000001
|
||||
|
||||
# 真实执行(必须追加 --apply --yes)
|
||||
hose-aipro decide S26000001 --apply --yes
|
||||
```
|
||||
|
||||
### 5. 审计流水追溯 (`logs`)
|
||||
```bash
|
||||
hose-aipro logs S26000001
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 本机常驻服务与跨进程管理 (Daemon & Peer Control)
|
||||
|
||||
`hose-aipro` 拥有独立的常驻 HTTP 守护进程(默认端口 `8889`),并能直接启停本机的 `hose-use` 服务(默认端口 `8888`):
|
||||
|
||||
```bash
|
||||
# 管理 hose-aipro 自身的服务 (端口 8889)
|
||||
hose-aipro service start
|
||||
hose-aipro service status
|
||||
hose-aipro service logs
|
||||
hose-aipro service stop
|
||||
|
||||
# 管理本机的 hose-use 服务 (端口 8888)
|
||||
hose-aipro hose-use start
|
||||
hose-aipro hose-use status
|
||||
hose-aipro hose-use stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 统一自升级与技能管理 (Update & Skill)
|
||||
|
||||
由于 `hose-aipro` 与 `hose-use` 由单一多呼叫二进制(Multicall Binary)构建,升级与技能操作保持完全统一:
|
||||
|
||||
```bash
|
||||
# 检查与执行版本自升级(同时更新 hose-aipro 与 hose-use)
|
||||
hose-aipro update
|
||||
hose-aipro update check
|
||||
hose-aipro update --changelog
|
||||
|
||||
# 查看与安装全局 Agent Skill
|
||||
hose-aipro skill status
|
||||
hose-aipro skill install --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 详细业务与专卷参考
|
||||
|
||||
深入细节请查阅对应参考文档:
|
||||
- 审批裁决、打标语义与规约语法:[references/approval.md](./references/approval.md)
|
||||
- 常驻服务与 HTTP 接口规范:[references/service.md](./references/service.md)
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
command: "hose-aipro"
|
||||
default_args: []
|
||||
@@ -0,0 +1,10 @@
|
||||
# hose-aipro 参考专卷索引 (references)
|
||||
|
||||
本目录是随 `hose-aipro` 分发的业务操作与服务管理参考,供 [hose-aipro Skill 入口](../SKILL.md) 按任务读取。
|
||||
|
||||
## 参考清单
|
||||
|
||||
| 文档 | 主题 |
|
||||
|---|---|
|
||||
| [approval.md](./approval.md) | AI PRO 审批核验流程、确定性网关仲裁规则与语法等级 |
|
||||
| [service.md](./service.md) | 常驻守护进程管理、HTTP 接口与对 hose-use 的跨进程启停控制 |
|
||||
@@ -1,14 +1,14 @@
|
||||
# 合思 AI PRO 确定性审批仲裁网关 (Approval Gateway & AI PRO Guide)
|
||||
# 合思 AI PRO 确定性审批仲裁网关专卷 (Approval Gateway & Rules)
|
||||
|
||||
本参考专卷面向开发者与 AI 智能体,系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
本参考专卷系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构与定位
|
||||
|
||||
- **双向命令入口**:可通过独立二进制 `hose-aipro <子命令>` 或统一入口 `hose-use aipro <子命令>` 唤起。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/config.json` 与 `enterprises` 凭证目录)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 或 `hose-use context` 即可直接构建完整的运行时上下文,无需翻阅代码。
|
||||
- **独立专属入口**:通过 `hose-aipro <子命令>` 执行所有审批、核验与仲裁动作。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/enterprises/` 凭据目录与 `config.json`)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 即可直接构建完整的审批与企业上下文,无需翻阅代码。
|
||||
- **强确定性硬条款阻断**:AI 仅负责事实核验打标(PASS / FAIL / SKIP);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】分级硬编码规则仲裁,物理切断幻觉可能导致的违规放行。
|
||||
|
||||
---
|
||||
@@ -25,8 +25,6 @@ hose-aipro status --json
|
||||
### 步骤 1:查看规约场景索引库
|
||||
```bash
|
||||
hose-aipro scopes
|
||||
# 或使用 hose-use:
|
||||
hose-use rule scopes
|
||||
```
|
||||
- 输出本地 SQLite 数据库中所有生效场景(如 `#1 差旅报销`、`#2 业务招待`)及规则条数。
|
||||
|
||||
@@ -52,8 +50,8 @@ hose-aipro checklist S26000001
|
||||
|
||||
### 步骤 5:逐项录入事实核验打标
|
||||
```bash
|
||||
# 批量快速打标:
|
||||
hose-aipro review S26000001 --eval "1=PASS:发票合规; 2=FAIL:住宿超标; 3=SKIP"
|
||||
# 批量打标:
|
||||
hose-aipro review S26000001 --findings='[{"index":1,"status":"PASS","evidence":"发票合规"},{"index":2,"status":"FAIL","reasoning":"住宿超标"}]'
|
||||
|
||||
# 单项精准打标:
|
||||
hose-aipro review S26000001 --point 2 --status FAIL --reason "住宿费超过差旅标准 200 元"
|
||||
@@ -0,0 +1,57 @@
|
||||
# hose-aipro 常驻服务与跨进程管理专卷 (Service & Daemon)
|
||||
|
||||
本参考专卷说明 `hose-aipro` 的常驻守护进程体系、HTTP 网关接口与对 `hose-use` 的跨进程管理能力。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构定位
|
||||
|
||||
`hose-aipro` 拥有独立的常驻后台 HTTP 守护进程(默认端口 `8889`,与 `hose-use` 的 `8888` 隔离):
|
||||
|
||||
- **PID 文件**: `~/.config/hose-use/aipro-service.pid`
|
||||
- **日志文件**: `~/.config/hose-use/aipro-service.log`
|
||||
- **默认监听地址**: `http://127.0.0.1:8889`
|
||||
- **HTTP 接口**:
|
||||
- `GET /`: 返回服务元数据
|
||||
- `GET /health`: 健康探针
|
||||
- `GET /v1/status`: 当前 AI PRO 网关与企业上下文
|
||||
- `POST /api/cli`: HTTP 版 CLI 执行网关
|
||||
|
||||
---
|
||||
|
||||
## 2. hose-aipro 自身服务管理
|
||||
|
||||
```bash
|
||||
# 启动后台常驻网关
|
||||
hose-aipro service start
|
||||
|
||||
# 查看服务运行状态
|
||||
hose-aipro service status
|
||||
hose-aipro service status --json
|
||||
|
||||
# 查看后台运行日志
|
||||
hose-aipro service logs
|
||||
|
||||
# 重启后台服务
|
||||
hose-aipro service restart
|
||||
|
||||
# 停止后台服务
|
||||
hose-aipro service stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 对本机 hose-use 服务的跨进程管理
|
||||
|
||||
通过 `hose-aipro hose-use <action>` 可以直接控制本机的通用平台守护进程:
|
||||
|
||||
```bash
|
||||
# 启动本机的 hose-use 服务 (端口 8888)
|
||||
hose-aipro hose-use start
|
||||
|
||||
# 查看本机的 hose-use 服务状态
|
||||
hose-aipro hose-use status
|
||||
|
||||
# 停止本机的 hose-use 服务
|
||||
hose-aipro hose-use stop
|
||||
```
|
||||
@@ -2,24 +2,29 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.22
|
||||
version: 0.9.2
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.22)
|
||||
# hose-use (v0.9.2)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
---
|
||||
|
||||
## 本套件结构(先看这里)
|
||||
## 本套件结构与独立配套技能(先看这里)
|
||||
|
||||
本 skill 是**合思/易快报系列的唯一入口**,下级技能不在模型目录中,按需读取:
|
||||
- **`hose-use`(本技能)**:合思企业级 SaaS 底层入口(登录、租户、单据、通讯录、档案、费用类型、角色、待办、自建应用、工作流、应用中心、守护进程)。
|
||||
- **`hose-aipro`(独立配套技能)**:合思 AI PRO 确定性审批仲裁网关(审核要点、事实证据打标、确定性硬门禁仲裁、审批日志)。通过独立命令 `hose-aipro` 运行。
|
||||
- **服务互启互关**:在 `hose-use` 中可通过 `hose-use aipro <start|stop|restart|status>` 管理本机的 `hose-aipro` 常驻服务;反之在 `hose-aipro` 中可通过 `hose-aipro hose-use <start|stop|restart|status>` 管理本机的 `hose-use` 服务。
|
||||
- **单一二进制与统一升级**:`hose-use` 与 `hose-aipro` 由单一多呼叫二进制(Unix Multicall Binary)打包分发,运行 `hose-use update` 或 `hose-aipro update` 均可同时升级两套命令行与对应的两个 Skill。
|
||||
|
||||
| 需要做什么 | 去哪里 |
|
||||
|---|---|
|
||||
| 登录/租户/单据/审批/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
|
||||
| 登录/租户/单据/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
|
||||
| AI PRO 确定性审批仲裁、事实证据打标与要点清单 | 请使用独立配套技能 `hose-aipro` 与命令行 `hose-aipro` |
|
||||
| 本机 AI PRO 审批网关常驻服务管理 | `hose-use aipro <start\|stop\|restart\|status>`;细节读 `references/service.md` |
|
||||
| 写或排错**工作流 MVEL 代码节点**脚本 | `multi/ekuaibao-mvel/SKILL.md` |
|
||||
| **批量开通工作流节点**(从浏览器 curl 提取 token/corpId/baseUrl) | `multi/ekuaibao-nodes/SKILL.md` |
|
||||
|
||||
@@ -92,10 +97,9 @@ metadata:
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) |
|
||||
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](./references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 / 事实证据核验 | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [独立技能 hose-aipro](../hose-aipro/SKILL.md) |
|
||||
| 本机 AI PRO 审批网关常驻服务启停与管理 | `hose-use aipro <start\|stop\|restart\|status>` | [references/service.md](./references/service.md) |
|
||||
| 本地审批规约场景与规则管理 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/service.md](./references/service.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](./references/auth.md) |
|
||||
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](./references/auth.md) |
|
||||
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](./references/auth.md) |
|
||||
|
||||
@@ -13,34 +13,33 @@ 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
|
||||
curl -s -X POST 'https://d9jxeccs5j.sealosgzg.site/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
|
||||
```
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
工作流节点开通的默认 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
||||
|
||||
**每个企业的工作流只对应一个 Piper 环境**:标准 Piper(默认)与测试 Piper(`--is-test`)二选一,不会同时可用,也不会在请求失败时自动切换。若某企业通过标准 Piper 成功开通,说明它的工作流在标准环境;同一企业再通过测试 Piper 开通应失败,反之亦然。企业名称、本地 `env=test` 标记和企业 `baseUrl` 都不能用来推断 Piper 环境。
|
||||
|
||||
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
|
||||
|
||||
## 结果处理
|
||||
|
||||
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
|
||||
**成功**:CLI 根据 Piper 业务响应中的 `code` 确认开通结果,并显示新开通或已开通的节点。
|
||||
|
||||
**失败排查**:
|
||||
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
|
||||
- `认证失败` + 其他 — token 过期,让用户重新获取
|
||||
- 认证失败 — 检查本地企业凭证是否有效,并按 CLI 提示重新登录或刷新认证
|
||||
- Piper 业务码失败 — 依据 CLI 返回的业务错误信息排查企业或节点配置
|
||||
- 节点名错误 — 核对名称拼写
|
||||
@@ -9,7 +9,6 @@
|
||||
| [auth.md](./auth.md) | 登录、企业身份与运行模式 |
|
||||
| [assist-platform.md](./assist-platform.md) | 协助平台、工单及代客登录 |
|
||||
| [bill.md](./bill.md) | 单据、费用明细、复制与写入操作 |
|
||||
| [approval.md](./approval.md) | AI PRO 确定性审批与规则 |
|
||||
| [workflow.md](./workflow.md) | 自建应用、工作流、节点、调试和恢复 |
|
||||
| [contact.md](./contact.md) | 通讯录与员工档案 |
|
||||
| [dimension.md](./dimension.md) | 自定义档案和核算维度 |
|
||||
|
||||
@@ -42,6 +42,25 @@ hose-use service poll --corp=<corpId>
|
||||
hose-use service poll --corp=<corpId> --limit=100 --json
|
||||
```
|
||||
|
||||
### 管理本机配套的 hose-aipro 服务 (`hose-use aipro`)
|
||||
|
||||
在 `hose-use` 中可直接管理本机的 `hose-aipro` 审批网关守护进程:
|
||||
|
||||
```bash
|
||||
# 启动本机配套的 hose-aipro 审批网关常驻服务 (默认端口 8889)
|
||||
hose-use aipro start
|
||||
|
||||
# 查看 hose-aipro 服务状态
|
||||
hose-use aipro status
|
||||
|
||||
# 查看 hose-aipro 服务日志
|
||||
hose-use aipro logs
|
||||
|
||||
# 重启 / 停止 hose-aipro 服务
|
||||
hose-use aipro restart
|
||||
hose-use aipro stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 前台 HTTP 服务 (`http` / `serve`)
|
||||
|
||||
@@ -503,6 +503,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 的错误节点和回写内容。草稿创建成功只证明此次草稿落库,不能据此声称提交送审、审批或付款成功;未验证的收款方、法人实体等字段应明确列出。关联引用次数耗尽可能自动停用源记录,不得为了重跑擅自重置引用次数、启用记录或重复创单。
|
||||
|
||||
@@ -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.8.22
|
||||
version: 0.9.2
|
||||
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.8.22",
|
||||
"version": "0.9.2",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,11 +1,44 @@
|
||||
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,
|
||||
isSaasPlatformCommand,
|
||||
SAAS_PLATFORM_COMMANDS,
|
||||
} 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);
|
||||
@@ -24,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 () => {
|
||||
@@ -159,4 +195,60 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
|
||||
});
|
||||
|
||||
test("二级公共命令一致性:update、skill 与 service 正常执行", async () => {
|
||||
// 1. update --dry-run
|
||||
const updateRes = await runAiProCli(["update", "--dry-run", "--json"]);
|
||||
expect(updateRes.exitCode).toBe(0);
|
||||
const updateData = JSON.parse(updateRes.stdout);
|
||||
expect(updateData.dryRun).toBe(true);
|
||||
|
||||
// 2. skill status
|
||||
const skillRes = await runAiProCli(["skill", "status", "--json"]);
|
||||
expect(skillRes.exitCode).toBe(0);
|
||||
const skillData = JSON.parse(skillRes.stdout);
|
||||
expect(skillData["hose-use"]).toBeDefined();
|
||||
expect(skillData["hose-aipro"]).toBeDefined();
|
||||
|
||||
// 3. service status (hose-aipro 自身)
|
||||
const serviceRes = await runAiProCli(["service", "status", "--json"]);
|
||||
expect(serviceRes.exitCode).toBe(0);
|
||||
const serviceData = JSON.parse(serviceRes.stdout);
|
||||
expect(serviceData.serviceName).toBe("hose-aipro");
|
||||
expect(serviceData.port).toBe(8889);
|
||||
|
||||
// 4. hose-use 服务跨进程管理 (hose-aipro hose-use status)
|
||||
const peerRes = await runAiProCli(["hose-use", "status", "--json"]);
|
||||
expect(peerRes.exitCode).toBe(0);
|
||||
const peerData = JSON.parse(peerRes.stdout);
|
||||
expect(peerData.serviceName).toBe("hose-use");
|
||||
expect(peerData.port).toBe(8888);
|
||||
|
||||
// 5. SaaS 命令在 hose-aipro 下友好重定向提示
|
||||
const billRes = await runAiProCli(["bill", "list"]);
|
||||
expect(billRes.exitCode).toBe(1);
|
||||
expect(billRes.stderr).toContain("属于合思企业平台能力,由 hose-use 命令行提供");
|
||||
});
|
||||
|
||||
test("声明式注册表规范性:所有命令与别名同元数据严格对齐", () => {
|
||||
const meta = COMMAND_METADATA["hose-aipro"];
|
||||
expect(meta).toBeDefined();
|
||||
|
||||
// 1. 注册表中的每一个命令都在 metadata.commands 中有说明
|
||||
for (const cmd of AIPRO_COMMAND_REGISTRY) {
|
||||
expect(meta.commands[cmd.name]).toBeDefined();
|
||||
}
|
||||
|
||||
// 2. 所有的别名都能正确通过 findAiProCommand 查找到原命令
|
||||
for (const [alias, canonical] of Object.entries(meta.commandAliases)) {
|
||||
const def = findAiProCommand(alias);
|
||||
expect(def).toBeDefined();
|
||||
expect(def?.name).toBe(canonical);
|
||||
}
|
||||
|
||||
// 3. 所有的 SaaS 重定向命令都正确标记
|
||||
for (const saasCmd of SAAS_PLATFORM_COMMANDS) {
|
||||
expect(isSaasPlatformCommand(saasCmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+43
-82
@@ -9,21 +9,13 @@ import {
|
||||
ApprovalRepository,
|
||||
ApprovalGatewayBlockedError,
|
||||
} from "./domains/approval/index.js";
|
||||
import { formatVersionLabel, getVersionInfo } from "./version.js";
|
||||
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js";
|
||||
import {
|
||||
handleAiProChecklist,
|
||||
handleAiProPoints,
|
||||
handleAiProRules,
|
||||
handleAiProScopes,
|
||||
} from "./cli/commands/aipro/rules.js";
|
||||
import {
|
||||
handleAiProBind,
|
||||
handleAiProDecide,
|
||||
handleAiProInit,
|
||||
handleAiProReview,
|
||||
handleAiProTranslate,
|
||||
} from "./cli/commands/aipro/session.js";
|
||||
findAiProCommand,
|
||||
isSaasPlatformCommand,
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import { assertAiProEnabled, handleAiProLogin } from "./cli/aipro-license.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -51,10 +43,21 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
const previewCommand = (previewPositional[0] || "help").toLowerCase();
|
||||
const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3);
|
||||
if (mutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
const previewDef = findAiProCommand(previewCommand);
|
||||
const isMutating = typeof previewDef?.mutating === "function"
|
||||
? previewDef.mutating(parsed, previewPositional)
|
||||
: Boolean(previewDef?.mutating);
|
||||
|
||||
if (isMutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
{ ...parsed, raw: ["hose-aipro", ...rawArgs] },
|
||||
runtime,
|
||||
"预览 AI PRO 审批操作",
|
||||
stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定",
|
||||
{ action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) }
|
||||
);
|
||||
}
|
||||
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | undefined;
|
||||
@@ -95,74 +98,32 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
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);
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "context":
|
||||
case "info":
|
||||
return await handleAiProStatus(ctx);
|
||||
|
||||
case "init":
|
||||
case "start":
|
||||
return await handleAiProInit(ctx);
|
||||
|
||||
case "scopes":
|
||||
case "index":
|
||||
case "indexes":
|
||||
return await handleAiProScopes(ctx);
|
||||
|
||||
case "translate":
|
||||
case "doc":
|
||||
case "markdown":
|
||||
case "render":
|
||||
return await handleAiProTranslate(ctx);
|
||||
|
||||
case "rules":
|
||||
case "rule":
|
||||
return await handleAiProRules(ctx);
|
||||
|
||||
case "bind":
|
||||
case "mount":
|
||||
return await handleAiProBind(ctx);
|
||||
|
||||
case "points":
|
||||
case "clauses":
|
||||
return await handleAiProPoints(ctx);
|
||||
|
||||
case "checklist":
|
||||
case "list":
|
||||
return await handleAiProChecklist(ctx);
|
||||
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate":
|
||||
return await handleAiProReview(ctx);
|
||||
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject":
|
||||
return await handleAiProDecide(ctx);
|
||||
|
||||
case "logs":
|
||||
case "log":
|
||||
case "history":
|
||||
case "trail":
|
||||
return await handleAiProLogs(ctx);
|
||||
|
||||
case "help":
|
||||
default:
|
||||
return handleAiProHelp(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;
|
||||
}
|
||||
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
}
|
||||
|
||||
if (isSaasPlatformCommand(command)) {
|
||||
return handleSaasPlatformRedirect(command, positional);
|
||||
}
|
||||
|
||||
return await handleAiProHelp(ctx);
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
repo.logAiProAction({
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)及统一导出。新增命令先声明元数据,再在此注册处理器。
|
||||
- `aipro-registry.ts`:`AIPRO_COMMAND_REGISTRY` AI PRO 确定性审批命令的声明式注册表(命令名称、别名、突变标记 `mutating`、处理器 `handler`)与 SaaS 重定向判定。与 `registry.ts` 保持完全一致的声明式设计。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
|
||||
@@ -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 尚未激活。凭证需向服务方离线申请,拿到后运行 hose-aipro login <凭证>" };
|
||||
}
|
||||
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 的版本号与期望到期日),再运行 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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./commands/aipro/status.js";
|
||||
import {
|
||||
handleAiProChecklist,
|
||||
handleAiProPoints,
|
||||
handleAiProRules,
|
||||
handleAiProScopes,
|
||||
} from "./commands/aipro/rules.js";
|
||||
import {
|
||||
handleAiProBind,
|
||||
handleAiProDecide,
|
||||
handleAiProInit,
|
||||
handleAiProReview,
|
||||
handleAiProTranslate,
|
||||
} from "./commands/aipro/session.js";
|
||||
import { handleUpdateCommand } from "./commands/update/index.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { formatVersionLabel, getVersionInfo } from "../version.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { AiProExecutionContext } from "./commands/aipro/types.js";
|
||||
import type { CliParsedArgs, CliResult } from "./types.js";
|
||||
|
||||
export type AiProMutatingCheck =
|
||||
| boolean
|
||||
| ((parsed: CliParsedArgs, positional: string[]) => boolean);
|
||||
|
||||
export interface AiProCommandDefinition {
|
||||
name: string;
|
||||
summary: string;
|
||||
aliases?: readonly string[];
|
||||
mutating?: AiProMutatingCheck;
|
||||
handler: (ctx: AiProExecutionContext) => Promise<CliResult> | CliResult;
|
||||
}
|
||||
|
||||
export const AIPRO_COMMAND_REGISTRY: readonly AiProCommandDefinition[] = [
|
||||
{
|
||||
name: "status",
|
||||
summary: "查看网关状态",
|
||||
aliases: ["whoami", "context", "info"],
|
||||
handler: (ctx) => handleAiProStatus(ctx),
|
||||
},
|
||||
{
|
||||
name: "init",
|
||||
summary: "初始化审批上下文",
|
||||
aliases: ["start"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProInit(ctx),
|
||||
},
|
||||
{
|
||||
name: "scopes",
|
||||
summary: "列出审批规则场景",
|
||||
aliases: ["index", "indexes"],
|
||||
handler: (ctx) => handleAiProScopes(ctx),
|
||||
},
|
||||
{
|
||||
name: "translate",
|
||||
summary: "转译单据",
|
||||
aliases: ["doc", "markdown", "render"],
|
||||
handler: (ctx) => handleAiProTranslate(ctx),
|
||||
},
|
||||
{
|
||||
name: "rules",
|
||||
summary: "查看审批规则",
|
||||
aliases: ["rule"],
|
||||
handler: (ctx) => handleAiProRules(ctx),
|
||||
},
|
||||
{
|
||||
name: "bind",
|
||||
summary: "绑定单据",
|
||||
aliases: ["mount"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProBind(ctx),
|
||||
},
|
||||
{
|
||||
name: "points",
|
||||
summary: "查看审核要点",
|
||||
aliases: ["clauses"],
|
||||
mutating: (_parsed, positional) => positional.length >= 3,
|
||||
handler: (ctx) => handleAiProPoints(ctx),
|
||||
},
|
||||
{
|
||||
name: "checklist",
|
||||
summary: "查看核验清单",
|
||||
aliases: ["list"],
|
||||
handler: (ctx) => handleAiProChecklist(ctx),
|
||||
},
|
||||
{
|
||||
name: "review",
|
||||
summary: "核验要点",
|
||||
aliases: ["eval", "evaluate"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProReview(ctx),
|
||||
},
|
||||
{
|
||||
name: "decide",
|
||||
summary: "执行仲裁",
|
||||
aliases: ["approve", "reject"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProDecide(ctx),
|
||||
},
|
||||
{
|
||||
name: "logs",
|
||||
summary: "查看审批日志",
|
||||
aliases: ["log", "history", "trail"],
|
||||
handler: (ctx) => handleAiProLogs(ctx),
|
||||
},
|
||||
{
|
||||
name: "service",
|
||||
summary: "管理本机 hose-aipro 常驻服务",
|
||||
aliases: ["daemon"],
|
||||
handler: async (ctx) => {
|
||||
const subTarget = ctx.positional[1]?.toLowerCase();
|
||||
if (subTarget === "hose-use" || subTarget === "hose") {
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: ctx.positional[2] || "status", args: ctx.positional.slice(3) },
|
||||
ctx.runtime,
|
||||
"hose-use"
|
||||
);
|
||||
}
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: ctx.positional[1] || "status", args: ctx.positional.slice(2) },
|
||||
ctx.runtime,
|
||||
"hose-aipro"
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "hose-use",
|
||||
summary: "管理本机 hose-use 常驻服务",
|
||||
aliases: ["hose"],
|
||||
handler: async (ctx) => {
|
||||
const subAction = (ctx.positional[1] || "status").toLowerCase();
|
||||
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
|
||||
if (serviceActions.includes(subAction)) {
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: subAction, args: ctx.positional.slice(2) },
|
||||
ctx.runtime,
|
||||
"hose-use"
|
||||
);
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] 运行 hose-use ${subAction} 可直接调用合思企业平台命令。\n` +
|
||||
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
|
||||
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
summary: "检查并升级版本",
|
||||
aliases: ["self-update"],
|
||||
handler: async (ctx) => handleUpdateCommand(ctx.parsed, ctx.runtime),
|
||||
},
|
||||
{
|
||||
name: "skill",
|
||||
summary: "管理 Agent 技能",
|
||||
aliases: ["skills"],
|
||||
handler: async (ctx) => handleSkillCommand(ctx.parsed, ctx.runtime),
|
||||
},
|
||||
{
|
||||
name: "version",
|
||||
summary: "查看版本信息",
|
||||
aliases: ["v"],
|
||||
handler: async (ctx) => ({
|
||||
stdout: ctx.jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "help",
|
||||
summary: "查看帮助说明",
|
||||
handler: (ctx) => handleAiProHelp(ctx),
|
||||
},
|
||||
];
|
||||
|
||||
const aiproCommandMap = new Map<string, AiProCommandDefinition>();
|
||||
for (const def of AIPRO_COMMAND_REGISTRY) {
|
||||
aiproCommandMap.set(def.name.toLowerCase(), def);
|
||||
for (const alias of def.aliases || []) {
|
||||
aiproCommandMap.set(alias.toLowerCase(), def);
|
||||
}
|
||||
}
|
||||
|
||||
export function findAiProCommand(name: string): AiProCommandDefinition | undefined {
|
||||
return aiproCommandMap.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
export const SAAS_PLATFORM_COMMANDS = [
|
||||
"bill",
|
||||
"flow",
|
||||
"workflow",
|
||||
"platform",
|
||||
"datalink",
|
||||
"auth",
|
||||
"corps",
|
||||
"contact",
|
||||
"feetype",
|
||||
"dimension",
|
||||
"role",
|
||||
"permission",
|
||||
"keys",
|
||||
"store",
|
||||
"message",
|
||||
"task",
|
||||
"config",
|
||||
"mcp",
|
||||
"assist-platform",
|
||||
] as const;
|
||||
|
||||
export function isSaasPlatformCommand(command: string): boolean {
|
||||
return (SAAS_PLATFORM_COMMANDS as readonly string[]).includes(command.toLowerCase());
|
||||
}
|
||||
|
||||
export function handleSaasPlatformRedirect(
|
||||
command: string,
|
||||
positional: string[] = []
|
||||
): CliResult {
|
||||
const subArgs = positional.slice(1).join(" ");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] ${command} 属于合思企业平台能力,由 hose-use 命令行提供。\n` +
|
||||
`请直接运行: hose-use ${command}${subArgs ? ` ${subArgs}` : ""}\n\n` +
|
||||
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
|
||||
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import { tmpdir } from "node:os";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { closeDatabase } from "../core/db/index.js";
|
||||
|
||||
const keys = ["HOSE_APPROVAL_DB", "HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
|
||||
const original = keys.map(key => process.env[key]);
|
||||
afterEach(() => { closeDatabase(); keys.forEach((key, i) => { if (original[i] === undefined) delete process.env[key]; else process.env[key] = original[i]; }); });
|
||||
test("approval and aipro dry-runs override apply/yes without requests or database creation", async () => {
|
||||
|
||||
test("aipro dry-runs override apply/yes without requests or database creation", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-approval-preview-"));
|
||||
const corps = join(root, "corps"); mkdirSync(corps);
|
||||
writeFileSync(join(corps, "corp.json"), JSON.stringify({ id: "corp", name: "Preview", source: "manual", credentials: { accessToken: "fixture", corpId: "corp", staffId: "staff" } }));
|
||||
@@ -19,15 +21,16 @@ test("approval and aipro dry-runs override apply/yes without requests or databas
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("No network during preview"); }) as any;
|
||||
try {
|
||||
for (const action of ["points", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runCli(["approval", action, "SN", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
}
|
||||
for (const action of ["init", "bind", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runAiProCli([action, "approve", "--run", "ABC123", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-use aipro ");
|
||||
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-aipro ");
|
||||
}
|
||||
// hose-use approval 重定向测试
|
||||
const redirect = await runCli(["approval", "decide", "S123"]);
|
||||
expect(redirect.exitCode).toBe(1);
|
||||
expect(redirect.stderr).toContain("hose-aipro");
|
||||
|
||||
expect(requests).toBe(0); expect(existsSync(process.env.HOSE_APPROVAL_DB)).toBe(false);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
+73
-17
@@ -32,20 +32,23 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
flags: { ...flagList("offline cached", "boolean") }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
"usage": "hose-use aipro <子命令>",
|
||||
"summary": "管理本机 hose-aipro 审批网关常驻服务",
|
||||
"usage": "hose-use aipro <start|stop|restart|status|logs>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"start": "启动本机 hose-aipro 网关服务",
|
||||
"stop": "停止本机 hose-aipro 网关服务",
|
||||
"restart": "重启本机 hose-aipro 网关服务",
|
||||
"status": "查看本机 hose-aipro 网关服务状态",
|
||||
"logs": "查看本机 hose-aipro 网关服务日志",
|
||||
"bind": "绑定单据 (已独立为 hose-aipro bind)",
|
||||
"review": "核验要点 (已独立为 hose-aipro review)",
|
||||
"decide": "执行仲裁 (已独立为 hose-aipro decide)",
|
||||
"init": "初始化审批会话 (已独立为 hose-aipro init)",
|
||||
"scopes": "列出审批规则场景 (已独立为 hose-aipro scopes)",
|
||||
"translate": "转译单据 (已独立为 hose-aipro translate)",
|
||||
"rules": "查看审批规则 (已独立为 hose-aipro rules)",
|
||||
"points": "查看审核要点 (已独立为 hose-aipro points)",
|
||||
"checklist": "查看核验清单 (已独立为 hose-aipro checklist)",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
@@ -71,7 +74,59 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"history": "logs",
|
||||
"trail": "logs"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"hose-aipro": {
|
||||
"summary": "合思 AI PRO 确定性审批仲裁网关",
|
||||
"usage": "hose-aipro <子命令>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"service": "管理本机 hose-aipro 常驻服务",
|
||||
"hose-use": "管理本机 hose-use 常驻服务",
|
||||
"update": "检查并升级版本",
|
||||
"skill": "管理 Agent 技能",
|
||||
"version": "查看版本信息",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"context": "status",
|
||||
"info": "status",
|
||||
"start": "init",
|
||||
"index": "scopes",
|
||||
"indexes": "scopes",
|
||||
"doc": "translate",
|
||||
"markdown": "translate",
|
||||
"render": "translate",
|
||||
"rule": "rules",
|
||||
"mount": "bind",
|
||||
"clauses": "points",
|
||||
"list": "checklist",
|
||||
"eval": "review",
|
||||
"evaluate": "review",
|
||||
"approve": "decide",
|
||||
"reject": "decide",
|
||||
"log": "logs",
|
||||
"history": "logs",
|
||||
"trail": "logs",
|
||||
"self-update": "update",
|
||||
"skills": "skill",
|
||||
"daemon": "service",
|
||||
"hose": "hose-use",
|
||||
"v": "version"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"auth": {
|
||||
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
@@ -231,6 +286,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--is-test 选择测试 Piper;每个企业的工作流只在标准/测试环境之一,不会自动回退",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
@@ -279,7 +335,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
},
|
||||
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 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 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") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -869,11 +925,11 @@ export function localCommandFlags(area?: string, action?: string): Record<string
|
||||
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|
||||
|| (resolved?.area === "workflow" && canonical === "node")
|
||||
|| (resolved?.area === "platform" && canonical === "record")
|
||||
|| (resolved?.area === "aipro" && canonical === "bind");
|
||||
|| (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "bind");
|
||||
if (!localC) delete flags.c;
|
||||
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
|
||||
// --run historically accepts a session ID and, for decide, an apply boolean.
|
||||
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
|
||||
if (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "decide") flags.run = "boolean-or-value";
|
||||
return flags;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalGatewayBlockedError,
|
||||
FindingCheckStatus,
|
||||
} from "../../domains/approval/index.js";
|
||||
|
||||
export async function handleApprovalCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
// 解析命令层级:
|
||||
// 形式 A: hose-use approval audit points S26000001
|
||||
// 形式 B: hose-use approval points S26000001
|
||||
// 形式 C: hose-use approval audit S26000001
|
||||
let subAction = parsed.action?.toLowerCase();
|
||||
let args = [...parsed.args];
|
||||
|
||||
if (subAction === "audit" && args.length > 0) {
|
||||
const candidateSub = args[0]?.toLowerCase();
|
||||
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
|
||||
subAction = candidateSub;
|
||||
args.shift();
|
||||
}
|
||||
}
|
||||
|
||||
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
|
||||
|
||||
if (targetSn && isDryRun(parsed, runtime) && ["audit", "points", "inject", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(subAction || "audit")) {
|
||||
return mutationPreview(parsed, runtime, "预览审批操作", targetSn, { action: subAction || "audit", corpId, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
}
|
||||
const client = await createSessionClient(corp);
|
||||
const service = new ApprovalService();
|
||||
|
||||
switch (subAction) {
|
||||
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
|
||||
case "points":
|
||||
case "inject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
|
||||
}
|
||||
|
||||
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
|
||||
const result = await service.injectAuditPoints(client, corpId, targetSn, {
|
||||
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
|
||||
const rows = result.findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus,
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
|
||||
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
|
||||
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
|
||||
case "checklist":
|
||||
case "list":
|
||||
case "status": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
|
||||
}
|
||||
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run || findings.length === 0) {
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
|
||||
const rows = findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
|
||||
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
|
||||
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
|
||||
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
|
||||
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
|
||||
|
||||
const updates: Array<{
|
||||
index?: number;
|
||||
id?: string;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({
|
||||
index: pointIndex,
|
||||
status: statusInput,
|
||||
evidence,
|
||||
reasoning,
|
||||
});
|
||||
} else if (evalStr) {
|
||||
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
|
||||
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = match[2].toUpperCase() as FindingCheckStatus;
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({
|
||||
index: idx,
|
||||
status,
|
||||
evidence: desc,
|
||||
reasoning: desc,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
|
||||
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
|
||||
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
|
||||
const rows = updatedFindings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const msg =
|
||||
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
|
||||
table +
|
||||
(pendingCount === 0
|
||||
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
|
||||
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
|
||||
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
|
||||
}
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
if (apply) {
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
}
|
||||
|
||||
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
|
||||
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
|
||||
|
||||
try {
|
||||
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
|
||||
requestedAction,
|
||||
apply,
|
||||
comment: userComment,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(decisionResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outLines: string[] = [];
|
||||
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
|
||||
outLines.push(`网关决策 : ${decisionResult.decision}`);
|
||||
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
|
||||
if (apply) {
|
||||
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
|
||||
} else {
|
||||
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
|
||||
}
|
||||
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
|
||||
|
||||
return {
|
||||
stdout: outLines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `\n${err.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
|
||||
case "audit":
|
||||
case undefined: {
|
||||
if (!targetSn) {
|
||||
return {
|
||||
stdout:
|
||||
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
|
||||
`用法:\n` +
|
||||
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
|
||||
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
|
||||
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
|
||||
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 检查当前是否已注入要点
|
||||
const { run } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run) {
|
||||
// 自动触发第一步:注入并出审核要点
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "points", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
} else {
|
||||
// 已有要点,展示清单与进度
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "checklist", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
|
||||
}
|
||||
}
|
||||
@@ -73,11 +73,14 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
"测试企业目录": globalConfig.testEnterprisesDir || "未配置 (仅读全局用户企业)",
|
||||
"默认自更新仓库": globalConfig.updateRepo || "官方默认 (yunyingk/hose-use)",
|
||||
"自更新源偏好": globalConfig.updateSource || "auto (自动择优)",
|
||||
"choose 表达式形态": globalConfig.chooseSerialization === "pure"
|
||||
? "pure (配平形态, JSON 合法)"
|
||||
: "frontend (百分百模拟设计器, 多一个右花括号 — 默认)",
|
||||
"配置文件路径": configPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n`,
|
||||
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n choose 形态: hose-use config set chooseSerialization <frontend|pure>\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -214,10 +217,21 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
};
|
||||
}
|
||||
partial.updateSource = srcLower;
|
||||
} else if (keyLower === "chooseserialization" || keyLower === "choose") {
|
||||
resolvedKey = "chooseSerialization";
|
||||
const modeLower = val.toLowerCase();
|
||||
if (modeLower !== "frontend" && modeLower !== "pure") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `不支持的 chooseSerialization 值: ${val}。可选: frontend (默认, 与设计器产出一致, 多一个右花括号), pure (配平形态)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
partial.chooseSerialization = modeLower;
|
||||
} else {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource\n`,
|
||||
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource, chooseSerialization\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,13 +79,14 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
expect(data.sessions).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use aipro status 双向桥接成功转发", async () => {
|
||||
test("hose-use aipro status 管理本机 aipro 守护进程状态", async () => {
|
||||
const res = await runCli(["aipro", "status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
expect(data.serviceName).toBe("hose-aipro");
|
||||
expect(data.port).toBe(8889);
|
||||
expect(data.running).toBe(false);
|
||||
});
|
||||
|
||||
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import * as service from "../service.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { handleServiceCommand } from "./service.js";
|
||||
import {
|
||||
handleServiceCommand,
|
||||
handleAiProServiceCommand,
|
||||
handleApprovalRedirectCommand,
|
||||
} from "./service.js";
|
||||
|
||||
test("service lifecycle previews never dispatch process or state mutations", async () => {
|
||||
const dispatch = spyOn(service, "runServiceCommand").mockResolvedValue({ running: false } as any);
|
||||
try {
|
||||
@@ -13,5 +18,19 @@ test("service lifecycle previews never dispatch process or state mutations", asy
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
await handleServiceCommand(parseArgs(["service", "status"]), { jsonMode: true } as any);
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// hose-use aipro status
|
||||
await handleAiProServiceCommand(parseArgs(["aipro", "status"]), { jsonMode: true } as any);
|
||||
expect(dispatch).toHaveBeenCalledTimes(2);
|
||||
|
||||
// hose-use aipro bind 重定向阻断提示
|
||||
const bindRedirect = await handleAiProServiceCommand(parseArgs(["aipro", "bind", "S123"]), { jsonMode: true } as any);
|
||||
expect(bindRedirect.exitCode).toBe(1);
|
||||
expect(bindRedirect.stderr).toContain("hose-aipro");
|
||||
|
||||
// hose-use approval 重定向提示
|
||||
const approvalRedirect = await handleApprovalRedirectCommand(parseArgs(["approval", "decide", "S123"]), { jsonMode: true } as any);
|
||||
expect(approvalRedirect.exitCode).toBe(1);
|
||||
expect(approvalRedirect.stderr).toContain("hose-aipro");
|
||||
} finally { dispatch.mockRestore(); }
|
||||
});
|
||||
+100
-21
@@ -1,8 +1,14 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
|
||||
import {
|
||||
runServiceCommand,
|
||||
getHoseUseServiceConfig,
|
||||
getAiProServiceConfig,
|
||||
getPidFile,
|
||||
getLogFile,
|
||||
SERVICE_STATE_DIR,
|
||||
type ServiceConfig,
|
||||
type ServiceTargetName,
|
||||
} from "../service.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -10,13 +16,30 @@ import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
export { SERVICE_STATE_DIR };
|
||||
|
||||
export async function handleServiceCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
runtime: CliRuntime,
|
||||
forcedTarget?: ServiceTargetName
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || parsed.args[0] || "status";
|
||||
const firstPos = (parsed.action || parsed.args[0] || "").toLowerCase();
|
||||
const secondPos = (parsed.args[0] || parsed.args[1] || "").toLowerCase();
|
||||
|
||||
let target: ServiceTargetName = forcedTarget || "hose-use";
|
||||
let action = parsed.action || parsed.args[0] || "status";
|
||||
|
||||
// 支持 hose-use service aipro <start|stop|status>
|
||||
if (!forcedTarget) {
|
||||
if (firstPos === "aipro" || firstPos === "hose-aipro") {
|
||||
target = "hose-aipro";
|
||||
action = secondPos || "status";
|
||||
} else if (firstPos === "hose-use" || firstPos === "hose") {
|
||||
target = "hose-use";
|
||||
action = secondPos || "status";
|
||||
}
|
||||
}
|
||||
|
||||
const port = numberOption(parsed.options, ["port", "p"]);
|
||||
const host = stringOption(parsed.options, ["host", "h"]);
|
||||
|
||||
@@ -30,22 +53,34 @@ export async function handleServiceCommand(
|
||||
const store = new EventStore(stateFile || `corp:${corpId}`);
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "存储后端": stateFile || "SQLite (observed_events)" })}\n`, stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({
|
||||
"待办扫描": result.scanned.todo,
|
||||
"未读消息扫描": result.scanned.messages,
|
||||
"新增事件": result.newEvents.length,
|
||||
"重复事件": result.duplicateCount,
|
||||
"存储后端": stateFile || "SQLite (observed_events)",
|
||||
})}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
appRoot: runtime.appRoot || process.cwd(),
|
||||
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime.launcher,
|
||||
port,
|
||||
host,
|
||||
};
|
||||
const config: ServiceConfig =
|
||||
target === "hose-aipro"
|
||||
? getAiProServiceConfig(runtime, { port, host })
|
||||
: getHoseUseServiceConfig(runtime, { port, host });
|
||||
|
||||
if (["start", "stop", "restart", "run"].includes(action) && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "管理 hose-use 服务", action, { action, port, host, stateDir: config.stateDir });
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
`管理 ${config.serviceName} 服务`,
|
||||
action,
|
||||
{ action, port, host, stateDir: config.stateDir }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runServiceCommand(action, config);
|
||||
|
||||
if (result === undefined) {
|
||||
@@ -60,7 +95,7 @@ export async function handleServiceCommand(
|
||||
if (action === "logs" || action === "log") {
|
||||
const logsResult = result as { logFile: string; lines: string[]; content: string };
|
||||
return {
|
||||
stdout: `====== hose-use 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
|
||||
stdout: `====== ${config.serviceName} 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -73,7 +108,7 @@ export async function handleServiceCommand(
|
||||
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
|
||||
...(status.pid ? { "进程 PID": status.pid } : {}),
|
||||
...(status.url ? { "服务地址": status.url } : {}),
|
||||
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
|
||||
...(target === "hose-use" && status.url ? { "交互式文档": `${status.url}/docs` } : {}),
|
||||
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
|
||||
"运行版本": status.version || config.version,
|
||||
"状态目录": status.stateDir || config.stateDir,
|
||||
@@ -81,10 +116,54 @@ export async function handleServiceCommand(
|
||||
"日志文件": status.logFile || getLogFile(config),
|
||||
};
|
||||
|
||||
const title = (status.serviceTitle as string) || config.serviceTitle || "常驻服务管理 (Service)";
|
||||
const formatted = printKeyValue(displayPairs);
|
||||
return {
|
||||
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
|
||||
stdout: `====== ${title} ======\n${formatted}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProServiceCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = (parsed.action || parsed.args[0] || "status").toLowerCase();
|
||||
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
|
||||
|
||||
if (!serviceActions.includes(action)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] AI PRO 确定性审批仲裁命令已完全独立为 hose-aipro 命令行。\n` +
|
||||
`请直接运行: hose-aipro ${action} ${parsed.args.join(" ")}\n\n` +
|
||||
`如需管理本机的 AI PRO 网关常驻服务,请运行:\n` +
|
||||
` hose-use aipro <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
return handleServiceCommand(parsed, runtime, "hose-aipro");
|
||||
}
|
||||
|
||||
export async function handleApprovalRedirectCommand(
|
||||
parsed: CliParsedArgs,
|
||||
_runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || parsed.args[0] || "";
|
||||
const subArgs = parsed.args.slice(1).join(" ");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] 确定性审批仲裁命令已独立为 hose-aipro 命令行。\n` +
|
||||
`请直接运行: hose-aipro ${action}${subArgs ? ` ${subArgs}` : ""}\n\n` +
|
||||
`常用命令推荐:\n` +
|
||||
` • 查看要点: hose-aipro points <单号>\n` +
|
||||
` • 事实证据核验: hose-aipro review <单号> --findings='[...]'\n` +
|
||||
` • 执行审批仲裁: hose-aipro decide <单号> --apply --yes\n` +
|
||||
` • 审批日志溯源: hose-aipro logs <单号>\n` +
|
||||
` • 网关服务启停: hose-use aipro <start|stop|status>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
+97
-29
@@ -1,10 +1,15 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
EMBEDDED_SKILL_FILES,
|
||||
EMBEDDED_HOSE_USE_SKILL_FILES,
|
||||
EMBEDDED_AIPRO_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getDefaultAiProGlobalSkillDir,
|
||||
getSkillContent,
|
||||
getAiProSkillContent,
|
||||
installSkillFiles,
|
||||
installHoseUseSkillFiles,
|
||||
installAiProSkillFiles,
|
||||
} from "../../packaging/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
@@ -16,13 +21,16 @@ export async function handleSkillCommand(
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "status";
|
||||
const isAiProCaller =
|
||||
parsed.area === "hose-aipro" ||
|
||||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
|
||||
|
||||
switch (action) {
|
||||
case "dump":
|
||||
case "cat":
|
||||
case "show":
|
||||
return {
|
||||
stdout: `${getSkillContent()}\n`,
|
||||
stdout: `${isAiProCaller ? getAiProSkillContent() : getSkillContent()}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -36,30 +44,71 @@ export async function handleSkillCommand(
|
||||
const customDir =
|
||||
stringOption(parsed.options, ["dir", "target"]) || parsed.args[0];
|
||||
|
||||
const targetDir = customDir
|
||||
? customDir
|
||||
: isLocal
|
||||
? join(process.cwd(), ".agents", "skills", "hose-use")
|
||||
: getDefaultGlobalSkillDir();
|
||||
const globalHoseDir = getDefaultGlobalSkillDir();
|
||||
const globalAiProDir = getDefaultAiProGlobalSkillDir();
|
||||
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
|
||||
|
||||
const targetPolicy = customDir ? "explicit" : isLocal ? "workspace" : "global-canonical";
|
||||
const totalFiles =
|
||||
Object.keys(EMBEDDED_HOSE_USE_SKILL_FILES).length +
|
||||
Object.keys(EMBEDDED_AIPRO_SKILL_FILES).length;
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
|
||||
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
|
||||
local: isLocal,
|
||||
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
|
||||
});
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"安装 Agent Skill 文件 (hose-use 与 hose-aipro)",
|
||||
customDir || (isLocal ? `${localHoseDir} & ${localAiProDir}` : `${globalHoseDir} & ${globalAiProDir}`),
|
||||
{
|
||||
fileCount: totalFiles,
|
||||
local: isLocal,
|
||||
targetPolicy,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
}
|
||||
);
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"安装 Agent Skill 文件",
|
||||
`${isAiProCaller ? "hose-aipro" : "hose-use"} skill install${customDir ? ` --dir=${customDir}` : ""} --yes`
|
||||
);
|
||||
|
||||
const result = installSkillFiles(targetDir);
|
||||
let installedReport: { targetDirs: string[]; filesCount: number; skills: string[] };
|
||||
|
||||
if (customDir) {
|
||||
const res = installSkillFiles(customDir);
|
||||
installedReport = {
|
||||
targetDirs: [res.targetDir],
|
||||
filesCount: res.files.length,
|
||||
skills: ["hose-use"],
|
||||
};
|
||||
} else if (isLocal) {
|
||||
const hoseRes = installHoseUseSkillFiles(localHoseDir);
|
||||
const aiproRes = installAiProSkillFiles(localAiProDir);
|
||||
installedReport = {
|
||||
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
|
||||
filesCount: hoseRes.files.length + aiproRes.files.length,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
} else {
|
||||
const hoseRes = installHoseUseSkillFiles(globalHoseDir);
|
||||
const aiproRes = installAiProSkillFiles(globalAiProDir);
|
||||
installedReport = {
|
||||
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
|
||||
filesCount: hoseRes.files.length + aiproRes.files.length,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
installed: true,
|
||||
targetDir: result.targetDir,
|
||||
fileCount: result.files.length,
|
||||
files: result.files,
|
||||
targetDirs: installedReport.targetDirs,
|
||||
fileCount: installedReport.filesCount,
|
||||
skills: installedReport.skills,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
@@ -67,7 +116,10 @@ export async function handleSkillCommand(
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] hose-use 技能已成功安装至: ${result.targetDir}\n包含文件: ${result.files.join(", ")}\n`,
|
||||
stdout:
|
||||
`[SUCCESS] Agent 技能已成功安装:\n` +
|
||||
installedReport.targetDirs.map((d) => ` • ${d}`).join("\n") +
|
||||
`\n共 ${installedReport.filesCount} 个文件。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -75,17 +127,31 @@ export async function handleSkillCommand(
|
||||
|
||||
case "status":
|
||||
case "get": {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const globalHoseDir = getDefaultGlobalSkillDir();
|
||||
const globalAiProDir = getDefaultAiProGlobalSkillDir();
|
||||
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
|
||||
|
||||
const statusObj = {
|
||||
global: {
|
||||
dir: globalDir,
|
||||
installed: existsSync(join(globalDir, "SKILL.md")),
|
||||
"hose-use": {
|
||||
global: {
|
||||
dir: globalHoseDir,
|
||||
installed: existsSync(join(globalHoseDir, "SKILL.md")),
|
||||
},
|
||||
local: {
|
||||
dir: localHoseDir,
|
||||
installed: existsSync(join(localHoseDir, "SKILL.md")),
|
||||
},
|
||||
},
|
||||
local: {
|
||||
dir: localDir,
|
||||
installed: existsSync(join(localDir, "SKILL.md")),
|
||||
"hose-aipro": {
|
||||
global: {
|
||||
dir: globalAiProDir,
|
||||
installed: existsSync(join(globalAiProDir, "SKILL.md")),
|
||||
},
|
||||
local: {
|
||||
dir: localAiProDir,
|
||||
installed: existsSync(join(localAiProDir, "SKILL.md")),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -94,12 +160,14 @@ export async function handleSkillCommand(
|
||||
}
|
||||
|
||||
const output = printKeyValue({
|
||||
"全局 Skill 目录": `${globalDir} [${statusObj.global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"本地 Skill 目录": `${localDir} [${statusObj.local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-use (全局)": `${globalHoseDir} [${statusObj["hose-use"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-aipro (全局)": `${globalAiProDir} [${statusObj["hose-aipro"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-use (本地)": `${localHoseDir} [${statusObj["hose-use"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-aipro (本地)": `${localAiProDir} [${statusObj["hose-aipro"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 ${isAiProCaller ? "hose-aipro" : "hose-use"} skill install --yes 进行全局安装\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -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(); }
|
||||
});
|
||||
@@ -23,4 +23,6 @@
|
||||
|
||||
启用、发布、测试运行及 Webhook 可能产生业务副作用,沿用各子命令的预演和确认要求。`tail` 的超时、取消、快照与完成状态分别表达,不能把监听停止视为执行成功。
|
||||
|
||||
`node add` / `node edit` 保存前会跑一次**接口 → 应用**预检(`preflightNodeAppRequirements`):只看本次写入的 HTTP 节点,URL 静态路径命中 [openapi-app-requirements.ts](../../../domains/platform/workflow/analysis/openapi-app-requirements.ts) 的映射表时,去应用商店核对企业是否开通了对应应用,未开通则在输出末尾给出 ⛔ 段(JSON 模式落在 `appRequirementAlerts`)。URL 读不出静态路径或读不到企业清单时只降级提示,不阻断写入。
|
||||
|
||||
参数以 `hose-use workflow --help` 及子命令帮助为准;用户侧操作见 [workflow.md](../../../../skills/hose-use/references/workflow.md)。本目录测试和上级 `workflow*.test.ts` 覆盖入口、确认、错误及摘要契约。
|
||||
@@ -9,10 +9,9 @@ import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
import { isClientGoodOpened } from "../../../domains/store/tools.js";
|
||||
|
||||
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
|
||||
return item.status?.toUpperCase() === "OPENED";
|
||||
}
|
||||
export { isClientGoodOpened };
|
||||
|
||||
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
@@ -46,22 +45,8 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
|
||||
let openedPowerCodes: Set<string> | undefined;
|
||||
try {
|
||||
const { fetchClientGoods } = await import("../../../domains/store/tools.js");
|
||||
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
|
||||
const codes = new Set<string>();
|
||||
for (const item of goods) {
|
||||
const isOpened = isClientGoodOpened(item);
|
||||
if (isOpened && Array.isArray(item.powers)) {
|
||||
for (const power of item.powers) {
|
||||
if (typeof power === "string") {
|
||||
codes.add(power.toLowerCase());
|
||||
} else if (power && typeof power === "object" && power.powerCode) {
|
||||
codes.add(power.powerCode.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
openedPowerCodes = codes;
|
||||
const { fetchOpenedPowerCodes } = await import("../../../domains/store/tools.js");
|
||||
openedPowerCodes = await fetchOpenedPowerCodes(runtime.selectedCorp!);
|
||||
} catch (error) {
|
||||
evidenceErrors.push({ source: "openedPowerCodes", message: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
|
||||
@@ -29,13 +29,27 @@ export async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await toggleWorkflow(client, pipelineId, state);
|
||||
const label = state === 1 ? "🟢 启用" : "⚪ 停用";
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: result.verified ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 启停未回读确认时必须如实告知:不得把「请求已提交」呈现为「已生效」。
|
||||
if (!result.verified) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[WARNING] 工作流 ${pipelineId} 启停请求已提交,但${result.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`,
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${label}(已回读确认)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -55,7 +69,10 @@ export async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await toggleWorkflow(client, pipelineId, 1);
|
||||
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
const output = { success: result.verified, pipelineId, published: result.verified, state: 1, verified: result.verified, message: result.message };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.verified ? 0 : 1 };
|
||||
if (!result.verified) {
|
||||
return { stdout: "", stderr: `❌ 工作流 [${pipelineId}] 发布状态未能确认:${result.message}\n`, exitCode: 1 };
|
||||
}
|
||||
return { stdout: `✅ 工作流 [${pipelineId}] 已发布并启用(已回读确认)。\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
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 { 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";
|
||||
@@ -134,9 +134,11 @@ 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()),
|
||||
isTest,
|
||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||
});
|
||||
}
|
||||
@@ -146,6 +148,7 @@ export async function handleGrantNodes(
|
||||
const result = await grantWorkflowNodes(corp, {
|
||||
nodes: targetNodes,
|
||||
password,
|
||||
isTest,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -156,16 +159,17 @@ 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 || "处理成功",
|
||||
"Piper 反馈": result.rawMessage || "处理成功",
|
||||
}),
|
||||
"",
|
||||
"✅ 节点权限已生效!工作流设计器与 hose-use workflow analyze 将立即支持该节点。",
|
||||
|
||||
@@ -3,15 +3,87 @@ import * as services from "../../../domains/platform/workflow/services.js";
|
||||
import * as shared from "./shared.js";
|
||||
import { handleWorkflowCommand } from "./index.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||
|
||||
afterEach(() => { mock.restore(); });
|
||||
|
||||
/** 构造支持读详情与写回的假 Piper 客户端,第二次及之后的读取返回变更后的版本。 */
|
||||
function createVersionedClient(options: {
|
||||
initialDetail: any;
|
||||
detailAfterSecondRead?: any;
|
||||
refuseChooses?: boolean;
|
||||
onPut?: () => void;
|
||||
}) {
|
||||
let reads = 0;
|
||||
return {
|
||||
get: async () => {
|
||||
reads += 1;
|
||||
const payload = reads > 1 && options.detailAfterSecondRead
|
||||
? options.detailAfterSecondRead
|
||||
: options.initialDetail;
|
||||
return Response.json({ code: 200, data: payload });
|
||||
},
|
||||
put: async (url: string, opts: any) => {
|
||||
if (String(url).includes("/chooses")) {
|
||||
if (options.refuseChooses) return Response.json({ code: 500, msg: "刷新拒绝" });
|
||||
return Response.json({ code: 200, data: [] });
|
||||
}
|
||||
options.onPut?.();
|
||||
return Response.json({ code: 200, data: opts?.json ?? options.initialDetail });
|
||||
},
|
||||
} as any;
|
||||
}
|
||||
|
||||
test("节点修改在远端版本变化时不提交完整快照", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [{ name: "code", type: "code-js2", code: "return 1", groupName: "action", orderIndex: 0, levelIndex: [0], status: "active" }] } as any;
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any);
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValueOnce(detail).mockResolvedValueOnce({ ...detail, tasksVersion: 2 });
|
||||
const save = spyOn(services, "updateWorkflow").mockResolvedValue(detail);
|
||||
let putCount = 0;
|
||||
const client = createVersionedClient({
|
||||
initialDetail: detail,
|
||||
detailAfterSecondRead: { ...detail, tasksVersion: 2 },
|
||||
onPut: () => { putCount += 1; },
|
||||
});
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client } as any);
|
||||
const runtime = { selectedCorp: { id: "corp" }, jsonMode: true } as any;
|
||||
await expect(handleWorkflowCommand(parseArgs(["workflow", "node", "edit", "wf", "code", "--code=return 2", "--yes"]), runtime)).rejects.toThrow("版本已变化");
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(putCount).toBe(0);
|
||||
});
|
||||
|
||||
test("SDK 出口在未声明期望版本时不读取详情,按原语义直接保存", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
let putCount = 0;
|
||||
const client = createVersionedClient({ initialDetail: detail, onPut: () => { putCount += 1; } });
|
||||
const result = await services.updateWorkflow(client, detail);
|
||||
expect(result.id).toBe("wf");
|
||||
expect(putCount).toBe(1);
|
||||
});
|
||||
|
||||
test("SDK 出口在 expectedVersion 一致时才允许写入", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail });
|
||||
await expect(
|
||||
services.updateWorkflow(client, detail, { expectedVersion: { version: "v1", tasksVersion: 1 } })
|
||||
).resolves.toMatchObject({ id: "wf" });
|
||||
await expect(
|
||||
services.updateWorkflow(client, detail, { expectedVersion: { version: "v1", tasksVersion: 9 } })
|
||||
).rejects.toThrow("版本已变化");
|
||||
});
|
||||
|
||||
test("第三参数沿用字符串写法时仍等价于 platformId", async () => {
|
||||
let payload: any;
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail, onPut: () => {} });
|
||||
const originalPut = client.put;
|
||||
client.put = async (url: string, opts: any) => {
|
||||
if (!String(url).includes("/chooses")) payload = opts?.json;
|
||||
return originalPut(url, opts);
|
||||
};
|
||||
await services.updateWorkflow(client, detail, "platform-9");
|
||||
expect(payload.inputs).toEqual([{ key: "$platformId", value: "platform-9" }]);
|
||||
});
|
||||
|
||||
test("chooses 刷新失败时保留主保存结果的部分成功语义", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail, refuseChooses: true });
|
||||
const error = await services.updateWorkflow(client, detail).catch((err: unknown) => err);
|
||||
expect(error).toBeInstanceOf(WorkflowSavePartialError);
|
||||
});
|
||||
@@ -15,15 +15,15 @@ import { stringOption, numberOption } 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";
|
||||
import { createWorkflowDetailClient, formatWorkflowVersion } from "./shared.js";
|
||||
import { createWorkflowDetailClient, formatWorkflowVersion, resolveChooseSerialization, normalizeNodeExpressionFields, preflightNodeAppRequirements, renderAppRequirementAlerts } from "./shared.js";
|
||||
import { handleGrantNodes, handleListAvailableNodes } from "./node-catalog.js";
|
||||
|
||||
async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0], original: WorkflowDetail, updated: WorkflowDetail, platformId?: string) {
|
||||
const remote = await getWorkflowDetail(client, original.id);
|
||||
if (remote.version !== original.version || remote.tasksVersion !== original.tasksVersion) {
|
||||
throw new ValidationError(`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 读取时 tasksVersion=${original.tasksVersion}。请重新执行命令。`);
|
||||
}
|
||||
return updateWorkflow(client, updated, platformId);
|
||||
// 并发保护由 SDK 出口统一负责,避免每个调用点各写一份、或干脆忘写。
|
||||
return updateWorkflow(client, updated, {
|
||||
platformId,
|
||||
expectedVersion: { version: original.version, tasksVersion: original.tasksVersion },
|
||||
});
|
||||
}
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
@@ -89,12 +89,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,
|
||||
@@ -319,6 +320,10 @@ async function handleAddNode(
|
||||
}
|
||||
}
|
||||
|
||||
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
|
||||
const chooseMode = resolveChooseSerialization(parsed);
|
||||
normalizeNodeExpressionFields(extra, chooseMode);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -351,11 +356,15 @@ async function handleAddNode(
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
});
|
||||
|
||||
const appPreflight = await preflightNodeAppRequirements(runtime, [
|
||||
newTask as unknown as Record<string, any>,
|
||||
]);
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -372,6 +381,7 @@ async function handleAddNode(
|
||||
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
|
||||
"工作流版本": formatWorkflowVersion(saveResult),
|
||||
}),
|
||||
renderAppRequirementAlerts(appPreflight.alerts),
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
@@ -445,6 +455,10 @@ async function handleEditNode(
|
||||
}
|
||||
}
|
||||
|
||||
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
|
||||
const chooseMode = resolveChooseSerialization(parsed);
|
||||
normalizeNodeExpressionFields(customSet, chooseMode);
|
||||
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
|
||||
if (mappingFile) {
|
||||
const fs = await import("fs/promises");
|
||||
@@ -488,11 +502,15 @@ async function handleEditNode(
|
||||
});
|
||||
const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type);
|
||||
|
||||
const appPreflight = await preflightNodeAppRequirements(runtime, [
|
||||
editedTask as unknown as Record<string, any>,
|
||||
]);
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged }, runtime.outputOptions),
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -510,7 +528,7 @@ async function handleEditNode(
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}`,
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}${renderAppRequirementAlerts(appPreflight.alerts)}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
preflightNodeAppRequirements,
|
||||
renderAppRequirementAlerts,
|
||||
type NodeAppRequirementAlert,
|
||||
} from "./shared.js";
|
||||
|
||||
const BACKLOG_URL =
|
||||
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_1\"}')}]";
|
||||
|
||||
const noCorpRuntime = { selectedCorp: undefined } as any;
|
||||
|
||||
function alert(overrides: Partial<NodeAppRequirementAlert> = {}): NodeAppRequirementAlert {
|
||||
return {
|
||||
taskName: "action_pyrg",
|
||||
taskLabel: "提交审批",
|
||||
apiName: "单据审批(执行单据动作:同意 / 驳回 / 加签)",
|
||||
appName: "单据审批",
|
||||
powerCode: "TICKET_AUDIT_switch",
|
||||
productId: "o0hMBw000000g0",
|
||||
staticPath: "/api/openapi/v1/backlog/data/[",
|
||||
verified: true,
|
||||
unlicensed: true,
|
||||
message: "节点 [提交审批] (action_pyrg) 调用单据审批,但当前企业尚未开通该应用。",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("保存期应用权限预检", () => {
|
||||
it("非 HTTP 节点不触发任何检查", async () => {
|
||||
const result = await preflightNodeAppRequirements(noCorpRuntime, [
|
||||
{ name: "action_code", type: "code-js2", code: `return "${BACKLOG_URL}";` },
|
||||
]);
|
||||
expect(result.alerts).toEqual([]);
|
||||
expect(result.verifyError).toBeUndefined();
|
||||
});
|
||||
|
||||
it("URL 无法静态判断(上游节点拼接)时不产生告警", async () => {
|
||||
const result = await preflightNodeAppRequirements(noCorpRuntime, [
|
||||
{ name: "action_dyn", type: "http", method: "POST", url: "@{choose('{\"key\":\"action_prev.url\"}')}" },
|
||||
]);
|
||||
expect(result.alerts).toEqual([]);
|
||||
});
|
||||
|
||||
it("命中接口但读不到企业清单 → verified=false,且不阻断", async () => {
|
||||
const result = await preflightNodeAppRequirements(noCorpRuntime, [
|
||||
{ name: "action_pyrg", type: "http", method: "POST", url: BACKLOG_URL },
|
||||
]);
|
||||
expect(result.alerts).toHaveLength(1);
|
||||
const item = result.alerts[0]!;
|
||||
expect(item.verified).toBe(false);
|
||||
expect(item.unlicensed).toBe(false);
|
||||
expect(item.powerCode).toBe("TICKET_AUDIT_switch");
|
||||
expect(item.productId).toBe("o0hMBw000000g0");
|
||||
expect(item.staticPath).toBe("/api/openapi/v1/backlog/data/[");
|
||||
expect(item.message).toContain("未能读取企业应用清单");
|
||||
expect(result.verifyError).toContain("未选择企业");
|
||||
});
|
||||
|
||||
it("非 http 与 http 混排时只检查 http 节点", async () => {
|
||||
const result = await preflightNodeAppRequirements(noCorpRuntime, [
|
||||
{ name: "trigger", type: "webhook", url: BACKLOG_URL },
|
||||
{ name: "action_pyrg", type: "http", method: "POST", url: BACKLOG_URL },
|
||||
null,
|
||||
]);
|
||||
expect(result.alerts.map((item) => item.taskName)).toEqual(["action_pyrg"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("预检结果渲染", () => {
|
||||
it("无告警时输出空串,不污染正常输出", () => {
|
||||
expect(renderAppRequirementAlerts([])).toBe("");
|
||||
});
|
||||
|
||||
it("未开通 → ⛔ 段并带判定依据路径", () => {
|
||||
const text = renderAppRequirementAlerts([alert()]);
|
||||
expect(text).toContain("⛔ 应用权限预检未通过");
|
||||
expect(text).toContain("action_pyrg");
|
||||
expect(text).toContain("判定依据: URL 静态路径 '/api/openapi/v1/backlog/data/['");
|
||||
expect(text).not.toContain("⚠️");
|
||||
});
|
||||
|
||||
it("未核对 → ⚠️ 段,不出现 ⛔", () => {
|
||||
const text = renderAppRequirementAlerts([
|
||||
alert({ verified: false, unlicensed: false, message: "节点 [提交审批] 未能读取企业应用清单" }),
|
||||
]);
|
||||
expect(text).toContain("⚠️ 应用权限未能核对");
|
||||
expect(text).not.toContain("⛔");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,12 @@
|
||||
import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/workflow/services.js";
|
||||
import {
|
||||
DEFAULT_CHOOSE_SERIALIZATION,
|
||||
normalizeChooseTags,
|
||||
type ChooseSerialization,
|
||||
} from "../../../domains/platform/workflow/models/choose-serialization.js";
|
||||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||||
import { matchAppRequirement } from "../../../domains/platform/workflow/analysis/openapi-app-requirements.js";
|
||||
import { fetchOpenedPowerCodes } from "../../../domains/store/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
@@ -171,3 +179,152 @@ export function formatCodeNodeSummariesCard(
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ── choose 表达式序列化模式 ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 解析本轮写入使用的 choose 序列化模式。
|
||||
*
|
||||
* 优先级:命令行 --choose-serialization > 全局配置 chooseSerialization > 默认 frontend。
|
||||
*
|
||||
* 说明:该模式只影响 CLI 往服务端写入的字节形态,读取侧永远同时容忍两种形态。
|
||||
* 详细背景见 src/domains/platform/workflow/models/choose-serialization.ts 顶部注释。
|
||||
*/
|
||||
export function resolveChooseSerialization(parsed: CliParsedArgs): ChooseSerialization {
|
||||
const explicit = stringOption(parsed.options, ["choose-serialization"]);
|
||||
if (explicit === "frontend" || explicit === "pure") {
|
||||
return explicit;
|
||||
}
|
||||
return loadGlobalConfig().chooseSerialization ?? DEFAULT_CHOOSE_SERIALIZATION;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化对象中所有形如 `url` 的字段(目前只有 http 节点的 `url`),
|
||||
* 让 CLI 写出的结果与设计器保持一致。
|
||||
*/
|
||||
export function normalizeNodeExpressionFields(
|
||||
target: Record<string, any>,
|
||||
mode: ChooseSerialization
|
||||
): { changed: boolean; before?: string; after?: string } {
|
||||
if (!target || typeof target.url !== "string") return { changed: false };
|
||||
const normalized = normalizeChooseTags(target.url, mode);
|
||||
if (normalized === target.url) return { changed: false };
|
||||
const before = target.url;
|
||||
target.url = normalized;
|
||||
return { changed: true, before, after: normalized };
|
||||
}
|
||||
|
||||
// ── 保存期:接口所需企业应用的自动开通状态预检 ──────────────────────────────
|
||||
|
||||
export interface NodeAppRequirementAlert {
|
||||
taskName: string;
|
||||
taskLabel: string;
|
||||
/** 接口的人类可读名称 */
|
||||
apiName: string;
|
||||
/** 所需应用名称 */
|
||||
appName: string;
|
||||
powerCode: string;
|
||||
productId?: string;
|
||||
/** 静态路径(判断依据) */
|
||||
staticPath: string;
|
||||
/** 是否真的读到了企业应用清单 */
|
||||
verified: boolean;
|
||||
/** 已核对且确认未开通 */
|
||||
unlicensed: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存节点时的权限预检:只看**本次写入的节点**,命中已知「接口 → 应用」映射时
|
||||
* 去应用商店核对企业是否已开通。
|
||||
*
|
||||
* 边界(与静态分析保持一致):
|
||||
* - 只处理 http 节点;
|
||||
* - URL 读不出静态路径(整体由上游节点变量拼接)时直接跳过,不猜测;
|
||||
* - 读不到企业应用清单时降级为「无法确认」,不阻断保存。
|
||||
*
|
||||
* 读清单失败不会抛错,也不会卡住写入 —— 这是提示性检查,不是门禁。
|
||||
*/
|
||||
export async function preflightNodeAppRequirements(
|
||||
runtime: CliRuntime,
|
||||
tasks: Array<Record<string, any> | undefined | null>
|
||||
): Promise<{ alerts: NodeAppRequirementAlert[]; verifyError?: string }> {
|
||||
const candidates: Array<{
|
||||
task: Record<string, any>;
|
||||
matched: NonNullable<ReturnType<typeof matchAppRequirement>>;
|
||||
}> = [];
|
||||
|
||||
for (const task of tasks) {
|
||||
if (!task || typeof task !== "object") continue;
|
||||
if (String(task.type || "").trim().toLowerCase() !== "http") continue;
|
||||
const matched = matchAppRequirement(task.url, task.method);
|
||||
if (matched) candidates.push({ task, matched });
|
||||
}
|
||||
if (!candidates.length) return { alerts: [] };
|
||||
|
||||
let opened: Set<string> | undefined;
|
||||
let verifyError: string | undefined;
|
||||
try {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("当前未选择企业");
|
||||
opened = await fetchOpenedPowerCodes(corp);
|
||||
} catch (error) {
|
||||
verifyError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
const alerts = candidates.map(({ task, matched }) => {
|
||||
const { requirement, staticPath } = matched;
|
||||
const verified = opened !== undefined;
|
||||
const unlicensed = verified && !opened!.has(requirement.powerCode.trim().toLowerCase());
|
||||
const taskName = String(task.name || "");
|
||||
const taskLabel = String(task.label || task.displayName || "");
|
||||
const where = requirement.productId
|
||||
? `「${requirement.appName}」(productId=${requirement.productId})`
|
||||
: `「${requirement.appName}」`;
|
||||
const head = `节点 [${taskLabel || taskName}] (${taskName}) 调用 ${requirement.apiName},需要应用${where},powerCode=${requirement.powerCode}`;
|
||||
|
||||
const message = !verified
|
||||
? `${head};未能读取企业应用清单(${verifyError}),请自行到应用商店确认已开通,否则运行时会返回 403。`
|
||||
: unlicensed
|
||||
? `${head},但当前企业尚未开通该应用。流程跑到这个节点必然返回 403「未开通功能,无权访问」,请先到应用商店开通再发布。`
|
||||
: `${head},企业已开通 ✅`;
|
||||
|
||||
return {
|
||||
taskName,
|
||||
taskLabel,
|
||||
apiName: requirement.apiName,
|
||||
appName: requirement.appName,
|
||||
powerCode: requirement.powerCode,
|
||||
productId: requirement.productId,
|
||||
staticPath,
|
||||
verified,
|
||||
unlicensed,
|
||||
message,
|
||||
};
|
||||
});
|
||||
|
||||
return { alerts, verifyError };
|
||||
}
|
||||
|
||||
/** 把预检结果渲染成命令行提示块;无告警时返回空串。 */
|
||||
export function renderAppRequirementAlerts(alerts: NodeAppRequirementAlert[]): string {
|
||||
if (!alerts.length) return "";
|
||||
const lines: string[] = [];
|
||||
const blocked = alerts.filter((a) => a.unlicensed);
|
||||
if (blocked.length) {
|
||||
lines.push("");
|
||||
lines.push("⛔ 应用权限预检未通过(发布后运行到这里必然 403):");
|
||||
for (const alert of blocked) {
|
||||
lines.push(` • ${alert.message}`);
|
||||
lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`);
|
||||
}
|
||||
}
|
||||
const unknown = alerts.filter((a) => !a.verified);
|
||||
for (const alert of unknown) {
|
||||
lines.push("");
|
||||
lines.push(`⚠️ 应用权限未能核对:${alert.message}`);
|
||||
lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
+7
-1
@@ -53,7 +53,13 @@ export function mutationPreview(
|
||||
changes: Record<string, unknown>
|
||||
): CliResult {
|
||||
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
|
||||
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
|
||||
const isAiPro = confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "aipro";
|
||||
const binaryPrefix = isAiPro ? "hose-aipro" : "hose-use";
|
||||
const cleanArgs =
|
||||
confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "hose-use" || confirmedArgs[0] === "aipro"
|
||||
? confirmedArgs.slice(1)
|
||||
: confirmedArgs;
|
||||
const nextAction = `${binaryPrefix} ${cleanArgs.join(" ")} --yes`;
|
||||
const payload = {
|
||||
dryRun: true,
|
||||
operation,
|
||||
|
||||
+1
-1
@@ -229,7 +229,7 @@ ${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${to
|
||||
|
||||
常用示例:
|
||||
hose-use context # 一键查看全局运行上下文与身份诊断 (免读源码)
|
||||
hose-use aipro status # 查看 AI PRO 审批网关状态与当前连接企业
|
||||
hose-aipro status # 查看 AI PRO 审批网关状态与当前连接企业
|
||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看当前登录状态与活跃企业
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
|
||||
+14
-9
@@ -13,7 +13,11 @@ import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill/index.js";
|
||||
import { handleFlowCommand } from "./commands/flow.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import {
|
||||
handleServiceCommand,
|
||||
handleAiProServiceCommand,
|
||||
handleApprovalRedirectCommand,
|
||||
} from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
@@ -21,7 +25,6 @@ import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
@@ -30,6 +33,8 @@ import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export * from "./aipro-registry.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
@@ -51,12 +56,12 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "aipro",
|
||||
...COMMAND_METADATA.aipro,
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return runAiProCli(subArgs);
|
||||
},
|
||||
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "hose-aipro",
|
||||
...COMMAND_METADATA["hose-aipro"],
|
||||
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
@@ -126,7 +131,7 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "approval",
|
||||
...COMMAND_METADATA.approval,
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
handler: (parsed, runtime) => handleApprovalRedirectCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
|
||||
+116
-19
@@ -1,9 +1,24 @@
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
|
||||
import { homedir } from "node:os";
|
||||
import {
|
||||
startHttpServer,
|
||||
DEFAULT_HTTP_PORT,
|
||||
DEFAULT_AIPRO_HTTP_PORT,
|
||||
DEFAULT_HTTP_HOST,
|
||||
} from "../http/server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
export type ServiceTargetName = "hose-use" | "hose-aipro";
|
||||
|
||||
export const SERVICE_STATE_DIR =
|
||||
process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
export type ServiceConfig = {
|
||||
serviceName?: ServiceTargetName;
|
||||
serviceTitle?: string;
|
||||
appRoot: string;
|
||||
entryFile: string;
|
||||
stateDir: string;
|
||||
@@ -14,13 +29,56 @@ export type ServiceConfig = {
|
||||
};
|
||||
port?: number;
|
||||
host?: string;
|
||||
pidFileName?: string;
|
||||
logFileName?: string;
|
||||
};
|
||||
|
||||
export function getHoseUseServiceConfig(
|
||||
runtime?: Partial<CliRuntime>,
|
||||
options?: { port?: number; host?: string }
|
||||
): ServiceConfig {
|
||||
const appRoot = runtime?.appRoot || process.cwd();
|
||||
return {
|
||||
serviceName: "hose-use",
|
||||
serviceTitle: "hose-use 常驻服务管理 (Service)",
|
||||
appRoot,
|
||||
entryFile: runtime?.entryFile || join(appRoot, "src", "cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime?.launcher,
|
||||
port: options?.port,
|
||||
host: options?.host,
|
||||
pidFileName: "service.pid",
|
||||
logFileName: "service.log",
|
||||
};
|
||||
}
|
||||
|
||||
export function getAiProServiceConfig(
|
||||
runtime?: Partial<CliRuntime>,
|
||||
options?: { port?: number; host?: string }
|
||||
): ServiceConfig {
|
||||
const appRoot = runtime?.appRoot || process.cwd();
|
||||
return {
|
||||
serviceName: "hose-aipro",
|
||||
serviceTitle: "hose-aipro 审批网关常驻服务 (Service)",
|
||||
appRoot,
|
||||
entryFile: join(appRoot, "src", "aipro-cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime?.launcher,
|
||||
port: options?.port,
|
||||
host: options?.host,
|
||||
pidFileName: "aipro-service.pid",
|
||||
logFileName: "aipro-service.log",
|
||||
};
|
||||
}
|
||||
|
||||
export async function runServiceCommand(
|
||||
action: string | undefined,
|
||||
config: ServiceConfig,
|
||||
options: { quiet?: boolean } = {}
|
||||
) {
|
||||
const targetLabel = config.serviceName || "hose-use";
|
||||
switch (action) {
|
||||
case "run":
|
||||
await runService(config);
|
||||
@@ -39,24 +97,32 @@ export async function runServiceCommand(
|
||||
case undefined:
|
||||
return serviceStatus(config);
|
||||
default:
|
||||
throw new Error("用法: hose-use service <start|stop|restart|status|logs|poll>");
|
||||
throw new Error(`用法: ${targetLabel} service <start|stop|restart|status|logs|poll>`);
|
||||
}
|
||||
}
|
||||
|
||||
export function serviceStatus(config: ServiceConfig) {
|
||||
const pidFile = getPidFile(config);
|
||||
const pid = readServicePid(pidFile);
|
||||
const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false;
|
||||
const running = pid ? isHoseServiceProcess(pid, config.appRoot, config.serviceName) : false;
|
||||
|
||||
if (pid && !running) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = config.serviceName === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
return {
|
||||
running,
|
||||
serviceName: config.serviceName || "hose-use",
|
||||
serviceTitle:
|
||||
config.serviceTitle ||
|
||||
(isAiPro
|
||||
? "hose-aipro 审批网关常驻服务 (Service)"
|
||||
: "hose-use 常驻服务管理 (Service)"),
|
||||
pid: running ? pid : undefined,
|
||||
version: config.version,
|
||||
port,
|
||||
@@ -75,17 +141,24 @@ async function runService(config: ServiceConfig) {
|
||||
ensureStateDir(config.stateDir);
|
||||
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
||||
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = config.serviceName === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service starting on http://${host}:${port} pid=${process.pid}`);
|
||||
|
||||
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
|
||||
try {
|
||||
server = await startHttpServer({ port, host, silent: true });
|
||||
appendLog(logFile, `service listening pid=${process.pid}`);
|
||||
server = await startHttpServer({
|
||||
port,
|
||||
host,
|
||||
silent: true,
|
||||
app: isAiPro ? "hose-aipro" : "hose-use",
|
||||
});
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service listening pid=${process.pid}`);
|
||||
} catch (err: unknown) {
|
||||
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
if (readServicePid(pidFile) === process.pid) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
@@ -100,7 +173,7 @@ async function runService(config: ServiceConfig) {
|
||||
if (readServicePid(pidFile) === process.pid) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
appendLog(logFile, `service stopped pid=${process.pid}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service stopped pid=${process.pid}`);
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
@@ -140,14 +213,14 @@ function startService(config: ServiceConfig) {
|
||||
|
||||
const pidFile = getPidFile(config);
|
||||
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
|
||||
appendLog(getLogFile(config), `service started pid=${child.pid}`);
|
||||
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service started pid=${child.pid}`);
|
||||
return { started: true, ...serviceStatus(config) };
|
||||
}
|
||||
|
||||
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
||||
const pidFile = getPidFile(config);
|
||||
const pid = readServicePid(pidFile);
|
||||
if (!pid || !isHoseServiceProcess(pid, config.appRoot)) {
|
||||
if (!pid || !isHoseServiceProcess(pid, config.appRoot, config.serviceName)) {
|
||||
rmSync(pidFile, { force: true });
|
||||
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
|
||||
}
|
||||
@@ -158,7 +231,7 @@ function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
||||
// ignore
|
||||
}
|
||||
rmSync(pidFile, { force: true });
|
||||
appendLog(getLogFile(config), `service stop requested pid=${pid}`);
|
||||
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service stop requested pid=${pid}`);
|
||||
return options.quiet ? undefined : { stopped: true, pid };
|
||||
}
|
||||
|
||||
@@ -176,16 +249,34 @@ function readServiceLogs(config: ServiceConfig, maxLines = 50) {
|
||||
};
|
||||
}
|
||||
|
||||
export function isHoseServiceProcess(pid: number, appRoot: string): boolean {
|
||||
export function isHoseServiceProcess(
|
||||
pid: number,
|
||||
appRoot: string,
|
||||
targetName?: ServiceTargetName
|
||||
): boolean {
|
||||
if (!isProcessRunning(pid)) return false;
|
||||
|
||||
try {
|
||||
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
||||
const matchesTarget =
|
||||
const isRun = command.includes("service") && command.includes("run");
|
||||
if (!isRun) return false;
|
||||
|
||||
if (targetName === "hose-aipro") {
|
||||
return command.includes("hose-aipro") || command.includes("aipro-cli");
|
||||
}
|
||||
if (targetName === "hose-use") {
|
||||
return (
|
||||
(command.includes("hose-use") || command.includes("src/cli.ts") || command.includes(appRoot)) &&
|
||||
!command.includes("hose-aipro") &&
|
||||
!command.includes("aipro-cli")
|
||||
);
|
||||
}
|
||||
return (
|
||||
command.includes(appRoot) ||
|
||||
command.includes("hose-use") ||
|
||||
command.includes("src/cli.ts");
|
||||
return matchesTarget && command.includes("service") && command.includes("run");
|
||||
command.includes("src/cli.ts") ||
|
||||
command.includes("hose-aipro")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -201,11 +292,17 @@ function isProcessRunning(pid: number): boolean {
|
||||
}
|
||||
|
||||
export function getPidFile(config: ServiceConfig): string {
|
||||
return join(config.stateDir, "service.pid");
|
||||
const fileName =
|
||||
config.pidFileName ||
|
||||
(config.serviceName === "hose-aipro" ? "aipro-service.pid" : "service.pid");
|
||||
return join(config.stateDir, fileName);
|
||||
}
|
||||
|
||||
export function getLogFile(config: ServiceConfig): string {
|
||||
return join(config.stateDir, "service.log");
|
||||
const fileName =
|
||||
config.logFileName ||
|
||||
(config.serviceName === "hose-aipro" ? "aipro-service.log" : "service.log");
|
||||
return join(config.stateDir, fileName);
|
||||
}
|
||||
|
||||
export function readServicePid(path: string): number | undefined {
|
||||
|
||||
@@ -190,6 +190,18 @@ export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
|
||||
|
||||
// ── 全局运行配置(有状态/无状态模式)─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* CLI 写出的 `@{choose('…')}` 表达式形态。
|
||||
*
|
||||
* - `frontend`(默认):百分百模拟合思设计器产出,choose 参数里的 JSON 会多一个右花括号。
|
||||
* 这是平台的稳定输出形态,引擎侧完全兼容(见 docs/合思前端-表达式序列化缺陷-2026-11-04.md)。
|
||||
* - `pure`:写出配平形态,JSON 合法;代价是 UI 下次保存会改回 `frontend` 形态。
|
||||
*
|
||||
* 该配置只影响「CLI 往服务端写什么」,读取侧永远同时容忍两种形态。
|
||||
*/
|
||||
export const ChooseSerializationSchema = z.enum(["frontend", "pure"]);
|
||||
export type ChooseSerialization = z.infer<typeof ChooseSerializationSchema>;
|
||||
|
||||
export const GlobalConfigSchema = z.object({
|
||||
stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),
|
||||
defaultCorpId: z.string().optional().describe("默认工作企业 ID"),
|
||||
@@ -197,6 +209,9 @@ export const GlobalConfigSchema = z.object({
|
||||
testEnterprisesDir: z.string().min(1).optional().describe("测试/自定义企业目录(仅用于开发测试重载,优先于全局用户目录)"),
|
||||
updateRepo: z.string().optional().describe("默认自更新的 GitHub 仓库 (owner/repo)"),
|
||||
updateSource: z.enum(["auto", "github", "gitea"]).optional().default("auto").describe("默认自更新源通道偏好 (auto/github/gitea)"),
|
||||
chooseSerialization: ChooseSerializationSchema.optional()
|
||||
.default("frontend")
|
||||
.describe("choose 表达式序列化形态: frontend(默认, 与设计器产出完全一致, 多一个右花括号) / pure(配平形态)"),
|
||||
});
|
||||
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
@@ -216,6 +216,32 @@ export const migrations: DatabaseMigration[] = [
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 4,
|
||||
name: "004_approval_runs_unique_short_id",
|
||||
up(db: Database): void {
|
||||
// 存量纠偏:历史短 ID 若发生大小写不敏感碰撞,仅保留每组最新一条,其余置空
|
||||
// (被置空的记录仍可通过 UUID / 单号定位,不影响既有会话)
|
||||
db.run(`
|
||||
UPDATE approval_runs
|
||||
SET short_id = NULL
|
||||
WHERE short_id IS NOT NULL
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (
|
||||
PARTITION BY UPPER(short_id) ORDER BY created_at DESC, id DESC
|
||||
) AS rn
|
||||
FROM approval_runs
|
||||
WHERE short_id IS NOT NULL
|
||||
) WHERE rn = 1
|
||||
);
|
||||
`);
|
||||
// short_id 必须大小写不敏感全局唯一,杜绝碰撞导致按短 ID 取错审批会话
|
||||
db.run(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_short_id_unique ON approval_runs(UPPER(short_id)) WHERE short_id IS NOT NULL;"
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -298,9 +298,25 @@ export class ApprovalRepository {
|
||||
|
||||
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
|
||||
|
||||
/**
|
||||
* 生成库内唯一的 6 位短 ID。
|
||||
* 迁移层已用 UPPER(short_id) 唯一索引兜底,这里再显式探测重试,
|
||||
* 避免极小概率碰撞直接把会话写到同一个短 ID 上。
|
||||
*/
|
||||
private allocateUniqueShortId(maxAttempts = 20): string {
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
const candidate = generateShortRunId();
|
||||
const hit = this.db
|
||||
.query("SELECT 1 FROM approval_runs WHERE UPPER(short_id) = UPPER(?) LIMIT 1")
|
||||
.get(candidate);
|
||||
if (!hit) return candidate;
|
||||
}
|
||||
throw new BusinessError("生成唯一审批会话短 ID 失败(连续碰撞),请稍后重试");
|
||||
}
|
||||
|
||||
public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const shortId = input.shortId ?? generateShortRunId();
|
||||
const shortId = input.shortId ?? this.allocateUniqueShortId();
|
||||
const now = Date.now();
|
||||
const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期
|
||||
|
||||
@@ -335,28 +351,31 @@ export class ApprovalRepository {
|
||||
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
|
||||
const now = Date.now();
|
||||
if (existing) {
|
||||
// 清理旧要点,重置运行记录
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
// 清理旧要点与重置运行记录必须原子完成,避免删了旧要点却没更新主记录
|
||||
const reset = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET expires_at = ?, flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
});
|
||||
reset();
|
||||
return this.getRunById(existing.id)!;
|
||||
}
|
||||
|
||||
@@ -491,39 +510,44 @@ export class ApprovalRepository {
|
||||
throw new NotFoundError(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
// 校验必须在事务外先行完成:任何非法状态都不应触发旧要点被删除
|
||||
for (const finding of findings) {
|
||||
if (!isValidFindingCheckStatus(finding.checkStatus ?? "PENDING")) throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
}
|
||||
|
||||
// 重新挂载时清空旧要点
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const now = Date.now();
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
const id = crypto.randomUUID();
|
||||
insertStmt.run(
|
||||
id,
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
// 清空旧要点 + 批量写入 + 回写计数必须原子完成,避免中途失败留下半残清单
|
||||
const persist = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
insertStmt.run(
|
||||
crypto.randomUUID(),
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
);
|
||||
}
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
persist();
|
||||
|
||||
return this.getFindingsByRunId(runId);
|
||||
}
|
||||
|
||||
@@ -91,8 +91,16 @@ export class ApprovalService {
|
||||
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
|
||||
}
|
||||
|
||||
// 默认回退至第一个场景
|
||||
matchedSummary = matchedSummary ?? allScopes[0];
|
||||
// 严禁静默回退到首个场景:用错规则集审单据(如差旅规则审办公费)比直接报错危险得多
|
||||
if (!matchedSummary) {
|
||||
const available = allScopes.map((s) => s.scope).join("、");
|
||||
if (options.scope !== undefined) {
|
||||
throw new NotFoundError(`指定场景 [${options.scope}] 不存在或无效,当前可用场景: ${available}`);
|
||||
}
|
||||
throw new ValidationError(
|
||||
`无法为单据 [${documentSn}] 自动匹配适用场景,请通过 --scope 显式指定。当前可用场景: ${available}`
|
||||
);
|
||||
}
|
||||
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
|
||||
}
|
||||
|
||||
@@ -181,7 +189,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
|
||||
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -225,7 +233,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点。`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
|
||||
|
||||
`workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。
|
||||
|
||||
启停(`toggle` / `publish`)属于生产开关:写请求按 EASO 业务码判定成败(HTTP 200 不代表成功),写成功后再回读详情确认 `state` 确实变化。回读状态与期望不一致抛 `BusinessError`(`WORKFLOW_STATE_NOT_APPLIED`);回读失败返回 `verified: false` 并给出非零退出码,不把「请求已提交」说成「已生效」。返回的 `WorkflowToggleResult` 中 `state` 为 `null` 表示未能读到服务端实际状态。
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
@@ -28,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]
|
||||
@@ -167,7 +169,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。
|
||||
|
||||
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。
|
||||
灰度节点开通以 Piper 响应中的业务 `code` 判定结果;非 200 业务码时 CLI 保留失败详情并返回非零退出码,HTTP 200 本身不会被视为成功。这样可以避免开通未生效却误报成功、下游仍报 `PERMISSION_MISSING_NODE` 的情况。
|
||||
|
||||
灰度节点开通不再依赖第三方网关: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。
|
||||
|
||||
@@ -181,6 +185,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\":\"实际费用类型名称\"}')}"}`。分析器提供以下软提示,不改写工作流、不查询或猜测显示名称:
|
||||
|
||||
| 诊断码 | 检查范围 |
|
||||
@@ -194,7 +200,7 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
动态表达式和其他筛选运算符不套用费用类型固定选择器规则;这不是完整表达式语法验证。批次大小未提供时保留服务端行为,不补默认值。节点摘要同时展示循环范围、顺序/并行和已配置批次大小,便于发现回读版本中的执行方式变化。业务金额、明细聚合和空列表处理的操作规范见 [工作流参考 §20](../../../../skills/hose-use/references/workflow.md#20-原生循环筛选选择器与费用明细)。
|
||||
|
||||
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
||||
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
|
||||
2. **开放接口所需应用核验 (`UNLICENSED_POWER_CODE` / `POWER_CODE_DEPENDENCY`)**:按 HTTP 节点 URL 的**静态路径**反查所需企业应用(映射表见 [analysis/openapi-app-requirements.ts](./analysis/openapi-app-requirements.ts),如 `/api/openapi/v1/backlog/data/` → 「单据审批」应用 `TICKET_AUDIT_switch`),与企业已开通应用交叉核验,未开通时产生硬门禁阻断,并在报文里带上应用名、productId 与判定依据路径;无法取得已开通清单时降级为软建议。**判定边界**:只对 HTTP 节点生效;URL 若整体由上游节点变量拼接(以 `@{...}` 开头)则完全不判断,宁可漏报不误报;节点显式声明的 `powerCode`(`params` 或 URL query)优先于路径反查。URL 参数含无效百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,并跳过该节点的后续权限判断;
|
||||
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
|
||||
4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。
|
||||
|
||||
@@ -224,10 +230,10 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
| [script](./script/README.script.md) | 代码节点的 JavaScript/MVEL 静态检查及本地沙箱求值 |
|
||||
| [branch](./branch/index.ts) | 根据执行记录解释条件规则及分支命中情况,证据不足时保留未知结果 |
|
||||
| [watch](./watch/README.watch.md) | 轮询工作流与 Job,跟踪节点变化并区分完成、超时和取消 |
|
||||
| [alert](./alert/index.ts) | 保存错误指纹,识别新增或变化的错误,避免重复提醒 |
|
||||
| [alert](./alert/index.ts) | 保存错误指纹,识别新增或变化的错误,避免重复提醒;SQLite 是唯一事实来源,JSON 副本导出失败会以 `exportError` 呈现而不中断巡检 |
|
||||
| [state](./state/index.ts) | 本地草稿路径补丁、状态及版本冲突判断 |
|
||||
|
||||
节点写入提交前会重新读取并比较 `version` 和 `tasksVersion`;这是一项客户端检查,不是原子条件写入,检查与提交间仍存在并发窗口。
|
||||
写入并发保护由 SDK 出口 `updateWorkflow` 提供:调用方传入 `expectedVersion: { version, tasksVersion }` 时,会在提交前重新读取远端并比较 `version` 与 `tasksVersion`,不一致抛 `ValidationError`(`WORKFLOW_VERSION_CONFLICT`)。这是一项客户端检查,不是原子条件写入,检查与提交之间仍存在并发窗口;不传期望值时按既有语义直接保存。CLI 的节点写入命令统一走这条路径,不再在命令层各自重读。
|
||||
|
||||
内部实现直接导入所属模块,不反向导入 services 门面。watch 的 tracker 使用 execution,工作流报告类型直接引用 branch/types,避免通过聚合出口形成循环。跨应用查询只通过 applications 的公开业务服务取得应用;各子模块禁止绕过服务直接调用兄弟模块 api。
|
||||
|
||||
@@ -235,3 +241,111 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
## 空历史快照兼容
|
||||
|
||||
Piper 对没有快照的新工作流可能返回 `items: null`。快照列表 API 将该字段归一化为 `[]`,保留分页数据;其他错误类型、无效条目、空详情及业务错误仍拒绝。该兼容仅在传输层处理,不改变工作流结构导出的模型。
|
||||
|
||||
## HTTP 节点「请求 URL」的表达式形态(必读,避免误判)
|
||||
|
||||
合思设计器的「请求 URL」字段是富文本,同一份内容在服务端存两份:
|
||||
|
||||
| 位置 | 形态 | 谁在用 |
|
||||
|---|---|---|
|
||||
| `tasks[i].url` | 扁平字符串 | **运行时只认这一份** |
|
||||
| `$snapshot` 中的 `tasks[i].url-snapshot` | 富文本模型(`text` / `context-tag` / `text` 三段) | 设计器渲染 |
|
||||
|
||||
正常形态是「静态文本 + 变量 + 静态文本」三段,序列化后形如:
|
||||
|
||||
```
|
||||
https://<企业域名>/api/openapi/v1/backlog/data/[@{choose('{"key":"action_xxx","properties":[{"key":"id","label":"单据ID","type":"TEXT"}],"label":"查询单据详情.单据ID"}}')}]
|
||||
```
|
||||
|
||||
### 坑 1:折叠态是摘要,不是内容
|
||||
|
||||
设计器折叠时只渲染摘要:字段是纯变量 → 显示变量 label(如「第3步:查询单据详情_单据ID」);字段是文本+变量混排 → 显示「自定义表达式」。
|
||||
|
||||
**因此两个环境可能显示完全一样,但底层数据一个是完整 URL、一个是裸变量。** 判断配置对错只能读 `tasks[i].url`,不能看设计器截图。
|
||||
|
||||
### 坑 2:`choose()` 参数里的 JSON 会多一个 `}`
|
||||
|
||||
设计器保存(以及人工按 UI 习惯填写)会把 `choose('…')` 内部的 JSON 写成 `{` / `}` 不配平,即上文示例中 `"label":"查询单据详情.单据ID"}}` 这一处。
|
||||
|
||||
这是平台的稳定行为,CSM 等多个租户的多个工作流均如此,**属于平台统一形态,不要把它当脏数据「修正」**:
|
||||
|
||||
- 把它改成配平形态会让配置与设计器产出不一致,任何人再点一次「保存」又会写回不配平形态;
|
||||
- 历史上曾据此误判为「序列化 bug」并改回配平形态,属于错误结论,勿重蹈。
|
||||
|
||||
#### 为什么引擎能跑:实测证据(2026-11-04)
|
||||
|
||||
在 HAB 对公测试环境用临时流程(`webhook → http × 3`)做过三组对照,`choose()` 均引用不存在的动作(求值为空串),只改形态:
|
||||
|
||||
| 组 | `url` 原文 | 引擎求值结果(节点日志 `http请求:` 实录) | 结果 |
|
||||
|---|---|---|---|
|
||||
| A | `…/double-@{choose('…}}')}` | `…/double-` | ✅ COMPLETED |
|
||||
| B | `…/single-@{choose('…}')}` | `…/single-` | ✅ COMPLETED |
|
||||
| C | `…/pre-@{choose('…}}')}/post-tail` | `…/pre-/post-tail` | ✅ COMPLETED |
|
||||
|
||||
C 组与本节的真实形态同构(表达式后面还有静态后缀),前后缀均完整保留,多出的 `}` 不吞任何字符。
|
||||
|
||||
后端解析器的行为也有直接证据:把 `properties[0].type` 误写成小写 `"string"` 时,Jackson 抛的是枚举值错误,异常信息里贴出了它收到的原始字符串:
|
||||
|
||||
```
|
||||
Cannot deserialize value of type `com.hosecloud.hab.enums.DynamicType` from String "string"
|
||||
at [Source: (String)"{…"label":"单据ID"}}"; line: 1, column: 71]
|
||||
(through reference chain: …ExpressionField["properties"]->…LabeledValue["type"])
|
||||
```
|
||||
|
||||
注意尾部 `}}` 就在 `at [Source: (String)"…"` 里,而**后端没有报 JSON 语法错误**,还精确解析到了 `properties[0].type` —— 说明 Jackson 的 `FAIL_ON_TRAILING_TOKENS` 是默认关闭的,尾随 `}` 被静默忽略。**能跑不是巧合,是序列化宽松策略兜住了。**
|
||||
|
||||
完整缺陷分析与前端源码定位见 `docs/合思前端-表达式序列化缺陷-2026-11-04.md`。
|
||||
|
||||
#### CLI 写入形态开关 `chooseSerialization`
|
||||
|
||||
CLI 通过 `node add` / `node edit` 写 `url` 时会归一如上的 choose 标签,模式由配置项控制:
|
||||
|
||||
| 模式 | 写出形态 | 说明 |
|
||||
|---|---|---|
|
||||
| `frontend`(**默认**) | `@{choose('{"k":"v"}}')}` | 百分百模拟设计器产出,避免「CLI 改完 → 人去 UI 点保存 → 形态漂移」 |
|
||||
| `pure` | `@{choose('{"k":"v"}')}` | 配平形态,JSON 合法;UI 下次保存会改回 `frontend` |
|
||||
|
||||
```bash
|
||||
hose-use config set chooseSerialization frontend --yes # 全局(默认)
|
||||
hose-use workflow node edit <id> <node> --choose-serialization=pure --set='url=…' --yes # 单次覆盖
|
||||
```
|
||||
|
||||
**开关只影响写入字节,读取侧永远同时容忍两种形态。** 无法解析成 JSON 的旧式载荷(如 `@{choose('body.details')}`)原样保留,不做猜测性改写。
|
||||
|
||||
判断 URL 是否被写坏,看这三个条件就够了,不要以「JSON 是否合法」作为唯一判据:
|
||||
|
||||
1. 以 `https://` 开头(缺了前缀是真正的坏形态);
|
||||
2. 变量段 `@{choose(...)}` 完整;
|
||||
3. 以 `]` 结尾。
|
||||
|
||||
### 真正的坏形态与报错
|
||||
|
||||
`url` 只剩 `@{choose(...)}`、静态前缀整段缺失时,运行时渲染成裸 ID,报:
|
||||
|
||||
```
|
||||
URI不合法: no protocol: ID01XzW4ovYvpl
|
||||
```
|
||||
|
||||
顺带记住:**这句报错本身就是「引擎能解析 `}}` 形态」的旁证** —— 报错里出现的是字段值 `ID01XzW4ovYvpl`,不是原始的 `@{choose('…')}` 文本。如果引擎解析不了,报错里贴的会是原文。所以看到这个错,去查前缀,别去查花括号。
|
||||
|
||||
### 直连 URL 必须使用企业自己的域名
|
||||
|
||||
设计器里的绝对 URL 走企业所在集群,不能跨租户照抄。集群映射以本地企业配置的 `baseUrl` 为准(如 `app.ekuaibao.com`、`wx2.ekuaibao.com`、`dd2.hosecloud.com`、`<企业>.hosecloud.com`)。
|
||||
|
||||
### 校验命令
|
||||
|
||||
```bash
|
||||
hose-use --corp=<企业ID> workflow get <pipelineId> --json \
|
||||
| jq -r '[.. | objects | select(.type?=="http")] | .[] | "\(.name)\t\(.url)"'
|
||||
```
|
||||
|
||||
### 坑 3:只改 `url` 字段,设计器会显示为空
|
||||
|
||||
`workflow node edit --set=url=...` 只写扁平的 `tasks[i].url`,**不会同步 `url-snapshot` 富文本**。而设计器渲染读的是 `url-snapshot`:
|
||||
|
||||
- 流程有 `url-snapshot` 条目 → 设计器正常显示(显示内容以快照为准)
|
||||
- 流程**没有**该条目(`$snapshot` 为空数组) → 设计器渲染为空,URL 框显示占位符「请输入 url」,但运行时仍按 `url` 执行
|
||||
|
||||
已有流程若 `$snapshot` 为空(例如由 CLI 复制/创建产生),需要用全量保存补齐快照条目:读取 `workflow get --json`、在 `$snapshot` 中按 `<taskPath>.url-snapshot` 追加富文本模型,再 `workflow save --file=<json> --yes`。
|
||||
|
||||
富文本模型形如:`root → paragraph → [text, context-tag(choose), text]`,三段的拼接结果必须等同于 `url` 字段。
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync, chmodSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Database } from "bun:sqlite";
|
||||
import { runMigrations } from "../../../../core/db/index.js";
|
||||
import { WorkflowAlertStore, type WorkflowErrorAlert } from "./index.js";
|
||||
|
||||
/**
|
||||
* 错误指纹的持久化行为。此前这些用例写在 state/index.test.ts 里(模块归属错位),
|
||||
* 改 alert 时容易被漏跑,这里连同新增的导出失败路径一起收拢。
|
||||
*/
|
||||
function createStore(): { store: WorkflowAlertStore; cleanup: () => void; file: string } {
|
||||
const dir = mkdtempSync("hose-alert-store-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const dbPath = join(dir, "state.db");
|
||||
const db = new Database(dbPath);
|
||||
runMigrations(db);
|
||||
const store = new WorkflowAlertStore(file, db);
|
||||
return { store, file, cleanup: () => { db.close(); rmSync(dir, { recursive: true, force: true }); } };
|
||||
}
|
||||
|
||||
const alert = (overrides: Partial<WorkflowErrorAlert> = {}): WorkflowErrorAlert => ({
|
||||
id: "corp:platform:wf-1",
|
||||
pipelineId: "wf-1",
|
||||
platformId: "platform-1",
|
||||
pipelineName: "测试流程",
|
||||
errorCount: 1,
|
||||
state: 0,
|
||||
observedAt: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("workflow alert store", () => {
|
||||
it("persists fingerprints and only reports changed counts", () => {
|
||||
const { store, file, cleanup } = createStore();
|
||||
try {
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([alert({ observedAt: 2 })]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([alert({ errorCount: 2, observedAt: 3 })]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([]).newAlerts).toHaveLength(0);
|
||||
// 告警消失后再次出现,应当重新提醒
|
||||
expect(store.observe([alert({ observedAt: 4 })]).newAlerts).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears resolved alerts only for complete scans", () => {
|
||||
const { store, cleanup } = createStore();
|
||||
try {
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
// 扫描不完整时不清空指纹:同一条告警再次出现不再重复提醒
|
||||
store.observe([], { complete: false });
|
||||
expect(store.observe([alert({ observedAt: 2 })], { complete: false }).newAlerts).toHaveLength(0);
|
||||
// 完整扫描才清理已解决的告警,之后重现才会重新提醒
|
||||
store.observe([], { complete: true });
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps observing when the JSON export fails", () => {
|
||||
const { store, cleanup } = createStore();
|
||||
try {
|
||||
const first = store.observe([alert()]);
|
||||
expect(first.newAlerts).toHaveLength(1);
|
||||
expect(first.exportError).toBeUndefined();
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("workflow alert store export failures", () => {
|
||||
it("surfaces the export failure without losing observed results", () => {
|
||||
const dir = mkdtempSync("hose-alert-export-");
|
||||
const nested = join(dir, "blocked");
|
||||
const unwritableFile = join(nested, "alerts.json");
|
||||
const db = new Database(join(dir, "state.db"));
|
||||
runMigrations(db);
|
||||
try {
|
||||
// 把目标目录设为不可写:SQLite 已写入,但 JSON 副本落盘必然失败
|
||||
const fs = require("node:fs");
|
||||
fs.mkdirSync(nested, { recursive: true });
|
||||
fs.chmodSync(nested, 0o500);
|
||||
const store = new WorkflowAlertStore(unwritableFile, db);
|
||||
const result = store.observe([alert()]);
|
||||
expect(result.newAlerts).toHaveLength(1);
|
||||
expect(result.exportError).toBeDefined();
|
||||
// 事实来源是 SQLite:即便副本失败,指纹依然被记住,下一轮不会重复提醒
|
||||
expect(store.observe([alert({ observedAt: 2 })]).newAlerts).toHaveLength(0);
|
||||
} finally {
|
||||
chmodSync(nested, 0o700);
|
||||
db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,12 @@ interface PersistedAlerts {
|
||||
export interface WorkflowAlertCheckResult {
|
||||
activeAlerts: WorkflowErrorAlert[];
|
||||
newAlerts: WorkflowErrorAlert[];
|
||||
/**
|
||||
* JSON 副本导出失败的原因。SQLite 已是唯一事实来源,
|
||||
* 导出失败不能让整轮巡检判定失败——那会让调用方以为观察没完成,
|
||||
* 从而在下一次巡检时漏报新增告警。
|
||||
*/
|
||||
exportError?: string;
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
|
||||
@@ -120,15 +126,20 @@ export class WorkflowAlertStore {
|
||||
});
|
||||
tx(alerts);
|
||||
|
||||
let exportError: string | undefined;
|
||||
if (this.jsonPath) {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
try {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
} catch (error) {
|
||||
exportError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
return { activeAlerts: alerts, newAlerts, ...(exportError ? { exportError } : {}) };
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@
|
||||
- [index.ts](./index.ts):统一导出。
|
||||
- [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、依赖、诊断分类、统计摘要和外部分析上下文。
|
||||
- 同级测试覆盖条件/循环、选择器引用、公式边界和诊断行为。
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ import type {
|
||||
AnalyzeWorkflowOptions,
|
||||
} 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",
|
||||
@@ -250,23 +252,54 @@ export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/** 合思条件里代表「上一步执行结果」的属性名。 */
|
||||
const EXECUTION_STATUS_PROPERTIES = ["$status", "status", "result", "data"];
|
||||
|
||||
/** 条件数据来源:各处写法顺序不统一,这里固定为唯一的解析入口。 */
|
||||
function collectFilterSource(task: WorkflowTask): unknown {
|
||||
const raw = task as Record<string, unknown>;
|
||||
return raw.combineFilters ?? raw.filters ?? raw.conditions ?? raw.inputs ?? {};
|
||||
}
|
||||
|
||||
/** 收集条件节点内的全部字符串,用于逐个做引用判定。 */
|
||||
function collectReferenceStrings(source: unknown, found: string[] = []): string[] {
|
||||
if (typeof source === "string") {
|
||||
found.push(source);
|
||||
return found;
|
||||
}
|
||||
if (Array.isArray(source)) {
|
||||
for (const item of source) collectReferenceStrings(item, found);
|
||||
return found;
|
||||
}
|
||||
if (source && typeof source === "object") {
|
||||
for (const value of Object.values(source as Record<string, unknown>)) {
|
||||
collectReferenceStrings(value, found);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** 取出 `${a.b}` 或 `a.b` 形态的引用目标;无法判定为引用时返回 undefined。 */
|
||||
function referenceTargetOf(raw: string): string | undefined {
|
||||
const trimmed = raw.trim();
|
||||
const bracketed = /^\$\{([^}]+)\}$/.exec(trimmed);
|
||||
const candidate = (bracketed ? bracketed[1] : trimmed).trim();
|
||||
return candidate || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定条件节点是否真正守卫了某个节点的执行状态。
|
||||
* 必须整体等于 `<节点名>.$status` 等形态,不能靠子串包含:
|
||||
* 子串匹配会让 `task_1` 命中 `task_10` 之类无关引用,从而把「未守卫」误判为「已守卫」,
|
||||
* 使这条安全建议静默失效。
|
||||
*/
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
const expected = new Set(EXECUTION_STATUS_PROPERTIES.map((property) => `${targetTaskName}.${property}`));
|
||||
return collectReferenceStrings(collectFilterSource(task)).some((item) => {
|
||||
const target = referenceTargetOf(item);
|
||||
return target !== undefined && expected.has(target);
|
||||
});
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
@@ -420,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);
|
||||
@@ -660,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 || "");
|
||||
@@ -690,13 +726,43 @@ export function analyzeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
|
||||
// 6.3 开放接口 → 所需企业应用 开通状态校验
|
||||
//
|
||||
// ── 判定边界(重要,别放宽)────────────────────────────────────
|
||||
// 1. 只对 HTTP 节点生效;
|
||||
// 2. 只对「能静态读出接口路径」的 URL 生效 —— URL 若整体由上游节点
|
||||
// 变量拼接(以 @{...} 开头),运行前无人知道会打到哪个接口,
|
||||
// 一律跳过,不做任何猜测性告警;
|
||||
// 3. 路径必须命中 OPENAPI_APP_REQUIREMENTS 里的已知映射才判断。
|
||||
//
|
||||
// 真实事故驱动:任子行「单据审批」应用未开通,流程跑到第 9 步才被网关
|
||||
// 403「未开通功能,无权访问」拦下,而 403 报文里完全看不出缺哪个应用。
|
||||
//
|
||||
// 优先级:节点自己显式声明的 powerCode(params / URL query)优先;
|
||||
// 没有显式声明时,才用接口路径去反查所需应用。
|
||||
const httpMethod = String((task as Record<string, unknown>).method || "");
|
||||
|
||||
const paramPowerCodes: string[] = [];
|
||||
const rawParams = (task as Record<string, unknown>).params;
|
||||
if (Array.isArray(rawParams)) {
|
||||
for (const param of rawParams) {
|
||||
if (!param || typeof param !== "object") continue;
|
||||
const entry = param as { key?: unknown; value?: unknown };
|
||||
if (String(entry.key ?? "").trim().toLowerCase() !== "powercode") continue;
|
||||
if (typeof entry.value !== "string") continue;
|
||||
const value = entry.value.trim();
|
||||
if (value) paramPowerCodes.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
let urlPowerCode: string | undefined;
|
||||
let powerCodeEncodingBroken = false;
|
||||
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
|
||||
if (powerCodeMatch) {
|
||||
let powerCode: string | undefined;
|
||||
try {
|
||||
powerCode = decodeURIComponent(powerCodeMatch[1]);
|
||||
urlPowerCode = decodeURIComponent(powerCodeMatch[1]);
|
||||
} catch {
|
||||
powerCodeEncodingBroken = true;
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
@@ -705,10 +771,66 @@ export function analyzeWorkflow(
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 中 powerCode 参数包含无效的百分号转义 [${powerCodeMatch[1]}],无法校验功能权限。请修正为有效的 URL 编码。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (powerCode !== undefined) {
|
||||
const powerCodeKey = powerCode.trim().toLowerCase();
|
||||
const explicitPowerCodes = powerCodeEncodingBroken
|
||||
? []
|
||||
: Array.from(
|
||||
new Map(
|
||||
[...paramPowerCodes, ...(urlPowerCode ? [urlPowerCode] : [])].map(
|
||||
(code) => [code.trim().toLowerCase(), code.trim()] as const
|
||||
)
|
||||
).values()
|
||||
).filter(Boolean);
|
||||
|
||||
// 没有显式声明、或显式声明的正是该接口要求的那一个 → 走「接口路径反查」,
|
||||
// 这样报文里能带上应用名、productId 与判定依据路径(比只有 powerCode 更好排查)。
|
||||
// 显式声明了别的 powerCode 时以声明为准,避免两套规则打架。
|
||||
const matched = powerCodeEncodingBroken ? null : matchAppRequirement(url, httpMethod);
|
||||
const preferPathRule =
|
||||
matched !== null &&
|
||||
(explicitPowerCodes.length === 0 ||
|
||||
explicitPowerCodes.some(
|
||||
(code) => code.toLowerCase() === matched.requirement.powerCode.toLowerCase()
|
||||
));
|
||||
|
||||
if (matched && preferPathRule) {
|
||||
// 6.3.1 按接口路径反查所需应用。
|
||||
const { requirement, staticPath } = matched;
|
||||
const powerCodeKey = requirement.powerCode.trim().toLowerCase();
|
||||
const where = requirement.productId
|
||||
? `「${requirement.appName}」(productId=${requirement.productId})`
|
||||
: `「${requirement.appName}」`;
|
||||
const evidence = `判定依据:URL 静态路径 '${staticPath}'`;
|
||||
const methodLabel = httpMethod ? `${httpMethod.toUpperCase()} ` : "";
|
||||
const hintSuffix = requirement.hint ? ` ${requirement.hint}` : "";
|
||||
const declaredNote = explicitPowerCodes.length
|
||||
? `(节点 ${paramPowerCodes.length ? "params" : "URL query"} 中已显式声明 powerCode=${requirement.powerCode})`
|
||||
: "";
|
||||
|
||||
if (openedPowerCodeSet === undefined) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
category: "soft_advice",
|
||||
code: "POWER_CODE_DEPENDENCY",
|
||||
path,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力,需要权限代码 powerCode=${requirement.powerCode}${declaredNote}。当前未提供企业已开通应用清单,无法确认是否可用;若未开通,运行时将返回 403 Forbidden。${evidence}。${hintSuffix}`,
|
||||
});
|
||||
} else if (!openedPowerCodeSet.has(powerCodeKey)) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
code: "UNLICENSED_POWER_CODE",
|
||||
path,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力${declaredNote},但当前企业尚未开通该应用(powerCode=${requirement.powerCode})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问),且报文不会提示缺哪个应用。请先在应用商店开通「${requirement.appName}」(或更换为已开通的等价接口)后重新发布。${evidence}。${hintSuffix}`,
|
||||
});
|
||||
}
|
||||
} else if (explicitPowerCodes.length > 0) {
|
||||
// 6.3.2 节点显式声明了该接口之外的 powerCode,以显式声明为准
|
||||
for (const powerCode of explicitPowerCodes) {
|
||||
const powerCodeKey = powerCode.toLowerCase();
|
||||
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
|
||||
const sourceHint = paramPowerCodes.includes(powerCode) ? "params" : "URL query";
|
||||
|
||||
if (openedPowerCodeSet !== undefined) {
|
||||
if (!openedPowerCodeSet.has(powerCodeKey)) {
|
||||
@@ -717,7 +839,7 @@ export function analyzeWorkflow(
|
||||
category: "hard_block",
|
||||
code: "UNLICENSED_POWER_CODE",
|
||||
path,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint}),但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -726,7 +848,7 @@ export function analyzeWorkflow(
|
||||
category: "soft_advice",
|
||||
code: "POWER_CODE_DEPENDENCY",
|
||||
path,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
|
||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint})。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -791,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 比较照样会被算出来。` +
|
||||
`请在该节点外层再套一个条件节点,先判断「列表不为空」,把本节点放进它的满足分支。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -434,5 +434,121 @@ describe("Workflow static analysis", () => {
|
||||
expect(result.summary.hardBlocks).toBe(1);
|
||||
expect(result.summary.softAdvices).toBe(1);
|
||||
});
|
||||
|
||||
describe("状态守卫判定", () => {
|
||||
/** 构造「循环内建单(SKIP) + 条件节点 + 台账更新」的最小工作流。 */
|
||||
const buildSkipWorkflow = (guardValue: string) => ({
|
||||
id: "wf-guard",
|
||||
label: "状态守卫校验",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "依次执行",
|
||||
groupName: "control",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建单据",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
},
|
||||
{
|
||||
name: "condition_0",
|
||||
type: "condition",
|
||||
label: "是否创建成功",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
combineFilters: {
|
||||
condition: "and",
|
||||
filters: [
|
||||
{ key: guardValue, compare: "eq", value: "SUCCESS" },
|
||||
],
|
||||
},
|
||||
// 状态守卫的典型写法:把台账更新放进条件分支内部
|
||||
tasks: [
|
||||
{
|
||||
name: "datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新台账",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 1, 0],
|
||||
status: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const guardCodes = (guardValue: string) =>
|
||||
analyzeWorkflow(buildSkipWorkflow(guardValue) as any).diagnostics.map((d) => d.code);
|
||||
|
||||
it("把 ${节点名}.$status 判定为已守卫", () => {
|
||||
expect(guardCodes("${create_task_0.$status}")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("把裸写 节点名.status 也判定为已守卫", () => {
|
||||
expect(guardCodes("create_task_0.status")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("不因为节点名子串而误判为已守卫", () => {
|
||||
// create_task_0 是另一个节点的名字前缀时,不能当成对 create_task_0 的守卫
|
||||
expect(guardCodes("${create_task_0_extended.$status}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("无关引用与注释文本不构成守卫", () => {
|
||||
expect(guardCodes("${every_0.item.id}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
});
|
||||
|
||||
describe("未知节点类型与权限证据边界", () => {
|
||||
const build = (type: string) => ({
|
||||
id: "wf-node-type",
|
||||
label: "节点类型校验",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "task_0",
|
||||
type,
|
||||
label: "被测节点",
|
||||
groupName: "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it("对未收录的节点类型给出软建议", () => {
|
||||
const codes = analyzeWorkflow(build("brand-new-node") as any).diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNKNOWN_TASK_TYPE");
|
||||
});
|
||||
|
||||
it("已收录的节点类型不产生该建议", () => {
|
||||
const codes = analyzeWorkflow(build("http") as any).diagnostics.map((d) => d.code);
|
||||
expect(codes).not.toContain("UNKNOWN_TASK_TYPE");
|
||||
});
|
||||
|
||||
it("拿不到开通清单时既不谎报通过也不误报缺失", () => {
|
||||
const codes = analyzeWorkflow(build("code-js2") as any, { availableNodeTypes: [] })
|
||||
.diagnostics.map((d) => d.code);
|
||||
expect(codes).not.toContain("PERMISSION_MISSING_NODE");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
extractStaticUrlPath,
|
||||
matchAppRequirement,
|
||||
OPENAPI_APP_REQUIREMENTS,
|
||||
} from "./openapi-app-requirements.js";
|
||||
import { analyzeWorkflow } from "./index.js";
|
||||
|
||||
describe("extractStaticUrlPath", () => {
|
||||
it("保留到第一个变量之前的静态路径前缀", () => {
|
||||
expect(
|
||||
extractStaticUrlPath(
|
||||
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_x\"}')}]"
|
||||
)
|
||||
).toBe("/api/openapi/v1/backlog/data/[");
|
||||
});
|
||||
|
||||
it("无变量的完整 URL 去掉 query 与 hash", () => {
|
||||
expect(
|
||||
extractStaticUrlPath("https://app.ekuaibao.com/api/openapi/v1/backlog/data/abc123?x=1#frag")
|
||||
).toBe("/api/openapi/v1/backlog/data/abc123");
|
||||
});
|
||||
|
||||
it("纯变量开头的 URL 无法静态判断,返回 null", () => {
|
||||
expect(extractStaticUrlPath("@{choose('{\"key\":\"action_prev.url\"}')}")).toBeNull();
|
||||
expect(extractStaticUrlPath("@{choose('{\"key\":\"action_prev.url\"}')}/api/openapi/v1/backlog/data/x")).toBeNull();
|
||||
});
|
||||
|
||||
it("空值一律返回 null", () => {
|
||||
expect(extractStaticUrlPath("")).toBeNull();
|
||||
expect(extractStaticUrlPath(" ")).toBeNull();
|
||||
expect(extractStaticUrlPath(undefined)).toBeNull();
|
||||
expect(extractStaticUrlPath(null)).toBeNull();
|
||||
expect(extractStaticUrlPath(123)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAppRequirement", () => {
|
||||
it("命中:单据审批接口的静态 URL", () => {
|
||||
const matched = matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]", "POST");
|
||||
expect(matched).not.toBeNull();
|
||||
expect(matched?.requirement.appName).toBe("单据审批");
|
||||
expect(matched?.requirement.powerCode).toBe("TICKET_AUDIT_switch");
|
||||
expect(matched?.staticPath).toBe("/api/openapi/v1/backlog/data/[{flowId}]");
|
||||
});
|
||||
|
||||
it("命中:设计器真实形态([@{choose(...)}] 后缀)", () => {
|
||||
const matched = matchAppRequirement(
|
||||
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_x\",\"properties\":[]}')}]",
|
||||
"post"
|
||||
);
|
||||
expect(matched?.requirement.powerCode).toBe("TICKET_AUDIT_switch");
|
||||
});
|
||||
|
||||
it("命中:节点未写 method 时不排除(路径已是强信号)", () => {
|
||||
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("跳过:method 明确不符", () => {
|
||||
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x", "GET")).toBeNull();
|
||||
});
|
||||
|
||||
it("跳过:URL 由上游节点变量整体拼接,无法判断", () => {
|
||||
expect(matchAppRequirement("@{choose('{\"key\":\"action_prev.url\"}')}", "POST")).toBeNull();
|
||||
});
|
||||
|
||||
it("跳过:路径不在已知映射表里", () => {
|
||||
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/departments/all", "GET")).toBeNull();
|
||||
});
|
||||
|
||||
it("映射表条目字段完整", () => {
|
||||
for (const item of OPENAPI_APP_REQUIREMENTS) {
|
||||
expect(item.apiName.length).toBeGreaterThan(0);
|
||||
expect(item.appName.length).toBeGreaterThan(0);
|
||||
expect(item.powerCode.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("按接口路径反查应用开通状态(analyzer 集成)", () => {
|
||||
const build = (url: string, extra: Record<string, unknown> = {}) => ({
|
||||
id: "wf-app-requirement",
|
||||
label: "单据审批调用",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_pyrg",
|
||||
type: "http",
|
||||
label: "提交审批",
|
||||
method: "POST",
|
||||
url,
|
||||
...extra,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const REAL_URL =
|
||||
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_1\",\"properties\":[]}')}]";
|
||||
|
||||
it("企业未开通「单据审批」→ 硬门禁,并给出应用与判定依据", () => {
|
||||
const result = analyzeWorkflow(build(REAL_URL) as any, {
|
||||
openedPowerCodes: ["staff_sync_switch"],
|
||||
});
|
||||
const diag = result.diagnostics.find((d) => d.code === "UNLICENSED_POWER_CODE");
|
||||
expect(diag).toBeDefined();
|
||||
expect(diag?.category).toBe("hard_block");
|
||||
expect(diag?.severity).toBe("error");
|
||||
expect(diag?.path).toBe("0");
|
||||
expect(diag?.message).toContain("单据审批");
|
||||
expect(diag?.message).toContain("TICKET_AUDIT_switch");
|
||||
expect(diag?.message).toContain("productId=o0hMBw000000g0");
|
||||
expect(diag?.message).toContain("/api/openapi/v1/backlog/data/[");
|
||||
expect(diag?.message).toContain("403 Forbidden");
|
||||
// 节点 key 必须出现在报文里,实施同学才能直接定位到画布上的节点
|
||||
expect(diag?.message).toContain("action_pyrg");
|
||||
expect(result.summary.passed).toBe(false);
|
||||
});
|
||||
|
||||
it("企业已开通「单据审批」→ 不产生任何权限诊断", () => {
|
||||
const result = analyzeWorkflow(build(REAL_URL) as any, {
|
||||
openedPowerCodes: ["TICKET_AUDIT_switch"],
|
||||
});
|
||||
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
|
||||
expect(result.diagnostics.some((d) => d.code === "POWER_CODE_DEPENDENCY")).toBe(false);
|
||||
});
|
||||
|
||||
it("未提供已开通清单 → 软建议而非硬门禁", () => {
|
||||
const result = analyzeWorkflow(build(REAL_URL) as any);
|
||||
const diag = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
|
||||
expect(diag?.category).toBe("soft_advice");
|
||||
expect(diag?.severity).toBe("warning");
|
||||
expect(diag?.message).toContain("单据审批");
|
||||
});
|
||||
|
||||
it("URL 整体由上游节点拼接 → 完全跳过,不猜测", () => {
|
||||
const result = analyzeWorkflow(
|
||||
build("@{choose('{\"key\":\"action_prev.url\"}')}") as any,
|
||||
{ openedPowerCodes: [] }
|
||||
);
|
||||
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
|
||||
expect(result.diagnostics.some((d) => d.code === "POWER_CODE_DEPENDENCY")).toBe(false);
|
||||
});
|
||||
|
||||
it("非 HTTP 节点即使 url 字段形似也不判断", () => {
|
||||
const wf = {
|
||||
id: "wf-non-http",
|
||||
label: "代码节点",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_code",
|
||||
type: "code-js2",
|
||||
label: "拼 URL",
|
||||
code: `const u = "${REAL_URL}"; return u;`,
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = analyzeWorkflow(wf as any, { openedPowerCodes: [] });
|
||||
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
|
||||
});
|
||||
|
||||
it("显式声明的 powerCode 优先于路径反查", () => {
|
||||
const result = analyzeWorkflow(
|
||||
build("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x?powerCode=CUSTOM_AUDIT_switch") as any,
|
||||
{ openedPowerCodes: [] }
|
||||
);
|
||||
const diags = result.diagnostics.filter((d) => d.code === "UNLICENSED_POWER_CODE");
|
||||
expect(diags).toHaveLength(1);
|
||||
expect(diags[0]?.message).toContain("CUSTOM_AUDIT_switch");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 合思开放平台接口 → 所需企业应用 的权限映射。
|
||||
*
|
||||
* ── 为什么需要这张表 ────────────────────────────────────────────────
|
||||
*
|
||||
* 工作流 HTTP 节点调用某些开放接口时,企业必须先开通对应的「应用商店」应用,
|
||||
* 否则运行时会直接返回:
|
||||
*
|
||||
* HTTP 403 未开通功能,无权访问
|
||||
*
|
||||
* 这个 403 发生在流程跑到一半的时候,报错信息本身不含「缺哪个应用」,
|
||||
* 排查成本极高(真实案例:任子行「单据审批」未开通,链路跑到第 9 步才炸)。
|
||||
*
|
||||
* 所以要在**保存/静态分析阶段**就根据接口路径反推所需应用,提前告警。
|
||||
*
|
||||
* ── 判定边界(重要)────────────────────────────────────────────────
|
||||
*
|
||||
* 只有 HTTP 节点、且 URL 里存在**静态可读的接口路径**时才判断。
|
||||
* URL 若整体由上游节点变量拼接(如 `@{choose(...)}` 开头),运行前无人知道
|
||||
* 会打到哪个接口,这类情况一律跳过,不做任何猜测性告警。
|
||||
*/
|
||||
|
||||
export interface OpenApiAppRequirement {
|
||||
/** 接口的人类可读名称 */
|
||||
apiName: string;
|
||||
/** 静态路径匹配正则(作用在去掉域名、去掉变量段之后的路径上) */
|
||||
pathPattern: RegExp;
|
||||
/** 需要校验的 HTTP 方法;省略表示不限方法 */
|
||||
methods?: string[];
|
||||
/** 所需应用名称 */
|
||||
appName: string;
|
||||
/** 应用提供的权限代码,用于与已开通应用交叉核验 */
|
||||
powerCode: string;
|
||||
/** 应用商店商品 ID,便于在告警里直接给出定位信息 */
|
||||
productId?: string;
|
||||
/** 补充说明 */
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 已知需要企业应用授权的开放接口。
|
||||
*
|
||||
* 新增条目时请以线上真实工作流抓到的请求为准(URL + method + powerCode 三者一起核)。
|
||||
*/
|
||||
export const OPENAPI_APP_REQUIREMENTS: OpenApiAppRequirement[] = [
|
||||
{
|
||||
apiName: "单据审批(执行单据动作:同意 / 驳回 / 加签)",
|
||||
// POST /api/openapi/v1/backlog/data/{flowId}
|
||||
// 设计器里 flowId 通常写成 [@{choose(...)}],静态前缀到 backlog/data/ 为止
|
||||
pathPattern: /^\/api\/openapi\/v1\/backlog\/data\//i,
|
||||
methods: ["POST", "PUT", "PATCH"],
|
||||
appName: "单据审批",
|
||||
powerCode: "TICKET_AUDIT_switch",
|
||||
productId: "o0hMBw000000g0",
|
||||
hint: "接口行为等效于在单据上手动点击「同意 / 驳回 / 加签」,会真实改变单据状态。",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 从 HTTP 节点的 URL 中提取「静态可判断的路径前缀」。
|
||||
*
|
||||
* 规则:
|
||||
* - 去掉协议与域名;
|
||||
* - 截断到第一个 `@{...}` 变量之前;
|
||||
* - 去掉 query 与 hash。
|
||||
*
|
||||
* 若 URL 本身以变量开头(完全没有静态路径),返回 `null` —— 表示无法静态判断。
|
||||
*
|
||||
* 示例:
|
||||
* ```
|
||||
* https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose(...)}]
|
||||
* → /api/openapi/v1/backlog/data/[
|
||||
*
|
||||
* @{choose(...)}
|
||||
* → null(纯变量拼接,放弃判断)
|
||||
* ```
|
||||
*/
|
||||
export function extractStaticUrlPath(url: unknown): string | null {
|
||||
if (typeof url !== "string") return null;
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
let rest = trimmed;
|
||||
|
||||
const schemeMatch = rest.match(/^https?:\/\/[^/]+/i);
|
||||
if (schemeMatch) {
|
||||
rest = rest.slice(schemeMatch[0].length);
|
||||
} else if (rest.startsWith("@{") || rest.startsWith("${")) {
|
||||
// 纯变量开头,没有可读的静态路径
|
||||
return null;
|
||||
}
|
||||
|
||||
const varIndex = rest.indexOf("@{");
|
||||
const staticPart = varIndex === -1 ? rest : rest.slice(0, varIndex);
|
||||
if (!staticPart) return null;
|
||||
|
||||
const path = staticPart.split("?")[0].split("#")[0].trim();
|
||||
return path || null;
|
||||
}
|
||||
|
||||
export interface MatchedAppRequirement {
|
||||
requirement: OpenApiAppRequirement;
|
||||
/** 提取到的静态路径,便于在诊断信息里展示判断依据 */
|
||||
staticPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 URL 与 HTTP 方法匹配「需要应用授权」的接口规则。
|
||||
*
|
||||
* 只有能提取出静态路径、且方法命中时才返回结果;否则返回 `null`(不判断、不告警)。
|
||||
*/
|
||||
export function matchAppRequirement(url: unknown, method?: unknown): MatchedAppRequirement | null {
|
||||
const staticPath = extractStaticUrlPath(url);
|
||||
if (!staticPath) return null;
|
||||
|
||||
const normalizedMethod = typeof method === "string" ? method.trim().toUpperCase() : "";
|
||||
|
||||
for (const requirement of OPENAPI_APP_REQUIREMENTS) {
|
||||
// 方法:节点没写 method 时不作为排除条件(路径已是足够强的信号);
|
||||
// 写了 method 但与规则不符才跳过。
|
||||
if (requirement.methods && requirement.methods.length > 0 && normalizedMethod) {
|
||||
if (!requirement.methods.includes(normalizedMethod)) continue;
|
||||
}
|
||||
if (!requirement.pathPattern.test(staticPath)) continue;
|
||||
return { requirement, staticPath };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { OP_MAP, cleanRuleValue, evaluateRule, parseChooseTag, parseValueTag } from "./explain.js";
|
||||
|
||||
/**
|
||||
* 条件解释器的值比较:此前只有 eq/gt 有覆盖,其余九个比较符完全裸奔。
|
||||
* `evaluateRule` 返回 `null` 表示「无法确定」,UI 侧据此不声称分支判定为 False。
|
||||
*/
|
||||
describe("evaluateRule equality operators", () => {
|
||||
it("compares scalars after string coercion", () => {
|
||||
expect(evaluateRule(10, "10", "eq")).toBe(true);
|
||||
expect(evaluateRule(10, "11", "eq")).toBe(false);
|
||||
expect(evaluateRule(10, "11", "neq")).toBe(true);
|
||||
expect(evaluateRule("a", "b", "neq")).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a single-element array as its item", () => {
|
||||
expect(evaluateRule(["SUCCESS"], "SUCCESS", "eq")).toBe(true);
|
||||
expect(evaluateRule("SUCCESS", ["SUCCESS"], "eq")).toBe(true);
|
||||
expect(evaluateRule(["A", "B"], "A", "eq")).toBe(false);
|
||||
});
|
||||
|
||||
it("unwraps identifier objects before comparing", () => {
|
||||
// 带 id 的对象会被归一成 id 本身
|
||||
expect(evaluateRule({ id: 1 }, 1, "eq")).toBe(true);
|
||||
});
|
||||
|
||||
it("reports null (unknown) when a non-identifier object survives normalization", () => {
|
||||
expect(evaluateRule({ amount: 10 }, 10, "eq")).toBeNull();
|
||||
expect(evaluateRule({ amount: 10 }, 10, "gt")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns false rather than unknown when the actual value is undefined", () => {
|
||||
expect(evaluateRule(undefined, "x", "eq")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns null for unsupported operators", () => {
|
||||
expect(evaluateRule("a", "b", "like")).toBeNull();
|
||||
expect(OP_MAP.like).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule emptiness", () => {
|
||||
it("detects empty values including empty arrays", () => {
|
||||
expect(evaluateRule(null, null, "empty")).toBe(true);
|
||||
expect(evaluateRule(undefined, null, "empty")).toBe(true);
|
||||
expect(evaluateRule("", null, "empty")).toBe(true);
|
||||
expect(evaluateRule([], null, "empty")).toBe(true);
|
||||
expect(evaluateRule(0, null, "empty")).toBe(false);
|
||||
});
|
||||
|
||||
it("negates emptiness", () => {
|
||||
expect(evaluateRule("x", null, "not_empty")).toBe(true);
|
||||
expect(evaluateRule([], null, "not_empty")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule membership", () => {
|
||||
it("checks membership against an expected list", () => {
|
||||
expect(evaluateRule("A", ["A", "B"], "in")).toBe(true);
|
||||
expect(evaluateRule("C", ["A", "B"], "in")).toBe(false);
|
||||
expect(evaluateRule("C", ["A", "B"], "not_in")).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot decide when the actual value itself is a list", () => {
|
||||
expect(evaluateRule(["A"], ["A"], "in")).toBeNull();
|
||||
expect(evaluateRule("A", "A", "in")).toBeNull();
|
||||
});
|
||||
|
||||
it("checks containment for strings and arrays", () => {
|
||||
expect(evaluateRule("abc", "b", "include")).toBe(true);
|
||||
expect(evaluateRule(["a", "b"], ["a"], "include")).toBe(true);
|
||||
expect(evaluateRule(["a", "b"], ["a", "c"], "include")).toBe(false);
|
||||
expect(evaluateRule(["a"], ["b"], "not_include")).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot decide containment for non-collection actual values", () => {
|
||||
expect(evaluateRule(5, [5], "include")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule numeric comparison", () => {
|
||||
it("compares numeric strings", () => {
|
||||
expect(evaluateRule("11", "10", "gt")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "gte")).toBe(true);
|
||||
expect(evaluateRule("9", "10", "lt")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "lte")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "gt")).toBe(false);
|
||||
});
|
||||
|
||||
it("cannot compare non-numeric values", () => {
|
||||
expect(evaluateRule("abc", "10", "gt")).toBeNull();
|
||||
expect(evaluateRule("", "10", "lt")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("rule value descriptors", () => {
|
||||
it("unwraps @{value('...')} selectors and identifier objects", () => {
|
||||
expect(cleanRuleValue(`@{value('{"key":"k1","label":"预算"}')}`)).toBe("k1");
|
||||
expect(cleanRuleValue({ id: "k2" })).toBe("k2");
|
||||
expect(cleanRuleValue(["@{value('{\"key\":\"k3\"}')}"])).toEqual(["k3"]);
|
||||
});
|
||||
|
||||
it("keeps value tags readable for display", () => {
|
||||
expect(parseValueTag(`@{value('{"key":"k1","label":"预算"}')}`)).toBe("预算 (k1)");
|
||||
expect(parseValueTag(`@{value('{"bad json"}')}`)).toContain("@{value");
|
||||
});
|
||||
|
||||
it("extracts upstream nodes from choose descriptors", () => {
|
||||
expect(parseChooseTag(`@{choose('{"key":"webhook_1","properties":[{"key":"body"}],"label":"触发人"}')}`)).toEqual({
|
||||
upstreamNode: "webhook_1",
|
||||
upstreamProp: "body",
|
||||
label: "触发人",
|
||||
});
|
||||
expect(parseChooseTag("plain.key")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
import { indexExecutionContexts } from "../execution/context.js";
|
||||
import { parseChoosePayloadLoose } from "../models/choose-serialization.js";
|
||||
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
|
||||
|
||||
export const OP_MAP: Record<string, string> = {
|
||||
@@ -18,7 +19,14 @@ export const OP_MAP: Record<string, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
|
||||
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签。
|
||||
*
|
||||
* 载荷解析走 `parseChoosePayloadLoose`,同时兼容两种形态:
|
||||
* - 设计器产出的 `{"k":"v"}}`(多一个右花括号,平台统一形态)
|
||||
* - 配平形态 `{"k":"v"}`
|
||||
*
|
||||
* 早期实现直接用 `JSON.parse`,遇到设计器产出的数据会静默返回 null,
|
||||
* 导致 `}}` 形态配置的分支解释全部失效。
|
||||
*/
|
||||
export function parseChooseTag(tag: string): {
|
||||
upstreamNode: string;
|
||||
@@ -26,10 +34,12 @@ export function parseChooseTag(tag: string): {
|
||||
label: string;
|
||||
} | null {
|
||||
if (typeof tag !== "string") return null;
|
||||
const match = tag.match(/@\{choose\('(.*)'\)\}/);
|
||||
const match = tag.match(/@\{choose\('([\s\S]*?)'\)\}/);
|
||||
if (!match) return null;
|
||||
const normalized = parseChoosePayloadLoose(match[1]);
|
||||
if (normalized === null) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(match[1]);
|
||||
const parsed = JSON.parse(normalized);
|
||||
const upstreamNode = parsed.key || "";
|
||||
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
||||
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
||||
|
||||
@@ -107,6 +107,7 @@ export async function grantWorkflowNodes(
|
||||
|
||||
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) {
|
||||
@@ -117,8 +118,10 @@ export async function grantWorkflowNodes(
|
||||
const result = await api.grantWorkflowNodesApi({
|
||||
token,
|
||||
corpId,
|
||||
staffId,
|
||||
nodes: normalizedNodes,
|
||||
baseUrl,
|
||||
isTest: options.isTest,
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
|
||||
- [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。
|
||||
- [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。
|
||||
- [job-status.ts](./job-status.ts):Job 状态归一化与终态判定,**watch 监听与 debug 轮询共用同一实现**。
|
||||
- [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。
|
||||
- [queries.ts](./queries.ts):Job、执行树与日志读取服务出口。
|
||||
|
||||
执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。
|
||||
|
||||
## Job 状态语义
|
||||
|
||||
Job 可能只返回字符串 `status`,也可能只返回数字 `state`(0 完成、1 运行中、2 失败)。
|
||||
归一化逻辑只在 `job-status.ts` 定义一次:过去 debug 侧自行判定时把 `state: 0` 当成未知而继续轮询,
|
||||
watch 侧却视为已完成,同一个 Job 在两条路径上会得到相反的结论。
|
||||
修改状态时必须同时考虑这两个入口,并在两侧补回归用例。
|
||||
@@ -3,6 +3,7 @@ import { ValidationError } from "../../../../core/errors.js";
|
||||
import { explainConditionBranches } from "../branch/index.js";
|
||||
import { WorkflowJobDetail } from "../types.js";
|
||||
import { extractFailureExecutions } from "./tree.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./job-status.js";
|
||||
|
||||
|
||||
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
||||
@@ -74,8 +75,6 @@ export async function runWorkflowDebugTest(
|
||||
const start = Date.now();
|
||||
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
||||
const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) });
|
||||
const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase();
|
||||
let finalJob: WorkflowJobDetail | undefined;
|
||||
let pollingFailed = false;
|
||||
|
||||
@@ -83,7 +82,7 @@ export async function runWorkflowDebugTest(
|
||||
try {
|
||||
const job = await api.getJob(client, jobId);
|
||||
finalJob = job;
|
||||
if (terminal.has(jobState(job))) break;
|
||||
if (isJobTerminal(normalizeJobStatus(job))) break;
|
||||
} catch (error) {
|
||||
// 任务刚创建可能存在短延时,继续轮询
|
||||
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
||||
@@ -101,7 +100,7 @@ export async function runWorkflowDebugTest(
|
||||
try { finalJob = await api.getJob(client, jobId); }
|
||||
catch (error) { recordError("job", error); pollingFailed = true; }
|
||||
}
|
||||
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
|
||||
const timedOut = !pollingFailed && !isJobTerminal(normalizeJobStatus(finalJob));
|
||||
const [treeResult, failuresResult] = await Promise.allSettled([
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
@@ -113,11 +112,11 @@ export async function runWorkflowDebugTest(
|
||||
|
||||
const rawFailed = extractFailureExecutions(tree, failedItems);
|
||||
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
||||
const status = jobState(finalJob);
|
||||
const status = normalizeJobStatus(finalJob);
|
||||
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
||||
let outcome: import("../types.js").WorkflowTestReport["outcome"] = "incomplete";
|
||||
if (timedOut) outcome = "timed_out";
|
||||
else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (isJobTerminal(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { WorkflowJobDetail } from "../types.js";
|
||||
|
||||
/**
|
||||
* Job 状态归一化。Job 可能只返回字符串 `status`,也可能只返回数字 `state`,
|
||||
* 两个入口(watch 监听与 debug 轮询)必须给出一致的解释,否则同一个 Job
|
||||
* 在一处被视为已完成、在另一处被视为仍在运行。
|
||||
*
|
||||
* 数字 state 的语义:0 完成、1 运行中、2 失败(与 watch 侧既有约定一致)。
|
||||
*/
|
||||
export const TERMINAL_JOB_STATES = new Set([
|
||||
"COMPLETED",
|
||||
"FAILED",
|
||||
"STOP",
|
||||
"STOPPED",
|
||||
"CANCELLED",
|
||||
"CANCELED",
|
||||
]);
|
||||
|
||||
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||
if (!job) return "UNKNOWN";
|
||||
const rawStatus = (job as Record<string, unknown>).status;
|
||||
const rawState = (job as Record<string, unknown>).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
const normalized = rawStatus.trim().toUpperCase();
|
||||
return normalized === "STARTED" ? "RUNNING" : normalized;
|
||||
}
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_JOB_STATES.has(status.toUpperCase());
|
||||
}
|
||||
@@ -63,6 +63,35 @@ describe("workflow debug completion evidence", () => {
|
||||
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
describe("numeric job state must agree with the watch pipeline", () => {
|
||||
const withState = (state: number) => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
client.get = async (path: string) => {
|
||||
if (path.endsWith("/job")) {
|
||||
return new Response(JSON.stringify({ code: 200, data: { id: "job", state } }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
return get(path);
|
||||
};
|
||||
return client;
|
||||
};
|
||||
|
||||
it("reads state 0 as completed instead of polling until timeout", async () => {
|
||||
const result = await runWorkflowDebugTest(withState(0), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
|
||||
expect(result.status).toBe("COMPLETED");
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(result.timedOut).toBe(false);
|
||||
});
|
||||
|
||||
it("reads state 1 as still running", async () => {
|
||||
const result = await runWorkflowDebugTest(withState(1), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
|
||||
expect(result.status).toBe("RUNNING");
|
||||
expect(result.outcome).toBe("timed_out");
|
||||
});
|
||||
});
|
||||
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
|
||||
@@ -5,3 +5,18 @@
|
||||
- [save-error.ts](./save-error.ts):主保存成功而元数据刷新失败时的部分成功异常。
|
||||
|
||||
HTTP 传输和共享模型仍位于上级 `api.ts`、`types.ts`,对外业务出口为上级 `services.ts`。
|
||||
|
||||
## 保存与并发保护
|
||||
|
||||
`updateWorkflow(client, workflow, options)` 的第三参数支持两种写法:
|
||||
|
||||
| 写法 | 语义 |
|
||||
|---|---|
|
||||
| `updateWorkflow(client, wf, "platform-id")` | 兼容旧调用,等价于 `{ platformId }` |
|
||||
| `updateWorkflow(client, wf, { platformId, expectedVersion })` | 提供 `expectedVersion: { version, tasksVersion }` 时,提交前重读远端比对,不一致抛 `ValidationError`(`WORKFLOW_VERSION_CONFLICT`) |
|
||||
|
||||
并发保护必须由调用方显式声明期望值才会启用:这是一项客户端检查而非原子条件写入,检查与提交之间仍存在窗口。任何绕过 CLI 的调用方都应走这条路径,而不是各自再实现一遍重读逻辑。
|
||||
|
||||
## 启停
|
||||
|
||||
`toggleWorkflow` 先按 EASO 业务码判定写请求,再回读详情确认 `state` 确实变化;回读失败返回 `verified: false`,交由调用方如实呈现,不谎称已生效。详见 [README.workflow.md](../README.workflow.md)。
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BusinessError, ValidationError } from "../../../../core/errors.js";
|
||||
import { KyInstance } from "ky";
|
||||
import { WorkflowSavePartialError } from "./save-error.js";
|
||||
import * as api from "../api.js";
|
||||
@@ -24,14 +25,33 @@ export function sanitizeWorkflowSnapshot(
|
||||
}
|
||||
|
||||
|
||||
export interface UpdateWorkflowOptions {
|
||||
/** 前端保存时带上的触发输入 $platformId,缺少它会让平台把内置节点 desc 重置为「」。 */
|
||||
platformId?: string;
|
||||
/**
|
||||
* 读取工作流时的版本快照。提供时会在提交前重读远端做比对,
|
||||
* 不一致抛 ValidationError,避免静默覆盖中间发生的修改。
|
||||
* 这是客户端检查而非原子条件写入,检查与提交之间仍存在并发窗口。
|
||||
*/
|
||||
expectedVersion?: { version?: unknown; tasksVersion?: unknown };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按前端「保存更新」语义提交工作流。
|
||||
* 第三参数兼容旧的 platformId 字符串写法;需要并发保护时改用对象形式并传入 expectedVersion。
|
||||
*/
|
||||
export async function updateWorkflow(
|
||||
client: KyInstance,
|
||||
workflow: import("../types.js").WorkflowDetail,
|
||||
platformId?: string
|
||||
options: string | UpdateWorkflowOptions = {}
|
||||
) {
|
||||
const opts: UpdateWorkflowOptions = typeof options === "string" ? { platformId: options } : options ?? {};
|
||||
if (opts.expectedVersion) {
|
||||
await assertVersionUnchanged(client, workflow.id, opts.expectedVersion);
|
||||
}
|
||||
// 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。
|
||||
const payload: import("../types.js").WorkflowDetail = platformId && !workflow.inputs?.length
|
||||
? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] }
|
||||
const payload: import("../types.js").WorkflowDetail = opts.platformId && !workflow.inputs?.length
|
||||
? { ...workflow, inputs: [{ key: "$platformId", value: opts.platformId }] }
|
||||
: workflow;
|
||||
const sanitized = sanitizeWorkflowSnapshot(payload);
|
||||
const updated = await api.updateWorkflow(client, sanitized);
|
||||
@@ -44,6 +64,22 @@ export async function updateWorkflow(
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** 提交前的事实校验:远端版本与读取时不一致则拒绝写入。 */
|
||||
async function assertVersionUnchanged(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
expected: { version?: unknown; tasksVersion?: unknown }
|
||||
): Promise<void> {
|
||||
const remote = await api.getWorkflowDetail(client, pipelineId);
|
||||
const versionMatches = expected.version === undefined || remote.version === expected.version;
|
||||
const tasksMatches = expected.tasksVersion === undefined || remote.tasksVersion === expected.tasksVersion;
|
||||
if (versionMatches && tasksMatches) return;
|
||||
throw new ValidationError(
|
||||
`工作流版本已变化,拒绝覆盖:远端 version=${remote.version}/tasksVersion=${remote.tasksVersion},读取时 version=${expected.version}/tasksVersion=${expected.tasksVersion}。请重新执行命令。`,
|
||||
"WORKFLOW_VERSION_CONFLICT"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/** 只重试元数据刷新,不重新提交完整工作流快照。 */
|
||||
export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise<void> {
|
||||
@@ -136,6 +172,48 @@ export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
|
||||
}
|
||||
|
||||
|
||||
export function toggleWorkflow(...args: Parameters<typeof api.toggleWorkflow>) {
|
||||
return api.toggleWorkflow(...args);
|
||||
/**
|
||||
* 启停是生产开关:写请求按 EASO 业务码判定成败,写成功之后再回读详情确认状态确实变化。
|
||||
* 回读失败(网络、鉴权、详情不可用)时不得宣称已生效,返回 `verified: false` 交由调用方如实呈现。
|
||||
* `verify: false` 仅用于无法回读的场景(如只需要触发写写的内部场景),默认为确认模式。
|
||||
*/
|
||||
export async function toggleWorkflow(
|
||||
client: import("ky").KyInstance,
|
||||
pipelineId: string,
|
||||
state: import("../types.js").WorkflowState,
|
||||
options: { verify?: boolean } = {}
|
||||
): Promise<import("../types.js").WorkflowToggleResult> {
|
||||
await api.toggleWorkflowState(client, pipelineId, state);
|
||||
const notVerified = (reason: string): import("../types.js").WorkflowToggleResult => ({
|
||||
pipelineId,
|
||||
requestedState: state,
|
||||
state: null,
|
||||
success: true,
|
||||
verified: false,
|
||||
message: `已提交启停请求,但${reason},服务端实际状态未能确认。请稍后用 workflow get 核对。`,
|
||||
});
|
||||
|
||||
if (options.verify === false) return notVerified("未请求回读");
|
||||
|
||||
try {
|
||||
const remote = await api.getWorkflowDetail(client, pipelineId);
|
||||
const actual: import("../types.js").WorkflowState = remote.state === 1 ? 1 : 0;
|
||||
if (actual !== state) {
|
||||
throw new BusinessError(
|
||||
`工作流 [${pipelineId}] 启停未生效:期望 state=${state},服务端回读 state=${actual}。请勿据此认为已发布或已停用。`,
|
||||
"WORKFLOW_STATE_NOT_APPLIED"
|
||||
);
|
||||
}
|
||||
return {
|
||||
pipelineId,
|
||||
requestedState: state,
|
||||
state: actual,
|
||||
success: true,
|
||||
verified: true,
|
||||
message: state === 1 ? "已确认启用" : "已确认停用",
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError) throw error;
|
||||
return notVerified(`回读详情失败(${error instanceof Error ? error.message : String(error)})`);
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ export interface AvailableWorkflowNodes {
|
||||
export interface GrantWorkflowNodesOptions {
|
||||
nodes: string[];
|
||||
password?: string;
|
||||
/** 显式选择 piper-test.ekuaibao.net;默认使用标准 Piper。 */
|
||||
isTest?: boolean;
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesResult {
|
||||
@@ -53,6 +55,7 @@ export interface GrantWorkflowNodesResult {
|
||||
saved: string[];
|
||||
skipped: string[];
|
||||
rawMessage: string;
|
||||
isTest?: boolean;
|
||||
}
|
||||
|
||||
// ── 员工 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
inspectChooseTags,
|
||||
normalizeChooseTags,
|
||||
parseChoosePayloadLoose,
|
||||
serializeChooseTag,
|
||||
} from "./choose-serialization.js";
|
||||
import { parseChooseTag } from "../branch/explain.js";
|
||||
|
||||
const payload = {
|
||||
key: "action_detail",
|
||||
properties: [{ key: "id", label: "单据ID", type: "TEXT" }],
|
||||
label: "查询单据详情.单据ID",
|
||||
};
|
||||
const json = JSON.stringify(payload);
|
||||
|
||||
describe("parseChoosePayloadLoose", () => {
|
||||
test("解析配平形态", () => {
|
||||
expect(parseChoosePayloadLoose(json)).toBe(json);
|
||||
});
|
||||
|
||||
test("解析设计器产出的多余右花括号形态", () => {
|
||||
expect(parseChoosePayloadLoose(`${json}}`)).toBe(json);
|
||||
});
|
||||
|
||||
test("解析多个多余右花括号", () => {
|
||||
expect(parseChoosePayloadLoose(`${json}}}`)).toBe(json);
|
||||
});
|
||||
|
||||
test("嵌套对象仍能正确剥离", () => {
|
||||
const nested = JSON.stringify({ key: "a", properties: [{ key: "b", meta: { x: 1 } }] });
|
||||
expect(parseChoosePayloadLoose(`${nested}}`)).toBe(nested);
|
||||
});
|
||||
|
||||
test("非 JSON 载荷(旧式路径写法)返回 null,不猜测", () => {
|
||||
expect(parseChoosePayloadLoose("body.details")).toBeNull();
|
||||
expect(parseChoosePayloadLoose("action_missing.data")).toBeNull();
|
||||
});
|
||||
|
||||
test("空载荷返回 null", () => {
|
||||
expect(parseChoosePayloadLoose("")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeChooseTag", () => {
|
||||
test("frontend 模式多一个右花括号", () => {
|
||||
expect(serializeChooseTag(json, "frontend")).toBe(`@{choose('${json}}')}`);
|
||||
});
|
||||
|
||||
test("pure 模式花括号配平", () => {
|
||||
expect(serializeChooseTag(json, "pure")).toBe(`@{choose('${json}')}`);
|
||||
});
|
||||
|
||||
test("frontend 产出可被再次解析(不累加)", () => {
|
||||
const once = serializeChooseTag(json, "frontend");
|
||||
const twice = normalizeChooseTags(once, "frontend");
|
||||
expect(twice).toBe(once);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeChooseTags", () => {
|
||||
const prefix = "https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[";
|
||||
const suffix = "]";
|
||||
|
||||
test("frontend 模式补齐前端形态", () => {
|
||||
const pureUrl = `${prefix}@{choose('${json}')}${suffix}`;
|
||||
expect(normalizeChooseTags(pureUrl, "frontend")).toBe(`${prefix}@{choose('${json}}')}${suffix}`);
|
||||
});
|
||||
|
||||
test("pure 模式去掉多余花括号", () => {
|
||||
const frontendUrl = `${prefix}@{choose('${json}}')}${suffix}`;
|
||||
expect(normalizeChooseTags(frontendUrl, "pure")).toBe(`${prefix}@{choose('${json}')}${suffix}`);
|
||||
});
|
||||
|
||||
test("静态前缀与后缀完整保留", () => {
|
||||
const frontendUrl = `${prefix}@{choose('${json}}')}${suffix}`;
|
||||
const out = normalizeChooseTags(frontendUrl, "frontend");
|
||||
expect(out.startsWith(prefix)).toBe(true);
|
||||
expect(out.endsWith(suffix)).toBe(true);
|
||||
});
|
||||
|
||||
test("同一字符串内多个标签全部归一化", () => {
|
||||
const text = `a@{choose('${json}')}b@{choose('${json}')}c`;
|
||||
const out = normalizeChooseTags(text, "frontend");
|
||||
expect(out).toBe(`a@{choose('${json}}')}b@{choose('${json}}')}c`);
|
||||
});
|
||||
|
||||
test("不含 choose 标签的字符串原样返回", () => {
|
||||
expect(normalizeChooseTags("https://example.com/plain", "frontend")).toBe("https://example.com/plain");
|
||||
});
|
||||
|
||||
test("旧式非 JSON 载荷原样保留,不被破坏", () => {
|
||||
const legacy = "@{choose('body.details')}";
|
||||
expect(normalizeChooseTags(legacy, "frontend")).toBe(legacy);
|
||||
expect(normalizeChooseTags(legacy, "pure")).toBe(legacy);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspectChooseTags", () => {
|
||||
test("区分配平与多花括号形态", () => {
|
||||
const text = `@{choose('${json}}')} @{choose('${json}')} @{choose('body.x')}`;
|
||||
expect(inspectChooseTags(text)).toEqual({
|
||||
total: 3,
|
||||
balanced: 1,
|
||||
extraBrace: 1,
|
||||
unparsable: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseChooseTag 兼容设计器产出形态", () => {
|
||||
test("配平形态可解析", () => {
|
||||
expect(parseChooseTag(`@{choose('${json}')}`)).toEqual({
|
||||
upstreamNode: "action_detail",
|
||||
upstreamProp: "id",
|
||||
label: "查询单据详情.单据ID",
|
||||
});
|
||||
});
|
||||
|
||||
test("多花括号形态同样可解析(回归:早期实现直接 JSON.parse 会失败)", () => {
|
||||
expect(parseChooseTag(`@{choose('${json}}')}`)).toEqual({
|
||||
upstreamNode: "action_detail",
|
||||
upstreamProp: "id",
|
||||
label: "查询单据详情.单据ID",
|
||||
});
|
||||
});
|
||||
|
||||
test("非 JSON 载荷返回 null", () => {
|
||||
expect(parseChooseTag("@{choose('body.details')}")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
ChooseSerializationSchema,
|
||||
type ChooseSerialization,
|
||||
} from "../../../../core/config/types.js";
|
||||
|
||||
/**
|
||||
* `@{choose('…')}` 标签的序列化形态。
|
||||
*
|
||||
* ── 背景(务必先读这里,否则很容易把正常数据当脏数据改坏)─────────────────
|
||||
*
|
||||
* 合思设计器的「请求 URL」是 Lexical 富文本字段,前端把富文本序列化成扁平字符串时,
|
||||
* 模板字符串多写了一个右花括号:
|
||||
*
|
||||
* `@{choose('${JSON.stringify(x)}}')}` // 注意 }}) 这一处,多了一个 }
|
||||
* ↑
|
||||
* 正确写法应为 `@{choose('${JSON.stringify(x)}')}`
|
||||
*
|
||||
* 因此 UI 保存出来的 `tasks[i].url` 里,choose 参数中的 JSON 永远是 `{"k":"v"}}`
|
||||
* (`{` 2 个、`}` 3 个,不配平)。这是**平台稳定输出形态**,不是偶发脏数据。
|
||||
*
|
||||
* 后端引擎能正常处理它:choose 载荷最终交给 Jackson 反序列化,而 Jackson 的
|
||||
* `FAIL_ON_TRAILING_TOKENS` 默认关闭,尾随的那个 `}` 被静默忽略。已用实机三组
|
||||
* 对照验证过(双 `}` / 单 `}` / 双 `}` + 后缀,全部 COMPLETED,求值结果逐字符一致),
|
||||
* 详见 `docs/合思前端-表达式序列化缺陷-2026-11-04.md` 第 8 章。
|
||||
*
|
||||
* ── 所以这个开关是干什么的 ────────────────────────────────────────────
|
||||
*
|
||||
* - `frontend`(默认):CLI 写出的表达式与 UI 产出一致,都带那个多余的 `}`。
|
||||
* 好处是「CLI 改完 → 人去设计器再点一次保存」不会发生形态漂移,diff 干净,
|
||||
* 也不会让设计器把变量节点降级成纯文本。
|
||||
* - `pure`:CLI 写出配平形态。JSON 合法,适合离线分析、文档示例、或对接做了
|
||||
* 严格 JSON 校验的下游。代价是 UI 下次保存会把它改回 `frontend` 形态。
|
||||
*
|
||||
* 注意:**读取侧永远同时容忍两种形态**,与写入模式无关。模式只影响「CLI 往服务端
|
||||
* 写的字节长什么样」,不影响 CLI 如何理解已存在的数据。
|
||||
*/
|
||||
export { ChooseSerializationSchema };
|
||||
export type { ChooseSerialization };
|
||||
|
||||
/** 默认百分百模拟真实前端。 */
|
||||
export const DEFAULT_CHOOSE_SERIALIZATION: ChooseSerialization = "frontend";
|
||||
|
||||
const CHOOSE_TAG_START = "@{choose('";
|
||||
|
||||
/**
|
||||
* 匹配 `@{choose('…')}` 标签。非贪婪,因为同一字符串里可能有多个标签。
|
||||
* 载荷里出现 `')}` 之外的字符(含换行、引号)都能吃进去。
|
||||
*/
|
||||
const CHOOSE_TAG_PATTERN = /@\{choose\('([\s\S]*?)'\)\}/g;
|
||||
|
||||
/**
|
||||
* 容错解析 choose 标签内的 JSON 载荷,返回规范化后的 JSON 文本。
|
||||
*
|
||||
* 依次尝试:
|
||||
* 1. 原样 `JSON.parse`(配平形态,即 `pure` 产出)
|
||||
* 2. 逐个剥离尾部多余的 `}` 后再解析(`frontend` 产出的多花括号形态)
|
||||
*
|
||||
* 无法解析时返回 `null`,调用方应原样保留标签,避免破坏旧式写法
|
||||
* (如 `@{choose('body.details')}`,其载荷不是 JSON)。
|
||||
*/
|
||||
export function parseChoosePayloadLoose(raw: string): string | null {
|
||||
let candidate = raw.trim();
|
||||
while (candidate.length > 0) {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(candidate));
|
||||
} catch {
|
||||
if (!candidate.endsWith("}")) return null;
|
||||
candidate = candidate.slice(0, -1).trimEnd();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按指定模式序列化一个 choose 标签。
|
||||
*
|
||||
* - `frontend` → `@{choose('{"k":"v"}}')}`(多一个 `}`)
|
||||
* - `pure` → `@{choose('{"k":"v"}')}`
|
||||
*/
|
||||
export function serializeChooseTag(json: string, mode: ChooseSerialization = DEFAULT_CHOOSE_SERIALIZATION): string {
|
||||
const tail = mode === "frontend" ? "}')}" : "')}";
|
||||
return `${CHOOSE_TAG_START}${json}${tail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化字符串中所有 `@{choose('…')}` 标签的形态。
|
||||
*
|
||||
* 只改写能成功解析为 JSON 的标签;解析不了的(旧式路径写法、人工手写的非 JSON 载荷)
|
||||
* 原样保留,绝不猜测。
|
||||
*/
|
||||
export function normalizeChooseTags(text: string, mode: ChooseSerialization = DEFAULT_CHOOSE_SERIALIZATION): string {
|
||||
if (typeof text !== "string" || !text.includes(CHOOSE_TAG_START)) return text;
|
||||
return text.replace(CHOOSE_TAG_PATTERN, (whole, payload: string) => {
|
||||
const json = parseChoosePayloadLoose(payload);
|
||||
if (json === null) return whole;
|
||||
return serializeChooseTag(json, mode);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计字符串里 choose 标签的形态分布,用于诊断与文档输出。
|
||||
*/
|
||||
export function inspectChooseTags(text: string): {
|
||||
total: number;
|
||||
balanced: number;
|
||||
extraBrace: number;
|
||||
unparsable: number;
|
||||
} {
|
||||
const result = { total: 0, balanced: 0, extraBrace: 0, unparsable: 0 };
|
||||
if (typeof text !== "string" || !text.includes(CHOOSE_TAG_START)) return result;
|
||||
|
||||
const pattern = new RegExp(CHOOSE_TAG_PATTERN.source, "g");
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(text)) !== null) {
|
||||
result.total += 1;
|
||||
const payload = match[1].trim();
|
||||
if (parseChoosePayloadLoose(payload) === null) {
|
||||
result.unparsable += 1;
|
||||
} else if (payload.endsWith("}}")) {
|
||||
result.extraBrace += 1;
|
||||
} else {
|
||||
result.balanced += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -174,3 +174,19 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
|
||||
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
|
||||
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
|
||||
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
|
||||
|
||||
// ── 启停结果 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 工作流启停结果。启停是生产开关,必须在写操作之后回读确认:
|
||||
* `verified` 区分「已确认生效」与「已提交但未能确认」,两者都不能谎称成功。
|
||||
* `state` 为 null 表示未能读到服务端实际状态。
|
||||
*/
|
||||
export interface WorkflowToggleResult {
|
||||
pipelineId: string;
|
||||
requestedState: WorkflowState;
|
||||
state: WorkflowState | null;
|
||||
success: boolean;
|
||||
verified: boolean;
|
||||
message: string;
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
JavaScript 在独立 QuickJS 运行时中执行,设置超时、内存及输入/输出、日志限制;输入同时提供变量和 `inputs` 命名空间。求值仅支持同步结果,不共享宿主构造器,不把本地求值视为服务端脚本执行的完整替代。
|
||||
|
||||
return 识别先剔除注释与字符串字面量(`stripCommentsAndStrings`)再匹配关键字,避免行尾注释、块注释内部行和字符串里的 `return` 让 `missing-return` 告警失效。该能力同样需要增加回归案例。
|
||||
|
||||
MVEL 本地支持范围以 `mvel-subset.ts` 为准,不等价完整 Java/MVEL 运行时。静态检查与本地求值分别报告问题和结果;不能用“本地通过”推断租户权限、服务端上下文或业务写入一定成功。
|
||||
|
||||
修改语法支持时增加支持/拒绝的回归案例,并保持沙箱资源释放。测试见 [index.test.ts](./index.test.ts)、[mvel-subset.test.ts](./mvel-subset.test.ts);命令适配在 [script.ts](../../../../cli/commands/workflow/script.ts),业务脚本编写参考位于 [MVEL 产品技能](../../../../../skills/hose-use/multi/ekuaibao-mvel/SKILL.md)。
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { hasReturnStatement, stripCommentsAndStrings, lintJavaScriptCode } from "./lint-js.js";
|
||||
|
||||
/**
|
||||
* return 检测曾经只跳过整行注释,行尾注释、块注释内部行和字符串里的 "return"
|
||||
* 都会让 missing-return 告警彻底失效。以下用例固定住这一修复。
|
||||
*/
|
||||
describe("JavaScript return detection", () => {
|
||||
it("finds real return statements", () => {
|
||||
expect(hasReturnStatement("return a + b;")).toBe(true);
|
||||
expect(hasReturnStatement("const x = 1;\nif (x) { return x; }\nreturn 0;")).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores returns in trailing comments", () => {
|
||||
expect(hasReturnStatement("const total = sum;\n// 记得 return 结果给下游")).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores returns inside block comments", () => {
|
||||
expect(hasReturnStatement("/*\nreturn 1;\n*/\nprepare();")).toBe(false);
|
||||
expect(hasReturnStatement("/* return 1 */ prepare();")).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores returns inside string literals", () => {
|
||||
expect(hasReturnStatement('log("return value: ");')).toBe(false);
|
||||
expect(hasReturnStatement("log('return value');")).toBe(false);
|
||||
expect(hasReturnStatement("log(`return ${x}`);")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat identifiers containing return as a return", () => {
|
||||
expect(hasReturnStatement("returnValue = 1;")).toBe(false);
|
||||
expect(hasReturnStatement("const return_of_day = 3;")).toBe(false);
|
||||
});
|
||||
|
||||
it("still detects a return that follows commented-out code", () => {
|
||||
expect(hasReturnStatement("// return 1;\nreturn 2;")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripCommentsAndStrings", () => {
|
||||
it("keeps code characters and blanks out comment bodies", () => {
|
||||
expect(stripCommentsAndStrings("// c\nkeep")).toBe(`${" ".repeat(4)}\nkeep`);
|
||||
const blockStripped = stripCommentsAndStrings("/* x */ keep");
|
||||
expect(blockStripped).toMatch(/^\s+keep$/);
|
||||
});
|
||||
|
||||
it("handles escaped quotes inside strings", () => {
|
||||
const stripped = stripCommentsAndStrings('"a\\"b" + x');
|
||||
expect(stripped).not.toContain('"');
|
||||
expect(stripped).toMatch(/\+\s*x$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lintJavaScriptCode missing-return reporting", () => {
|
||||
it("warns when only comments mention return", () => {
|
||||
const { issues } = lintJavaScriptCode("// 记得 return 值\nnormalize(data);");
|
||||
expect(issues.map((i) => i.rule)).toContain("missing-return");
|
||||
});
|
||||
|
||||
it("stays quiet when a real return exists", () => {
|
||||
const { issues, hasReturn } = lintJavaScriptCode("normalize(data);\nreturn data;");
|
||||
expect(hasReturn).toBe(true);
|
||||
expect(issues.map((i) => i.rule)).not.toContain("missing-return");
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,61 @@
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
|
||||
type ScanState = "code" | "lineComment" | "blockComment" | "singleQuote" | "doubleQuote" | "template";
|
||||
|
||||
/**
|
||||
* 检查代码中是否存在 return 关键字(排除纯注释中的 return)
|
||||
* 剔除注释与字符串字面量,其余字符原样保留、被剔除部分用空格占位(保持偏移便于将来定位)。
|
||||
* 覆盖行注释、块注释、单/双引号与模板串(含转义)。正则字面量中的 return 仍可能误判,
|
||||
* 由后续语法解析兜底。
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
const lines = code.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
||||
continue;
|
||||
}
|
||||
if (/\breturn\b/.test(trimmed)) {
|
||||
return true;
|
||||
export function stripCommentsAndStrings(code: string): string {
|
||||
let output = "";
|
||||
let state: ScanState = "code";
|
||||
let index = 0;
|
||||
while (index < code.length) {
|
||||
const char = code[index]!;
|
||||
const next = code[index + 1];
|
||||
switch (state) {
|
||||
case "code":
|
||||
if (char === "/" && next === "/") { state = "lineComment"; output += " "; index += 2; continue; }
|
||||
if (char === "/" && next === "*") { state = "blockComment"; output += " "; index += 2; continue; }
|
||||
if (char === "'" || char === '"' || char === "`") {
|
||||
state = char === "'" ? "singleQuote" : char === '"' ? "doubleQuote" : "template";
|
||||
output += " ";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
output += char;
|
||||
index += 1;
|
||||
continue;
|
||||
case "lineComment":
|
||||
if (char === "\n") { state = "code"; output += char; } else if (char !== "\r") { output += " "; }
|
||||
index += 1;
|
||||
continue;
|
||||
case "blockComment":
|
||||
if (char === "*" && next === "/") { state = "code"; output += " "; index += 2; continue; }
|
||||
output += char === "\n" ? char : " ";
|
||||
index += 1;
|
||||
continue;
|
||||
default: {
|
||||
if (char === "\\") { output += " "; index += 2; continue; }
|
||||
const closer = state === "singleQuote" ? "'" : state === "doubleQuote" ? '"' : "`";
|
||||
if (char === closer) { state = "code"; output += " "; index += 1; continue; }
|
||||
output += char === "\n" ? char : " ";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断脚本是否真的写了 return。
|
||||
* 先前只跳过整行注释,行尾注释 `// return`、块注释内部行与字符串里的 "return"
|
||||
* 都会被当成真语句,导致 missing-return 告警永不触发。
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
return /\breturn\b/.test(stripCommentsAndStrings(code));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,10 +34,9 @@ export {
|
||||
createWorkflow,
|
||||
deleteWorkflow,
|
||||
toggleWorkflow,
|
||||
type CreateWorkflowOptions,
|
||||
} from "./management/configuration.js";
|
||||
export type {
|
||||
CreateWorkflowOptions,
|
||||
} from "./management/configuration.js";
|
||||
export type { WorkflowToggleResult } from "./models/workflow.js";
|
||||
export {
|
||||
listDsl,
|
||||
listStaffs,
|
||||
|
||||
@@ -19,8 +19,8 @@ import {
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
} from "../api.js";
|
||||
import { toggleWorkflow } from "../management/configuration.js";
|
||||
import {
|
||||
extractFailureExecutions,
|
||||
findExecutionNode,
|
||||
@@ -30,9 +30,6 @@ import {
|
||||
sanitizeWorkflowSnapshot,
|
||||
} from "../services.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "../alert/index.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const workflow = (overrides: Partial<WorkflowDetail> = {}): WorkflowDetail => WorkflowDetailSchema.parse({
|
||||
id: "wf-1",
|
||||
@@ -144,45 +141,47 @@ describe("workflow draft state machine", () => {
|
||||
expect(result.items[0]?.message).toBe("测试错误");
|
||||
});
|
||||
|
||||
it("uses the state endpoint for publishing a workflow", async () => {
|
||||
it("uses the state endpoint for publishing a workflow and confirms the new state", async () => {
|
||||
let request: { url: string; options: any } | undefined;
|
||||
const client = {
|
||||
put: async (url: string, options: any) => {
|
||||
request = { url, options };
|
||||
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
|
||||
},
|
||||
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 1, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
|
||||
} as any;
|
||||
const result = await toggleWorkflow(client, "wf-1", 1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.verified).toBe(true);
|
||||
expect(result.state).toBe(1);
|
||||
expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
|
||||
expect(request?.options.searchParams).toEqual({ state: "1" });
|
||||
});
|
||||
|
||||
it("persists workflow alert fingerprints and only reports new counts", () => {
|
||||
const dir = mkdtempSync("hose-workflow-alert-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const store = new WorkflowAlertStore(file);
|
||||
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([{ ...alert, observedAt: 2 }]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, errorCount: 2, observedAt: 3 }]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, observedAt: 4 }]).newAlerts).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
it("refuses to claim success when the server keeps the old state", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
|
||||
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 0, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
|
||||
} as any;
|
||||
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("启停未生效");
|
||||
});
|
||||
|
||||
it("preserves previously observed alerts when a scan is incomplete", () => {
|
||||
const dir = mkdtempSync("hose-workflow-alert-partial-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const store = new WorkflowAlertStore(file);
|
||||
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
store.observe([], { complete: false });
|
||||
expect(store.observe([{ ...alert, observedAt: 2 }], { complete: false }).newAlerts).toHaveLength(0);
|
||||
store.observe([], { complete: true });
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
it("reports business failures carried by HTTP 200 responses", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 500, msg: "流程存在非法节点" }), { status: 200 }),
|
||||
} as any;
|
||||
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("流程存在非法节点");
|
||||
});
|
||||
|
||||
it("does not claim success when the confirmation read fails", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
|
||||
get: async () => new Response(JSON.stringify({ code: 401, msg: "凭证过期" }), { status: 200 }),
|
||||
} as any;
|
||||
const result = await toggleWorkflow(client, "wf-1", 0);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.verified).toBe(false);
|
||||
expect(result.state).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks dirty revisions and commits the server snapshot", () => {
|
||||
|
||||
@@ -7,3 +7,20 @@
|
||||
- [response.ts](./response.ts):EASO/Piper 响应和写入结果校验。
|
||||
|
||||
上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。
|
||||
|
||||
## 写入结果判定
|
||||
|
||||
所有写操作(保存、刷新 chooses、删除、启停)统一走 `readEasoWriteResponse`:先按 HTTP 状态,再解析 body 中的业务码 `code`。
|
||||
**HTTP 200 不等于业务成功**,只看状态码会把未生效的写操作报成成功。
|
||||
|
||||
## 灰度节点开通 (grantWorkflowNodesApi)
|
||||
|
||||
| 项目 | 说明 |
|
||||
|---|---|
|
||||
| 换票 | 通过企业 `baseUrl` 的 `/api/engine/realm/$EASO/actions/jwt` 获取 EASO JWT;复用 `fetchEasoJwt`,去除 `baseUrl` 末尾斜线 |
|
||||
| 开通请求 | 携带 EASO JWT 直接 POST 到 Piper 的 `/api/easo/dsl/corporation`;默认使用 `SCRIPT_ENGINE_BASE_URL`,`isTest: true` 时使用 `https://piper-test.ekuaibao.net`。每个企业的工作流只在其中一个 Piper 环境,不会同时支持两者;请求失败时不自动切换 |
|
||||
| 成功判定 | 检查 Piper 响应业务码 `code === 200`;HTTP 200 本身不作为成功依据 |
|
||||
| 结果 | 保留服务端消息,并将新开通节点映射到 `saved`、已开通节点映射到 `skipped` |
|
||||
| 凭证 | access token 与 EASO JWT 只用于本机直连请求,不写入日志或返回结果 |
|
||||
|
||||
环境由调用方显式选择:`isTest` 只切换 Piper 目标地址,不由企业名称、本地 `env=test` 或 EASO 换票使用的 `baseUrl` 推断。通过某一环境成功开通能确认企业对应的工作流环境;另一环境对同一企业不适用。`--dry-run` 不会发请求或探测环境,失败响应还需结合认证与业务错误判断,不能仅凭失败认定环境选错。
|
||||
@@ -1,6 +1,7 @@
|
||||
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, SCRIPT_ENGINE_BASE_URL } from "../../../../../core/http/script-engine-client.js";
|
||||
import { WorkflowDslSchema, WorkflowDslCatalogSchema, StaffSchema, WorkflowEnumItemSchema, type WorkflowEnumItem } from "../../types.js";
|
||||
import { unwrap } from "../response.js";
|
||||
|
||||
@@ -69,36 +70,92 @@ export async function getWorkflowEnumOptions(
|
||||
return unwrap(response, z.array(WorkflowEnumItemSchema));
|
||||
}
|
||||
|
||||
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
|
||||
// ── 灰度节点开通 (EASO -> Piper) ─────────────────────────────────────────────
|
||||
|
||||
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();
|
||||
|
||||
export const SCRIPT_ENGINE_TEST_BASE_URL = "https://piper-test.ekuaibao.net";
|
||||
|
||||
function normalizeEkbBaseUrl(baseUrl?: string): string {
|
||||
return (baseUrl || "https://app.ekuaibao.com").trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function parseNodeNames(message: string): string[] {
|
||||
const match = message.match(/(?:新开通的节点|以下节点已开通[^::]*|已开通[^::]*节点)[::]\s*(.+)$/);
|
||||
return match?.[1]
|
||||
.split(/[,,、\s]+/)
|
||||
.map((node) => node.trim())
|
||||
.filter(Boolean) ?? [];
|
||||
}
|
||||
|
||||
export async function grantWorkflowNodesApi(options: {
|
||||
token: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
nodes: string[];
|
||||
isTest?: boolean;
|
||||
/** 目标企业合思地址,用于 EASO JWT 换票。 */
|
||||
baseUrl?: string;
|
||||
}): Promise<import("../../types.js").GrantWorkflowNodesResult> {
|
||||
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,
|
||||
);
|
||||
}
|
||||
const payload = {
|
||||
token: options.token,
|
||||
corpId: options.corpId,
|
||||
nodes: options.nodes.join(","),
|
||||
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
||||
corporationId: options.corpId,
|
||||
dslTypes: options.nodes,
|
||||
"recalculate-the-approval-flow": true,
|
||||
"ui-notification": true,
|
||||
start: 0,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await ky.post("https://d9jxeccs5j.sealosgzg.site/hose-workflow-node", {
|
||||
// 每个企业的工作流只对应标准或测试 Piper 之一;显式选择,不探测或自动回退。
|
||||
const piperBaseUrl = options.isTest ? SCRIPT_ENGINE_TEST_BASE_URL : SCRIPT_ENGINE_BASE_URL;
|
||||
const response = await ky.post(`${piperBaseUrl}/api/easo/dsl/corporation`, {
|
||||
json: payload,
|
||||
timeout: 30000,
|
||||
headers: { Authorization: `Bearer ${easoJwt}` },
|
||||
timeout: 15000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
const json = WorkflowNodeGrantResponseSchema.parse(await response.json());
|
||||
const rawMessage = json.msg || "";
|
||||
const saved = json.data?.saved ?? (Number(json.code) === 200 && rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
const skipped = json.data?.skipped ?? (Number(json.code) === 200 && rawMessage.includes("已开通") && !rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
|
||||
return {
|
||||
success: Boolean(json?.success ?? true),
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
success: Number(json.code) === 200,
|
||||
saved,
|
||||
skipped,
|
||||
rawMessage,
|
||||
isTest: Boolean(options.isTest),
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败: ${message}`, "GATEWAY_ERROR", 502);
|
||||
if (err instanceof EkbError) throw err;
|
||||
throw new EkbApiError(`灰度节点开通 Piper 请求失败: ${message}`, "PIPER_ERROR", 502);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
import { grantWorkflowNodesApi, SCRIPT_ENGINE_TEST_BASE_URL } from "./catalog/api.js";
|
||||
|
||||
describe("grantWorkflowNodesApi direct Piper request", () => {
|
||||
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 requested node types to Piper", 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: "新开通的节点:recalculate-the-approval-flow" }),
|
||||
};
|
||||
}) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["recalculate-the-approval-flow"],
|
||||
baseUrl: "https://app.ekuaibao.com///",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
saved: ["recalculate-the-approval-flow"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:recalculate-the-approval-flow",
|
||||
isTest: false,
|
||||
});
|
||||
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({
|
||||
corporationId: "corp-1",
|
||||
dslTypes: ["recalculate-the-approval-flow"],
|
||||
"recalculate-the-approval-flow": true,
|
||||
"ui-notification": true,
|
||||
start: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports already-open nodes as skipped", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 200, msg: "以下节点已开通,不再重复开通:code" }),
|
||||
})) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.saved).toEqual([]);
|
||||
expect(result.skipped).toEqual(["code"]);
|
||||
expect(result.isTest).toBe(false);
|
||||
});
|
||||
|
||||
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));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
isTest: true,
|
||||
});
|
||||
|
||||
expect(requestedUrl).toBe(`${SCRIPT_ENGINE_TEST_BASE_URL}/api/easo/dsl/corporation`);
|
||||
expect(result.isTest).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat an HTTP 200 with a failing business code as success", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 500, msg: "JWT 签名无效" }),
|
||||
})) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
});
|
||||
|
||||
expect(result).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",
|
||||
nodes: ["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",
|
||||
nodes: ["code"],
|
||||
})).rejects.toThrow("灰度节点开通 Piper 请求失败: connect ETIMEDOUT");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { WorkflowPageSchema, WorkflowStatsSchema, WorkflowChargeSchema, WorkflowDetailSchema, WorkflowSnapshotSchema, WorkflowSnapshotPageSchema, WorkflowLogPageSchema } from "../../types.js";
|
||||
import type { WorkflowState } from "../../types.js";
|
||||
import { unwrap, readEasoWriteResponse, ok } from "../response.js";
|
||||
import { unwrap, readEasoWriteResponse } from "../response.js";
|
||||
|
||||
// ── 工作流(EASO)─────────────────────────────────────────────────────────────
|
||||
// 注意:EASO 客户端已自动注入 corpId,无需再传
|
||||
@@ -166,13 +166,18 @@ export async function listWorkflowLogs(
|
||||
|
||||
// ── 工作流启停(Piper)────────────────────────────────────────────────────────
|
||||
|
||||
export async function toggleWorkflow(
|
||||
/**
|
||||
* 工作流启停写操作。响应必须走 `readEasoWriteResponse` 校验业务码:
|
||||
* HTTP 200 也可能携带 code != 200 的业务失败,只看状态码会把未生效的启停报成成功。
|
||||
* 是否真的生效由上层回读详情确认,本层不做推断。
|
||||
*/
|
||||
export async function toggleWorkflowState(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
state: WorkflowState
|
||||
): Promise<{ success: boolean }> {
|
||||
): Promise<void> {
|
||||
const response = await client.put(`api/easo/pipelines/state/${pipelineId}`, {
|
||||
searchParams: { state: String(state) },
|
||||
});
|
||||
return ok(response);
|
||||
await readEasoWriteResponse(response);
|
||||
}
|
||||
@@ -54,8 +54,3 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
export async function ok(response: Response): Promise<{ success: boolean }> {
|
||||
return { success: response.status === 200 };
|
||||
}
|
||||
@@ -1,25 +1,25 @@
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
import type { WatchWorkflowOptions, WorkflowWatchEvent } from "./types.js";
|
||||
|
||||
export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
// Job 状态判定统一来自 execution/job-status.ts,watch 与 debug 共用同一套语义。
|
||||
export { normalizeJobStatus, isJobTerminal, TERMINAL_JOB_STATES } from "../execution/job-status.js";
|
||||
|
||||
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||
if (!job) return "UNKNOWN";
|
||||
const rawStatus = (job as any).status;
|
||||
const rawState = (job as any).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
const s = rawStatus.trim().toUpperCase();
|
||||
if (s === "STARTED") return "RUNNING";
|
||||
return s;
|
||||
}
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_STATES.has(status.toUpperCase());
|
||||
/**
|
||||
* `--failed-only` 的事件过滤。此前的实现在两个监听入口各写了一份且逐字相同,
|
||||
* 任一侧漏改都会让两种监听模式给出不同的结果。
|
||||
*/
|
||||
export function shouldEmitWatchEvent(
|
||||
event: WorkflowWatchEvent,
|
||||
options: Pick<WatchWorkflowOptions, "failedOnly">
|
||||
): boolean {
|
||||
if (!options.failedOnly) return true;
|
||||
return (
|
||||
event.type === "task_failed" ||
|
||||
(event.type === "task_skipped" && Boolean(event.error)) ||
|
||||
event.type === "job_completed" ||
|
||||
event.type === "timeout" ||
|
||||
event.type === "cancelled"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js";
|
||||
import { watchSingleJob } from "./single-job.js";
|
||||
|
||||
/**
|
||||
@@ -21,16 +21,7 @@ export async function watchWorkflowPipeline(
|
||||
const seenJobIds = new Set<string>();
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout" && event.type !== "cancelled"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!shouldEmitWatchEvent(event, options)) return;
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js";
|
||||
import { TaskExecutionTracker } from "./tracker.js";
|
||||
|
||||
/**
|
||||
@@ -20,16 +20,7 @@ export async function watchSingleJob(
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout" && event.type !== "cancelled"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!shouldEmitWatchEvent(event, options)) return;
|
||||
events.push(event);
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
|
||||
@@ -50,6 +50,40 @@ export async function fetchClientGoods(
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用是否处于「已开通」状态。
|
||||
*
|
||||
* 只看 `status`,不看 `onLineStatus` —— 后者表示应用是否在架,
|
||||
* 已购买但已下架的应用仍然可以正常调用其开放接口。
|
||||
*/
|
||||
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
|
||||
return item.status?.toUpperCase() === "OPENED";
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总当前企业**已开通**应用所提供的权限代码(统一小写,便于大小写不敏感比对)。
|
||||
*
|
||||
* 用于在保存工作流时判断「节点要调的接口,企业到底有没有买对应的应用」。
|
||||
* 典型场景:调用 `/api/openapi/v1/backlog/data/*`(单据审批)需要
|
||||
* `TICKET_AUDIT_switch`,未开通时运行期只会返回 403「未开通功能,无权访问」。
|
||||
*/
|
||||
export async function fetchOpenedPowerCodes(corp: CorpConfig): Promise<Set<string>> {
|
||||
const goods = await fetchClientGoods(corp, { isAll: true });
|
||||
const codes = new Set<string>();
|
||||
for (const item of goods) {
|
||||
if (!isClientGoodOpened(item)) continue;
|
||||
for (const power of item.powers ?? []) {
|
||||
if (typeof power === "string") {
|
||||
if (power.trim()) codes.add(power.trim().toLowerCase());
|
||||
continue;
|
||||
}
|
||||
const code = power?.powerCode;
|
||||
if (code && code.trim()) codes.add(code.trim().toLowerCase());
|
||||
}
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
export async function searchGoods(
|
||||
corp: CorpConfig,
|
||||
options: { keyword?: string; start?: number; count?: number } = {}
|
||||
|
||||
+49
-16
@@ -1,6 +1,7 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
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 { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
@@ -28,7 +29,12 @@ function checkHttpAuth(req: IncomingMessage): boolean {
|
||||
return authHeader === `Bearer ${requiredToken}`;
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
export async function handleHttpRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
options: { app?: "hose-use" | "hose-aipro" } = {}
|
||||
): Promise<void> {
|
||||
const isAiPro = options.app === "hose-aipro";
|
||||
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
|
||||
const trustedOrigin = isTrustedOrigin(origin);
|
||||
|
||||
@@ -59,32 +65,59 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
try {
|
||||
// 2. Metadata & Health
|
||||
if (method === "GET" && pathname === "/") {
|
||||
sendJson(res, 200, {
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
rawOpenapi: "/raw-openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
corps: "GET /v1/corps",
|
||||
},
|
||||
});
|
||||
sendJson(
|
||||
res,
|
||||
200,
|
||||
isAiPro
|
||||
? {
|
||||
name: "hose-aipro",
|
||||
version: VERSION,
|
||||
description: "合思 AI PRO 确定性审批仲裁网关 HTTP 服务",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
status: "GET /v1/status",
|
||||
},
|
||||
}
|
||||
: {
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
rawOpenapi: "/raw-openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
corps: "GET /v1/corps",
|
||||
},
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/health") {
|
||||
sendJson(res, 200, {
|
||||
status: "ok",
|
||||
name: "hose-use",
|
||||
name: isAiPro ? "hose-aipro" : "hose-use",
|
||||
version: VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAiPro && method === "GET" && pathname === "/v1/status") {
|
||||
const statusRes = await runAiProCli(["status", "--json"]);
|
||||
let parsedData: any = {};
|
||||
try {
|
||||
parsedData = JSON.parse(statusRes.stdout);
|
||||
} catch {
|
||||
parsedData = { stdout: statusRes.stdout };
|
||||
}
|
||||
sendJson(res, 200, parsedData);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
@@ -119,7 +152,7 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
const tokens = tokenizeCommand(command);
|
||||
const cliArgs = normalizeCliArgs(tokens);
|
||||
const result = await runCli(cliArgs);
|
||||
const result = isAiPro ? await runAiProCli(cliArgs) : await runCli(cliArgs);
|
||||
|
||||
let parsedData: unknown = undefined;
|
||||
const trimmedStdout = result.stdout.trim();
|
||||
|
||||
+17
-6
@@ -6,18 +6,22 @@ export type HttpServerOptions = {
|
||||
port?: number;
|
||||
host?: string;
|
||||
silent?: boolean;
|
||||
app?: "hose-use" | "hose-aipro";
|
||||
};
|
||||
|
||||
export const DEFAULT_HTTP_PORT = 8888;
|
||||
export const DEFAULT_AIPRO_HTTP_PORT = 8889;
|
||||
export const DEFAULT_HTTP_HOST = "127.0.0.1";
|
||||
|
||||
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = options.app === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
await handleHttpRequest(req, res, { app: options.app || "hose-use" });
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
||||
@@ -33,12 +37,19 @@ export async function startHttpServer(options: HttpServerOptions = {}): Promise<
|
||||
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
|
||||
const appName = isAiPro ? "hose-aipro" : "hose-use";
|
||||
console.error(`\n⚡ ${appName} HTTP Server (v${VERSION}) 已启动`);
|
||||
console.error(` 主服务地址: http://${host}:${port}`);
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
if (!isAiPro) {
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
}
|
||||
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
if (!isAiPro) {
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
} else {
|
||||
console.error(` 网关状态接口: GET http://${host}:${port}/v1/status\n`);
|
||||
}
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
|
||||
@@ -2,65 +2,86 @@ import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
import {
|
||||
EMBEDDED_HOSE_USE_SKILL_FILES,
|
||||
EMBEDDED_AIPRO_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getDefaultAiProGlobalSkillDir,
|
||||
getSkillContent,
|
||||
getAiProSkillContent,
|
||||
installSkillFiles,
|
||||
installHoseUseSkillFiles,
|
||||
installAiProSkillFiles,
|
||||
} from "./embedded-skill.js";
|
||||
|
||||
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
|
||||
describe("embedded-skill - 双 Skill 体系内嵌与分发 (hose-use 与 hose-aipro)", () => {
|
||||
test("全局 Skill 目录分别固定为 ~/.agents/skills/hose-use 与 hose-aipro", () => {
|
||||
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
|
||||
expect(getDefaultAiProGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-aipro"));
|
||||
});
|
||||
|
||||
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
test("hose-use: 正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
expect(getSkillContent()).toContain("name: hose-use");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toContain("POST /api/cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toContain("hose-use aipro");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
|
||||
// 套件结构:根入口路由到 multi/ 下的子技能
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
test("hose-aipro: 正确内嵌 SKILL.md、agents/openai.yaml、approval.md 与 service.md", () => {
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toContain("name: hose-aipro");
|
||||
expect(getAiProSkillContent()).toContain("name: hose-aipro");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toContain("command: \"hose-aipro\"");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toContain("hose-aipro decide");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toContain("8889");
|
||||
});
|
||||
|
||||
test("installSkillFiles 显式路径安装保留层级结构", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "hose-skill-test-"));
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
const res = installHoseUseSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(19);
|
||||
expect(res.files.length).toBe(18);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "feetype.md"))).toBe(true);
|
||||
@@ -74,4 +95,19 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("installAiProSkillFiles 正确落盘 hose-aipro 专属技能文件", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "aipro-skill-test-"));
|
||||
try {
|
||||
const res = installAiProSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(5);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
// ── hose-use Skill 文件 ────────────────────────────────────────────────────────
|
||||
import skillMain from "../../skills/hose-use/SKILL.md" with { type: "text" };
|
||||
import agentOpenAi from "../../skills/hose-use/agents/openai.yaml" with { type: "text" };
|
||||
import refAuth from "../../skills/hose-use/references/auth.md" with { type: "text" };
|
||||
@@ -13,7 +14,6 @@ import refTask from "../../skills/hose-use/references/task.md" with { type: "tex
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
|
||||
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
|
||||
import refAssistPlatform from "../../skills/hose-use/references/assist-platform.md" with { type: "text" };
|
||||
@@ -22,11 +22,17 @@ import multiMvelAgent from "../../skills/hose-use/multi/ekuaibao-mvel/agents/ope
|
||||
import multiNodes from "../../skills/hose-use/multi/ekuaibao-nodes/SKILL.md" with { type: "text" };
|
||||
import multiNodesGray from "../../skills/hose-use/multi/ekuaibao-nodes/references/gray-nodes.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
// ── hose-aipro Skill 文件 ──────────────────────────────────────────────────────
|
||||
import aiproSkillMain from "../../skills/hose-aipro/SKILL.md" with { type: "text" };
|
||||
import aiproAgentOpenAi from "../../skills/hose-aipro/agents/openai.yaml" with { type: "text" };
|
||||
import aiproRefApproval from "../../skills/hose-aipro/references/approval.md" with { type: "text" };
|
||||
import aiproRefService from "../../skills/hose-aipro/references/service.md" with { type: "text" };
|
||||
import aiproRefReadme from "../../skills/hose-aipro/references/README.references.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_HOSE_USE_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
"agents/openai.yaml": agentOpenAi,
|
||||
"references/auth.md": refAuth,
|
||||
"references/approval.md": refApproval,
|
||||
"references/bill.md": refBill,
|
||||
"references/feetype.md": refFeeType,
|
||||
"references/contact.md": refContact,
|
||||
@@ -44,36 +50,92 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"multi/ekuaibao-nodes/references/gray-nodes.md": multiNodesGray,
|
||||
};
|
||||
|
||||
export const EMBEDDED_AIPRO_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": aiproSkillMain,
|
||||
"agents/openai.yaml": aiproAgentOpenAi,
|
||||
"references/approval.md": aiproRefApproval,
|
||||
"references/service.md": aiproRefService,
|
||||
"references/README.references.md": aiproRefReadme,
|
||||
};
|
||||
|
||||
// 保持模块级向后兼容
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = EMBEDDED_HOSE_USE_SKILL_FILES;
|
||||
|
||||
export function getSkillContent(): string {
|
||||
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
|
||||
return EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getAiProSkillContent(): string {
|
||||
return EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getDefaultGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-use");
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
export function getDefaultAiProGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-aipro");
|
||||
}
|
||||
|
||||
export function installHoseUseSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) {
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_HOSE_USE_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return {
|
||||
targetDir,
|
||||
files: installed,
|
||||
};
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string } {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
installSkillFiles(globalDir);
|
||||
return { synced: true, targetDir: globalDir };
|
||||
export function installAiProSkillFiles(targetDir: string = getDefaultAiProGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_AIPRO_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
skills?: string[];
|
||||
} {
|
||||
const defaultGlobalDir = getDefaultGlobalSkillDir();
|
||||
// 当为全局默认目录时,自动同时安装两个 Skill
|
||||
if (targetDir === defaultGlobalDir) {
|
||||
const hoseRes = installHoseUseSkillFiles(defaultGlobalDir);
|
||||
const aiproRes = installAiProSkillFiles(getDefaultAiProGlobalSkillDir());
|
||||
return {
|
||||
targetDir,
|
||||
files: [...hoseRes.files, ...aiproRes.files.map((f) => `hose-aipro/${f}`)],
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
}
|
||||
|
||||
// 显式指定自定义目录时,在该目录下安装 hose-use 文件
|
||||
return installHoseUseSkillFiles(targetDir);
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string; targetDirs: string[] } {
|
||||
const hoseDir = getDefaultGlobalSkillDir();
|
||||
const aiproDir = getDefaultAiProGlobalSkillDir();
|
||||
installHoseUseSkillFiles(hoseDir);
|
||||
installAiProSkillFiles(aiproDir);
|
||||
return { synced: true, targetDir: hoseDir, targetDirs: [hoseDir, aiproDir] };
|
||||
}
|
||||
Reference in new issue
Block a user