Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e51dc9db5 | ||
|
|
e9f6caa76f | ||
|
|
df7b583014 | ||
|
|
dd67c88f49 | ||
|
|
debfdec77d | ||
|
|
d7a7203eeb | ||
|
|
86a02b82b7 | ||
|
|
5e59c835f1 | ||
|
|
f9422ee431 | ||
|
|
41503917ce | ||
|
|
6f60803c66 | ||
|
|
c63ec24344 | ||
|
|
35a118c456 | ||
|
|
0e8d844f3f | ||
|
|
d65a906fb3 | ||
|
|
df25d7b187 | ||
|
|
adebbcfffb | ||
|
|
b0b23f0c23 | ||
|
|
9e191f2ef8 | ||
|
|
5be2bd5432 | ||
|
|
038aca10fb | ||
|
|
9b780c345d | ||
|
|
d38eaecc12 | ||
|
|
4b4a7049a0 | ||
|
|
baec8be6d3 | ||
|
|
833cdf8573 | ||
|
|
d6d5d2d732 | ||
|
|
8b0346221f | ||
|
|
235e4b806d | ||
|
|
4ea73ef322 | ||
|
|
edafe8d086 | ||
|
|
b787130880 | ||
|
|
54382ae7ce | ||
|
|
950e97eacc | ||
|
|
85992e29ce | ||
|
|
42bf0bfb0b | ||
|
|
62b47f5ad7 | ||
|
|
83dacf90c4 | ||
|
|
1c5d6153a2 | ||
|
|
6ba748e531 | ||
|
|
9cf247fe45 | ||
|
|
4f572ad9c1 | ||
|
|
448dd438ff | ||
|
|
cfd0c48a8b | ||
|
|
b7fda124fd | ||
|
|
e00adbe5a8 | ||
|
|
75a0611f0e | ||
|
|
75740c4ec3 | ||
|
|
22215eb317 | ||
|
|
0c9eb27f85 | ||
|
|
ea5eb22c51 | ||
|
|
e588416a5f | ||
|
|
de88e218e7 | ||
|
|
020e4a2761 | ||
|
|
e7e856bbb0 | ||
|
|
bfbf6cf55f | ||
|
|
f3caebfd8a | ||
|
|
1eeb288143 | ||
|
|
4272dd8e60 | ||
|
|
7666db9f1d | ||
|
|
f9de8337b2 | ||
|
|
4beafe40cc | ||
|
|
3710f50ea4 | ||
|
|
55573de6a8 | ||
|
|
50362c2937 | ||
|
|
36e21e5dc2 | ||
|
|
b51152276d | ||
|
|
901fa072d3 | ||
|
|
ecab64477f | ||
|
|
13c47d7569 | ||
|
|
d772ff0164 | ||
|
|
8375445bcb | ||
|
|
876dcc7175 | ||
|
|
a71f1675b8 | ||
|
|
384f611a26 | ||
|
|
f465979ec3 | ||
|
|
6fef188f2f | ||
|
|
417be3ef54 | ||
|
|
46fa2597d0 | ||
|
|
957cb04324 | ||
|
|
19d8fd3c59 | ||
|
|
dfb464605e | ||
|
|
fb29ff630a | ||
|
|
c8adf0e051 | ||
|
|
e58841e164 | ||
|
|
e562ae9227 | ||
|
|
07a8a792af | ||
|
|
731e67377c | ||
|
|
4be87d448a | ||
|
|
a1cc808717 | ||
|
|
bb60053072 | ||
|
|
23f12f17c5 | ||
|
|
c46a140ac4 | ||
|
|
8ff0e5ff52 | ||
|
|
7d09a8400a | ||
|
|
f0dde0083e | ||
|
|
7a19fa8337 |
No files matched your search
@@ -10,7 +10,9 @@
|
||||
| [production-safety.md](./production-safety.md) | 操作真实企业前;确认只读/写入范围、预演、凭证脱敏要求 |
|
||||
| [tenant-and-credential.md](./tenant-and-credential.md) | 多租户身份、协助链接和凭证导入,以及个人单据查询 |
|
||||
| [testing-and-dev-hygiene.md](./testing-and-dev-hygiene.md) | 编写测试、隔离环境、处理非交互输入与提交验证 |
|
||||
| [troubleshooting-and-investigation.md](./troubleshooting-and-investigation.md) | 业务排障诊断、探针环境隔离,以及沉淀优先原则 |
|
||||
| [typescript-style.md](./typescript-style.md) | TypeScript、ESM 导入和运行时模型修改 |
|
||||
|
||||
| [windows-development.md](./windows-development.md) | 跨平台路径、分支命名、换行及文件名兼容 |
|
||||
|
||||
## 维护边界
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: "排障诊断、探针环境与正式环境隔离,以及沉淀优先原则"
|
||||
globs: "src/**/*.{ts,md}"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 业务排障与系统探查铁律(Troubleshooting & Investigation Rules)
|
||||
|
||||
本规则总结自多租户、工作流与审批流联动真实排障过程中的典型教训,面向所有在此仓库进行业务排查与功能迭代的 AI Agent。
|
||||
|
||||
---
|
||||
|
||||
## 1. 探针环境与业务目标企业严格隔离(Probe vs. Target Boundary)
|
||||
|
||||
在面对未知系统接口、未逆向的页面交互或存在破坏性风险的操作时,用户常会引导 Agent「先去测试企业(如沈玥妍测试企业)摸一下/探查一下」:
|
||||
|
||||
1. **明确行为性质是“探针(Probe)”而非“诊断结论”**:
|
||||
- 访问测试企业的**唯一目的**是:安全抓包、获取底层 API 路径、探明请求/响应 JSON Schema 或验证逆向结论。
|
||||
- **绝对禁止将探针环境的现状当作业务问题的根因**:例如测试企业的出站规则停用,绝不代表目标正式企业的单据卡住是因为规则停用。
|
||||
2. **探针完毕后必须立即主动切回业务企业**:
|
||||
- 一旦在测试企业摸清 API 契约与数据结构,必须**自动、毫不犹豫地切换回用户最初声明的问题主体(目标正式企业与员工身份)**执行只读验证;
|
||||
- 绝不能等用户反问“你在说什么、为什么不看某某所在的正式企业”才被动纠正。
|
||||
|
||||
---
|
||||
|
||||
## 2. 沉淀优先于临时脚本(Productization First)
|
||||
|
||||
在排障过程中,当发现需要调用尚未被 CLI 封装的系统内部接口(如系统出站消息规则 `GET api/outbound/v1/message`、投递日志 `POST api/outbound/v1/message/messageLog` 等)时:
|
||||
|
||||
1. **严禁随手编写 ad-hoc 一次性脚本(`scratch_*.ts`)解决眼前问题**:
|
||||
- 一次性脚本容易陷入路径引用、未导出函数、临时编译报错等低价值泥潭;
|
||||
- 一次性脚本无法给用户留下可复现、可交付的资产。
|
||||
2. **标准研发流:边排障边沉淀到工程体系**:
|
||||
- 按照分层架构规范,第一时间将接口接入:
|
||||
$$\text{transport/ (API 校验)} \rightarrow \text{services.ts (业务门面)} \rightarrow \text{cli/commands/ (用户命令)} \rightarrow \text{command-metadata.ts (参数契约)}$$
|
||||
- 补齐最小单元测试,保证 `bun test` 与 `bun run check` 通过;
|
||||
- **直接使用自身编译/运行的官方 CLI 命令(例如 `hose-use workflow outbound logs ...`)为用户输出排查结果**。
|
||||
3. **闭环 PR 与本地重载**:
|
||||
- 查完问题后,主动通过标准 PR 流程将能力合入主分支;
|
||||
- 执行 `bun run dev:override` 重新编译安装本地开发二进制与 Skill,保持环境资产最新。
|
||||
|
||||
---
|
||||
|
||||
## 3. 合思审批流与工作流联动排障心智模型(Mental Model)
|
||||
|
||||
当遇到“新提交的单据卡在工作流计算节点,且工作流运行日志没有任何记录”时,必须建立**全链路事件下发**的全局排查视角:
|
||||
|
||||
$$\text{单据提交审批} \xrightarrow{\text{审批流出站节点}} \text{系统出站规则 (Outbound)} \xrightarrow{\text{HTTP Webhook}} \text{工作流触发器 (Piper)} \xrightarrow{\text{OpenAPI}} \text{回写/推进节点}$$
|
||||
|
||||
排查漏斗四步法:
|
||||
1. **看出站规则列表(`workflow outbound list`)**:
|
||||
- 检查企业内是否存在类型为 `flow` 的出站规则;
|
||||
- 检查规则是否启用(`enable: true`),且其 `callbackUrl` 是否指向目标工作流的 Webhook 路径。
|
||||
2. **看出站投递日志(`workflow outbound logs <单号>`)**:
|
||||
- 若**完全无记录**:说明单据流转时未匹配上任何出站规则(常见原因:审批流中的出站节点未关联出站规则,或单据模板类型不在出站规则适用范围);
|
||||
- 若**有记录但状态为 FAILED**:查看日志中的 `request` 与目标服务器返回的 `response`(错误码、超时或 404 等)。
|
||||
3. **看工作流日志(`workflow logs <workflowId>`)**:
|
||||
- 若出站日志记录为 SUCCESS,但工作流日志为 0,排查 Webhook 载荷格式与工作流触发器入参映射是否脱节。
|
||||
4. **看单据类型契约(`formSpecification`)**:
|
||||
- 检查历史成功单据与卡住单据的表单规范(如「商机费用报销」vs「差旅费报销单」),核对工作流内代码节点或查询节点是否写死了特定单据模板 ID。
|
||||
@@ -21,3 +21,19 @@
|
||||
|
||||
# MCP Server 总开关(默认关闭)
|
||||
# HOSE_USE_MCP_ENABLED=true
|
||||
|
||||
# Piper / ScriptEngine 集群地址(默认 piper.ekuaibao.com / piper-test.ekuaibao.net)
|
||||
# 私有化或多集群部署可覆盖;影响工作流引擎客户端、Webhook 触发 URL 与灰度节点开通。
|
||||
# HOSE_PIPER_BASE_URL=https://piper.ekuaibao.com
|
||||
# HOSE_PIPER_TEST_BASE_URL=https://piper-test.ekuaibao.net
|
||||
|
||||
# AI PRO 离线凭证(默认 ~/.config/hose-use/aipro-license.token,0600)
|
||||
# 仅 hose-aipro 需要凭证;hose-use 是免费功能,不受凭证管辖。
|
||||
# HOSE_AIPRO_LICENSE_FILE=~/.config/hose-use/aipro-license.token
|
||||
|
||||
# 签发方专用(只在本机签发凭证时使用,客户端运行不需要)
|
||||
# HOSE_AIPRO_LICENSE_PRIVATE_KEY=<PEM 文本,切勿提交仓库>
|
||||
# HOSE_AIPRO_LICENSE_PRIVATE_FILE=~/.config/hose-use/license/private.pem
|
||||
|
||||
# 灰度节点开通的可选管理员密码(设置后需 --password)
|
||||
# HOSE_ADMIN_PASSWORD=<管理员密码>
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
@@ -183,9 +183,9 @@ jobs:
|
||||
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
|
||||
filename=$(basename "$file")
|
||||
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
|
||||
for attempt in 1 2 3; do
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
|
||||
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/5)..."
|
||||
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
|
||||
continue
|
||||
fi
|
||||
@@ -212,24 +212,16 @@ jobs:
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
echo "::error::Failed to upload ${filename} after 5 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
# 串行上传:Gitea 维护期并发推大文件容易把重试窗口耗光,宁可慢也不要丢资产。
|
||||
# 配合 job 超时 60 分钟与单资产 5 次重试,给服务端抖动留出余量。
|
||||
failed=0
|
||||
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
|
||||
upload_asset "$file" &
|
||||
pids+=($!)
|
||||
if [ "${#pids[@]}" -eq 2 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
pids=()
|
||||
fi
|
||||
upload_asset "$file" || failed=1
|
||||
done
|
||||
if [ "${#pids[@]}" -gt 0 ]; then
|
||||
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
|
||||
fi
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::One or more Gitea assets failed to upload."
|
||||
exit 1
|
||||
|
||||
@@ -59,3 +59,10 @@ exports/
|
||||
|
||||
# Local API captures may contain tenant business data
|
||||
/specs/hose-close-api/_tmp-captured/
|
||||
|
||||
# 排障时临时下载的截图,通常带有客户名称与业务数据,不得入库
|
||||
/downloads/
|
||||
|
||||
# Vue 控制台的 Vite 中间产物;最终单文件产物在 src/packaging/generated/ 并提交
|
||||
/.webui-dist/
|
||||
/web/dist/
|
||||
@@ -4,10 +4,10 @@
|
||||
"type": "stdio",
|
||||
"command": "bun",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
"src/server.ts"
|
||||
],
|
||||
"env": {
|
||||
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
|
||||
"HOSE_USE_MCP_ENABLED": "true"
|
||||
},
|
||||
"timeoutMs": 120000
|
||||
}
|
||||
|
||||
@@ -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,24 @@
|
||||
|
||||
## 企业租户操作红线(强制)
|
||||
|
||||
- **唯一允许操作的测试企业是「沈玥妍测试企业」**,任何需要真实联调/验证的场景只能在它上面做。
|
||||
- **默认测试企业「沈玥妍测试企业」`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` 停用。
|
||||
|
||||
## 功能授权边界(用户 2026-11-05 明确)
|
||||
|
||||
- **`hose-use` 是免费功能**,不需要凭证、不受任何激活门禁管辖。
|
||||
- **AI PRO 离线凭证只管 `hose-aipro`**,门禁挂在 `runAiProCli`。不要把「`hose-use` 写命令未受凭证约束」当成安全缺口或待办——这是设计,不是漏实现。需要凭证的是 AI PRO 审批能力,不是企业平台 CLI。
|
||||
|
||||
## 仓库协作
|
||||
|
||||
- 双远端:`origin` = GitHub(主),`home` = Gitea(git.ying-qing.cn)。发布顺序先 `home` 再 `origin`。
|
||||
@@ -14,7 +27,8 @@
|
||||
|
||||
## 已知基础设施
|
||||
|
||||
- New API 端点已从 Sealos 的 `sealosgzg.site` 迁移至 `api.ying-qing.cn`;代码里残留的 `*.sealosgzg.site` 硬编码属于待清理项(workflow 灰度开通网关)。
|
||||
- New API(LLM 代理)端点为 `api.ying-qing.cn`;原 Sealos 实例 `sealosgzg.site` 已回收,属用户本地基础设施,与本仓库代码无关。
|
||||
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/piper-workflow-client.ts`(收口于 `piper-endpoints.ts`)与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
|
||||
|
||||
## 工作流与 Piper 核心契约(2026-11-02 固化)
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.10",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
},
|
||||
"license": "MIT",
|
||||
"skills": "skills",
|
||||
"mcpServers": "./.mcp.json",
|
||||
"mcpServers": "./mcp.json",
|
||||
"userConfig": {
|
||||
"enable_mcp": {
|
||||
"type": "boolean",
|
||||
|
||||
@@ -39,6 +39,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
||||
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
|
||||
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
|
||||
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
|
||||
- 开放平台官方接口/规范/参数规格检索统一使用 `hose-use docs search/show`,严禁 Agent 或上层代码绕过 CLI 直接解析 specs 目录下的底层 JSON 数据
|
||||
- 自建应用平台统一位于 `domains/platform/`,applications、datalink、workflow 分别拥有自己的模型、传输与服务出口;applications 不反向依赖另外两者,DataLink 不依赖 workflow,跨子模块不得直接调用 api。
|
||||
- `domains/**/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
|
||||
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
|
||||
@@ -54,6 +55,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
||||
常用子域入口:
|
||||
|
||||
- Platform 说明:[src/domains/platform/README.platform.md](./src/domains/platform/README.platform.md)
|
||||
- Docs 说明:[src/domains/docs/README.docs.md](./src/domains/docs/README.docs.md)
|
||||
|
||||
## 开发与修改规则
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.0)
|
||||
# hose-use (v0.9.10)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -32,6 +32,31 @@ hose-use version
|
||||
|
||||
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
|
||||
|
||||
### AI PRO 激活(默认关闭)
|
||||
|
||||
`hose-aipro` 与 `hose-use` 是同一个二进制的两个入口,安装脚本会自动软链出 `hose-aipro`。AI PRO 默认**不激活**:
|
||||
|
||||
1. 跑 `hose-aipro version --json` 记下当前版本;
|
||||
2. 把**版本号 + 期望到期日 + 客户名**通过微信 / 邮件 / 工单等离线渠道发给服务方申请凭证;
|
||||
3. 拿到凭证后**直接粘贴给你的 AI 助手**,由助手执行 `hose-aipro login '<凭证>'`(纯本地验签,不联网);
|
||||
4. 助手跑 `hose-aipro scopes --json` 能返回场景数据即激活成功。
|
||||
|
||||
凭证有两条约束:当前二进制版本不得高于其 `maxVersion`,当前时间不得晚于其 `exp`。完整流程与失败处理见 [hose-aipro Skill](./skills/hose-aipro/SKILL.md) 的「首次安装与激活」章节——Agent 自行安装时以该文档为准。
|
||||
|
||||
**`hose-use` 是免费功能,不需要凭证、不受任何激活门禁管辖;凭证只作用于 `hose-aipro`。**
|
||||
|
||||
### 环境变量
|
||||
|
||||
全部可选,完整清单见 [.env.example](./.env.example)。几个与发布相关的:
|
||||
|
||||
| 变量 | 作用 |
|
||||
|---|---|
|
||||
| `HOSE_PIPER_BASE_URL` / `HOSE_PIPER_TEST_BASE_URL` | 覆盖标准 / 测试 Piper 集群地址,影响工作流引擎客户端、Webhook 触发 URL 与灰度节点开通 |
|
||||
| `HOSE_AIPRO_LICENSE_FILE` | AI PRO 凭证文件路径(默认 `~/.config/hose-use/aipro-license.token`,0600) |
|
||||
| `HOSE_AIPRO_LICENSE_PRIVATE_KEY` / `HOSE_AIPRO_LICENSE_PRIVATE_FILE` | 仅签发方使用,客户端运行不需要 |
|
||||
|
||||
AI PRO 常驻服务启动后,浏览器打开 `http://127.0.0.1:8889/report` 即为本地 Web 控制台(Vue 单页、资源全内嵌、不依赖 CDN)。前端源码在 `web/`,构建产物由 `bun run web:build` 生成并内嵌进二进制。`GET /docs` 的交互式 API 文档同样全离线——Scalar 运行时由 `GET /static/scalar.js` 本地提供,仅在升级版本时才需要 `bun run docs:fetch` 联网刷新。
|
||||
|
||||
---
|
||||
|
||||
### CLI 常用命令速查 (`hose-use`)
|
||||
@@ -113,7 +138,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `mcp.json` 插件清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;仓库根目录的 `.mcp.json` 是 Claude Code 项目级 MCP 配置,直接以 `bun src/server.ts` 启动当前源码;
|
||||
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,整个 `dist/` 不纳入 Git。源码方式加载插件须先安装依赖并执行此构建;插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
|
||||
- **完整插件包**:`bun run package:plugin` 从当前源码构建并生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,内含清单、MCP 配置、Skill 与 bundle。Release 发布此包并纳入 `checksums.txt` 和 Gitea 镜像;解包目录可作为本地插件根目录,无需源码或 `node_modules/`,仍需 Bun。打包命令需要 `tar`;详细用法见 [构建与分发说明](./src/packaging/README.packaging.md)。
|
||||
|
||||
@@ -130,7 +155,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
| `.github/` | CI 与 Release 工作流,负责校验、构建和发布。 |
|
||||
| `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 |
|
||||
| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`hose-open-api/` 是 hose-use 包装层对外 API 的 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。[hose-close-api/](./specs/hose-close-api/README.md) 保存从代码整理的合思内部接口清单与 Schema;本地临时抓包不纳入 Git。生成入口见下文。 |
|
||||
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [.mcp.json](.mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
|
||||
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [mcp.json](mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
|
||||
| `docs/` | 跨模块参考与审阅记录;Platform 模块说明和各域 README 提供当前 CLI 与服务导航,架构总纲见 [AGENTS.md](./AGENTS.md);`reviews/` 保留历史审阅及验证证据。 |
|
||||
| `enterprises/` | 仅跟踪配置示例与 [目录说明](./enterprises/README.md)。实际企业配置默认放在 `~/.config/hose-use/enterprises/`,仓库内其他企业 JSON 被忽略。 |
|
||||
| `.git/` 或 `.git` 文件 | Git 元数据;独立工作树中通常是指向共享仓库的文件。 |
|
||||
@@ -142,7 +167,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
|
||||
- [AGENTS.md](./AGENTS.md) 是项目开发规则总入口;`CLAUDE.md → AGENTS.md` 是兼容软链接,共享同一份内容。
|
||||
- [package.json](./package.json)、`bun.lock` 与 [tsconfig.json](./tsconfig.json) 分别管理项目入口和命令、锁定依赖、配置 TypeScript;[.env.example](.env.example) 是环境变量示例。
|
||||
- [.mcp.json](.mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
|
||||
- [mcp.json](mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.mcp.json](.mcp.json) 是 Claude Code 项目级 MCP 配置,避免把插件变量 `${CLAUDE_PLUGIN_ROOT}` 带到项目上下文;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
|
||||
- `ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。
|
||||
|
||||
规范生成关系与命令:
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
@@ -17,6 +18,7 @@
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/qrcode-terminal": "^0.12.2",
|
||||
"typescript": "^5.9.3",
|
||||
},
|
||||
@@ -37,42 +39,102 @@
|
||||
|
||||
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
|
||||
|
||||
"@types/qrcode": ["@types/qrcode@1.5.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
|
||||
|
||||
"@types/qrcode-terminal": ["@types/qrcode-terminal@0.12.2", "", {}, "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q=="],
|
||||
|
||||
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
|
||||
|
||||
"camelcase": ["camelcase@5.3.1", "", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="],
|
||||
|
||||
"cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
|
||||
|
||||
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
|
||||
|
||||
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
|
||||
|
||||
"dijkstrajs": ["dijkstrajs@1.0.3", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
|
||||
|
||||
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
|
||||
|
||||
"find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
|
||||
|
||||
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
|
||||
|
||||
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
|
||||
|
||||
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
|
||||
|
||||
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
|
||||
|
||||
"locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
|
||||
|
||||
"p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
|
||||
|
||||
"p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
|
||||
|
||||
"p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
|
||||
|
||||
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
|
||||
|
||||
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
|
||||
|
||||
"qrcode": ["qrcode@1.5.4", "", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
|
||||
|
||||
"qrcode-terminal": ["qrcode-terminal@0.12.0", "", { "bin": { "qrcode-terminal": "./bin/qrcode-terminal.js" } }, "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="],
|
||||
|
||||
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
|
||||
|
||||
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
|
||||
|
||||
"require-main-filename": ["require-main-filename@2.0.0", "", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="],
|
||||
|
||||
"set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
|
||||
|
||||
"wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
|
||||
|
||||
"y18n": ["y18n@4.0.3", "", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="],
|
||||
|
||||
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
|
||||
|
||||
"yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="],
|
||||
|
||||
"yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="],
|
||||
|
||||
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ src/http/ # HTTP -> runCli
|
||||
| `EasoClient` | `unity.ekuaibao.com` | 统一认证与 EASO 资源 |
|
||||
| `PiperClient` | `piper.ekuaibao.com` | 工作流列表、详情、配置保存与 Job 执行 |
|
||||
|
||||
客户端装配统一位于 `src/core/http/`:主站使用 `session-client.ts`,Unity/EASO 使用 `unity-client.ts`,Piper 使用 `script-engine-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
|
||||
客户端装配统一位于 `src/core/http/`:主站使用 `hose-web-session-client.ts`,Unity/EASO 使用 `unity-easo-client.ts`,Piper 使用 `piper-workflow-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
|
||||
|
||||
## 认证链路
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
# 生产环境门禁系统性审计(2026-11-18)
|
||||
|
||||
## 结论摘要
|
||||
|
||||
1. 全仓库真正按企业环境(`prod`)做**硬拦截**的只有两处,都在 `workflow` 命令族:
|
||||
- `workflow test`:生产调试需 `--force`
|
||||
- `workflow nodes grant`:生产开通灰度节点需 `--allow-prod`
|
||||
2. 其余所有写操作(工作流增删改发、单据审批、DataLink 记录编辑、费用类型、审批规则等)**没有环境级硬拦截**,只受统一的 `--dry-run` / `--yes` 两阶段确认保护。
|
||||
3. 因此“生产环境被大面积禁用”不成立。此前客户侧遇到的问题,是 `workflow nodes grant` 在 PR #174(`8375445`)中被单独加成了“默认拒绝且明确不提供逃生口”,属于一次性的过度加固,而不是全局策略。
|
||||
4. 当前两处门禁都有逃生口,但存在协议不一致:逃生参数命名不同、JSON 错误形状不同、预览行为不同、成功结果的可观测标记不同。
|
||||
|
||||
## 审计范围
|
||||
|
||||
- `src/core/config/`:环境属性判定与配置归一化
|
||||
- `src/cli/`:所有命令的环境分支、确认机制与输出
|
||||
- `src/domains/`、`src/server.ts`、`src/http/`:是否存在域层或网关层的环境拦截
|
||||
- `skills/`、各层 README:文档与实际行为是否一致
|
||||
- Git 历史:每个门禁的引入时间、背景与是否带逃生口
|
||||
|
||||
## 一、生产环境硬拦截清单(整改前)
|
||||
|
||||
| 命令 | 拦截动作 | 判定 | 逃生口 | 预览是否需要逃生口 | 确认要求 | JSON 错误 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `workflow test` | 在正式企业执行端到端调试(可能产生真实单据、外部调用、快照发布) | `isCorpProd(selectedCorp)` | `--force`(同时接受 `--allow-prod` / `--allow-production` 别名) | 否,`--dry-run` 先返回 | `--yes` / `--confirm` | ❌ `stdout` 为空,只有文本 `stderr` |
|
||||
| `workflow nodes grant` | 为正式企业开通灰度节点(企业级不可逆能力变更) | `isCorpProd(selectedCorp)` | `--allow-prod` / `--allow-production` | 是,`--dry-run` 也必须带 `--allow-prod` | `--yes` / `--confirm` | ✅ `PROD_GRANT_BLOCKED` + `nextAction` |
|
||||
|
||||
关键代码:
|
||||
|
||||
- `src/cli/commands/workflow/test.ts:67`(判定)、`:393`(阻断)
|
||||
- `src/cli/commands/workflow/node-catalog.ts:116`(判定)、`:122`(阻断)
|
||||
- 环境判定:`src/core/config/types.ts:83-121`
|
||||
|
||||
## 二、确认机制覆盖(非环境门禁)
|
||||
|
||||
所有业务数据写操作都走 `requireMutationConfirmation` 或 `bill` 命令族自己的 `requireWriteConfirmation`,要求 `--dry-run` 预览后追加 `--yes`:
|
||||
|
||||
- 工作流:创建、复制、删除、启停、发布、草稿保存、节点增改删、节点映射、Webhook 发送、调试
|
||||
- 单据:创建、复制、提交、删除、同意、驳回、转交、加签、评论
|
||||
- 平台:DataLink 记录切换、编辑、批量编辑、重算
|
||||
- 费用类型:新建、修改、启停、移动
|
||||
- 审批规则:新增、删除
|
||||
- 其他:登录、换票、密钥持久化、企业切换、环境打标、消息已读、协助平台动作
|
||||
|
||||
结论:写操作的安全基线是“两阶段确认”,不是“生产环境禁止”。
|
||||
|
||||
## 三、环境判定与打标机制
|
||||
|
||||
`src/core/config/types.ts`:
|
||||
|
||||
- 优先级:显式 `env` > `isTest` > 按名称/ID 推导 `inferCorpEnvFromName`
|
||||
- 推导规则:名称或 ID 含“测试 / test” → `test`;含“演示 / POC / demo” → `demo`;否则 → `prod`
|
||||
- `isCorpTest = env in (test, demo) || isTest === true`
|
||||
- `isCorpProd = !isCorpTest`(保守默认:未标记一律视为生产)
|
||||
- 配置加载时 `normalizeCorpConfig` 会把推导结果写回内存对象,因此所有显示路径拿到的 `corp.env` 实际已归一化
|
||||
|
||||
打标与筛选:
|
||||
|
||||
- `hose-use corps tag <企业> --test|--prod|--demo|--env=<env>` 持久化环境属性
|
||||
- `--migrate-all` 按名称批量推导并持久化
|
||||
- `corps list` 支持 `--test` / `--prod` / `--demo` / `--env` 筛选
|
||||
- 当前本机配置的 29 家企业中,21 家判为 `prod`(包含未显式打标、按默认归为 `prod` 的),5 家 `test`,3 家 `demo`
|
||||
|
||||
## 四、发现的问题
|
||||
|
||||
### P1:`workflow test` 的生产阻断在 JSON 模式下不可解析
|
||||
|
||||
`src/cli/commands/workflow/test.ts:393-416` 在阻断时无条件返回:
|
||||
|
||||
- `stdout: ""`
|
||||
- `stderr: "🛑 生产环境安全阻断 ..."`
|
||||
|
||||
当 `--json` / MCP / HTTP 调用时,Agent 拿到的是空 stdout 和文本 stderr,无法读取 `code`、`nextAction`、当前企业与逃生命令。这与 `workflow nodes grant` 的结构化 `PROD_GRANT_BLOCKED` 不一致,也是此前 `platform records --all` 同类问题的翻版。
|
||||
|
||||
建议:JSON 模式返回统一结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": true,
|
||||
"code": "PROD_WORKFLOW_TEST_BLOCKED",
|
||||
"message": "正式生产企业执行工作流调试需显式追加 --force",
|
||||
"exitCode": 1,
|
||||
"nextAction": "hose-use workflow test <pipelineId> --yes --force",
|
||||
"details": { "corpId": "...", "env": "prod" }
|
||||
}
|
||||
```
|
||||
|
||||
### P1:预览行为不一致
|
||||
|
||||
- `workflow test --dry-run` 在生产环境可以直接预览,不需要 `--force`。
|
||||
- `workflow nodes grant --dry-run` 在生产环境仍会被门禁挡住,必须先加 `--allow-prod`。
|
||||
|
||||
预览不产生写操作,不应要求先接受生产风险。建议统一为“预览永远放行,执行才要求逃生口”,并让预览的 `nextAction` 带上逃生参数。
|
||||
|
||||
### P2:逃生参数命名与文档漂移
|
||||
|
||||
- `workflow test` 代码接受 `--force`、`--allow-prod`、`--allow-production`,但帮助只写 `--force`(`src/cli/help.ts:54`、`test.ts:50`)。
|
||||
- `workflow nodes grant` 只使用 `--allow-prod`。
|
||||
- 全仓没有统一的“生产覆盖”术语。
|
||||
|
||||
建议统一以 `--allow-prod` 作为跨命令的显式覆盖参数,`--force` 保留为兼容别名,并在帮助、README、Skill 中一致说明。
|
||||
|
||||
### P2:成功结果的可观测标记不一致
|
||||
|
||||
- `nodes grant` 在 JSON 与文本结果中标记 `productionOverride: true` 并打印风险提示。
|
||||
- `workflow test` 只有 `warnings` 文本数组,没有机器可读的覆盖标记。
|
||||
|
||||
建议统一在成功结果中加入 `productionOverride: true` 与 `productionWarning`,便于自动化和审计。
|
||||
|
||||
### P2:`nodes grant` 门禁顺序
|
||||
|
||||
`node-catalog.ts:122` 的门禁发生在参数解析与 `--dry-run` 判断之前。生产环境下即使没有提供节点类型,也会先返回“生产阻断”,而不是“缺少节点类型”;同时导致上面的预览不一致。
|
||||
|
||||
建议顺序:参数校验 → `--dry-run` 预览放行 → 生产门禁 → 确认 → 执行。
|
||||
|
||||
### P2:`corps tag` 从生产改为测试缺少强化提示
|
||||
|
||||
`corps tag --test` 是解除两处生产门禁的唯一途径,但目前只有通用确认,没有“这会关闭该企业的生产保护”的显著警告,也没有审计记录。
|
||||
|
||||
建议:
|
||||
|
||||
- 当 `currentEnv === "prod"` 且目标是 `test` / `demo` 时,输出显著警告并要求再次确认;
|
||||
- 可选:把打标变更写入本地审计日志(企业、旧值、新值、时间、操作人)。
|
||||
|
||||
### P3:名称推导存在双向误判
|
||||
|
||||
- 测试企业名称不含“测试 / test” → 被当作 `prod`(保守,但会误拦)。
|
||||
- 正式企业名称或 ID 恰好含“test / 测试” → 被当作 `test`,跳过两处生产门禁(危险方向)。
|
||||
|
||||
建议在 `auth login` / `corps link` / OpenAPI 导入等新建配置的路径上,显式展示推导结果并提示使用 `corps tag` 固化;或导入时要求用户确认环境。
|
||||
|
||||
### P3:策略只在 CLI 层生效
|
||||
|
||||
两处门禁都在 `src/cli/commands/`。MCP 与 HTTP 网关都委托 `runCli`,因此自动继承;但直接使用 `hose-use/sdk` 或 `domains/*` 的调用方会绕过门禁。这是分层设计的结果,需要在 SDK 文档中明确“安全策略属于 CLI 层,SDK 调用方自行承担”。
|
||||
|
||||
### P3:文档残留
|
||||
|
||||
- `skills/hose-use/references/workflow.md:191` 仍以“生产企业默认被硬拦截”示范不带逃生口的命令,后两行才给出 `--allow-prod`。
|
||||
- `src/cli/help.ts:54` 只描述 `--force`。
|
||||
- `src/cli/README.cli.md:17` 与 `src/domains/platform/workflow/README.workflow.md:106,164` 已正确描述当前行为。
|
||||
|
||||
## 五、历史回溯
|
||||
|
||||
| 提交 | 日期 | 内容 | 评价 |
|
||||
|---|---|---|---|
|
||||
| `af1e11c` | 2026-10-16 | 引入 `env` / `isTest` 环境属性、`corps tag`、`workflow test` 生产阻断(带 `--force`) | 设计内的初始安全机制 |
|
||||
| `103ead0` | 2026-10-17 | 为 workflow 命令补充 `allow-prod` / `allow-production` 参数词表 | 说明当时已考虑统一命名,但帮助文档未跟进 |
|
||||
| `8375445` | 2026-11-05 | PR #174 给 `nodes grant` 加生产硬拦截,提交说明明确写着“不提供 `--force` 逃生口” | **本次问题的根因:一次性过度加固** |
|
||||
| `8b03462` | 2026-11-18 | 增加 `--allow-prod` 逃生口、结构化 JSON、两阶段确认与 6 条单测 | 已修复,合并为 `d6d5d2d` |
|
||||
|
||||
结论:不是历史遗留的全局设计,而是一次 review 修复中夹带的单点硬编码。
|
||||
|
||||
## 六、整改建议(按优先级)
|
||||
|
||||
1. **统一生产门禁协议**
|
||||
- `--allow-prod` 作为唯一显式覆盖参数,`--force` 兼容保留;
|
||||
- JSON 错误统一 `{ error, code, message, exitCode, nextAction, details }`;
|
||||
- 每个命令使用独立错误码(如 `PROD_WORKFLOW_TEST_BLOCKED`、`PROD_GRANT_BLOCKED`)。
|
||||
2. **预览永远放行**
|
||||
- `--dry-run` 不要求覆盖参数,且预览的 `nextAction` 自带 `--allow-prod` / `--force`。
|
||||
3. **成功结果统一标记**
|
||||
- `productionOverride: true` + `productionWarning`,文本与 JSON 一致。
|
||||
4. **修正门禁顺序**
|
||||
- 参数校验 → 预览 → 生产门禁 → 确认 → 执行。
|
||||
5. **强化环境打标**
|
||||
- `corps tag` 生产降级为测试时增加显著警告;
|
||||
- 新建企业配置时展示推导环境并提示固化;
|
||||
- 可选审计日志。
|
||||
6. **文档统一**
|
||||
- `help.ts`、`references/workflow.md`、README 统一到 `--allow-prod` 术语。
|
||||
|
||||
## 七、复核命令
|
||||
|
||||
```bash
|
||||
# 环境分布与打标
|
||||
hose-use corps list --json
|
||||
hose-use corps list --test
|
||||
hose-use corps list --prod
|
||||
|
||||
# 当前企业环境
|
||||
hose-use context --json
|
||||
hose-use probe --json
|
||||
|
||||
# 两处门禁的帮助
|
||||
hose-use workflow test --help
|
||||
hose-use workflow nodes --help
|
||||
```
|
||||
|
||||
## 八、整改结果(2026-11-18,同批 PR)
|
||||
|
||||
本次审计发现的不一致已按“生产企业只多做一次显式确认,不禁止功能”的原则统一整改:
|
||||
|
||||
- 新增 `src/cli/production.ts`:`--allow-prod` 为唯一覆盖参数,`--allow-production` / `--force` 为兼容别名;阻断提示与 JSON 错误统一为 `PROD_OVERRIDE_REQUIRED`,包含 `nextAction` 与 `details.operation`。
|
||||
- `workflow test`:JSON 模式返回结构化错误;生产阻断前移到任何网络请求之前;`--dry-run` 不要求覆盖参数;成功结果带 `productionOverride` / `productionWarning`。
|
||||
- `workflow nodes grant`:参数校验前置;`--dry-run` 预览不再要求 `--allow-prod`;阻断结构与 `workflow test` 完全一致;成功结果同样带覆盖标记。
|
||||
- `src/cli/mutation.ts` 新增 `buildConfirmedCommand`,所有预览与确认的 `nextAction` 统一生成,生产覆盖参数自动补齐。
|
||||
- `corps tag` 将企业从 `prod` 降级为 `test` / `demo` 时输出显著警告,提示生产确认门禁将不再触发。
|
||||
- 帮助、CLI README、workflow 域 README、Skill 与节点命令示例同步为 `--allow-prod` 术语。
|
||||
- 单测覆盖:两命令的文本/JSON 阻断、预览免覆盖、`--force` 兼容、缺少参数优先报错、成功结果覆盖标记、降级警告。
|
||||
|
||||
整改后,生产企业执行敏感命令的行为是:
|
||||
|
||||
1. 预览永远可用;
|
||||
2. 实际执行多一个显式 `--allow-prod`(或兼容的 `--force`),让用户确认“知道自己在操作生产企业”;
|
||||
3. 仍然需要 `--yes` 确认;
|
||||
4. CLI 不再替用户决定“生产环境不能做”。
|
||||
@@ -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。
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"hose-use": {
|
||||
"type": "stdio",
|
||||
"command": "bun",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
],
|
||||
"env": {
|
||||
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
|
||||
},
|
||||
"timeoutMs": 120000
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.10",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
@@ -29,6 +29,9 @@
|
||||
"openapi:bundle": "bun run scripts/generate/bundle-openapi.ts",
|
||||
"openapi:generate-raw": "bun run scripts/generate/generate-raw-openapi.ts",
|
||||
"openapi:all": "bun run scripts/generate/generate-raw-openapi.ts && bun run scripts/generate/bundle-openapi.ts",
|
||||
"docs:fetch": "node scripts/build/build-docs.mjs",
|
||||
"web:dev": "bun --cwd web run dev",
|
||||
"web:build": "node scripts/build/build-webui.mjs",
|
||||
"build:binary": "node scripts/build/build-binary.mjs",
|
||||
"build:plugin": "node scripts/build/build-plugin.mjs",
|
||||
"package:plugin": "node scripts/build/package-plugin.mjs",
|
||||
@@ -46,6 +49,7 @@
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
@@ -54,6 +58,7 @@
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/qrcode-terminal": "^0.12.2",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 构建脚本
|
||||
|
||||
| 脚本 | 职责 |
|
||||
|---|---|
|
||||
| `build-binary.mjs` | 用 `bun build --compile` 编译各平台单二进制,注入 `HOSE_BUILD_*` 版本元数据,并创建 `hose-aipro` multicall 软链 |
|
||||
| `build-plugin.mjs` | 打包 `dist/mcp/server.js`(MCP 单文件产物) |
|
||||
| `package-plugin.mjs` | 生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz` 完整插件包 |
|
||||
| `build-webui.mjs` | 构建 `web/` 的 Vue 控制台,把 JS/CSS 内联成 `src/packaging/generated/webui.txt` 供二进制内嵌 |
|
||||
| `build-docs.mjs` | 拉取固定版本 Scalar standalone 并校验 SHA-256,生成 `src/packaging/generated/scalar-standalone.js.txt` |
|
||||
|
||||
`build-webui.mjs` 需要开发机先执行 `bun install --cwd web`;生成物随 git 提交,CI 与编译二进制不需要前端依赖。其余三个脚本只依赖根仓库的 `bun install`。
|
||||
|
||||
对应根命令:`build:binary`、`build:plugin`、`package:plugin`、`web:build`。
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 刷新 /docs 页面使用的 Scalar 浏览器运行时。
|
||||
*
|
||||
* 固定版本 + SHA-256 校验,产物写到 src/packaging/generated/ 并随 git 提交,
|
||||
* 因此运行时完全离线,编译二进制与 CI 都不需要访问 CDN。
|
||||
* 用法:bun run docs:fetch(仅在升级 Scalar 版本时需要)
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
||||
const SCALAR_VERSION = "1.25.101";
|
||||
const SOURCE = `https://cdn.jsdelivr.net/npm/@scalar/api-reference@${SCALAR_VERSION}/dist/browser/standalone.js`;
|
||||
const EXPECTED_SHA256 = "045c6a1ffa88167ea7f8adb8359cdfe2d2233faead3ebe1d2ec0b1e7975d3fdc";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const target = join(root, "src", "packaging", "generated", "scalar-standalone.js.txt");
|
||||
|
||||
console.log(`[build:docs] fetching @scalar/api-reference@${SCALAR_VERSION} ...`);
|
||||
const response = await fetch(SOURCE);
|
||||
if (!response.ok) {
|
||||
console.error(`[build:docs] 下载失败: HTTP ${response.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const actual = createHash("sha256").update(bytes).digest("hex");
|
||||
if (actual !== EXPECTED_SHA256) {
|
||||
console.error(`[build:docs] SHA-256 不匹配,拒绝写入`);
|
||||
console.error(` expected=${EXPECTED_SHA256}`);
|
||||
console.error(` actual =${actual}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 后缀 .txt:Bun 对 .js 的 text import 可能被当成模块;内容仍是完整 JS。
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, bytes);
|
||||
console.log(`[build:docs] ✓ ${target} (${(bytes.length / 1024 / 1024).toFixed(2)} MiB, sha256 ${actual.slice(0, 12)}…)`);
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 构建 web/ 下的 Vue 控制台,并把 JS/CSS 内联成单个 HTML 供二进制内嵌。
|
||||
*
|
||||
* 前置:bun install --cwd web(仅开发机需要;生成物随 git 提交,CI 不需要)
|
||||
* 用法:bun run web:build
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const webDir = join(root, "web");
|
||||
const outDir = join(root, ".webui-dist");
|
||||
// 后缀用 .txt 而非 .html:Bun 对 .html 的 text import 会推断成 HTMLBundle,
|
||||
// 导致 tsc 报错;内容仍是完整 HTML,由 HTTP 层按 text/html 返回。
|
||||
const target = join(root, "src", "packaging", "generated", "webui.txt");
|
||||
|
||||
if (!existsSync(join(webDir, "node_modules"))) {
|
||||
console.error("[build:webui] web/ 依赖未安装,请先执行: bun install --cwd web");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("[build:webui] building Vue app...");
|
||||
execFileSync("bun", ["run", "build"], { cwd: webDir, stdio: "inherit" });
|
||||
|
||||
const indexPath = join(outDir, "index.html");
|
||||
if (!existsSync(indexPath)) {
|
||||
console.error(`[build:webui] 找不到构建产物: ${indexPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let html = readFileSync(indexPath, "utf8");
|
||||
const files = readdirSync(outDir);
|
||||
|
||||
for (const file of files.filter((name) => name.endsWith(".css"))) {
|
||||
const css = readFileSync(join(outDir, file), "utf8");
|
||||
html = html.replace(/<link[^>]+href="[^"]*\.css"[^>]*>/g, () => `<style>${css}</style>`);
|
||||
}
|
||||
|
||||
for (const file of files.filter((name) => name.endsWith(".js"))) {
|
||||
const js = readFileSync(join(outDir, file), "utf8").replaceAll("</script>", "<\\/script>");
|
||||
html = html.replace(/<script[^>]+src="[^"]*\.js"[^>]*><\/script>/g, () => `<script type="module">${js}</script>`);
|
||||
}
|
||||
|
||||
if (/<script[^>]+src=/.test(html) || /<link[^>]+href="[^"]*\.css"/.test(html)) {
|
||||
console.warn("[build:webui] 警告: 仍有外链资源未被内联,页面在纯本地环境可能加载失败");
|
||||
}
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, html, "utf8");
|
||||
console.log(`[build:webui] ✓ ${target} (${(html.length / 1024).toFixed(1)} KiB)`);
|
||||
@@ -22,13 +22,13 @@ function run(command, commandArgs) {
|
||||
|
||||
try {
|
||||
// Explicit package inputs keep credentials, local notes and dependencies out of the archive.
|
||||
for (const path of [".zcode-plugin/plugin.json", ".mcp.json", "skills"]) {
|
||||
for (const path of [".zcode-plugin/plugin.json", "mcp.json", "skills"]) {
|
||||
cpSync(join(root, path), join(stage, path), { recursive: true });
|
||||
}
|
||||
// Always build from current source; never package a stale local dist/ bundle.
|
||||
run(process.execPath, [join(root, "scripts/build/build-plugin.mjs"), `--outfile=${join(stage, "dist/mcp/server.js")}`]);
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", ".mcp.json", "skills", "dist"]);
|
||||
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", "mcp.json", "skills", "dist"]);
|
||||
console.log(`✓ Packaged plugin: ${archive}`);
|
||||
} finally {
|
||||
rmSync(stage, { recursive: true, force: true });
|
||||
|
||||
@@ -17,7 +17,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac
|
||||
mkdirSync(pluginRoot);
|
||||
const extracted = Bun.spawnSync(["tar", "-xzf", archive, "-C", pluginRoot]);
|
||||
expect(extracted.exitCode, extracted.stderr.toString()).toBe(0);
|
||||
expect(readdirSync(pluginRoot).sort()).toEqual([".mcp.json", ".zcode-plugin", "dist", "skills"]);
|
||||
expect(readdirSync(pluginRoot).sort()).toEqual([".zcode-plugin", "dist", "mcp.json", "skills"]);
|
||||
const manifest = JSON.parse(readFileSync(join(pluginRoot, ".zcode-plugin/plugin.json"), "utf8"));
|
||||
expect(manifest.version).toBe(version);
|
||||
expect(manifest.skills).toBe("skills");
|
||||
|
||||
+3
-1
@@ -263,5 +263,7 @@ echo " 2. List corps: hose-use corps list"
|
||||
echo " 3. List workflows: hose-use workflow list"
|
||||
echo " 4. Switch mode: hose-use config mode stateless"
|
||||
echo " 5. Self-update: hose-use update"
|
||||
echo " AI PRO alias: hose-aipro"
|
||||
echo " AI PRO alias: hose-aipro (默认未激活)"
|
||||
echo " AI PRO 申请凭证: 把版本号与期望到期日发给服务方,拿到凭证后直接粘贴给你的 AI 助手"
|
||||
echo " AI PRO 激活: 由 AI 助手执行,无需手动敲命令"
|
||||
echo ""
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* AI PRO 离线凭证签发工具(仅签发方本地使用,不参与二进制构建)。
|
||||
*
|
||||
* 用法:
|
||||
* bun run scripts/license/issue.ts --sub "客户名称" --exp 2027-12-31 --max-version 0.9.99
|
||||
*
|
||||
* 私钥来源(优先级):
|
||||
* 1. HOSE_AIPRO_LICENSE_PRIVATE_KEY 环境变量(PEM 文本)
|
||||
* 2. HOSE_AIPRO_LICENSE_PRIVATE_FILE 环境变量(PEM 文件路径)
|
||||
* 3. ~/.config/hose-use/license/private.pem
|
||||
*
|
||||
* 私钥绝不进入仓库。exp 是绝对到期时间,脚本不施加任何时长上限。
|
||||
*/
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { randomBytes, sign } from "node:crypto";
|
||||
|
||||
const DEFAULT_PRIVATE_FILE = join(homedir(), ".config", "hose-use", "license", "private.pem");
|
||||
|
||||
function option(name: string): string | undefined {
|
||||
const prefix = `--${name}=`;
|
||||
const inline = process.argv.slice(2).find((arg) => arg.startsWith(prefix));
|
||||
if (inline) return inline.slice(prefix.length).trim();
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
return index >= 0 ? process.argv[index + 1]?.trim() : undefined;
|
||||
}
|
||||
|
||||
function loadPrivateKeyPem(): string {
|
||||
const inline = process.env.HOSE_AIPRO_LICENSE_PRIVATE_KEY?.trim();
|
||||
if (inline) return inline.replace(/\\n/g, "\n");
|
||||
const configured = process.env.HOSE_AIPRO_LICENSE_PRIVATE_FILE?.trim();
|
||||
const file = configured || DEFAULT_PRIVATE_FILE;
|
||||
if (!existsSync(file)) {
|
||||
throw new Error(`找不到签发私钥: ${file}\n请设置 HOSE_AIPRO_LICENSE_PRIVATE_KEY 或 HOSE_AIPRO_LICENSE_PRIVATE_FILE`);
|
||||
}
|
||||
return readFileSync(file, "utf-8");
|
||||
}
|
||||
|
||||
function parseExpiry(raw: string | undefined): number {
|
||||
if (!raw) throw new Error("缺少 --exp(绝对到期时间,如 2027-12-31 或 Unix 秒)");
|
||||
if (/^\d+$/.test(raw)) return Number(raw);
|
||||
const parsed = Date.parse(raw);
|
||||
if (Number.isNaN(parsed)) throw new Error(`无法解析到期时间: ${raw}`);
|
||||
return Math.floor(parsed / 1000);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const sub = option("sub");
|
||||
const maxVersion = option("max-version");
|
||||
if (!sub) throw new Error("缺少 --sub(授权对象标识)");
|
||||
if (!maxVersion || !/^\d+\.\d+\.\d+$/.test(maxVersion)) {
|
||||
throw new Error("缺少或非法的 --max-version(应为 x.y.z)");
|
||||
}
|
||||
|
||||
const exp = parseExpiry(option("exp"));
|
||||
const payload = {
|
||||
v: 1 as const,
|
||||
sub,
|
||||
exp,
|
||||
maxVersion,
|
||||
features: ["aipro"],
|
||||
nonce: randomBytes(12).toString("base64url"),
|
||||
};
|
||||
|
||||
const payloadBytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, loadPrivateKeyPem());
|
||||
const token = `${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
|
||||
console.log(`授权对象 : ${sub}`);
|
||||
console.log(`到期时间 : ${new Date(exp * 1000).toISOString().slice(0, 10)}`);
|
||||
console.log(`版本上限 : v${maxVersion}`);
|
||||
console.log(`凭证编号 : ${payload.nonce}`);
|
||||
console.log("");
|
||||
console.log(token);
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`[签发失败] ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// ==============================================================================
|
||||
// 合思代码节点 (MVEL): 单据日期/日期范围字段转化为具体时间字符串与时间戳
|
||||
// ==============================================================================
|
||||
|
||||
// ── 1. 配置区(按需修改)───────────────────────────────────────────────────────
|
||||
// (1) 前置工作流节点 ID(例如:第2步单据详情节点 action_pfsq28)
|
||||
upstreamNode = action_pfsq28;
|
||||
|
||||
// (2) 需要转化的单据层面字段 ID(例如标准起止日期 "feeDatePeriod",或自定义字段 "u_出差起止日期")
|
||||
dateFieldKey = "feeDatePeriod";
|
||||
|
||||
// ── 2. 字段取值与防御提取 ──────────────────────────────────────────────────────
|
||||
fieldVal = null;
|
||||
if (upstreamNode != null) {
|
||||
fieldVal = upstreamNode.get(dateFieldKey);
|
||||
if (fieldVal == null && upstreamNode.get("form") != null) {
|
||||
fieldVal = upstreamNode.get("form").get(dateFieldKey);
|
||||
}
|
||||
}
|
||||
|
||||
rawStart = null;
|
||||
rawEnd = null;
|
||||
|
||||
if (fieldVal != null) {
|
||||
if (fieldVal instanceof java.util.Map) {
|
||||
rawStart = fieldVal.get("start");
|
||||
rawEnd = fieldVal.get("end");
|
||||
} else {
|
||||
rawStart = fieldVal;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 3. 初始化日期格式化器(强制北京时间 GMT+8) ────────────────────────────────
|
||||
tz = java.util.TimeZone.getTimeZone("GMT+8");
|
||||
|
||||
sdfSecond = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
sdfSecond.setTimeZone(tz);
|
||||
|
||||
sdfMinute = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
sdfMinute.setTimeZone(tz);
|
||||
|
||||
sdfDay = new java.text.SimpleDateFormat("yyyy-MM-dd");
|
||||
sdfDay.setTimeZone(tz);
|
||||
|
||||
// ── 4. 转换开始时间 (start) ───────────────────────────────────────────────────
|
||||
startStr = "";
|
||||
startMinute = "";
|
||||
startDay = "";
|
||||
startMs = 0L;
|
||||
startSec = 0L;
|
||||
dStart = null;
|
||||
|
||||
if (rawStart != null && String.valueOf(rawStart).trim() != "") {
|
||||
startMs = java.lang.Long.parseLong(String.valueOf(rawStart).trim());
|
||||
if (startMs < 10000000000L) {
|
||||
startMs = startMs * 1000L;
|
||||
}
|
||||
startSec = startMs / 1000L;
|
||||
dStart = new java.util.Date(startMs);
|
||||
startStr = sdfSecond.format(dStart);
|
||||
startMinute = sdfMinute.format(dStart);
|
||||
startDay = sdfDay.format(dStart);
|
||||
}
|
||||
|
||||
// ── 5. 转换结束时间 (end) ─────────────────────────────────────────────────────
|
||||
endStr = "";
|
||||
endMinute = "";
|
||||
endDay = "";
|
||||
endMs = 0L;
|
||||
endSec = 0L;
|
||||
dEnd = null;
|
||||
|
||||
if (rawEnd != null && String.valueOf(rawEnd).trim() != "") {
|
||||
endMs = java.lang.Long.parseLong(String.valueOf(rawEnd).trim());
|
||||
if (endMs < 10000000000L) {
|
||||
endMs = endMs * 1000L;
|
||||
}
|
||||
endSec = endMs / 1000L;
|
||||
dEnd = new java.util.Date(endMs);
|
||||
endStr = sdfSecond.format(dEnd);
|
||||
endMinute = sdfMinute.format(dEnd);
|
||||
endDay = sdfDay.format(dEnd);
|
||||
}
|
||||
|
||||
// ── 6. 组合区间显示文本 ───────────────────────────────────────────────────────
|
||||
rangeMinuteStr = "";
|
||||
rangeSecondStr = "";
|
||||
if (startMinute != "" && endMinute != "") {
|
||||
rangeMinuteStr = startMinute + " ~ " + endMinute;
|
||||
rangeSecondStr = startStr + " ~ " + endStr;
|
||||
} else if (startMinute != "") {
|
||||
rangeMinuteStr = startMinute;
|
||||
rangeSecondStr = startStr;
|
||||
}
|
||||
|
||||
// ── 7. 组装返回结果 ───────────────────────────────────────────────────────────
|
||||
result = new java.util.HashMap();
|
||||
|
||||
// 开始时间 / 单个时间
|
||||
result.put("startTimeStr", startStr); // 如: "2026-11-19 20:59:00"
|
||||
result.put("startTimeMinute", startMinute); // 如: "2026-11-19 20:59"
|
||||
result.put("startDate", startDay); // 如: "2026-11-19"
|
||||
result.put("startTimestampMs", startMs); // 毫秒时间戳 (Long)
|
||||
result.put("startTimestampSec", startSec); // 秒时间戳 (Long)
|
||||
|
||||
// 结束时间
|
||||
result.put("endTimeStr", endStr); // 如: "2026-11-20 16:55:00"
|
||||
result.put("endTimeMinute", endMinute); // 如: "2026-11-20 16:55"
|
||||
result.put("endDate", endDay); // 如: "2026-11-20"
|
||||
result.put("endTimestampMs", endMs); // 毫秒时间戳 (Long)
|
||||
result.put("endTimestampSec", endSec); // 秒时间戳 (Long)
|
||||
|
||||
// 区间文本(方便下游直接放入 comment 或通知)
|
||||
result.put("rangeMinuteStr", rangeMinuteStr); // 如: "2026-11-19 20:59 ~ 2026-11-20 16:55"
|
||||
result.put("rangeSecondStr", rangeSecondStr); // 如: "2026-11-19 20:59:00 ~ 2026-11-20 16:55:00"
|
||||
|
||||
// 兼容单日期直接取用别名
|
||||
result.put("formattedTime", startStr);
|
||||
result.put("formattedMinute", startMinute);
|
||||
result.put("timestampMs", startMs);
|
||||
result.put("timestampSec", startSec);
|
||||
|
||||
return result;
|
||||
@@ -136,7 +136,14 @@ describe("release preparation and publication guards", () => {
|
||||
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
|
||||
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
|
||||
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
|
||||
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
|
||||
const pluginMcp = JSON.parse(readFileSync(join(root, "mcp.json"), "utf8")).mcpServers["hose-use"];
|
||||
expect(pluginMcp.command).toBe("bun");
|
||||
expect(pluginMcp.args[0]).toContain("${CLAUDE_PLUGIN_ROOT}");
|
||||
const projectMcp = JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"];
|
||||
expect(projectMcp.command).toBe("bun");
|
||||
expect(projectMcp.args).toEqual(["src/server.ts"]);
|
||||
expect(JSON.stringify(projectMcp)).not.toContain("${CLAUDE_PLUGIN_ROOT}");
|
||||
expect(JSON.stringify(projectMcp)).not.toContain("${user_config");
|
||||
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
|
||||
for (const name of ["Compile multi-target binaries", "Package plugin archive", "Package release archives", "Publish GitHub Release"]) {
|
||||
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
|
||||
@@ -162,7 +169,7 @@ for arg in "$@"; do
|
||||
done
|
||||
exit 22
|
||||
`, { mode: 0o755 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
|
||||
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 40_000 });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toContain("assets failed to upload");
|
||||
expect(result.stdout).not.toContain("Successfully published");
|
||||
@@ -173,7 +180,7 @@ exit 22
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
|
||||
expect(result.stdout).toContain("attempt 2/3");
|
||||
expect(result.stdout).toContain("attempt 2/5");
|
||||
}, 60_000);
|
||||
|
||||
test("correct mirror assets are verified and retained without uploading replacements", () => {
|
||||
@@ -189,7 +196,7 @@ exit 22
|
||||
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
|
||||
}, 60_000);
|
||||
|
||||
test("asset transfers never exceed two concurrent workers", () => {
|
||||
test("asset transfers are serialized to a single worker", () => {
|
||||
const f = mirrorFixture("concurrency");
|
||||
expect(f.run().status).toBe(0);
|
||||
let active = 0, peak = 0;
|
||||
@@ -198,6 +205,6 @@ exit 22
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
expect(active).toBe(0);
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
expect(peak).toBe(1);
|
||||
}, 60_000);
|
||||
});
|
||||
+108
-2
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
version: 0.9.10
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.0)
|
||||
# hose-aipro (v0.9.10)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
@@ -32,6 +32,95 @@ metadata:
|
||||
|
||||
---
|
||||
|
||||
## 首次安装与激活(Agent 操作序列)
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AI PRO **默认不激活**。装完二进制后,业务命令一律返回 `AIPRO_NOT_ACTIVATED`。
|
||||
> **客户不碰命令行**:客户只会把凭证粘贴到与 Agent 的对话框里;申请引导、执行激活、验证结果全部由 Agent 完成。
|
||||
> **凭证只作用于 `hose-aipro`**;`hose-use` 是免费功能,无需凭证、不受此门禁管辖。
|
||||
> 凭证**不能由 Agent 自行生成**——客户端只内嵌验签公钥,私钥在服务方手里。
|
||||
> 不要尝试绕过门禁、不要改系统时间、不要伪造或拼接凭证。
|
||||
|
||||
### 步骤 0 · 安装二进制(若尚未安装)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
脚本下载 Release 二进制并校验 SHA-256 清单,安装同一个 `hose-use` 后软链出 `hose-aipro`,同时把两份 Skill 装到 `~/.agents/skills/`。升级用 `hose-use update`。
|
||||
|
||||
### 步骤 1 · 确认版本(申请凭证的必要信息)
|
||||
|
||||
```bash
|
||||
hose-aipro version --json
|
||||
```
|
||||
|
||||
记下 `version` 字段。步骤 3 里由 Agent 直接把这个版本号写进给用户的消息,用户转给服务方,服务方据此设定凭证的 `maxVersion`。
|
||||
|
||||
### 步骤 2 · 判断是否已激活
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
- 返回场景数组 → 已激活,直接跳到步骤 5。
|
||||
- 返回 `{"code":"AIPRO_NOT_ACTIVATED","reason":"missing"}` → 未激活,继续步骤 3。
|
||||
|
||||
`status` / `help` / `version` 属自省命令,未激活也能运行;`scopes` 等业务命令一律受统一门禁管辖。
|
||||
|
||||
### 步骤 3 · 向用户索取凭证(Agent 在此等待)
|
||||
|
||||
在对话框里用一句话请用户提供凭证,并说明申请方式:向服务方提供**版本号(步骤 1 已查到,直接写进消息)+ 期望到期日 + 客户名 / 用途**,通过微信 / 邮件 / 工单等离线渠道申请,拿到后**把凭证直接粘贴回对话框**。
|
||||
|
||||
| 申请时需要的信息 | 由谁提供 |
|
||||
|---|---|
|
||||
| 当前二进制版本 | Agent 从步骤 1 读出并写进消息里 |
|
||||
| 期望到期日 | 用户决定,凭证里是绝对到期时间 `exp` |
|
||||
| 客户名 / 用途标识 | 用户决定,会写进凭证的 `sub` |
|
||||
|
||||
**不要让用户执行命令、不要让用户找配置文件、不要让用户自己敲 `login`。** 用户只做两件事:申请、粘贴。
|
||||
|
||||
### 步骤 4 · Agent 接住凭证并自行激活
|
||||
|
||||
用户粘贴后,从对话内容里**只提取那串 `xxx.yyy` 凭证文本**(`base64url(payload).base64url(签名)`),去掉前后的说明文字、引号、换行与空格,然后由 Agent 自己执行:
|
||||
|
||||
```bash
|
||||
hose-aipro login '<凭证>'
|
||||
# 等价写法
|
||||
hose-aipro login --token='<凭证>'
|
||||
```
|
||||
|
||||
- 原样传递,**不要生成、拼接、改写、重新编码或截断**这串文本;用单引号包裹,避免 shell 解析点号与特殊字符。
|
||||
- 不要把凭证回显到对话、不要写进日志、不要存到项目文件或笔记里。工具会落盘到 `~/.config/hose-use/aipro-license.token`(0600);可用 `HOSE_AIPRO_LICENSE_FILE` 指向别处。
|
||||
- 纯本地验签,**不联网**。
|
||||
|
||||
### 步骤 5 · Agent 验证并继续任务
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
返回真实场景数据即激活成功,直接继续原本的审批任务。`hose-aipro login --json` 会输出授权对象、到期时间与版本上限。
|
||||
|
||||
### 失败原因与处理
|
||||
|
||||
| `reason` | 含义 | 处理 |
|
||||
|---|---|---|
|
||||
| `missing` | 未激活 | 走步骤 3 请用户把凭证粘贴回对话框,Agent 自行激活 |
|
||||
| `expired` | 已超过 `exp` 绝对到期时间 | 重新申请凭证 |
|
||||
| `version_exceeded` | 当前版本高于 `maxVersion` | **不要降级二进制**,重新申请更高 `maxVersion` 的凭证 |
|
||||
| `bad_signature` | 凭证被篡改或复制不完整 | 重新复制完整凭证,检查引号与换行 |
|
||||
| `no_feature` / `malformed` | 凭证不含 AI PRO 授权或格式错误 | 重新申请凭证 |
|
||||
|
||||
### 两条约束
|
||||
|
||||
- 当前二进制版本不得高于凭证的 `maxVersion`(三段数字比较,忽略 `-dev` 后缀)。**升级二进制超过上限会立刻失效**,需重新申请。
|
||||
- 当前时间不得晚于凭证的 `exp`(绝对到期时间)。客户端不做设备绑定、不做时钟防篡改。
|
||||
|
||||
凭证是 Ed25519 签名数据,不是二进制变体:所有客户下载的是**同一个二进制**,区别只在本地有没有凭证文件。新增任意 AI PRO 命令自动受统一门禁管辖。
|
||||
|
||||
---
|
||||
|
||||
## 快速自省与运行上下文 (Zero-Source-Reading)
|
||||
|
||||
在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文:
|
||||
@@ -101,6 +190,23 @@ hose-aipro logs S26000001
|
||||
|
||||
---
|
||||
|
||||
## 本地 Web 控制台
|
||||
|
||||
常驻 HTTP 服务自带一个离线可用的 Vue 控制台,把审批会话、规则库、审核要点、审计流水与命令终端放到网页里看:
|
||||
|
||||
```bash
|
||||
hose-aipro service start # 默认 127.0.0.1:8889
|
||||
# 浏览器打开 http://127.0.0.1:8889/report
|
||||
```
|
||||
|
||||
- 页面资源全部内嵌在二进制里,**不请求任何 CDN**;只监听回环地址。是否映射成公网地址由使用者自行决定,工具不提供也不建议。
|
||||
- `GET /report` 返回页面;页面通过 `POST /api/cli` 调用现有 CLI 命令,`report --json` 是聚合数据源(场景 / 规则 / 会话 / 要点 / 流水 / 授权状态)。
|
||||
- 若设置了 `HOSE_HTTP_TOKEN`,浏览器请求需带 Bearer Token;默认本地使用不需要。
|
||||
- 控制台属于 AI PRO 能力,未激活时 `report --json` 会被统一门禁拦截。
|
||||
- 前端源码在 `web/`,改动后执行 `bun install --cwd web` 与 `bun run web:build` 重新生成 `src/packaging/generated/webui.txt`。生成物随 git 提交,CI 与编译二进制不需要安装前端依赖。
|
||||
|
||||
---
|
||||
|
||||
## 本机常驻服务与跨进程管理 (Daemon & Peer Control)
|
||||
|
||||
`hose-aipro` 拥有独立的常驻 HTTP 守护进程(默认端口 `8889`),并能直接启停本机的 `hose-use` 服务(默认端口 `8888`):
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
version: 0.9.10
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.0)
|
||||
# hose-use (v0.9.10)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -39,6 +39,7 @@ metadata:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
|
||||
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
|
||||
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
|
||||
- **扫码登录交互**:在执行扫码登录 (`login --qr`) 时,Agent 必须主动监控终端输出。一旦识别出二维码已保存(如提示 “💡 二维码已自动保存至: ...”),Agent **必须立即且自动**调用 `SendUserFile` 将该二维码图片渲染给用户查看,严禁等待用户主动提示。
|
||||
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
|
||||
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
|
||||
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
|
||||
@@ -60,12 +61,12 @@ metadata:
|
||||
11. **本地企业名录最高可信度与合思 payType 混淆防范(Local Config as Source of Truth & PayType Trap)**:
|
||||
- **本地配置具有最高权威性**:本地企业名录(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)经过人工审核确认,是判断企业真实性质的唯一权威来源;
|
||||
- **合思云端 payType 极度混乱陷阱**:合思数据库中的元数据 `payType`(如 `TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式客户租户在系统底层依然被标记为 `TRYOUT`(试用)**;
|
||||
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境,仅在明确标记为 🧪 测试 的企业中进行,正式企业必须有用户显式指令与二次确认。
|
||||
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境。测试/演示企业按正常两阶段确认执行;正式生产企业**不禁止**,但必须同时满足:① 用户已明确指令对该企业执行;② 完成 `--dry-run` 预览与 `--yes` 确认(涉及 `workflow test` / `workflow nodes grant` 时追加 `--allow-prod`)。Agent 不得仅因企业是正式生产环境而自行拒绝用户已明确授权的操作。
|
||||
12. **工作流草稿非隔离副本与生产介入明确知情权(Draft != Isolated Clone & Explicit Awareness)**:
|
||||
- **草稿绝非独立副本**:合思工作流处于草稿态(`state: 0`)仅代表“修改尚未发布生效”,它与生产流程是**同一个实体**。若直接在原流程上修改草稿,一旦点击发布就会直接覆盖生产运行逻辑,绝不可将其误认为互不影响的沙箱副本;
|
||||
- **排障或改造的知情选择权**:客户现场常存在“原本有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。Agent 介入排障或调整前,**必须向用户明确揭示实体归属与当前状态**,并提供两条明确路径供用户决策:
|
||||
1. **克隆独立副本(推荐稳健路径)**:使用 `hose-use workflow copy <pipelineId>` 创建真正的独立工作流副本(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
|
||||
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
|
||||
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改;**未经用户明确指令不得点击发布(publish)**,完成全链路验证并获得用户确认后即可上线。
|
||||
13. **协助会话人员身份角色穿透与高管权限防误用守则 (Assist Identity Profile & Executive Privilege Guard)**:
|
||||
- **身份与角色权限第一时间穿透呈现**:通过协助链接进入企业(`hose-use assist-platform enter`)或生成免密会话时,系统自动穿透解析并输出当前获得的员工姓名、工号、所属部门、所配角色清单以及核心系统权限;并自动将该人员画像与风控等级持久化落盘至本地企业配置(`enterprises/<corpId>.json`);
|
||||
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
||||
@@ -89,6 +90,23 @@ metadata:
|
||||
- 原生 `every` 的筛选字段物理键与右值选择器是两种结构:左侧保留 `feeTypeId`,右侧固定费用类型需保留前端 `value()` 描述符的真实 `key` 和 `label`;裸 ID 运行成功不代表设计器正常显示;
|
||||
- 金额来源、费用类型与明细对应关系须按用户确认的业务规则和实际字段元数据确定;创单引用循环聚合结果,空明细不得继续创单或回写成功;
|
||||
- 回读用户手工保存的 JSON 时,同时检查 `batch` / `batchSize`;并行配置会改变执行方式,不得当作显示修复自动覆盖。完整结构、金额类型与空列表兼容方案见 [references/workflow.md §20](./references/workflow.md#20-原生循环筛选选择器与费用明细)。
|
||||
18. **合思开放平台接口自省铁律(Docs & OpenAPI Self-Reflection First & Zero-JSON-Digging)**:
|
||||
- 当需要调研或回答“合思有哪些接口、支持哪些字段、具体参数/返回值规范是什么、如何设计第三方系统对接方案”时,**唯一正规、第一优先级的入口是 `hose-use docs search <关键词>` 与 `hose-use docs show <Path>`**;
|
||||
- **严禁翻找源码或 specs 目录下的 `docs-catalog.json` / `openapi*.json`**,严禁使用 `bun -e '...'` 或系统临时脚本暴力解析底层 JSON 文件;
|
||||
- 检索三步法:
|
||||
1. 查看模块大类:`hose-use docs categories`(了解合思 26+ 个业务分类及端点分布);
|
||||
2. 关键词检索:`hose-use docs search <关键词> [--category=<分类>] [--json]`(毫秒级获取接口清单与废弃标记);
|
||||
3. 单篇精细查阅:`hose-use docs show <Path|URL|名称> [--json]`(获取官方完整参数规格、类型约束与 CURL 示例);
|
||||
- 细节查阅专属参考文档:[references/docs.md](./references/docs.md)。
|
||||
19. **三大凭证通道矩阵与人工直通链接守则 (Three-Tier Credential Channels & Passwordless Direct Links)**:
|
||||
- **通道 A:企业 OpenAPI 持久化凭证 (`appKey` + `appSecurity`)**:企业级永久凭证,永不过期。当用户/开发者提出“生成免密链接 / 去界面人工 review / 看看画布”等直达需求时,**第一首选动作**是调用 `hose-use corps link <corpId>` 或 `hose-use workflow link <pipelineId>`。底层通过 `getProvisionalAuth` 动态签发带安全签名的 Web 直达 URL(`thirdparty.html?accessToken=...` 或直接带 EASO JWT 的 Piper 画布链接),任意浏览器点开即免密登录!
|
||||
- **通道 B:用户个人会话凭证 (`userAuthToken` / `cloudAuthToken`)**:个人会话凭证(手机验证码/密码),存在 TTL。供 CLI 在终端执行 API 读写、单据查询、调测。
|
||||
- **通道 C:协助运营平台工单会话 (`assist-platform`)**:合思官方技术支持(实施/客服)跨企业工单流转平台(Unity)。仅限在处理客户授权工单流转时使用(`assist-platform transfer` / `assist-platform list`),**严禁**直接向用户丢出未签名的 Unity 运营平台登录页让用户手动登录。
|
||||
- **非冲突双轨共存**:企业即便通过用户个人凭证登录,如果本地已配置过自建应用的 `appKey` / `appSecurity`,两者完全互不冲突、协同工作。
|
||||
20. **工作流节点 Schema 规范与前端图标降级防范 (Workflow Node Schema & Fallback Trap)**:
|
||||
- 合思前端微前端设计器(Piper)将节点图标分为 `action`(基础通用)与 `control`(控制节点:仅包含 condition、every、while、loop、if)两套硬编码字典;
|
||||
- **终止节点 (`stop`) 必须标记为 `groupName: "action"`**(归属基础通用);若错误标记为 `control`,前端在控制字典查无此项时会触发 Fallback 降级,被强行渲染为灰色通用工具扳手(`[🔧]` `OutlinedGeneralTool`);只有保持 `groupName: "action"` 才会正常渲染为官方红色禁止标(`[⛔]` `OutlinedTipsNo`)。
|
||||
- **代码节点 (`code` / `code-js2`)** 同样归属于 `action`。
|
||||
|
||||
---
|
||||
|
||||
@@ -97,6 +115,7 @@ metadata:
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) |
|
||||
| 合思开放平台官方接口/文档规范/售前能力调研/端点规格与CURL检索 | `hose-use docs search <关键词>`, `hose-use docs show <Path>`, `hose-use docs categories` | [references/docs.md](./references/docs.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) |
|
||||
@@ -107,7 +126,7 @@ metadata:
|
||||
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](./references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](./references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](./references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>] [--state=draft]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](./references/bill.md) |
|
||||
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](./references/bill.md) |
|
||||
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](./references/bill.md) |
|
||||
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](./references/bill.md) |
|
||||
@@ -131,7 +150,7 @@ metadata:
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](./references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](./references/task.md) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](./references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](./references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all --ndjson -o <path>`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](./references/workflow.md) |
|
||||
| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record <get|toggle|edit|batch-edit|recompute>` | [references/workflow.md](./references/workflow.md) |
|
||||
| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) |
|
||||
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](./references/workflow.md) |
|
||||
@@ -139,7 +158,7 @@ metadata:
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](./references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](./references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](./references/workflow.md) |
|
||||
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...>` | [references/workflow.md](./references/workflow.md) |
|
||||
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...> [--allow-prod]` | [references/workflow.md](./references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](./references/workflow.md) |
|
||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](./references/store.md) |
|
||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](./references/store.md) |
|
||||
@@ -182,7 +201,10 @@ hose-use bill list --keyword=打车 # 单据关键字跨
|
||||
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
|
||||
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||
hose-use bill list --state=draft --json # 查询我发起的未提交草稿(flows/my 数据源)
|
||||
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 # 草稿模板/标题/提交人过滤
|
||||
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||
hose-use bill get <单号|flowId> # 草稿也支持按 flowId 直读(工作流 Job 输出)
|
||||
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||
hose-use bill approve S26000001 --yes # 同意当前待办
|
||||
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
|
||||
@@ -233,7 +255,7 @@ hose-use platform list # 列出企业可见的
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
|
||||
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
|
||||
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
|
||||
hose-use platform records 新转转集团 合同 --all --ndjson -o /tmp/records.json # 自动翻页并流式导出全量业务对象记录
|
||||
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
||||
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
||||
@@ -256,7 +278,8 @@ hose-use workflow check --json --fail-on-alert # 扫描错误管道
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
|
||||
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
|
||||
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
|
||||
hose-use workflow nodes grant code-js2 --dry-run # 预览灰度开通变更(含固定附带开关)
|
||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业需追加 --allow-prod
|
||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
|
||||
@@ -287,12 +310,23 @@ hose-use service status # 查看常驻守护进
|
||||
hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
|
||||
hose-use service logs # 查看常驻守护进程日志
|
||||
hose-use service stop # 停止后台常驻守护进程
|
||||
|
||||
# 8. 合思开放平台官方接口文档与端点规范 (docs)
|
||||
hose-use docs categories # 查看 26+ 个业务分类及 HTTP 端点分布
|
||||
hose-use docs categories --json # 结构化查看业务模块清单
|
||||
hose-use docs search 预算 # 智能加权检索包含“预算”的全部接口与指南
|
||||
hose-use docs search 批量更新 --category=预算 # 在指定业务分类内精准检索
|
||||
hose-use docs search 角色组 --json # 结构化输出匹配端点列表
|
||||
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate # 查看指定端点完整参数规格、约束与 CURL 示例
|
||||
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate --json # 结构化输出端点定义模型
|
||||
hose-use docs sync # 强制与 docs.ekuaibao.com 线上文档全量同步
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 全局选项
|
||||
|
||||
- `--timeout`, `-T <seconds>`:命令全局超时时间,超时后自动终止运行。
|
||||
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
|
||||
- `--json`, `-j`:以标准 JSON 结构化输出结果
|
||||
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
|
||||
|
||||
@@ -158,3 +158,22 @@ Treat tenant-specific behavior as evidence, not a universal rule. Say what assum
|
||||
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
|
||||
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
|
||||
|
||||
## 沙箱调试绝佳技巧:终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning)
|
||||
|
||||
在真实业务流程(尤其包含单据驳回、审批通过、企微/钉钉消息推送、台账更新等危险副作用)中调测新增的代码节点时,强烈建议采用**紧随终止节点 (Stop Node Barrier)** 模式:
|
||||
|
||||
```text
|
||||
[前置查询/触发节点] ──> [新代码节点 (MVEL)] ──> [临时终止节点 (stop)] ──x (下游循环/驳回/审批被彻底物理隔离)
|
||||
```
|
||||
|
||||
### 1. 为什么必须紧随终止节点?
|
||||
1. **防止业务穿透与脏数据(安全第一)**:调试执行由云端真实引擎运行。若不设断点,引擎向下执行一旦命中驳回 HTTP 节点或审批同意,会向真实系统发起调用;紧随插入一个 `stop` 节点可形成绝对安全隔离,执行到代码节点后即刻安全着陆。
|
||||
2. **纯净捕获真实出参**:在安全阻断的同时,当次调试 Job 的 `executionTree` 产物中能完整记录新代码节点的实际返回值(`output`),验证数据精度与格式。
|
||||
|
||||
### 2. 保存样本数据 (Sample Pinning) 赋能设计器下拉树
|
||||
代码节点在没有样本数据(`sampleData`)前,下游节点在合思设计器中打开「引用字段」下拉菜单时**无法识别其输出属性**。
|
||||
- **固化样本**:调试成功后,将当次执行的 `output` 一键回写为该节点的 `sampleData`(如使用 `hose-use workflow test ... --save-sample` 或 `workflow node sample-save`);
|
||||
- **设计器自动解析**:一旦保存样本,合思工作流会自动为该代码节点生成选择器树(chooses),后续人工在配置下游驳回、条件或消息节点时,即可在界面下拉树中直接点选其格式化变量(如 `startTimeMinute`, `rangeMinuteStr`);
|
||||
- **调试后清理**:业务验证并完成下游表达式配置后,在界面上手动删除该临时的终止节点即可。
|
||||
|
||||
|
||||
@@ -13,39 +13,39 @@ description: |
|
||||
|
||||
## 参数提取
|
||||
|
||||
用户通常会贴浏览器请求(curl),从请求中自动提取参数:
|
||||
使用本机已配置的企业和认证信息,不需要浏览器 curl、手工提取 token 或调用第三方网关:
|
||||
|
||||
| 参数 | 提取位置 | 说明 |
|
||||
|------|----------|------|
|
||||
| token | Header `accesstoken` 或 Cookie `ekb-access-token` | accessToken |
|
||||
| corpId | Header `corpid` 或 URL query `corpId` | 企业 ID |
|
||||
| baseUrl | URL 协议+域名部分(如 `https://dd2.hosecloud.com`) | 自定义合思地址 |
|
||||
| nodes | 向用户确认 | 节点名,逗号分隔 |
|
||||
| 参数 | 来源 | 说明 |
|
||||
|------|------|------|
|
||||
| 企业 | `hose-use corps list` | 用 `--corp=<id>` 指定目标企业;遵循企业环境标记 |
|
||||
| 节点类型 | 本文件中的灰度节点清单 | 传 `type` 值,不传中文显示名 |
|
||||
|
||||
**域名判断**:URL 不是 `*.hosecloud.com` 而是 `dd2.hosecloud.com` 这类就是自定义域名,必须提取为 `baseUrl`。
|
||||
CLI 使用本地企业配置中的 `accessToken`、员工 ID 和 `baseUrl` 完成 EASO 换票与 Piper 请求;凭证不需要复制到 shell 命令或聊天中。
|
||||
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
# 网关地址优先取环境变量 HOSE_GRAY_GATEWAY_URL(尾部斜杠会自动忽略),未配置时用内置默认地址
|
||||
GATEWAY="${HOSE_GRAY_GATEWAY_URL:-https://d9jxeccs5j.sealosgzg.site}"
|
||||
curl -s -X POST "${GATEWAY%/}/hose-workflow-node" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
||||
|
||||
# 正式生产企业:执行前需显式追加 --allow-prod 确认环境(--force 兼容;预览可省略)
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --allow-prod --yes
|
||||
```
|
||||
|
||||
> 网关托管在第三方域,实例可能被回收或迁移。CLI 侧同样支持 `HOSE_GRAY_GATEWAY_URL` 覆盖;
|
||||
> 网关不可用时不要自行改用其他地址,先确认变量指向的实例仍然有效。
|
||||
工作流节点开通的默认 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
**每个企业的工作流只对应一个 Piper 环境**:标准 Piper(默认)与测试 Piper(`--is-test`)二选一,不会同时可用,也不会在请求失败时自动切换。若某企业通过标准 Piper 成功开通,说明它的工作流在标准环境;同一企业再通过测试 Piper 开通应失败,反之亦然。企业名称、本地 `env=test` 标记和企业 `baseUrl` 都不能用来推断 Piper 环境。
|
||||
|
||||
`--dry-run` 只预览操作,不会探测企业对应的 Piper 环境。成功开通可以确认所选环境;请求失败本身不能单独证明环境选错,还应检查认证错误和 Piper 返回的业务错误。确认目标使用测试 Piper 后,才在原命令上加 `--is-test`;该选项不会根据企业信息自动开启。
|
||||
|
||||
**生产企业需显式确认,但不禁止**:CLI 用 `isCorpProd` 判定企业,正式生产环境(含未标记、按名称保守推断为 prod 的企业)实际执行时必须追加 `--allow-prod`(`--force` 为兼容别名),表明操作者已知晓目标为生产企业;预览 `--dry-run` 始终放行。灰度节点开通仍是不可逆的企业级写操作,执行仍遵守 `--dry-run` 预览 → `--yes` 确认的两阶段约束。`--is-test` 仅切换 Piper 域名,不构成对生产企业的授权。`--dry-run` 预览会展示 Piper 固定附带开关(`recalculate-the-approval-flow`、`ui-notification`、`start`),与实际 payload 一致。
|
||||
|
||||
## 结果处理
|
||||
|
||||
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
|
||||
**成功**:CLI 根据 Piper 业务响应中的 `code` 确认开通结果,并显示新开通或已开通的节点。
|
||||
|
||||
**失败排查**:
|
||||
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
|
||||
- `认证失败` + 其他 — token 过期,让用户重新获取
|
||||
- 认证失败 — 检查本地企业凭证是否有效,并按 CLI 提示重新登录或刷新认证
|
||||
- Piper 业务码失败 — 依据 CLI 返回的业务错误信息排查企业或节点配置
|
||||
- 节点名错误 — 核对名称拼写
|
||||
@@ -64,7 +64,7 @@ hose-use assist-platform tickets <企业ID> --all --limit 20
|
||||
> [!WARNING] 合思底层 payType 混淆与本地企业名录可信度原则
|
||||
> 1. **合思付费模式混乱**:合思数据库中的 `payType`(`TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式生产客户在系统中依然被标记为 `TRYOUT`(试用)**。
|
||||
> 2. **严禁仅凭云端标记臆断沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"` 擅自推断企业为测试沙箱!
|
||||
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)严禁在未经授权的正式企业上执行。
|
||||
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)在正式企业上必须先获得用户明确授权,并完成 `--dry-run` → `--yes` 确认;用户明确授权后,不得仅因环境为生产而拒绝执行。
|
||||
|
||||
---
|
||||
|
||||
@@ -84,7 +84,7 @@ hose-use assist-platform staff <企业ID> --mobile "13800000000"
|
||||
|
||||
## 5. 发起协助申请工单 (`apply`)
|
||||
|
||||
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作仅限在本地确认的 🧪 测试企业中进行,正式企业必须获得用户明确指示。**
|
||||
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作在测试企业按正常两阶段确认执行;正式企业必须获得用户明确指示,并在 `--dry-run` → `--yes` 确认后执行,不得仅因环境为生产而自行拒绝。**
|
||||
|
||||
> [!IMPORTANT] 协助时长服务端硬性上限与 24 小时限制
|
||||
> 合思协助平台服务端(`POST /api/assistPlatform/create`)实施了底层的硬性安全管控:
|
||||
|
||||
@@ -22,9 +22,10 @@ hose-use bill list --corp=uzU7pcWfScck00 --json
|
||||
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
|
||||
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
|
||||
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
|
||||
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿);
|
||||
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中)。`--state=draft`(或 `草稿`)使用专用草稿列表:草稿尚未进入台账索引,数据源为「我发起」的 `flows/my`;
|
||||
- 草稿专用过滤:`--template=<模板ID>`、`--title=<标题关键字>`、`--staff=<姓名|工号|员工ID>`、`--page=<页码>`(与 `--count` 配合分页);
|
||||
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
|
||||
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`);
|
||||
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`;`--state=draft` 时仍走草稿列表);
|
||||
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
|
||||
- `--distinct`: 是否对单据记录去重。
|
||||
|
||||
@@ -40,6 +41,30 @@ hose-use bill list --code=CL20260901001
|
||||
|
||||
# 查询近 30 天已支付的报销单
|
||||
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
|
||||
|
||||
# 查询我发起的未提交草稿(支持模板、标题、提交人与分页过滤)
|
||||
hose-use bill list --state=draft
|
||||
hose-use bill list --state=draft --template=<模板ID> --title=付款 --staff=张三 --page=1 --count=20
|
||||
|
||||
# 草稿详情:支持单号或 flowId(工作流创建的草稿可用 Job 输出里的 flowId 查询)
|
||||
hose-use bill get <单号|flowId>
|
||||
```
|
||||
|
||||
> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中;
|
||||
> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get <flowId>` 直读详情。
|
||||
|
||||
### 草稿复制与编辑(支持报销单与差旅申请单)
|
||||
- `bill copy <单号|ID>` 支持报销单与申请单(`requisition`)自动路由:
|
||||
- 复制差旅申请单时会自动清理历史流转字段、重置 `u_行程规划` 等 `dataLinkEdits` 条目为 `"dataLinkId": null`(避免审批通过后无法生成行程订单),并支持通过 `--title`、`--reason`/`--description`、`--amount`、`--start-date=YYYY-MM-DD`、`--end-date=YYYY-MM-DD` 覆写标题、事由、额度与差旅日期(联动行程内日期与天数)。
|
||||
- `bill edit <单号|ID>`(别名 `update`)支持在草稿态(`draft`)修改 `--title`、`--reason`/`--description`、`--amount`(申请单)、`--start-date` 与 `--end-date`,支持 `--dry-run` 预览与 `--yes` 保存。
|
||||
|
||||
```bash
|
||||
# 复制历史差旅申请单为新草稿(预览 → 确认)
|
||||
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --dry-run
|
||||
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --yes
|
||||
|
||||
# 修改已有草稿的标题或事由
|
||||
hose-use bill edit S26005804 --title="新标题" --reason="新事由" --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# 合思开放平台官方接口文档与端点规范 (docs)
|
||||
|
||||
合思/易快报拥有 26+ 个业务分类、330+ 篇官方文档与 270+ 个 HTTP OpenAPI 端点。
|
||||
`hose-use docs` 命令域提供了**完全离线、毫秒级响应、带加权打分与完整 CURL/参数表格**的结构化自省能力。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Agent 与实施首选铁律**:
|
||||
> 凡涉及“合思有哪些接口、特定业务(如预算/发票/报销/自建应用)支持哪些 API、请求参数与返回结构是什么、如何设计第三方系统集成方案”等场景,**唯一正规、第一优先级的入口是 `hose-use docs search` 与 `hose-use docs show`**。
|
||||
> **严禁**翻找源码目录或直接用临时脚本(如 `bun -e`)硬扒 `specs/docs-catalog.json`!
|
||||
|
||||
---
|
||||
|
||||
## 常用子命令与速查
|
||||
|
||||
### 1. 业务分类全览 (`hose-use docs categories`)
|
||||
查看合思开放平台包含的所有业务大类以及每个分类下的端点数量:
|
||||
|
||||
```bash
|
||||
hose-use docs categories
|
||||
hose-use docs categories --json
|
||||
```
|
||||
|
||||
输出示例:
|
||||
```text
|
||||
====== 合思开放平台业务模块分类 (共 26 个) ======
|
||||
|
||||
# 业务分类 文档篇数 HTTP 端点数
|
||||
-- ------------ -------- -----------
|
||||
1 单据 50 篇 42 个
|
||||
2 自建应用 45 篇 38 个
|
||||
3 预算 13 篇 9 个
|
||||
4 费用类型 12 篇 10 个
|
||||
5 员工档案 15 篇 12 个
|
||||
...
|
||||
```
|
||||
|
||||
### 2. 关键词加权智能检索 (`hose-use docs search`)
|
||||
按接口标题、请求路径、URL、参数规格、正文段落综合加权搜索。
|
||||
|
||||
```bash
|
||||
# 基础检索
|
||||
hose-use docs search 预算
|
||||
hose-use docs search roleDefGroups
|
||||
hose-use docs search "发票查重"
|
||||
|
||||
# 限定业务大类检索 (通过 --category)
|
||||
hose-use docs search 批量更新 --category=预算
|
||||
hose-use docs search 审批 --category=单据
|
||||
|
||||
# 限制返回条数与 JSON 结构化输出 (最适合 Agent 解析)
|
||||
hose-use docs search 预算 --limit=10 --json
|
||||
```
|
||||
|
||||
**JSON 模式返回字段说明**:
|
||||
- `total`: 命中总数
|
||||
- `results`: 匹配条目数组,包含:
|
||||
- `id`: 文档 ID
|
||||
- `title`: 中文标题(如“批量更新(新增/修改/删除)预算节点”)
|
||||
- `category`: 业务分类(如“预算”)
|
||||
- `path`: HTTP 路由(如 `/api/openapi/v2.1/budgets/$budgetId/batchUpdate`)
|
||||
- `method`: HTTP 方法(`GET`, `POST`, `PUT`, `DELETE` 等)
|
||||
- `permalink`: 官方在线文档链接
|
||||
- `matchReason`: 匹配依据与高亮摘要
|
||||
|
||||
### 3. 单篇接口详细规格查询 (`hose-use docs show`)
|
||||
精准调阅指定端点的全量参数规格表、Query/Path/Body 定义、完整 CURL 示例以及成功/失败响应报文。
|
||||
|
||||
```bash
|
||||
# 按接口 Path 查看 (推荐)
|
||||
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate
|
||||
|
||||
# 按文档 URL 查看
|
||||
hose-use docs show /docs/open-api/budget/batch-pdate-budget-node
|
||||
|
||||
# 按中文标题模糊查看
|
||||
hose-use docs show "批量更新(新增/修改/删除)预算节点"
|
||||
|
||||
# JSON 模式输出完整原始模型
|
||||
hose-use docs show /api/openapi/v2.1/budgets/\$budgetId/batchUpdate --json
|
||||
```
|
||||
|
||||
输出包含以下结构:
|
||||
- **基本信息**:标题、分类、方法、路径、在线链接;
|
||||
- **参数规格与定义**:Path Parameters、Query Parameters、Body Parameters(含层级嵌套、字段类型、必填性、默认值、枚举值和业务语义备注);
|
||||
- **CURL / 调用示例**:包含实际请求头、典型 Payload JSON 模板;
|
||||
- **响应示例**:成功响应 JSON 与失败状态码说明。
|
||||
|
||||
### 4. 强制全量同步更新 (`hose-use docs sync`)
|
||||
当合思官方开放平台上线新接口或调整文档时,运行同步命令:
|
||||
|
||||
```bash
|
||||
hose-use docs sync
|
||||
```
|
||||
该命令会自动从 `https://docs.ekuaibao.com/search-index.json` 拉取最新全量索引,并自动更新本地 SQLite 缓存与静态存储。
|
||||
|
||||
---
|
||||
|
||||
## 接口调研与售前方案编写标准 SOP (Agent Playbook)
|
||||
|
||||
当客户提出“我们需要做一个第三方系统(如预算系统、HRM、CRM、ERP)与合思的集成方案”时,Agent 必须遵循以下工作流:
|
||||
|
||||
1. **第一步:摸底业务分类**
|
||||
执行 `hose-use docs categories`,识别目标业务在合思体系中的归属分类(例如预算归属于“预算”,部门人员归属于“企业组织架构/员工档案”,单据归属于“单据”)。
|
||||
2. **第二步:拉取端点清单**
|
||||
执行 `hose-use docs search <核心词> --category=<分类> --json`,获取该业务领域全量推荐端点,并注意过滤掉标注为 `历史版本(不推荐)` 的废弃接口。
|
||||
3. **第三步:获取主力端点规格**
|
||||
对筛选出的 2~3 个主力接口(如主数据批量更新、单据提交、状态回调),执行 `hose-use docs show <Path> --json` 获取精确的字段层级、类型与约束。
|
||||
4. **第四步:产出方案**
|
||||
基于官方规范提炼出系统对接模式(定时下发 vs 实时回调)、字段映射表、版本控制机制与并发防踩坑建议。整个过程完全通过 CLI 命令自闭环,高效且精确。
|
||||
@@ -44,12 +44,14 @@ hose-use platform entities 新转转集团
|
||||
hose-use platform schema 新转转集团 合同
|
||||
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
||||
|
||||
# 检索业务对象的底层真实数据记录(支持 --all 自动翻页拉取全量记录)
|
||||
# 检索业务对象的底层真实数据记录(--all 自动翻页拉取全量记录)
|
||||
hose-use platform records 新转转集团 合同 --limit=5
|
||||
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
||||
hose-use platform records 新转转集团 支付计划表 --all --json -o /tmp/payment_plans.json
|
||||
hose-use platform records 新转转集团 支付计划表 --all --ndjson -o /tmp/payment_plans.json
|
||||
```
|
||||
|
||||
> `--all` 必须与 `--ndjson --output-file <path>` 一起使用;缺少流式导出时会返回 `DATASET_TOO_LARGE`(exitCode 2),并给出分页与流式导出的恢复建议。
|
||||
|
||||
### 2.1 业务对象记录操作 (`platform record`) 与安全全量合并 (Read-Modify-Write)
|
||||
|
||||
> **关键防坑说明**:合思 DataLink `PUT /api/v2.2/datalink/platformDataLink/$id` 是**整单覆盖接口**,而非局部 PATCH。若只传修改的 1 个字段,未传字段会被清空、对象引用若未提取 `.id` 会报 417、`visibility` 漏传会导致全员不可见。`hose-use platform record edit` 与 `batch-edit` 默认内置 **Read-Modify-Write 安全合并引擎**,自动拉取原记录与 Schema、归一化嵌套引用 ID、保留全部存量字段与 `visibility` 权限,并支持字段中英文短名自动解析。
|
||||
@@ -184,10 +186,16 @@ hose-use workflow nodes
|
||||
# 2. 与官方全量 108 个灰度节点清单进行完整对照
|
||||
hose-use workflow nodes --all
|
||||
|
||||
# 3. 申请开通灰度节点(支持节点拼音与中文名)
|
||||
hose-use workflow nodes grant code-js2
|
||||
# 3. 申请开通灰度节点(支持中文名归一化;同名节点需改用明确的 type)
|
||||
hose-use workflow nodes grant code-js2 --dry-run # 预览变更,含 Piper 固定附带开关(生产企业也放行)
|
||||
hose-use workflow nodes grant code-js2 --yes # 确认执行;生产企业需补 --allow-prod
|
||||
hose-use workflow nodes grant code-js2 --allow-prod --dry-run # 生产企业:预览(覆盖参数可省略)
|
||||
hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行
|
||||
```
|
||||
|
||||
> 生产企业执行敏感命令时,CLI 只要求显式 `--allow-prod` 表明已知晓目标环境,不禁止功能;
|
||||
> `--force` 为兼容别名。JSON 模式下的阻断统一为 `PROD_OVERRIDE_REQUIRED`,并带 `nextAction`。
|
||||
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
|
||||
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
|
||||
@@ -279,7 +287,7 @@ hose-use workflow publish <pipelineId>
|
||||
> - **草稿态实质**:合思工作流的草稿状态(`state: 0`)仅表示“改动尚未发布对线上生效”,它与线上流程是**同一个实体**。直接在生产工作流上改草稿,一旦点击发布就会直接覆盖线上运行逻辑,绝不可将其误认为独立的沙箱副本;
|
||||
> - **生产排障与改造的知情权**:客户现场常存在“原有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。介入排障或调整前,**必须向用户明确说明当前实体性质**,并提供清晰决策路径:
|
||||
> 1. **克隆独立副本(推荐稳健路径)**:使用 `workflow copy` 克隆出新流水线(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
|
||||
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
|
||||
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改;**未经用户明确指令不得点击发布(publish)**,完成全链路验证并获得用户确认后即可上线。
|
||||
|
||||
```bash
|
||||
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
|
||||
@@ -344,6 +352,13 @@ hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --yes
|
||||
hose-use workflow node rm <pipelineId> 3 --yes
|
||||
|
||||
# 6. 只读探针与样本数据固化 (inspect / sample-save)
|
||||
# 定向透视指定节点的固化样本数据 (sampleData) 以及最近一次调试执行出参 (execution output)
|
||||
hose-use workflow node inspect <pipelineId> <nodeName>
|
||||
|
||||
# 将最近一次调测出参一键固化为 sampleData,使设计器下游节点可自动解析其选择器树 (chooses)
|
||||
hose-use workflow node sample-save <pipelineId> <nodeName> --yes
|
||||
```
|
||||
|
||||
---
|
||||
@@ -503,6 +518,33 @@ result;
|
||||
|
||||
将代码保存为独立 `.mvel` 文件,通过 `--code-file` 同步,节点说明保留 `agent use:` 标识。条件节点引用代码结果的 `hasDetails`,与布尔选择器 `@{value('{"key":true,"label":"是"}')}` 比较;创单和成功回写均放在该条件内部。至少验证空数组与非空数组,代码规范参见 [MVEL 参考](../multi/ekuaibao-mvel/SKILL.md)。
|
||||
|
||||
### 列表取数字段参与比较,必须先判空
|
||||
|
||||
上一节处理的是「数组本身参与比较」;这里处理另一个更常见的坑:**取值链要先穿过列表再往下取字段**,例如「查找业务对象数据 → 结果列表 → 首条数据 → 剩余额度」。上游查到 0 条时取值为 `null`,而 `null < 0` 在 MVEL 里返回 `null` 而不是 `false`,引擎对 `condition` 做 Boolean 强校验,直接抛:
|
||||
|
||||
```
|
||||
if 节点(control_xxx)的 condition 参数的解析结果必须为 Boolean 类型
|
||||
```
|
||||
|
||||
流程**中断**,不是安静走 false 分支。这条报错信息看不出是取值拿到 null,实际排查成本很高。
|
||||
|
||||
两条实测结论决定了正确写法:
|
||||
|
||||
1. **`AND` 不短路**。`AND(列表不为空, 额度 < 0)` 在列表为空时照样报同一个错——引擎是逐叶子求值再合并,`null < 0` 一定被算出来。所以「在同一个条件节点里加一层非空判断」这条路是死的。
|
||||
2. **`notNull` 对空数组 `[]` 返回 false**,对非空数组返回 true;条件为 false 时节点 COMPLETED、子节点不执行、流程继续。所以判断列表非空可以直接用 `notNull`,且**不需要 `value` 字段**。
|
||||
|
||||
可靠写法是把守卫上提一层,用流程控制短路:
|
||||
|
||||
```text
|
||||
条件节点A 条件:结果列表 notNull ← 新增守卫
|
||||
└─(满足) 条件节点B 条件:OR(额差<0, 招待<0) ← 原条件,表达式不动
|
||||
└─ 真正的处理动作
|
||||
```
|
||||
|
||||
列表为空时 A 为 false,B 根本不被求值。`workflow analyze` 对「列表取数 + `gt/gte/lt/lte` 比较 + 祖先链上没有同列表守卫」的情况给 `CONDITION_NULL_UNSAFE_COMPARE` 软提示,不推断数据是否真的非空、不改写配置。
|
||||
|
||||
比较符完整枚举:`eq` / `neq` / `gt` / `lt` / `gte` / `lte` / `isNull` / `notNull` / `include` / `dynamicRange` / `givenRange`。其中 `isNull` / `notNull` 不需要 `value` 字段。
|
||||
|
||||
### 调试成功必须回读单据
|
||||
|
||||
核对实际新单号、明细条数、每条金额、合计、源单关联与逐项入库关联;同时核对 Job 的错误节点和回写内容。草稿创建成功只证明此次草稿落库,不能据此声称提交送审、审批或付款成功;未验证的收款方、法人实体等字段应明确列出。关联引用次数耗尽可能自动停用源记录,不得为了重跑擅自重置引用次数、启用记录或重复创单。
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# 规范与生成物(specs)
|
||||
|
||||
本目录集中存放随仓库分发的接口规范、结构快照与生成物,供 CLI 内嵌分发(`hose-use openapi`、本地 HTTP 文档页)、docs 域离线检索与发布校验读取。除 `hose-open-api/` 的源 YAML 和 `hose-close-api/` 的契约文档外,其余 JSON 都是生成物,不要手工编辑。
|
||||
|
||||
## 目录与文件
|
||||
|
||||
| 路径 | 类型 | 说明 | 维护方式 |
|
||||
|---|---|---|---|
|
||||
| [hose-open-api/](./hose-open-api/openapi.yaml) | 源 YAML | hose-use 包装层 OpenAPI 3.1 源规范,入口文件通过相对 `$ref` 组装 `paths/` 与 `components/` | 手工维护,拆分说明见 [README.paths.md](./hose-open-api/paths/README.paths.md) |
|
||||
| [hose-close-api/](./hose-close-api/README.md) | 文档 | 合思内部/网页接口契约清单(method、path、参数、响应结构与 JSON Schema) | 手工维护,约定见目录 README |
|
||||
| [openapi.json](./openapi.json) | 生成物 | 包装层 OpenAPI 打包结果,供 `hose-use openapi` 与 HTTP 文档页内嵌 | `bun run openapi:bundle` |
|
||||
| [openapi.raw.json](./openapi.raw.json) | 生成物 | 原生下游接口规范(`data` / `code` / `message` 响应包装) | `bun run openapi:generate-raw` |
|
||||
| [workflow-schema.json](./workflow-schema.json) | 生成物 | 由 Zod 导出的工作流归一化结构 | `bun run export:workflow-schema` |
|
||||
| [docs-catalog.json](./docs-catalog.json) | 快照 | 开放平台文档索引静态快照,作为 docs 域离线检索保底 | 随 docs 域更新重新生成并提交;运行时 `hose-use docs sync` 只刷新本地缓存,不改写本文件 |
|
||||
|
||||
## 修改约定
|
||||
|
||||
- 改包装层 API 一律先改 `hose-open-api/` 源 YAML,再执行 `bun run openapi:all` 重新生成两份 JSON;不要直接编辑生成物。
|
||||
- `workflow-schema.json` 由 `src/domains/platform/workflow/types.ts` 的 Zod 模式推导;`export-workflow-schema.test.ts` 会校验仓库文件与重新导出的结果一致,改模式后必须重新导出。
|
||||
- 生成物必须随 Git 提交:编译二进制与 CI 无需额外构建步骤即可携带完整规范(见 [Packaging 说明](../src/packaging/README.packaging.md))。
|
||||
- 发布前 `scripts/release/check-version-sync.ts` 会核对 `hose-open-api/openapi.yaml` 与 `openapi.json` 的 `info.version` 是否和 `package.json` 一致。
|
||||
- 本地抓包、租户模板等含业务 ID 的资料只放在已 Git 忽略的 `hose-close-api/_tmp-captured/`,不得提交。
|
||||
|
||||
## 消费方
|
||||
|
||||
| 消费方 | 读取内容 |
|
||||
|---|---|
|
||||
| `src/packaging/embedded-openapi.ts` | `openapi.json`、`openapi.raw.json`(构建期内嵌) |
|
||||
| `src/domains/docs/tools.ts` | `docs-catalog.json`(离线检索保底) |
|
||||
| `scripts/release/check-version-sync.ts` | `hose-open-api/openapi.yaml`、`openapi.json`(版本一致性) |
|
||||
|
||||
检索开放平台官方接口的正式入口是 `hose-use docs search/show`;上层代码与 Agent 不应绕过 CLI 直接解析本目录的 JSON 文件。
|
||||
@@ -0,0 +1 @@
|
||||
{"version":"1.0.0","updatedAt":"2026-11-16T08:08:21.159Z","sourceUrl":"https://docs.ekuaibao.com/search-index.json","totalDocs":330,"totalEndpoints":279,"items":[{"id":3788,"title":"下载附件","category":"附件","url":"/docs/open-api/attachment/attachment-download","permalink":"https://docs.ekuaibao.com/docs/open-api/attachment/attachment-download","method":"POST","path":"/api/openapi/v2/attachment/downloadurls","breadcrumbs":["Open API","附件"],"headings":["Query Parameters","Body Parameters","CURL","成功响应","失败响应","钉盘附件下载","阿里云OSS CURL"],"sections":[{"title":"下载附件","content":"通过附件的 id、key 去获取附件的下载链接。 POST/api/openapi/v2/attachment/downloadurls 更新日志 2.3.1 🚀 优化了接口,支持ISV应用钉盘附件下载。 1.6.3 🐞 优化了接口 HTTP 500 错误,输出报错信息。"},{"title":"Query Parameters","content":"名称 类型 描述 是否必填 默认值 备注 accessToken String 认证token 必填 - 通过 获取授权 获取 accessToken"},{"title":"Body Parameters","content":"名称 类型 描述 是否必填 默认值 备注 -- Array 数组参数 必填 - 数组参数,最大支持 100 个参数 ∟ id String 文件fileId 必填 - 上传附件 接口返回的 fileId 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 fileId 值 ∟ key String 文件key 必填 - 上传附件 接口返回的 key 字段 接口下载单据上的附件时,可通过 获取单据详情 获取 attachments 字段的 key 值,注意: key 值前缀是 DP:时,表示该附件是钉盘附件 。 ∟ expiration Number 下载链接有效时间 必填 - 下载链接在多长时间内有效,单位:秒,最大 1800 秒 ,钉盘附件该值无效"},{"title":"CURL","content":"curl --location --request POST 'https://app.ekuaibao.com/api/openapi/v2/attachment/downloadurls?accessToken=UvsbtOEHTsk000' \\ --header 'Content-Type: application/json' \\ --data-raw '[ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"expiration\": 1000 }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"expiration\": 1000 } ]'"},{"title":"成功响应","content":"tip url 是文件下载路径,thumbUrl 是指缩略图的下载路径。 thumbUrl 只针对图片有效,PDF文件生成的链接是不可用的。 key 下载钉盘附件时,url 和 thumbUrl 都是 阿里OSS 文件链接,保存文件时需要根据key值内的 fileType 值来判断文件类型。 headers 只针对钉盘附件有效,下载文件时需要将 headers传入,否则会下载失败。 [ { \"id\": \"61sbwX3DEAgk00\", \"key\": \"openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin简介.docx\", \"url\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=wTRfcimdrHhXbL3efe8MftOSOmo%3D&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\", \"thumbUrl\": \"https://ekuaibao.oss-cn-hangzhou.aliyuncs.com/openapi0306c2d1-7a5b-4e96-8172-60c5ee0f971e-kotlin%E7%AE%80%E4%BB%8B.docx?Expires=1599099810&OSSAccessKeyId=STS.NUTdxysMYQXwZApA734jgqnJb&Signature=evQnFfd4YhL5zkFMovDl9ZfVdlw%3D&x-oss-process=image%2Fresize%2Cw_120%2Ch_120&security-token=CAIS8AF1q6Ft5B2yfSjIr5bhL8LNnpJ45pqcWGfBpTdmOOVLnqvhgDz2IHlPdHZhBekYtPszmW9Z6%2FsdlqF%2BSIJETEbNapPbRkWwXEXzDbDasumZsJYm6vT8a0XxZjf%2F2MjNGZabKPrWZvaqbX3diyZ32sGUXD6%2BXlujQ%2Fbr4NwdGbZxZASjaidcD9p7PxZrrNRgVUHcLvGwKBXn8AGyZQhKwlMk1zojtf7lmpTMtUuE0ALAp7VL99irEP%2BNdNJxOZpzadCx0dFte7DJuCwqsEERpPgn0PUao2ib447MXgQO%2BXScOu%2FT6cZ0MBRpwUXA2EKANZEagAFRCqgjZY6QvIiWMtTWb7UIfba4ebfujIHa7cn7sA3r0vGyNUnObhl5H5zW4cc%2FM%2FiHehACg83wRu189TUg4Qt5MRZ0KuYre7mpa4NWPJpcILHkRjLBR2YoL6Z27iqhNbtcZoezq%2B4ky3N60IIaXhUoYJcteXtru12W%2BiLzfiB%2FuA%3D%3D\" }, { \"id\": \"136634573449\", \"key\": \"DP:{\\\"fileId\\\":\\\"136634437985\\\",\\\"fileName\\\":\\\"128163bbba83.jpg\\\",\\\"fileSize\\\":2985928,\\\"fileType\\\":\\\"jpg\\\",\\\"spaceId\\\":\\\"7215288789\\\"}\", \"url\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXNrMATOITK4JgXNEKcGzTyBB85mF5ENCM24VQ.file\", \"thumbUrl\": \"https://sh-dualstack.trans.dingtalk.com/yundisk0/iAEIAqRmaWxlA6h5dW5kaXLine truncated
|
||||
@@ -45,7 +45,7 @@ specs/hose-close-api/
|
||||
- `src/domains/feetype/api.ts`
|
||||
- `src/domains/assist-platform/api.ts`
|
||||
- `src/core/auth/login.ts`、`src/core/auth/openapi-v1.ts`、`src/core/auth/link-import.ts`
|
||||
- `src/core/http/openapi-client.ts`、`unity-client.ts`、`script-engine-client.ts`、`assist-platform-client.ts`、`session-client.ts`
|
||||
- `src/core/http/hose-web-session-client.ts`、`openapi-client.ts`、`piper-workflow-client.ts`、`hose-docs-client.ts`、`unity-easo-client.ts`、`assist-platform-client.ts`、`sso-auth-client.ts`
|
||||
- 历史参考:`specs/openapi.raw.json`
|
||||
|
||||
## 域名约定
|
||||
@@ -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` | 灰度节点开通网关(非合思域名) |
|
||||
|
||||
## 响应包装约定
|
||||
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
| A05 | GET | `BC /cloud-auth/public/auth/list-corporations` | Header `cloud-auth-token` | `{data:{items:[CorporationItem],externalItems:[]},errorCode?,errorMessage?}`;Item 字段见下 | `src/core/auth/login.ts:242` | 否 |
|
||||
| A06 | POST | `BC /cloud-auth/public/auth/switch-corporation` | Header `cloud-auth-token`;body `{corporationId,userId,cluster}` | `{data:{accessToken:<authCode>},errorCode?,errorMessage?}` | `src/core/auth/login.ts:269` | 否 |
|
||||
| A07 | POST | `IDP /api/idp/public/oauth2/token` | `{clientId:"whispered-app",grantType:"authorization_code",code:<authCode>,withIdToken:false}` | `{access_token,token_type,expires_in,refresh_token?,id_token?}` | `src/core/auth/login.ts:288` | 否 |
|
||||
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-client.ts:70` | 否 |
|
||||
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
|
||||
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/script-engine-client.ts:68` | 否 |
|
||||
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-client.ts:119` | 否 |
|
||||
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-easo-client.ts:70` | 否 |
|
||||
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-easo-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
|
||||
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/piper-workflow-client.ts:68` | 否 |
|
||||
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-easo-client.ts:119` | 否 |
|
||||
| A12 | GET | `EKB /api/account/v2/session` | Headers `accesstoken`、`corpid`、可选 `staffid` | `{value:{id,userId,loginStaffId,corporationId,platform,isAssistPlatform,isShortTermToken,assistId,operationUserId,operationUserName,privilege,deviceType,loginAccountType,loginTime,expTime}}` | `src/core/auth/link-import.ts:329` | 否 |
|
||||
| A13 | POST | `EKB /api/openapi/v1/auth/getAccessToken` | `{appKey,appSecurity}` | `{value:{accessToken,corporationId,expireTime,errorCode?,errorMessage?}}`;也兼容顶层 `accessToken`/`token` | `src/core/auth/openapi-v1.ts:133` | 否 |
|
||||
| A14 | POST | `EKB /api/openapi/v1.1/provisional/getProvisionalAuth` | Query `{accessToken}`;body `{uid,pageType:"home",expireDate}` | `{value:{message:<loginUrl>}}`,从 URL 的 `accessToken` 参数取临时会话 token | `src/core/auth/openapi-v1.ts:199` | 否 |
|
||||
@@ -39,7 +39,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
|
||||
|
||||
## 2. platform / workflow(30)
|
||||
|
||||
工作流接口通过 Piper 客户端调用(`src/core/http/script-engine-client.ts`):
|
||||
工作流接口通过 Piper 客户端调用(`src/core/http/piper-workflow-client.ts`):
|
||||
`Authorization: Bearer <EASO JWT>`、`platformid: <platformId>`、可选 `hoseaccesstoken`。
|
||||
`listPlatforms` 例外,它走主站 `ekbClient`。
|
||||
|
||||
@@ -74,7 +74,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
|
||||
| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/workflow/transport/debug/api.ts:28` | 否 |
|
||||
| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:<jobId>|{id}|{jobId}}` | `src/domains/platform/workflow/transport/debug/api.ts:43` | 否 |
|
||||
| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/workflow/transport/catalog/api.ts:57` | 否 |
|
||||
| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/transport/catalog/api.ts:74` | 否 |
|
||||
| P30 | POST | `PIPER` / `PIPER_TEST` `/api/easo/dsl/corporation` | `{corporationId,dslTypes:[type],"recalculate-the-approval-flow":true,"ui-notification":true,start:0}`;Authorization: Bearer EASO JWT;`--is-test` 选择 `PIPER_TEST` | `{code,msg,data?}`;成功必须 `code:200` | `src/domains/platform/workflow/transport/catalog/api.ts:134` | 否 |
|
||||
|
||||
`Platform` 代码字段(`src/domains/platform/workflow/models/nodes.ts:5`):
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.0
|
||||
version: 0.9.10
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
@@ -27,9 +27,36 @@ list:
|
||||
- name: state
|
||||
in: query
|
||||
required: false
|
||||
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
|
||||
description: >-
|
||||
按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用
|
||||
「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。
|
||||
schema:
|
||||
type: string
|
||||
- name: template
|
||||
in: query
|
||||
required: false
|
||||
description: 草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希
|
||||
schema:
|
||||
type: string
|
||||
- name: title
|
||||
in: query
|
||||
required: false
|
||||
description: 草稿模式下按标题关键字过滤
|
||||
schema:
|
||||
type: string
|
||||
- name: staff
|
||||
in: query
|
||||
required: false
|
||||
description: 草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤
|
||||
schema:
|
||||
type: string
|
||||
- name: page
|
||||
in: query
|
||||
required: false
|
||||
description: 页码,与 count 配合分页(从 1 开始)
|
||||
schema:
|
||||
type: integer
|
||||
default: 1
|
||||
- name: count
|
||||
in: query
|
||||
required: false
|
||||
|
||||
+39
-2
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.10",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
@@ -662,11 +662,48 @@
|
||||
"name": "state",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)",
|
||||
"description": "按审批/支付状态过滤(paid 已支付, approving 审批中)。传 draft/草稿 时改用 「我发起」的 flows/my 草稿列表,因为草稿尚未进入台账索引。",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "template",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "草稿模式下按模板(表单规格)ID 过滤;版本化 ID 会剥离末尾哈希",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "title",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "草稿模式下按标题关键字过滤",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "staff",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "草稿模式下按提交人(员工 ID、工号或唯一姓名)过滤",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "page",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "页码,与 count 配合分页(从 1 开始)",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"default": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"in": "query",
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
import { COMMAND_METADATA } from "./cli/command-metadata.js";
|
||||
import { setAiProLicenseDeps, resetAiProLicenseDeps, saveAiProLicenseToken } from "./cli/aipro-license.js";
|
||||
import {
|
||||
AIPRO_COMMAND_REGISTRY,
|
||||
findAiProCommand,
|
||||
@@ -12,7 +17,28 @@ import {
|
||||
} from "./cli/aipro-registry.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
let licenseDir = "";
|
||||
|
||||
beforeEach(() => {
|
||||
// 门禁默认关闭:注入临时密钥对与有效凭证,让原有全链路用例无需改动
|
||||
licenseDir = mkdtempSync(join(tmpdir(), "hose-aipro-cli-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(licenseDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
const privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
const licensePayload = {
|
||||
v: 1,
|
||||
sub: "集成测试",
|
||||
exp: Math.floor(Date.now() / 1000) + 86_400,
|
||||
maxVersion: "99.99.99",
|
||||
features: ["aipro"],
|
||||
nonce: "integration",
|
||||
};
|
||||
const payloadBytes = Buffer.from(JSON.stringify(licensePayload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, privateKeyPem);
|
||||
saveAiProLicenseToken(`${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`);
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1" });
|
||||
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
@@ -31,6 +57,9 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
resetAiProLicenseDeps();
|
||||
rmSync(licenseDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("version/help --json only emit machine-readable stdout", async () => {
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import { handleAiProReport } from "./cli/commands/aipro/report.js";
|
||||
import { assertAiProEnabled, handleAiProLogin } from "./cli/aipro-license.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -38,6 +40,8 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
// multicall 二进制的 argv0 不进 parsed.raw,显式标注入口身份供命令层判断
|
||||
runtime.app = "hose-aipro";
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
@@ -97,11 +101,27 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "login" || command === "activate") {
|
||||
return handleAiProLogin(rawArgs, jsonMode);
|
||||
}
|
||||
if (booleanOption(parsed.options, ["version", "v"])) {
|
||||
const versionDef = findAiProCommand("version");
|
||||
if (versionDef) return await versionDef.handler(ctx);
|
||||
}
|
||||
|
||||
// 统一门禁:除只读自省命令外,其余 AI PRO 命令一律要求有效凭证。
|
||||
// 以后新增命令只需照常注册,自动被此处拦截,无需改动授权代码。
|
||||
const readOnly = new Set(["status", "whoami", "context", "info", "help", "version", "v"]);
|
||||
if (!readOnly.has(command)) {
|
||||
const licenseGate = assertAiProEnabled(jsonMode);
|
||||
if (licenseGate) return licenseGate;
|
||||
}
|
||||
|
||||
// 本地 Web 控制台的聚合数据源(只读,不进命令注册表)
|
||||
if (command === "report") {
|
||||
return handleAiProReport(ctx);
|
||||
}
|
||||
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
|
||||
+19
-2
@@ -15,6 +15,23 @@ process.stderr.on("error", (err: any) => {
|
||||
const entryFile = fileURLToPath(import.meta.url);
|
||||
const appRoot = dirname(dirname(entryFile));
|
||||
|
||||
// 命令行参数超时处理:--timeout [秒] / -T [秒]
|
||||
const args = process.argv.slice(2);
|
||||
for (let i = args.length - 1; i >= 0; i--) {
|
||||
if (args[i] === "--timeout" || args[i] === "-T") {
|
||||
if (i + 1 < args.length) {
|
||||
const timeoutSec = parseInt(args[i + 1], 10);
|
||||
if (!isNaN(timeoutSec) && timeoutSec > 0) {
|
||||
setTimeout(() => {
|
||||
console.error(`[ERROR] 命令执行超时 (${timeoutSec}秒)`);
|
||||
process.exit(1);
|
||||
}, timeoutSec * 1000);
|
||||
}
|
||||
args.splice(i, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
|
||||
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
|
||||
const isAiPro = candidates.some((c) => {
|
||||
@@ -23,8 +40,8 @@ const isAiPro = candidates.some((c) => {
|
||||
});
|
||||
|
||||
const result = isAiPro
|
||||
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
|
||||
: await runCli(process.argv.slice(2), {
|
||||
? await (await import("./aipro-cli.js")).runAiProCli(args)
|
||||
: await runCli(args, {
|
||||
appRoot,
|
||||
entryFile,
|
||||
writeStdout: writeStdoutChunk,
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
- `生产环境确认 (Production Safeguard)`:`src/cli/production.ts` 统一策略。正式生产企业 (`env === "prod"`) 执行敏感命令时,只要求显式追加 `--allow-prod` 表明操作者已知晓目标为生产企业,不禁止功能;`--force` 保留为兼容别名。预览 (`--dry-run`) 始终放行,不要求覆盖参数;实际执行仍遵守 `--dry-run`/`--yes` 两阶段确认。阻断统一返回文本提示或 JSON 错误 `PROD_OVERRIDE_REQUIRED`(含 `nextAction` 与 `details.operation`)。自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
||||
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
||||
- `help.ts`:帮助文本组织。
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertAiProEnabled,
|
||||
checkAiProLicense,
|
||||
compareBaseVersion,
|
||||
handleAiProLogin,
|
||||
resetAiProLicenseDeps,
|
||||
saveAiProLicenseToken,
|
||||
setAiProLicenseDeps,
|
||||
verifyAiProLicenseToken,
|
||||
} from "./aipro-license.js";
|
||||
|
||||
let tempDir = "";
|
||||
let privateKeyPem = "";
|
||||
|
||||
function issue(overrides: Record<string, unknown> = {}): string {
|
||||
const payload = {
|
||||
v: 1,
|
||||
sub: "测试客户",
|
||||
exp: 4_102_444_800,
|
||||
maxVersion: "0.9.99",
|
||||
features: ["aipro"],
|
||||
nonce: "test-nonce",
|
||||
...overrides,
|
||||
};
|
||||
const bytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, bytes, privateKeyPem);
|
||||
return `${bytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-aipro-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(tempDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1", nowSeconds: 1_700_000_000 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetAiProLicenseDeps();
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("版本上限", () => {
|
||||
test("三段数字比较,dev 后缀被忽略", () => {
|
||||
expect(compareBaseVersion("0.9.1-dev.2+gabc", "0.9.99")).toBe(-1);
|
||||
expect(compareBaseVersion("0.10.0", "0.9.99")).toBe(1);
|
||||
expect(compareBaseVersion("0.9.99-dev.3+gXXX", "0.9.99")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("双约束校验", () => {
|
||||
test("有效凭证放行", () => {
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("签名被篡改拒绝", () => {
|
||||
const [payload] = issue().split(".");
|
||||
const forged = `${payload}.${Buffer.from("bad").toString("base64url")}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("payload 改动后签名失配", () => {
|
||||
const [payload, signature] = issue().split(".");
|
||||
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
||||
decoded.exp = 9_999_999_999;
|
||||
const forged = `${Buffer.from(JSON.stringify(decoded)).toString("base64url")}.${signature}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("超过绝对到期时间拒绝", () => {
|
||||
setAiProLicenseDeps({ nowSeconds: 4_102_444_801 });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "expired" });
|
||||
});
|
||||
|
||||
test("当前版本超过上限拒绝,等于上限放行", () => {
|
||||
setAiProLicenseDeps({ version: "0.10.0" });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "version_exceeded" });
|
||||
setAiProLicenseDeps({ version: "0.9.99" });
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("缺少 aipro feature 拒绝", () => {
|
||||
expect(verifyAiProLicenseToken(issue({ features: ["other"] }))).toMatchObject({ ok: false, reason: "no_feature" });
|
||||
});
|
||||
|
||||
test("格式错误与非法版本上限拒绝", () => {
|
||||
expect(verifyAiProLicenseToken("not-a-token")).toMatchObject({ ok: false, reason: "malformed" });
|
||||
expect(verifyAiProLicenseToken(issue({ maxVersion: "latest" }))).toMatchObject({ ok: false, reason: "malformed" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("统一门禁与激活", () => {
|
||||
test("默认无凭证即未激活,门禁拦截", () => {
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
const blocked = assertAiProEnabled(false);
|
||||
expect(blocked?.exitCode).toBe(1);
|
||||
expect(blocked?.stderr).toContain("尚未激活");
|
||||
});
|
||||
|
||||
test("login 激活后门禁放行", () => {
|
||||
const result = handleAiProLogin(["login", issue()], false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("已激活");
|
||||
expect(assertAiProEnabled(false)).toBeNull();
|
||||
});
|
||||
|
||||
test("无效凭证激活失败且不落盘", () => {
|
||||
const result = handleAiProLogin(["login", "forged.token"], false);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
});
|
||||
|
||||
test("缺少凭证返回用法提示", () => {
|
||||
expect(handleAiProLogin(["login"], false).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("json 模式拦截返回结构化错误", () => {
|
||||
const blocked = assertAiProEnabled(true);
|
||||
expect(blocked?.stderr).toBe("");
|
||||
expect(JSON.parse(blocked?.stdout ?? "{}")).toMatchObject({ code: "AIPRO_NOT_ACTIVATED", reason: "missing" });
|
||||
});
|
||||
|
||||
test("凭证文件权限为 0600", () => {
|
||||
saveAiProLicenseToken(issue());
|
||||
expect(statSync(join(tempDir, "license.token")).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* AI PRO 离线授权:单文件,唯一门禁入口由 aipro-cli.ts 调用。
|
||||
*
|
||||
* 新增任意 AI PRO 命令都不需要改动本文件——门禁在分发层统一拦截。
|
||||
* 唯一例外是 login / activate,在门禁之前分流。
|
||||
*
|
||||
* 凭证:base64url(payload).base64url(Ed25519 签名)
|
||||
* payload:{ v, sub, exp, maxVersion, features, nonce }
|
||||
* 两条约束:当前版本 <= maxVersion;当前时间 <= exp(绝对到期,Unix 秒)。
|
||||
* 刻意不做:设备绑定、时钟防篡改、激活时间锚点、相对时长上限。
|
||||
*/
|
||||
import { createPublicKey, verify } from "node:crypto";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { VERSION } from "../version.js";
|
||||
import { parseArgs, stringOption } from "./parser.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { CliResult } from "./types.js";
|
||||
|
||||
/** 验签公钥(随源码编译进二进制)。私钥由签发方离线保管,绝不进仓库。
|
||||
* SHA-256(SPKI DER): f5ead0d75667c259afae00474040177012fa2de4509e6dfa9c2eb7c25f1ad403
|
||||
* 更换此公钥会使所有已签发凭证失效,发版后不得随意变更。
|
||||
*/
|
||||
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEA0e0mcz9TnKnVJAEmr96mOc+9OineoekA3tY/UhGE7mo=
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export const AIPRO_LICENSE_FILE_ENV = "HOSE_AIPRO_LICENSE_FILE";
|
||||
|
||||
interface LicensePayload {
|
||||
v: 1;
|
||||
sub: string;
|
||||
exp: number;
|
||||
maxVersion: string;
|
||||
features: string[];
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export type LicenseCheck =
|
||||
| { ok: true; payload: LicensePayload }
|
||||
| { ok: false; reason: "missing" | "malformed" | "bad_signature" | "no_feature" | "expired" | "version_exceeded"; message: string };
|
||||
|
||||
interface LicenseDeps {
|
||||
publicKeyPem: string;
|
||||
version: string;
|
||||
nowSeconds?: number;
|
||||
}
|
||||
|
||||
const defaults: LicenseDeps = { publicKeyPem: PUBLIC_KEY.trim(), version: VERSION };
|
||||
let deps: LicenseDeps = { ...defaults };
|
||||
|
||||
/** 进程内依赖注入,仅供单元测试使用;CLI 运行时不暴露。 */
|
||||
export function setAiProLicenseDeps(partial: Partial<LicenseDeps>): void {
|
||||
deps = { ...deps, ...partial };
|
||||
}
|
||||
|
||||
export function resetAiProLicenseDeps(): void {
|
||||
deps = { ...defaults };
|
||||
}
|
||||
|
||||
export function resolveAiProLicenseFile(): string {
|
||||
const explicit = process.env[AIPRO_LICENSE_FILE_ENV]?.trim();
|
||||
if (explicit) return explicit;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "aipro-license.token");
|
||||
return join(homedir(), ".config", "hose-use", "aipro-license.token");
|
||||
}
|
||||
|
||||
export function saveAiProLicenseToken(token: string): string {
|
||||
const file = resolveAiProLicenseFile();
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(file, token.trim(), { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(file, 0o600);
|
||||
} catch {
|
||||
// 写入时的 mode 已生效
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
function loadToken(): string | null {
|
||||
try {
|
||||
const file = resolveAiProLicenseFile();
|
||||
return existsSync(file) ? readFileSync(file, "utf-8").trim() || null : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 只取 x.y.z 三段数字,忽略 -dev.N+gXXX 等后缀。 */
|
||||
export function compareBaseVersion(a: string, b: string): number {
|
||||
const parse = (v: string): [number, number, number] | null => {
|
||||
const m = v.match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
||||
};
|
||||
const left = parse(a);
|
||||
const right = parse(b);
|
||||
if (!left || !right) throw new Error(`非法版本号: ${a} 或 ${b}`);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function parsePayload(text: string): LicensePayload | null {
|
||||
try {
|
||||
const p = JSON.parse(text);
|
||||
if (p.v !== 1 || typeof p.sub !== "string" || !p.sub) return null;
|
||||
if (!Number.isInteger(p.exp) || p.exp <= 0) return null;
|
||||
if (typeof p.maxVersion !== "string" || !/^\d+\.\d+\.\d+$/.test(p.maxVersion)) return null;
|
||||
if (!Array.isArray(p.features) || !p.features.every((f: unknown) => typeof f === "string")) return null;
|
||||
if (typeof p.nonce !== "string" || !p.nonce) return null;
|
||||
return p as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyAiProLicenseToken(token: string): LicenseCheck {
|
||||
const parts = token.trim().split(".");
|
||||
if (parts.length !== 2 || !parts[0] || !parts[1]) {
|
||||
return { ok: false, reason: "malformed", message: "凭证格式错误:应为 <payload>.<signature> 两段" };
|
||||
}
|
||||
|
||||
let payloadBytes: Buffer;
|
||||
let signature: Buffer;
|
||||
try {
|
||||
payloadBytes = Buffer.from(parts[0], "base64url");
|
||||
signature = Buffer.from(parts[1], "base64url");
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: "凭证编码错误:无法按 base64url 解码" };
|
||||
}
|
||||
|
||||
let valid = false;
|
||||
try {
|
||||
valid = verify(null, payloadBytes, createPublicKey(deps.publicKeyPem), signature);
|
||||
} catch {
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return { ok: false, reason: "bad_signature", message: "凭证签名无效,可能被篡改或并非本工具签发" };
|
||||
|
||||
const payload = parsePayload(payloadBytes.toString("utf-8"));
|
||||
if (!payload) return { ok: false, reason: "malformed", message: "凭证内容无效:字段缺失或格式不符" };
|
||||
if (!payload.features.includes("aipro")) {
|
||||
return { ok: false, reason: "no_feature", message: "该凭证未包含 AI PRO 授权" };
|
||||
}
|
||||
|
||||
const now = deps.nowSeconds ?? Math.floor(Date.now() / 1000);
|
||||
if (now > payload.exp) {
|
||||
const date = new Date(payload.exp * 1000).toISOString().slice(0, 10);
|
||||
return { ok: false, reason: "expired", message: `授权凭证已于 ${date} 到期,请重新申请凭证` };
|
||||
}
|
||||
|
||||
try {
|
||||
if (compareBaseVersion(deps.version, payload.maxVersion) > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "version_exceeded",
|
||||
message: `当前版本 v${deps.version} 超出授权上限 v${payload.maxVersion},请重新申请凭证`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: `凭证版本上限非法: ${payload.maxVersion}` };
|
||||
}
|
||||
|
||||
return { ok: true, payload };
|
||||
}
|
||||
|
||||
export function checkAiProLicense(): LicenseCheck {
|
||||
const token = loadToken();
|
||||
if (!token) {
|
||||
return { ok: false, reason: "missing", message: "AI PRO 尚未激活。凭证需向服务方离线申请,拿到后直接粘贴给 AI 助手完成激活" };
|
||||
}
|
||||
return verifyAiProLicenseToken(token);
|
||||
}
|
||||
|
||||
/** 统一门禁:返回拦截结果,null 表示放行。 */
|
||||
export function assertAiProEnabled(jsonMode: boolean): CliResult | null {
|
||||
const status = checkAiProLicense();
|
||||
if (status.ok) return null;
|
||||
const hint = status.reason === "missing"
|
||||
? "\n下一步: 向服务方申请凭证(提供 hose-aipro version 的版本号与期望到期日),把凭证粘贴给 AI 助手,或自行运行 hose-aipro login '<凭证>'"
|
||||
: "\n下一步: 联系服务方重新申请凭证";
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, code: "AIPRO_NOT_ACTIVATED", reason: status.reason, message: status.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 未激活] ${status.message}${hint}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/** login 不进注册表,由分发层在门禁之前直接分流,避免任何注册表/元数据同步。 */
|
||||
export function handleAiProLogin(rawArgs: string[], jsonMode: boolean): CliResult {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const token =
|
||||
stringOption(parsed.options, ["token", "license", "credential", "code"]) ||
|
||||
parsed.positional?.slice(1).find((part) => part && !part.startsWith("-")) ||
|
||||
"";
|
||||
|
||||
if (!token.trim()) {
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ error: true, message: "缺少凭证" }) + "\n" : "",
|
||||
stderr: jsonMode
|
||||
? ""
|
||||
: "[AI PRO 激活] 缺少凭证。\n用法: hose-aipro login <凭证>\n 或: hose-aipro login --token=<凭证>\n",
|
||||
exitCode: 2,
|
||||
};
|
||||
}
|
||||
|
||||
const result = verifyAiProLicenseToken(token.trim());
|
||||
if (!result.ok) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, activated: false, reason: result.reason, message: result.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 激活失败] ${result.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const file = saveAiProLicenseToken(token.trim());
|
||||
const { sub, exp, maxVersion } = result.payload;
|
||||
const expiresAt = new Date(exp * 1000).toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ activated: true, subject: sub, expiresAt, maxVersion, licenseFile: file }) + "\n"
|
||||
: `AI PRO 已激活。\n 授权对象: ${sub}\n 到期时间: ${expiresAt}\n 版本上限: v${maxVersion}\n 凭证文件: ${file} (0600)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -277,8 +277,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)",
|
||||
"outbound": "查询合思系统出站消息规则与投递日志 (list|logs)"
|
||||
},
|
||||
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
@@ -286,6 +288,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--is-test 选择测试 Piper;每个企业的工作流只在标准/测试环境之一,不会自动回退",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
@@ -332,9 +335,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"webhook-send": "webhook",
|
||||
"webhooks": "webhook",
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
"web": "link",
|
||||
"outbounds": "outbound",
|
||||
"outbound-message": "outbound"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c 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 save-sample saveSample save-samples saveSamples snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -358,8 +365,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
|
||||
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态/行程dataLinkId)",
|
||||
"copy": "复制单据为新草稿(支持报销单与申请单,不提交)",
|
||||
"edit": "编辑草稿单据字段(仅 draft,支持标题/事由/金额/差旅日期,需 --yes)",
|
||||
"delete": "删除草稿单据(仅 draft,需 --yes)",
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)",
|
||||
"create": "按模板创建单据草稿(不提交)",
|
||||
@@ -369,6 +377,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容",
|
||||
"--state=draft/草稿 查询未提交草稿(数据源为 flows/my),支持 --template/--title/--staff/--page 过滤",
|
||||
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"aliases": [
|
||||
@@ -406,9 +415,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"files": "attachments",
|
||||
"file-download": "download",
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
"specification": "spec",
|
||||
"update": "edit"
|
||||
},
|
||||
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") }
|
||||
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days description dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
@@ -440,7 +450,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"show": "get",
|
||||
"find": "get"
|
||||
},
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir page participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
@@ -897,6 +907,41 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||
...flagList("status", "boolean-or-value")
|
||||
}
|
||||
},
|
||||
"docs": {
|
||||
"summary": "合思开放平台官方接口文档与端点规范检索",
|
||||
"usage": "hose-use docs <search|show|categories|sync> [关键词|路径] [--json]",
|
||||
"commands": {
|
||||
"search": "按关键词、分类或方法检索开放平台 HTTP 接口",
|
||||
"show": "查看指定接口的完整规范、参数定义、CURL 与响应示例",
|
||||
"categories": "查看开放平台所有业务模块分类与端点统计",
|
||||
"sync": "强制与线上文档中心全量同步最新索引"
|
||||
},
|
||||
"aliases": [
|
||||
"doc",
|
||||
"api-doc",
|
||||
"api-docs"
|
||||
],
|
||||
"commandAliases": {
|
||||
"find": "search",
|
||||
"list": "search",
|
||||
"ls": "search",
|
||||
"get": "show",
|
||||
"info": "show",
|
||||
"cat": "show",
|
||||
"read": "show",
|
||||
"detail": "show",
|
||||
"category": "categories",
|
||||
"cats": "categories",
|
||||
"modules": "categories",
|
||||
"groups": "categories",
|
||||
"update": "sync",
|
||||
"refresh": "sync"
|
||||
},
|
||||
flags: {
|
||||
...flagList("keyword query q category cat module method m path p target id name url limit count n", "value"),
|
||||
...flagList("refresh sync force", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# AI PRO 命令层
|
||||
|
||||
`hose-aipro` 专属命令的 handler,由 `src/cli/aipro-registry.ts` 注册,经 `src/aipro-cli.ts` 的统一凭证门禁后分发。只读自省命令(`status` / `version` / `help` 等)豁免门禁,其余一律要求有效离线凭证。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `status.ts` | 网关运行上下文、企业信息与帮助页 |
|
||||
| `rules.ts` | 规约场景、审核要点、核验清单 |
|
||||
| `bind.ts` | 单据挂载与会话初始化 |
|
||||
| `review.ts` | 事实证据核验打标(PASS / FAIL / SKIP) |
|
||||
| `decide.ts` | 确定性仲裁与流转 |
|
||||
| `logs.ts` | 审计流水查询 |
|
||||
| `service.ts` | 常驻服务控制 |
|
||||
| `report.ts` | `report --json` 聚合数据源,供本地 Web 控制台一次拉取场景 / 规则 / 会话 / 要点 / 流水 / 授权状态 |
|
||||
|
||||
`types.ts` 定义 `AiProExecutionContext` 与命令结果类型;`index.ts` 汇总导出。新增命令照常注册即可自动受门禁管辖,不需要改授权代码。
|
||||
|
||||
**边界**:凭证只作用于 `hose-aipro`;`hose-use` 是免费功能,不受任何激活门禁约束。
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeDatabase, getDatabase } from "../../../core/db/index.js";
|
||||
import { ApprovalRepository } from "../../../domains/approval/repository.js";
|
||||
import { handleAiProReport } from "./report.js";
|
||||
|
||||
describe("handleAiProReport 聚合数据", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("返回场景/规则/会话/要点/流水与授权状态", () => {
|
||||
const repo = new ApprovalRepository(getDatabase(":memory:"));
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传真实发票]{硬性},[建议填写详细事由]{建议}。",
|
||||
});
|
||||
|
||||
const result = handleAiProReport({
|
||||
repo,
|
||||
corp: null,
|
||||
corpId: undefined,
|
||||
operator: "tester",
|
||||
} as never);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.summary.rules).toBe(1);
|
||||
expect(payload.summary.scopes).toBeGreaterThanOrEqual(1);
|
||||
expect(Array.isArray(payload.scopes)).toBe(true);
|
||||
expect(Array.isArray(payload.rules)).toBe(true);
|
||||
expect(Array.isArray(payload.runs)).toBe(true);
|
||||
expect(Array.isArray(payload.findings)).toBe(true);
|
||||
expect(Array.isArray(payload.logs)).toBe(true);
|
||||
expect(payload.license).toBeDefined();
|
||||
expect(payload.generatedAt).toBeTruthy();
|
||||
// 单据快照等大字段不应出现在报表里
|
||||
expect(result.stdout).not.toContain("documentSnapshot");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { printJson } from "../../printer.js";
|
||||
import { VERSION } from "../../../version.js";
|
||||
import { checkAiProLicense } from "../../aipro-license.js";
|
||||
import type { AiProCommandResult, AiProExecutionContext } from "./types.js";
|
||||
|
||||
/**
|
||||
* hose-aipro report --json:本地 Web 控制台的聚合数据源。
|
||||
* 只读、不联网;单据快照等大字段不返回,避免撑爆浏览器。
|
||||
*/
|
||||
export function handleAiProReport(ctx: AiProExecutionContext): AiProCommandResult {
|
||||
const { repo, corp, corpId, operator } = ctx;
|
||||
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = repo.listRuns({ corpId, limit: 500 });
|
||||
const logs = repo.listAiProLogs(undefined, 200);
|
||||
const license = checkAiProLicense();
|
||||
|
||||
const runRows = runs.map((run) => ({
|
||||
id: run.id,
|
||||
shortId: run.shortId,
|
||||
documentSn: run.documentSn,
|
||||
corpId: run.corpId,
|
||||
decision: run.decision,
|
||||
createdAt: run.createdAt,
|
||||
updatedAt: run.updatedAt,
|
||||
findingsCount: repo.getFindingsByRunId(run.id).length,
|
||||
}));
|
||||
|
||||
const findings = runs.flatMap((run) =>
|
||||
repo.getFindingsByRunId(run.id).map((finding) => ({
|
||||
runId: run.shortId || run.id,
|
||||
documentSn: run.documentSn,
|
||||
ruleCode: finding.ruleCode,
|
||||
status: finding.checkStatus,
|
||||
strictness: finding.strictness,
|
||||
content: finding.clauseText,
|
||||
evidence: finding.evidence,
|
||||
reasoning: finding.reasoning,
|
||||
}))
|
||||
);
|
||||
|
||||
const payload = {
|
||||
version: VERSION,
|
||||
generatedAt: new Date().toISOString(),
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corp.credentials?.staffId || corp.staffId || null,
|
||||
baseUrl: corp.baseUrl || null,
|
||||
source: corp.source || null,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
license: license.ok
|
||||
? {
|
||||
activated: true,
|
||||
subject: license.payload.sub,
|
||||
expiresAt: new Date(license.payload.exp * 1000).toISOString(),
|
||||
maxVersion: license.payload.maxVersion,
|
||||
}
|
||||
: { activated: false, reason: license.reason, message: license.message },
|
||||
summary: {
|
||||
scopes: scopes.length,
|
||||
rules: rules.length,
|
||||
runs: runRows.length,
|
||||
pending: runRows.filter((run) => run.decision === "PENDING").length,
|
||||
findings: findings.length,
|
||||
logs: logs.length,
|
||||
},
|
||||
scopes,
|
||||
rules,
|
||||
runs: runRows,
|
||||
findings,
|
||||
logs,
|
||||
};
|
||||
|
||||
return { stdout: printJson(payload) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||
import {
|
||||
approveAssistTicket,
|
||||
listAssistTickets,
|
||||
|
||||
@@ -11,6 +11,9 @@ import {
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
// ... other imports ...
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
export async function handleLogin(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -184,6 +187,18 @@ export async function handleLogin(
|
||||
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
|
||||
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
|
||||
process.stdout.write(`${qrText}\n\n`);
|
||||
|
||||
// 自动保存二维码
|
||||
const downloadsDir = path.join(os.homedir(), "Downloads");
|
||||
const qrPath = path.join(downloadsDir, "dingtalk-login.png");
|
||||
(async () => {
|
||||
const QRCode = await import("qrcode");
|
||||
await QRCode.toFile(qrPath, dingUrl);
|
||||
process.stdout.write(`💡 二维码已自动保存至: ${qrPath}\n\n`);
|
||||
})().catch((e: Error) => {
|
||||
process.stdout.write(`[WARN] 自动保存二维码失败: ${e.message}\n\n`);
|
||||
});
|
||||
|
||||
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
|
||||
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
getActiveAccount,
|
||||
setActiveAccount,
|
||||
} from "../../core/auth/account-store.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|---|---|
|
||||
| [search.ts](./search.ts) | 列表、详情和定位诊断 |
|
||||
| [templates.ts](./templates.ts)、[meta.ts](./meta.ts) | 可用模板、字段规格、结构与链接 |
|
||||
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[delete.ts](./delete.ts) | 草稿创建、复制与删除 |
|
||||
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[edit.ts](./edit.ts)、[delete.ts](./delete.ts) | 草稿创建、复制(含申请单/行程适配)、编辑与删除 |
|
||||
| [validate.ts](./validate.ts)、[submit.ts](./submit.ts) | 现有草稿校验及提交 |
|
||||
| [approve.ts](./approve.ts) | 同意、驳回、转交、加签、评论的命令适配 |
|
||||
| [flow.ts](./flow.ts)、[related.ts](./related.ts) | 审批时间线、风险预算、关联记录与附件 |
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
|
||||
|
||||
@@ -1,53 +1,62 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import { buildBillCopyForm, copyBillAsDraft } from "../../../domains/bill/copy.js";
|
||||
import type { BillDraftForm } from "../../../domains/bill/draft-validation.js";
|
||||
import { copyBillAsDraft, prepareBillCopy } from "../../../domains/bill/copy.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
|
||||
if (!period?.start || !period?.end) return "-";
|
||||
const fmt = (ms: number) =>
|
||||
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
|
||||
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
|
||||
* `hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--drop-attachments] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
|
||||
* 纯接口复制(支持报销单与差旅/常规申请单):
|
||||
* 读取服务端最新表单 → 重置行程 dataLinkId 为 null / 清空发票绑定 → 一致性校验 → 创建新草稿。
|
||||
* 只创建草稿,不提交。
|
||||
*/
|
||||
export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] --yes");
|
||||
throw new Error(
|
||||
"请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
|
||||
);
|
||||
}
|
||||
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const reason = stringOption(parsed.options, ["reason", "description"]);
|
||||
const amount = stringOption(parsed.options, ["amount"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
|
||||
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
|
||||
const copyOptions = { title, reason, amount, startDate, endDate, keepAttachments };
|
||||
|
||||
const client = await ctx.getClient();
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
|
||||
if (!form) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据,无法复制\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const copy = buildBillCopyForm(form, { title, keepAttachments });
|
||||
const prepared = await prepareBillCopy(client, corpId, target, copyOptions);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
dryRun: true,
|
||||
source: target,
|
||||
sourceTitle: form.title,
|
||||
title: copy.title,
|
||||
detailCount: copy.details?.length ?? 0,
|
||||
expenseMoney: copy.expenseMoney?.standard,
|
||||
sourceTitle: prepared.sourceTitle,
|
||||
title: prepared.form.title,
|
||||
formType: prepared.formType,
|
||||
detailCount: prepared.detailCount,
|
||||
expenseMoney: prepared.expenseMoney,
|
||||
amount: prepared.amount,
|
||||
tripCount: prepared.tripCount,
|
||||
dataLinkIdsReset: prepared.dataLinkIdsReset,
|
||||
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
|
||||
keepAttachments,
|
||||
invoicesCleared: true,
|
||||
invoicesCleared: prepared.formType === "expense",
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -55,23 +64,41 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 复制单据(dry-run,未创建) ======`,
|
||||
` 源单 : ${target}(${prepared.sourceTitle || "-"})`,
|
||||
` 类型 : ${prepared.formType}`,
|
||||
` 新标题 : ${prepared.form.title ?? "-"}`,
|
||||
];
|
||||
if (prepared.form.description) {
|
||||
lines.push(` 事由 : ${prepared.form.description}`);
|
||||
}
|
||||
if (prepared.formType === "expense") {
|
||||
lines.push(` 明细 : ${prepared.detailCount} 条`);
|
||||
lines.push(` 金额 : ${prepared.expenseMoney} CNY`);
|
||||
lines.push(` 发票 : 清空绑定,发票总额归零`);
|
||||
} else {
|
||||
lines.push(` 金额 : ${prepared.amount} CNY`);
|
||||
if (prepared.feeDatePeriod) {
|
||||
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
|
||||
}
|
||||
if (prepared.tripCount > 0) {
|
||||
lines.push(` 行程 : ${prepared.tripCount} 条(dataLinkId 已重置为 null)`);
|
||||
}
|
||||
}
|
||||
lines.push(` 附件 : ${keepAttachments ? "保留" : "清空"}`);
|
||||
lines.push("", "提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)", "");
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`====== 复制单据(dry-run,未创建) ======\n` +
|
||||
` 源单 : ${target}(${form.title ?? "-"})\n` +
|
||||
` 新标题 : ${copy.title ?? "-"}\n` +
|
||||
` 明细 : ${copy.details?.length ?? 0} 条\n` +
|
||||
` 金额 : ${copy.expenseMoney?.standard ?? "0"} CNY\n` +
|
||||
` 附件 : ${keepAttachments ? "保留" : "清空"}\n` +
|
||||
` 发票 : 清空绑定,发票总额归零\n` +
|
||||
`\n提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)\n`,
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
|
||||
const result = await copyBillAsDraft(client, corpId, target, copyOptions);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -81,8 +108,11 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
flowId: result.flowId,
|
||||
code: result.code,
|
||||
title: result.title,
|
||||
formType: result.formType,
|
||||
detailCount: result.detailCount,
|
||||
expenseMoney: result.expenseMoney,
|
||||
amount: result.amount,
|
||||
tripCount: result.tripCount,
|
||||
submitted: false,
|
||||
},
|
||||
runtime.outputOptions
|
||||
@@ -92,13 +122,19 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
};
|
||||
}
|
||||
|
||||
const summaryLine =
|
||||
result.formType === "expense"
|
||||
? ` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`
|
||||
: ` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`;
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`复制成功(已创建草稿,未提交)\n` +
|
||||
` 新单号 : ${result.code}\n` +
|
||||
` 单据 ID : ${result.flowId}\n` +
|
||||
` 类型 : ${result.formType}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
|
||||
summaryLine,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleEdit } from "./edit.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
|
||||
function makeReqFixture() {
|
||||
const writes: Array<{ url: string; json: any }> = [];
|
||||
const sourceForm = {
|
||||
code: "S26003502",
|
||||
title: "旧差旅标题",
|
||||
description: "旧事由",
|
||||
specificationId: `reqSpec:${"a".repeat(32)}`,
|
||||
submitterId: "staff-1",
|
||||
requisitionDate: 1784563200000,
|
||||
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
|
||||
u_差旅天数: "2",
|
||||
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
|
||||
u_行程规划: [
|
||||
{
|
||||
dataLinkId: "OLD_TRIP_ID",
|
||||
dataLinkTemplateId: "tpl-trip",
|
||||
dataLinkForm: { E_x_行程开始日期: "2026-07-24", E_x_行程结束日期: "2026-07-25" },
|
||||
},
|
||||
],
|
||||
};
|
||||
const draftForm = structuredClone(sourceForm) as Record<string, any>;
|
||||
draftForm.code = "S26005804";
|
||||
draftForm.u_行程规划[0].dataLinkId = null;
|
||||
|
||||
const client = {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url.includes("specifications/")) {
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
id: "reqSpec",
|
||||
name: "4.1日常差旅申请单",
|
||||
type: "requisition",
|
||||
components: [
|
||||
{ field: "title", optional: false },
|
||||
{ field: "u_行程规划", type: "dataLinkEdits", optional: false },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { items: [] };
|
||||
},
|
||||
}),
|
||||
post: (url: string, payload: { json: any }) => ({
|
||||
json: async () => {
|
||||
if (url.endsWith("/flows/searchByCode")) {
|
||||
return {
|
||||
items: [
|
||||
{ id: "ID01SRC", form: sourceForm },
|
||||
{ id: "ID01DRAFT", form: draftForm },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (url.includes("/flows/flowId/")) {
|
||||
const isDraft = url.includes("ID01DRAFT");
|
||||
return {
|
||||
value: {
|
||||
id: isDraft ? "ID01DRAFT" : "ID01SRC",
|
||||
state: isDraft ? "draft" : "paid",
|
||||
formType: "requisition",
|
||||
form: isDraft ? draftForm : sourceForm,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (url.includes("/backlogs/") || url.endsWith("/flows/my") || url.endsWith("/flows/approved") || url.endsWith("/carbonCopy/search")) {
|
||||
return { items: [] };
|
||||
}
|
||||
writes.push({ url, json: payload.json });
|
||||
return { flow: { id: "ID01DRAFT", form: { ...(payload.json?.form ?? {}), code: payload.json?.form?.code ?? "S26005999" } } };
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const context = (args: string[]) =>
|
||||
({
|
||||
parsed: parseArgs(args),
|
||||
runtime: { jsonMode: true },
|
||||
corpId: "corp",
|
||||
getClient: async () => client,
|
||||
requireWriteConfirmation: async () => {},
|
||||
}) as any;
|
||||
|
||||
return { writes, context };
|
||||
}
|
||||
|
||||
test("bill copy 支持申请单 --dry-run 预览并校验,不发写请求", async () => {
|
||||
const { writes, context } = makeReqFixture();
|
||||
const res = await handleCopy(
|
||||
context([
|
||||
"bill",
|
||||
"copy",
|
||||
"S26003502",
|
||||
"--title",
|
||||
"新差旅标题",
|
||||
"--reason",
|
||||
"团建",
|
||||
"--amount",
|
||||
"1000",
|
||||
"--start-date",
|
||||
"2026-12-04",
|
||||
"--end-date",
|
||||
"2026-12-05",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
])
|
||||
);
|
||||
const out = JSON.parse(res.stdout);
|
||||
expect(out.dryRun).toBe(true);
|
||||
expect(out.formType).toBe("requisition");
|
||||
expect(out.tripCount).toBe(1);
|
||||
expect(out.dataLinkIdsReset).toBe(true);
|
||||
expect(out.amount).toBe("1000");
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
test("bill edit 支持 --dry-run 预览与 --yes 保存草稿", async () => {
|
||||
const { writes, context } = makeReqFixture();
|
||||
const preview = await handleEdit(
|
||||
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--dry-run", "--json"])
|
||||
);
|
||||
const pOut = JSON.parse(preview.stdout);
|
||||
expect(pOut.dryRun).toBe(true);
|
||||
expect(pOut.beforeTitle).toBe("旧差旅标题");
|
||||
expect(pOut.afterTitle).toBe("更新后标题");
|
||||
expect(writes).toEqual([]);
|
||||
|
||||
const saved = await handleEdit(
|
||||
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--yes", "--json"])
|
||||
);
|
||||
const sOut = JSON.parse(saved.stdout);
|
||||
expect(sOut.updated).toBe(true);
|
||||
expect(sOut.title).toBe("更新后标题");
|
||||
expect(sOut.description).toBe("新事由");
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0].json.name).toBe("freeflow.edit");
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { editBillDraft, prepareBillEdit } from "../../../domains/bill/write.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
|
||||
if (!period?.start || !period?.end) return "-";
|
||||
const fmt = (ms: number) =>
|
||||
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
|
||||
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `hose-use bill edit <单号|ID> [--title=...] [--reason=...] [--description=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--dry-run] --yes`
|
||||
*
|
||||
* 仅允许编辑 `draft` 状态草稿(`freeflow.edit`)。
|
||||
*/
|
||||
export async function handleEdit(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error(
|
||||
"请提供要编辑的草稿单号或 ID: hose-use bill edit <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
|
||||
);
|
||||
}
|
||||
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const reason = stringOption(parsed.options, ["reason", "description"]);
|
||||
const amount = stringOption(parsed.options, ["amount"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
|
||||
const editOptions = { title, reason, amount, startDate, endDate };
|
||||
|
||||
const client = await ctx.getClient();
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const prepared = await prepareBillEdit(client, corpId, target, editOptions);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
dryRun: true,
|
||||
code: prepared.code,
|
||||
flowId: prepared.flowId,
|
||||
formType: prepared.formType,
|
||||
beforeTitle: prepared.beforeTitle,
|
||||
afterTitle: prepared.afterTitle,
|
||||
beforeDescription: prepared.beforeDescription,
|
||||
afterDescription: prepared.afterDescription,
|
||||
amount: prepared.amount,
|
||||
tripCount: prepared.tripCount,
|
||||
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 编辑草稿(dry-run,未保存) ======`,
|
||||
` 单号 : ${prepared.code}(${prepared.flowId})`,
|
||||
` 类型 : ${prepared.formType}`,
|
||||
` 标题 : ${prepared.beforeTitle === prepared.afterTitle ? prepared.afterTitle : `${prepared.beforeTitle} -> ${prepared.afterTitle}`}`,
|
||||
` 事由 : ${prepared.beforeDescription === prepared.afterDescription ? (prepared.afterDescription || "-") : `${prepared.beforeDescription || "(空)"} -> ${prepared.afterDescription || "(空)"}`}`,
|
||||
` 金额 : ${prepared.amount} CNY`,
|
||||
];
|
||||
if (prepared.feeDatePeriod) {
|
||||
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
|
||||
}
|
||||
if (prepared.tripCount > 0) {
|
||||
lines.push(` 行程 : ${prepared.tripCount} 条`);
|
||||
}
|
||||
lines.push("", "提示: 确认无误后追加 --yes 保存草稿(不会提交)", "");
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await editBillDraft(client, corpId, target, editOptions);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
updated: true,
|
||||
code: result.code,
|
||||
flowId: result.flowId,
|
||||
title: result.title,
|
||||
description: result.description,
|
||||
formType: result.formType,
|
||||
amount: result.amount,
|
||||
tripCount: result.tripCount,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`草稿保存成功(未提交)\n` +
|
||||
` 单号 : ${result.code}\n` +
|
||||
` 单据 ID : ${result.flowId}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 事由 : ${result.description || "-"}\n` +
|
||||
` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { handleRefs, handleRelations, handleAttachments, handleDownload } from "
|
||||
import { handleSchema, handleLink, handleSpec } from "./meta.js";
|
||||
import { handleValidate } from "./validate.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleEdit } from "./edit.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleTemplates } from "./templates.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
@@ -120,6 +121,10 @@ export async function handleBillCommand(
|
||||
case "clone":
|
||||
return handleCopy(ctx);
|
||||
|
||||
case "edit":
|
||||
case "update":
|
||||
return handleEdit(ctx);
|
||||
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "remove":
|
||||
@@ -140,6 +145,6 @@ export async function handleBillCommand(
|
||||
return handleSubmit(ctx);
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, edit <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import * as session from "../../../core/http/hose-web-session-client.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { createBillActionContext } from "./context.js";
|
||||
import { handleList } from "./search.js";
|
||||
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
afterEach(() => {
|
||||
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
|
||||
});
|
||||
|
||||
function json(value: unknown): Response {
|
||||
return new Response(JSON.stringify(value));
|
||||
}
|
||||
|
||||
function draftClient(corpId: string) {
|
||||
const flowsPosts: any[] = [];
|
||||
const client = {
|
||||
get: async (url: string) => {
|
||||
if (url.includes("staffs/actives")) {
|
||||
return json({ items: [{ id: "staff-1", name: "张三", code: "1001" }] });
|
||||
}
|
||||
return json({});
|
||||
},
|
||||
post: async (url: string, payload: any) => {
|
||||
if (url.includes("datalink/entity/search")) return json({ items: [] });
|
||||
if (url.endsWith("/flows/my")) {
|
||||
flowsPosts.push({ url, payload, corpId });
|
||||
return json({
|
||||
count: 1,
|
||||
items: [{
|
||||
flow: {
|
||||
id: "flow-cli-draft",
|
||||
state: "draft",
|
||||
formType: "payment",
|
||||
createTime: 1781682826000,
|
||||
updateTime: 1781682870000,
|
||||
},
|
||||
form: {
|
||||
code: "FK26000009",
|
||||
title: "付款草稿CLI",
|
||||
specificationId: { id: "spec-pay", name: "对公付款单" },
|
||||
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||
payMoney: { standard: "10.00", standardSymbol: "¥", standardStrCode: "CNY" },
|
||||
},
|
||||
}],
|
||||
});
|
||||
}
|
||||
return json({});
|
||||
},
|
||||
};
|
||||
return { client, flowsPosts };
|
||||
}
|
||||
|
||||
function context(args: string[], corpId: string, jsonMode: boolean) {
|
||||
const corp = { id: corpId, name: "测试企业", credentials: { corpId } };
|
||||
return createBillActionContext(parseArgs(args), { jsonMode, selectedCorp: corp } as any);
|
||||
}
|
||||
|
||||
describe("bill list draft mode", () => {
|
||||
it("routes --state=draft to flows/my with template, title, submitter and page filters", async () => {
|
||||
const { client, flowsPosts } = draftClient("cli-draft-corp-json");
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
|
||||
|
||||
const args = [
|
||||
"bill", "list", "--state=draft", "--mine",
|
||||
`--template=spec-pay:${"a".repeat(32)}`,
|
||||
"--title=付款", "--staff=张三",
|
||||
"--page=2", "--count=10", "--json",
|
||||
];
|
||||
const result = await handleList(context(args, "cli-draft-corp-json", true));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const output = JSON.parse(result.stdout);
|
||||
expect(output.total).toBe(1);
|
||||
expect(output.items[0]).toMatchObject({
|
||||
billId: "flow-cli-draft",
|
||||
billCode: "FK26000009",
|
||||
billName: "付款草稿CLI",
|
||||
state: "draft",
|
||||
});
|
||||
expect(output.items[0].amount).toContain("10.00");
|
||||
|
||||
expect(flowsPosts).toHaveLength(1);
|
||||
const filterBy = flowsPosts[0].payload.json.filterBy as string;
|
||||
expect(filterBy).toContain('(state.in("draft"))');
|
||||
expect(filterBy).toContain('INSTR(form.title, "付款")');
|
||||
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
|
||||
expect(filterBy).not.toContain("a".repeat(32));
|
||||
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
|
||||
expect(flowsPosts[0].payload.json.limit).toEqual({ start: 10, count: 10 });
|
||||
expect(flowsPosts[0].payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
|
||||
});
|
||||
|
||||
it("renders a draft-specific text header for --state=草稿", async () => {
|
||||
const { client } = draftClient("cli-draft-corp-text");
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue(client as any));
|
||||
|
||||
const result = await handleList(context(["bill", "list", "--state=草稿"], "cli-draft-corp-text", false));
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("单据草稿列表");
|
||||
expect(result.stdout).toContain("FK26000009");
|
||||
expect(result.stdout).toContain("bill submit");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,10 @@
|
||||
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
|
||||
import {
|
||||
getBillByCodeOrId,
|
||||
getBillRisk,
|
||||
searchAndFormatBills,
|
||||
searchAndFormatDraftBills,
|
||||
traceBillFlowDetail,
|
||||
} from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
@@ -6,8 +12,10 @@ import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const isDraft = state ? /^(draft|草稿)$/i.test(state.trim()) : false;
|
||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||
if (mine) {
|
||||
if (mine && !isDraft) {
|
||||
const { handleTaskCommand } = await import("./../task.js");
|
||||
return handleTaskCommand(
|
||||
{
|
||||
@@ -23,8 +31,9 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||
const page = Math.max(1, numberOption(parsed.options, ["page"], 1) ?? 1);
|
||||
const start = (page - 1) * count;
|
||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||
@@ -34,21 +43,54 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||
|
||||
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const rawTemplate = stringOption(parsed.options, [
|
||||
"template",
|
||||
"spec",
|
||||
"specification",
|
||||
"specification-id",
|
||||
"specificationId",
|
||||
]);
|
||||
const templateId = rawTemplate
|
||||
? rawTemplate
|
||||
.trim()
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.replace(/:[0-9a-f]{32,64}$/i, "")
|
||||
: undefined;
|
||||
const staffValues = ctx.listOption(["staff", "staff-id"]);
|
||||
const submitterIds =
|
||||
isDraft && staffValues?.length ? await ctx.resolveApproverIds(staffValues) : undefined;
|
||||
|
||||
const result = isDraft
|
||||
? await searchAndFormatDraftBills(await ctx.getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
title,
|
||||
templateId,
|
||||
submitterIds,
|
||||
start,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
})
|
||||
: await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
start,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -67,7 +109,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", isDraft ? "创建时间" : "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
@@ -75,7 +117,7 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
isDraft ? b.createTime || b.submitDate || "-" : b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const filterSummary: string[] = [];
|
||||
@@ -87,14 +129,23 @@ export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
}
|
||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||
if (state) filterSummary.push(`状态: ${state}`);
|
||||
if (isDraft) {
|
||||
if (templateId) filterSummary.push(`模板: ${templateId}`);
|
||||
if (title) filterSummary.push(`标题: ${title}`);
|
||||
if (staffValues?.length) filterSummary.push(`提交人: ${staffValues.join(", ")}`);
|
||||
if (page > 1) filterSummary.push(`第 ${page} 页`);
|
||||
}
|
||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
const listLabel = isDraft ? "单据草稿列表" : "单据与费用明细列表";
|
||||
const titleLine = `====== ${listLabel} (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = isDraft
|
||||
? `\n提示: 运行 hose-use bill get <单号|flowId> 查看草稿详情;提交使用 hose-use bill submit <单号|flowId> --yes\n`
|
||||
: `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stdout: titleLine + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getEnterprisesDirCandidates,
|
||||
} from "../../core/config/loader.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { getDocsCatalog } from "../../domains/docs/tools.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -53,6 +54,18 @@ export async function handleContextCommand(
|
||||
// 容错处理(如 SQLite 尚未初始化等场景)
|
||||
}
|
||||
|
||||
let docsStats = { totalDocs: 0, totalEndpoints: 0, ready: false };
|
||||
try {
|
||||
const catalog = await getDocsCatalog();
|
||||
docsStats = {
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
ready: true,
|
||||
};
|
||||
} catch {
|
||||
// 容错处理
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
|
||||
@@ -114,6 +127,7 @@ export async function handleContextCommand(
|
||||
pendingRunsCount,
|
||||
totalRunsCount,
|
||||
},
|
||||
docsCatalog: docsStats,
|
||||
runtime: {
|
||||
mode: isStateful ? "stateful" : "stateless",
|
||||
configFile,
|
||||
@@ -152,6 +166,7 @@ export async function handleContextCommand(
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
|
||||
` 开放平台接口库: ${docsStats.ready ? `已就绪 (${docsStats.totalDocs} 篇文档 / ${docsStats.totalEndpoints} 个端点,可用 hose-use docs search 检索)` : "未就绪"}`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||
@@ -160,6 +175,7 @@ export async function handleContextCommand(
|
||||
"",
|
||||
"提示:",
|
||||
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
|
||||
" - 调研合思开放接口与参数规范: hose-use docs search <关键词> 或 hose-use docs show <Path>",
|
||||
" - 切换全局默认企业: hose-use corps switch <企业ID>",
|
||||
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - AI PRO 专属上下文: hose-aipro status",
|
||||
|
||||
@@ -159,6 +159,25 @@ describe("CLI - corps environment attributes & filtering", () => {
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("设置企业环境属性");
|
||||
expect(res.stdout).toContain("newEnv: test");
|
||||
expect(res.stdout).toContain("将不再触发生产环境确认");
|
||||
});
|
||||
|
||||
it("corps tag dry-run from production to demo includes the same downgrade warning", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "tag",
|
||||
args: ["corp_prod"],
|
||||
options: { demo: true, "dry-run": true },
|
||||
raw: ["corps", "tag", "corp_prod", "--demo", "--dry-run"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("将不再触发生产环境确认");
|
||||
expect(res.stdout).toContain("newEnv: demo");
|
||||
});
|
||||
|
||||
it("corps current displays environment attribute label", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-easo-client.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
@@ -35,7 +35,7 @@ describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/http/unity-client > resolveCorpCluster", () => {
|
||||
describe("core/http/unity-easo-client > resolveCorpCluster", () => {
|
||||
it("prioritizes explicit cluster config", () => {
|
||||
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
|
||||
});
|
||||
|
||||
@@ -6,6 +6,12 @@ import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mu
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
/** 生产降级为测试/演示会关闭该企业的生产确认门禁,必须显著提示。 */
|
||||
function productionDowngradeWarning(currentEnv: CorpEnv, targetEnv: CorpEnv): string | undefined {
|
||||
if (currentEnv !== "prod" || targetEnv === "prod") return undefined;
|
||||
return "该企业原为正式生产环境;改为测试/演示后,workflow test 与 workflow nodes grant 将不再触发生产环境确认。";
|
||||
}
|
||||
|
||||
export async function handleTagCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -154,12 +160,15 @@ export async function handleTagCorp(
|
||||
};
|
||||
}
|
||||
|
||||
const currentEnv = getCorpEnv(targetCorp);
|
||||
const downgradeWarning = productionDowngradeWarning(currentEnv, targetEnv);
|
||||
const changes = {
|
||||
corpId: targetCorp.id,
|
||||
name: targetCorp.name,
|
||||
currentEnv: targetCorp.env,
|
||||
currentEnv,
|
||||
newEnv: targetEnv,
|
||||
newIsTest: targetEnv !== "prod",
|
||||
...(downgradeWarning ? { warning: downgradeWarning } : {}),
|
||||
};
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
@@ -192,6 +201,7 @@ export async function handleTagCorp(
|
||||
env: updatedCorp.env,
|
||||
isTest: updatedCorp.isTest,
|
||||
configFile: filePath,
|
||||
...(downgradeWarning ? { warning: downgradeWarning } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -209,7 +219,7 @@ export async function handleTagCorp(
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
|
||||
stdout: `${downgradeWarning ? `⚠️ ${downgradeWarning}\n\n` : ""}[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { loadCorpConfigs } from "../../../core/config/loader.js";
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { NotFoundError } from "../../../core/errors.js";
|
||||
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
||||
|
||||
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
describe("CLI - 开放平台官方接口文档域 (docs / openapi-docs)", () => {
|
||||
test("hose-use docs 输出开放平台文档概览与端点总数", async () => {
|
||||
const res = await runCli(["docs"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台官方文档中心");
|
||||
expect(res.stdout).toContain("文档总数:");
|
||||
expect(res.stdout).toContain("端点总数:");
|
||||
expect(res.stdout).toContain("hose-use docs search");
|
||||
});
|
||||
|
||||
test("hose-use docs --json 输出概览结构化元数据", async () => {
|
||||
const res = await runCli(["docs", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.totalDocs).toBeGreaterThan(100);
|
||||
expect(data.totalEndpoints).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
test("hose-use docs search roleDefGroups 能检索出角色组接口", async () => {
|
||||
const res = await runCli(["docs", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
});
|
||||
|
||||
test("hose-use docs search 角色组 --json 输出精准结构化搜索结果", async () => {
|
||||
const res = await runCli(["docs", "search", "角色组", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.total).toBeGreaterThanOrEqual(1);
|
||||
expect(data.items.some((i: any) => i.path === "/api/openapi/v1/roleDefGroups")).toBe(true);
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups 展示完整接口规格与 CURL 示范", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("查询角色组和角色");
|
||||
expect(res.stdout).toContain("GET");
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
expect(res.stdout).toContain("CURL 请求示范");
|
||||
expect(res.stdout).toContain("成功响应示例");
|
||||
expect(res.stdout).toContain("accessToken");
|
||||
});
|
||||
|
||||
test("hose-use docs show /api/openapi/v1/roleDefGroups --json 返回全量结构化文档项", async () => {
|
||||
const res = await runCli(["docs", "show", "/api/openapi/v1/roleDefGroups", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
const doc = JSON.parse(res.stdout);
|
||||
expect(doc.path).toBe("/api/openapi/v1/roleDefGroups");
|
||||
expect(doc.method).toBe("GET");
|
||||
expect(doc.category).toBe("企业通讯录");
|
||||
expect(doc.permalink).toContain("get-roles-group");
|
||||
});
|
||||
|
||||
test("hose-use docs show 未知目标时返回友好错误", async () => {
|
||||
const res = await runCli(["docs", "show", "non_existing_api_path_xyz"]);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("NOT FOUND");
|
||||
});
|
||||
|
||||
test("hose-use docs categories 输出所有业务分类与端点分布", async () => {
|
||||
const res = await runCli(["docs", "categories"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("合思开放平台业务模块分类");
|
||||
expect(res.stdout).toContain("企业通讯录");
|
||||
expect(res.stdout).toContain("预算");
|
||||
expect(res.stdout).toContain("单据");
|
||||
});
|
||||
|
||||
test("hose-use doc 别名也能正常调用", async () => {
|
||||
const res = await runCli(["doc", "search", "roleDefGroups"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("/api/openapi/v1/roleDefGroups");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import {
|
||||
getDocDetail,
|
||||
getDocsCatalog,
|
||||
listCategories,
|
||||
searchDocs,
|
||||
syncDocsCatalog,
|
||||
} from "../../domains/docs/tools.js";
|
||||
|
||||
export async function handleDocsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "";
|
||||
const forceRefresh =
|
||||
booleanOption(parsed.options, ["refresh", "force", "sync"]) ||
|
||||
action === "sync";
|
||||
|
||||
// 1. 同步命令: hose-use docs sync
|
||||
if (action === "sync") {
|
||||
const res = await syncDocsCatalog();
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(res, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 开放平台文档同步完成 ======\n文档总数: ${res.totalDocs}\n接口端点: ${res.totalEndpoints}\n数据源: ${res.source}\n更新时间: ${res.updatedAt}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 分类列表: hose-use docs categories
|
||||
if (["categories", "category", "cats", "modules"].includes(action)) {
|
||||
const cats = await listCategories({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: cats.length, categories: cats }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = cats.map((c, i) => [
|
||||
i + 1,
|
||||
c.name,
|
||||
`${c.count} 篇`,
|
||||
`${c.endpointsCount} 个`,
|
||||
]);
|
||||
const table = printTable(["#", "业务分类", "文档篇数", "HTTP 端点数"], rows);
|
||||
return {
|
||||
stdout: `====== 合思开放平台业务模块分类 (共 ${cats.length} 个) ======\n\n${table}\n\n提示: 运行 hose-use docs search --category=<模块名> 可查看该模块下的所有接口\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 详情命令: hose-use docs show <target>
|
||||
if (["show", "get", "info", "cat", "read"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["path", "url", "id", "name", "target"]);
|
||||
if (!target) {
|
||||
throw new Error("请指定要查看的接口路径、文档 URL 或名称: hose-use docs show <接口或URL>");
|
||||
}
|
||||
|
||||
const doc = await getDocDetail(target, { forceRefresh });
|
||||
if (!doc) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到匹配的文档或接口: ${target}\n提示: 可以先运行 hose-use docs search ${target} 检索相近接口。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(doc, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let out = `====== ${doc.title} ======\n`;
|
||||
out += printKeyValue({
|
||||
"业务模块": doc.category,
|
||||
"HTTP 方法": doc.method || "非端点/指南页面",
|
||||
"接口路径": doc.path || "-",
|
||||
"在线文档": doc.permalink,
|
||||
"文档标识": `#${doc.id}`,
|
||||
});
|
||||
|
||||
if (doc.parameters) {
|
||||
out += `\n\n### 参数规格与定义\n${doc.parameters}\n`;
|
||||
}
|
||||
|
||||
if (doc.curl) {
|
||||
out += `\n### CURL 请求示范\n\`\`\`bash\n${doc.curl}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
if (doc.responseSample) {
|
||||
out += `\n### 成功响应示例\n\`\`\`json\n${doc.responseSample}\n\`\`\`\n`;
|
||||
}
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 4. 搜索命令 (默认行为): hose-use docs search <keyword> 或 hose-use docs <keyword>
|
||||
const isSearchAction = ["search", "find", "list", "ls", ""].includes(action);
|
||||
if (isSearchAction) {
|
||||
const keyword =
|
||||
(action === "search" || action === "find" ? parsed.args[0] : action || parsed.args[0]) ||
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
|
||||
const category = stringOption(parsed.options, ["category", "cat", "module"]);
|
||||
const method = stringOption(parsed.options, ["method", "m"]);
|
||||
const path = stringOption(parsed.options, ["path", "p"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n", "count"], 25);
|
||||
|
||||
// 如果没有任何搜索条件且没有关键词,展示全局概览
|
||||
if (!keyword && !category && !method && !path && !action) {
|
||||
const catalog = await getDocsCatalog({ forceRefresh });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
totalDocs: catalog.totalDocs,
|
||||
totalEndpoints: catalog.totalEndpoints,
|
||||
sourceUrl: catalog.sourceUrl,
|
||||
updatedAt: catalog.updatedAt,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `====== 合思开放平台官方文档中心 ======
|
||||
文档总数: ${catalog.totalDocs} 篇
|
||||
端点总数: ${catalog.totalEndpoints} 个
|
||||
数据来源: ${catalog.sourceUrl}
|
||||
更新时间: ${catalog.updatedAt}
|
||||
|
||||
常用子命令:
|
||||
hose-use docs search <关键词> 检索开放平台 HTTP 接口与文档
|
||||
hose-use docs show <路径|名称|URL> 查看单篇接口规格、参数表格与 CURL 响应
|
||||
hose-use docs categories 查看 26+ 个业务分类及其端点数
|
||||
hose-use docs sync 强制与线上最新文档中心全量同步
|
||||
`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const searchRes = await searchDocs(
|
||||
{
|
||||
keyword,
|
||||
category,
|
||||
method,
|
||||
path,
|
||||
limit,
|
||||
},
|
||||
{ forceRefresh }
|
||||
);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const summaryItems = searchRes.items.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
category: item.category,
|
||||
method: item.method,
|
||||
path: item.path,
|
||||
url: item.url,
|
||||
permalink: item.permalink,
|
||||
matchReason: item.matchReason || undefined,
|
||||
}));
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
total: searchRes.total,
|
||||
count: summaryItems.length,
|
||||
keyword: searchRes.keyword,
|
||||
category: searchRes.category,
|
||||
method: searchRes.method,
|
||||
items: summaryItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (searchRes.items.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配的文档或接口 (关键词: ${keyword || "-"}, 分类: ${category || "-"}, 方法: ${method || "-"})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const hasKeyword = Boolean(keyword);
|
||||
const headers = hasKeyword
|
||||
? ["Method", "Path / URL", "标题", "分类", "匹配依据"]
|
||||
: ["Method", "Path / URL", "标题", "分类"];
|
||||
|
||||
const rows = searchRes.items.map((item) => {
|
||||
const base = [
|
||||
item.method || "DOC",
|
||||
item.path || item.url,
|
||||
item.title,
|
||||
item.category,
|
||||
];
|
||||
if (hasKeyword) {
|
||||
base.push(item.matchReason || "-");
|
||||
}
|
||||
return base;
|
||||
});
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const filterDesc = [
|
||||
keyword ? `关键词: '${keyword}'` : "",
|
||||
category ? `分类: '${category}'` : "",
|
||||
method ? `方法: '${method}'` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
stdout: `====== 开放平台接口搜索结果 (找到 ${searchRes.total} 条${filterDesc ? ` | ${filterDesc}` : ""}) ======\n\n${table}\n\n提示: 运行 hose-use docs show <Path> 可查看对应接口的完整参数和 CURL 示范\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知的 docs 子命令: ${action}。支持: search <关键词>, show <路径|URL>, categories, sync`
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import {
|
||||
createFeeType,
|
||||
disableFeeTypeItem,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleFlowCommand } from "./flow.js";
|
||||
import { handleBillCommand } from "./bill/index.js";
|
||||
import { findCommandByArea } from "../registry.js";
|
||||
import * as sessionModule from "../../core/http/session-client.js";
|
||||
import * as sessionModule from "../../core/http/hose-web-session-client.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
||||
import type { MessageItem } from "../../domains/message/types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { getPermissions } from "../../domains/permission/tools.js";
|
||||
|
||||
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -528,6 +528,33 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
).rejects.toThrow("--all 不再直接返回全量");
|
||||
});
|
||||
|
||||
it("platform records --all --json 返回 DATASET_TOO_LARGE 结构化错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const result = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "records",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { all: true, json: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--all", "--json"],
|
||||
},
|
||||
{ ...dummyRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(2);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.error).toBe(true);
|
||||
expect(parsed.code).toBe("DATASET_TOO_LARGE");
|
||||
expect(parsed.exitCode).toBe(2);
|
||||
expect(parsed.nextAction).toContain("--ndjson");
|
||||
expect(parsed.suggestions).toEqual([
|
||||
{ type: "paginate", command: "--page=1 --pageSize=500" },
|
||||
{ type: "stream_export", command: "--ndjson --output-file=<path>" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
@@ -572,5 +599,85 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
|
||||
it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
// 按应用名称查未找到
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
// 列出所有平台
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "platform-lease", name: "租赁摊销业务" } as any,
|
||||
{ id: "platform-other", name: "其他应用" } as any,
|
||||
]));
|
||||
// 模拟应用详情与对象列表
|
||||
spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({
|
||||
id: "platform-lease",
|
||||
name: "租赁摊销业务",
|
||||
} as any));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
if (platformId === "platform-lease") {
|
||||
return [
|
||||
{ id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any,
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 1,
|
||||
data: [
|
||||
{
|
||||
id: "rec-1",
|
||||
dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("记录1");
|
||||
});
|
||||
|
||||
it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
{ id: "app-2", name: "应用二" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any];
|
||||
}));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称");
|
||||
});
|
||||
|
||||
it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([]));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,9 +63,27 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
// 全量 JSON/表格很容易把几十万条记录倒进 stdout 或内存;全量导出必须显式走文件流。
|
||||
if (isAll && !isProfileStats && !sumOption) {
|
||||
if (!isStream || !runtime.outputOptions?.outputFile) {
|
||||
throw usageError(
|
||||
"--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file <path> 流式导出;大范围检索建议交给脚本处理。"
|
||||
);
|
||||
const message =
|
||||
"--all 不再直接返回全量 JSON/表格。请使用 --page/--count 分页查询,或使用 --ndjson --output-file <path> 流式导出;大范围检索建议交给脚本处理。";
|
||||
const nextAction = "hose-use platform records <应用> <业务对象> --ndjson --output-file <path>";
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
error: true,
|
||||
code: "DATASET_TOO_LARGE",
|
||||
message,
|
||||
exitCode: 2,
|
||||
nextAction,
|
||||
suggestions: [
|
||||
{ type: "paginate", command: "--page=1 --pageSize=500" },
|
||||
{ type: "stream_export", command: "--ndjson --output-file=<path>" },
|
||||
],
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 2,
|
||||
};
|
||||
}
|
||||
throw usageError(message, nextAction);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,8 +261,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameField = resolved.entity.fields?.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields?.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js";
|
||||
import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
@@ -19,16 +22,81 @@ export function cell(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId
|
||||
*/
|
||||
async function resolveEntityGlobally(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> {
|
||||
const platforms = await listPlatforms(client, corpId);
|
||||
const matches: Array<{ platform: any; entity: DatalinkEntity }> = [];
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
platforms.map(async (p) => {
|
||||
const entities = await listPlatformEntities(client, corpId, p.id);
|
||||
const found = entities.find((e) =>
|
||||
[e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase())
|
||||
);
|
||||
if (found) {
|
||||
return { platform: p, entity: found };
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
matches.push(r.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length === 1) {
|
||||
const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id);
|
||||
return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity };
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", ");
|
||||
throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const targetA = parsed.args[appIndex]?.trim();
|
||||
const targetB = parsed.args[entityIndex]?.trim();
|
||||
|
||||
if (!targetA) {
|
||||
throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>");
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
// 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析
|
||||
if (targetB) {
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`);
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
// 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等)
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (platform) {
|
||||
return { clients, corpId, platform, entity: undefined };
|
||||
}
|
||||
|
||||
// 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search)
|
||||
const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA);
|
||||
if (globalMatch) {
|
||||
return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity };
|
||||
}
|
||||
|
||||
throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
import * as billApi from "../../domains/bill/api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as session from "../../core/http/session-client.js";
|
||||
import * as session from "../../core/http/hose-web-session-client.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as workflowShared from "./workflow/shared.js";
|
||||
import * as platformShared from "./platform/shared.js";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||
|
||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleSkillCommand } from "./skill.js";
|
||||
import { getAiProSkillContent, getSkillContent } from "../../packaging/embedded-skill.js";
|
||||
|
||||
const parsed = {
|
||||
area: "skill",
|
||||
action: "dump",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["skill", "dump"],
|
||||
};
|
||||
|
||||
const baseRuntime = {
|
||||
selectedCorp: null,
|
||||
corpContext: {},
|
||||
jsonMode: false,
|
||||
};
|
||||
|
||||
describe("skill dump 的 multicall 入口识别", () => {
|
||||
test("hose-aipro 入口返回 AI PRO Skill(不依赖 argv0 猜测)", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-aipro" } as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-aipro (v");
|
||||
});
|
||||
|
||||
test("hose-use 入口返回平台 Skill", async () => {
|
||||
const result = await handleSkillCommand(parsed as never,{ ...baseRuntime, app: "hose-use" } as never);
|
||||
expect(result.stdout).toBe(`${getSkillContent()}\n`);
|
||||
expect(result.stdout).toContain("hose-use (v");
|
||||
});
|
||||
|
||||
test("兼容历史:未标注 app 时仍按 parsed.raw 里的 aipro 标记识别", async () => {
|
||||
const legacyParsed = { ...parsed, raw: ["skill", "dump", "aipro"] };
|
||||
const result = await handleSkillCommand(legacyParsed as never, baseRuntime as never);
|
||||
expect(result.stdout).toBe(`${getAiProSkillContent()}\n`);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ export async function handleSkillCommand(
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "status";
|
||||
const isAiProCaller =
|
||||
runtime.app === "hose-aipro" ||
|
||||
parsed.area === "hose-aipro" ||
|
||||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
|
||||
import { listTasks } from "../../domains/task/tools.js";
|
||||
import type { TaskView } from "../../domains/task/types.js";
|
||||
|
||||
|
||||
@@ -106,11 +106,58 @@ describe("workflow debug mutation and result contract", () => {
|
||||
} as any;
|
||||
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
|
||||
expect(blocked.exitCode).toBe(1);
|
||||
expect(blocked.stderr).toContain("生产环境安全阻断");
|
||||
expect(blocked.stderr).toContain("生产环境确认");
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
|
||||
const allowed = await handleWorkflowTest(args({ yes: true, force: true }), prodRuntime);
|
||||
expect(allowed.exitCode).toBe(0);
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reports a structured production confirmation error in JSON mode", async () => {
|
||||
const { client, run } = setup();
|
||||
const prodRuntime = {
|
||||
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
|
||||
jsonMode: true,
|
||||
} as any;
|
||||
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
|
||||
expect(blocked.exitCode).toBe(1);
|
||||
expect(blocked.stderr).toBe("");
|
||||
const payload = JSON.parse(blocked.stdout);
|
||||
expect(payload.code).toBe("PROD_OVERRIDE_REQUIRED");
|
||||
expect(payload.details.operation).toBe("workflow.test");
|
||||
expect(payload.nextAction).toContain("--allow-prod");
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows production dry-run without the override and teaches --allow-prod", async () => {
|
||||
const { client, run } = setup();
|
||||
const prodRuntime = {
|
||||
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
|
||||
jsonMode: true,
|
||||
} as any;
|
||||
const preview = await handleWorkflowTest(args({ "dry-run": true }), prodRuntime);
|
||||
expect(preview.exitCode).toBe(0);
|
||||
const payload = JSON.parse(preview.stdout);
|
||||
expect(payload.dryRun).toBe(true);
|
||||
expect(payload.changes.productionOverride).toBe(false);
|
||||
expect(payload.nextAction).toContain("--allow-prod");
|
||||
expect(client).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks production execution results when --allow-prod is used", async () => {
|
||||
const { run } = setup();
|
||||
const prodRuntime = {
|
||||
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
|
||||
jsonMode: true,
|
||||
} as any;
|
||||
const result = await handleWorkflowTest(args({ yes: true, "allow-prod": true }), prodRuntime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.productionOverride).toBe(true);
|
||||
expect(payload.productionWarning).toContain("正式生产企业");
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,478 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as helpers from "./workflow/shared.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "ID01ofWoOC1wiX",
|
||||
name: "沈玥妍测试企业",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
cluster: "app",
|
||||
source: "link",
|
||||
credentials: {
|
||||
accessToken: "test-token",
|
||||
corpId: "ID01ofWoOC1wiX",
|
||||
staffId: "ID01ofWoOC1wiX:ID01KsDgHaH5nN",
|
||||
},
|
||||
env: "test",
|
||||
isTest: true,
|
||||
};
|
||||
|
||||
describe("CLI - workflow node inspect 与 sample-save (只读探针与样本一键固化)", () => {
|
||||
let spies: any[] = [];
|
||||
let mockRuntime: CliRuntime;
|
||||
|
||||
beforeEach(() => {
|
||||
spies = [];
|
||||
const corpContext = new CorpContext([mockCorp], { stateful: true, defaultCorpId: mockCorp.id });
|
||||
mockRuntime = {
|
||||
corpContext,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
it("workflow node inspect: 成功透视节点配置、已存样本与历史调试出参", async () => {
|
||||
const mockTasks = [
|
||||
{
|
||||
name: "trigger_1",
|
||||
type: "ekuaibao-ebot-trigger",
|
||||
label: "EBOT触发",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
},
|
||||
{
|
||||
name: "action_calc_1",
|
||||
type: "code",
|
||||
label: "代码节点",
|
||||
displayName: "时间转换节点",
|
||||
orderIndex: 1,
|
||||
levelIndex: [1],
|
||||
status: "active",
|
||||
code: "result = ['minute': '2026-11-19 20:59'];\nreturn result;",
|
||||
sampleData: {
|
||||
minute: "2026-11-19 20:59",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const mockDetail = {
|
||||
id: "wf_inspect_test",
|
||||
label: "测试工作流",
|
||||
state: 0,
|
||||
tasks: mockTasks,
|
||||
};
|
||||
|
||||
const mockExecutionTree = [
|
||||
{
|
||||
id: "exec_1",
|
||||
name: "action_calc_1",
|
||||
status: "COMPLETED",
|
||||
executionTime: 8,
|
||||
output: {
|
||||
minute: "2026-11-19 20:59",
|
||||
timestampMs: 1795093140000,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/pipelines/wf_inspect_test/log")) {
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200 }),
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
totalCount: 1,
|
||||
items: [{ id: "job_test_100", status: "COMPLETED" }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/wf_inspect_test")) {
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200 }),
|
||||
json: async () => ({ code: 200, data: mockDetail }),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_test_100/execution")) {
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200 }),
|
||||
json: async () => ({ code: 200, data: mockExecutionTree }),
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200 }),
|
||||
json: async () => ({ code: 200, data: null }),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: mockClient as any,
|
||||
clients: {} as any,
|
||||
platformId: undefined,
|
||||
})
|
||||
);
|
||||
|
||||
// 1. 终端文本透视
|
||||
const resText = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["inspect", "wf_inspect_test", "action_calc_1"],
|
||||
options: {},
|
||||
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(resText.exitCode).toBe(0);
|
||||
expect(resText.stdout).toContain("工作流节点只读探针");
|
||||
expect(resText.stdout).toContain("action_calc_1");
|
||||
expect(resText.stdout).toContain("时间转换节点");
|
||||
expect(resText.stdout).toContain("已固化样本");
|
||||
expect(resText.stdout).toContain("最近一次调试执行出参");
|
||||
expect(resText.stdout).toContain("job_test_100");
|
||||
expect(resText.stdout).toContain("1795093140000");
|
||||
|
||||
// 2. JSON 模式结构化输出
|
||||
mockRuntime.jsonMode = true;
|
||||
const resJson = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["inspect", "wf_inspect_test", "action_calc_1"],
|
||||
options: {},
|
||||
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1", "--json"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(resJson.exitCode).toBe(0);
|
||||
const parsedJson = JSON.parse(resJson.stdout);
|
||||
expect(parsedJson.sampleData.minute).toBe("2026-11-19 20:59");
|
||||
expect(parsedJson.executionProbe.jobId).toBe("job_test_100");
|
||||
expect(parsedJson.executionProbe.output.timestampMs).toBe(1795093140000);
|
||||
});
|
||||
|
||||
it("workflow node sample-save: 支持 dry-run 预览并一键固化出参至节点 sampleData", async () => {
|
||||
let savedTasks: any = null;
|
||||
let choosesRefreshed = false;
|
||||
|
||||
const mockTasks = [
|
||||
{
|
||||
name: "action_target_node",
|
||||
type: "code",
|
||||
label: "代码节点",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
},
|
||||
];
|
||||
|
||||
const mockDetail = {
|
||||
id: "wf_save_sample_test",
|
||||
label: "样本固化测试流",
|
||||
version: "1.0.0",
|
||||
tasksVersion: 1,
|
||||
state: 0,
|
||||
tasks: mockTasks,
|
||||
};
|
||||
|
||||
const mockExecutionTree = [
|
||||
{
|
||||
id: "exec_node_target",
|
||||
name: "action_target_node",
|
||||
status: "COMPLETED",
|
||||
output: {
|
||||
formattedDate: "2026-11-24 11:30",
|
||||
rangeSec: "2026-11-24 11:30:00 ~ 2026-11-24 12:00:00",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
|
||||
return { json: async () => ({ code: 200, data: mockDetail }) };
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_custom_999/execution")) {
|
||||
return { json: async () => ({ code: 200, data: mockExecutionTree }) };
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
put: (url: string, opts: any) => {
|
||||
if (url.endsWith("/chooses")) {
|
||||
choosesRefreshed = true;
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200, data: [] }),
|
||||
json: async () => ({ code: 200, data: [] }),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
|
||||
savedTasks = opts.json.tasks;
|
||||
return {
|
||||
text: async () =>
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
...mockDetail,
|
||||
...opts.json,
|
||||
tasksVersion: 2,
|
||||
},
|
||||
}),
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
...mockDetail,
|
||||
...opts.json,
|
||||
tasksVersion: 2,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200, data: null }),
|
||||
json: async () => ({ code: 200, data: null }),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: mockClient as any,
|
||||
clients: {} as any,
|
||||
platformId: undefined,
|
||||
})
|
||||
);
|
||||
|
||||
// 1. Dry-run 预览
|
||||
const dryRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
|
||||
options: { dryRun: true, job: "job_custom_999" },
|
||||
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--dry-run"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(dryRes.exitCode).toBe(0);
|
||||
expect(dryRes.stdout).toContain("[DRY-RUN]");
|
||||
expect(dryRes.stdout).toContain("固化节点样本数据 (sampleData)");
|
||||
expect(savedTasks).toBeNull();
|
||||
|
||||
// 2. 确认执行
|
||||
const execRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
|
||||
options: { yes: true, job: "job_custom_999" },
|
||||
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(execRes.exitCode).toBe(0);
|
||||
expect(execRes.stdout).toContain("样本数据 (sampleData) 固化成功");
|
||||
expect(execRes.stdout).toContain("固化字段数 : 2 个属性");
|
||||
expect(savedTasks).not.toBeNull();
|
||||
expect(savedTasks[0].sampleData.formattedDate).toBe("2026-11-24 11:30");
|
||||
expect(choosesRefreshed).toBe(true);
|
||||
});
|
||||
|
||||
it("workflow test --save-sample: 调试通过后自动固化执行出参为节点 sampleData", async () => {
|
||||
let savedTasks: any = null;
|
||||
let choosesRefreshed = false;
|
||||
|
||||
const mockTasks = [
|
||||
{
|
||||
name: "trigger_1",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
label: "单据触发",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
},
|
||||
{
|
||||
name: "action_code_date",
|
||||
type: "code",
|
||||
label: "代码节点",
|
||||
orderIndex: 1,
|
||||
levelIndex: [1],
|
||||
status: "active",
|
||||
code: "return ['minute': '2026-11-24 11:35'];",
|
||||
},
|
||||
];
|
||||
|
||||
const mockDetail = {
|
||||
id: "wf_test_save_sample",
|
||||
label: "自动保存样本流程",
|
||||
version: "1.0.0",
|
||||
tasksVersion: 1,
|
||||
state: 0,
|
||||
tasks: mockTasks,
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
post: (url: string) => {
|
||||
if (url.includes("debugSource")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
type: "flowForm",
|
||||
total: 1,
|
||||
items: [{ id: "S26000001", title: "测试单据", flowState: "审批中" }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: "job_auto_sample_123",
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
get: (url: string) => {
|
||||
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
|
||||
if (url.includes("execution")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "e1",
|
||||
name: "trigger_1",
|
||||
label: "单据触发",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
status: "COMPLETED",
|
||||
executionTime: 10,
|
||||
},
|
||||
{
|
||||
id: "e2",
|
||||
name: "action_code_date",
|
||||
label: "代码节点",
|
||||
type: "code",
|
||||
status: "COMPLETED",
|
||||
executionTime: 5,
|
||||
output: {
|
||||
minute: "2026-11-24 11:35",
|
||||
timestampMs: 1795093140000,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/jobs/job_auto_sample_123")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "job_auto_sample_123",
|
||||
pipelineId: "wf_test_save_sample",
|
||||
status: "COMPLETED",
|
||||
startTime: 1795490000000,
|
||||
endTime: 1795490001000,
|
||||
executionTime: 1000,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: mockDetail,
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
put: (url: string, opts: any) => {
|
||||
if (url.endsWith("/chooses")) {
|
||||
choosesRefreshed = true;
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200, data: [] }),
|
||||
json: async () => ({ code: 200, data: [] }),
|
||||
};
|
||||
}
|
||||
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
|
||||
savedTasks = opts.json.tasks;
|
||||
return {
|
||||
text: async () =>
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
...mockDetail,
|
||||
...opts.json,
|
||||
tasksVersion: 2,
|
||||
},
|
||||
}),
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
...mockDetail,
|
||||
...opts.json,
|
||||
tasksVersion: 2,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: async () => JSON.stringify({ code: 200, data: null }),
|
||||
json: async () => ({ code: 200, data: null }),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: mockClient as any,
|
||||
clients: {} as any,
|
||||
platformId: undefined,
|
||||
})
|
||||
);
|
||||
|
||||
const testRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "test",
|
||||
args: ["wf_test_save_sample"],
|
||||
options: { flow: "S26000001", saveSample: true, yes: true },
|
||||
raw: ["workflow", "test", "wf_test_save_sample", "--flow=S26000001", "--save-sample", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(testRes.exitCode).toBe(0);
|
||||
expect(testRes.stdout).toContain("工作流自动化调测报告");
|
||||
expect(testRes.stdout).toContain("样本数据自动固化");
|
||||
expect(testRes.stdout).toContain("action_code_date");
|
||||
expect(savedTasks).not.toBeNull();
|
||||
expect(savedTasks[1].sampleData.minute).toBe("2026-11-24 11:35");
|
||||
expect(savedTasks[1].sampleData.timestampMs).toBe(1795093140000);
|
||||
expect(choosesRefreshed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,8 @@ import { parseArgs } from "../parser.js";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
|
||||
test("node grant previews without a gateway call and requires explicit confirmation", async () => {
|
||||
const runtime = { selectedCorp: { id: "corp", credentials: { corpId: "corp" } }, jsonMode: true } as any;
|
||||
test("node grant previews without a Piper call and requires explicit confirmation", async () => {
|
||||
const runtime = { selectedCorp: { id: "corp", isTest: true, credentials: { corpId: "corp" } }, jsonMode: true } as any;
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: true, saved: ["code-js2"], skipped: [], rawMessage: "ok" });
|
||||
try {
|
||||
await expect(handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2"]), runtime)).rejects.toThrow("--yes");
|
||||
@@ -12,7 +12,12 @@ test("node grant previews without a gateway call and requires explicit confirmat
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).changes.nodes).toEqual(["code-js2"]);
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
const testPreview = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code", "--is-test", "--dry-run", "--yes"]), runtime);
|
||||
expect(JSON.parse(testPreview.stdout).changes.isTest).toBe(true);
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--confirm"]), runtime);
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code", "--is-test", "--yes"]), runtime);
|
||||
expect(grant).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ nodes: ["code"], isTest: true }));
|
||||
} finally { grant.mockRestore(); }
|
||||
});
|
||||
@@ -2,11 +2,11 @@ import { expect, spyOn, test } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
test("failed grants retain gateway details and never report success", async () => {
|
||||
test("failed grants retain Piper details and never report success", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({ success: false, saved: [], skipped: [], rawMessage: "permission denied" });
|
||||
try {
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--yes"]), { selectedCorp: { id: "corp", name: "test" }, jsonMode } as any);
|
||||
const result = await handleWorkflowCommand(parseArgs(["workflow", "nodes", "grant", "code-js2", "--yes"]), { selectedCorp: { id: "corp", name: "test", isTest: true }, jsonMode } as any);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).not.toContain("节点权限已生效");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout)).toMatchObject({ success: false, rawMessage: "permission denied" });
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import * as services from "../../domains/platform/workflow/services.js";
|
||||
|
||||
function prodRuntime(jsonMode = false) {
|
||||
return {
|
||||
selectedCorp: {
|
||||
id: "prod-corp",
|
||||
name: "正式生产企业",
|
||||
env: "prod",
|
||||
credentials: { corpId: "prod-corp", accessToken: "token" },
|
||||
},
|
||||
jsonMode,
|
||||
} as any;
|
||||
}
|
||||
|
||||
test("production corp is blocked before any grant request or confirmation", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("生产环境确认");
|
||||
expect(result.stderr).toContain("--allow-prod");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("env-unmarked corp is conservatively treated as production", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: [], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--yes"]),
|
||||
{ selectedCorp: { id: "corp", name: "浙江麦瑞克科技有限公司" }, jsonMode: true } as any
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.code).toBe("PROD_OVERRIDE_REQUIRED");
|
||||
expect(parsed.nextAction).toContain("--allow-prod");
|
||||
expect(parsed.details.operation).toBe("workflow.nodes.grant");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("production dry-run is allowed without --allow-prod and teaches the override", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--dry-run"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("productionOverride: false");
|
||||
expect(result.stdout).toContain("实际执行需追加 --allow-prod");
|
||||
expect(result.stdout).toContain("--allow-prod");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("missing node types is reported before the production confirmation", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: [], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "--yes"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("请指定要开通的节点类型");
|
||||
expect(result.stderr).not.toContain("生产环境确认");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("--allow-prod dry-run previews the production grant without writing", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--dry-run"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("productionOverride: true");
|
||||
expect(result.stdout).toContain("生产环境覆盖已启用");
|
||||
expect(result.stdout).toContain("--allow-prod --yes");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("--allow-prod still requires --yes before the production grant runs", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod"]),
|
||||
prodRuntime()
|
||||
)
|
||||
).rejects.toThrow("拒绝执行开通企业工作流灰度节点");
|
||||
expect(grant).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("--allow-prod --yes executes the production grant and marks the result", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--yes"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("生产环境覆盖已启用");
|
||||
expect(result.stdout).toContain("灰度节点开通结果");
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("--force remains a compatible production override alias", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "ok", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--force", "--yes"]),
|
||||
prodRuntime()
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("生产环境覆盖已启用");
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("--allow-prod --yes JSON result exposes productionOverride", async () => {
|
||||
const grant = spyOn(services, "grantWorkflowNodes").mockResolvedValue({
|
||||
success: true, saved: ["code"], skipped: [], rawMessage: "新开通的节点:code", isTest: false,
|
||||
});
|
||||
try {
|
||||
const result = await handleWorkflowCommand(
|
||||
parseArgs(["workflow", "nodes", "grant", "code", "--allow-prod", "--yes", "--json"]),
|
||||
prodRuntime(true)
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).productionOverride).toBe(true);
|
||||
expect(grant).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -11,6 +11,7 @@ const mockCorp: CorpConfig = {
|
||||
name: "浙江麦瑞克科技有限公司",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
env: "test",
|
||||
credentials: {
|
||||
accessToken: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
@@ -135,10 +136,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
it("workflow nodes grant: 免密模式下成功发起灰度节点开通", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
code: 200,
|
||||
msg: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
@@ -159,7 +158,7 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
expect(res.stdout).toContain("code-js2");
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
payload: expect.objectContaining({ dslTypes: ["code-js2"] }),
|
||||
token: "mock-access-token",
|
||||
corpId: "ID01rJEL708iTI",
|
||||
})
|
||||
@@ -168,10 +167,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
it("workflow nodes grant: 节点名称自动中文归一化 (如 'JS节点(新)' 映射为 'code-js2')", async () => {
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:code-js2",
|
||||
code: 200,
|
||||
msg: "新开通的节点:code-js2",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
@@ -189,12 +186,12 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(grantSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
nodes: ["code-js2"],
|
||||
payload: expect.objectContaining({ dslTypes: ["code-js2"] }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("workflow nodes grant: 管理员密码保护预留生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
it("workflow nodes grant: 可选管理员密码保护生效 (未提供密码或密码错误被拒绝)", async () => {
|
||||
process.env.HOSE_ADMIN_PASSWORD = "secret_admin_pass";
|
||||
|
||||
// 1. 无密码调用被拒绝
|
||||
@@ -214,10 +211,8 @@ describe("CLI - workflow nodes 字典探针与灰度开通测试", () => {
|
||||
|
||||
// 3. 正确密码调用放行
|
||||
const grantSpy = spyOn(api, "grantWorkflowNodesApi").mockResolvedValue({
|
||||
success: true,
|
||||
saved: ["code-js2"],
|
||||
skipped: [],
|
||||
rawMessage: "开通成功",
|
||||
code: 200,
|
||||
msg: "开通成功",
|
||||
});
|
||||
spies.push(grantSpy);
|
||||
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { EkbError } from "../../../core/errors.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
|
||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
|
||||
import {
|
||||
@@ -99,6 +99,22 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
|
||||
// 保存前静态代码健康度检查
|
||||
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
|
||||
const scriptWarnings: string[] = [];
|
||||
if (scriptLintReport.totalCodeNodes > 0) {
|
||||
for (const node of scriptLintReport.reports) {
|
||||
if (node.issues.length > 0) {
|
||||
for (const iss of node.issues) {
|
||||
const icon = iss.level === "error" ? "❌" : "⚠️";
|
||||
const loc = iss.line ? `(L${iss.line})` : "";
|
||||
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -112,6 +128,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
tasksVersion: parsedWorkflow.tasksVersion,
|
||||
forceWrite,
|
||||
syncFile,
|
||||
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
|
||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查)
|
||||
const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]);
|
||||
if (flowFilter) {
|
||||
const corpId = runtime.selectedCorp?.credentials.corpId || "";
|
||||
const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, {
|
||||
maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(searchResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: searchResult.found ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!searchResult.found) {
|
||||
return {
|
||||
stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`,
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const job = searchResult.job!;
|
||||
const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存";
|
||||
const out = [
|
||||
`====== 工作流单据定位成功 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"定位来源": hitInfo,
|
||||
"触发单号": searchResult.flowCode || "-",
|
||||
"实例 ID (jobId)": job.id,
|
||||
"运行状态 (status)": job.status || "-",
|
||||
"提交人": job.inputs?.userInfo?.name || "-",
|
||||
"创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-",
|
||||
}),
|
||||
"",
|
||||
`提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
|
||||
@@ -17,6 +17,8 @@ import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js"
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import { handleWorkflowLink } from "./link.js";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -126,11 +128,16 @@ export async function handleWorkflowCommand(
|
||||
case "url":
|
||||
case "web":
|
||||
return handleWorkflowLink(parsed, runtime);
|
||||
case "outbound":
|
||||
case "outbounds":
|
||||
case "outbound-message":
|
||||
return handleOutboundCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link, outbound\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { getWorkflowAvailableNodes, grantWorkflowNodes } from "../../../domains/platform/workflow/services.js";
|
||||
import { GRAY_NODES_CATALOG, findGrayNode } from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { getWorkflowAvailableNodes, grantWorkflowNodes, GRANT_ATTACHED_OPTIONS } from "../../../domains/platform/workflow/services.js";
|
||||
import { GRAY_NODES_CATALOG, normalizeGrayNodes } from "../../../domains/platform/workflow/nodes/gray-nodes-catalog.js";
|
||||
import { isCorpProd } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createPiperClientForCorp } from "../../helpers.js";
|
||||
|
||||
@@ -19,7 +21,7 @@ export async function handleListAvailableNodes(
|
||||
|
||||
const showAll = Boolean(parsed.options.all || parsed.options.compare || parsed.options.diff);
|
||||
const filterKw = (
|
||||
parsed.args[1] ||
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["keyword", "query", "filter"]) ||
|
||||
""
|
||||
).toLowerCase();
|
||||
@@ -114,16 +116,18 @@ export async function handleGrantNodes(
|
||||
const corp = runtime.selectedCorp!;
|
||||
const rawNodes = parsed.args.slice(1);
|
||||
const optionNodes = stringOption(parsed.options, ["nodes", "node", "type", "types"]);
|
||||
const targetNodes: string[] = [];
|
||||
const collected: string[] = [];
|
||||
|
||||
if (optionNodes) {
|
||||
targetNodes.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
collected.push(...optionNodes.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
for (const arg of rawNodes) {
|
||||
if (arg && !arg.startsWith("-")) {
|
||||
targetNodes.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
collected.push(...arg.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean));
|
||||
}
|
||||
}
|
||||
// 去重,避免同一节点被重复提交;不做白名单硬校验(灰度清单不是全集)。
|
||||
const targetNodes = Array.from(new Set(collected));
|
||||
|
||||
if (targetNodes.length === 0) {
|
||||
return {
|
||||
@@ -133,39 +137,88 @@ export async function handleGrantNodes(
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(parsed, runtime, "开通企业工作流灰度节点", "hose-use workflow nodes grant <type...> --yes");
|
||||
const isProd = isCorpProd(corp);
|
||||
const allowProd = hasProductionOverride(parsed);
|
||||
const isTest = booleanOption(parsed.options, ["is-test"]);
|
||||
const confirmNextAction = buildConfirmedCommand(parsed);
|
||||
const prodNextAction = buildConfirmedCommand(parsed, ["--allow-prod"]);
|
||||
|
||||
// 预览不产生写操作,始终放行;生产环境只在 nextAction 中补上覆盖参数。
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "开通企业工作流灰度节点", corp.corpId || corp.credentials.corpId || corp.id, {
|
||||
nodes: targetNodes.map(node => findGrayNode(node)?.type || node.trim()),
|
||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||
});
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"开通企业工作流灰度节点",
|
||||
corp.corpId || corp.credentials.corpId || corp.id,
|
||||
{
|
||||
nodes: normalizeGrayNodes(targetNodes),
|
||||
isTest,
|
||||
attachedOptions: GRANT_ATTACHED_OPTIONS,
|
||||
adminPasswordRequired: Boolean(process.env.HOSE_ADMIN_PASSWORD),
|
||||
...(isProd
|
||||
? {
|
||||
productionOverride: allowProd,
|
||||
productionWarning: allowProd
|
||||
? "生产环境覆盖已启用:实际执行会变更正式生产企业,请再次核对企业与节点类型。"
|
||||
: "当前为正式生产企业:实际执行需追加 --allow-prod 确认。",
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
{ extraArgs: isProd && !allowProd ? ["--allow-prod"] : [] }
|
||||
);
|
||||
}
|
||||
|
||||
const blocked = productionGuard(parsed, runtime, {
|
||||
operation: "开通企业工作流灰度节点",
|
||||
operationCode: "workflow.nodes.grant",
|
||||
risk: "灰度节点开通是不可逆的企业级写操作,会改变正式生产企业的可用节点能力。",
|
||||
nextAction: prodNextAction,
|
||||
});
|
||||
if (blocked) return blocked;
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"开通企业工作流灰度节点",
|
||||
isProd ? prodNextAction : confirmNextAction
|
||||
);
|
||||
|
||||
const password = stringOption(parsed.options, ["password", "pwd", "admin-key"]);
|
||||
|
||||
const result = await grantWorkflowNodes(corp, {
|
||||
nodes: targetNodes,
|
||||
password,
|
||||
isTest,
|
||||
});
|
||||
|
||||
const overrideMeta = productionOverrideMeta(
|
||||
parsed,
|
||||
runtime,
|
||||
"生产环境覆盖已启用 (--allow-prod):本次对正式生产企业执行了灰度节点开通。"
|
||||
);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stdout: printJson({ ...result, ...overrideMeta }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: result.success ? 0 : 1,
|
||||
};
|
||||
}
|
||||
if (!result.success) {
|
||||
return { stdout: "", stderr: `灰度节点开通失败: ${result.rawMessage || "网关拒绝了开通请求"}\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `灰度节点开通失败: ${result.rawMessage || "Piper 拒绝了开通请求"}\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const lines = [
|
||||
...(overrideMeta.productionOverride
|
||||
? [`⚠️ ${overrideMeta.productionWarning}`, ""]
|
||||
: []),
|
||||
`====== 灰度节点开通结果 [${corp.name}] ======`,
|
||||
printKeyValue({
|
||||
"申请开通节点": targetNodes.join(", "),
|
||||
"Piper 环境": result.isTest ? "测试 Piper" : "标准 Piper",
|
||||
"新开通成功": result.saved.length ? result.saved.join(", ") : "无 (已处于开通状态)",
|
||||
"跳过(已开通)": result.skipped.length ? result.skipped.join(", ") : "无",
|
||||
"网关反馈": result.rawMessage || "处理成功",
|
||||
"附带固定开关": Object.keys(GRANT_ATTACHED_OPTIONS).join(", "),
|
||||
"Piper 反馈": result.rawMessage || "处理成功",
|
||||
}),
|
||||
"",
|
||||
"✅ 节点权限已生效!工作流设计器与 hose-use workflow analyze 将立即支持该节点。",
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
applyNodeMapping,
|
||||
getJobExecutionTree,
|
||||
listWorkflowLogs,
|
||||
refreshWorkflowChooses,
|
||||
} from "../../../domains/platform/workflow/services.js";
|
||||
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
|
||||
import { ValidationError } from "../../../core/errors.js";
|
||||
@@ -15,7 +18,7 @@ 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) {
|
||||
@@ -26,8 +29,11 @@ async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0],
|
||||
});
|
||||
}
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||
const SUB_ACTIONS = new Set([
|
||||
"list", "ls", "get", "show", "info", "add", "append", "insert",
|
||||
"edit", "update", "set", "map", "rm", "remove", "delete", "del",
|
||||
"inspect", "probe", "examine", "sample-save", "save-sample",
|
||||
]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -80,21 +86,26 @@ export async function handleNodeCommand(
|
||||
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
|
||||
"",
|
||||
"子命令 (工作流级别):",
|
||||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
|
||||
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
"",
|
||||
"子命令 (企业灰度节点级别):",
|
||||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||||
" nodes grant <type...> 为当前企业开通灰度节点",
|
||||
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产企业执行需显式 --allow-prod)",
|
||||
"",
|
||||
"示例:",
|
||||
" 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 nodes grant code-js2 --dry-run # 生产企业:预览(无需覆盖参数)",
|
||||
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行(--force 兼容)",
|
||||
" hose-use workflow node list 896398895352487950",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
@@ -105,6 +116,13 @@ export async function handleNodeCommand(
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleListNodes(pipelineId, parsed, runtime);
|
||||
case "inspect":
|
||||
case "probe":
|
||||
case "examine":
|
||||
return handleInspectNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "sample-save":
|
||||
case "save-sample":
|
||||
return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "get":
|
||||
case "show":
|
||||
case "info":
|
||||
@@ -319,6 +337,10 @@ async function handleAddNode(
|
||||
}
|
||||
}
|
||||
|
||||
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
|
||||
const chooseMode = resolveChooseSerialization(parsed);
|
||||
normalizeNodeExpressionFields(extra, chooseMode);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -351,11 +373,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 +398,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 +472,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 +519,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 +545,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,
|
||||
};
|
||||
@@ -658,3 +693,251 @@ async function handleRemoveNode(
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleInspectNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||||
|
||||
if (!located) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { task, hierarchicalIndex, path, parentName } = located;
|
||||
const sampleData = (task as any).sampleData ?? null;
|
||||
|
||||
let executionProbe: {
|
||||
jobId: string;
|
||||
status: string;
|
||||
executionTime?: number;
|
||||
output?: any;
|
||||
error?: any;
|
||||
} | null = null;
|
||||
|
||||
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
|
||||
try {
|
||||
let jobIdToProbe = targetJobId;
|
||||
if (!jobIdToProbe) {
|
||||
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||||
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
|
||||
if (firstItem && firstItem.id) {
|
||||
jobIdToProbe = firstItem.id;
|
||||
}
|
||||
}
|
||||
|
||||
if (jobIdToProbe) {
|
||||
const tree = await getJobExecutionTree(client, jobIdToProbe);
|
||||
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
|
||||
if (matchExecution) {
|
||||
executionProbe = {
|
||||
jobId: jobIdToProbe,
|
||||
status: matchExecution.status || "UNKNOWN",
|
||||
executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime,
|
||||
output: matchExecution.output,
|
||||
error: matchExecution.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探针容错
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
pipelineId,
|
||||
node: located,
|
||||
sampleData,
|
||||
executionProbe,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outLines: string[] = [
|
||||
`====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`,
|
||||
`节点标识 (name) : ${task.name}`,
|
||||
`层级编号 (#) : ${hierarchicalIndex}`,
|
||||
`节点类型 (type) : ${task.type}`,
|
||||
`节点标题 (label) : ${task.label || "-"}`,
|
||||
`节点显示名 (display): ${(task as any).displayName || "-"}`,
|
||||
`父容器节点 : ${parentName || "顶级节点 (root)"}`,
|
||||
`JSON 路径 : ${path}`,
|
||||
];
|
||||
|
||||
if ((task as any).code !== undefined) {
|
||||
outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`);
|
||||
}
|
||||
if ((task as any).url) {
|
||||
outLines.push(`请求 URL : ${(task as any).url}`);
|
||||
}
|
||||
if ((task as any).specificationId) {
|
||||
outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`);
|
||||
}
|
||||
|
||||
outLines.push("");
|
||||
outLines.push("── 📦 节点固化样本数据 (sampleData) ──");
|
||||
if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) {
|
||||
const keys = Object.keys(sampleData);
|
||||
outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`);
|
||||
outLines.push(printJson(sampleData, runtime.outputOptions));
|
||||
} else {
|
||||
outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)");
|
||||
outLines.push("💡 提示: 可运行 hose-use workflow node sample-save <pipelineId> <nodeName> 固化最近调测出参");
|
||||
}
|
||||
|
||||
outLines.push("");
|
||||
outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──");
|
||||
if (executionProbe) {
|
||||
outLines.push(`来源 Job ID : ${executionProbe.jobId}`);
|
||||
outLines.push(`执行状态 (status) : ${executionProbe.status}`);
|
||||
outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`);
|
||||
if (executionProbe.output && typeof executionProbe.output === "object") {
|
||||
outLines.push(`出参全貌 (output):`);
|
||||
outLines.push(printJson(executionProbe.output, runtime.outputOptions));
|
||||
} else {
|
||||
outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`);
|
||||
}
|
||||
} else {
|
||||
outLines.push("未找到或无匹配的最近调试执行记录。");
|
||||
}
|
||||
|
||||
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSaveNodeSample(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||||
|
||||
if (!located) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { task } = located;
|
||||
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
|
||||
|
||||
let jobIdToProbe = targetJobId;
|
||||
if (!jobIdToProbe) {
|
||||
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||||
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
|
||||
if (firstItem && firstItem.id) {
|
||||
jobIdToProbe = firstItem.id;
|
||||
}
|
||||
}
|
||||
|
||||
if (!jobIdToProbe) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job=<id> 指定。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const tree = await getJobExecutionTree(client, jobIdToProbe);
|
||||
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
|
||||
|
||||
if (!matchExecution || matchExecution.output === undefined) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const samplePayload = matchExecution.output;
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, {
|
||||
pipelineId,
|
||||
nodeName: task.name,
|
||||
jobId: jobIdToProbe,
|
||||
samplePayload,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"固化节点样本数据 (sampleData)",
|
||||
`hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes`
|
||||
);
|
||||
|
||||
(task as any).sampleData = samplePayload;
|
||||
const saveResult = await saveNodeChanges(client, detail, detail, platformId);
|
||||
|
||||
try {
|
||||
await refreshWorkflowChooses(client, pipelineId);
|
||||
} catch {}
|
||||
|
||||
const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
pipelineId,
|
||||
nodeName: task.name,
|
||||
jobId: jobIdToProbe,
|
||||
fieldsSaved: fieldCount,
|
||||
sampleData: samplePayload,
|
||||
workflow: saveResult,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`,
|
||||
` • 来源 Job ID : ${jobIdToProbe}`,
|
||||
` • 固化字段数 : ${fieldCount} 个属性`,
|
||||
` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`,
|
||||
`📌 ${formatWorkflowVersion(saveResult)}`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { handleOutboundCommand } from "./outbound.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
describe("handleOutboundCommand", () => {
|
||||
it("rejects when no corp selected", async () => {
|
||||
const result = await handleOutboundCommand(
|
||||
{ args: ["list"], options: {}, raw: [] },
|
||||
{ selectedCorp: null, jsonMode: false } as unknown as CliRuntime
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未选中企业");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user