Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86b88d8785 | ||
|
|
9fa4cfe38f | ||
|
|
77bd125ef3 | ||
|
|
644c3d2005 | ||
|
|
4e36a1d9a5 | ||
|
|
7c0bdb7518 | ||
|
|
2865728885 | ||
|
|
eaa2b9391f | ||
|
|
51502fada5 | ||
|
|
cf5d12b0a5 | ||
|
|
535404871c | ||
|
|
269b7e8f0f | ||
|
|
c99c5d98ec | ||
|
|
4fbd737402 | ||
|
|
40b3b29ca5 | ||
|
|
04d3dbcc02 | ||
|
|
39fb3a47f5 | ||
|
|
aa2a61d44f | ||
|
|
507bf6ab91 | ||
|
|
9ddbd0390d | ||
|
|
a2d078aafe | ||
|
|
85bbc9bbb4 | ||
|
|
e84cae7f80 | ||
|
|
2b4bf49663 | ||
|
|
06da94152d | ||
|
|
17e5418005 | ||
|
|
a5bfaafa10 | ||
|
|
84e6fa58fd | ||
|
|
f72deb01b1 | ||
|
|
acd187b616 | ||
|
|
43d923f567 | ||
|
|
e44b120cc2 | ||
|
|
7d9f656567 | ||
|
|
c14338f1bc | ||
|
|
9d351ed15d | ||
|
|
373fb11a81 | ||
|
|
2a06cf58b7 | ||
|
|
6d61ece8cd | ||
|
|
3d963e9a7e | ||
|
|
96d28da862 | ||
|
|
1d1170526b | ||
|
|
1f3334bfbd | ||
|
|
a0d13ca36a | ||
|
|
9e1a13c1fe | ||
|
|
334c72617c | ||
|
|
0514291d2d | ||
|
|
cbeeca746b | ||
|
|
7a8f2f6931 | ||
|
|
3df9201a5e | ||
|
|
60866efa2e | ||
|
|
dbf8dd942e | ||
|
|
6468710730 | ||
|
|
85d5f8f13a | ||
|
|
a8bdb67293 | ||
|
|
155f179fcd | ||
|
|
621c8cb7dc | ||
|
|
0be1365289 | ||
|
|
97abdb4f96 | ||
|
|
12247fd350 | ||
|
|
49b0359adb | ||
|
|
1ef611eeab | ||
|
|
d28b0c92d9 | ||
|
|
6c0f4dc567 | ||
|
|
8aa401ab79 | ||
|
|
a381fa2698 | ||
|
|
88e8c384a6 | ||
|
|
68d570022d | ||
|
|
188a0fb5dc |
No files matched your search
@@ -42,12 +42,27 @@ jobs:
|
||||
- name: Package release archives
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y zip
|
||||
cd dist/bin
|
||||
tar -czf hose-use-linux-x64.tar.gz hose-use-linux-x64
|
||||
tar -czf hose-use-linux-arm64.tar.gz hose-use-linux-arm64
|
||||
tar -czf hose-use-darwin-x64.tar.gz hose-use-darwin-x64
|
||||
tar -czf hose-use-darwin-arm64.tar.gz hose-use-darwin-arm64
|
||||
zip -q hose-use-windows-x64.zip hose-use-windows-x64.exe
|
||||
package_unix() {
|
||||
local binary="$1"
|
||||
local archive="$2"
|
||||
local stage
|
||||
stage=$(mktemp -d)
|
||||
cp "dist/bin/${binary}" "${stage}/${binary}"
|
||||
ln -s "${binary}" "${stage}/hose-aipro"
|
||||
tar -czf "dist/bin/${archive}" -C "${stage}" "${binary}" hose-aipro
|
||||
rm -rf "${stage}"
|
||||
}
|
||||
|
||||
package_unix hose-use-linux-x64 hose-use-linux-x64.tar.gz
|
||||
package_unix hose-use-linux-arm64 hose-use-linux-arm64.tar.gz
|
||||
package_unix hose-use-darwin-x64 hose-use-darwin-x64.tar.gz
|
||||
package_unix hose-use-darwin-arm64 hose-use-darwin-arm64.tar.gz
|
||||
|
||||
stage=$(mktemp -d)
|
||||
cp dist/bin/hose-use-windows-x64.exe "${stage}/hose-use-windows-x64.exe"
|
||||
printf '@echo off\r\n"%%~dp0hose-use-windows-x64.exe" %%*\r\n' > "${stage}/hose-aipro.cmd"
|
||||
(cd "${stage}" && zip -q "${GITHUB_WORKSPACE}/dist/bin/hose-use-windows-x64.zip" hose-use-windows-x64.exe hose-aipro.cmd)
|
||||
rm -rf "${stage}"
|
||||
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@ node_modules
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
dist/bin/
|
||||
dist/hose-use-*
|
||||
*.tgz
|
||||
|
||||
# code coverage
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"hose-use": {
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
],
|
||||
"env": {
|
||||
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
|
||||
},
|
||||
"timeoutMs": 120000
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.7.1",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
},
|
||||
"license": "MIT",
|
||||
"skills": "skills",
|
||||
"mcpServers": "./.mcp.json",
|
||||
"userConfig": {
|
||||
"enable_mcp": {
|
||||
"type": "boolean",
|
||||
"title": "启用 MCP 服务",
|
||||
"description": "开启后向 Agent 暴露 hose_cli 单工具网关;默认关闭。保存后重新连接该插件的 MCP 服务。",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,3 +89,38 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
- 目录细节写进对应目录的 `README.{dirname}.md`
|
||||
- 文件细节写进对应文件旁的说明文档
|
||||
- 子域的 API 路径、枚举值、字段语义不要继续回填到根目录
|
||||
|
||||
## 分支管理与 PR 合并规范(严格对标 seal-use)
|
||||
|
||||
为了保证代码变更可追溯、CI 校验完备与版本安全,本仓库实施**硬性约束(通过 Git pre-push hook 与 PR 流程双重卡点)**:
|
||||
|
||||
1. **严禁直接推送到 `main` 分支**:
|
||||
- 仓库已内置 `.git/hooks/pre-push` 钩子,本地直接执行 `git push origin main` 将被直接拦截拒绝;
|
||||
- 日常功能开发、Bug 修复和版本发布必须且只能走独立分支;
|
||||
2. **分支命名规范**:
|
||||
- 特性分支:`feat/<feature-name>` 或 `codex/issue-<id>-<name>`
|
||||
- 发布分支:`codex/release-v<X.Y.Z>` 或 `release/v<X.Y.Z>`
|
||||
- 维护优化:`chore/<task-name>` 或 `fix/<issue-name>`
|
||||
3. **Pull Request 提交流程**:
|
||||
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
|
||||
- 推送分支至远端:`git push origin <branch>`;
|
||||
- 发起 PR:`gh pr create --base main --head <branch> --title "..." --body "..."`(如有对应 Issue 需关联 `Fixes #...`);
|
||||
- 等待 CI 检查:`gh pr checks <pr-number> --watch`;
|
||||
- 审查通过后合入:`gh pr merge <pr-number> --merge --delete-branch`;
|
||||
4. **版本发布与 Tag 推送标准流程(严格对齐 seal-use)**:
|
||||
- PR 合并后,切回本地 `main` 分支并同步:
|
||||
```bash
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
git push home main
|
||||
```
|
||||
- 打 Release Tag:
|
||||
```bash
|
||||
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
|
||||
```
|
||||
- **推送顺序极关键**:先推 `home` (Gitea),再推 `origin` (GitHub)。最后推 GitHub 触发 Release Action:
|
||||
```bash
|
||||
git push home refs/tags/vX.Y.Z
|
||||
git push origin refs/tags/vX.Y.Z
|
||||
```
|
||||
- 监控云端 Release 构建并验证产物发布完成。
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.5.0)
|
||||
# hose-use (v0.7.1)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -78,10 +78,16 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
|
||||
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
|
||||
- 避免数十个业务工具占用大量 Prompt Tokens;
|
||||
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 中,Agent 按需学习;
|
||||
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
|
||||
- 内部同进程调用 CLI 分发层,零子进程开销;
|
||||
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
|
||||
|
||||
### 模块化 Agent Skill 与 IDE 插件规范
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
|
||||
|
||||
## 架构
|
||||
|
||||
```text
|
||||
@@ -132,7 +138,7 @@ src/
|
||||
- **Runtime**: Bun
|
||||
- **HTTP Client**: ky
|
||||
- **Schema**: Zod
|
||||
- **MCP SDK**: @modelcontextprotocol/sdk
|
||||
- **MCP Protocol**: @modelcontextprotocol/server & @modelcontextprotocol/core (v2.0+)
|
||||
|
||||
## 面向 AI 智能体
|
||||
|
||||
|
||||
@@ -5,214 +5,60 @@
|
||||
"": {
|
||||
"name": "ekb-mcp",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"typescript": "^5.9.3",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
|
||||
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
|
||||
|
||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
|
||||
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
|
||||
|
||||
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
|
||||
|
||||
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
|
||||
|
||||
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
|
||||
|
||||
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
||||
|
||||
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
|
||||
|
||||
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
|
||||
|
||||
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
|
||||
|
||||
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
|
||||
|
||||
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
|
||||
|
||||
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
|
||||
|
||||
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
|
||||
|
||||
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
|
||||
|
||||
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
|
||||
|
||||
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
|
||||
|
||||
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
|
||||
|
||||
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
|
||||
|
||||
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
|
||||
|
||||
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
|
||||
|
||||
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
|
||||
|
||||
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
|
||||
|
||||
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
|
||||
|
||||
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
|
||||
|
||||
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
|
||||
|
||||
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
|
||||
|
||||
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
|
||||
|
||||
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
|
||||
|
||||
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
|
||||
|
||||
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
|
||||
|
||||
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
|
||||
|
||||
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
|
||||
|
||||
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
|
||||
|
||||
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
|
||||
|
||||
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
|
||||
|
||||
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
|
||||
|
||||
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
|
||||
|
||||
"hasown": ["hasown@2.0.3", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg=="],
|
||||
|
||||
"hono": ["hono@4.12.19", "", {}, "sha512-xa3eYXYXx68XTT4hZ7dRzsXBhaq85ToSrlUJNoR0gwz/1Ap/CNwX47wfvV7pc/xWhjKVVkLT7zBJy8chhNguqQ=="],
|
||||
|
||||
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
|
||||
|
||||
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
|
||||
|
||||
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],
|
||||
|
||||
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
|
||||
|
||||
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
|
||||
|
||||
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
|
||||
|
||||
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
|
||||
|
||||
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
|
||||
|
||||
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
|
||||
|
||||
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
|
||||
|
||||
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
|
||||
|
||||
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
|
||||
|
||||
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
|
||||
|
||||
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
|
||||
|
||||
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
|
||||
|
||||
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
|
||||
|
||||
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
|
||||
|
||||
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
|
||||
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
|
||||
|
||||
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
|
||||
|
||||
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
|
||||
|
||||
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
|
||||
|
||||
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
|
||||
|
||||
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
|
||||
|
||||
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
|
||||
|
||||
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
|
||||
|
||||
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
|
||||
|
||||
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
|
||||
|
||||
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
|
||||
|
||||
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
|
||||
|
||||
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
|
||||
|
||||
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
|
||||
|
||||
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
|
||||
|
||||
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
|
||||
|
||||
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
|
||||
|
||||
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
|
||||
|
||||
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
|
||||
|
||||
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
|
||||
|
||||
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
|
||||
|
||||
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
|
||||
}
|
||||
}
|
||||
Vendored
+635
@@ -0,0 +1,635 @@
|
||||
import{createRequire as LN}from"node:module";var JN=Object.create;var{getPrototypeOf:XN,defineProperty:F0,getOwnPropertyNames:ON}=Object;var jN=Object.prototype.hasOwnProperty;function AN($){return this[$]}var GN,QN,CJ=($,i,v)=>{var u=$!=null&&typeof $==="object";if(u){var n=i?GN??=new WeakMap:QN??=new WeakMap,b=n.get($);if(b)return b}v=$!=null?JN(XN($)):{};let I=i||!$||!$.__esModule?F0(v,"default",{value:$,enumerable:!0}):v;for(let U of ON($))if(!jN.call(I,U))F0(I,U,{get:AN.bind($,U),enumerable:!0});if(u)n.set($,I);return I};var S=($,i)=>()=>(i||$((i={exports:{}}).exports,i),i.exports);var YN=($)=>$;function NN($,i){this[$]=YN.bind(null,i)}var Gi=($,i)=>{for(var v in i)F0($,v,{get:i[v],enumerable:!0,configurable:!0,set:NN.bind(i,v)})};var _J=LN(import.meta.url);var l4=S((jO)=>{Object.defineProperty(jO,"__esModule",{value:!0});jO.regexpCode=jO.getEsmExportName=jO.getProperty=jO.safeStringify=jO.stringify=jO.strConcat=jO.addCodeArg=jO.str=jO._=jO.nil=jO._Code=jO.Name=jO.IDENTIFIER=jO._CodeOrName=void 0;class Gb{}jO._CodeOrName=Gb;jO.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class gv extends Gb{constructor($){super();if(!jO.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}jO.Name=gv;class ii extends Gb{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((i,v)=>`${i}${v}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((i,v)=>{if(v instanceof gv)i[v.str]=(i[v.str]||0)+1;return i},{})}}jO._Code=ii;jO.nil=new ii("");function XO($,...i){let v=[$[0]],u=0;while(u<i.length)Cg(v,i[u]),v.push($[++u]);return new ii(v)}jO._=XO;var Rg=new ii("+");function OO($,...i){let v=[T4($[0])],u=0;while(u<i.length)v.push(Rg),Cg(v,i[u]),v.push(Rg,T4($[++u]));return fL(v),new ii(v)}jO.str=OO;function Cg($,i){if(i instanceof ii)$.push(...i._items);else if(i instanceof gv)$.push(i);else $.push(cL(i))}jO.addCodeArg=Cg;function fL($){let i=1;while(i<$.length-1){if($[i]===Rg){let v=xL($[i-1],$[i+1]);if(v!==void 0){$.splice(i-1,3,v);continue}$[i++]="+"}i++}}function xL($,i){if(i==='""')return $;if($==='""')return i;if(typeof $=="string"){if(i instanceof gv||$[$.length-1]!=='"')return;if(typeof i!="string")return`${$.slice(0,-1)}${i}"`;if(i[0]==='"')return $.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!($ instanceof gv))return`"${$}${i.slice(1)}`;return}function yL($,i){return i.emptyStr()?$:$.emptyStr()?i:OO`${$}${i}`}jO.strConcat=yL;function cL($){return typeof $=="number"||typeof $=="boolean"||$===null?$:T4(Array.isArray($)?$.join(","):$)}function hL($){return new ii(T4($))}jO.stringify=hL;function T4($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}jO.safeStringify=T4;function mL($){return typeof $=="string"&&jO.IDENTIFIER.test($)?new ii(`.${$}`):XO`[${$}]`}jO.getProperty=mL;function oL($){if(typeof $=="string"&&jO.IDENTIFIER.test($))return new ii(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}jO.getEsmExportName=oL;function dL($){return new ii($.toString())}jO.regexpCode=dL});var xg=S((YO)=>{Object.defineProperty(YO,"__esModule",{value:!0});YO.ValueScope=YO.ValueScopeName=YO.Scope=YO.varKinds=YO.UsedValueState=void 0;var C$=l4();class GO extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var Yb;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(Yb||(YO.UsedValueState=Yb={}));YO.varKinds={const:new C$.Name("const"),let:new C$.Name("let"),var:new C$.Name("var")};class rg{constructor({prefixes:$,parent:i}={}){this._names={},this._prefixes=$,this._parent=i}toName($){return $ instanceof C$.Name?$:this.name($)}name($){return new C$.Name(this._newName($))}_newName($){let i=this._names[$]||this._nameGroup($);return`${$}${i.index++}`}_nameGroup($){var i,v;if(((v=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||v===void 0?void 0:v.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}YO.Scope=rg;class fg extends C$.Name{constructor($,i){super(i);this.prefix=$}setValue($,{property:i,itemIndex:v}){this.value=$,this.scopePath=C$._`.${new C$.Name(i)}[${v}]`}}YO.ValueScopeName=fg;var DK=C$._`\n`;class QO extends rg{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?DK:C$.nil}}get(){return this._scope}name($){return new fg($,this._newName($))}value($,i){var v;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let u=this.toName($),{prefix:n}=u,b=(v=i.key)!==null&&v!==void 0?v:i.ref,I=this._values[n];if(I){let w=I.get(b);if(w)return w}else I=this._values[n]=newLine truncated
|
||||
`:""},this._extScope=$,this._scope=new ni.Scope({parent:$}),this._nodes=[new BO]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,i){let v=this._extScope.value($,i);return(this._values[v.prefix]||(this._values[v.prefix]=new Set)).add(v),v}getScopeValue($,i){return this._extScope.getValue($,i)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,i,v,u){let n=this._scope.toName(i);if(v!==void 0&&u)this._constants[n.str]=v;return this._leafNode(new LO($,n,v)),n}const($,i,v){return this._def(ni.varKinds.const,$,i,v)}let($,i,v){return this._def(ni.varKinds.let,$,i,v)}var($,i,v){return this._def(ni.varKinds.var,$,i,v)}assign($,i,v){return this._leafNode(new hg($,i,v))}add($,i){return this._leafNode(new KO($,_$.operators.ADD,i))}code($){if(typeof $=="function")$();else if($!==d.nil)this._leafNode(new FO($));return this}object(...$){let i=["{"];for(let[v,u]of $){if(i.length>1)i.push(",");if(i.push(v),v!==u||this.opts.es5)i.push(":"),(0,d.addCodeArg)(i,u)}return i.push("}"),new d._Code(i)}if($,i,v){if(this._blockNode(new Ki($)),i&&v)this.code(i).else().code(v).endIf();else if(i)this.code(i).endIf();else if(v)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Ki($))}else(){return this._elseNode(new E4)}endIf(){return this._endBlockNode(Ki,E4)}_for($,i){if(this._blockNode($),i)this.code(i).endFor();return this}for($,i){return this._for(new SO($),i)}forRange($,i,v,u,n=this.opts.es5?ni.varKinds.var:ni.varKinds.let){let b=this._scope.toName($);return this._for(new ZO(n,b,i,v),()=>u(b))}forOf($,i,v,u=ni.varKinds.const){let n=this._scope.toName($);if(this.opts.es5){let b=i instanceof d.Name?i:this.var("_arr",i);return this.forRange("_i",0,d._`${b}.length`,(I)=>{this.var(n,d._`${b}[${I}]`),v(n)})}return this._for(new yg("of",u,n,i),()=>v(n))}forIn($,i,v,u=this.opts.es5?ni.varKinds.var:ni.varKinds.const){if(this.opts.ownProperties)return this.forOf($,d._`Object.keys(${i})`,v);let n=this._scope.toName($);return this._for(new yg("in",u,n,i),()=>v(n))}endFor(){return this._endBlockNode(Wv)}label($){return this._leafNode(new zO($))}break($){return this._leafNode(new HO($))}return($){let i=new Lb;if(this._blockNode(i),this.code($),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Lb)}try($,i,v){if(!i&&!v)throw Error('CodeGen: "try" without "catch" and "finally"');let u=new VO;if(this._blockNode(u),this.code($),i){let n=this.name("e");this._currNode=u.catch=new Kb(n),i(n)}if(v)this._currNode=u.finally=new zb,this.code(v);return this._endBlockNode(Kb,zb)}throw($){return this._leafNode(new PO($))}block($,i){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(i);return this}endBlock($){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let v=this._nodes.length-i;if(v<0||$!==void 0&&v!==$)throw Error(`CodeGen: wrong number of nodes: ${v} vs ${$} expected`);return this._nodes.length=i,this}func($,i=d.nil,v,u){if(this._blockNode(new Nb($,i,v)),u)this.code(u).endFunc();return this}endFunc(){return this._endBlockNode(Nb)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,i){let v=this._currNode;if(v instanceof $||i&&v instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${$.kind}/${i.kind}`:$.kind}"`)}_elseNode($){let i=this._currNode;if(!(i instanceof Ki))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let i=this._nodes;i[i.length-1]=$}}_$.CodeGen=qO;function Wn($,i){for(let v in i)$[v]=($[v]||0)+(i[v]||0);return $}function Hb($,i){return i instanceof d._CodeOrName?Wn($,i.names):$}function Jv($,i,v){if($ instanceof d.Name)return u($);if(!n($))return $;return new d._Code($._items.reduce((b,I)=>{if(I instanceof d.Name)I=u(I);if(I instanceof d._Code)b.push(...I._items);else b.push(I);return b},[]));function u(b){let I=v[b.str];if(I===void 0||i[b.str]!==1)return b;return delete i[b.str],I}function n(b){return b instanceof d._Code&&b._items.some((I)=>I instanceof d.Name&&i[I.str]===1&&v[I.str]!==void 0)}}function JK($,i){for(let v in i)$[v]=($[v]||0)-(i[v]||0)}function MO($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:d._`!${cg($)}`}_$.not=MO;var XK=kO(_$.operators.AND);function OK(...$){return $.reduce(XK)}_$.and=OK;var jK=kO(_$.operators.OR);function AK(...$){return $.reduce(jK)}_$.or=AK;function kO($){return(i,v)=>i===d.nil?v:v===d.nil?i:d._`${cg(i)} ${$} ${cg(v)}`}function cg($){return $ instanceof d.Name?$:d._`(${$})`}});var p=S((fO)=>{Object.
Line truncated
|
||||
|| (${I} == "string" && ${n} && ${n} == +${n})`).assign(U,x._`+${n}`);return;case"integer":u.elseIf(x._`${I} === "boolean" || ${n} === null
|
||||
|| (${I} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(U,x._`+${n}`);return;case"boolean":u.elseIf(x._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(U,!1).elseIf(x._`${n} === "true" || ${n} === 1`).assign(U,!0);return;case"null":u.elseIf(x._`${n} === "" || ${n} === 0 || ${n} === false`),u.assign(U,null);return;case"array":u.elseIf(x._`${I} === "string" || ${I} === "number"
|
||||
|| ${I} === "boolean" || ${n} === null`).assign(U,x._`[${n}]`)}}}function Zz({gen:$,parentData:i,parentDataProperty:v},u){$.if(x._`${i} !== undefined`,()=>$.assign(x._`${i}[${v}]`,u))}function sg($,i,v,u=Xv.Correct){let n=u===Xv.Correct?x.operators.EQ:x.operators.NEQ,b;switch($){case"null":return x._`${i} ${n} null`;case"array":b=x._`Array.isArray(${i})`;break;case"object":b=x._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":b=I(x._`!(${i} % 1) && !isNaN(${i})`);break;case"number":b=I();break;default:return x._`typeof ${i} ${n} ${$}`}return u===Xv.Correct?b:(0,x.not)(b);function I(U=x.nil){return(0,x.and)(x._`typeof ${i} == "number"`,U,v?x._`isFinite(${i})`:x.nil)}}wj.checkDataType=sg;function $W($,i,v,u){if($.length===1)return sg($[0],i,v,u);let n,b=(0,Ij.toHash)($);if(b.array&&b.object){let I=x._`typeof ${i} != "object"`;n=b.null?I:x._`!${i} || ${I}`,delete b.null,delete b.array,delete b.object}else n=x.nil;if(b.number)delete b.integer;for(let I in b)n=(0,x.and)(n,sg(I,i,v,u));return n}wj.checkDataTypes=$W;var Vz={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:i})=>typeof $=="string"?x._`{type: ${$}}`:x._`{type: ${i}}`};function iW($){let i=qz($);(0,Hz.reportError)(i,Vz)}wj.reportTypeError=iW;function qz($){let{gen:i,data:v,schema:u}=$,n=(0,Ij.schemaRefOrVal)($,u,"type");return{gen:i,keyword:"type",data:v,schema:u.type,schemaCode:n,schemaValue:n,parentSchema:u,params:{},it:$}}});var Oj=S((Jj)=>{Object.defineProperty(Jj,"__esModule",{value:!0});Jj.assignDefaults=void 0;var Ov=y(),Rz=p();function Cz($,i){let{properties:v,items:u}=$.schema;if(i==="object"&&v)for(let n in v)Wj($,n,v[n].default);else if(i==="array"&&Array.isArray(u))u.forEach((n,b)=>Wj($,b,n.default))}Jj.assignDefaults=Cz;function Wj($,i,v){let{gen:u,compositeRule:n,data:b,opts:I}=$;if(v===void 0)return;let U=Ov._`${b}${(0,Ov.getProperty)(i)}`;if(n){(0,Rz.checkStrictMode)($,`default is ignored for: ${U}`);return}let D=Ov._`${U} === undefined`;if(I.useDefaults==="empty")D=Ov._`${D} || ${U} === null || ${U} === ""`;u.if(D,Ov._`${U} = ${(0,Ov.stringify)(v)}`)}});var a$=S((Gj)=>{Object.defineProperty(Gj,"__esModule",{value:!0});Gj.validateUnion=Gj.validateArray=Gj.usePattern=Gj.callValidateCode=Gj.schemaProperties=Gj.allSchemaProperties=Gj.noPropertyInData=Gj.propertyInData=Gj.isOwnProperty=Gj.hasPropFunc=Gj.reportMissingProp=Gj.checkMissingProp=Gj.checkReportMissingProp=void 0;var w$=y(),nW=p(),hi=zi(),_z=p();function rz($,i){let{gen:v,data:u,it:n}=$;v.if(uW(v,u,i,n.opts.ownProperties),()=>{$.setParams({missingProperty:w$._`${i}`},!0),$.error()})}Gj.checkReportMissingProp=rz;function fz({gen:$,data:i,it:{opts:v}},u,n){return(0,w$.or)(...u.map((b)=>(0,w$.and)(uW($,i,b,v.ownProperties),w$._`${n} = ${b}`)))}Gj.checkMissingProp=fz;function xz($,i){$.setParams({missingProperty:i},!0),$.error()}Gj.reportMissingProp=xz;function jj($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:w$._`Object.prototype.hasOwnProperty`})}Gj.hasPropFunc=jj;function vW($,i,v){return w$._`${jj($)}.call(${i}, ${v})`}Gj.isOwnProperty=vW;function yz($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} !== undefined`;return u?w$._`${n} && ${vW($,i,v)}`:n}Gj.propertyInData=yz;function uW($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} === undefined`;return u?(0,w$.or)(n,(0,w$.not)(vW($,i,v))):n}Gj.noPropertyInData=uW;function Aj($){return $?Object.keys($).filter((i)=>i!=="__proto__"):[]}Gj.allSchemaProperties=Aj;function cz($,i){return Aj(i).filter((v)=>!(0,nW.alwaysValidSchema)($,i[v]))}Gj.schemaProperties=cz;function hz({schemaCode:$,data:i,it:{gen:v,topSchemaRef:u,schemaPath:n,errorPath:b},it:I},U,D,w){let g=w?w$._`${$}, ${i}, ${u}${n}`:i,J=[[hi.default.instancePath,(0,w$.strConcat)(hi.default.instancePath,b)],[hi.default.parentData,I.parentData],[hi.default.parentDataProperty,I.parentDataProperty],[hi.default.rootData,hi.default.rootData]];if(I.opts.dynamicRef)J.push([hi.default.dynamicAnchors,hi.default.dynamicAnchors]);let X=w$._`${g}, ${v.object(...J)}`;return D!==w$.nil?w$._`${U}.call(${D}, ${X})`:w$._`${U}(${X})`}Gj.callValidateCode=hz;var mz=w$._`new RegExp`;function oz({gen:$,it:{opts:i}},v){let u=i.unicodeRegExp?"u":"",{regExp:n}=i.code,b=n(v,u);return $.scopeValue("pattern",{key:b.toString(),ref:b,code:w$._`${n.code==="new RegExp"?mz:(0,_z.useFunc)($,n)}(${v}, ${u})`})}Gj.usePattern=oz;function dz($){let{gen:i,data:v,keyword:u,it:n}=$,b=i.name("valid");if(n.allErrors){let U=i.let("valid",!0);return I(()=>i.assign(U,!1)),U}return i.var(b,!0),I(()=>i.break()),b;function I(U){let D=i.const("len",w$._`${v}.length`);i.forRange("i",0,D,(w)=>{$.subschema({keyword:u,dataProp:w,dataPropType:nW.Type.Num},b),i.if((0,w$.not)(b),U)})}}Gj.validateArray=dz;function pz($){let{gen:i,schema:v,keyword:u,it:n}=$;if(!Array.isArray(v))throw Error("ajv implementation error");if(v.some((D)=>(0,nW.alwaysValidSchema)(n,D))&&!n.opts.unevaluated)return;let I=i.let("valid",!1),U=i.name("_valid");i.block(()=>v.for
Line truncated
|
||||
missingProperty: ${u},
|
||||
depsCount: ${i},
|
||||
deps: ${v}}`};var jS={keyword:"dependencies",type:"object",schemaType:"object",error:TA.error,code($){let[i,v]=AS($);MA($,i),kA($,v)}};function AS({schema:$}){let i={},v={};for(let u in $){if(u==="__proto__")continue;let n=Array.isArray($[u])?i:v;n[u]=$[u]}return[i,v]}function MA($,i=$.schema){let{gen:v,data:u,it:n}=$;if(Object.keys(i).length===0)return;let b=v.let("missing");for(let I in i){let U=i[I];if(U.length===0)continue;let D=(0,$6.propertyInData)(v,u,I,n.opts.ownProperties);if($.setParams({property:I,depsCount:U.length,deps:U.join(", ")}),n.allErrors)v.if(D,()=>{for(let w of U)(0,$6.checkReportMissingProp)($,w)});else v.if(BW._`${D} && (${(0,$6.checkMissingProp)($,U,b)})`),(0,$6.reportMissingProp)($,b),v.else()}}TA.validatePropertyDeps=MA;function kA($,i=$.schema){let{gen:v,data:u,keyword:n,it:b}=$,I=v.name("valid");for(let U in i){if((0,OS.alwaysValidSchema)(b,i[U]))continue;v.if((0,$6.propertyInData)(v,u,U,b.opts.ownProperties),()=>{let D=$.subschema({keyword:n,schemaProp:U},I);$.mergeValidEvaluated(D,I)},()=>v.var(I,!0)),$.ok(I)}}TA.validateSchemaDeps=kA;TA.default=jS});var _A=S((CA)=>{Object.defineProperty(CA,"__esModule",{value:!0});var RA=y(),YS=p(),NS={message:"property name must be valid",params:({params:$})=>RA._`{propertyName: ${$.propertyName}}`},LS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:NS,code($){let{gen:i,schema:v,data:u,it:n}=$;if((0,YS.alwaysValidSchema)(n,v))return;let b=i.name("valid");i.forIn("key",u,(I)=>{$.setParams({propertyName:I}),$.subschema({keyword:"propertyNames",data:I,dataTypes:["string"],propertyName:I,compositeRule:!0},b),i.if((0,RA.not)(b),()=>{if($.error(!0),!n.allErrors)i.break()})}),$.ok(b)}};CA.default=LS});var SW=S((rA)=>{Object.defineProperty(rA,"__esModule",{value:!0});var hb=a$(),bi=y(),zS=zi(),mb=p(),HS={message:"must NOT have additional properties",params:({params:$})=>bi._`{additionalProperty: ${$.additionalProperty}}`},PS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:HS,code($){let{gen:i,schema:v,parentSchema:u,data:n,errsCount:b,it:I}=$;if(!b)throw Error("ajv implementation error");let{allErrors:U,opts:D}=I;if(I.props=!0,D.removeAdditional!=="all"&&(0,mb.alwaysValidSchema)(I,v))return;let w=(0,hb.allSchemaProperties)(u.properties),g=(0,hb.allSchemaProperties)(u.patternProperties);J(),$.ok(bi._`${b} === ${zS.default.errors}`);function J(){i.forIn("key",n,(N)=>{if(!w.length&&!g.length)j(N);else i.if(X(N),()=>j(N))})}function X(N){let L;if(w.length>8){let B=(0,mb.schemaRefOrVal)(I,u.properties,"properties");L=(0,hb.isOwnProperty)(i,B,N)}else if(w.length)L=(0,bi.or)(...w.map((B)=>bi._`${N} === ${B}`));else L=bi.nil;if(g.length)L=(0,bi.or)(L,...g.map((B)=>bi._`${(0,hb.usePattern)($,B)}.test(${N})`));return(0,bi.not)(L)}function O(N){i.code(bi._`delete ${n}[${N}]`)}function j(N){if(D.removeAdditional==="all"||D.removeAdditional&&v===!1){O(N);return}if(v===!1){if($.setParams({additionalProperty:N}),$.error(),!U)i.break();return}if(typeof v=="object"&&!(0,mb.alwaysValidSchema)(I,v)){let L=i.name("valid");if(D.removeAdditional==="failing")G(N,L,!1),i.if((0,bi.not)(L),()=>{$.reset(),O(N)});else if(G(N,L),!U)i.if((0,bi.not)(L),()=>i.break())}}function G(N,L,B){let V={keyword:"additionalProperties",dataProp:N,dataPropType:mb.Type.Str};if(B===!1)Object.assign(V,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(V,L)}}};rA.default=PS});var cA=S((yA)=>{Object.defineProperty(yA,"__esModule",{value:!0});var BS=f4(),fA=a$(),ZW=p(),xA=SW(),SS={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:i,schema:v,parentSchema:u,data:n,it:b}=$;if(b.opts.removeAdditional==="all"&&u.additionalProperties===void 0)xA.default.code(new BS.KeywordCxt(b,xA.default,"additionalProperties"));let I=(0,fA.allSchemaProperties)(v);for(let J of I)b.definedProperties.add(J);if(b.opts.unevaluated&&I.length&&b.props!==!0)b.props=ZW.mergeEvaluated.props(i,(0,ZW.toHash)(I),b.props);let U=I.filter((J)=>!(0,ZW.alwaysValidSchema)(b,v[J]));if(U.length===0)return;let D=i.name("valid");for(let J of U){if(w(J))g(J);else{if(i.if((0,fA.propertyInData)(i,n,J,b.opts.ownProperties)),g(J),!b.allErrors)i.else().var(D,!0);i.endIf()}$.it.definedProperties.add(J),$.ok(D)}function w(J){return b.opts.useDefaults&&!b.compositeRule&&v[J].default!==void 0}function g(J){$.subschema({keyword:"properties",schemaProp:J,dataProp:J},D)}}};yA.default=SS});var pA=S((dA)=>{Object.defineProperty(dA,"__esModule",{value:!0});var hA=a$(),ob=y(),mA=p(),oA=p(),VS={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:i,schema:v,data:u,parentSchema:n,it:b}=$,{opts:I}=b,U=(0,hA.allSchemaProperties)(v),D=U.filter((G)=>(0,mA.alwaysValidSchema)(b,v[G]));if(U.length===0||D.length===U.length&&(!b.opts.unevaluated||b.props===!0))return;let w=I.strictSchema&&!I.allowMatchingProperties&&n.properties,g=i.name("valid");if(b.props!==!0&&!(b.props instanceof ob.Name))b.props=(0,oA.evalu
Line truncated
|
||||
`)}var Vn=($)=>(i,v,u,n)=>{let b=u?{...u,async:!1}:{async:!1},I=i._zod.run({value:v,issues:[]},b);if(I instanceof Promise)throw new wi;if(I.issues.length){let U=new(n?.Err??$)(I.issues.map((D)=>V$(D,b,X$())));throw S6(U,n?.callee),U}return I.value},hv=Vn(t$),qn=($)=>async(i,v,u,n)=>{let b=u?{...u,async:!0}:{async:!0},I=i._zod.run({value:v,issues:[]},b);if(I instanceof Promise)I=await I;if(I.issues.length){let U=new(n?.Err??$)(I.issues.map((D)=>V$(D,b,X$())));throw S6(U,n?.callee),U}return I.value},mv=qn(t$),Mn=($)=>(i,v,u)=>{let n=u?{...u,async:!1}:{async:!1},b=i._zod.run({value:v,issues:[]},n);if(b instanceof Promise)throw new wi;return b.issues.length?{success:!1,error:new($??xv)(b.issues.map((I)=>V$(I,n,X$())))}:{success:!0,data:b.value}},kn=Mn(t$),Tn=($)=>async(i,v,u)=>{let n=u?{...u,async:!0}:{async:!0},b=i._zod.run({value:v,issues:[]},n);if(b instanceof Promise)b=await b;return b.issues.length?{success:!1,error:new $(b.issues.map((I)=>V$(I,n,X$())))}:{success:!0,data:b.value}},ov=Tn(t$),Z6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Vn($)(i,v,n)},oJ=Z6(t$),V6=($)=>(i,v,u)=>{return Vn($)(i,v,u)},dJ=V6(t$),q6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return qn($)(i,v,n)},pJ=q6(t$),M6=($)=>async(i,v,u)=>{return qn($)(i,v,u)},aJ=M6(t$),k6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Mn($)(i,v,n)},eJ=k6(t$),T6=($)=>(i,v,u)=>{return Mn($)(i,v,u)},sJ=T6(t$),l6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Tn($)(i,v,n)},$8=l6(t$),E6=($)=>async(i,v,u)=>{return Tn($)(i,v,u)},i8=E6(t$);var c$={};Gi(c$,{xid:()=>y0,uuid7:()=>aN,uuid6:()=>pN,uuid4:()=>dN,uuid:()=>bn,uppercase:()=>j1,unicodeEmail:()=>n8,undefined:()=>X1,ulid:()=>x0,time:()=>I1,string:()=>D1,sha512_hex:()=>Q7,sha512_base64url:()=>N7,sha512_base64:()=>Y7,sha384_hex:()=>j7,sha384_base64url:()=>G7,sha384_base64:()=>A7,sha256_hex:()=>J7,sha256_base64url:()=>O7,sha256_base64:()=>X7,sha1_hex:()=>w7,sha1_base64url:()=>W7,sha1_base64:()=>g7,rfc5322Email:()=>sN,number:()=>dv,null:()=>J1,nanoid:()=>h0,md5_hex:()=>I7,md5_base64url:()=>D7,md5_base64:()=>U7,mac:()=>s0,lowercase:()=>O1,ksuid:()=>c0,ipv6:()=>e0,ipv4:()=>a0,integer:()=>g1,idnEmail:()=>$7,httpProtocol:()=>v1,html5Email:()=>eN,hostname:()=>v7,hex:()=>b7,guid:()=>o0,extendedDuration:()=>oN,emoji:()=>p0,email:()=>d0,e164:()=>u1,duration:()=>m0,domain:()=>u7,datetime:()=>U1,date:()=>b1,cuid2:()=>f0,cuid:()=>r0,cidrv6:()=>i1,cidrv4:()=>$1,browserEmail:()=>i7,boolean:()=>W1,bigint:()=>w1,base64url:()=>t6,base64:()=>n1});var r0=/^[cC][0-9a-z]{6,}$/,f0=/^[0-9a-z]+$/,x0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,y0=/^[0-9a-vA-V]{20}$/,c0=/^[A-Za-z0-9]{27}$/,h0=/^[a-zA-Z0-9_-]{21}$/,m0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,o0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bn=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},dN=bn(4),pN=bn(6),aN=bn(7),d0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,eN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sN=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,n8=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$7=n8,i7=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,n7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function p0(){return new RegExp(n7,"u")}var a0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,e0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,s0=($)=>{let i=o$($??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},$1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
|
||||
`).filter((b)=>b),u=Math.min(...v.map((b)=>b.length-b.trimStart().length)),n=v.map((b)=>b.slice(u)).map((b)=>" ".repeat(this.indent*2)+b);for(let b of n)this.content.push(b)}compile(){let $=Function,i=this?.args,u=[...(this?.content??[""]).map((n)=>` ${n}`)];return new $(...i,u.join(`
|
||||
`))}}var T1={major:4,minor:4,patch:3};var t=A("$ZodType",($,i)=>{var v;$??($={}),$._zod.def=i,$._zod.bag=$._zod.bag||{},$._zod.version=T1;let u=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))u.unshift($);for(let n of u)for(let b of n._zod.onattach)b($);if(u.length===0)(v=$._zod).deferred??(v.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let n=(I,U,D)=>{let w=ki(I),g;for(let J of U){if(J._zod.def.when){if(R0(I))continue;if(!J._zod.def.when(I))continue}else if(w)continue;let X=I.issues.length,O=J._zod.check(I);if(O instanceof Promise&&D?.async===!1)throw new wi;if(g||O instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await O,I.issues.length===X)return;if(!w)w=ki(I,X)});else{if(I.issues.length===X)continue;if(!w)w=ki(I,X)}}if(g)return g.then(()=>{return I});return I},b=(I,U,D)=>{if(ki(I))return I.aborted=!0,I;let w=n(U,u,D);if(w instanceof Promise){if(D.async===!1)throw new wi;return w.then((g)=>$._zod.parse(g,D))}return $._zod.parse(w,D)};$._zod.run=(I,U)=>{if(U.skipChecks)return $._zod.parse(I,U);if(U.direction==="backward"){let w=$._zod.parse({value:I.value,issues:[]},{...U,skipChecks:!0});if(w instanceof Promise)return w.then((g)=>{return b(g,I,U)});return b(w,I,U)}let D=$._zod.parse(I,U);if(D instanceof Promise){if(U.async===!1)throw new wi;return D.then((w)=>n(w,u,U))}return n(D,u,U)}}c($,"~standard",()=>({validate:(n)=>{try{let b=kn($,n);return b.success?{value:b.data}:{issues:b.error?.issues}}catch(b){return ov($,n).then((I)=>I.success?{value:I.data}:{issues:I.error?.issues})}},vendor:"zod",version:1}))}),In=A("$ZodString",($,i)=>{t.init($,i),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??D1($._zod.bag),$._zod.parse=(v,u)=>{if(i.coerce)try{v.value=String(v.value)}catch(n){}if(typeof v.value==="string")return v;return v.issues.push({expected:"string",code:"invalid_type",input:v.value,inst:$}),v}}),n$=A("$ZodStringFormat",($,i)=>{ln.init($,i),In.init($,i)}),E1=A("$ZodGUID",($,i)=>{i.pattern??(i.pattern=o0),n$.init($,i)}),t1=A("$ZodUUID",($,i)=>{if(i.version){let u={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(u===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=bn(u))}else i.pattern??(i.pattern=bn());n$.init($,i)}),R1=A("$ZodEmail",($,i)=>{i.pattern??(i.pattern=d0),n$.init($,i)}),C1=A("$ZodURL",($,i)=>{n$.init($,i),$._zod.check=(v)=>{try{let u=v.value.trim();if(!i.normalize&&i.protocol?.source===v1.source){if(!/^https?:\/\//i.test(u)){v.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:v.value,inst:$,continue:!i.abort});return}}let n=new URL(u);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(n.hostname))v.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:v.value,inst:$,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))v.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:v.value,inst:$,continue:!i.abort})}if(i.normalize)v.value=n.href;else v.value=u;return}catch(u){v.issues.push({code:"invalid_format",format:"url",input:v.value,inst:$,continue:!i.abort})}}}),_1=A("$ZodEmoji",($,i)=>{i.pattern??(i.pattern=p0()),n$.init($,i)}),r1=A("$ZodNanoID",($,i)=>{i.pattern??(i.pattern=h0),n$.init($,i)}),f1=A("$ZodCUID",($,i)=>{i.pattern??(i.pattern=r0),n$.init($,i)}),x1=A("$ZodCUID2",($,i)=>{i.pattern??(i.pattern=f0),n$.init($,i)}),y1=A("$ZodULID",($,i)=>{i.pattern??(i.pattern=x0),n$.init($,i)}),c1=A("$ZodXID",($,i)=>{i.pattern??(i.pattern=y0),n$.init($,i)}),h1=A("$ZodKSUID",($,i)=>{i.pattern??(i.pattern=c0),n$.init($,i)}),m1=A("$ZodISODateTime",($,i)=>{i.pattern??(i.pattern=U1(i)),n$.init($,i)}),o1=A("$ZodISODate",($,i)=>{i.pattern??(i.pattern=b1),n$.init($,i)}),d1=A("$ZodISOTime",($,i)=>{i.pattern??(i.pattern=I1(i)),n$.init($,i)}),p1=A("$ZodISODuration",($,i)=>{i.pattern??(i.pattern=m0),n$.init($,i)}),a1=A("$ZodIPv4",($,i)=>{i.pattern??(i.pattern=a0),n$.init($,i),$._zod.bag.format="ipv4"}),e1=A("$ZodIPv6",($,i)=>{i.pattern??(i.pattern=e0),n$.init($,i),$._zod.bag.format="ipv6",$._zod.check=(v)=>{try{new URL(`http://[${v.value}]`)}catch{v.issues.push({code:"invalid_format",format:"ipv6",input:v.value,inst:$,continue:!i.abort})}}}),s1=A("$ZodMAC",($,i)=>{i.pattern??(i.pattern=s0(i.delimiter)),n$.init($,i),$._zod.bag.format="mac"}),$I=A("$ZodCIDRv4",($,i)=>{i.pattern??(i.pattern=$1),n$.init($,i)}),iI=A("$ZodCIDRv6",($,i)=>{i.pattern??(i.pattern=i1),n$.init($,i),$._zod.check=(v)=>{let u=v.value.split("/");try{if(u.length!==2)throw Error();let[n,b]=u;if(!b)throw Error();let I=Number(b);if(`${I}`!==b)throw Error();if(I<0||I>128)throw Error();new URL(`http://[${n}]`)}catch{v.issues.push({code:"invalid_format",format:"cidrv6",input:v.value,inst:$,continue:!i.abort})}}});function nI($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var
Line truncated
|
||||
if (${q}.issues.length) {
|
||||
if (${M} in input) {
|
||||
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
|
||||
...iss,
|
||||
path: iss.path ? [${M}, ...iss.path] : [${M}]
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
if (${q}.value === undefined) {
|
||||
if (${M} in input) {
|
||||
newResult[${M}] = undefined;
|
||||
}
|
||||
} else {
|
||||
newResult[${M}] = ${q}.value;
|
||||
}
|
||||
|
||||
`);else if(!C)O.write(`
|
||||
const ${q}_present = ${M} in input;
|
||||
if (${q}.issues.length) {
|
||||
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
|
||||
...iss,
|
||||
path: iss.path ? [${M}, ...iss.path] : [${M}]
|
||||
})));
|
||||
}
|
||||
if (!${q}_present && !${q}.issues.length) {
|
||||
payload.issues.push({
|
||||
code: "invalid_type",
|
||||
expected: "nonoptional",
|
||||
input: undefined,
|
||||
path: [${M}]
|
||||
});
|
||||
}
|
||||
|
||||
if (${q}_present) {
|
||||
if (${q}.value === undefined) {
|
||||
newResult[${M}] = undefined;
|
||||
} else {
|
||||
newResult[${M}] = ${q}.value;
|
||||
}
|
||||
}
|
||||
|
||||
`);else O.write(`
|
||||
if (${q}.issues.length) {
|
||||
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
|
||||
...iss,
|
||||
path: iss.path ? [${M}, ...iss.path] : [${M}]
|
||||
})));
|
||||
}
|
||||
|
||||
if (${q}.value === undefined) {
|
||||
if (${M} in input) {
|
||||
newResult[${M}] = undefined;
|
||||
}
|
||||
} else {
|
||||
newResult[${M}] = ${q}.value;
|
||||
}
|
||||
|
||||
`)}O.write("payload.value = newResult;"),O.write("return payload;");let B=O.compile();return(V,q)=>B(X,V,q)},b,I=un,U=!nn.jitless,w=U&&M0.value,g=i.catchall,J;$._zod.parse=(X,O)=>{J??(J=u.value);let j=X.value;if(!I(j))return X.issues.push({expected:"object",code:"invalid_type",input:j,inst:$}),X;if(U&&w&&O?.async===!1&&O.jitless!==!0){if(!b)b=n(i.shape);if(X=b(X,O),!g)return X;return P8([],j,X,O,J,$)}return v(X,O)}});function w8($,i,v,u){for(let b of $)if(b.issues.length===0)return i.value=b.value,i;let n=$.filter((b)=>!ki(b));if(n.length===1)return i.value=n[0].value,n[0];return i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:$.map((b)=>b.issues.map((I)=>V$(I,u,X$())))}),i}var sv=A("$ZodUnion",($,i)=>{t.init($,i),c($._zod,"optin",()=>i.options.some((u)=>u._zod.optin==="optional")?"optional":void 0),c($._zod,"optout",()=>i.options.some((u)=>u._zod.optout==="optional")?"optional":void 0),c($._zod,"values",()=>{if(i.options.every((u)=>u._zod.values))return new Set(i.options.flatMap((u)=>Array.from(u._zod.values)));return}),c($._zod,"pattern",()=>{if(i.options.every((u)=>u._zod.pattern)){let u=i.options.map((n)=>n._zod.pattern);return new RegExp(`^(${u.map((n)=>Cv(n.source)).join("|")})$`)}return});let v=i.options.length===1?i.options[0]._zod.run:null;$._zod.parse=(u,n)=>{if(v)return v(u,n);let b=!1,I=[];for(let U of i.options){let D=U._zod.run({value:u.value,issues:[]},n);if(D instanceof Promise)I.push(D),b=!0;else{if(D.issues.length===0)return D;I.push(D)}}if(!b)return w8(I,u,$,n);return Promise.all(I).then((U)=>{return w8(U,u,$,n)})}});function g8($,i,v,u){let n=$.filter((b)=>b.issues.length===0);if(n.length===1)return i.value=n[0].value,i;if(n.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:$.map((b)=>b.issues.map((I)=>V$(I,u,X$())))});else i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:[],inclusive:!1});return i}var NI=A("$ZodXor",($,i)=>{sv.init($,i),i.inclusive=!1;let v=i.options.length===1?i.options[0]._zod.run:null;$._zod.parse=(u,n)=>{if(v)return v(u,n);let b=!1,I=[];for(let U of i.options){let D=U._zod.run({value:u.value,issues:[]},n);if(D instanceof Promise)I.push(D),b=!0;else I.push(D)}if(!b)return g8(I,u,$,n);return Promise.all(I).then((U)=>{return g8(U,u,$,n)})}}),LI=A("$ZodDiscriminatedUnion",($,i)=>{i.inclusive=!1,sv.init($,i);let v=$._zod.parse;c($._zod,"propValues",()=>{let n={};for(let b of i.options){let I=b._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(b)}"`);for(let[U,D]of Object.entries(I)){if(!n[U])n[U]=new Set;for(let w of D)n[U].add(w)}}return n});let u=Sn(()=>{let n=i.options,b=new Map;for(let I of n){let U=I._zod.propValues?.[i.discriminator];if(!U||U.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(I)}"`);for(let D of U){if(b.has(D))throw Error(`Duplicate discriminator value "${String(D)}"`);b.set(D,I)}}return b});$._zod.parse=(n,b)=>{let I=n.value;if(!un(I))return n.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),n;let U=u.value.get(I?.[i.discriminator]);if(U)return U._zod.run(n,b);if(i.unionFallback||b.direction==="backward")return v(n,b);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(u.value.keys()),input:I,path:[i.discriminator],inst:$}),n}}),KI=A("$ZodIntersection",($,i)=>{t.init($,i),$._zod.parse=(v,u)=>{let n=v.value,b=i.left._zod.run({value:n,issues:[]},u),I=i.right._zod.run({value:n,issues:[]},u);if(b instanceof Promise||I instanceof Promise)return Promise.all([b,I]).then(([D,w])=>{return W8(v,D,w)});return W8(v,b,I)}});function l1($,i){if($===i)return{valid:!0,data:$};if($ instanceof Date&&i instanceof Date&&+$===+i)return{valid:!0,data:$};if(Mi($)&&Mi(i)){let v=Object.keys(i),u=Object.keys($).filter((b)=>v.indexOf(b)!==-1),n={...$,...i};for(let b of u){let I=l1($[b],i[b]);if(!I.valid)return{valid:!1,mergeErrorPath:[b,...I.mergeErrorPath]};n[b]=I.data}return{valid:!0,data:n}}if(Array.isArray($)&&Array.isArray(i)){if($.length!==i.length)return{valid:!1,mergeErrorPath:[]};let v=[];for(let u=0;u<$.length;u++){let n=$[u],b=i[u],I=l1(n,b);if(!I.valid)return{valid:!1,mergeErrorPath:[u,...I.mergeErrorPath]};v.push(I.data)}return{valid:!0,data:v}}return{valid:!1,mergeErrorPath:[]}}function W8($,i,v){let u=new Map,n;for(let U of i.issues)if(U.code==="unrecognized_keys"){n??(n=U);for(let D of U.keys){if(!u.has(D))u.set(D,{});u.get(D).l=!0}}else $.issues.push(U);for(let U of v.issues)if(U.code==="unrecognized_keys")for(let D of U.keys){if(!u.has(D))u.set(D,{});u.get(D).r=!0}else $.issues.push(U);let b=[...u].filter(([,U])=>U.l&&U.r).map(([U])=>U);if(b.length&&n)$.issues.push({...n,keys:b});if(ki($))return $;let I=l1(i.value,v.value);if(!I.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}var m6=A("$ZodTuple",($,i)=>{t.init($,i
Line truncated
|
||||
|
||||
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let I of $.seen.entries()){let U=I[1];if(i===I[0]){b(I);continue}if($.external){let w=$.external.registry.get(I[0])?.id;if(i!==I[0]&&w){b(I);continue}}if($.metadataRegistry.get(I[0])?.id){b(I);continue}if(U.cycle){b(I);continue}if(U.count>1){if($.reused==="ref"){b(I);continue}}}}function Ri($,i){let v=$.seen.get(i);if(!v)throw Error("Unprocessed schema. This is a bug in Zod.");let u=(U)=>{let D=$.seen.get(U);if(D.ref===null)return;let w=D.def??D.schema,g={...w},J=D.ref;if(D.ref=null,J){u(J);let O=$.seen.get(J),j=O.schema;if(j.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))w.allOf=w.allOf??[],w.allOf.push(j);else Object.assign(w,j);if(Object.assign(w,g),U._zod.parent===J)for(let N in w){if(N==="$ref"||N==="allOf")continue;if(!(N in g))delete w[N]}if(j.$ref&&O.def)for(let N in w){if(N==="$ref"||N==="allOf")continue;if(N in O.def&&JSON.stringify(w[N])===JSON.stringify(O.def[N]))delete w[N]}}let X=U._zod.parent;if(X&&X!==J){u(X);let O=$.seen.get(X);if(O?.schema.$ref){if(w.$ref=O.schema.$ref,O.def)for(let j in w){if(j==="$ref"||j==="allOf")continue;if(j in O.def&&JSON.stringify(w[j])===JSON.stringify(O.def[j]))delete w[j]}}}$.override({zodSchema:U,jsonSchema:w,path:D.path??[]})};for(let U of[...$.seen.entries()].reverse())u(U[0]);let n={};if($.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let U=$.external.registry.get(i)?.id;if(!U)throw Error("Schema is missing an `id` property");n.$id=$.external.uri(U)}Object.assign(n,v.def??v.schema);let b=$.metadataRegistry.get(i)?.id;if(b!==void 0&&n.id===b)delete n.id;let I=$.external?.defs??{};for(let U of $.seen.entries()){let D=U[1];if(D.def&&D.defId){if(D.def.id===D.defId)delete D.def.id;I[D.defId]=D.def}}if($.external);else if(Object.keys(I).length>0)if($.target==="draft-2020-12")n.$defs=I;else n.definitions=I;try{let U=JSON.parse(JSON.stringify(n));return Object.defineProperty(U,"~standard",{value:{...i["~standard"],jsonSchema:{input:pn(i,"input",$.processors),output:pn(i,"output",$.processors)}},enumerable:!1,writable:!1}),U}catch(U){throw Error("Error converting schema to JSON.")}}function M$($,i){let v=i??{seen:new Set};if(v.seen.has($))return!1;v.seen.add($);let u=$._zod.def;if(u.type==="transform")return!0;if(u.type==="array")return M$(u.element,v);if(u.type==="set")return M$(u.valueType,v);if(u.type==="lazy")return M$(u.getter(),v);if(u.type==="promise"||u.type==="optional"||u.type==="nonoptional"||u.type==="nullable"||u.type==="readonly"||u.type==="default"||u.type==="prefault")return M$(u.innerType,v);if(u.type==="intersection")return M$(u.left,v)||M$(u.right,v);if(u.type==="record"||u.type==="map")return M$(u.keyType,v)||M$(u.valueType,v);if(u.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return M$(u.in,v)||M$(u.out,v)}if(u.type==="object"){for(let n in u.shape)if(M$(u.shape[n],v))return!0;return!1}if(u.type==="union"){for(let n of u.options)if(M$(n,v))return!0;return!1}if(u.type==="tuple"){for(let n of u.items)if(M$(n,v))return!0;if(u.rest&&M$(u.rest,v))return!0;return!1}return!1}var SD=($,i={})=>(v)=>{let u=Ei({...v,processors:i});return $$($,u),ti(u,$),Ri(u,$)},pn=($,i,v={})=>(u)=>{let{libraryOptions:n,target:b}=u??{},I=Ei({...n??{},target:b,io:i,processors:v});return $$($,I),ti(I,$),Ri(I,$)};var f5={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ZD=($,i,v,u)=>{let n=v;n.type="string";let{minimum:b,maximum:I,format:U,patterns:D,contentEncoding:w}=$._zod.bag;if(typeof b==="number")n.minLength=b;if(typeof I==="number")n.maxLength=I;if(U){if(n.format=f5[U]??U,n.format==="")delete n.format;if(U==="time")delete n.format}if(w)n.contentEncoding=w;if(D&&D.size>0){let g=[...D];if(g.length===1)n.pattern=g[0].source;else if(g.length>1)n.allOf=[...g.map((J)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:J.source}))]}},VD=($,i,v,u)=>{let n=v,{minimum:b,maximum:I,format:U,multipleOf:D,exclusiveMaximum:w,exclusiveMinimum:g}=$._zod.bag;if(typeof U==="string"&&U.includes("int"))n.type="integer";else n.type="number";let J=typeof g==="number"&&g>=(b??Number.NEGATIVE_INFINITY),X=typeof w==="number"&&w<=(I??Number.POSITIVE_INFINITY),O=i.target==="draft-04"||i.target==="openapi-3.0";if(J)if(O)n.minimum=g,n.exclusiveMinimum=!0;else n.exclusiveMinimum=g;else if(typeof b==="number")n.minimum=b;if(X)if(O)n.maximum=w,n.exclusiveMaximum=!0;else n.exclusiveMaximum=w;else if(typeof I==="number")n.maximum=I;if(typeof D==="number")n.multipleOf=D},qD=($,i,v,u)=>{v.type="boolean"},MD=($,i,v,u)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},kD=($,i,v,u)=>{if(i.unrepresentable==="Line truncated
|
||||
`);if($===-1)return null;let i=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),gV(i)}clear(){this._buffer=void 0}}function gV($){return nO.parse(JSON.parse($))}function eG($){return JSON.stringify($)+`
|
||||
`}class hW{constructor($=sG.stdin,i=sG.stdout){this._stdin=$,this._stdout=i,this._readBuffer=new cW,this._started=!1,this._ondata=(v)=>{this._readBuffer.append(v),this.processReadBuffer()},this._onerror=(v)=>{this.onerror?.(v)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((i)=>{let v=eG($);if(this._stdout.write(v))i();else this._stdout.once("drain",i)})}}import{dirname as F6,resolve as wN}from"node:path";import{fileURLToPath as hM}from"node:url";import{existsSync as pi,mkdirSync as jV,readFileSync as iQ,readdirSync as AV,writeFileSync as nQ}from"node:fs";import{homedir as $0}from"node:os";import{dirname as GV,join as zv}from"node:path";var WV=W.enum(["account","assist","browser","manual","curl","f12"]),JV=W.object({accessToken:W.string().describe("主站访问令牌"),corpId:W.string().describe("企业 ID"),staffId:W.string().describe("员工 ID")}),XV=W.object({refreshTtl:W.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),refreshToken:W.string().optional().describe("OAuth2 Refresh Token"),expiresAt:W.number().optional().describe("AccessToken 到期时间戳 (ms)")}),OV=W.object({platform:W.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),isAssistPlatform:W.boolean().optional().describe("是否为官方协助/代客平台登录"),isShortTermToken:W.boolean().optional().describe("是否为短期临时 Token"),assistId:W.string().optional().describe("协助会话/工单 ID"),operationUserId:W.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),operationUserName:W.string().optional().describe("协助操作人姓名"),staffName:W.string().optional().describe("当前员工真实姓名"),cellphone:W.string().optional().describe("绑定手机号"),isAdmin:W.boolean().optional().describe("是否管理员"),deviceType:W.string().optional().describe("设备类型"),loginAccountType:W.string().optional().describe("登录账号类型"),loginTime:W.number().optional().describe("登录时间戳 (ms)"),expTime:W.number().optional().describe("过期时间戳 (ms)"),sourceChannel:W.string().optional().describe("来源渠道 (如 APP, WEB)")}),mW=W.object({id:W.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),name:W.string().describe("企业名称"),corpId:W.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),userId:W.string().optional().describe("所属用户 ID"),staffId:W.string().optional().describe("员工工号 (默认取 credentials.staffId)"),staffName:W.string().optional().describe("员工真实姓名"),baseUrl:W.string().url().optional().default("https://app.ekuaibao.com"),source:WV.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),accountId:W.string().optional().describe("所属主账号标识(如手机号)"),credentials:JV,auth:XV.optional(),session:OV.optional().describe("官方服务端 Session 与操作人元数据")}),oW=W.object({stateful:W.boolean().default(!0).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),defaultCorpId:W.string().optional().describe("默认工作企业 ID"),defaultAccountId:W.string().optional().describe("默认主账号")});var v6="enterprises",dW="HOSE_ENTERPRISES_DIR",vQ="HOSE_USER_ENTERPRISES_DIR",uQ="HOSE_CONFIG_FILE",pW=zv($0(),".config","hose-use","enterprises"),bQ=zv($0(),".cache","ekb-mcp","enterprises");var sb=zv($0(),".config","hose-use","config.json"),$Q=zv($0(),".cache","ekb-mcp","config.json");function IQ($){jV($,{recursive:!0})}function aW(){let $=process.env[dW]?.trim();if($)return pi($)?[$]:[];let i=process.env[vQ]?.trim();if(i)return[v6,i].filter((n)=>pi(n));let v=[v6,pW,bQ],u=[];for(let n of v)if(pi(n)&&!u.includes(n))u.push(n);return u}function eW(){let $=process.env[dW]?.trim();if($)return $;let i=process.env[vQ]?.trim();if(i)return i;if(pi(v6))return v6;return pW}function i0(){return[`${dW}=<path>`,v6,pW,bQ]}function n0(){let $=process.env[uQ]?.trim();if($)return $;if(pi(sb))return sb;if(pi($Q))return $Q;return sb}function Qn(){let $=n0();try{if(pi($)){let i=iQ($,"utf-8");return oW.parse(JSON.parse(i))}}catch{}return{stateful:!0,defaultCorpId:void 0,defaultAccountId:void 0}}function u6($){let i=Qn(),v=oW.parse({...i,...$}),n=process.env[uQ]?.trim()||sb;return IQ(GV(n)),nQ(n,JSON.stringify(v,null,2),"utf-8"),v}f
Line truncated
|
||||
`+"如需设置默认企业,可执行 `hose config mode stateful` 切换为有状态模式。");let I=$[0];if(I)return I;let U=v?.length?` (已检索路径: ${v.join(", ")})`:"";throw Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${U}。`)}class b6{current=null;corps=new Map;stateful=!0;defaultCorpId;constructor($=[],i={}){this.stateful=i.stateful??!0,this.defaultCorpId=i.defaultCorpId,this.reload($)}reload($){this.corps.clear();for(let i of $)this.corps.set(i.id,i);if(!this.stateful){this.current=null;return}if(this.defaultCorpId&&this.corps.has(this.defaultCorpId))this.current=this.corps.get(this.defaultCorpId);else if(this.corps.size>0)this.current=Array.from(this.corps.values())[0];else this.current=null}isStateful(){return this.stateful}setStateful($){if(this.stateful=$,!$)this.current=null;else if(!this.current&&this.corps.size>0)this.current=Array.from(this.corps.values())[0]}getCurrent(){return this.current}getCorp($){return this.corps.get($)}resolve($,i){return QV(Array.from(this.corps.values()),{stateful:this.stateful,defaultCorpId:this.defaultCorpId,corpId:$},i)}upsertCorp($,i=!1){if(this.corps.set($.id,$),this.stateful&&(i||!this.current))this.current=$,this.defaultCorpId=$.id}switchCorp($,i=!0){let v=this.corps.get($);if(!v)return!1;if(this.current=v,this.defaultCorpId=v.id,i&&this.stateful)u6({defaultCorpId:v.id});return!0}listCorps(){return Array.from(this.corps.values()).map(($)=>({id:$.id,name:$.name,source:$.source||"manual",accountId:$.accountId,staffId:$.credentials.staffId,baseUrl:$.baseUrl,current:$.id===this.current?.id,expiresAt:$.auth?.expiresAt||$.session?.expTime}))}}class Fi extends Error{name="KyError";get isKyError(){return!0}}class I6 extends Fi{name="HTTPError";response;request;options;data;constructor($,i,v){let u=$.status||$.status===0?$.status:"",n=$.statusText??"",b=`${u} ${n}`.trim(),I=b?`status code ${b}`:"an unknown error";super(`Request failed with ${I}: ${i.method} ${i.url}`);this.response=$,this.request=i,this.options=v}}class U6 extends Fi{name="NetworkError";request;constructor($,i){super(`Request failed due to a network error: ${$.method} ${$.url}`,i);this.request=$}}class D6 extends Error{name="NonError";value;constructor($){let i="Non-error value was thrown";try{if(typeof $==="string")i=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")i=$.message}catch{}super(i);this.value=$}}class Fv extends Fi{name="ForceRetryError";customDelay;code;customRequest;constructor($){let i=$?.cause?$.cause instanceof Error?$.cause:new D6($.cause):void 0;super($?.code?`Forced retry: ${$.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class sW extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class Ui extends Fi{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var $J=(()=>{let $=!1,i=!1,v=typeof globalThis.ReadableStream==="function",u=typeof globalThis.Request==="function";if(v&&u)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return $&&!i})(),DQ=typeof globalThis.AbortController==="function",v0=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",wQ=typeof globalThis.ReadableStream==="function",gQ=typeof globalThis.FormData==="function",u0=["get","post","put","patch","head","delete"],YV=()=>{return};YV();var WQ={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Bv=2147483647,JQ=40,b0=Symbol("stop");class I0{options;constructor($){this.options=$}}var XQ=($)=>new I0($),OQ={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},jQ={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var U0=new TextEncoder,NV=($)=>{if(!$)return 0;if($ instanceof FormData){let i=0;for(let[v,u]of $)i+=JQ,i+=U0.encode(`Content-Disposition: form-data; name="${v}"`).byteLength,i+=typeof u==="string"?U0.encode(u).byteLength:u.size;return i}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return U0.encode($).byteLength;if($ instanceof URLSearchParams)return U0.encode($.toString()).byteLength;return 0},AQ=($,i,v)=>{let u,n=0;return $.pipeThrough(new TransformStream({transform(b,I){if(I.enqueue(b),u){n+=u.byteLength;let U=i===0?0:n/i;if(U>=1)U=1-Number.EPSILON;v?.({percent:U,totalBytes:Math.max(i,n),transf
Line truncated
|
||||
${i}
|
||||
-----END PUBLIC KEY-----`;return EQ.publicEncrypt({key:v,padding:EQ.constants.RSA_PKCS1_PADDING},Buffer.from($)).toString("base64")}function A6($,i="86"){let v=$.trim();if(v.includes("-"))return v;return`${i}-${v}`}async function sV($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u=$.deviceType||"desktop",n=await aV(i),b=eV($.password,n),I=await Q$.post(`${i}/cloud-auth/public/auth/login-by-password`,{json:{deviceType:u,username:A6($.phone,v),password:b}}).json();if(!I.data)throw new g$(I.errorMessage||"账号或密码错误");return{cloudAuthToken:I.data}}async function RQ($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u={bizType:"LOGIN",account:A6($.phone,v),channelType:"SMS",...$.captchaParams},n=await Q$.post(`${i}/cloud-auth/public/auth/send-verification-code`,{json:u}).json();if(n.errorCode)throw new g$(n.errorMessage||"发送验证码失败");return{codeId:n.data?.codeId}}async function $q($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u=$.deviceType||"desktop",n=await Q$.post(`${i}/cloud-auth/public/auth/login-by-code`,{json:{username:A6($.phone,v),code:$.code.trim(),codeId:$.codeId,deviceType:u}}).json();if(!n.data)throw new g$(n.errorMessage||"验证码错误或已过期");return{cloudAuthToken:n.data}}async function iq($={}){let i=$.webbridgeUrl||dV;try{let u=(await Q$.post(`${i}/command`,{json:{action:"evaluate",args:{code:`(() => {
|
||||
const sessionStr = localStorage.getItem("session");
|
||||
const cloudAuthToken = localStorage.getItem("cloudAuthToken");
|
||||
let sessionObj = null;
|
||||
try { sessionObj = JSON.parse(sessionStr || "{}"); } catch {}
|
||||
return {
|
||||
cloudAuthToken,
|
||||
accessToken: sessionObj?.user?.accessToken || localStorage.getItem("accessToken"),
|
||||
corpId: sessionObj?.user?.corpId || localStorage.getItem("corpId"),
|
||||
staffId: sessionObj?.user?.staffId || sessionObj?.staff?.id || localStorage.getItem("staffId"),
|
||||
};
|
||||
})()`},session:"ekb-sync-auth"}}).json()).data?.value;if(!u||!u.cloudAuthToken&&!u.accessToken)throw new g$("未能从当前浏览器会话中获取到合思登录凭证,请确保网页已登录");return{cloudAuthToken:u.cloudAuthToken,activeSession:u.accessToken&&u.corpId?{accessToken:u.accessToken,corpId:u.corpId,staffId:u.staffId}:void 0}}catch(v){if(v instanceof g$)throw v;throw new g$(`连接浏览器 WebBridge 失败: ${v instanceof Error?v.message:String(v)}`)}}function CQ($){let i={};if(!$)return i;let v=/(?:-H|--header)\s+['"]([^'"]+)['"]/gi,u;while((u=v.exec($))!==null){let b=u[1],I=b.indexOf(":");if(I!==-1){let U=b.slice(0,I).trim().toLowerCase().replace(/[^a-z]/g,""),D=b.slice(I+1).trim();if(U==="accesstoken")i.accessToken=D;if(U==="corpid"||U==="corporationid")i.corpId=D;if(U==="staffid")i.staffId=D}}let n=$.split(`
|
||||
`);for(let b of n){let I=b.trim(),U=I.indexOf(":");if(U!==-1){let D=I.slice(0,U).trim().toLowerCase().replace(/[^a-z]/g,""),w=I.slice(U+1).trim().replace(/^['"]|['"]$/g,"");if(D==="accesstoken"&&!i.accessToken)i.accessToken=w;if((D==="corpid"||D==="corporationid")&&!i.corpId)i.corpId=w;if(D==="staffid"&&!i.staffId)i.staffId=w}}if(!i.corpId){let b=/(?:[?&]corpId=)([^&'"\s]+)/i.exec($);if(b)i.corpId=decodeURIComponent(b[1])}if(!i.accessToken){let b=/ekb-access-token=([^;'"\s]+)/i.exec($);if(b)i.accessToken=decodeURIComponent(b[1])}if(!i.corpId){let b=/(?:^|;\s*)corpId=([^;'"\s]+)/i.exec($);if(b)i.corpId=decodeURIComponent(b[1])}return i}async function _Q($){let{accessToken:i,corpId:v,staffId:u}=$,n=$.baseUrl||pV;if(!i||!v||!u)throw new g$("导入凭证失败:accessToken、corpId、staffId 均为必填项");let b;try{if(b=(await Q$.get(`${n}/api/account/v2/session`,{headers:{accesstoken:i,corpid:v,staffid:u}}).json()).value,!b||!b.corporationId&&!b.id&&!b.userId)throw Error("服务端未返回有效 Session")}catch(G){throw new g$(`凭证校验失败,请检查 token 是否已过期: ${G instanceof Error?G.message:String(G)}`)}let I=$.name,U=b?.privilege,D,w,g,J;try{let G=await Q$.get(`${n}/api/engine/realm/$UNITY/actions/jwt`,{searchParams:{corpId:v},headers:{accesstoken:i,corpid:v,staffid:u}}).json(),N=G.id||G.value;if(N){let L=N.split(".");if(L.length>=2){let B=JSON.parse(Buffer.from(L[1],"base64").toString("utf-8"));if(!I&&B.corporationName)I=B.corporationName;if(B.staffName)U=B.staffName;if(B.cellphone)D=B.cellphone;if(B.isAdmin!==void 0)w=B.isAdmin==="true"||B.isAdmin===!0;if(B.exp)J=Number(B.exp)*1000}}}catch{}let X="curl";if(b?.isAssistPlatform||b?.platform==="ASSIST")X="assist";let O;if(b?.expTime&&b.expTime>0)O=b.expTime;else if(J&&J>0)O=J;else if(b?.isAssistPlatform&&b?.loginTime)O=b.loginTime+7200000;let j={id:v,name:I||`企业-${v}`,baseUrl:n,source:X,staffName:U,credentials:{accessToken:i,corpId:v,staffId:u},auth:{refreshTtl:300,expiresAt:O},session:{platform:b?.platform,isAssistPlatform:b?.isAssistPlatform,isShortTermToken:b?.isShortTermToken,assistId:b?.assistId,operationUserId:b?.operationUserId,operationUserName:b?.operationUserName,staffName:U,cellphone:D,isAdmin:w,deviceType:b?.deviceType,loginAccountType:b?.loginAccountType,loginTime:b?.loginTime,expTime:O||b?.expTime,sourceChannel:g}};return Pv(j,$.enterprisesDir),j}async function nq($,i=Yn){let v=await Q$.get(`${i}/cloud-auth/public/auth/list-corporations`,{headers:{"cloud-auth-token":$}}).json();if(!v.data?.items)throw new g$(v.errorMessage||"获取企业列表失败");return[...v.data.items||[],...v.data.externalItems||[]].map((n)=>lQ.parse(n))}async function JJ($,i,v,u=tQ,n=Yn){let b=await Q$.post(`${n}/cloud-auth/public/auth/switch-corporation`,{headers:{"cloud-auth-token":$},json:{corporationId:i.corporationId,userId:i.userId,cluster:i.cluster}}).json(),I=b.data?.accessToken;if(!I)throw new g$(b.errorMessage||`切换到企业 ${i.corporationName} 失败`);let U=await Q$.post(`${u}/api/idp/public/oauth2/token`,{json:{clientId:i.clientId||"whispered-app",grantType:"authorization_code",code:I,withIdToken:!1}}).json();if(!U.access_token)throw new g$(`换取企业 ${i.corporationName} 访问令牌失败`);let D={id:i.corporationId,name:i.corporationName,corpId:i.corporationId,userId:i.userId,staffId:i.staffId,baseUrl:i.baseUrl||"https://app.ekuaibao.com",source:"account",accountId:v,credentials:{accessToken:U.access_token,corpId:i.corporationId,staffId:i.staffId},auth:{refreshTtl:300,refreshToken:U.refresh_token,expiresAt:Date.now()+U.expires_in*1000}};return{accessToken:U.access_token,refreshToken:U.refresh_token,expiresIn:U.expires_in,corpConfig:D}}async function XJ($,i=Yn,v=tQ){let u=$.accountId?WJ($.accountId):Vv();if(!u?.cloudAuthToken)return!1;try{let n={corporationId:$.corpId||$.credentials.corpId,corporationName:$.name,cluster:"app",clientId:"whispered-app",staffId:$.staffId||$.credentials.staffId,userId:$.userId||u.userId||"",baseUrl:$.baseUrl||"https://app.ekuaibao.com",external:!1,needAuth:!1},b=await JJ(u.cloudAuthToken,n,$.accountId,v,i);if($.credentials.accessToken=b.accessToken,!$.auth)$.auth={refreshTtl:300};return $.auth.refreshToken=b.refreshToken,$.auth.expiresAt=Date.now()+b.expiresIn*1000,Pv($),!0}catch(n){return console.warn(`[auth] 自动续杯刷新企业 ${$.name} 失败:`,n instanceof Error?n.message:String(n)),!1}}async function rQ($){let{cloudAuthToken:i}=await sV($),v=A6($.phone,$.areaCode);return g0(v,i,$)}async function fQ($){let{cloudAuthToken:i}=await $q($),v=A6($.phone,$.areaCode);return g0(v,i,$)}async function xQ($={}){let{cloudAuthToken:i,activeSession:v}=await iq($);if(i)return g0("browser_session",i,$);if(v){let u={id:v.corpId,name:"当前浏览器企业",baseUrl:"https://app.ekuaibao.com",source:"browser",credentials:{accessToken:v.accessToken,corpId:v.corpId,staffId:v.staffId||`${v.corpId}:admin`}};return Pv(u,$.enterprisesDir),{selectedCorp:u,allCorps:[u],cloudAuthToken:"",accountId:"browser_
Line truncated
|
||||
`)}function Y$($,i){if(i.length===0)return` (暂无数据)
|
||||
`;let v=i.map((U)=>U.map((D)=>String(D??""))),u=$.map((U,D)=>{let w=Math.max(...v.map((g)=>(g[D]||"").length),0);return Math.max(U.length,w)}),n=$.map((U,D)=>U.padEnd(u[D])).join(" "),b=u.map((U)=>"-".repeat(U)).join(" "),I=v.map((U)=>U.map((D,w)=>D.padEnd(u[w])).join(" "));return[n,b,...I].map((U)=>` ${U}`).join(`
|
||||
`)}function KJ(){return`
|
||||
合思/易快报企业级 CLI 工具 (hose-use) v${E}
|
||||
|
||||
用法:
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema, link <单号|ID>)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
platform 自建应用管理 (list)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog)
|
||||
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs)
|
||||
mcp MCP Server 运行 (serve)
|
||||
version 查看版本信息
|
||||
|
||||
全局选项:
|
||||
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
||||
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
||||
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
|
||||
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看当前登录状态与活跃企业
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use corps list # 列出名下所有企业
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
|
||||
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
|
||||
hose-use service start # 后台启动常驻守护进程服务
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
hose-use update --changelog # 查看版本发布历史
|
||||
hose-use openapi paths # 查看所有 API 路径与概要一览
|
||||
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
|
||||
`.trim()}import rq from"readline";function XY($={}){let i=Hv(),v=Qn(),u=$.stateless?!1:$.stateful?!0:v.stateful,n=new b6(i,{stateful:u,defaultCorpId:v.defaultCorpId}),b=null;try{b=n.resolve($.corpId,i0())}catch{b=null}return{corpContext:n,selectedCorp:b,jsonMode:$.jsonMode??!1,outputOptions:$.outputOptions,appRoot:$.appRoot,entryFile:$.entryFile,launcher:$.launcher}}async function Bi($){let i=await x$($),{client:v}=await ei($);return{corp:$,ekbClient:i,easoClient:v}}function Si($){let i=rq.createInterface({input:process.stdin,output:process.stdout});return new Promise((v)=>{i.question($,(u)=>{i.close(),v(u.trim())})})}async function OY($,i){let v=$.action||"status";switch(v){case"login":return fq($,i);case"status":case"whoami":return xq($,i);case"refresh":return yq($,i);case"import":return cq($,i);case"accounts":return hq($,i);case"switch-account":return mq($,i);default:return{stdout:"",stderr:`未知 auth 子命令: ${v}。支持: login, status, refresh, import, accounts, switch-account
|
||||
`,exitCode:1}}}async function fq($,i){let v=m($.options,["phone","p"]),u=m($.options,["password","pwd"]),n=W$($.options,["sms"]),b=W$($.options,["sync"]),I=W$($.options,["interactive","i"])||!v&&!u&&!n&&!b;if(b){let X=await xQ({saveAll:!0});if(i.jsonMode)return{stdout:l(X),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 成功从浏览器会话同步企业凭证!
|
||||
默认企业: ${X.selectedCorp.name} (${X.selectedCorp.id})
|
||||
共保存企业: ${X.allCorps.length} 家
|
||||
`,stderr:"",exitCode:0}}if(n){let X=v||await Si("请输入手机号: ");if(!X)return{stdout:"",stderr:`手机号不能为空
|
||||
`,exitCode:1};let O;try{O=(await RQ({phone:X})).codeId,console.log("短信验证码已发送!")}catch(N){console.log("若触发了人机验证,请在浏览器中获取验证码后直接在下方输入。")}let j=await Si("请输入收到的 6 位短信验证码: ");if(!j)return{stdout:"",stderr:`验证码不能为空
|
||||
`,exitCode:1};let G=await fQ({phone:X,code:j,codeId:O,saveAll:!0});if(i.jsonMode)return{stdout:l(G),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 短信验证码登录成功!
|
||||
账号: ${G.accountId}
|
||||
默认企业: ${G.selectedCorp.name} (${G.selectedCorp.id})
|
||||
共保存企业: ${G.allCorps.length} 家
|
||||
`,stderr:"",exitCode:0}}let U=v||(I?await Si("请输入手机号: "):""),D=u||(I?await Si("请输入密码: "):"");if(!U||!D)return{stdout:"",stderr:`手机号和密码不能为空
|
||||
`,exitCode:1};let w=await rQ({phone:U,password:D,saveAll:!0});if(i.jsonMode)return{stdout:l(w),stderr:"",exitCode:0};let g=w.allCorps.map((X,O)=>[O+1,X.id,X.name,X.credentials.staffId]),J=Y$(["#","企业 ID","企业名称","员工工号"],g);return{stdout:`[SUCCESS] 账密登录成功!
|
||||
账号: ${w.accountId}
|
||||
默认企业: ${w.selectedCorp.name} (${w.selectedCorp.id})
|
||||
共保存企业配置: ${w.allCorps.length} 家
|
||||
|
||||
${J}
|
||||
`,stderr:"",exitCode:0}}async function xq($,i){let v=i.selectedCorp,u=Vv(),n=!1,b=null;if(v)try{let g=await(await x$(v)).get("api/account/v2/session").json();n=!!g.value,b=g.value}catch{n=!1}let I={activeAccount:u?.accountId||null,currentCorp:v?{id:v.id,name:v.name,staffId:v.credentials.staffId,source:v.source,accountId:v.accountId,tokenValid:n}:null,session:b};if(i.jsonMode)return{stdout:l(I),stderr:"",exitCode:0};let U={"当前活跃账号":u?.accountId||"未登录","当前激活企业":v?`${v.name} (${v.id})`:"未配置","当前员工工号":v?.credentials.staffId||"-","员工真实姓名":v?.staffName||v?.session?.staffName||"-","凭证来源类型":Nn(v?.source),"Token 有效性":n?"✅ 有效 (已通过 Session 验证)":"❌ 无效或未连接","Token 过期时间":si(v?.auth?.expiresAt||v?.session?.expTime)};if(v?.session){if(v.session.loginTime)U["会话创建时间"]=new Date(v.session.loginTime).toLocaleString("zh-CN",{hour12:!1});if(v.session.platform)U["官方平台类型"]=v.session.platform;if(v.session.isAssistPlatform){if(U["协助调试模式"]="是 (Assist Platform)",v.session.operationUserName||v.session.operationUserId)U["协助操作人员"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim();if(v.session.assistId)U["协助会话 ID"]=v.session.assistId}if(v.session.cellphone)U["绑定手机号码"]=v.session.cellphone;if(v.session.isAdmin!==void 0)U["是否企业管理"]=v.session.isAdmin?"是":"否"}return{stdout:`====== 当前登录与企业状态 ======
|
||||
${J$(U)}
|
||||
`,stderr:"",exitCode:0}}async function yq($,i){let v=m($.options,["account","a"]),u=await yQ(v,{saveAll:!0});if(i.jsonMode)return{stdout:l(u),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 成功批量刷新账号 ${u.accountId} 下的所有企业 AccessToken!
|
||||
共刷新企业: ${u.allCorps.length} 家
|
||||
`,stderr:"",exitCode:0}}async function cq($,i){let v=m($.options,["raw","headers","curl"]),u=m($.options,["token","accessToken"]),n=m($.options,["corp","corpId"]),b=m($.options,["staff","staffId"]),I=m($.options,["name"]);if(!v&&!u)v=await Si("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");if(v){let g=CQ(v);if(g.accessToken)u=g.accessToken;if(g.corpId)n=g.corpId;if(g.staffId)b=g.staffId}if(!u)u=await Si("请输入 accessToken: ");if(!n)n=await Si("请输入 corpId: ");if(!b)b=await Si("请输入 staffId: ");if(!u||!n||!b)return{stdout:"",stderr:`accessToken, corpId, staffId 均为必填!
|
||||
`,exitCode:1};let U=await _Q({accessToken:u,corpId:n,staffId:b,name:I});if(i.jsonMode)return{stdout:l(U),stderr:"",exitCode:0};let D={"企业名称":U.name,"企业 ID":U.id,"员工工号":U.credentials.staffId,"员工姓名":U.staffName||U.session?.staffName||"-","凭证来源":Nn(U.source),"过期时间":si(U.auth?.expiresAt||U.session?.expTime),"保存路径":`enterprises/${U.id}.json`};if(U.session?.isAssistPlatform){if(D["协助平台"]="是 (Assist Platform 调试授权)",U.session.operationUserName||U.session.operationUserId)D["协助操作人"]=`${U.session.operationUserName||""} (${U.session.operationUserId||""})`.trim();if(U.session.assistId)D["协助会话 ID"]=U.session.assistId}return{stdout:`[SUCCESS] 成功导入并保存企业凭证!
|
||||
${J$(D)}
|
||||
`,stderr:"",exitCode:0}}async function hq($,i){let v=kQ(),u=Vv();if(i.jsonMode)return{stdout:l({activeAccountId:u?.accountId,accounts:v}),stderr:"",exitCode:0};if(v.length===0)return{stdout:`暂无保存的账号,请使用 hose auth login 登录
|
||||
`,stderr:"",exitCode:0};let n=v.map((I,U)=>[I.accountId===u?.accountId?`* ${U+1}`:` ${U+1}`,I.accountId,I.userId||"-",I.corporations.length,new Date(I.updatedAt).toLocaleString()]);return{stdout:`====== 本地已保存账号列表 ======
|
||||
${Y$(["#","账号标识","用户 ID","关联企业数","最近更新时间"],n)}
|
||||
`,stderr:"",exitCode:0}}async function mq($,i){let v=$.args[0]||m($.options,["account","a"]);if(!v)return{stdout:"",stderr:`用法: hose auth switch-account <accountId>
|
||||
`,exitCode:1};if(!TQ(v))return{stdout:"",stderr:`未找到账号: ${v}
|
||||
`,exitCode:1};return{stdout:`[SUCCESS] 当前活跃主账号已切换至: ${v}
|
||||
`,stderr:"",exitCode:0}}async function jY($,i){let v=$.action||"list";switch(v){case"list":return oq($,i);case"switch":case"use":return dq($,i);case"current":return pq($,i);default:return{stdout:"",stderr:`未知 corps 子命令: ${v}。支持: list, switch, current
|
||||
`,exitCode:1}}}async function oq($,i){let v=i.corpContext.listCorps();if(i.jsonMode)return{stdout:l({activeCorpId:i.selectedCorp?.id,corporations:v},i.outputOptions),stderr:"",exitCode:0};if(v.length===0)return{stdout:`未找到任何企业配置,请先运行 hose auth login
|
||||
`,stderr:"",exitCode:0};let u=v.map((b,I)=>[b.current?`* ${I+1}`:` ${I+1}`,b.id,b.name,b.staffId,b.source||"manual",si(b.expiresAt),b.accountId||"-"]),n=Y$(["#","企业 ID","企业名称","员工工号","来源","Token 过期时间","所属账号"],u);return{stdout:`====== 已配置企业列表 (${v.length} 家) ======
|
||||
${n}
|
||||
|
||||
提示: 使用 hose corps switch <企业ID> 切换工作企业
|
||||
`,stderr:"",exitCode:0}}async function dq($,i){let v=$.args[0];if(!v)return{stdout:"",stderr:`用法: hose corps switch <企业ID>
|
||||
`,exitCode:1};if(!i.corpContext.switchCorp(v))return{stdout:"",stderr:`企业 ${v} 不存在或未配置。可运行 hose corps list 查看可用列表。
|
||||
`,exitCode:1};let n=i.corpContext.getCurrent();if(i.jsonMode)return{stdout:l(n,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 已切换到企业: ${n?.name} (${n?.id})
|
||||
`,stderr:"",exitCode:0}}async function pq($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:`未选中任何企业
|
||||
`,exitCode:1};if(i.jsonMode)return{stdout:l(v,i.outputOptions),stderr:"",exitCode:0};let u={"企业 ID":v.id,"企业名称":v.name,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Nn(v.source),"Token 过期时间":si(v.auth?.expiresAt||v.session?.expTime),"所属账号":v.accountId||"-","主站地址":v.baseUrl||"https://app.ekuaibao.com"};if(v.session){if(v.session.loginTime)u["会话创建时间"]=new Date(v.session.loginTime).toLocaleString("zh-CN",{hour12:!1});if(v.session.platform)u["官方平台类型"]=v.session.platform;if(v.session.isAssistPlatform){if(u["协助登录模式"]="是 (Assist Platform)",v.session.operationUserName||v.session.operationUserId)u["协助操作人员"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim();if(v.session.assistId)u["协助会话 ID"]=v.session.assistId}if(v.session.cellphone)u["绑定手机号码"]=v.session.cellphone;if(v.session.isAdmin!==void 0)u["是否企业管理"]=v.session.isAdmin?"是":"否"}return{stdout:`====== 当前激活企业 ======
|
||||
${J$(u)}
|
||||
`,stderr:"",exitCode:0}}async function AY($,i){let v=$.action||"show";switch(v){case"show":case"get":case"list":return aq($,i);case"paths":case"path":case"dirs":return $M($,i);case"mode":return eq($,i);case"set":return sq($,i);default:return{stdout:"",stderr:`未知 config 子命令: ${v}。支持: show, paths, mode <stateful|stateless>, set <key> <val>
|
||||
`,exitCode:1}}}async function aq($,i){let v=Qn(),u=i.selectedCorp,n=n0(),b={mode:v.stateful?"stateful":"stateless",stateful:v.stateful,defaultCorpId:v.defaultCorpId||null,defaultAccountId:v.defaultAccountId||null,activeCorp:u?{id:u.id,name:u.name}:null,configFile:n};if(i.jsonMode)return{stdout:l(b),stderr:"",exitCode:0};return{stdout:`====== 全局运行配置 ======
|
||||
${J$({"运行模式 (Mode)":v.stateful?"有状态模式 (Stateful - 自动记忆默认企业)":"无状态模式 (Stateless - 每次需显式传 --corp)","默认工作企业":v.defaultCorpId||"未设置 (使用首个可用企业)","当前解析企业":u?`${u.name} (${u.id})`:"无","配置文件路径":n})}
|
||||
|
||||
提示:
|
||||
切换模式: hose config mode <stateful|stateless>
|
||||
指定企业: hose corps switch <corpId>
|
||||
`,stderr:"",exitCode:0}}async function eq($,i){let v=$.args[0]?.toLowerCase();if(!v||v!=="stateful"&&v!=="stateless")return{stdout:"",stderr:`用法: hose config mode <stateful|stateless>
|
||||
`,exitCode:1};let u=v==="stateful",n=u6({stateful:u});if(i.jsonMode)return{stdout:l(n),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 全局运行模式已切换为: ${u?"有状态模式 (Stateful)":"无状态模式 (Stateless)"}
|
||||
`,stderr:"",exitCode:0}}async function sq($,i){let v=$.args[0],u=$.args[1];if(!v||u===void 0)return{stdout:"",stderr:`用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)
|
||||
`,exitCode:1};let n={};if(v==="stateful")n.stateful=u==="true"||u==="1";else if(v==="defaultCorpId")n.defaultCorpId=u;else if(v==="defaultAccountId")n.defaultAccountId=u;else return{stdout:"",stderr:`不支持配置键: ${v}。支持: stateful, defaultCorpId, defaultAccountId
|
||||
`,exitCode:1};let b=u6(n);if(i.jsonMode)return{stdout:l(b),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 配置已更新: ${v} = ${u}
|
||||
`,stderr:"",exitCode:0}}async function $M($,i){let v=process.env.HOSE_ENTERPRISES_DIR,u=process.env.HOSE_USER_ENTERPRISES_DIR,n=process.env.HOSE_CONFIG_FILE,b=aW(),I=eW(),U=n0(),D=i0(),w={configFile:U,writableDir:I,existingDirs:b,env:{HOSE_ENTERPRISES_DIR:v||null,HOSE_USER_ENTERPRISES_DIR:u||null,HOSE_CONFIG_FILE:n||null},candidates:D};if(i.jsonMode)return{stdout:l(w),stderr:"",exitCode:0};return{stdout:`====== 配置路径诊断 (Config Paths) ======
|
||||
${J$({"当前生效配置文件":U,"凭证保存写入目录":I,"已发现企业目录":b.length?b.join(`
|
||||
`):"无 (未发现任何有效企业目录)","环境变量指定目录":v||"未设置 (HOSE_ENTERPRISES_DIR)","全部目录候选链":D.join(`
|
||||
`)})}
|
||||
`,stderr:"",exitCode:0}}async function GY($,i){if(!i.selectedCorp)return{stdout:"",stderr:`未选中企业,请先通过 hose corps switch 或 --corp 指定企业
|
||||
`,exitCode:1};let u=$.action||"list";switch(u){case"list":case"list-all":case"ls":return iM($,i);case"get":case"detail":case"info":return nM($,i);case"find":case"search":return vM($,i);case"toggle":return uM($,i);default:return{stdout:"",stderr:`未知 workflow 子命令: ${u}。支持: list, get, find, toggle
|
||||
`,exitCode:1}}}async function iM($,i){let v=await Bi(i.selectedCorp),u=l$($.options,["page"])||1,n=l$($.options,["pageSize","size"])||50,b=await Q6(v,{page:u,pageSize:n});if(i.jsonMode)return{stdout:l(b,i.outputOptions),stderr:"",exitCode:0};if(b.workflows.length===0)return{stdout:`企业 [${i.selectedCorp.name}] 下暂无工作流
|
||||
`,stderr:"",exitCode:0};let I=b.workflows.map((D,w)=>[w+1,D.id,D.pipelineName,D.platformName||D.platformId||"-",D.state===1?"\uD83D\uDFE2 启用":"⚪ 停用",D.tasks?.length??"-"]),U=Y$(["#","工作流 ID","工作流名称","所属自建应用","状态","节点数"],I);return{stdout:`====== [${i.selectedCorp.name}] 工作流列表 (共 ${b.workflows.length} 条) ======
|
||||
${U}
|
||||
`,stderr:"",exitCode:0}}async function nM($,i){let v=$.args[0]||m($.options,["id","pipelineId"]);if(!v)return{stdout:"",stderr:`用法: hose workflow get <pipelineId>
|
||||
`,exitCode:1};let u=await Bi(i.selectedCorp),n=await Mv(u.easoClient,v);if(i.jsonMode)return{stdout:l(n,i.outputOptions),stderr:"",exitCode:0};let b=J$({"工作流 ID":n.id,"工作流名称":n.label,"状态":n.state===1?"\uD83D\uDFE2 启用":"⚪ 停用","版本号":n.version||"-","节点总数":n.tasks?.length??0}),I="";if(n.tasks&&n.tasks.length>0){let U=n.tasks.map((D,w)=>[w+1,D.name||"-",D.label||"-",D.type,D.groupName||"-"]);I=`
|
||||
节点结构:
|
||||
`+Y$(["#","节点标识","节点名称","类型","分组"],U)}return{stdout:`====== 工作流详情 ======
|
||||
${b}
|
||||
${I}
|
||||
`,stderr:"",exitCode:0}}async function vM($,i){let v=m($.options,["task","taskType","type"])||$.args[0];if(!v)return{stdout:"",stderr:`用法: hose workflow find --task=<节点类型> (如 code-js2, http, condition)
|
||||
`,exitCode:1};let u=await Bi(i.selectedCorp),n=W$($.options,["includeDetail","detail"]),b=l$($.options,["page"])||1,I=l$($.options,["pageSize","size"])||50,U=await iY(u,v,{page:b,pageSize:I,includeDetail:n});if(i.jsonMode)return{stdout:l(U,i.outputOptions),stderr:"",exitCode:0};if(U.workflows.length===0)return{stdout:`未找到包含节点类型 [${v}] 的工作流
|
||||
`,stderr:"",exitCode:0};let D=U.workflows.map((g,J)=>[J+1,g.id,g.pipelineName,g.platformName||g.platformId||"-",g.state===1?"\uD83D\uDFE2 启用":"⚪ 停用"]),w=Y$(["#","工作流 ID","工作流名称","所属自建应用","状态"],D);return{stdout:`====== 匹配节点类型 [${v}] 的工作流 (共 ${U.workflows.length} 条) ======
|
||||
${w}
|
||||
`,stderr:"",exitCode:0}}async function uM($,i){let v=$.args[0]||m($.options,["id","pipelineId"]),u=m($.options,["state","s"]);if(!v||u===void 0)return{stdout:"",stderr:`用法: hose workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)
|
||||
`,exitCode:1};let n=u==="1"||u==="true"?1:0,b=await Bi(i.selectedCorp),I=await sQ(b.easoClient,v,n);if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 工作流 ${v} 状态已更新为: ${n===1?"\uD83D\uDFE2 启用":"⚪ 停用"}
|
||||
`,stderr:"",exitCode:0}}async function QY($,i){if(!i.selectedCorp)return{stdout:"",stderr:`未选中企业,请先通过 hose corps switch 或 --corp 指定企业
|
||||
`,exitCode:1};let u=$.action||"list";switch(u){case"list":case"ls":return bM($,i);default:return{stdout:"",stderr:`未知 platform 子命令: ${u}。支持: list
|
||||
`,exitCode:1}}}async function bM($,i){let v=await Bi(i.selectedCorp),u=await qv(v.ekbClient,i.selectedCorp.credentials.corpId);if(i.jsonMode)return{stdout:l(u,i.outputOptions),stderr:"",exitCode:0};if(u.length===0)return{stdout:`企业 [${i.selectedCorp.name}] 下暂无自建应用
|
||||
`,stderr:"",exitCode:0};let n=u.map((I,U)=>[U+1,I.id,I.name,I.active?"\uD83D\uDFE2 已启用":"⚪ 未启用"]),b=Y$(["#","自建应用 ID","应用名称","状态"],n);return{stdout:`====== [${i.selectedCorp.name}] 自建应用列表 (共 ${u.length} 个) ======
|
||||
${b}
|
||||
`,stderr:"",exitCode:0}}import{existsSync as PJ}from"node:fs";import{join as K6}from"node:path";import{mkdirSync as FY,writeFileSync as XM}from"node:fs";import{homedir as A0}from"node:os";import{dirname as OM,join as N6}from"node:path";var YY=`---
|
||||
name: hose-use
|
||||
description: "v0.5.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据费用检索与下钻、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.5.1
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.5.1)
|
||||
---
|
||||
|
||||
# hose-use (v0.5.2)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 \`hose_cli\` 单工具网关**,传入 \`command: string\` 执行;在终端或自动化脚本中,直接调用全局 \`hose\` 或 \`hose-use\` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(\`references/*.md\`)。
|
||||
|
||||
---
|
||||
|
||||
## Agent 执行原则 (First Rules)
|
||||
|
||||
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 \`hose corps list\`。如果目标企业已配置,通过企业名称映射出对应的 \`id\` 并作为 \`--corp=<id>\` 传入;不要向普通用户询问底层 \`corpId\`。
|
||||
3. **输出防护与大报文处理**:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 \`--json -o <path>\` 本地转储或使用 \`--limit\` 限制分页;
|
||||
- 严禁盲目使用 \`--full\` 将上万行原始报文一次性塞入上下文;
|
||||
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
|
||||
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 \`--stateless\` 或显式指定 \`--corp=<id>\`),避免多任务并发切换全局状态发生冲突。
|
||||
|
||||
---
|
||||
|
||||
## 意图路由导航 (Route By Intent)
|
||||
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | \`hose auth login\`, \`hose auth status\`, \`hose auth refresh\` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | \`hose auth import\`, \`hose probe\` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | \`hose corps list\`, \`hose corps switch <id>\` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | \`hose bill list\`, \`hose bill get <单号|ID>\` | [references/bill.md](references/bill.md) |
|
||||
| 单据 Web 详情直达链接生成 | \`hose bill link <单号|ID>\` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | \`hose bill schema\` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | \`hose contact search\`, \`hose contact list\`, \`hose contact get\` | [references/contact.md](references/contact.md) |
|
||||
| 跨自建应用工作流聚合检索 | \`hose workflow list\`, \`hose platform list\` | [references/workflow.md](references/workflow.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | \`hose workflow find --task=code-js2\` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情与开通切换 | \`hose workflow get\`, \`hose workflow toggle\` | [references/workflow.md](references/workflow.md) |
|
||||
| 常驻守护进程管理 / 后台运行 | \`hose service start\`, \`hose service status\` | [references/service.md](references/service.md) |
|
||||
| 启动本地 HTTP 服务 / 打开可视化交互文档 | \`hose http --port=8888\` (访问 \`/docs\`) | [references/service.md](references/service.md) |
|
||||
| CLI 同进程执行网关 / REST 接口调用 | \`POST /api/cli\`, \`GET /v1/corps\` | [references/service.md](references/service.md) |
|
||||
| 导出标准 OpenAPI 3.1.0 JSON 规范 | \`hose openapi\`, \`hose openapi --raw\` | [references/service.md](references/service.md) |
|
||||
| 一键自动自更新 / 查看版本发布日志 | \`hose update\`, \`hose update --changelog\` | \`hose update --help\` |
|
||||
|
||||
---
|
||||
|
||||
## 常用命令速查
|
||||
|
||||
\`\`\`bash
|
||||
# 1. 认证与企业
|
||||
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
|
||||
hose auth status # 查看 Token 剩余有效期与登录账号
|
||||
hose corps list # 查看企业租户列表
|
||||
hose corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose probe # 诊断当前企业接口连通性
|
||||
|
||||
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
|
||||
hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话
|
||||
hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
|
||||
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
|
||||
|
||||
# 3. 单据与费用
|
||||
hose bill list # 查看最新单据与报销记录
|
||||
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||
hose bill schema # 查询单据实体元数据字典
|
||||
|
||||
# 4. 自建应用与工作流
|
||||
hose platform list # 查看自建应用列表
|
||||
hose workflow list # 聚合扫描全部应用下的工作流
|
||||
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
|
||||
# 5. 服务与守护进程
|
||||
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
hose service start # 后台启动常驻守护进程服务
|
||||
hose service status # 查看常驻守护进程运行状态与端点
|
||||
hose service logs # 查看常驻守护进程日志
|
||||
hose service stop # 停止后台常驻守护进程
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 全局选项
|
||||
|
||||
- \`--corp=<id>\`:临时指定操作的企业 ID(单次覆盖默认企业)
|
||||
- \`--json\`, \`-j\`:以标准 JSON 结构化输出结果
|
||||
- \`--output-file, -o <path>\`:将结果直接安全写入本地文件,仅返回精简摘要
|
||||
- \`--full\`:全量输出大报文(绕过 200KB 体积防爆拦截)
|
||||
- \`--stateless\`:单次命令强制以无状态模式执行
|
||||
- \`--stateful\`:单次命令强制以有状态模式执行
|
||||
- \`--help, -h\`:查看命令帮助与参数说明
|
||||
`;var NY=`schema_version: "v1"
|
||||
name: "hose-use"
|
||||
description: "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业多租户切换、单据明细检索、自建应用工作流管理、内置 HTTP 服务与常驻守护进程。"
|
||||
auth:
|
||||
type: "none"
|
||||
tools:
|
||||
- name: "hose_cli"
|
||||
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
|
||||
parameters:
|
||||
type: "object"
|
||||
properties:
|
||||
command:
|
||||
type: "string"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
|
||||
required:
|
||||
- "command"
|
||||
`;var LY="# 认证、多租户与运行模式指南 (Authentication & Multi-Tenant Guide)\n\n本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。\n\n---\n\n## 1. 账号认证与登录 (`auth`)\n\n`hose-use` 实现了**纯 API 级 RSA 密码加密登录**,无需通过浏览器抓包或人工复制 Cookie。\n\n### 纯 API 账密自动登录\n```bash\n# 自动通过公钥加密密码,登录并拉取名下全部企业凭据写入本地配置\nhose-use auth login --phone=17718556446 --password=YourPassword123\n```\n- **核心逻辑**:向合思主站请求 RSA 公钥,将密码密文提交到 `/api/auth/login`;成功后自动遍历用户关联的企业租户,调用换票接口写入对应的企业配置。\n\n### 查看登录状态与 Token 有效期\n```bash\nhose-use auth status\n```\n- 自动计算并输出自然语言剩余有效期(如 `29天23小时后过期`),清晰展示当前账号与当前企业。\n\n### 30 天无感 Token 刷新\n```bash\nhose-use auth refresh\n```\n- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。\n\n### 代客协助凭证导入\n```bash\nhose-use auth import \\\n --name=\"CSM代客\" \\\n --corp-id=\"Cxa3oOtQi2eS$g\" \\\n --staff-id=\"Cxa3oOtQi2eS$g:2HQbkGx2DgnM00\" \\\n --token=\"1361c470-3d7c-4a3a-a1fb-e946aee5723b\"\n```\n- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。\n\n### 多账号清单\n```bash\nhose-use auth accounts\n```\n- 查看本地已记录的手机号多账号清单及其关联的企业列表。\n\n---\n\n## 2. 企业租户管理 (`corps`)\n\n### 列出所有企业\n```bash\nhose-use corps list\nhose-use corps list --json\n```\n\n### 切换当前活跃企业\n```bash\nhose-use corps switch uzU7pcWfScck00\n```\n- 在有状态(stateful)模式下,此命令将更新全局默认企业 ID。\n\n### 查看当前企业\n```bash\nhose-use corps current\n```\n\n---\n\n## 3. 全局配置与模式管理 (`config`)\n\n### 运行模式(有状态 vs 无状态)\n- **有状态模式 (Stateful,默认)**:\n - 会话状态保存在 `~/.config/hose-use/config.json` 中;\n - 执行 `corps switch` 后,后续命令自动继承当前选中的企业。\n- **无状态模式 (Stateless,推荐给 Agent)**:\n - 不依赖全局状态切换,所有命令通过 `--corp=<id>` 显式指定,防止并发操作相互干扰;\n - 通过环境变量 `HOSE_STATELESS=1` 或单次参数 `--stateless` 开启。\n\n```bash\n# 查看当前配置\nhose-use config show\n\n# 查看多层级配置发现路径诊断\nhose-use config paths\n\n# 切换全局运行模式\nhose-use config mode stateless\nhose-use config mode stateful\n```\n\n### 多层级配置发现顺序\n1. 环境变量 `HOSE_ENTERPRISES_DIR`(最高优先级)\n2. 当前工作区根目录下的 `enterprises/`\n3. 用户主目录配置:`~/.config/hose-use/enterprises/`\n4. 历史兼容缓存:`~/.cache/ekb-mcp/enterprises/`\n\n---\n\n## 4. 连通性探针 (`probe`)\n\n```bash\n# 诊断当前企业的鉴权链路与平台可用性\nhose-use probe\n\n# 诊断指定企业的连通性\nhose-use probe --corp=uzU7pcWfScck00\n```\n- **探针行为**:\n 1. 验证主站 Session 是否有效;\n 2. 测试 EASO 平台 SSO 握手是否成功;\n 3. 输出各环节毫秒级延迟与 HTTP 状态。\n";var KY="# 单据与费用明细指南 (Bill & Expense Guide)\n\n本参考专卷详细说明合思单据检索、费用报销明细下钻、中文标签映射字典以及大报文防爆机制。\n\n---\n\n## 1. 单据列表检索 (`bill list`)\n\n### 基础查询\n```bash\n# 查看当前企业最近的单据与报销列表 (默认表格格式)\nhose-use bill list\n\n# 指定企业查询并以 JSON 输出\nhose-use bill list --corp=uzU7pcWfScck00 --json\n```\n\n### 过滤选项\n- `--type=<type>`:按单据大类过滤(如 `TRAVEL_EXPENSE` 差旅报销、`DAILY_EXPENSE` 日常报销、`BORROW` 借款申请、`LOAN` 借款申请等);\n- `--status=<status>`:按审批状态过滤(如 `APPROVED` 审批完成、`PROCESSING` 审批中、`REJECTED` 已驳回、`DRAFT` 草稿等);\n- `--limit=<number>`:单页数量(默认 20,最大 100);\n- `--page=<number>`:分页页码(默认 1)。\n\n```bash\n# 查询审批通过的差旅报销单\nhose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50\n```\n\n---\n\n## 2. 单据详情精准下钻 (`bill get`)\n\n支持传入**单据编号**(如 `CL20260903001`)或合思全局**单据 ID**(如 `n0GMIM0dkQmKbS`):\n\n```bash\nhose-use bill get n0GMIM0dkQmKbS\nhose-use bill get CL20260903001 --json\n```\n\n### 中文字段智能映射字典\n合思底层原生单据接口通常返回类似 `c0_1`, `d1_4`, `u_fee_amount` 等混淆字段。\n`hose-use` 内置**动态中文 LabeLine truncated
|
||||
|
||||
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
|
||||
|
||||
---
|
||||
|
||||
## 1. 自建应用管理 (\`platform\`)
|
||||
|
||||
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
|
||||
|
||||
\`\`\`bash
|
||||
# 列出当前企业下全部已开通的自建应用
|
||||
hose-use platform list
|
||||
hose-use platform list --json
|
||||
\`\`\`
|
||||
|
||||
**输出关键字段**:
|
||||
- \`appId\`:应用全局唯一标识
|
||||
- \`appName\`:应用中文名称
|
||||
- \`status\`:应用运行状态(ENABLE / DISABLE)
|
||||
- \`createdAt\` / \`updatedAt\`:创建与最后更新时间
|
||||
|
||||
---
|
||||
|
||||
## 2. 跨应用工作流聚合检索 (\`workflow list\`)
|
||||
|
||||
合思官方后台一次只能查看单个自建应用的工作流。\`hose-use\` 实现了跨应用并发聚合扫描:
|
||||
|
||||
\`\`\`bash
|
||||
# 查看所有自建应用下的全部工作流汇总
|
||||
hose-use workflow list
|
||||
|
||||
# 查看指定自建应用下的工作流
|
||||
hose-use workflow list --app-id=app_01j72x...
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 3. 工作流任务节点精准扫描 (\`workflow find\`)
|
||||
|
||||
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
|
||||
|
||||
\`\`\`bash
|
||||
# 搜索包含自定义代码节点 (code-js2) 的所有工作流
|
||||
hose-use workflow find --task=code-js2
|
||||
|
||||
# 搜索包含飞书通知节点的工作流
|
||||
hose-use workflow find --task=feishu-notify
|
||||
|
||||
# 模糊搜索包含关键词的工作流
|
||||
hose-use workflow find --keyword="自动审批"
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 4. 工作流详情查询 (\`workflow get\`)
|
||||
|
||||
获取工作流的完整节点拓扑、参数配置与表达式定义:
|
||||
|
||||
\`\`\`bash
|
||||
hose-use workflow get wf_01k83y...
|
||||
hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 5. 工作流启用与关闭 (\`workflow toggle\`)
|
||||
|
||||
\`\`\`bash
|
||||
# 激活/启用指定工作流
|
||||
hose-use workflow toggle wf_01k83y... --enable
|
||||
|
||||
# 停用指定工作流
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
\`\`\`
|
||||
`;var HY=`# 服务、守护进程与 API 网关指南 (Service & HTTP Gateway Guide)
|
||||
|
||||
本参考专卷详细说明 \`hose-use\` 内置的轻量 HTTP Server、常驻 Service 守护进程、Scalar 交互式文档以及 OpenAPI 规范导出能力。
|
||||
|
||||
---
|
||||
|
||||
## 1. 常驻 Service 守护进程 (\`service\`)
|
||||
|
||||
常驻守护进程允许 \`hose-use\` 在后台全天候运行,支持远程/本地无子进程开销调用 CLI,同时持久化存储 PID 与运行日志。
|
||||
|
||||
### 常用指令
|
||||
\`\`\`bash
|
||||
# 启动常驻后台守护进程 (自动落盘 PID 到 ~/.config/hose-use/service.pid)
|
||||
hose-use service start
|
||||
|
||||
# 检查常驻服务运行状态、PID、端口与访问端点
|
||||
hose-use service status
|
||||
|
||||
# 查看常驻服务最近运行日志
|
||||
hose-use service logs
|
||||
|
||||
# 重启常驻服务
|
||||
hose-use service restart
|
||||
|
||||
# 优雅停止常驻服务 (清理 PID 文件)
|
||||
hose-use service stop
|
||||
|
||||
# 容器/前台守护运行模式 (供 Dockerfile 或 Supervisor 使用)
|
||||
hose-use service run
|
||||
\`\`\`
|
||||
|
||||
### 自愈保护机制
|
||||
每次执行 \`service status\` 或 \`service start\` 时,系统会自动探测记录的 PID:
|
||||
- 若进程已终止(孤儿 PID)或 PID 被其它非 \`hose\` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
|
||||
|
||||
---
|
||||
|
||||
## 2. 前台 HTTP 服务 (\`http\` / \`serve\`)
|
||||
|
||||
在当前终端前台启动 HTTP 服务并输出直观的服务信息面板,按 \`Ctrl+C\` 即可平滑退出:
|
||||
|
||||
\`\`\`bash
|
||||
# 启动本地 HTTP 服务 (默认端口 8888,主机 127.0.0.1)
|
||||
hose-use http
|
||||
|
||||
# 指定自定义端口与主机
|
||||
hose-use http --port=9999 --host=0.0.0.0
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 3. HTTP 路由端点一览
|
||||
|
||||
| 方法 | 端点 | 说明 |
|
||||
|---|---|---|
|
||||
| \`GET\` | \`/\` | 服务元信息、版本号与端点导航 |
|
||||
| \`GET\` | \`/health\` | 存活健康探针(返回 \`{ "status": "ok", "version": "..." }\`) |
|
||||
| \`GET\` | \`/docs\` | 基于 **Scalar API Reference** 的沉浸式交互文档界面 |
|
||||
| \`GET\` | \`/openapi.json\` | 包装层标准 OpenAPI 3.1.0 JSON 规范 |
|
||||
| \`GET\` | \`/raw-openapi.json\` | 合思原生下游 OpenAPI 规范 |
|
||||
| \`POST\` | \`/api/cli\` | **CLI 同进程执行网关**(免 spawn 子进程) |
|
||||
| \`GET\` | \`/v1/corps\` | RESTful 风格企业租户列表与运行模式 |
|
||||
|
||||
### 同进程 CLI 执行网关 (\`POST /api/cli\`)
|
||||
通过 HTTP POST 提交任意 CLI 命令字符串,在主服务进程内部直接分发执行,毫秒级响应,无需拉起 Node/Bun 子进程:
|
||||
|
||||
\`\`\`bash
|
||||
curl -X POST http://127.0.0.1:8888/api/cli \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"command": "corps list --json"}'
|
||||
\`\`\`
|
||||
|
||||
**响应结构**:
|
||||
\`\`\`json
|
||||
{
|
||||
"success": true,
|
||||
"stdout": "...",
|
||||
"stderr": "",
|
||||
"exitCode": 0,
|
||||
"data": {
|
||||
"corporations": [ ... ]
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## 4. OpenAPI 规范导出 (\`openapi\`)
|
||||
|
||||
\`\`\`bash
|
||||
# 查看所有 API 路径与概要一览
|
||||
hose-use openapi paths
|
||||
|
||||
# 查看合思原生下游全量 API 路径
|
||||
hose-use openapi --raw paths
|
||||
|
||||
# 查看 OpenAPI 规范元数据概览
|
||||
hose-use openapi info
|
||||
|
||||
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Apifox)
|
||||
hose-use openapi
|
||||
|
||||
# 输出原生下游全量 OpenAPI 3.1.0 JSON
|
||||
hose-use openapi --raw
|
||||
\`\`\`
|
||||
`;var PY="# hose-use 专卷:企业通讯录与人员档案 (Contact Domain)\n\n本文件是 `skills/hose-use/` 的领域参考专卷,详述合思/易快报企业通讯录的人员检索、防爆保护机制与单人档案下钻。\n\n---\n\n## 核心设计与防爆原则\n\n企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**\n\n因此,`hose-use` 遵循以下防爆安全原则:\n1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);\n2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;\n3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;\n4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。\n\n---\n\n## CLI 命令速查\n\n```bash\n# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)\nhose contact search 王硕\nhose contact search xiezihao@hosecloud.com\nhose contact search 18600612659\n\n# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)\nhose contact list\nhose contact list --limit=50\n\n# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)\nhose contact list --json -o /tmp/all_staffs.json\n\n# 4. 精确下钻查看指定人员详细档案\nhose contact get ID01MCcOgJl1td:3LsanKdS7Uo000\n\n# 5. 指定特定企业租户检索\nhose contact search 李 --corp=ID01MCcOgJl1td\n```\n\n---\n\n## MCP 工具调用\n\n在单工具网关模式下,推荐使用 `hose_cli` 触发:\n```json\n{\n \"command\": \"contact search 王硕\"\n}\n```\n\n在全量模式(`HOSE_MCP_MODE=all`)下,提供以下细粒度工具:\n- `contact_search(keyword: string, limit?: number)`:返回匹配的员工列表\n- `contact_get(staffId: string)`:获取单条员工详情\n- `contact_list(limit?: number, allowFull?: boolean)`:带保护的企业通讯录列表\n\n---\n\n## 业务联动典型场景\n\n### 1. 查找某人发起的单据\n当用户要求“帮我查一下王硕提交的报销单”时:\n1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);\n2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;\n3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。\n";var BY={"SKILL.md":YY,"agents/openai.yaml":NY,"references/auth.md":LY,"references/bill.md":KY,"references/contact.md":PY,"references/workflow.md":zY,"references/service.md":HY};function SY(){return BY["SKILL.md"]||""}function L6(){return N6(A0(),".agents","skills","hose-use")}function zJ(){return[N6(A0(),".agents","skills","hose-use"),N6(A0(),".gemini","antigravity","skills","hose-use"),N6(A0(),".codex","skills","hose-use")]}function G0($=L6()){FY($,{recursive:!0});let i=[];for(let[v,u]of Object.entries(BY)){let n=N6($,v);FY(OM(n),{recursive:!0}),XM(n,u,"utf8"),i.push(v)}return{targetDir:$,files:i}}function HJ(){let $=L6();return G0($),{synced:!0,targetDir:$}}async function ZY($,i){let v=$.action||"status";switch(v){case"dump":case"cat":case"show":return{stdout:`${SY()}
|
||||
`,stderr:"",exitCode:0};case"install":case"init":case"sync":{let u=W$($.options,["local"])||W$($.options,["workspace"]),n=m($.options,["dir","target"])||$.args[0],b=n?n:u?K6(process.cwd(),".agents","skills","hose-use"):L6(),I=G0(b),U=zJ();for(let D of U)if(D!==b)try{G0(D)}catch{}if(i.jsonMode)return{stdout:l({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] hose-use 技能已成功安装至: ${I.targetDir}
|
||||
包含文件: ${I.files.join(", ")}
|
||||
`,stderr:"",exitCode:0}}case"status":case"get":{let u=L6(),n=K6(process.cwd(),".agents","skills","hose-use"),b=zJ(),I={global:{dir:u,installed:PJ(K6(u,"SKILL.md"))},local:{dir:n,installed:PJ(K6(n,"SKILL.md"))},candidates:b.map((D)=>({dir:D,installed:PJ(K6(D,"SKILL.md"))}))};if(i.jsonMode)return{stdout:l(I),stderr:"",exitCode:0};return{stdout:`====== Agent Skill 状态 ======
|
||||
${J$({"全局 Skill 目录":`${u} [${I.global.installed?"已安装 ✅":"未安装 ❌"}]`,"本地 Skill 目录":`${n} [${I.local.installed?"已安装 ✅":"未安装 ❌"}]`})}
|
||||
|
||||
提示: 运行 hose-use skill install 进行全局安装
|
||||
`,stderr:"",exitCode:0}}default:return{stdout:"",stderr:`未知 skill 子命令: ${v}。支持: install, status, dump
|
||||
`,exitCode:1}}}async function VY($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:`未配置任何企业,请先运行 hose auth login 或使用 --corp 指定
|
||||
`,exitCode:1};let u={enterprise:{id:v.id,name:v.name,staffId:v.credentials.staffId,baseUrl:v.baseUrl,source:v.source,accountId:v.accountId},ekbSession:{status:"pending"},easoToken:{status:"pending"},platformAccess:{status:"pending"}};try{let I=await Bi(v);try{let U=await I.ekbClient.get("api/account/v2/session").json();u.ekbSession={status:"ok",userId:U.value?.userId,loginStaffId:U.value?.loginStaffId,expTime:U.value?.expTime?new Date(U.value.expTime).toLocaleString():void 0}}catch(U){u.ekbSession={status:"error",error:U instanceof Error?U.message:String(U)}}try{let U=await qv(I.ekbClient,v.credentials.corpId);u.platformAccess={status:"ok",totalPlatforms:U.length};let D=await eQ(I.easoClient,U[0]?.id||"platform");u.easoToken={status:"ok",message:"EASO 四步换票握手成功"}}catch(U){u.easoToken={status:"error",error:U instanceof Error?U.message:String(U)}}}catch(I){u.error=I instanceof Error?I.message:String(I)}if(i.jsonMode)return{stdout:l(u),stderr:"",exitCode:0};let n={"企业名称":v.name,"企业 ID":v.id,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Nn(v.source),"Token 过期时间":si(v.auth?.expiresAt||v.session?.expTime),"主站 Session 连通":u.ekbSession.status==="ok"?"\uD83D\uDFE2 正常":"\uD83D\uDD34 异常","EASO 引擎鉴权换票":u.easoToken.status==="ok"?"\uD83D\uDFE2 握手成功":"\uD83D\uDD34 失败","自建应用扫描":u.platformAccess.status==="ok"?`\uD83D\uDFE2 可访问 (${u.platformAccess.totalPlatforms} 个自建应用)`:"\uD83D\uDD34 失败"};if(v.session?.isAssistPlatform){if(n["协助操作人"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim(),v.session.assistId)n["协助会话 ID"]=v.session.assistId}return{stdout:`====== 诊断结果 (Enterprise Probe) ======
|
||||
${J$(n)}
|
||||
`,stderr:"",exitCode:0}}import{spawn as jM}from"child_process";import{join as AM}from"path";async function qY($,i){let v=i.appRoot||process.cwd(),u=AM(v,"src","server.ts");console.error("启动 MCP Server on stdio...");let n=jM("bun",["run",u],{stdio:"inherit",cwd:v,env:process.env});return await new Promise((b)=>{n.on("exit",()=>b())}),{stdout:"",stderr:"",exitCode:0}}import{chmodSync as QM,mkdirSync as YM,renameSync as FJ,rmSync as NM,unlinkSync as RY,writeFileSync as TY}from"node:fs";import{dirname as LM,join as lY}from"node:path";import{spawnSync as Ln}from"node:child_process";import{dirname as MY}from"node:path";import{fileURLToPath as GM}from"node:url";function z6($=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let v=$.toLowerCase().replace(/\\/g,"/");return!v.endsWith("/bun")&&!v.endsWith("/bun.exe")}function kY($,i=z6()){if(i)return process.cwd();let v=$||GM(import.meta.url);return MY(MY(v))}var CY="yunyingk/hose-use",KM="HOSE_USE_GITHUB_REPO";async function _Y($,i,v={}){let u=$.area==="changelog"||$.action==="changelog"||$.action==="log"||$.action==="history"||W$($.options,["changelog","log","l"]),n=$.action==="check"||W$($.options,["check","check-only","c"]),b=m($.options,["version","tag","target","t"])||(!u&&!n&&$.action&&!$.action.startsWith("-")?$.action:void 0),I=b&&b.toLowerCase()!=="latest"?b.replace(/^v/,""):void 0,U=m($.options,["repo"])||process.env[KM]?.trim()||CY,D={checkOnly:n,changelogOnly:u,limit:l$($.options,["limit","n"]),force:W$($.options,["force","f"]),targetVersion:I,repo:U},w=v.appRoot||kY(v.entryFile);if(I){let C=rY(I,E);if(C<0&&!D.force){let r=`无法降级 hose-use(当前版本 v${E},目标版本 v${I})。如需强制重装请使用 --force。`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,targetVersion:I,mode:z6()?"binary":"source",message:r}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${r}
|
||||
`,exitCode:1}}if(C===0&&!D.force){let r=`hose-use 当前已是版本 v${E}。如需强制重装请添加 --force。`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,targetVersion:I,mode:z6()?"binary":"source",message:r}),stderr:"",exitCode:0};return{stdout:`ℹ️ ${r}
|
||||
`,stderr:"",exitCode:0}}}if(D.changelogOnly){let C=await BJ(U,D.limit??10);if(i.jsonMode)return{stdout:l({currentVersion:E,totalQueried:C.length,releases:C.map((s)=>({version:s.version,tagName:s.tagName,publishedAt:s.publishedAt,author:s.author,releaseNotes:s.notes,releaseUrl:s.htmlUrl,isCurrent:s.version===E,isNewer:Tv(s.version,E)}))}),stderr:"",exitCode:0};let r=[`====== hose-use 版本发布记录 (当前版本: v${E}) ======`,""];for(let s of C){let y$=s.version===E?" [当前版本]":Tv(s.version,E)?" [新版本 ✨]":"";if(r.push(`• v${s.version} (${s.publishedAt?s.publishedAt.slice(0,10):"未知日期"})${y$}`),s.notes){let $n=s.notes.trim().split(`
|
||||
`).map((Zi)=>` ${Zi}`).join(`
|
||||
`);r.push($n)}r.push("")}return{stdout:r.join(`
|
||||
`),stderr:"",exitCode:0}}if(!z6()){if(D.checkOnly){let r=await BJ(U,30),s=r[0],y$=s?.version??E,$n=r.find((Di)=>Di.version===E),Zi=Tv(y$,E),Fn=r.filter((Di)=>Tv(Di.version,E));if(i.jsonMode)return{stdout:l({updated:!1,updateAvailable:Zi,currentVersion:E,currentVersionPublishedAt:$n?.publishedAt,latestVersion:y$,latestVersionPublishedAt:s?.publishedAt,behindCount:Fn.length,pendingReleases:Fn.map((Di)=>({version:Di.version,tagName:Di.tagName,publishedAt:Di.publishedAt,author:Di.author,releaseNotes:Di.notes,releaseUrl:Di.htmlUrl})),releaseNotes:s?.notes??"",releaseUrl:s?.htmlUrl??"",mode:"source",message:"当前运行于源码开发模式。运行 'hose-use update' 执行 git pull 与依赖更新。"}),stderr:"",exitCode:0};return{stdout:`====== hose-use 版本检查 ======
|
||||
${J$({"运行模式":"源码开发模式 (Source Mode)","当前版本":`v${E}`,"最新版本":`v${y$} ${Zi?"(可升级 ✨)":"(已是最新 ✅)"}`,"待更新版本数":Fn.length,"源码路径":w})}
|
||||
|
||||
${Zi?"可运行 hose-use update 执行 git pull 与依赖同步":"已经是最新版本"}
|
||||
`,stderr:"",exitCode:0}}try{tY("git",["-C",w,"pull","--ff-only"])}catch(r){let s=r instanceof Error?r.message:String(r);console.error(`git pull 提示: ${s}`)}tY("bun",["install"],{cwd:w});let C=HJ();if(i.jsonMode)return{stdout:l({updated:!0,version:E,mode:"source",skillSynced:C.synced?C.targetDir:!1}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] hose-use 源码与依赖更新成功!
|
||||
版本: v${E}
|
||||
技能同步: ${C.synced?"已同步至全局 ✅":"未同步"}
|
||||
`,stderr:"",exitCode:0}}let g=zM(),J=HM(),X=await BJ(U,30),O=I?X.find((C)=>C.version===I||C.tagName===I||C.tagName===`v${I}`)??await EY(U,I):X[0]??await EY(U);if(!O){let C=`无法从 GitHub 仓库 '${U}' 获取 Release 列表`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,mode:"binary",message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
|
||||
`,exitCode:1}}let j=O.version,G=X.find((C)=>C.version===E),N=Tv(j,E),L=N||Boolean(D.force),B=X.filter((C)=>Tv(C.version,E));if(D.checkOnly){if(i.jsonMode)return{stdout:l({updated:!1,updateAvailable:N,currentVersion:E,currentVersionPublishedAt:G?.publishedAt,latestVersion:j,latestVersionPublishedAt:O.publishedAt,behindCount:B.length,pendingReleases:B.map((r)=>({version:r.version,tagName:r.tagName,publishedAt:r.publishedAt,author:r.author,releaseNotes:r.notes,releaseUrl:r.htmlUrl})),releaseNotes:O.notes,releaseUrl:O.htmlUrl,mode:"binary"}),stderr:"",exitCode:0};return{stdout:`====== hose-use 版本检查 ======
|
||||
${J$({"运行模式":"独立二进制 (Binary Mode)","当前版本":`v${E}`,"最新版本":`v${j} ${N?"(可升级 ✨)":"(已是最新 ✅)"}`,"发布时间":O.publishedAt?O.publishedAt.slice(0,10):"未知","平台架构":`${g}-${J}`})}
|
||||
|
||||
${N?`运行 hose-use update 升级至 v${j}`:"已经是最新版本"}
|
||||
`,stderr:"",exitCode:0}}if(!L){if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,currentVersionPublishedAt:G?.publishedAt,latestVersion:j,latestVersionPublishedAt:O.publishedAt,mode:"binary",message:`hose-use 当前已是最新版本 (v${E})`}),stderr:"",exitCode:0};return{stdout:`ℹ️ hose-use 当前已是最新版本 (v${E})。如需重装请添加 --force。
|
||||
`,stderr:"",exitCode:0}}let V=PM(O.assets,g,J);if(!V){let C=`未找到适用于 ${g}-${J} 平台的 Release 资产 (v${j})。可用文件: ${O.assets.map((r)=>r.name).join(", ")}`;if(i.jsonMode)return{stdout:l({updated:!1,error:!0,message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
|
||||
`,exitCode:1}}let q=process.execPath,M=LM(q),O$=lY(M,`.tmp-update-${Date.now()}`);YM(O$,{recursive:!0});try{let C=lY(O$,V.name);await FM(V.downloadUrl,C,O.tagName,V.name);let r=C;if(V.name.endsWith(".tar.gz")||V.name.endsWith(".tgz"))r=BM(C,O$,g);else if(V.name.endsWith(".zip"))r=SM(C,O$,g);if(QM(r,493),process.platform==="darwin")try{Ln("/usr/bin/codesign",["--remove-signature",r],{stdio:"ignore"}),Ln("/usr/bin/codesign",["--force","--sign","-",r],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let y$=`${q}.old.${Date.now()}`;try{FJ(q,y$)}catch{}FJ(r,q)}else FJ(r,q);let s=HJ();if(i.jsonMode)return{stdout:l({updated:!0,fromVersion:E,toVersion:j,skillSynced:s.synced?s.targetDir:!1,mode:"binary"}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] ✨ hose-use 已成功升级至 v${j}!
|
||||
可执行文件: ${q}
|
||||
Agent 技能: ${s.synced?"已自动同步最新版 ✅":"未同步"}
|
||||
`,stderr:"",exitCode:0}}finally{try{NM(O$,{recursive:!0,force:!0})}catch{}}}function zM(){if(process.platform==="darwin")return"darwin";if(process.platform==="win32")return"windows";return"linux"}function HM(){return process.arch==="arm64"?"arm64":"x64"}async function BJ($,i=20){let v=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,u={"User-Agent":`hose-use/${E}`,Accept:"application/vnd.github.v3+json",...v?{Authorization:`Bearer ${v}`}:{}},n=[`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${i}`,`https://api.github.com/repos/${$}/releases?per_page=${i}`];for(let b of n)try{let I=await fetch(b,{headers:u,signal:AbortSignal.timeout(5000)});if(!I.ok)continue;let U=await I.json();if(!Array.isArray(U)||U.length===0)continue;let D=[];for(let w of U){let g=w.tag_name??"",J=g.replace(/^v/,"");if(!J)continue;let X=(w.assets??[]).map((O)=>({name:O.name,downloadUrl:O.browser_download_url,size:O.size??0}));D.push({version:J,tagName:g,name:w.name??g,publishedAt:w.published_at,author:w.author?.login,notes:w.body??"",htmlUrl:w.html_url??"",assets:X})}if(D.length>0)return D}catch{}return[]}async function EY($,i){let v=i?i.startsWith("v")?i:`v${i}`:void 0,u=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,n={"User-Agent":`hose-use/${E}`,Accept:"application/vnd.github.v3+json",...u?{Authorization:`Bearer ${u}`}:{}},b=v?[`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${v}`,`https://api.github.com/repos/${$}/releases/tags/${v}`]:["https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest",`https://api.github.com/repos/${$}/releases/latest`],I;for(let U of b)try{let D=await fetch(U,{headers:n,signal:AbortSignal.timeout(5000)});if(!D.ok)continue;let w=await D.json(),g=w.tag_name??"",J=g.replace(/^v/,"");if(!J)continue;let X=(w.assets??[]).map((j)=>({name:j.name,downloadUrl:j.browser_download_url,size:j.size??0})),O={version:J,tagName:g,name:w.name??g,publishedAt:w.published_at,author:w.author?.login,notes:w.body??"",htmlUrl:w.html_url??"",assets:X};if(X.length>0)return O;if(!I)I=O}catch{}return I}function PM($,i,v){let u={darwin:["darwin","macos","osx","apple"],linux:["linux"],windows:["windows","win32","win64",".exe"]},n={arm64:["arm64","aarch64"],x64:["x64","x86_64","amd64"]},b=u[i]||[],I=n[v]||[],U=$.filter((g)=>{let J=g.name.toLowerCase(),X=b.some((j)=>J.includes(j)),O=I.some((j)=>J.includes(j));return X&&O}),D=U.find((g)=>!g.name.endsWith(".tar.gz")&&!g.name.endsWith(".tgz")&&!g.name.endsWith(".zip")&&!g.name.endsWith(".sha256"));if(D)return D;return U.find((g)=>g.name.endsWith(".tar.gz")||g.name.endsWith(".tgz")||g.name.endsWith(".zip"))||U[0]}function Q0($){try{process.stderr.write(`${$}
|
||||
`)}catch{}}async function FM($,i,v,u){let n=[],b=v?v.startsWith("v")?v:`v${v}`:void 0,I=u||$.split("/").pop()||"";if(b&&I)n.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${b}/${I}`);if($.startsWith("https://git.ying-qing.cn"))n.push($);if(b&&I){let w=`https://github.com/${CY}/releases/download/${b}/${I}`;n.push(`https://ghfast.top/${w}`),n.push(`https://ghproxy.net/${w}`),n.push(`https://gh.ddlc.top/${w}`),n.push(`https://mirror.ghproxy.com/${w}`),n.push(w)}else if($.includes("github.com"))n.push(`https://ghfast.top/${$}`),n.push(`https://ghproxy.net/${$}`),n.push(`https://gh.ddlc.top/${$}`),n.push(`https://mirror.ghproxy.com/${$}`),n.push($);else n.push($);let U=Array.from(new Set(n)),D;for(let w=0;w<U.length;w++){let g=U[w];try{Q0(`==> [${w+1}/${U.length}] 正在下载更新: ${g}`);let J=await fetch(g,{signal:AbortSignal.timeout(6000)});if(!J.ok)throw Error(`HTTP ${J.status} ${J.statusText}`);let X=Number(J.headers.get("content-length"))||0,O=J.body?.getReader();if(!O){let B=Buffer.from(await J.arrayBuffer());if(B.length<1000)throw Error(`下载文件异常(大小仅 ${B.length} 字节)`);TY(i,B),Q0(`✓ 下载完成 (${(B.length/1024/1024).toFixed(1)} MB)`);return}let j=[],G=0,N=0;while(!0){let{done:B,value:V}=await O.read();if(B)break;if(V){j.push(V),G+=V.length;let q=Date.now();if(q-N>200){N=q;let M=X?Math.round(G/X*100):0,O$=(G/1048576).toFixed(1),C=X?(X/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ 进度: ${M}% (${O$} / ${C} MB)...`)}catch{}}}}try{process.stderr.write(`
|
||||
`)}catch{}let L=Buffer.concat(j);if(L.length<1000)throw Error(`下载文件异常(大小仅 ${L.length} 字节)`);TY(i,L),Q0(`✓ 下载完成 (${(L.length/1024/1024).toFixed(1)} MB)`);return}catch(J){D=J instanceof Error?J:Error(String(J)),Q0(` ↳ 节点失败: ${D.message}`)}}throw Error(`所有下载镜像均失败: ${D?.message}`)}function BM($,i,v){let u=Ln("tar",["-xzf",$,"-C",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 tar 归档失败: ${u.stderr.toString()}`);RY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Ln("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
|
||||
`).filter(Boolean),I=b.find((U)=>U.endsWith(`/${n}`)||U.endsWith(n));if(I)return I;return b[0]||$}function SM($,i,v){let u=Ln("unzip",["-q","-o",$,"-d",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 zip 归档失败: ${u.stderr.toString()}`);RY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Ln("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
|
||||
`).filter(Boolean),I=b.find((U)=>U.endsWith(`/${n}`)||U.endsWith(n));if(I)return I;return b[0]||$}function rY($,i){let v=$.replace(/^v/,"").split(".").map((n)=>Number.parseInt(n,10)||0),u=i.replace(/^v/,"").split(".").map((n)=>Number.parseInt(n,10)||0);for(let n=0;n<Math.max(v.length,u.length);n++){let b=v[n]??0,I=u[n]??0;if(b>I)return 1;if(b<I)return-1}return 0}function Tv($,i){return rY($,i)>0}function tY($,i,v={}){let u=Ln($,i,{cwd:v.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(u.stdout)console.error(u.stdout.trimEnd());if(u.stderr)console.error(u.stderr.trimEnd());if(u.status!==0)throw Error(`${$} ${i.join(" ")} 执行失败 (退出码 ${u.status})`)}var fY={openapi:"3.1.0",info:{title:"hose-use API & MCP Tools Specification",version:"0.5.2",description:"Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."},servers:[{url:"http://localhost:3000",description:"Local hose-use CLI / MCP Runtime Gateway"}],tags:[{name:"Auth & SSO",description:"统一认证、多账号管理与 30 天 Token 自动无感续杯"},{name:"Corps & Tenancy",description:"多企业租户管理与工作空间切换"},{name:"Platforms",description:"自建应用检索与实例枚举"},{name:"Workflows",description:"跨自建应用工作流聚合检索、DSL 图谱与启停"},{name:"Bills & Documents",description:"费控单据、报销借款单、发票明细与 DataLink 实体字典"},{name:"Probe & Diagnostics",description:"会话有效性与 EASO 鉴权连通性诊断"}],paths:{"/api/auth/login":{post:{tags:["Auth & SSO"],summary:"纯 API 账密自动全流程登录",description:"自动拉取公钥进行 RSA PKCS#1 加密,发起统一认证中心握手并批量获取名下所有企业身份。",operationId:"authLogin",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["phone","password"],properties:{phone:{type:"string",description:"登录手机号",example:"17718556446"},password:{type:"string",description:"登录明文密码 (由客户端自动完成 RSA 加密)"},autoSwitch:{type:"boolean",description:"是否自动切换到首个企业",default:!0}}}}}},responses:{"200":{description:"登录成功",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},totalCorps:{type:"integer"},activeCorp:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",description:"员工身份 ID"},accountId:{type:"string",description:"归属账号手机号"}}}}}}}},"401":{description:"账密错误或鉴权失败",content:{"application/json":{schema:{type:"object",properties:{error:{type:"boolean",example:!0},message:{type:"string",example:"操作失败原因"}}}}}}}}},"/api/auth/status":{get:{tags:["Auth & SSO"],summary:"查看当前登录与活跃企业状态",description:"查询本地或无状态下的当前账号、工作企业与凭证有效期。",operationId:"authStatus",responses:{"200":{description:"状态正常",content:{"application/json":{schema:{type:"object",properties:{loggedIn:{type:"boolean"},activeCorpId:{type:"string"},activeCorpName:{type:"string"},totalAccounts:{type:"integer"},totalCorps:{type:"integer"}}}}}}}}},"/api/auth/refresh":{post:{tags:["Auth & SSO"],summary:"批量刷新企业 30 天 AccessToken",description:"自动无感为当前账号名下的所有企业租户更新最新 30 天访问令牌。",operationId:"authRefresh",responses:{"200":{description:"刷新完成",content:{"application/json":{schema:{type:"object",properties:{refreshed:{type:"integer"},total:{type:"integer"}}}}}}}}},"/api/corps":{get:{tags:["Corps & Tenancy"],summary:"列出当前账号名下所有已配置企业租户",description:"支持单账号管理多家企业与同一企业下的多员工身份分层展示。",operationId:"listCorps",responses:{"200":{description:"企业租户列表",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",description:"员工身份 ID"},accountId:{type:"string",description:"归属账号手机号"}}}}}}}}}},"/api/corps/switch":{post:{tags:["Corps & Tenancy"],summary:"切换当前工作企业",description:"在有状态模式下切换并记忆工作企业,后续操作自动以该企业身份执行。",operationId:"switchCorp",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string",description:"目标企业 ID 或身份 ID (corpId@accountId)"}}}}}},responses:{"200":{description:"切换成功",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},activeCorp:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",des
Line truncated
|
||||
|
||||
${U}
|
||||
|
||||
提示: 运行 hose-use openapi ${v?"--raw ":""}可直接输出完整 OpenAPI 3.1.0 JSON
|
||||
`,stderr:"",exitCode:0}}case"info":case"summary":{let b=Kn(u),I=b.info||{},U=(b.servers||[]).map((X)=>`${X.url} (${X.description||"-"})`),D=(b.tags||[]).map((X)=>`${X.name}: ${X.description||""}`),w=SJ(u),g={title:I.title,version:I.version,description:I.description,type:u,totalEndpoints:w.length,servers:U,tags:D};if(i.jsonMode)return{stdout:l(g),stderr:"",exitCode:0};return{stdout:`====== OpenAPI 规范概览 ======
|
||||
${J$({"规范标题":I.title,"规范版本":I.version,"规范类型":v?"原始下游原生 API (Raw Spec)":"包装层工具 API (Wrapped Spec)","接口总数":w.length,"描述信息":I.description,"服务器列表":U.join(`
|
||||
`),"标签分组":D.join(`
|
||||
`)})}
|
||||
`,stderr:"",exitCode:0}}case"dump":case"export":case"raw":case void 0:default:{let b=Kn(u);return{stdout:`${JSON.stringify(b,null,2)}
|
||||
`,stderr:"",exitCode:0}}}}async function cY($,i){let v=i.selectedCorp;if(!v)throw Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");let u=await x$(v),n=$.action?.toLowerCase(),b=v.corpId||v.id;switch(n){case"list":case"search":case void 0:{let I=m($.options,["code","c"]),U=m($.options,["keyword","k","q","query"]),D=m($.options,["stage"]),w=m($.options,["state","s"]),g=l$($.options,["count","limit","n"],20),J=await NJ(u,b,{code:I,keyword:U,stage:D,state:w,count:g});if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,total:J.total,returned:J.returned,items:J.items},i.outputOptions),stderr:"",exitCode:0};let X=["#","单据编号 (单号)","单据名称","阶段","状态","金额","提交时间"],O=J.items.map((L,B)=>[B+1,L.billCode,L.billName,L.stage||"-",L.state||"-",L.amount||"-",L.submitDate||L.createTime||"-"]),j=Y$(X,O),G=`====== 单据与费用明细列表 (企业: ${v.name} | 总数: ${J.total} | 本次返回: ${J.returned}) ======
|
||||
`,N=`
|
||||
提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细
|
||||
`;return{stdout:G+j+N,stderr:"",exitCode:0}}case"get":case"show":case"find":{let I=$.args[0]||m($.options,["code","id"]);if(!I)throw Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");let U=await j0(u,b,I);if(U.length===0){if(i.jsonMode)return{stdout:l({found:!1,code:I,message:"未找到匹配单据"}),stderr:"",exitCode:1};return{stdout:"",stderr:`[NOT FOUND] 在企业 [${v.name}] 下未找到单号或 ID 为 [${I}] 的单据
|
||||
`,exitCode:1}}if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,count:U.length,bills:U},i.outputOptions),stderr:"",exitCode:0};let D=[];for(let w=0;w<U.length;w++){let g=U[w];if(D.push(`
|
||||
====== 单据详情 [${w+1}/${U.length}] (单号: ${g.billCode}) ======`),D.push(` 单据 ID : ${g.billId}`),D.push(` 单据名称 : ${g.billName}`),g.title)D.push(` 单据标题 : ${g.title}`);if(g.stage)D.push(` 业务阶段 : ${g.stage}`);if(g.state)D.push(` 审批状态 : ${g.state}`);if(g.amount)D.push(` 单据金额 : ${g.amount}`);if(g.submitterId)D.push(` 提交人员 : ${g.submitterId}`);if(g.submitDate)D.push(` 提交时间 : ${g.submitDate}`);D.push(` 创建时间 : ${g.createTime}`),D.push(` 更新时间 : ${g.updateTime}`),D.push(`
|
||||
--- 结构化表单字段明细 ---`);let J=Object.entries(g.details);if(J.length===0)D.push(" (无额外字段数据)");else{let X=Math.max(...J.map(([O])=>O.length),0);for(let[O,j]of J){let G=typeof j==="object"?JSON.stringify(j):String(j);D.push(` ${O.padEnd(X+2)}: ${G}`)}}}return{stdout:D.join(`
|
||||
`)+`
|
||||
`,stderr:"",exitCode:0}}case"schema":case"schemas":case"entities":{let{entities:I}=await Y6(u,b,!0);if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,totalEntities:I.length,entities:I},i.outputOptions),stderr:"",exitCode:0};let U=["#","实体 ID","实体名称","类型","字段数"],D=I.map((J,X)=>[X+1,J.id,J.name||"-",J.type||"-",J.fields.length]),w=Y$(U,D);return{stdout:`====== 单据实体与数据模型字典 (企业: ${v.name} | 共 ${I.length} 个实体) ======
|
||||
`+w+`
|
||||
`,stderr:"",exitCode:0}}case"link":case"url":{let I=$.args[0]||m($.options,["code","id","c"]);if(!I)return{stdout:"",stderr:"用法: hose bill link <单号或ID>",exitCode:1};let U=await j0(u,b,I);if(!U||U.length===0)return{stdout:"",stderr:`未找到单据: ${I}`,exitCode:1};let D=U[0],w=D.billId,g=D.billCode||I,X=`${(v.baseUrl||"https://app.ekuaibao.com").replace(/\/+$/,"")}/#/invoice/detail?id=${encodeURIComponent(w)}&corporationId=${encodeURIComponent(b)}`;if(i.jsonMode)return{stdout:l({code:g,id:w,corpId:b,corpName:v.name,url:X},i.outputOptions),stderr:"",exitCode:0};return{stdout:["====== 合思单据 Web 直达链接 ======",` 单据编号: ${g}`,` 单据 ID : ${w}`,` 所属企业: ${v.name} (${b})`," 直达链接:",` ${X}`,"",`Markdown 链接: [查看单据 ${g}](${X})`].join(`
|
||||
`)+`
|
||||
`,stderr:"",exitCode:0}}default:throw Error(`未知 bill 子命令: ${n}。支持: list, get <单号>, schema, link <单号>`)}}var hY=W.object({id:W.string(),name:W.string(),email:W.string().nullable().optional(),cellphone:W.string().nullable().optional(),department:W.string().nullable().optional()});async function Y0($,i=!1){let u=await(await $.get("api/easo/common/staffs",{searchParams:{external:String(i)}})).json();return W.array(hY).parse(u.data??[])}var N0=20;async function ZJ($,i={}){let{client:v}=await ei($),u=await Y0(v,i.external??!1),n=u.length,I=i.allowFull===!0?n:i.limit??N0,U=u.slice(0,I),D=n>U.length;return{total:n,limit:I,hasMore:D,hint:D?`企业员工共 ${n} 人,当前仅展示前 ${U.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`:void 0,staffs:U}}async function VJ($,i){let{client:v}=await ei($),u=await Y0(v,i.external??!1),n=i.keyword.trim().toLowerCase();if(!n)return u.slice(0,i.limit??N0);return u.filter((I)=>{let U=I.name?.toLowerCase()||"",D=I.email?.toLowerCase()||"",w=I.cellphone||"",g=I.id?.toLowerCase()||"";return U.includes(n)||D.includes(n)||w.includes(n)||g.includes(n)}).slice(0,i.limit??50)}async function qJ($,i){let{client:v}=await ei($),u=await Y0(v,!1),n=i.trim();return u.find((I)=>I.id===n||I.id.endsWith(`:${n}`)||I.id.split(":")[1]===n)||null}var vc=[{name:"contact_search",description:"在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",parameters:W.object({keyword:W.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),limit:W.number().optional().describe("最大返回条数,默认 20")}),handler:async($,i)=>{let v=await VJ($,i);return{count:v.length,staffs:v}}},{name:"contact_get",description:"根据员工 staffId 或工号精准获取员工详细档案",parameters:W.object({staffId:W.string().describe("员工的完整 staffId 或 ID")}),handler:async($,i)=>{let v=await qJ($,i.staffId);if(!v)throw Error(`未找到员工: ${i.staffId}`);return v}},{name:"contact_list",description:"查看企业通讯录(带默认 20 条防爆截断与总数保护)",parameters:W.object({limit:W.number().optional().describe("截断返回条数,默认 20"),allowFull:W.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)")}),handler:async($,i)=>{return await ZJ($,i)}}];async function mY($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:"未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",exitCode:1};let u=$.action||$.args[0]||"list",n=l$($.options,["limit","l"]);if(u==="search"||u==="find"){let b=$.args[0]||m($.options,["keyword","query","k"])||"";if(!b.trim())return{stdout:"",stderr:"用法: hose contact search <关键词 (姓名/邮箱/工号)>",exitCode:1};let I=await VJ(v,{keyword:b,limit:n});if(i.jsonMode)return{stdout:l({count:I.length,keyword:b,staffs:I},i.outputOptions),stderr:"",exitCode:0};if(I.length===0)return{stdout:`未找到匹配关键词 "${b}" 的员工。
|
||||
`,stderr:"",exitCode:0};let U=["姓名","工号 / staffId","邮箱","手机号"],D=I.map((w)=>[w.name||"-",w.id,w.email||"-",w.cellphone||"-"]);return{stdout:`====== 员工搜索结果 (关键词: "${b}", 找到 ${I.length} 人) ======
|
||||
${Y$(U,D)}
|
||||
`,stderr:"",exitCode:0}}if(u==="get"){let b=$.args[0]||m($.options,["id","staff-id"]);if(!b)return{stdout:"",stderr:"用法: hose contact get <staffId>",exitCode:1};let I=await qJ(v,b);if(!I)return{stdout:"",stderr:`未找到员工档案: ${b}`,exitCode:1};if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};let U={"员工姓名":I.name,"工号/staffId":I.id,"电子邮箱":I.email||"-","联系手机":I.cellphone||"-","所属部门":I.department||"-"};return{stdout:`====== 员工详细档案 ======
|
||||
${J$(U)}
|
||||
`,stderr:"",exitCode:0}}if(u==="list"){let b=i.outputOptions?.allowFull===!0,I=await ZJ(v,{limit:n??(b?void 0:N0),allowFull:b});if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};let U=["姓名","工号 / staffId","邮箱","手机号"],D=I.staffs.map((g)=>[g.name||"-",g.id,g.email||"-",g.cellphone||"-"]),w=`====== 企业通讯录采样 (共 ${I.total} 人,当前显示 ${I.staffs.length} 条) ======
|
||||
`;if(w+=Y$(U,D)+`
|
||||
`,I.hint)w+=`
|
||||
\uD83D\uDCA1 提示: ${I.hint}
|
||||
`;return{stdout:w,stderr:"",exitCode:0}}return{stdout:"",stderr:`未知通讯录子命令: ${u}。支持的子命令: list, search <关键词>, get <staffId>`,exitCode:1}}import{homedir as rM}from"node:os";import{join as uN}from"node:path";import{spawn as lM,execFileSync as EM}from"node:child_process";import{existsSync as eY,mkdirSync as tM,readFileSync as sY,rmSync as P6,writeFileSync as EJ}from"node:fs";import{join as $N}from"node:path";import{createServer as TM}from"node:http";import{URL as qM}from"node:url";function oY(){return`<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<title>hose-use API Reference (v${E})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #0f172a;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`}async function dY($,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Hose-Corp"),$.method==="OPTIONS"){i.writeHead(204),i.end();return}let v=$.headers.host||"localhost",u=$.headers["x-forwarded-proto"]||"http",b=new qM($.url||"/",`${u}://${v}`).pathname.replace(/\/+$/,"")||"/",I=($.method||"GET").toUpperCase();try{if(I==="GET"&&b==="/"){zn(i,200,{name:"hose-use",version:E,description:"合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",docs:"/docs",openapi:"/openapi.json",rawOpenapi:"/raw-openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",corps:"GET /v1/corps"}});return}if(I==="GET"&&b==="/health"){zn(i,200,{status:"ok",name:"hose-use",version:E,timestamp:new Date().toISOString()});return}if(I==="GET"&&b==="/docs"){MM(i,200,oY());return}if(I==="GET"&&b==="/openapi.json"){zn(i,200,Kn("wrapped"));return}if(I==="GET"&&b==="/raw-openapi.json"){zn(i,200,Kn("raw"));return}if(I==="POST"&&b==="/api/cli"){let U=await kM($),D=(typeof U?.command==="string"?U.command:"").trim();if(!D){MJ(i,400,"Missing 'command' property in request body");return}let w=kJ(D),g=TJ(w),J=await H6(g),X=void 0,O=J.stdout.trim();try{if(O.startsWith("{")||O.startsWith("["))X=JSON.parse(O)}catch{}zn(i,J.exitCode===0?200:400,{success:J.exitCode===0,stdout:J.stdout,stderr:J.stderr,exitCode:J.exitCode,...X!==void 0?{data:X}:{}});return}if(I==="GET"&&b==="/v1/corps"){let U=Hv(),D=Qn();zn(i,200,{count:U.length,mode:D.stateful?"stateful":"stateless",defaultCorpId:D.defaultCorpId,corps:U.map((w)=>({id:w.id,name:w.name,source:w.source,staffId:w.credentials.staffId,baseUrl:w.baseUrl,expiresAt:w.auth?.expiresAt||w.session?.expTime}))});return}MJ(i,404,`Cannot ${I} ${b}. Visit /docs for available endpoints.`)}catch(U){let D=U instanceof Error?U.message:String(U);MJ(i,500,D)}}function zn($,i,v){if($.headersSent)return;let u=JSON.stringify(v,null,2);$.writeHead(i,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(u,"utf-8")}),$.end(u)}function MM($,i,v){if($.headersSent)return;$.writeHead(i,{"Content-Type":"text/html; charset=utf-8","Content-Length":Buffer.byteLength(v,"utf-8")}),$.end(v)}function MJ($,i,v){zn($,i,{error:!0,message:v})}async function kM($){return new Promise((i,v)=>{let u="";$.on("data",(n)=>{if(u+=n,u.length>5242880)v(Error("Request payload too large (max 5MB)"))}),$.on("end",()=>{if(!u.trim()){i(null);return}try{i(JSON.parse(u))}catch(n){v(Error(`Invalid JSON body: ${n instanceof Error?n.message:String(n)}`))}}),$.on("error",(n)=>{v(n)})})}var L0=8888,K0="127.0.0.1";async function z0($={}){let i=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),v=$.host??(process.env.HOST?process.env.HOST:K0),u=TM(async(n,b)=>{try{await dY(n,b)}catch(I){if(!b.headersSent)b.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),b.end(JSON.stringify({error:!0,message:I instanceof Error?I.message:String(I)}))}});return new Promise((n,b)=>{u.on("error",(I)=>{b(I)}),u.listen(i,v,()=>{if(!$.silent)console.error(`
|
||||
⚡ hose-use HTTP Server (v${E}) 已启动`),console.error(` 主服务地址: http://${v}:${i}`),console.error(` 交互式文档: http://${v}:${i}/docs`),console.error(` OpenAPI规范: http://${v}:${i}/openapi.json`),console.error(` CLI执行网关: POST http://${v}:${i}/api/cli`),console.error(` 企业列表接口: GET http://${v}:${i}/v1/corps
|
||||
`);n(u)})})}async function iN($,i,v={}){switch($){case"run":await RM(i);return;case"start":return pY(i);case"stop":return aY(i,v);case"restart":return aY(i,{quiet:!0}),pY(i);case"logs":case"log":return CM(i);case"status":case void 0:return lJ(i);default:throw Error("用法: hose service <start|stop|restart|status|logs>")}}function lJ($){let i=Ev($),v=H0(i),u=v?nN(v,$.appRoot):!1;if(v&&!u)P6(i,{force:!0});let n=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),b=$.host??(process.env.HOST?process.env.HOST:K0);return{running:u,pid:u?v:void 0,version:$.version,port:n,host:b,url:u?`http://${b}:${n}`:void 0,appRoot:$.appRoot,stateDir:$.stateDir,pidFile:i,logFile:Hn($)}}async function RM($){let i=Ev($),v=Hn($);vN($.stateDir),EJ(i,`${process.pid}
|
||||
`,{mode:384});let u=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),n=$.host??(process.env.HOST?process.env.HOST:K0);lv(v,`service starting on http://${n}:${u} pid=${process.pid}`);let b=null;try{b=await z0({port:u,host:n,silent:!0}),lv(v,`service listening pid=${process.pid}`)}catch(U){if(lv(v,`service failed to bind port ${u}: ${U instanceof Error?U.message:String(U)}`),H0(i)===process.pid)P6(i,{force:!0});throw U}let I=()=>{if(b)b.close(),b=null;if(H0(i)===process.pid)P6(i,{force:!0});lv(v,`service stopped pid=${process.pid}`)};await new Promise((U)=>{let D=!1,w=()=>{if(D)return;D=!0,I(),process.off("SIGTERM",w),process.off("SIGINT",w),U()};process.once("SIGTERM",w),process.once("SIGINT",w)})}function pY($){vN($.stateDir);let i=lJ($);if(i.running)return i;let v=$.launcher??{command:process.execPath,args:[$.entryFile]},u=[...v.args??[],"service","run"];if($.port)u.push(`--port=${$.port}`);if($.host)u.push(`--host=${$.host}`);let n=lM(v.command,u,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});n.unref();let b=Ev($);return EJ(b,`${n.pid}
|
||||
`,{mode:384}),lv(Hn($),`service started pid=${n.pid}`),{started:!0,...lJ($)}}function aY($,i={}){let v=Ev($),u=H0(v);if(!u||!nN(u,$.appRoot))return P6(v,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"服务未处于运行状态"};try{process.kill(u,"SIGTERM")}catch{}return P6(v,{force:!0}),lv(Hn($),`service stop requested pid=${u}`),i.quiet?void 0:{stopped:!0,pid:u}}function CM($,i=50){let v=Hn($);if(!eY(v))return{logFile:v,lines:[],content:"暂无服务运行日志"};let n=sY(v,"utf-8").trim().split(`
|
||||
`).filter(Boolean).slice(-i);return{logFile:v,lines:n,content:n.join(`
|
||||
`)}}function nN($,i){if(!_M($))return!1;try{let v=EM("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(v.includes(i)||v.includes("hose-use")||v.includes("src/cli.ts"))&&v.includes("service")&&v.includes("run")}catch{return!1}}function _M($){try{return process.kill($,0),!0}catch{return!1}}function Ev($){return $N($.stateDir,"service.pid")}function Hn($){return $N($.stateDir,"service.log")}function H0($){if(!eY($))return;let i=Number(sY($,"utf-8").trim());return Number.isInteger(i)&&i>0?i:void 0}function vN($){tM($,{recursive:!0,mode:448})}function lv($,i){EJ($,`${new Date().toISOString()} ${i}
|
||||
`,{flag:"a",mode:384})}var fM=process.env.HOSE_STATE_DIR||uN(rM(),".config","hose-use");async function bN($,i){let v=$.action||$.args[0]||"status",u=l$($.options,["port","p"]),n=m($.options,["host","h"]),b={appRoot:i.appRoot||process.cwd(),entryFile:i.entryFile||uN(i.appRoot||process.cwd(),"src","cli.ts"),stateDir:fM,version:E,launcher:i.launcher,port:u,host:n},I=await iN(v,b);if(I===void 0)return{stdout:"",stderr:"",exitCode:0};if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};if(v==="logs"||v==="log"){let J=I;return{stdout:`====== hose-use 守护进程日志 (${J.logFile}) ======
|
||||
${J.content}
|
||||
`,stderr:"",exitCode:0}}let U=I,w={"服务状态":Boolean(U.running)?"\uD83D\uDFE2 正在运行 (Running)":"⚪ 已停止 (Stopped)",...U.pid?{"进程 PID":U.pid}:{},...U.url?{"服务地址":U.url}:{},...U.url?{"交互式文档":`${U.url}/docs`}:{},...U.url?{"CLI 网关":`POST ${U.url}/api/cli`}:{},"运行版本":U.version||b.version,"状态目录":U.stateDir||b.stateDir,"PID 文件":U.pidFile||Ev(b),"日志文件":U.logFile||Hn(b)};return{stdout:`====== hose-use 常驻服务管理 (Service) ======
|
||||
${J$(w)}
|
||||
`,stderr:"",exitCode:0}}async function IN($,i){let v=l$($.options,["port","p"]),u=m($.options,["host","h"]),n=await z0({port:v,host:u,silent:i.jsonMode}),b=()=>{n.close(()=>{process.exit(0)})};return process.on("SIGINT",b),process.on("SIGTERM",b),await new Promise(()=>{}),{stdout:"",stderr:"",exitCode:0}}var xM=new Set(["http","server","web","mcp"]);function yM($){if(!$.length)return!1;let i=$[0]?.toLowerCase(),v=$[1]?.toLowerCase();if(xM.has(i))return!0;if((i==="service"||i==="daemon")&&v==="run")return!0;return!1}var UN=Promise.resolve(void 0);function H6($,i={}){if(yM($))return DN($,i);let v=UN.then(()=>cM($,i));return UN=v.then(()=>{return},()=>{return}),v}async function cM($,i={}){let v=[],u=[],n=console.log,b=console.error;console.log=(...I)=>{v.push(I.map((U)=>typeof U==="string"?U:String(U)).join(" "))},console.error=(...I)=>{u.push(I.map((U)=>typeof U==="string"?U:String(U)).join(" "))};try{let I=await DN($,i),U=v.length?`${v.join(`
|
||||
`)}
|
||||
`:"",D=u.length?`${u.join(`
|
||||
`)}
|
||||
`:"";return{stdout:kv(U+(I.stdout||"")),stderr:kv(D+(I.stderr||"")),exitCode:I.exitCode}}finally{console.log=n,console.error=b}}async function DN($,i={}){let v=gY($);if(W$(v.options,["help","h"])||v.area==="help")return{stdout:KJ()+`
|
||||
`,stderr:"",exitCode:0};if(W$(v.options,["version","v"])||v.area==="version")return{stdout:`hose-use v${E}
|
||||
`,stderr:"",exitCode:0};let u=W$(v.options,["json","j"]),n=m(v.options,["corp","c"]),b=W$(v.options,["stateless"]),I=W$(v.options,["stateful"]),U=WY(v.options),D=XY({corpId:n,stateless:b,stateful:I,jsonMode:u,outputOptions:U,appRoot:i.appRoot,entryFile:i.entryFile,launcher:i.launcher});try{switch(v.area){case"auth":case"login":return await OY(v,D);case"corps":case"corp":return await jY(v,D);case"config":case"mode":return await AY(v,D);case"workflow":case"workflows":case"wf":return await GY(v,D);case"bill":case"bills":case"fee":case"fees":case"invoice":case"invoices":return await cY(v,D);case"contact":case"contacts":case"staff":case"staffs":return await mY(v,D);case"platform":case"platforms":case"app":case"apps":return await QY(v,D);case"skill":case"skills":return await ZY(v,D);case"probe":case"diagnose":return await VY(v,D);case"update":case"upgrade":case"self-update":case"changelog":return await _Y(v,D,i);case"openapi":case"schema":case"spec":return await yY(v,D);case"http":case"server":case"web":return await IN(v,D);case"service":case"daemon":return await bN(v,D);case"mcp":return await qY(v,i);case void 0:return{stdout:KJ()+`
|
||||
`,stderr:"",exitCode:0};default:return{stdout:"",stderr:`未知命令域: ${v.area}。运行 hose --help 查看帮助
|
||||
`,exitCode:1}}}catch(w){let g=kv(w instanceof Error?w.message:String(w));if(u)return{stdout:l({error:!0,message:g}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${g}
|
||||
`,exitCode:1}}}var tJ="hose_cli",mM="HOSE_MCP_MODE",oM="HOSE_USE_MCP_ENABLED",Pn=hM(import.meta.url),gN=Pn.includes("/dist/mcp/")||Pn.includes("\\dist\\mcp\\")?F6(F6(F6(Pn))):F6(F6(Pn));function dM($=process.env[oM]){if($===void 0)return!0;return["1","true","yes","on"].includes($.trim().toLowerCase())}function WN($=process.env[mM]){if(!$)return"single";let i=$.trim().toLowerCase();if(i==="all"||i==="both"||i==="full")return"all";if(i==="legacy"||i==="multi")return"legacy";return"single"}function kJ($){let i=[],v="",u,n=!1,b=!1;for(let I of $){if(n){v+=I,n=!1,b=!0;continue}if(I==="\\"&&u!=="'"){n=!0,b=!0;continue}if(u){if(I===u)u=void 0;else v+=I;b=!0;continue}if(I==="'"||I==='"'){u=I,b=!0;continue}if(/\s/.test(I)){if(b)i.push(v),v="",b=!1;continue}v+=I,b=!0}if(n)throw Error("Invalid command: trailing escape");if(u)throw Error("Invalid command: unterminated quote");if(b)i.push(v);return i}function TJ($){let i=$[0];if(!i)return[];let v=i.toLowerCase().replace(/\\/g,"/");if(v==="hose-use"||v==="hose"||v.endsWith("/hose-use")||v.endsWith("/hose")||v.endsWith("/hose-use.exe")||v.endsWith("/hose.exe"))return $.slice(1);return $}function P0($){let i=$.exitCode!==0,v=i?$.stderr||$.stdout||"Command failed":$.stdout||$.stderr||"Success";return v=kv(v),{content:[{type:"text",text:v.trimEnd()}],isError:i}}function pM($){if($ instanceof wJ)return{content:[{type:"text",text:"未配置企业,请先添加企业配置或登录"}],isError:!0};if($ instanceof g$)return{content:[{type:"text",text:`认证失败: ${$.message}`}],isError:!0};if($ instanceof O6)return{content:[{type:"text",text:`错误 [${$.code}]: ${$.message}`}],isError:!0};if($ instanceof W.ZodError)return{content:[{type:"text",text:`参数错误: ${$.message}`}],isError:!0};return{content:[{type:"text",text:$ instanceof Error?$.message:"发生内部错误,请稍后重试"}],isError:!0}}function aM($={}){let i=$.enabled??dM(),v=$.mode??WN(),u=new yW({name:"hose-use",version:E},{capabilities:{tools:{}}}),n=[...jJ,...GJ,...LJ];return u.setRequestHandler(qg,async()=>{if(!i)return{tools:[]};let b=[];if(v==="single"||v==="all")b.push({name:tJ,description:"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",inputSchema:{type:"object",properties:{command:{type:"string",description:"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'."}},required:["command"],additionalProperties:!1}});if(v==="all"||v==="legacy")for(let I of n)b.push({name:I.name,description:I.description,inputSchema:I.parameters.toJSONSchema()});return{tools:b}}),u.setRequestHandler(V4,async(b)=>{if(!i)return P0({stdout:"",stderr:"hose-use MCP 服务在插件配置中已被禁用 (HOSE_USE_MCP_ENABLED=false)",exitCode:1});let{name:I,arguments:U}=b.params;if(I===tJ){let D=U&&typeof U.command==="string"?U.command:void 0;if(!D?.trim())return P0({stdout:"",stderr:"hose_cli requires a non-empty command string",exitCode:1});try{let w=kJ(D),g=TJ(w);if(!g.length)throw Error("hose_cli requires a non-empty command string");let J=await H6(g,{appRoot:gN,entryFile:Pn});return P0(J)}catch(w){return P0({stdout:"",stderr:w instanceof Error?w.message:String(w),exitCode:1})}}try{let D=Hv(),w=new b6(D),g=jJ.find((j)=>j.name===I);if(g){let j=g.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await g.handler({corpContext:w},j.data);return{content:[{type:"text",text:typeof G==="string"?G:JSON.stringify(G,null,2)}]}}let J=LJ.find((j)=>j.name===I);if(J){let j=J.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await J.handler({corpContext:w},j.data);return{content:[{type:"text",text:typeof G==="string"?G:JSON.stringify(G,null,2)}]}}let X=w.getCurrent();if(!X)return{content:[{type:"text",text:"未配置企业,请先调用 auth login 登录或 auth import 导入凭证"}],isError:!0};let O=GJ.find((j)=>j.name===I);if(O){let j=O.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await x$(X),{client:N}=await ei(X),L=await O.handler({corp:X,ekbClient:G,easoClient:N},j.data);return{content:[{type:"text",text:typeof L==="string"?L:JSON.stringify(L,null,2)}]}}return{content:[{type:"text",text:`未知工具: ${I}。在单工具网关模式下,请通过 ${tJ} 调用。`}],isError:!0}}catch(D){return pM(D)}}),u}async function eM(){let $=aM(),i=new hW;await $.connect(i),console.error(`hose-use MCP Server (v${E}) running on stdio [mode: ${WN()}]`)}async function sM(){let $=await H6(process.argv.slice(3),{appRoot:gN,entryFile:Pn});if($.stdout)process.stdout.write($.stdout);if($.stderr)process.stderr.write(`${$.stderr}${$.stderr.endsWith(`
|
||||
`)?"":`
|
||||
`}`);process.exitCode=$.exitCode}var $k=Boolean(_J.main==_J.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&wN(process.argv[1])===wN(Pn));if($k)if(process.argv[2]==="--hose-use-cli"||process.argv[2]==="--hose-cli")await sM();else eM().catch(($)=>{console.error($),process.exitCode=1});export{kJ as tokenizeCommand,eM as startServer,WN as resolveMcpMode,dM as resolveMcpEnabled,TJ as normalizeCliArgs,aM as createServer,P0 as cliResult,mM as HOSE_MCP_MODE_ENV,oM as HOSE_MCP_ENABLED_ENV,tJ as HOSE_CLI_TOOL_NAME};
|
||||
Vendored
+1152
File diff suppressed because it is too large.
Load diff
Vendored
+1501
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.5.0
|
||||
version: 0.7.1
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+7
-3
@@ -1,14 +1,15 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.5.0",
|
||||
"version": "0.7.1",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"hose-use": "src/cli.ts",
|
||||
"hose": "src/cli.ts"
|
||||
"hose-aipro": "src/cli.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"cli": "bun run src/cli.ts",
|
||||
"aipro": "bun run src/aipro-cli.ts",
|
||||
"probe": "bun run src/cli.ts probe",
|
||||
"check": "tsc --noEmit",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -18,17 +19,20 @@
|
||||
"openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts",
|
||||
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
|
||||
"build:binary": "node scripts/build-binary.mjs",
|
||||
"build:plugin": "node scripts/build-plugin.mjs",
|
||||
"dev": "bun run --watch src/server.ts",
|
||||
"start": "bun run src/server.ts",
|
||||
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -29,17 +29,27 @@ if (isAll) {
|
||||
}
|
||||
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
|
||||
} else {
|
||||
const output = resolve(root, "dist/bin/hose-use");
|
||||
buildTarget("host", null, output);
|
||||
const outputHose = resolve(root, "dist/bin/hose-use");
|
||||
buildTarget("host", null, outputHose, "src/cli.ts");
|
||||
|
||||
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
|
||||
const outputAipro = resolve(root, "dist/bin/hose-aipro");
|
||||
try {
|
||||
if (existsSync(outputAipro)) unlinkSync(outputAipro);
|
||||
symlinkSync("hose-use", outputAipro);
|
||||
console.log(`[build:binary] created multicall symlink: ${outputAipro} -> hose-use`);
|
||||
} catch {
|
||||
// 忽略软链接异常
|
||||
}
|
||||
}
|
||||
|
||||
function buildTarget(name, bunTarget, output) {
|
||||
function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
|
||||
mkdirSync(dirname(output), { recursive: true });
|
||||
const buildArgs = ["build", "--compile"];
|
||||
if (bunTarget) {
|
||||
buildArgs.push(`--target=${bunTarget}`);
|
||||
}
|
||||
buildArgs.push("--outfile", output, "src/cli.ts");
|
||||
buildArgs.push("--outfile", output, entry);
|
||||
|
||||
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
|
||||
run(bun, buildArgs);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const bun = process.env.BUN_BIN || "bun";
|
||||
|
||||
function run(args) {
|
||||
const result = spawnSync(bun, args, {
|
||||
cwd: root,
|
||||
stdio: "inherit",
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${bun} ${args.join(" ")} failed with status ${result.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
const mcpOutput = resolve(root, "dist/mcp/server.js");
|
||||
mkdirSync(dirname(mcpOutput), { recursive: true });
|
||||
run(["build", "src/server.ts", "--minify", "--target=node", "--outfile", mcpOutput]);
|
||||
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
|
||||
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
|
||||
@@ -63,6 +63,15 @@ if (existsSync(openapiPath)) {
|
||||
console.log("✓ Updated openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 5.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 6. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
|
||||
+3
-1
@@ -152,9 +152,10 @@ fi
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
|
||||
# Also create 'hose' symlink if possible
|
||||
# Create command aliases pointing at the same single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose" 2>/dev/null || true
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Ad-hoc sign on macOS
|
||||
@@ -177,4 +178,5 @@ 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 ""
|
||||
+109
-176
@@ -1,205 +1,138 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底层 SDK。支持多账号纯 API 登录、30天 Token 自动无感续杯、多企业租户管理、有状态/无状态模式切换、自建应用扫描与跨应用工作流聚合检索。
|
||||
description: "v0.7.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
metadata:
|
||||
version: 0.7.1
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.1)
|
||||
---
|
||||
|
||||
# hose-use (合思/易快报企业级 CLI 与底层 SDK)
|
||||
# hose-use (v0.7.1)
|
||||
|
||||
`hose-use` 是面向合思/易快报 SaaS、开发者与 AI 智能体的高性能交互工具。
|
||||
|
||||
## 核心架构原则
|
||||
|
||||
- **纯 API 认证**:内置 RSA PKCS#1 密码加密与统一认证中心握手,无需浏览器滑块即可登录。
|
||||
- **全自动无感续杯**:内置 401 拦截与预检换票机制,Token 到期自动刷新并重试,零人工介入。
|
||||
- **多账号与多身份分层**:支持一个手机号管理 13+ 家企业;支持同一企业下多身份(`corpId@accountId`)共存。
|
||||
- **有状态 / 无状态双模式**:
|
||||
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
|
||||
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
|
||||
- **MCP 单工具网关架构**:统一暴露 `hose_cli` 工具,避免数十个细粒度工具膨胀污染 Agent 的上下文,零子进程同构执行。
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
---
|
||||
|
||||
## 调用通道与执行协议
|
||||
## Agent 执行原则 (First Rules)
|
||||
|
||||
`hose-use` 同时支持 **MCP 工具** 与 **Shell CLI** 两种调用通道:
|
||||
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
|
||||
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
|
||||
3. **输出防护与大报文处理**:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
|
||||
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
|
||||
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
|
||||
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
|
||||
|
||||
- **MCP 工具通道 (AI Agent 优先推荐)**:在具备 MCP 的智能体环境中,优先调用 `hose_cli` 工具网关:
|
||||
```json
|
||||
{
|
||||
"command": "corps list"
|
||||
}
|
||||
```
|
||||
或者执行业务检索:
|
||||
```json
|
||||
{
|
||||
"command": "bill query --code BX20260901001 --corp ID01MCcOgJl1td"
|
||||
}
|
||||
```
|
||||
- **Shell CLI 通道 (运维/终端/脚本)**:在终端或子进程环境中,直接执行:
|
||||
```bash
|
||||
hose corps list
|
||||
# 或
|
||||
hose-use bill query --code BX20260901001
|
||||
```
|
||||
---
|
||||
|
||||
## 意图路由导航 (Route By Intent)
|
||||
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose auth login`, `hose auth status`, `hose auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据关联关系 / 冲借款与前置申请追溯 | `hose bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件下载 | `hose bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
|
||||
| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) |
|
||||
| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose task todo`, `hose task submitted`, `hose task records`, `hose task cc` | [references/task.md](references/task.md) |
|
||||
| 消息中心 / 未读统计 / 标记已读 / 类型过滤 | `hose message list [--all]`, `hose message count`, `hose message read` | [references/message.md](references/message.md) |
|
||||
| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
|
||||
| 待办/消息事件轮询与去重 | `hose service poll --corp=<id>` | [references/service.md](references/service.md) |
|
||||
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
|
||||
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
|
||||
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) |
|
||||
| 一键自动自更新 / 查看版本发布日志 | `hose update`, `hose update --changelog` | `hose update --help` |
|
||||
|
||||
---
|
||||
|
||||
## 常用命令速查
|
||||
|
||||
### 1. 认证管理 (`hose-use auth`)
|
||||
|
||||
```bash
|
||||
# 纯 API 账密全自动登录(自动获取 RSA 公钥加密并拉取旗下所有企业)
|
||||
hose-use auth login --phone=17718556446 --password=...
|
||||
# 1. 认证与企业
|
||||
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
|
||||
hose auth status # 查看 Token 剩余有效期与登录账号
|
||||
hose corps list # 查看企业租户列表
|
||||
hose corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose probe # 诊断当前企业接口连通性
|
||||
|
||||
# 导入 F12 抓包复制的 cURL 或 Request Headers
|
||||
hose-use auth import --raw="curl ..."
|
||||
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
|
||||
hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话
|
||||
hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
|
||||
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
|
||||
|
||||
# 查看当前登录状态与活跃账号
|
||||
hose-use auth status
|
||||
# 3. 单据与费用
|
||||
hose bill list # 查看最新单据与报销记录
|
||||
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||
hose bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||
hose bill approve S26000001 --yes # 同意当前待办
|
||||
hose bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因
|
||||
hose bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
|
||||
hose bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
|
||||
hose bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
|
||||
hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
|
||||
hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose bill attachments S26000001 # 查看附件和发票原件列表
|
||||
hose bill download S26000001 --output-dir ./downloads # 下载附件到本地目录
|
||||
hose dimension list # 查看系统与自定义档案维度
|
||||
hose dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose role list # 查看企业角色定义
|
||||
hose role groups # 查看角色组及其角色
|
||||
hose role members 财务主管 # 查看指定角色成员
|
||||
hose permission get # 查看角色权限开关(只读)
|
||||
hose bill schema # 查询单据实体元数据字典
|
||||
|
||||
# 一键批量刷新名下所有企业的最新 30 天 AccessToken
|
||||
hose-use auth refresh
|
||||
# 4. 待办与消息
|
||||
hose task submitted # 查看我发起的单据
|
||||
hose message list --unread # 查看未读消息
|
||||
hose message list --all # 合并查看已读和未读消息
|
||||
hose message count # 查看未读数量
|
||||
hose message read <messageId> # 标记单条消息已读
|
||||
|
||||
# 查看已保存的全部主账号
|
||||
hose-use auth accounts
|
||||
```
|
||||
# 5. 自建应用与工作流
|
||||
hose platform list # 查看自建应用列表
|
||||
hose workflow list # 聚合扫描全部应用下的工作流
|
||||
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
|
||||
### 2. 多企业租户管理 (`hose-use corps`)
|
||||
|
||||
```bash
|
||||
# 列出名下所有已授权企业
|
||||
hose-use corps list
|
||||
|
||||
# 切换当前工作企业 (有状态模式下自动持久化)
|
||||
hose-use corps switch uzU7pcWfScck00
|
||||
|
||||
# 查看当前激活企业信息
|
||||
hose-use corps current
|
||||
```
|
||||
|
||||
### 3. 全局运行模式 (`hose-use config`)
|
||||
|
||||
```bash
|
||||
# 查看全局运行模式与配置文件路径
|
||||
hose-use config show
|
||||
|
||||
# 查看多级企业目录发现路径与诊断
|
||||
hose-use config paths
|
||||
|
||||
# 切换为无状态模式 (Stateless)
|
||||
hose-use config mode stateless
|
||||
|
||||
# 切换为有状态模式 (Stateful)
|
||||
hose-use config mode stateful
|
||||
```
|
||||
|
||||
### 4. 平台与工作流管理 (`hose-use workflow` / `hose-use platform`)
|
||||
|
||||
```bash
|
||||
# 汇总查看企业下所有工作流 (跨自建应用聚合)
|
||||
hose-use workflow list
|
||||
|
||||
# 查看指定工作流详情与节点结构
|
||||
hose-use workflow get 829729467412037634
|
||||
|
||||
# 搜索包含指定节点类型的工作流 (如 code-js2, http 等)
|
||||
hose-use workflow find --task=code-js2
|
||||
|
||||
# 启用 / 停用工作流 (1: 启用, 0: 停用)
|
||||
hose-use workflow toggle <pipelineId> --state=1
|
||||
|
||||
# 查看企业下所有启用的自建应用
|
||||
hose-use platform list
|
||||
```
|
||||
|
||||
### 5. 单据与费用明细检索 (`hose-use bill`)
|
||||
|
||||
```bash
|
||||
# 查看企业单据与报销列表 (支持分页/阶段/状态过滤)
|
||||
hose-use bill list
|
||||
hose-use bill list --stage=expense --state=paid --count=10
|
||||
|
||||
# 大数据量防爆落盘: 使用 -o / --output-file 将完整 JSON 转储至本地文件 (推荐 Agent 处理海量数据时使用)
|
||||
hose-use bill list --json -o /tmp/bills.json
|
||||
# 确需向终端输出完整大报文时附加 --full (跳过 200KB 防爆限制)
|
||||
hose-use bill list --json --full
|
||||
|
||||
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
||||
hose-use bill get n0GMIM0dkQmKbS
|
||||
hose-use bill get ID01TRzg7HMLcb
|
||||
|
||||
# 查看企业全部单据实体与数据模型字典
|
||||
hose-use bill schema
|
||||
```
|
||||
|
||||
### 6. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
|
||||
|
||||
```bash
|
||||
# 连通性与 EASO 平台鉴权诊断
|
||||
hose-use probe
|
||||
hose-use probe --corp=uzU7pcWfScck00
|
||||
|
||||
# 启动极简 MCP stdio 服务
|
||||
hose-use mcp serve
|
||||
```
|
||||
|
||||
### 7. OpenAPI 规范导出 (`hose-use openapi`)
|
||||
|
||||
```bash
|
||||
# 查看包装层 API 路径与概要一览
|
||||
hose-use openapi paths
|
||||
|
||||
# 查看合思原生下游全量 API 路径
|
||||
hose-use openapi --raw paths
|
||||
|
||||
# 查看 OpenAPI 规范元数据概览
|
||||
hose-use openapi info
|
||||
|
||||
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Agent)
|
||||
hose-use openapi
|
||||
|
||||
# 输出原生下游全量 OpenAPI 3.1.0 JSON
|
||||
hose-use openapi --raw
|
||||
```
|
||||
|
||||
### 8. HTTP 服务与常驻守护进程 (`hose-use http` / `hose-use service`)
|
||||
|
||||
```bash
|
||||
# 启动本地轻量 HTTP 服务并打开 Scalar 交互式文档 (http://127.0.0.1:8888/docs)
|
||||
hose-use http --port=8888
|
||||
|
||||
# 后台启动常驻守护进程服务
|
||||
hose-use service start
|
||||
|
||||
# 查看常驻守护进程运行状态与端点
|
||||
hose-use service status
|
||||
|
||||
# 查看常驻守护进程最近运行日志
|
||||
hose-use service logs
|
||||
|
||||
# 停止后台常驻守护进程
|
||||
hose-use service stop
|
||||
```
|
||||
|
||||
### 9. 自更新与版本历史 (`hose-use update`)
|
||||
|
||||
```bash
|
||||
# 检查最新可用版本与 Release Notes
|
||||
hose-use update --check
|
||||
|
||||
# 一键自动下载并升级到最新版本(多源 CDN 加速 + 自动同步 Agent 技能)
|
||||
hose-use update
|
||||
|
||||
# 查看最近版本发布历史与更新说明
|
||||
hose-use update --changelog
|
||||
# 6. 服务与守护进程
|
||||
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
hose service start # 后台启动常驻守护进程服务
|
||||
hose service status # 查看常驻守护进程运行状态与端点
|
||||
hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
|
||||
hose service logs # 查看常驻守护进程日志
|
||||
hose service stop # 停止后台常驻守护进程
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 全局选项
|
||||
|
||||
- `--corp=<id>`:临时指定操作的企业/身份 ID
|
||||
- `--json`, `-j`:输出 JSON 结构化格式(适合脚本解析)
|
||||
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
|
||||
- `--json`, `-j`:以标准 JSON 结构化输出结果
|
||||
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
|
||||
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
|
||||
- `--stateless`:单次命令强制以无状态模式执行
|
||||
- `--stateful`:单次命令强制以有状态模式执行
|
||||
- `--help, -h`:查看命令帮助与参数说明
|
||||
@@ -0,0 +1,16 @@
|
||||
schema_version: "v1"
|
||||
name: "hose-use"
|
||||
description: "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业多租户切换、单据明细检索、自建应用工作流管理、内置 HTTP 服务与常驻守护进程。"
|
||||
auth:
|
||||
type: "none"
|
||||
tools:
|
||||
- name: "hose_cli"
|
||||
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
|
||||
parameters:
|
||||
type: "object"
|
||||
properties:
|
||||
command:
|
||||
type: "string"
|
||||
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
|
||||
required:
|
||||
- "command"
|
||||
@@ -0,0 +1,111 @@
|
||||
# 认证、多租户与运行模式指南 (Authentication & Multi-Tenant Guide)
|
||||
|
||||
本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。
|
||||
|
||||
---
|
||||
|
||||
## 1. 账号认证与登录 (`auth`)
|
||||
|
||||
`hose-use` 实现了**纯 API 级 RSA 密码加密登录**,无需通过浏览器抓包或人工复制 Cookie。
|
||||
|
||||
### 纯 API 账密自动登录
|
||||
```bash
|
||||
# 自动通过公钥加密密码,登录并拉取名下全部企业凭据写入本地配置
|
||||
hose-use auth login --phone=17718556446 --password=YourPassword123
|
||||
```
|
||||
- **核心逻辑**:向合思主站请求 RSA 公钥,将密码密文提交到 `/api/auth/login`;成功后自动遍历用户关联的企业租户,调用换票接口写入对应的企业配置。
|
||||
|
||||
### 查看登录状态与 Token 有效期
|
||||
```bash
|
||||
hose-use auth status
|
||||
```
|
||||
- 自动计算并输出自然语言剩余有效期(如 `29天23小时后过期`),清晰展示当前账号与当前企业。
|
||||
|
||||
### 30 天无感 Token 刷新
|
||||
```bash
|
||||
hose-use auth refresh
|
||||
```
|
||||
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
hose-use auth import \
|
||||
--name="CSM代客" \
|
||||
--corp-id="Cxa3oOtQi2eS$g" \
|
||||
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
|
||||
```
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。
|
||||
|
||||
### 多账号清单
|
||||
```bash
|
||||
hose-use auth accounts
|
||||
```
|
||||
- 查看本地已记录的手机号多账号清单及其关联的企业列表。
|
||||
|
||||
---
|
||||
|
||||
## 2. 企业租户管理 (`corps`)
|
||||
|
||||
### 列出所有企业
|
||||
```bash
|
||||
hose-use corps list
|
||||
hose-use corps list --json
|
||||
```
|
||||
|
||||
### 切换当前活跃企业
|
||||
```bash
|
||||
hose-use corps switch uzU7pcWfScck00
|
||||
```
|
||||
- 在有状态(stateful)模式下,此命令将更新全局默认企业 ID。
|
||||
|
||||
### 查看当前企业
|
||||
```bash
|
||||
hose-use corps current
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 全局配置与模式管理 (`config`)
|
||||
|
||||
### 运行模式(有状态 vs 无状态)
|
||||
- **有状态模式 (Stateful,默认)**:
|
||||
- 会话状态保存在 `~/.config/hose-use/config.json` 中;
|
||||
- 执行 `corps switch` 后,后续命令自动继承当前选中的企业。
|
||||
- **无状态模式 (Stateless,推荐给 Agent)**:
|
||||
- 不依赖全局状态切换,所有命令通过 `--corp=<id>` 显式指定,防止并发操作相互干扰;
|
||||
- 通过环境变量 `HOSE_STATELESS=1` 或单次参数 `--stateless` 开启。
|
||||
|
||||
```bash
|
||||
# 查看当前配置
|
||||
hose-use config show
|
||||
|
||||
# 查看多层级配置发现路径诊断
|
||||
hose-use config paths
|
||||
|
||||
# 切换全局运行模式
|
||||
hose-use config mode stateless
|
||||
hose-use config mode stateful
|
||||
```
|
||||
|
||||
### 多层级配置发现顺序
|
||||
1. 环境变量 `HOSE_ENTERPRISES_DIR`(最高优先级)
|
||||
2. 当前工作区根目录下的 `enterprises/`
|
||||
3. 用户主目录配置:`~/.config/hose-use/enterprises/`
|
||||
4. 历史兼容缓存:`~/.cache/ekb-mcp/enterprises/`
|
||||
|
||||
---
|
||||
|
||||
## 4. 连通性探针 (`probe`)
|
||||
|
||||
```bash
|
||||
# 诊断当前企业的鉴权链路与平台可用性
|
||||
hose-use probe
|
||||
|
||||
# 诊断指定企业的连通性
|
||||
hose-use probe --corp=uzU7pcWfScck00
|
||||
```
|
||||
- **探针行为**:
|
||||
1. 验证主站 Session 是否有效;
|
||||
2. 测试 EASO 平台 SSO 握手是否成功;
|
||||
3. 输出各环节毫秒级延迟与 HTTP 状态。
|
||||
@@ -0,0 +1,185 @@
|
||||
# 单据与费用明细指南 (Bill & Expense Guide)
|
||||
|
||||
本参考专卷详细说明合思单据检索、费用报销明细下钻、中文标签映射字典以及大报文防爆机制。
|
||||
|
||||
---
|
||||
|
||||
## 1. 单据列表检索 (`bill list`)
|
||||
|
||||
### 基础查询
|
||||
```bash
|
||||
# 查看当前企业最近的单据与报销列表 (默认表格格式)
|
||||
hose-use bill list
|
||||
|
||||
# 指定企业查询并以 JSON 输出
|
||||
hose-use bill list --corp=uzU7pcWfScck00 --json
|
||||
```
|
||||
|
||||
### 过滤选项
|
||||
- `--type=<type>`:按单据大类过滤(如 `TRAVEL_EXPENSE` 差旅报销、`DAILY_EXPENSE` 日常报销、`BORROW` 借款申请、`LOAN` 借款申请等);
|
||||
- `--status=<status>`:按审批状态过滤(如 `APPROVED` 审批完成、`PROCESSING` 审批中、`REJECTED` 已驳回、`DRAFT` 草稿等);
|
||||
- `--limit=<number>`:单页数量(默认 20,最大 100);
|
||||
- `--page=<number>`:分页页码(默认 1)。
|
||||
|
||||
```bash
|
||||
# 查询审批通过的差旅报销单
|
||||
hose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 单据详情精准下钻 (`bill get`)
|
||||
|
||||
支持传入**单据编号**(如 `CL20260903001`)或合思全局**单据 ID**(如 `n0GMIM0dkQmKbS`):
|
||||
|
||||
```bash
|
||||
hose-use bill get n0GMIM0dkQmKbS
|
||||
hose-use bill get CL20260903001 --json
|
||||
hose-use bill flow CL20260903001
|
||||
```
|
||||
|
||||
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
|
||||
|
||||
```bash
|
||||
hose bill get S26000001 --risk
|
||||
hose bill get S26000001 --risk --json
|
||||
```
|
||||
|
||||
### 中文字段智能映射字典
|
||||
合思底层原生单据接口通常返回类似 `c0_1`, `d1_4`, `u_fee_amount` 等混淆字段。
|
||||
`hose-use` 内置**动态中文 Label 字典转换引擎**:
|
||||
- 自动提取单据所属模板的中文配置定义;
|
||||
- 将 `c0_1` 翻译为清晰的 `费用发生日期`;
|
||||
- 将 `d1_4` 翻译为 `费用类型/科目`;
|
||||
- 将 `u_fee_amount` 翻译为 `报销金额`;
|
||||
- 向 AI 与用户同时提供规范化的结构体与原始值对照。
|
||||
|
||||
---
|
||||
|
||||
## 3. 单据审批流程 (`bill flow`)
|
||||
|
||||
读取单据右侧审批流程面板的真实业务接口,输出历史流转日志、处理人、审批意见、节点停留时长、自动跳过标记、当前节点和后续节点;使用 `--json` 可获得结构化时间线。
|
||||
|
||||
```bash
|
||||
hose-use bill flow CL20260903001
|
||||
hose-use bill flow CL20260903001 --json
|
||||
hose-use bill risk CL20260903001
|
||||
```
|
||||
|
||||
`bill risk` 聚合审批页“审查”面板的风控预警、信用规则、预算状态与发票风险接口;默认只输出摘要,`--json` 保留结构化原始结果。
|
||||
|
||||
## 4. 单据审批动作套件
|
||||
|
||||
审批动作直接复用合思 Web 点击时的业务接口。写操作必须显式带 `--yes`;交互终端未带该参数时会进行二次确认,非交互终端会直接拒绝,避免脚本误写业务状态。
|
||||
|
||||
```bash
|
||||
# 同意:可附带纯文本审批意见
|
||||
hose bill approve S26000001 --comment "同意" --yes
|
||||
|
||||
# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标
|
||||
hose bill reject S26000001 --comment "请补充发票" --yes
|
||||
|
||||
# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名
|
||||
hose bill transfer S26000001 --approver-id 111 --yes
|
||||
|
||||
# 加签:默认前加签,--mode post 表示后加签
|
||||
hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
|
||||
|
||||
# 评论:支持 --participants 传入逗号分隔的人员 ID
|
||||
hose bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
|
||||
```
|
||||
|
||||
动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。
|
||||
|
||||
### 单据引用 ID 二级解析 (`bill refs`)
|
||||
|
||||
读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID:
|
||||
|
||||
```bash
|
||||
hose bill refs S26000001
|
||||
hose bill refs S26000001 --json
|
||||
```
|
||||
|
||||
JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。
|
||||
|
||||
### 单据关联链 (`bill relations`)
|
||||
|
||||
从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树:
|
||||
|
||||
```bash
|
||||
hose bill relations S26000001
|
||||
hose bill relations S26000001 --json
|
||||
```
|
||||
|
||||
表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。
|
||||
|
||||
### 单据预算状态 (`bill budget`)
|
||||
|
||||
读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段:
|
||||
|
||||
```bash
|
||||
hose bill budget S26000001
|
||||
hose bill budget S26000001 --json
|
||||
```
|
||||
|
||||
### 单据附件列表 (`bill attachments`)
|
||||
|
||||
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
|
||||
|
||||
```bash
|
||||
hose bill attachments S26000001
|
||||
hose bill attachments S26000001 --json
|
||||
```
|
||||
|
||||
需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件:
|
||||
|
||||
```bash
|
||||
hose bill download S26000001 --output-dir ./downloads
|
||||
hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
|
||||
```
|
||||
|
||||
## 5. 单据实体元数据字典 (`bill schema`)
|
||||
|
||||
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
|
||||
|
||||
```bash
|
||||
hose-use bill schema
|
||||
hose-use bill schema --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 上下文防爆保护与安全转储
|
||||
|
||||
合思复杂的报销单通常携带大量明细行、发票 OCR 原生报文与附件列表,查询结果动辄数万行(几百 KB 到数 MB)。
|
||||
|
||||
### 默认 200KB 体积熔断保护
|
||||
在未附加放行参数时,若序列化报文超过 200,000 字节,`hose-use` 会自动阻断并返回防御提示:
|
||||
```text
|
||||
[Output Protected] 输出内容超过 200KB 体积保护阈值 (284,520 bytes)。
|
||||
为防止过大输出打爆 AI 智能体上下文窗口,建议使用:
|
||||
-o, --output-file <path> 将全量结果保存至本地文件
|
||||
--full 强制全量输出
|
||||
```
|
||||
|
||||
### 本地安全转储 (`--output-file` / `-o`)
|
||||
将巨型报文直接直写到磁盘,终端/AI 仅输出轻量摘要:
|
||||
```bash
|
||||
hose-use bill list --json -o /tmp/bills_full.json
|
||||
```
|
||||
**返回摘要**:
|
||||
```json
|
||||
{
|
||||
"outputFile": "/tmp/bills_full.json",
|
||||
"bytes": 284520
|
||||
}
|
||||
```
|
||||
|
||||
### 强制全量放行 (`--full`)
|
||||
明确需要捕获全部 stdout 时添加 `--full`:
|
||||
```bash
|
||||
hose-use bill list --json --full
|
||||
```
|
||||
|
||||
### 全链路敏感信息脱敏
|
||||
输出流中的 `accessToken`、`token`、`Bearer` 以及密码、秘钥等均由底层的 `redactSensitiveText` 自动清洗过滤,保障会话与调用日志安全。
|
||||
@@ -0,0 +1,65 @@
|
||||
# hose-use 专卷:企业通讯录与人员档案 (Contact Domain)
|
||||
|
||||
本文件是 `skills/hose-use/` 的领域参考专卷,详述合思/易快报企业通讯录的人员检索、防爆保护机制与单人档案下钻。
|
||||
|
||||
---
|
||||
|
||||
## 核心设计与防爆原则
|
||||
|
||||
企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**
|
||||
|
||||
因此,`hose-use` 遵循以下防爆安全原则:
|
||||
1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
|
||||
2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
|
||||
3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;
|
||||
4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。
|
||||
|
||||
---
|
||||
|
||||
## CLI 命令速查
|
||||
|
||||
```bash
|
||||
# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)
|
||||
hose contact search 王硕
|
||||
hose contact search xiezihao@hosecloud.com
|
||||
hose contact search 18600612659
|
||||
|
||||
# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)
|
||||
hose contact list
|
||||
hose contact list --limit=50
|
||||
|
||||
# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)
|
||||
hose contact list --json -o /tmp/all_staffs.json
|
||||
|
||||
# 4. 精确下钻查看指定人员详细档案
|
||||
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000
|
||||
|
||||
# 5. 指定特定企业租户检索
|
||||
hose contact search 李 --corp=ID01MCcOgJl1td
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP 工具调用
|
||||
|
||||
在单工具网关模式下,推荐使用 `hose_cli` 触发:
|
||||
```json
|
||||
{
|
||||
"command": "contact search 王硕"
|
||||
}
|
||||
```
|
||||
|
||||
在全量模式(`HOSE_MCP_MODE=all`)下,提供以下细粒度工具:
|
||||
- `contact_search(keyword: string, limit?: number)`:返回匹配的员工列表
|
||||
- `contact_get(staffId: string)`:获取单条员工详情
|
||||
- `contact_list(limit?: number, allowFull?: boolean)`:带保护的企业通讯录列表
|
||||
|
||||
---
|
||||
|
||||
## 业务联动典型场景
|
||||
|
||||
### 1. 查找某人发起的单据
|
||||
当用户要求“帮我查一下王硕提交的报销单”时:
|
||||
1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
|
||||
2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
|
||||
3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。
|
||||
@@ -0,0 +1,15 @@
|
||||
# 自定义档案与核算维度
|
||||
|
||||
合思前端“系统配置 → 档案设置 → 扩展档案 → 自定义档案”对应 CLI 的 `dimension` 域。
|
||||
|
||||
```bash
|
||||
# 查看系统/自定义档案维度目录
|
||||
hose dimension list
|
||||
hose dimension list --keyword=项目
|
||||
|
||||
# 查看某个维度的档案项(支持维度 ID、编码或名称)
|
||||
hose dimension items 项目
|
||||
hose dimension items DA001 --json
|
||||
```
|
||||
|
||||
目录来源于 `/api/v1/basedata/dimensions/active`,档案项来源于 `/api/v1/basedata/dimensionItems/$<dimensionId>`。结果在同一进程内按企业缓存 10 分钟,JSON 会保留底层 ID、编码、父项 ID 和表单字段。
|
||||
@@ -0,0 +1,15 @@
|
||||
# 消息中心
|
||||
|
||||
消息中心是 CLI-only 能力,不新增 MCP tool。命令默认查询未读消息。
|
||||
|
||||
```bash
|
||||
hose message list --unread
|
||||
hose message list --read
|
||||
hose message list --all
|
||||
hose message list --type=Approve
|
||||
hose message count
|
||||
hose message read <messageId>
|
||||
hose message read-all
|
||||
```
|
||||
|
||||
`message list --json` 返回消息 ID、标题、内容、消息类型、已读状态和原始字段;`--all` 会并行拉取已读与未读页面并去重后按时间排序;`--type` 在 CLI 层按 `messageType`、`msgType`、`msgTypeName` 或 `msgName` 做兼容过滤。`message read-all` 会分页读取全部未读消息再逐条标记,避免只处理首 100 条。
|
||||
@@ -0,0 +1,20 @@
|
||||
# 角色与角色组
|
||||
|
||||
角色页对应的只读 CLI:
|
||||
|
||||
```bash
|
||||
hose role list
|
||||
hose role list --keyword=财务
|
||||
hose role groups
|
||||
hose role members 财务主管
|
||||
hose role members CODE15 --json
|
||||
```
|
||||
|
||||
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
|
||||
|
||||
权限页的角色权限快照:
|
||||
|
||||
```bash
|
||||
hose permission get
|
||||
hose permission get --json
|
||||
```
|
||||
@@ -0,0 +1,114 @@
|
||||
# 服务、守护进程与 API 网关指南 (Service & HTTP Gateway Guide)
|
||||
|
||||
本参考专卷详细说明 `hose-use` 内置的轻量 HTTP Server、常驻 Service 守护进程、Scalar 交互式文档以及 OpenAPI 规范导出能力。
|
||||
|
||||
---
|
||||
|
||||
## 1. 常驻 Service 守护进程 (`service`)
|
||||
|
||||
常驻守护进程允许 `hose-use` 在后台全天候运行,支持远程/本地无子进程开销调用 CLI,同时持久化存储 PID 与运行日志。
|
||||
|
||||
### 常用指令
|
||||
```bash
|
||||
# 启动常驻后台守护进程 (自动落盘 PID 到 ~/.config/hose-use/service.pid)
|
||||
hose-use service start
|
||||
|
||||
# 检查常驻服务运行状态、PID、端口与访问端点
|
||||
hose-use service status
|
||||
|
||||
# 查看常驻服务最近运行日志
|
||||
hose-use service logs
|
||||
|
||||
# 重启常驻服务
|
||||
hose-use service restart
|
||||
|
||||
# 优雅停止常驻服务 (清理 PID 文件)
|
||||
hose-use service stop
|
||||
|
||||
# 容器/前台守护运行模式 (供 Dockerfile 或 Supervisor 使用)
|
||||
hose-use service run
|
||||
```
|
||||
|
||||
### 自愈保护机制
|
||||
每次执行 `service status` 或 `service start` 时,系统会自动探测记录的 PID:
|
||||
- 若进程已终止(孤儿 PID)或 PID 被其它非 `hose` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
|
||||
|
||||
### 事件轮询与去重 (`service poll`)
|
||||
|
||||
单次读取待办和未读消息,按事件 ID 写入 `~/.config/hose-use/events-<corpId>.json`,重复轮询不会重复返回已观察事件:
|
||||
|
||||
```bash
|
||||
hose-use service poll --corp=<corpId>
|
||||
hose-use service poll --corp=<corpId> --limit=100 --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 前台 HTTP 服务 (`http` / `serve`)
|
||||
|
||||
在当前终端前台启动 HTTP 服务并输出直观的服务信息面板,按 `Ctrl+C` 即可平滑退出:
|
||||
|
||||
```bash
|
||||
# 启动本地 HTTP 服务 (默认端口 8888,主机 127.0.0.1)
|
||||
hose-use http
|
||||
|
||||
# 指定自定义端口与主机
|
||||
hose-use http --port=9999 --host=0.0.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. HTTP 路由端点一览
|
||||
|
||||
| 方法 | 端点 | 说明 |
|
||||
|---|---|---|
|
||||
| `GET` | `/` | 服务元信息、版本号与端点导航 |
|
||||
| `GET` | `/health` | 存活健康探针(返回 `{ "status": "ok", "version": "..." }`) |
|
||||
| `GET` | `/docs` | 基于 **Scalar API Reference** 的沉浸式交互文档界面 |
|
||||
| `GET` | `/openapi.json` | 包装层标准 OpenAPI 3.1.0 JSON 规范 |
|
||||
| `GET` | `/raw-openapi.json` | 合思原生下游 OpenAPI 规范 |
|
||||
| `POST` | `/api/cli` | **CLI 同进程执行网关**(免 spawn 子进程) |
|
||||
| `GET` | `/v1/corps` | RESTful 风格企业租户列表与运行模式 |
|
||||
|
||||
### 同进程 CLI 执行网关 (`POST /api/cli`)
|
||||
通过 HTTP POST 提交任意 CLI 命令字符串,在主服务进程内部直接分发执行,毫秒级响应,无需拉起 Node/Bun 子进程:
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:8888/api/cli \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"command": "corps list --json"}'
|
||||
```
|
||||
|
||||
**响应结构**:
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"stdout": "...",
|
||||
"stderr": "",
|
||||
"exitCode": 0,
|
||||
"data": {
|
||||
"corporations": [ ... ]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. OpenAPI 规范导出 (`openapi`)
|
||||
|
||||
```bash
|
||||
# 查看所有 API 路径与概要一览
|
||||
hose-use openapi paths
|
||||
|
||||
# 查看合思原生下游全量 API 路径
|
||||
hose-use openapi --raw paths
|
||||
|
||||
# 查看 OpenAPI 规范元数据概览
|
||||
hose-use openapi info
|
||||
|
||||
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Apifox)
|
||||
hose-use openapi
|
||||
|
||||
# 输出原生下游全量 OpenAPI 3.1.0 JSON
|
||||
hose-use openapi --raw
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# hose-use 专卷:待办中心与审批任务
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
hose task todo # 待我审批
|
||||
hose task approved # 我已审批
|
||||
hose task records # 审批记录
|
||||
hose task submitted # 我发起的单据
|
||||
hose task cc --unread # 未读抄送
|
||||
hose task cc --read # 已读抄送
|
||||
hose task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤
|
||||
hose task todo --json --count 50
|
||||
hose task records --from 2026-01-01 --to 2026-09-05
|
||||
```
|
||||
|
||||
任务结果包含任务 ID、流程 ID、单号、标题、单据模板、提交人、金额、状态、当前节点和可用动作。分页使用 `--start` 与 `--count`。
|
||||
|
||||
当前实现对接合思 Web 待办工作台实际使用的业务接口:待审批/审批记录走 `/api/flow/v2/backlogs/search`,已审批走 `/api/flow/v1/flows/approved`。接口响应的完整原始对象保留在 JSON 结果的 `raw` 字段中,便于后续接入“我发起的”和“抄送我的”视图。
|
||||
|
||||
当前只通过 CLI 暴露任务查询;MCP 不新增待办专用工具。
|
||||
@@ -0,0 +1,83 @@
|
||||
# 工作流与自建应用指南 (Workflow & Platform Guide)
|
||||
|
||||
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
|
||||
|
||||
---
|
||||
|
||||
## 1. 自建应用管理 (`platform`)
|
||||
|
||||
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
|
||||
|
||||
```bash
|
||||
# 列出当前企业下全部已开通的自建应用
|
||||
hose-use platform list
|
||||
hose-use platform list --json
|
||||
```
|
||||
|
||||
**输出关键字段**:
|
||||
- `appId`:应用全局唯一标识
|
||||
- `appName`:应用中文名称
|
||||
- `status`:应用运行状态(ENABLE / DISABLE)
|
||||
- `createdAt` / `updatedAt`:创建与最后更新时间
|
||||
|
||||
---
|
||||
|
||||
## 2. 跨应用工作流聚合检索 (`workflow list`)
|
||||
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
|
||||
|
||||
```bash
|
||||
# 查看所有自建应用下的全部工作流汇总
|
||||
hose-use workflow list
|
||||
|
||||
# 查看指定自建应用下的工作流
|
||||
hose-use workflow list --app-id=app_01j72x...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 工作流任务节点精准扫描 (`workflow find`)
|
||||
|
||||
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
|
||||
|
||||
```bash
|
||||
# 搜索包含自定义代码节点 (code-js2) 的所有工作流
|
||||
hose-use workflow find --task=code-js2
|
||||
|
||||
# 搜索包含飞书通知节点的工作流
|
||||
hose-use workflow find --task=feishu-notify
|
||||
|
||||
# 模糊搜索包含关键词的工作流
|
||||
hose-use workflow find --keyword="自动审批"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 工作流详情查询 (`workflow get`)
|
||||
|
||||
获取工作流的完整节点拓扑、参数配置与表达式定义:
|
||||
|
||||
```bash
|
||||
hose-use workflow get wf_01k83y...
|
||||
hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 工作流启用与关闭 (`workflow toggle`)
|
||||
|
||||
```bash
|
||||
# 激活/启用指定工作流
|
||||
hose-use workflow toggle wf_01k83y... --enable
|
||||
|
||||
# 停用指定工作流
|
||||
hose-use workflow toggle wf_01k83y... --disable
|
||||
```
|
||||
|
||||
## 6. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
```
|
||||
@@ -0,0 +1,450 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
|
||||
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
|
||||
import { initCorpRuntime } from "./cli/helpers.js";
|
||||
import { createEkbClient } from "./core/auth/ekb.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalRepository,
|
||||
ApprovalGatewayBlockedError,
|
||||
FindingCheckStatus,
|
||||
} from "./domains/approval/index.js";
|
||||
import { VERSION } from "./version.js";
|
||||
|
||||
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: stringOption(parsed.options, ["corp", "c"]),
|
||||
jsonMode: booleanOption(parsed.options, ["json"]),
|
||||
});
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
|
||||
|
||||
const positional: string[] = [];
|
||||
for (let i = 0; i < rawArgs.length; i++) {
|
||||
const arg = rawArgs[i];
|
||||
if (arg === "--") {
|
||||
positional.push(...rawArgs.slice(i + 1));
|
||||
break;
|
||||
}
|
||||
if (arg.startsWith("-")) {
|
||||
const eqIdx = arg.indexOf("=");
|
||||
if (eqIdx === -1) {
|
||||
const flagName = arg.replace(/^--?/, "").toLowerCase();
|
||||
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName);
|
||||
if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
|
||||
i++; // skip option value
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
positional.push(arg);
|
||||
}
|
||||
|
||||
const command = (positional[0] || "help").toLowerCase();
|
||||
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
const args = positional.slice(1);
|
||||
const corpId = corp?.corpId || corp?.id;
|
||||
const operator = corp?.staffId || corp?.name || "AI-Agent";
|
||||
|
||||
const requireCorpId = () => {
|
||||
if (!corpId) {
|
||||
throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
|
||||
}
|
||||
return corpId;
|
||||
};
|
||||
|
||||
const getClient = async () => {
|
||||
const activeCorpId = requireCorpId();
|
||||
if (!corp) throw new Error("未找到当前企业配置");
|
||||
client ??= await createEkbClient(corp);
|
||||
return { client, corpId: activeCorpId };
|
||||
};
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
// ── 1. 明细级规则注入(出审核要点清单)────────────────────────────────
|
||||
case "points":
|
||||
case "inject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro points <单号> [--scope <1|场景>]");
|
||||
}
|
||||
|
||||
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
|
||||
const context = await getClient();
|
||||
const result = await service.injectAuditPoints(context.client, context.corpId, targetSn, {
|
||||
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "points",
|
||||
documentSn: result.bill.billCode,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: "PENDING",
|
||||
summary: `注入审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
|
||||
const rows = result.findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus,
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 单据 ${result.bill.billCode} 审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
|
||||
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
|
||||
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
|
||||
|
||||
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 2. 查看审核要点清单与进度(未注入则硬阻断)────────────────────────
|
||||
case "checklist":
|
||||
case "list":
|
||||
case "status": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro checklist <单号>");
|
||||
}
|
||||
|
||||
const activeCorpId = requireCorpId();
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, activeCorpId);
|
||||
if (!run || findings.length === 0) {
|
||||
repo.logAiProAction({
|
||||
action: "checklist",
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "BLOCKED",
|
||||
summary: "查询审核清单阻断:单据尚未注入任何审核要点",
|
||||
});
|
||||
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关安全卡点生效:在要点未注入前,审批链路物理不通!\n` +
|
||||
`请先执行: hose-aipro points ${targetSn} 注入明细级审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 说明"];
|
||||
const rows = findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 3. 事实核验打标录入 ───────────────────────────────────────────────
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro review <单号> --eval '...'");
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]);
|
||||
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
|
||||
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
|
||||
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
|
||||
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
|
||||
|
||||
const updates: Array<{
|
||||
index?: number;
|
||||
id?: string;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({ index: pointIndex, status: statusInput, evidence, reasoning });
|
||||
} else if (evalStr) {
|
||||
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = match[2].toUpperCase() as FindingCheckStatus;
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-aipro review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
|
||||
` 或: hose-aipro review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
|
||||
);
|
||||
}
|
||||
|
||||
const activeCorpId = requireCorpId();
|
||||
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, activeCorpId);
|
||||
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "review",
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${pendingCount} 项)`,
|
||||
});
|
||||
|
||||
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
|
||||
const rows = updatedFindings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const msg =
|
||||
`====== [AI PRO] 单据 ${targetSn} 事实核验已登记入库 (待核验剩余: ${pendingCount} 项) ======\n` +
|
||||
table +
|
||||
(pendingCount === 0
|
||||
? `\n🎉 [事实全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-aipro decide ${targetSn} --apply --yes\n`
|
||||
: `\n⏳ [待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
|
||||
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 4. 确定性网关仲裁决断与执行 ───────────────────────────────────────
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro decide <单号> [--apply] [--yes]");
|
||||
}
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
if (apply) {
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
|
||||
}
|
||||
const { prompt } = await import("./cli/helpers.js");
|
||||
const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: ");
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
}
|
||||
|
||||
const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
|
||||
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
|
||||
|
||||
const context = await getClient();
|
||||
const decisionResult = await service.decideAudit(context.client, context.corpId, targetSn, {
|
||||
requestedAction,
|
||||
apply,
|
||||
comment: userComment,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "decide",
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: decisionResult.decision,
|
||||
summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(decisionResult),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outLines: string[] = [];
|
||||
outLines.push(`\n====== [AI PRO] 合思确定性网关仲裁决断书 (单号: ${targetSn}) ======`);
|
||||
outLines.push(`网关决策 : ${decisionResult.decision}`);
|
||||
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
|
||||
if (apply) {
|
||||
outLines.push(`下游动作 : 已安全真实执行 [${decisionResult.appliedAction}] 动作`);
|
||||
} else {
|
||||
outLines.push(`执行模式 : 仿真预审 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
|
||||
}
|
||||
outLines.push(`\n--- 审计意见留痕快照 ---\n${decisionResult.decisionSummary}\n`);
|
||||
|
||||
return { stdout: outLines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 5. 全流程监控流水查看 (Audit Logs) ────────────────────────────────
|
||||
case "logs":
|
||||
case "log":
|
||||
case "history":
|
||||
case "trail": {
|
||||
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
|
||||
const logs = repo.listAiProLogs(targetSn || undefined, limit);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ total: logs.length, logs }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
return {
|
||||
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
|
||||
const rows = logs.map((l, i) => [
|
||||
i + 1,
|
||||
new Date(l.createdAt).toLocaleString("zh-CN"),
|
||||
l.action,
|
||||
l.documentSn || "-",
|
||||
l.operator || "-",
|
||||
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
|
||||
l.decision || "-",
|
||||
l.summary || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 6. 规约快捷查看 ───────────────────────────────────────────────────
|
||||
case "rules":
|
||||
case "rule":
|
||||
case "scopes": {
|
||||
const scopes = repo.listScopes();
|
||||
const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"];
|
||||
const rows = scopes.map((s) => [
|
||||
s.index,
|
||||
s.scope,
|
||||
s.ruleCount,
|
||||
s.ruleCodes.map((c) => `#${c}`).join(", "),
|
||||
]);
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 规约场景索引库 (共 ${scopes.length} 个场景) ======\n`;
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// ── 7. 帮助 ───────────────────────────────────────────────────────────
|
||||
case "help":
|
||||
default: {
|
||||
const helpText = `
|
||||
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
|
||||
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
|
||||
|
||||
核心工作流:
|
||||
1. 规则注入 (出明细级审核要点清单):
|
||||
hose-aipro points <单号> [--scope <索引号|场景>]
|
||||
|
||||
2. 查看审核要点清单与核验进度 (未注入则硬阻断):
|
||||
hose-aipro checklist <单号>
|
||||
|
||||
3. 逐项录入事实核验打标:
|
||||
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
|
||||
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
|
||||
|
||||
4. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
|
||||
hose-aipro decide <单号> # 预审仿真 (Dry Run)
|
||||
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
|
||||
|
||||
5. 全流程监控日志流水查看:
|
||||
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
|
||||
|
||||
6. 查看审批规约场景:
|
||||
hose-aipro rules # 查看所有场景与规则分布
|
||||
`;
|
||||
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
// 将阻断或异常统一记录至审计日志
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
repo.logAiProAction({
|
||||
action: command,
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "BLOCKED",
|
||||
summary: err.message.replace(/\n+/g, " "),
|
||||
});
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `\n${err.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
repo.logAiProAction({
|
||||
action: command,
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "ERROR",
|
||||
summary: String(err?.message || err),
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 直接作为可执行脚本运行时
|
||||
if (import.meta.main) {
|
||||
const rawArgs = process.argv.slice(2);
|
||||
const result = await runAiProCli(rawArgs);
|
||||
if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout));
|
||||
if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr));
|
||||
process.exit(result.exitCode);
|
||||
}
|
||||
+12
-3
@@ -14,11 +14,20 @@ process.stderr.on("error", (err: any) => {
|
||||
const entryFile = fileURLToPath(import.meta.url);
|
||||
const appRoot = dirname(dirname(entryFile));
|
||||
|
||||
const result = await runCli(process.argv.slice(2), {
|
||||
appRoot,
|
||||
entryFile,
|
||||
// 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) => {
|
||||
const base = c.split("/").pop() || "";
|
||||
return base.includes("hose-aipro") || base === "aipro" || base.includes("aipro-cli");
|
||||
});
|
||||
|
||||
const result = isAiPro
|
||||
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
|
||||
: await runCli(process.argv.slice(2), {
|
||||
appRoot,
|
||||
entryFile,
|
||||
});
|
||||
|
||||
try {
|
||||
if (result.stdout) process.stdout.write(result.stdout);
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalGatewayBlockedError,
|
||||
FindingCheckStatus,
|
||||
} from "../../domains/approval/index.js";
|
||||
|
||||
export async function handleApprovalCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const service = new ApprovalService();
|
||||
|
||||
// 解析命令层级:
|
||||
// 形式 A: hose-use approval audit points S26000001
|
||||
// 形式 B: hose-use approval points S26000001
|
||||
// 形式 C: hose-use approval audit S26000001
|
||||
let subAction = parsed.action?.toLowerCase();
|
||||
let args = [...parsed.args];
|
||||
|
||||
if (subAction === "audit" && args.length > 0) {
|
||||
const candidateSub = args[0]?.toLowerCase();
|
||||
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
|
||||
subAction = candidateSub;
|
||||
args.shift();
|
||||
}
|
||||
}
|
||||
|
||||
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
|
||||
|
||||
switch (subAction) {
|
||||
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
|
||||
case "points":
|
||||
case "inject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
|
||||
}
|
||||
|
||||
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
|
||||
const result = await service.injectAuditPoints(client, corpId, targetSn, {
|
||||
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
|
||||
const rows = result.findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus,
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
|
||||
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
|
||||
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
|
||||
case "checklist":
|
||||
case "list":
|
||||
case "status": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
|
||||
}
|
||||
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run || findings.length === 0) {
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
|
||||
const rows = findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
|
||||
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
|
||||
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
|
||||
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
|
||||
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
|
||||
|
||||
const updates: Array<{
|
||||
index?: number;
|
||||
id?: string;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({
|
||||
index: pointIndex,
|
||||
status: statusInput,
|
||||
evidence,
|
||||
reasoning,
|
||||
});
|
||||
} else if (evalStr) {
|
||||
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
|
||||
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = match[2].toUpperCase() as FindingCheckStatus;
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({
|
||||
index: idx,
|
||||
status,
|
||||
evidence: desc,
|
||||
reasoning: desc,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
|
||||
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
|
||||
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
|
||||
const rows = updatedFindings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const msg =
|
||||
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
|
||||
table +
|
||||
(pendingCount === 0
|
||||
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
|
||||
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
|
||||
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
|
||||
}
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
if (apply) {
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
}
|
||||
|
||||
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
|
||||
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
|
||||
|
||||
try {
|
||||
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
|
||||
requestedAction,
|
||||
apply,
|
||||
comment: userComment,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(decisionResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outLines: string[] = [];
|
||||
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
|
||||
outLines.push(`网关决策 : ${decisionResult.decision}`);
|
||||
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
|
||||
if (apply) {
|
||||
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
|
||||
} else {
|
||||
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
|
||||
}
|
||||
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
|
||||
|
||||
return {
|
||||
stdout: outLines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `\n${err.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
|
||||
case "audit":
|
||||
case undefined: {
|
||||
if (!targetSn) {
|
||||
return {
|
||||
stdout:
|
||||
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
|
||||
`用法:\n` +
|
||||
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
|
||||
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
|
||||
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
|
||||
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 检查当前是否已注入要点
|
||||
const { run } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run) {
|
||||
// 自动触发第一步:注入并出审核要点
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "points", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
} else {
|
||||
// 已有要点,展示清单与进度
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "checklist", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
|
||||
}
|
||||
}
|
||||
+403
-3
@@ -1,11 +1,23 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, numberOption } from "../parser.js";
|
||||
import { booleanOption, stringOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getBillFlow,
|
||||
getBillRisk,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
downloadBillAttachments,
|
||||
getFieldDictionary,
|
||||
approveBill,
|
||||
rejectBill,
|
||||
transferBill,
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
} from "../../domains/bill/tools.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
@@ -23,7 +35,98 @@ export async function handleBillCommand(
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(client, corpId, values);
|
||||
};
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill approve <单号|ID> --yes");
|
||||
const result = await approveBill(client, corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "reject":
|
||||
case "deny": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
const result = await rejectBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "transfer":
|
||||
case "shift": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await transferBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await addNodeBill(client, corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "comment":
|
||||
case "remark": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose bill comment <单号|ID> --comment <内容> --yes");
|
||||
const result = await commentBill(client, corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined: {
|
||||
@@ -105,6 +208,11 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
@@ -112,7 +220,7 @@ export async function handleBillCommand(
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -147,6 +255,25 @@ export async function handleBillCommand(
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -195,7 +322,280 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(client, corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
entry.operator?.name || (entry.automatic ? "系统" : "-"),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose bill risk <单号|ID>");
|
||||
const report = await getBillRisk(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "budget":
|
||||
case "budgets": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose bill budget <单号|ID>");
|
||||
const report = await getBillRisk(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>");
|
||||
const report = await getBillReferences(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose bill relations <单号|ID>");
|
||||
const report = await getBillRelations(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "download":
|
||||
case "file-download": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "link":
|
||||
case "url": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose bill link <单号或ID>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(client, corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到单据: ${target}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const item = items[0];
|
||||
const billId = item.billId;
|
||||
const billCode = item.billCode || target;
|
||||
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
|
||||
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
code: billCode,
|
||||
id: billId,
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
url: webUrl,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
`====== 合思单据 Web 直达链接 ======`,
|
||||
` 单据编号: ${billCode}`,
|
||||
` 单据 ID : ${billId}`,
|
||||
` 所属企业: ${corp.name} (${corpId})`,
|
||||
` 直达链接:`,
|
||||
` ${webUrl}`,
|
||||
``,
|
||||
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: text + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, schema`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,8 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
defaultCorpId: globalConfig.defaultCorpId || null,
|
||||
defaultAccountId: globalConfig.defaultAccountId || null,
|
||||
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
|
||||
updateRepo: globalConfig.updateRepo || null,
|
||||
updateSource: globalConfig.updateSource || "auto",
|
||||
configFile: configPath,
|
||||
};
|
||||
|
||||
@@ -59,11 +61,13 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
|
||||
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
|
||||
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
|
||||
"默认自更新仓库": globalConfig.updateRepo || "官方默认 (yunyingk/hose-use)",
|
||||
"自更新源偏好": globalConfig.updateSource || "auto (自动择优)",
|
||||
"配置文件路径": configPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode <stateful|stateless>\n 指定企业: hose corps switch <corpId>\n`,
|
||||
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode <stateful|stateless>\n 指定企业: hose corps switch <corpId>\n 更新源设置: hose config set updateSource <auto|github|gitea>\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -95,10 +99,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
}
|
||||
|
||||
async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const key = parsed.args[0];
|
||||
const rawKey = parsed.args[0];
|
||||
const val = parsed.args[1];
|
||||
|
||||
if (!key || val === undefined) {
|
||||
if (!rawKey || val === undefined) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)\n",
|
||||
@@ -106,17 +110,37 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
};
|
||||
}
|
||||
|
||||
const keyLower = rawKey.toLowerCase();
|
||||
const partial: Record<string, unknown> = {};
|
||||
if (key === "stateful") {
|
||||
let resolvedKey = rawKey;
|
||||
|
||||
if (keyLower === "stateful") {
|
||||
resolvedKey = "stateful";
|
||||
partial.stateful = val === "true" || val === "1";
|
||||
} else if (key === "defaultCorpId") {
|
||||
} else if (keyLower === "defaultcorpid") {
|
||||
resolvedKey = "defaultCorpId";
|
||||
partial.defaultCorpId = val;
|
||||
} else if (key === "defaultAccountId") {
|
||||
} else if (keyLower === "defaultaccountid") {
|
||||
resolvedKey = "defaultAccountId";
|
||||
partial.defaultAccountId = val;
|
||||
} else if (keyLower === "updaterepo") {
|
||||
resolvedKey = "updateRepo";
|
||||
partial.updateRepo = val;
|
||||
} else if (keyLower === "updatesource") {
|
||||
resolvedKey = "updateSource";
|
||||
const srcLower = val.toLowerCase();
|
||||
if (srcLower !== "auto" && srcLower !== "github" && srcLower !== "gitea") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `不支持的 updateSource 值: ${val}。可选: auto, github, gitea\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
partial.updateSource = srcLower;
|
||||
} else {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `不支持配置键: ${key}。支持: stateful, defaultCorpId, defaultAccountId\n`,
|
||||
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, updateRepo, updateSource\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -127,7 +151,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 配置已更新: ${key} = ${val}\n`,
|
||||
stdout: `[SUCCESS] 配置已更新: ${resolvedKey} = ${val}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import {
|
||||
getStaffById,
|
||||
listStaffsProtected,
|
||||
searchStaffs,
|
||||
DEFAULT_STAFF_LIST_LIMIT,
|
||||
} from "../../domains/contact/tools.js";
|
||||
|
||||
export async function handleContactCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || parsed.args[0] || "list";
|
||||
const limit = numberOption(parsed.options, ["limit", "l"]);
|
||||
|
||||
// 1. 搜索: hose contact search <keyword> 或 hose contact find <keyword>
|
||||
if (action === "search" || action === "find") {
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k"]) || "";
|
||||
if (!keyword.trim()) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose contact search <关键词 (姓名/邮箱/工号)>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const results = await searchStaffs(corp, { keyword, limit });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: results.length, keyword, staffs: results }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配关键词 "${keyword}" 的员工。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["姓名", "工号 / staffId", "邮箱", "手机号"];
|
||||
const rows = results.map((s) => [
|
||||
s.name || "-",
|
||||
s.id,
|
||||
s.email || "-",
|
||||
s.cellphone || "-",
|
||||
]);
|
||||
|
||||
return {
|
||||
stdout: `====== 员工搜索结果 (关键词: "${keyword}", 找到 ${results.length} 人) ======\n${printTable(headers, rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 详情: hose contact get <staffId>
|
||||
if (action === "get") {
|
||||
const staffId = parsed.args[0] || stringOption(parsed.options, ["id", "staff-id"]);
|
||||
if (!staffId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose contact get <staffId>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const staff = await getStaffById(corp, staffId);
|
||||
if (!staff) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到员工档案: ${staffId}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(staff, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
"员工姓名": staff.name,
|
||||
"工号/staffId": staff.id,
|
||||
"电子邮箱": staff.email || "-",
|
||||
"联系手机": staff.cellphone || "-",
|
||||
"所属部门": staff.department || "-",
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 员工详细档案 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 列表采样: hose contact list (默认限流截断防爆)
|
||||
if (action === "list") {
|
||||
const isFull = runtime.outputOptions?.allowFull === true;
|
||||
const result = await listStaffsProtected(corp, {
|
||||
limit: limit ?? (isFull ? undefined : DEFAULT_STAFF_LIST_LIMIT),
|
||||
allowFull: isFull,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["姓名", "工号 / staffId", "邮箱", "手机号"];
|
||||
const rows = result.staffs.map((s) => [
|
||||
s.name || "-",
|
||||
s.id,
|
||||
s.email || "-",
|
||||
s.cellphone || "-",
|
||||
]);
|
||||
|
||||
let output = `====== 企业通讯录采样 (共 ${result.total} 人,当前显示 ${result.staffs.length} 条) ======\n`;
|
||||
output += printTable(headers, rows) + "\n";
|
||||
if (result.hint) {
|
||||
output += `\n💡 提示: ${result.hint}\n`;
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: output,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知通讯录子命令: ${action}。支持的子命令: list, search <关键词>, get <staffId>`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
||||
|
||||
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search", "catalogs", undefined].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const dimensions = await searchDimensions(client, corpId, { name: keyword });
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: dimensions.length, dimensions }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = dimensions.map((item, index) => [index + 1, item.name, item.code || "-", item.id, item.type || "-", item.active ? "启用" : "停用"]);
|
||||
return { stdout: `====== 企业档案维度目录 (企业: ${corp.name} | 共 ${dimensions.length} 个) ======\n${rows.length ? printTable(["#", "名称", "编码", "ID", "类型", "状态"], rows) : "暂无匹配档案维度"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["items", "get", "show"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["dimension", "id", "code", "name"]);
|
||||
if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose dimension items <维度>");
|
||||
const result = await resolveDimension(client, corpId, target);
|
||||
if (!result) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到档案维度: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 100) || 100;
|
||||
const items = count >= result.items.length ? result.items : result.items.slice(0, count);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, dimension: result.dimension, count: items.length, items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = items.map((item, index) => [index + 1, item.name, item.code || "-", item.id, item.parentId || "-", item.fullPath || "-"]);
|
||||
return { stdout: `====== 档案项 (维度: ${result.dimension.name} | 共 ${items.length} 条) ======\n${rows.length ? printTable(["#", "名称", "编码", "ID", "上级 ID", "全路径"], rows) : "暂无档案项"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
throw new Error(`未知 dimension 子命令: ${action}。支持: list, items <维度 ID|编码|名称>`);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
||||
import type { MessageItem } from "../../domains/message/types.js";
|
||||
|
||||
function formatTime(value: number | undefined): string {
|
||||
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
|
||||
}
|
||||
|
||||
function renderItems(items: MessageItem[]): string {
|
||||
const headers = ["消息 ID", "时间", "类型", "标题", "内容", "状态"];
|
||||
const rows = items.map((item) => [
|
||||
item.id,
|
||||
formatTime(item.sortTime ?? item.createTime),
|
||||
item.msgTypeName || item.messageType || "-",
|
||||
item.title || "-",
|
||||
item.content || "-",
|
||||
item.read ? "已读" : "未读",
|
||||
]);
|
||||
return printTable(headers, rows);
|
||||
}
|
||||
|
||||
export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
|
||||
const action = parsed.action || parsed.args[0] || "list";
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
if (action === "count" || action === "unread") {
|
||||
const result = await listMessages(client, corpId, { start: 0, count: 1, read: false });
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action === "read" || action === "mark-read") {
|
||||
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
|
||||
if (!messageId) return { stdout: "", stderr: "用法: hose message read <messageId>\n", exitCode: 1 };
|
||||
await readMessage(client, corpId, messageId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action === "read-all" || action === "mark-all-read") {
|
||||
const ids: string[] = [];
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
do {
|
||||
const page = await listMessages(client, corpId, { start, count: 100, read: false });
|
||||
total = page.total;
|
||||
ids.push(...page.items.map((item) => item.id));
|
||||
start += page.items.length;
|
||||
if (page.items.length === 0) break;
|
||||
} while (start < total);
|
||||
for (const id of ids) await readMessage(client, corpId, id);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, requested: ids.length, read: ids.length, totalUnreadBefore: total }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `已标记 ${ids.length} 条消息为已读。\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action !== "list") {
|
||||
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const read = booleanOption(parsed.options, ["read"]);
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
const all = booleanOption(parsed.options, ["all"]);
|
||||
const readFilter = read && !unread;
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20) ?? 20;
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0) ?? 0;
|
||||
const type = stringOption(parsed.options, ["type", "message-type"]);
|
||||
const result = all
|
||||
? await (async () => {
|
||||
const [unreadPage, readPage] = await Promise.all([
|
||||
listMessages(client, corpId, { start: 0, count: Math.max(100, start + count), read: false }),
|
||||
listMessages(client, corpId, { start: 0, count: Math.max(100, start + count), read: true }),
|
||||
]);
|
||||
const merged = mergeMessages([...unreadPage.items, ...readPage.items]);
|
||||
return { total: unreadPage.total + readPage.total, start, count, read: false, items: merged.slice(start, start + count) };
|
||||
})()
|
||||
: await listMessages(client, corpId, { start, count, read: readFilter });
|
||||
const items = filterMessages(result.items, type);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, total: type ? items.length : result.total, start: result.start, count: result.count, read: all ? "all" : readFilter, items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout: `====== ${all ? "全部" : readFilter ? "已读" : "未读"}消息 (企业: ${corp.name} | 总数: ${type ? items.length : result.total} | 当前返回: ${items.length}) ======\n${items.length ? renderItems(items) : " (暂无数据)"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getPermissions } from "../../domains/permission/tools.js";
|
||||
|
||||
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const action = parsed.action?.toLowerCase() || "get";
|
||||
if (!["get", "list", "show"].includes(action)) throw new Error(`未知 permission 子命令: ${action}。支持: get`);
|
||||
const client = await createEkbClient(corp);
|
||||
const report = await getPermissions(client, corp.corpId || corp.id);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.permissions.map((item) => [item.name, item.auth ? "启用" : "停用"]);
|
||||
return { stdout: `====== 角色权限快照 (权限模型: ${report.type || "-"}) ======\n${rows.length ? printTable(["权限", "状态"], rows) : "暂无权限项"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||
|
||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const client = await createEkbClient(corp), corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search"].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const roles = await searchRoles(client, corpId, { keyword });
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], roles.length) || roles.length;
|
||||
const items = roles.slice(0, count);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: items.length, roles: items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = items.map((role) => [role.name, role.code || "-", role.id, role.scope.name || "-", role.roleGroupId || "-"]);
|
||||
return { stdout: `====== 企业角色 (共 ${items.length} 个) ======\n${rows.length ? printTable(["名称", "编码", "ID", "角色类型", "角色组 ID"], rows) : "暂无匹配角色"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["groups", "group"].includes(action)) {
|
||||
const groups = await getRoleGroups(client, corpId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: groups.length, groups }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = groups.map((group) => [group.name, group.id, group.roleDefs.length, group.roleDefs.map((role) => role.name).join(", ") || "-"]);
|
||||
return { stdout: `====== 角色组 (共 ${groups.length} 个) ======\n${rows.length ? printTable(["名称", "ID", "角色数", "角色"], rows) : "暂无角色组"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["members", "member", "staffs", "staff"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["role", "id", "code", "name"]);
|
||||
if (!target) throw new Error("请提供角色 ID、编码或名称: hose role members <角色>");
|
||||
const report = await getRoleMembers(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到角色: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, ...report, count: report.members.length }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.members.map((member) => [member.name, member.code || "-", member.id, member.email || "-", member.cellphone || "-"]);
|
||||
return { stdout: `====== 角色成员 (角色: ${report.role.name} | 共 ${rows.length} 人) ======\n${rows.length ? printTable(["姓名", "工号", "staffId", "邮箱", "手机号"], rows) : "暂无成员"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
throw new Error(`未知 role 子命令: ${action}。支持: list, groups, members <角色 ID|编码|名称>`);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/repository.js";
|
||||
|
||||
describe("CLI - hose-use rule 规则与场景索引命令", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 预置几条测试规则 (仅需 适用场景 + 规约正文 两个要素)
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票]{硬性}。"
|
||||
});
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[尽量上传支付凭证]{弹性}。"
|
||||
});
|
||||
repo.createRule({
|
||||
scope: "业务招待",
|
||||
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。"
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("hose-use rule scopes 一键获取去重场景索引列表", async () => {
|
||||
const res = await runCli(["rule", "scopes", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.count).toBe(2);
|
||||
expect(data.scopes[0].index).toBe(1);
|
||||
expect(data.scopes[0].scope).toBe("差旅报销");
|
||||
expect(data.scopes[0].ruleCount).toBe(2);
|
||||
expect(data.scopes[0].ruleCodes).toEqual([1, 2]);
|
||||
|
||||
expect(data.scopes[1].index).toBe(2);
|
||||
expect(data.scopes[1].scope).toBe("业务招待");
|
||||
expect(data.scopes[1].ruleCount).toBe(1);
|
||||
expect(data.scopes[1].ruleCodes).toEqual([3]);
|
||||
});
|
||||
|
||||
test("hose-use rule scope <1> 输入索引号获取该场景下的全部规则明细", async () => {
|
||||
const res = await runCli(["rule", "scope", "1", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.index).toBe(1);
|
||||
expect(data.scope).toBe("差旅报销");
|
||||
expect(data.ruleCount).toBe(2);
|
||||
expect(data.rules.length).toBe(2);
|
||||
expect(data.rules[0].code).toBe(1);
|
||||
expect(data.rules[0].parsed.clauses[0].strictness).toBe("硬性");
|
||||
expect(data.rules[1].code).toBe(2);
|
||||
expect(data.rules[1].parsed.clauses[0].strictness).toBe("弹性");
|
||||
});
|
||||
|
||||
test("hose-use rule scope <场景名称> 输入名称同样可以获取明细", async () => {
|
||||
const res = await runCli(["rule", "scope", "业务招待", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.index).toBe(2);
|
||||
expect(data.scope).toBe("业务招待");
|
||||
expect(data.ruleCount).toBe(1);
|
||||
expect(data.rules[0].code).toBe(3);
|
||||
expect(data.rules[0].parsed.clauses[0].action).toBe("必须提供餐饮点餐水单");
|
||||
});
|
||||
|
||||
test("hose-use rule scope <不存在> 返回 1 并提示未找到", async () => {
|
||||
const res = await runCli(["rule", "scope", "999", "--json"]);
|
||||
expect(res.exitCode).toBe(1);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.found).toBe(false);
|
||||
});
|
||||
|
||||
test("hose-use rule add 纯双参数 (索引 + 正文) 快速新增并强校验", async () => {
|
||||
// 成功添加:支持直接传 [适用场景] [正文] 两个参数
|
||||
const addRes = await runCli([
|
||||
"rule",
|
||||
"add",
|
||||
"办公采购",
|
||||
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
|
||||
"--json"
|
||||
]);
|
||||
expect(addRes.exitCode).toBe(0);
|
||||
const addData = JSON.parse(addRes.stdout);
|
||||
expect(addData.success).toBe(true);
|
||||
expect(addData.rule.code).toBe(4);
|
||||
expect(addData.rule.scope).toBe("办公采购");
|
||||
|
||||
// 再次调用 scopes 应该出现第 3 个索引
|
||||
const scopesRes = await runCli(["rule", "scopes", "--json"]);
|
||||
const scopesData = JSON.parse(scopesRes.stdout);
|
||||
expect(scopesData.count).toBe(3);
|
||||
expect(scopesData.scopes[2].scope).toBe("办公采购");
|
||||
});
|
||||
|
||||
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
|
||||
const failRes = await runCli([
|
||||
"rule",
|
||||
"add",
|
||||
"差旅报销",
|
||||
"差旅报销时,[必须附发票]{严重}。" // 非法严格程度
|
||||
]);
|
||||
expect(failRes.exitCode).not.toBe(0);
|
||||
expect(failRes.stderr).toContain("非法严格程度");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleRuleCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const repo = new ApprovalRepository();
|
||||
const action = (parsed.action || "scopes").toLowerCase();
|
||||
|
||||
// 1. 获取所有去重索引(适用场景)列表及对应索引号
|
||||
// 用法: hose-use rule scopes [--all]
|
||||
if (["scopes", "scope-list", "indexes", "index"].includes(action)) {
|
||||
const showAll = booleanOption(parsed.options, ["all"]);
|
||||
const status = showAll ? undefined : "active";
|
||||
const scopes = repo.listScopes(status);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: scopes.length, scopes }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
const rows = scopes.map((s) => [
|
||||
s.index,
|
||||
s.scope,
|
||||
s.ruleCount,
|
||||
s.ruleCodes.map((c) => `#${c}`).join(", ") || "-"
|
||||
]);
|
||||
|
||||
const header = `====== 审批规约索引列表 (共 ${scopes.length} 个适用场景) ======\n`;
|
||||
const table = rows.length
|
||||
? printTable(["索引号", "适用场景 (Scope)", "规则数", "包含规则编号"], rows)
|
||||
: "暂无有效规则索引。可使用 hose-use rule add 添加规则。\n";
|
||||
|
||||
return {
|
||||
stdout: `${header}${table}\n提示:输入 "hose-use rule scope <索引号>" 查看该场景下的全部规约明细。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 根据索引号或场景名称,获取该场景下的所有规约明细
|
||||
// 用法: hose-use rule scope <1|"差旅报销">
|
||||
if (action === "scope") {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["target", "name", "id", "index"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供索引号或适用场景名称: hose-use rule scope <索引号|场景名称>");
|
||||
}
|
||||
|
||||
const detail = repo.getScopeDetail(target);
|
||||
if (!detail) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到索引号或场景为 "${target}" 的有效规则。\n提示:可先运行 "hose-use rule scopes" 查看所有可用索引号。\n`,
|
||||
exitCode: 1
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(detail, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [
|
||||
`====== 适用场景 [${detail.index}] ${detail.scope} (共 ${detail.ruleCount} 条规则) ======\n`
|
||||
];
|
||||
|
||||
detail.rules.forEach((r, idx) => {
|
||||
lines.push(`${idx + 1}. [规则 #${r.code}] (v${r.version})`);
|
||||
lines.push(` 正文: ${r.body}`);
|
||||
lines.push(" 审查要点:");
|
||||
r.parsed.clauses.forEach((c) => {
|
||||
lines.push(` - [${c.strictness}] ${c.action}`);
|
||||
});
|
||||
lines.push("");
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 规则列表查询
|
||||
// 用法: hose-use rule list [--scope <name>] [--status active]
|
||||
if (action === "list") {
|
||||
const scope = stringOption(parsed.options, ["scope", "s"]);
|
||||
const statusOption = stringOption(parsed.options, ["status"]);
|
||||
const status = (statusOption as any) || "active";
|
||||
const rules = repo.listRules({ scope, status });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ count: rules.length, rules }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
const rows = rules.map((r) => [
|
||||
`#${r.code}`,
|
||||
r.scope,
|
||||
`v${r.version}`,
|
||||
r.status,
|
||||
r.body.length > 35 ? r.body.slice(0, 35) + "..." : r.body,
|
||||
r.id
|
||||
]);
|
||||
|
||||
const header = `====== 审批规约清单 (共 ${rules.length} 条) ======\n`;
|
||||
const table = rows.length
|
||||
? printTable(["编号", "适用场景 (索引)", "版本", "状态", "规约正文预览", "ID"], rows)
|
||||
: "暂无规则记录。\n";
|
||||
|
||||
return { stdout: `${header}${table}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 4. 查看单条规则详情
|
||||
// 用法: hose-use rule get <code|id>
|
||||
if (action === "get" || action === "show") {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供规则编号或 ID: hose-use rule get <编号|ID>");
|
||||
}
|
||||
|
||||
let rule = /^\d+$/.test(target) ? repo.getRuleByCode(Number(target)) : null;
|
||||
if (!rule) {
|
||||
rule = repo.getRuleById(target);
|
||||
}
|
||||
|
||||
if (!rule) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到编号或 ID 为 "${target}" 的规则。\n`,
|
||||
exitCode: 1
|
||||
};
|
||||
}
|
||||
|
||||
const parsedRule = parseRuleBody(rule.body);
|
||||
const result = {
|
||||
...rule,
|
||||
parsed: parsedRule
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [
|
||||
`====== 规则 #${rule.code} 详情 ======\n`,
|
||||
`规则 ID: ${rule.id}`,
|
||||
`适用场景: ${rule.scope}`,
|
||||
`规则版本: v${rule.version}`,
|
||||
`当前状态: ${rule.status}`,
|
||||
`规约正文:\n${rule.body}\n`,
|
||||
`审查要点拆解 (${parsedRule.clauses.length} 项):`
|
||||
];
|
||||
|
||||
parsedRule.clauses.forEach((c) => {
|
||||
lines.push(` - [${c.strictness}] ${c.action}`);
|
||||
});
|
||||
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 5. 新增规则 (内置语法分析强校验)
|
||||
// 用法: hose-use rule add <适用场景/索引> <规约正文>
|
||||
// 或: hose-use rule add --scope <scope> --body <body>
|
||||
if (action === "add" || action === "create") {
|
||||
let scope = stringOption(parsed.options, ["scope", "s"]);
|
||||
let body = stringOption(parsed.options, ["body", "b"]);
|
||||
|
||||
if (!scope && parsed.args.length >= 1) {
|
||||
scope = parsed.args[0];
|
||||
if (!body && parsed.args.length >= 2) {
|
||||
body = parsed.args.slice(1).join(" ");
|
||||
}
|
||||
}
|
||||
|
||||
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
|
||||
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
|
||||
|
||||
const rule = repo.createRule({
|
||||
scope,
|
||||
body,
|
||||
status: "active"
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, rule }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✓ 成功创建规则 #${rule.code} (ID: ${rule.id})!\n适用场景 (索引): ${rule.scope}\n规约正文: ${rule.body}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0
|
||||
};
|
||||
}
|
||||
|
||||
// 6. 删除规则
|
||||
// 用法: hose-use rule delete <id>
|
||||
if (action === "delete" || action === "remove" || action === "rm") {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "code"]);
|
||||
if (!target) throw new Error("请提供要删除的规则 ID 或编号: hose-use rule delete <ID|编号>");
|
||||
|
||||
let ruleId = target;
|
||||
if (/^\d+$/.test(target)) {
|
||||
const found = repo.getRuleByCode(Number(target));
|
||||
if (!found) throw new Error(`未找到编号为 #${target} 的规则`);
|
||||
ruleId = found.id;
|
||||
}
|
||||
|
||||
const deleted = repo.deleteRule(ruleId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: deleted, id: ruleId }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: deleted ? 0 : 1
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: deleted ? `✓ 成功删除规则 (ID: ${ruleId})\n` : `未找到规则 (ID: ${ruleId})\n`,
|
||||
stderr: "",
|
||||
exitCode: deleted ? 0 : 1
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`未知 rule 子命令: "${action}"。\n支持命令:\n` +
|
||||
` hose-use rule scopes 获取去重场景索引列表与索引号\n` +
|
||||
` hose-use rule scope <索引号|场景> 获取指定场景下的全部规则明细\n` +
|
||||
` hose-use rule list 列出全部规则\n` +
|
||||
` hose-use rule get <编号|ID> 查看规则详情与要点拆解\n` +
|
||||
` hose-use rule add 添加新规则 (带语法强校验)\n` +
|
||||
` hose-use rule delete <编号|ID> 删除规则\n`
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../ser
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
@@ -16,6 +19,18 @@ export async function handleServiceCommand(
|
||||
const port = numberOption(parsed.options, ["port", "p"]);
|
||||
const host = stringOption(parsed.options, ["host", "h"]);
|
||||
|
||||
if (action === "poll") {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("事件轮询需要企业上下文,请通过 --corp=<id> 指定企业。");
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createEkbClient(corp);
|
||||
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
|
||||
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
appRoot: runtime.appRoot || process.cwd(),
|
||||
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { listTasks } from "../../domains/task/tools.js";
|
||||
import type { TaskView } from "../../domains/task/types.js";
|
||||
|
||||
function dateOption(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const numeric = Number(value);
|
||||
if (Number.isFinite(numeric)) return numeric;
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isNaN(parsed) ? undefined : parsed;
|
||||
}
|
||||
|
||||
export async function handleTaskCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
|
||||
const action = parsed.action || parsed.args[0] || "todo";
|
||||
const view: TaskView | undefined = action === "todo" || action === "pending"
|
||||
? "todo"
|
||||
: action === "approved" || action === "done"
|
||||
? "approved"
|
||||
: action === "processed" || action === "records" || action === "history"
|
||||
? "processed"
|
||||
: action === "cc" || action === "carboncopy" || action === "carbon-copy"
|
||||
? "cc"
|
||||
: action === "submitted" || action === "mine" || action === "created"
|
||||
? "submitted"
|
||||
: undefined;
|
||||
if (!view) {
|
||||
throw new Error("未知 task 子命令。支持: todo, approved, records, submitted, cc");
|
||||
}
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const staffId = stringOption(parsed.options, ["staff", "staff-id", "staffId"]);
|
||||
const from = dateOption(stringOption(parsed.options, ["from", "start-date"]));
|
||||
const to = dateOption(stringOption(parsed.options, ["to", "end-date"]));
|
||||
const read = booleanOption(parsed.options, ["read"]);
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
// Carbon copy defaults to unread, while the other views do not use this flag.
|
||||
const readFilter = view === "cc" ? read && !unread : undefined;
|
||||
const result = await listTasks(await createEkbClient(corp), corp.corpId || corp.id, view, { start, count, staffId, from, to, read: readFilter });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const headers = ["#", "任务 ID", "单号", "标题", "模板", "提交人", "金额", "状态", "当前节点", "动作"];
|
||||
const rows = result.items.map((item, index) => [
|
||||
index + 1,
|
||||
item.taskId,
|
||||
item.billCode || "-",
|
||||
item.title || "-",
|
||||
item.templateName || "-",
|
||||
item.submitter ? `${item.submitter.name || "-"}${item.submitter.code ? `(${item.submitter.code})` : ""}` : "-",
|
||||
item.amount ? `${item.amount.symbol || ""}${item.amount.value} ${item.amount.currency || ""}`.trim() : "-",
|
||||
item.state || "-",
|
||||
item.nodeName || "-",
|
||||
item.action || "-",
|
||||
]);
|
||||
const labels: Record<TaskView, string> = {
|
||||
todo: "待审批",
|
||||
approved: "已审批",
|
||||
processed: "审批记录",
|
||||
submitted: "我发起的",
|
||||
cc: readFilter ? "抄送(已读)" : "抄送(未读)",
|
||||
};
|
||||
return {
|
||||
stdout: `====== ${labels[view]}任务 (企业: ${corp.name} | 总数: ${result.total} | 当前返回: ${result.items.length}) ======\n${printTable(headers, rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { compareSemVer, isNewerVersion, matchAssetForPlatform, type GitHubAsset } from "./update.js";
|
||||
import {
|
||||
compareSemVer,
|
||||
isNewerVersion,
|
||||
matchAssetForPlatform,
|
||||
normalizeRepo,
|
||||
isValidRepo,
|
||||
type GitHubAsset,
|
||||
} from "./update.js";
|
||||
|
||||
describe("update version comparator", () => {
|
||||
test("correctly identifies newer semantic versions", () => {
|
||||
@@ -20,6 +27,29 @@ describe("update version comparator", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeRepo and isValidRepo", () => {
|
||||
test("normalizeRepo trims and cleans various GitHub URL formats", () => {
|
||||
expect(normalizeRepo("yunyingk/hose-use")).toBe("yunyingk/hose-use");
|
||||
expect(normalizeRepo("https://github.com/yunyingk/hose-use")).toBe("yunyingk/hose-use");
|
||||
expect(normalizeRepo("https://github.com/yunyingk/hose-use.git")).toBe("yunyingk/hose-use");
|
||||
expect(normalizeRepo("http://www.github.com/my-org/my-fork/")).toBe("my-org/my-fork");
|
||||
expect(normalizeRepo(" custom/project.git ")).toBe("custom/project");
|
||||
expect(normalizeRepo("github.com/test-org/repo")).toBe("test-org/repo");
|
||||
});
|
||||
|
||||
test("isValidRepo validates owner/repo format and rejects illegal inputs", () => {
|
||||
expect(isValidRepo("yunyingk/hose-use")).toBe(true);
|
||||
expect(isValidRepo("my-org/hose-use-fork")).toBe(true);
|
||||
expect(isValidRepo("user.name/repo_name.v2")).toBe(true);
|
||||
|
||||
expect(isValidRepo("")).toBe(false);
|
||||
expect(isValidRepo("single-word")).toBe(false);
|
||||
expect(isValidRepo("too/many/parts/here")).toBe(false);
|
||||
expect(isValidRepo("../path/traversal")).toBe(false);
|
||||
expect(isValidRepo("invalid character/repo")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAssetForPlatform", () => {
|
||||
const assets: GitHubAsset[] = [
|
||||
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
|
||||
@@ -49,3 +79,4 @@ describe("matchAssetForPlatform", () => {
|
||||
expect(matched?.name).toBe("hose-use-windows-x64.zip");
|
||||
});
|
||||
});
|
||||
|
||||
+158
-42
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
|
||||
import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
@@ -11,15 +12,29 @@ import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../typ
|
||||
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
|
||||
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
|
||||
|
||||
export type UpdateSourcePreference = "auto" | "github" | "gitea";
|
||||
|
||||
export type UpdateOptions = {
|
||||
checkOnly?: boolean;
|
||||
changelogOnly?: boolean;
|
||||
limit?: number;
|
||||
force?: boolean;
|
||||
targetVersion?: string;
|
||||
repo?: string;
|
||||
repo: string;
|
||||
sourcePreference: UpdateSourcePreference;
|
||||
};
|
||||
|
||||
export function normalizeRepo(raw: string): string {
|
||||
let repo = raw.trim();
|
||||
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
|
||||
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
|
||||
return repo;
|
||||
}
|
||||
|
||||
export function isValidRepo(repo: string): boolean {
|
||||
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
|
||||
}
|
||||
|
||||
export async function handleUpdateCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
@@ -47,11 +62,44 @@ export async function handleUpdateCommand(
|
||||
? targetVersionRaw.replace(/^v/, "")
|
||||
: undefined;
|
||||
|
||||
const repo =
|
||||
const isGitHub = booleanOption(parsed.options, ["github", "gh"]);
|
||||
const isGitea = booleanOption(parsed.options, ["gitea", "yingqing", "mirror"]);
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const configuredSource = globalConfig.updateSource || "auto";
|
||||
|
||||
let sourcePreference: UpdateSourcePreference = "auto";
|
||||
if (isGitHub) {
|
||||
sourcePreference = "github";
|
||||
} else if (isGitea) {
|
||||
sourcePreference = "gitea";
|
||||
} else if (configuredSource === "github" || configuredSource === "gitea") {
|
||||
sourcePreference = configuredSource;
|
||||
}
|
||||
|
||||
const rawRepo =
|
||||
stringOption(parsed.options, ["repo"]) ||
|
||||
process.env[GITHUB_REPO_ENV]?.trim() ||
|
||||
globalConfig.updateRepo?.trim() ||
|
||||
DEFAULT_GITHUB_REPO;
|
||||
|
||||
const repo = normalizeRepo(rawRepo);
|
||||
|
||||
if (!isValidRepo(repo)) {
|
||||
const errorMsg = `非法 GitHub 仓库标识: '${rawRepo}'。应为 'owner/repo' 格式(如 'yunyingk/hose-use')。`;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ updated: false, error: true, message: errorMsg }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const options: UpdateOptions = {
|
||||
checkOnly: isCheck,
|
||||
changelogOnly: isChangelog,
|
||||
@@ -59,6 +107,7 @@ export async function handleUpdateCommand(
|
||||
force: booleanOption(parsed.options, ["force", "f"]),
|
||||
targetVersion,
|
||||
repo,
|
||||
sourcePreference,
|
||||
};
|
||||
|
||||
const appRoot = runOptions.appRoot || resolveAppRoot(runOptions.entryFile);
|
||||
@@ -112,11 +161,13 @@ export async function handleUpdateCommand(
|
||||
|
||||
// 1. Changelog / Release History query
|
||||
if (options.changelogOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
|
||||
const releases = await fetchGitHubReleases(repo, options.limit ?? 10, options.sourcePreference);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
currentVersion: VERSION,
|
||||
repo,
|
||||
sourcePreference: options.sourcePreference,
|
||||
totalQueried: releases.length,
|
||||
releases: releases.map((r) => ({
|
||||
version: r.version,
|
||||
@@ -157,7 +208,7 @@ export async function handleUpdateCommand(
|
||||
// 2. Source development mode (running via bun/node)
|
||||
if (!isCompiledBinary()) {
|
||||
if (options.checkOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const releases = await fetchGitHubReleases(repo, 30, options.sourcePreference);
|
||||
const latestRelease = releases[0];
|
||||
const latestVersion = latestRelease?.version ?? VERSION;
|
||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||||
@@ -174,6 +225,8 @@ export async function handleUpdateCommand(
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: latestRelease?.publishedAt,
|
||||
behindCount: pendingReleases.length,
|
||||
repo,
|
||||
sourcePreference: options.sourcePreference,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
@@ -197,6 +250,8 @@ export async function handleUpdateCommand(
|
||||
"当前版本": `v${VERSION}`,
|
||||
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
|
||||
"待更新版本数": pendingReleases.length,
|
||||
"发布仓库": repo,
|
||||
"通道偏好": options.sourcePreference,
|
||||
"源码路径": appRoot,
|
||||
});
|
||||
|
||||
@@ -241,11 +296,11 @@ export async function handleUpdateCommand(
|
||||
const platform = detectPlatform();
|
||||
const arch = detectArch();
|
||||
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const releases = await fetchGitHubReleases(repo, 30, options.sourcePreference);
|
||||
const release = targetVersion
|
||||
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
|
||||
await fetchGitHubRelease(repo, targetVersion))
|
||||
: (releases[0] ?? await fetchGitHubRelease(repo));
|
||||
await fetchGitHubRelease(repo, targetVersion, options.sourcePreference))
|
||||
: (releases[0] ?? await fetchGitHubRelease(repo, undefined, options.sourcePreference));
|
||||
|
||||
if (!release) {
|
||||
const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`;
|
||||
@@ -254,6 +309,8 @@ export async function handleUpdateCommand(
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
repo,
|
||||
sourcePreference: options.sourcePreference,
|
||||
mode: "binary",
|
||||
message: errorMsg,
|
||||
}),
|
||||
@@ -285,6 +342,8 @@ export async function handleUpdateCommand(
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
behindCount: pendingReleases.length,
|
||||
repo,
|
||||
sourcePreference: options.sourcePreference,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
@@ -308,6 +367,8 @@ export async function handleUpdateCommand(
|
||||
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
|
||||
"发布时间": release.publishedAt ? release.publishedAt.slice(0, 10) : "未知",
|
||||
"平台架构": `${platform}-${arch}`,
|
||||
"发布仓库": repo,
|
||||
"通道偏好": options.sourcePreference,
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -326,6 +387,8 @@ export async function handleUpdateCommand(
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
repo,
|
||||
sourcePreference: options.sourcePreference,
|
||||
mode: "binary",
|
||||
message: `hose-use 当前已是最新版本 (v${VERSION})`,
|
||||
}),
|
||||
@@ -365,7 +428,7 @@ export async function handleUpdateCommand(
|
||||
|
||||
try {
|
||||
const downloadedFile = join(tmpDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
|
||||
|
||||
let newBinaryPath = downloadedFile;
|
||||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||||
@@ -456,7 +519,11 @@ export type GitHubRelease = {
|
||||
assets: GitHubAsset[];
|
||||
};
|
||||
|
||||
export async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
|
||||
export async function fetchGitHubReleases(
|
||||
repo: string,
|
||||
limit = 20,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease[]> {
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
@@ -464,10 +531,25 @@ export async function fetchGitHubReleases(repo: string, limit = 20): Promise<Git
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const urls = [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`,
|
||||
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
|
||||
];
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
}
|
||||
|
||||
let fallbackList: GitHubRelease[] = [];
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
@@ -506,18 +588,26 @@ export async function fetchGitHubReleases(repo: string, limit = 20): Promise<Git
|
||||
assets,
|
||||
});
|
||||
}
|
||||
if (list.length > 0) return list;
|
||||
if (list.length > 0) {
|
||||
if (list.some((r) => r.assets.length > 0)) {
|
||||
return list;
|
||||
}
|
||||
if (fallbackList.length === 0) {
|
||||
fallbackList = list;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return fallbackList;
|
||||
}
|
||||
|
||||
export async function fetchGitHubRelease(
|
||||
repo: string,
|
||||
targetVersion?: string
|
||||
targetVersion?: string,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease | undefined> {
|
||||
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
@@ -527,15 +617,26 @@ export async function fetchGitHubRelease(
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const urls = tag
|
||||
? [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`,
|
||||
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
|
||||
]
|
||||
: [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`,
|
||||
`https://api.github.com/repos/${repo}/releases/latest`,
|
||||
];
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
const giteaTagUrl = tag
|
||||
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
|
||||
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
|
||||
const githubTagUrl = tag
|
||||
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
|
||||
: `https://api.github.com/repos/${repo}/releases/latest`;
|
||||
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(githubTagUrl);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
} else {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
}
|
||||
|
||||
let fallbackRelease: GitHubRelease | undefined;
|
||||
|
||||
@@ -642,32 +743,47 @@ function logProgress(msg: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
const fileName = assetName || url.split("/").pop() || "";
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
// 1. High-speed Gitea direct mirror first
|
||||
if (tag && fileName) {
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
||||
}
|
||||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.push(url);
|
||||
// 1. High-speed Gitea direct mirror first (only for default official repo)
|
||||
if (allowGitea) {
|
||||
if (tag && fileName) {
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
||||
}
|
||||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.push(url);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fast GitHub CDN proxies and direct GitHub fallback
|
||||
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
|
||||
if (tag && fileName) {
|
||||
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
|
||||
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
||||
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
||||
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
||||
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
||||
}
|
||||
candidates.push(ghDirectUrl);
|
||||
} else if (url.includes("github.com")) {
|
||||
candidates.push(`https://ghfast.top/${url}`);
|
||||
candidates.push(`https://ghproxy.net/${url}`);
|
||||
candidates.push(`https://gh.ddlc.top/${url}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${url}`);
|
||||
candidates.push(`https://ghproxy.net/${url}`);
|
||||
candidates.push(`https://gh.ddlc.top/${url}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
||||
}
|
||||
candidates.push(url);
|
||||
} else {
|
||||
candidates.push(url);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -37,6 +38,9 @@ export async function handleWorkflowCommand(
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
@@ -46,6 +50,23 @@ export async function handleWorkflowCommand(
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
const result = analyzeWorkflow(detail);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({ "工作流 ID": detail.id, "根节点数": result.ast.length, "依赖节点数": result.dependencies.length, "诊断数": result.diagnostics.length }),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
|
||||
+15
-5
@@ -8,6 +8,7 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"h",
|
||||
"version",
|
||||
"v",
|
||||
"V",
|
||||
"force",
|
||||
"f",
|
||||
"stateless",
|
||||
@@ -23,6 +24,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"confirm",
|
||||
"force-write",
|
||||
]);
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
@@ -45,8 +49,10 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
options[key] = val;
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key)) {
|
||||
const keyLower = key.toLowerCase();
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
} else {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
@@ -62,10 +68,14 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
|
||||
if (arg.startsWith("-") && arg.length > 1) {
|
||||
const flag = arg.slice(1);
|
||||
if (flag === "h") options.help = true;
|
||||
else if (flag === "j") options.json = true;
|
||||
else if (flag === "v") options.version = true;
|
||||
else if (flag === "o") {
|
||||
const flagLower = flag.toLowerCase();
|
||||
if (flagLower === "h" || flag === "?") {
|
||||
options.help = true;
|
||||
} else if (flagLower === "j") {
|
||||
options.json = true;
|
||||
} else if (flagLower === "v") {
|
||||
options.version = true;
|
||||
} else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
|
||||
@@ -21,6 +21,15 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain("corpId=corpxx");
|
||||
});
|
||||
|
||||
test("脱敏对象存储签名 URL 中的临时凭证", () => {
|
||||
const input = "https://files.example/a.png?Expires=1&OSSAccessKeyId=key&Signature=sig&security-token=secret";
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).toContain("OSSAccessKeyId=<redacted>");
|
||||
expect(redacted).toContain("Signature=<redacted>");
|
||||
expect(redacted).toContain("security-token=<redacted>");
|
||||
expect(redacted).not.toContain("secret");
|
||||
});
|
||||
|
||||
test("脱敏 Authorization Bearer token", () => {
|
||||
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||
const redacted = redactSensitiveText(input);
|
||||
|
||||
+46
-6
@@ -6,7 +6,7 @@ export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
@@ -118,15 +118,23 @@ export function printHelp(): string {
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
platform 自建应用管理 (list)
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog)
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
|
||||
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs)
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
version 查看版本信息
|
||||
|
||||
@@ -137,6 +145,7 @@ export function printHelp(): string {
|
||||
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--yes, -y 确认执行会改变单据状态的审批动作
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
@@ -145,18 +154,49 @@ export function printHelp(): string {
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use corps list # 列出名下所有企业
|
||||
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
||||
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
|
||||
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
|
||||
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
|
||||
hose-use task todo --json # 查看当前待我审批任务
|
||||
hose-use task approved # 查看我已审批任务
|
||||
hose-use task submitted # 查看我发起的单据
|
||||
hose-use task cc --unread # 查看未读抄送
|
||||
hose-use message list --unread # 查看未读消息
|
||||
hose-use message list --all # 合并查看已读和未读消息
|
||||
hose-use message count # 查看未读消息数
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill flow S26000001 # 查看单据审批历史与后续节点
|
||||
hose-use bill risk S26000001 # 查看风控预警、预算与发票风险
|
||||
hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用
|
||||
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表
|
||||
hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
hose-use permission get # 查看角色权限开关
|
||||
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||
hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照
|
||||
hose-use bill approve S26000001 --yes # 同意待审批单据
|
||||
hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并填写原因
|
||||
hose-use bill transfer S26000001 --approver-id <员工ID> --yes # 转交审批
|
||||
hose-use bill add-node S26000001 --approver-id <员工ID> --mode pre --yes # 前加签
|
||||
hose-use bill comment S26000001 --comment "请补充发票" --yes # 添加单据评论
|
||||
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
|
||||
hose-use service start # 后台启动常驻守护进程服务
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
hose-use update --github # 强制走官方 GitHub 源升级
|
||||
hose-use update --changelog # 查看版本发布历史
|
||||
hose-use openapi paths # 查看所有 API 路径与概要一览
|
||||
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runCli } from "./runner.js";
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
describe("CLI runner - version and help aliases", () => {
|
||||
const versionVariants = [
|
||||
["version"],
|
||||
["verSion"],
|
||||
["versioN"],
|
||||
["VERSION"],
|
||||
["Version"],
|
||||
["v"],
|
||||
["V"],
|
||||
["-v"],
|
||||
["-V"],
|
||||
["--version"],
|
||||
["--verSion"],
|
||||
["--VERSION"],
|
||||
["--v"],
|
||||
["--V"],
|
||||
];
|
||||
|
||||
for (const args of versionVariants) {
|
||||
it(`correctly outputs version for "${args.join(" ")}"`, async () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toBe(`hose-use v${VERSION}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
const helpVariants = [
|
||||
[],
|
||||
["help"],
|
||||
["HeLp"],
|
||||
["HELP"],
|
||||
["h"],
|
||||
["H"],
|
||||
["-h"],
|
||||
["-H"],
|
||||
["--help"],
|
||||
["--HeLp"],
|
||||
["--HELP"],
|
||||
["?"],
|
||||
["-?"],
|
||||
];
|
||||
|
||||
for (const args of helpVariants) {
|
||||
it(`correctly outputs help for "${args.join(" ") || "<empty>"}"`, async () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}`);
|
||||
expect(result.stdout).toContain("用法:");
|
||||
});
|
||||
}
|
||||
|
||||
it("handles unknown commands gracefully", async () => {
|
||||
const result = await runCli(["unknown-command-xyz"]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
|
||||
});
|
||||
});
|
||||
+69
-3
@@ -13,9 +13,17 @@ import { handleMcpCommand } from "./commands/mcp.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import type { CliResult, CliRunOptions } from "./types.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
|
||||
@@ -76,17 +84,43 @@ async function runCliOnce(
|
||||
}
|
||||
}
|
||||
|
||||
function isHelpRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
if (normKey === "help" || normKey === "h" || normKey === "?") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "version" || normArea === "v") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
if (normKey === "version" || normKey === "v") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
|
||||
if (booleanOption(parsed.options, ["help", "h"]) || parsed.area === "help") {
|
||||
if (isHelpRequested(parsed)) {
|
||||
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (booleanOption(parsed.options, ["version", "v"]) || parsed.area === "version") {
|
||||
if (isVersionRequested(parsed)) {
|
||||
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
@@ -129,6 +163,38 @@ async function dispatchCli(
|
||||
case "invoice":
|
||||
case "invoices":
|
||||
return await handleBillCommand(parsed, runtime);
|
||||
case "contact":
|
||||
case "contacts":
|
||||
case "staff":
|
||||
case "staffs":
|
||||
return await handleContactCommand(parsed, runtime);
|
||||
case "task":
|
||||
case "tasks":
|
||||
case "todo":
|
||||
return await handleTaskCommand(parsed, runtime);
|
||||
case "dimension":
|
||||
case "dimensions":
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
case "permission":
|
||||
case "permissions":
|
||||
return await handlePermissionCommand(parsed, runtime);
|
||||
case "rule":
|
||||
case "rules":
|
||||
return await handleRuleCommand(parsed, runtime);
|
||||
case "approval":
|
||||
case "approvals":
|
||||
case "audit":
|
||||
return await handleApprovalCommand(parsed, runtime);
|
||||
case "message":
|
||||
case "messages":
|
||||
case "notify":
|
||||
case "notifications":
|
||||
return await handleMessageCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "app":
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ export async function runServiceCommand(
|
||||
case undefined:
|
||||
return serviceStatus(config);
|
||||
default:
|
||||
throw new Error("用法: hose service <start|stop|restart|status|logs>");
|
||||
throw new Error("用法: hose service <start|stop|restart|status|logs|poll>");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,11 +86,7 @@ export function loadGlobalConfig(): GlobalConfig {
|
||||
// 容错返回默认
|
||||
}
|
||||
|
||||
return {
|
||||
stateful: true,
|
||||
defaultCorpId: undefined,
|
||||
defaultAccountId: undefined,
|
||||
};
|
||||
return GlobalConfigSchema.parse({});
|
||||
}
|
||||
|
||||
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
|
||||
@@ -65,6 +65,9 @@ export const GlobalConfigSchema = z.object({
|
||||
stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),
|
||||
defaultCorpId: z.string().optional().describe("默认工作企业 ID"),
|
||||
defaultAccountId: z.string().optional().describe("默认主账号"),
|
||||
updateRepo: z.string().optional().describe("默认自更新的 GitHub 仓库 (owner/repo)"),
|
||||
updateSource: z.enum(["auto", "github", "gitea"]).optional().default("auto").describe("默认自更新源通道偏好 (auto/github/gitea)"),
|
||||
});
|
||||
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
|
||||
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
expect(getSkillContent()).toContain("name: hose-use");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toContain("POST /api/cli");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "hose-skill-test-"));
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(11);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,31 @@
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import skillMain from "../../skills/hose-use/SKILL.md" with { type: "text" };
|
||||
import agentOpenAi from "../../skills/hose-use/agents/openai.yaml" with { type: "text" };
|
||||
import refAuth from "../../skills/hose-use/references/auth.md" with { type: "text" };
|
||||
import refBill from "../../skills/hose-use/references/bill.md" with { type: "text" };
|
||||
import refWorkflow from "../../skills/hose-use/references/workflow.md" with { type: "text" };
|
||||
import refService from "../../skills/hose-use/references/service.md" with { type: "text" };
|
||||
import refContact from "../../skills/hose-use/references/contact.md" with { type: "text" };
|
||||
import refTask from "../../skills/hose-use/references/task.md" with { type: "text" };
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
"agents/openai.yaml": agentOpenAi,
|
||||
"references/auth.md": refAuth,
|
||||
"references/bill.md": refBill,
|
||||
"references/contact.md": refContact,
|
||||
"references/task.md": refTask,
|
||||
"references/message.md": refMessage,
|
||||
"references/dimension.md": refDimension,
|
||||
"references/role.md": refRole,
|
||||
"references/workflow.md": refWorkflow,
|
||||
"references/service.md": refService,
|
||||
};
|
||||
|
||||
export function getSkillContent(): string {
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "./db.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { ApprovalService } from "./service.js";
|
||||
import { ApprovalRuleValidationError } from "./types.js";
|
||||
|
||||
describe("Approval Domain - SQLite 持久化与规约仓储", () => {
|
||||
let db: Database;
|
||||
let repo: ApprovalRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
// 每次测试使用独立的内存数据库,隔离状态
|
||||
db = getApprovalDatabase(":memory:");
|
||||
repo = new ApprovalRepository(db);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
});
|
||||
|
||||
test("数据库初始化时自动种子化默认偏好配置", () => {
|
||||
const defaultPref = repo.getDefaultPreference();
|
||||
expect(defaultPref).toBeDefined();
|
||||
expect(defaultPref.id).toBe("default");
|
||||
expect(defaultPref.name).toBe("标准财务审批偏好");
|
||||
expect(defaultPref.rulesReject).toContain("@{硬性}");
|
||||
expect(defaultPref.rulesReview).toContain("@{特殊}");
|
||||
});
|
||||
|
||||
test("成功创建合规规则并自动递增编号", () => {
|
||||
const rule1 = repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[一定需要上传发票]{硬性},[尽量上传支付凭证]{弹性}。"
|
||||
});
|
||||
|
||||
expect(rule1.id).toBeDefined();
|
||||
expect(rule1.code).toBe(1);
|
||||
expect(rule1.scope).toBe("差旅报销");
|
||||
expect(rule1.version).toBe(1);
|
||||
expect(rule1.status).toBe("active");
|
||||
|
||||
const rule2 = repo.createRule({
|
||||
scope: "业务招待",
|
||||
body: "招待报销时,[必须提供菜单水单]{硬性};[建议注明客户姓名与职务]{建议}。"
|
||||
});
|
||||
|
||||
expect(rule2.code).toBe(2);
|
||||
expect(rule2.scope).toBe("业务招待");
|
||||
|
||||
expect(repo.countRules()).toBe(2);
|
||||
});
|
||||
|
||||
test("强校验拦截:不合规的规则正文物理禁止入库", () => {
|
||||
const initialCount = repo.countRules();
|
||||
|
||||
expect(() => {
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票]{严重}。" // 非法严格程度
|
||||
});
|
||||
}).toThrow(ApprovalRuleValidationError);
|
||||
|
||||
// 验证数据库没有任何脏数据写入
|
||||
expect(repo.countRules()).toBe(initialCount);
|
||||
|
||||
expect(() => {
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票],大家遵守。" // 悬空中括号
|
||||
});
|
||||
}).toThrow(ApprovalRuleValidationError);
|
||||
|
||||
expect(repo.countRules()).toBe(initialCount);
|
||||
});
|
||||
|
||||
test("更新规则正文时自动增加版本号并再次校验", () => {
|
||||
const created = repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "差旅报销时,[必须上传发票]{硬性}。"
|
||||
});
|
||||
|
||||
expect(created.version).toBe(1);
|
||||
|
||||
// 正常更新
|
||||
const updated = repo.updateRule(created.id, {
|
||||
body: "差旅报销时,[必须上传发票]{硬性};[尽量上传水单]{弹性}。"
|
||||
});
|
||||
|
||||
expect(updated.version).toBe(2);
|
||||
expect(updated.body).toContain("[尽量上传水单]{弹性}");
|
||||
|
||||
// 非法更新被拦截,原数据不变
|
||||
expect(() => {
|
||||
repo.updateRule(created.id, {
|
||||
body: "差旅报销时,[必须上传发票]{未知名词}。"
|
||||
});
|
||||
}).toThrow(ApprovalRuleValidationError);
|
||||
|
||||
const check = repo.getRuleById(created.id);
|
||||
expect(check?.version).toBe(2); // 版本未递增,未被篡改
|
||||
});
|
||||
|
||||
test("按 Scope 与 Status 进行条件过滤检索", () => {
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "[必须提供发票]{硬性}。"
|
||||
});
|
||||
|
||||
repo.createRule({
|
||||
scope: "差旅报销",
|
||||
body: "[尽量提供水单]{弹性}。",
|
||||
status: "draft"
|
||||
});
|
||||
|
||||
repo.createRule({
|
||||
scope: "业务招待",
|
||||
body: "[必须提供人均名单]{硬性}。"
|
||||
});
|
||||
|
||||
const travelRules = repo.listRules({ scope: "差旅报销" });
|
||||
expect(travelRules.length).toBe(2);
|
||||
|
||||
const activeTravelRules = repo.listRules({ scope: "差旅报销", status: "active" });
|
||||
expect(activeTravelRules.length).toBe(1);
|
||||
|
||||
const entertainRules = repo.listRules({ scope: "业务招待" });
|
||||
expect(entertainRules.length).toBe(1);
|
||||
});
|
||||
|
||||
test("一键获取去重索引列表 listScopes 及对应的索引编号", () => {
|
||||
// 插入多条规则,部分共享相同索引
|
||||
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
|
||||
repo.createRule({ scope: "差旅报销", body: "[尽量上传水单]{弹性}。" });
|
||||
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
|
||||
repo.createRule({ scope: "差旅报销", body: "[建议注明事由]{建议}。" });
|
||||
repo.createRule({ scope: "办公采购", body: "[发票抬头须一致]{硬性}。" });
|
||||
|
||||
const scopes = repo.listScopes("active");
|
||||
|
||||
expect(scopes.length).toBe(3); // 差旅报销、业务招待、办公采购
|
||||
|
||||
// 验证索引 1:差旅报销
|
||||
expect(scopes[0]!.index).toBe(1);
|
||||
expect(scopes[0]!.scope).toBe("差旅报销");
|
||||
expect(scopes[0]!.ruleCount).toBe(3);
|
||||
expect(scopes[0]!.ruleCodes).toEqual([1, 2, 4]);
|
||||
|
||||
// 验证索引 2:业务招待
|
||||
expect(scopes[1]!.index).toBe(2);
|
||||
expect(scopes[1]!.scope).toBe("业务招待");
|
||||
expect(scopes[1]!.ruleCount).toBe(1);
|
||||
expect(scopes[1]!.ruleCodes).toEqual([3]);
|
||||
|
||||
// 验证索引 3:办公采购
|
||||
expect(scopes[2]!.index).toBe(3);
|
||||
expect(scopes[2]!.scope).toBe("办公采购");
|
||||
expect(scopes[2]!.ruleCount).toBe(1);
|
||||
expect(scopes[2]!.ruleCodes).toEqual([5]);
|
||||
});
|
||||
|
||||
test("通过索引编号或索引名称获取该索引对应的所有规则明细 getScopeDetail", () => {
|
||||
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
|
||||
repo.createRule({ scope: "差旅报销", body: "[尽量上传支付凭证]{弹性}。" });
|
||||
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
|
||||
|
||||
// 1. 通过数字索引号 1 检索
|
||||
const detailByIndex = repo.getScopeDetail(1);
|
||||
expect(detailByIndex).not.toBeNull();
|
||||
expect(detailByIndex!.scope).toBe("差旅报销");
|
||||
expect(detailByIndex!.rules.length).toBe(2);
|
||||
expect(detailByIndex!.rules[0]!.parsed.clauses[0]!.strictness).toBe("硬性");
|
||||
expect(detailByIndex!.rules[1]!.parsed.clauses[0]!.strictness).toBe("弹性");
|
||||
|
||||
// 2. 通过索引名称 "业务招待" 检索
|
||||
const detailByName = repo.getScopeDetail("业务招待");
|
||||
expect(detailByName).not.toBeNull();
|
||||
expect(detailByName!.index).toBe(2);
|
||||
expect(detailByName!.rules.length).toBe(1);
|
||||
|
||||
// 3. 不存在的索引号返回 null
|
||||
expect(repo.getScopeDetail(999)).toBeNull();
|
||||
expect(repo.getScopeDetail("不存在的场景")).toBeNull();
|
||||
});
|
||||
|
||||
test("风格偏好的更新与非法引用拦截", () => {
|
||||
const pref = repo.getDefaultPreference();
|
||||
|
||||
const updated = repo.updatePreference(pref.id, {
|
||||
name: "宽松型偏好",
|
||||
rulesReview: "触发 @{特殊} 条款;未满足 @{弹性} 且金额 > 2000 元"
|
||||
});
|
||||
|
||||
expect(updated.name).toBe("宽松型偏好");
|
||||
expect(updated.rulesReview).toContain("金额 > 2000 元");
|
||||
|
||||
// 非法偏好引用被拦截
|
||||
expect(() => {
|
||||
repo.updatePreference(pref.id, {
|
||||
rulesReview: "触犯 @{严重} 条款则复核"
|
||||
});
|
||||
}).toThrow(ApprovalRuleValidationError);
|
||||
});
|
||||
|
||||
test("审批运行、要点清单注入与全流程审计流水登记", () => {
|
||||
// 1. 创建审批运行记录并注入要点清单
|
||||
const run = repo.createOrResetApprovalRun({
|
||||
documentSn: "TEST260001",
|
||||
flowId: "FLOW_001",
|
||||
decision: "PENDING",
|
||||
});
|
||||
|
||||
expect(run.id).toBeDefined();
|
||||
expect(run.documentSn).toBe("TEST260001");
|
||||
expect(run.decision).toBe("PENDING");
|
||||
|
||||
const findings = repo.injectFindings(run.id, [
|
||||
{ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PENDING" },
|
||||
{ clauseText: "建议说明事由", strictness: "建议", checkStatus: "PENDING" },
|
||||
]);
|
||||
|
||||
expect(findings.length).toBe(2);
|
||||
expect(findings[0]!.strictness).toBe("硬性");
|
||||
expect(findings[0]!.checkStatus).toBe("PENDING");
|
||||
|
||||
// 2. 更新核验状态
|
||||
const updated = repo.updateFinding(findings[0]!.id, {
|
||||
checkStatus: "FAIL",
|
||||
evidence: "未提供发票附件",
|
||||
});
|
||||
expect(updated.checkStatus).toBe("FAIL");
|
||||
expect(updated.evidence).toBe("未提供发票附件");
|
||||
|
||||
// 3. 登记 AI PRO 审计监控日志
|
||||
const log = repo.logAiProAction({
|
||||
action: "decide",
|
||||
documentSn: "TEST260001",
|
||||
operator: "AI-Agent-01",
|
||||
status: "BLOCKED",
|
||||
decision: "REJECT",
|
||||
summary: "硬性违规条款未通过,网关阻断放行",
|
||||
});
|
||||
|
||||
expect(log.id).toBeDefined();
|
||||
expect(log.status).toBe("BLOCKED");
|
||||
|
||||
const logs = repo.listAiProLogs("TEST260001");
|
||||
expect(logs.length).toBe(1);
|
||||
expect(logs[0]!.action).toBe("decide");
|
||||
expect(logs[0]!.status).toBe("BLOCKED");
|
||||
});
|
||||
|
||||
test("审批运行按当前企业隔离相同单号", () => {
|
||||
const corpARun = repo.createOrResetApprovalRun({
|
||||
documentSn: "SAME-SN",
|
||||
corpId: "corp-a",
|
||||
decision: "PENDING",
|
||||
});
|
||||
repo.injectFindings(corpARun.id, [
|
||||
{ clauseText: "企业 A 要点", strictness: "硬性", checkStatus: "PENDING" },
|
||||
]);
|
||||
|
||||
const corpBRun = repo.createOrResetApprovalRun({
|
||||
documentSn: "SAME-SN",
|
||||
corpId: "corp-b",
|
||||
decision: "PENDING",
|
||||
});
|
||||
expect(corpBRun.id).not.toBe(corpARun.id);
|
||||
expect(repo.getAuditChecklist("SAME-SN", "corp-a").findings[0]?.clauseText).toBe("企业 A 要点");
|
||||
expect(repo.getAuditChecklist("SAME-SN", "corp-b").findings).toEqual([]);
|
||||
});
|
||||
|
||||
test("下游审批执行失败时将运行标记为 ERROR", async () => {
|
||||
const run = repo.createOrResetApprovalRun({
|
||||
documentSn: "EXEC-FAIL",
|
||||
corpId: "corp-a",
|
||||
decision: "PENDING",
|
||||
});
|
||||
repo.injectFindings(run.id, [
|
||||
{ clauseText: "已核验", strictness: "硬性", checkStatus: "PASS" },
|
||||
]);
|
||||
|
||||
const service = new ApprovalService(repo);
|
||||
const client = {
|
||||
post: async () => {
|
||||
throw new Error("downstream unavailable");
|
||||
},
|
||||
} as any;
|
||||
|
||||
await expect(
|
||||
service.decideAudit(client, "corp-a", "EXEC-FAIL", {
|
||||
apply: true,
|
||||
requestedAction: "approve",
|
||||
}),
|
||||
).rejects.toThrow("downstream unavailable");
|
||||
|
||||
expect(repo.getAuditChecklist("EXEC-FAIL", "corp-a").run?.decision).toBe("ERROR");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
export const DEFAULT_APPROVAL_DB_PATH = join(
|
||||
homedir(),
|
||||
".config",
|
||||
"hose-use",
|
||||
"approval.db"
|
||||
);
|
||||
|
||||
export function resolveApprovalDbPath(): string {
|
||||
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
|
||||
if (envPath) {
|
||||
return envPath;
|
||||
}
|
||||
return DEFAULT_APPROVAL_DB_PATH;
|
||||
}
|
||||
|
||||
let activeDb: Database | null = null;
|
||||
let currentDbPath: string | null = null;
|
||||
|
||||
/**
|
||||
* 获取或创建 SQLite 数据库连接单例
|
||||
*/
|
||||
export function getApprovalDatabase(customPath?: string): Database {
|
||||
const targetPath = customPath ?? resolveApprovalDbPath();
|
||||
|
||||
if (activeDb && currentDbPath === targetPath) {
|
||||
return activeDb;
|
||||
}
|
||||
|
||||
// 内存数据库无需创建目录
|
||||
if (targetPath !== ":memory:") {
|
||||
const dir = dirname(targetPath);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
}
|
||||
|
||||
const db = new Database(targetPath);
|
||||
if (targetPath !== ":memory:") {
|
||||
// 规则、单据快照、审核证据和审计日志都可能包含敏感信息。
|
||||
// SQLite 默认文件权限受 umask 影响,不能依赖默认值保护凭证与业务数据。
|
||||
chmodSync(targetPath, 0o600);
|
||||
}
|
||||
currentDbPath = targetPath;
|
||||
activeDb = db;
|
||||
|
||||
initDatabaseSchema(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
|
||||
*/
|
||||
export function closeApprovalDatabase(): void {
|
||||
if (activeDb) {
|
||||
activeDb.close();
|
||||
activeDb = null;
|
||||
currentDbPath = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化表结构与默认数据
|
||||
*/
|
||||
export function initDatabaseSchema(db: Database): void {
|
||||
// 启用 WAL 模式提高并发性能与数据安全性
|
||||
db.run("PRAGMA journal_mode = WAL;");
|
||||
db.run("PRAGMA foreign_keys = ON;");
|
||||
|
||||
// 1. 规约主表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS rules (
|
||||
id TEXT PRIMARY KEY,
|
||||
code INTEGER NOT NULL UNIQUE,
|
||||
scope TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);");
|
||||
|
||||
// 2. 风格偏好表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS preferences (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
is_default INTEGER NOT NULL DEFAULT 0,
|
||||
rules_reject TEXT NOT NULL,
|
||||
rules_review TEXT NOT NULL,
|
||||
rules_pass_note TEXT NOT NULL,
|
||||
rules_approve TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
// 3. 审批运行执行记录表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS approval_runs (
|
||||
id TEXT PRIMARY KEY,
|
||||
flow_id TEXT,
|
||||
document_sn TEXT NOT NULL,
|
||||
corp_id TEXT,
|
||||
decision TEXT NOT NULL,
|
||||
decision_summary TEXT,
|
||||
matched_rules_count INTEGER NOT NULL DEFAULT 0,
|
||||
failed_rules_count INTEGER NOT NULL DEFAULT 0,
|
||||
document_snapshot TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
|
||||
|
||||
// 4. 审批要点事实记录表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS approval_findings (
|
||||
id TEXT PRIMARY KEY,
|
||||
run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE,
|
||||
rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL,
|
||||
clause_text TEXT NOT NULL,
|
||||
strictness TEXT NOT NULL,
|
||||
check_status TEXT NOT NULL,
|
||||
evidence TEXT,
|
||||
reasoning TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);");
|
||||
|
||||
// 5. AI PRO 全流程操作与审计监控流水表
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS aipro_logs (
|
||||
id TEXT PRIMARY KEY,
|
||||
action TEXT NOT NULL,
|
||||
document_sn TEXT,
|
||||
operator TEXT,
|
||||
args TEXT,
|
||||
status TEXT NOT NULL,
|
||||
decision TEXT,
|
||||
summary TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
|
||||
|
||||
// 种子数据:初始化默认偏好
|
||||
seedDefaultPreference(db);
|
||||
}
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
const existing = db.query("SELECT id FROM preferences WHERE id = 'default'").get();
|
||||
if (!existing) {
|
||||
const now = Date.now();
|
||||
db.run(
|
||||
`
|
||||
INSERT INTO preferences (
|
||||
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
"default",
|
||||
"标准财务审批偏好",
|
||||
1,
|
||||
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
|
||||
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
|
||||
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
|
||||
"所有条款全部满足,秒级免审全自动通过",
|
||||
now
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./parser.js";
|
||||
export * from "./db.js";
|
||||
export * from "./repository.js";
|
||||
export * from "./service.js";
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { parseRuleBody, validatePreferenceText } from "./parser.js";
|
||||
import { ApprovalRuleValidationError } from "./types.js";
|
||||
|
||||
describe("Approval Rule Parser - 规则语法解析与校验", () => {
|
||||
test("正常解析包含单一硬性条款的规则", () => {
|
||||
const text = "差旅报销时,[必须上传真实有效的发票]{硬性}。";
|
||||
const result = parseRuleBody(text);
|
||||
|
||||
expect(result.clauses.length).toBe(1);
|
||||
expect(result.clauses[0]!.action).toBe("必须上传真实有效的发票");
|
||||
expect(result.clauses[0]!.strictness).toBe("硬性");
|
||||
expect(result.cleanText).toBe("差旅报销时,必须上传真实有效的发票。");
|
||||
});
|
||||
|
||||
test("正常解析包含复合梯度(硬性、弹性、建议、特殊)的整段自然语言规约", () => {
|
||||
const text =
|
||||
"员工进行差旅报销时,[一定需要上传发票]{硬性}。[尽量上传支付凭证]{弹性}以佐证真实性;" +
|
||||
"如涉及大额费用或合规争议,[须提交法务专项审核]{特殊};针对市内同城交通,[建议补充说明消费事由]{建议}。";
|
||||
|
||||
const result = parseRuleBody(text);
|
||||
|
||||
expect(result.clauses.length).toBe(4);
|
||||
expect(result.clauses[0]!.action).toBe("一定需要上传发票");
|
||||
expect(result.clauses[0]!.strictness).toBe("硬性");
|
||||
|
||||
expect(result.clauses[1]!.action).toBe("尽量上传支付凭证");
|
||||
expect(result.clauses[1]!.strictness).toBe("弹性");
|
||||
|
||||
expect(result.clauses[2]!.action).toBe("须提交法务专项审核");
|
||||
expect(result.clauses[2]!.strictness).toBe("特殊");
|
||||
|
||||
expect(result.clauses[3]!.action).toBe("建议补充说明消费事由");
|
||||
expect(result.clauses[3]!.strictness).toBe("建议");
|
||||
|
||||
expect(result.cleanText).toBe(
|
||||
"员工进行差旅报销时,一定需要上传发票。尽量上传支付凭证以佐证真实性;" +
|
||||
"如涉及大额费用或合规争议,须提交法务专项审核;针对市内同城交通,建议补充说明消费事由。"
|
||||
);
|
||||
});
|
||||
|
||||
test("拦截非法的严格程度标签", () => {
|
||||
const text = "差旅报销时,[必须上传发票]{必须遵守}。";
|
||||
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
|
||||
expect(() => parseRuleBody(text)).toThrow('非法严格程度 "必须遵守"');
|
||||
});
|
||||
|
||||
test("拦截悬空的中括号(未指定严格程度)", () => {
|
||||
const text = "差旅报销时,[必须上传发票],请大家注意。";
|
||||
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
|
||||
expect(() => parseRuleBody(text)).toThrow('检测到未指定严格程度的标记 "[必须上传发票]"');
|
||||
});
|
||||
|
||||
test("拦截括号未闭合的语法错误", () => {
|
||||
expect(() => parseRuleBody("差旅报销时,[必须上传发票{硬性}。")).toThrow("未闭合的左中括号");
|
||||
expect(() => parseRuleBody("差旅报销时,[必须上传发票]{硬性。")).toThrow("未闭合的左花括号");
|
||||
expect(() => parseRuleBody("差旅报销时,必须上传发票]{硬性}。")).toThrow("未匹配的多余右中括号");
|
||||
});
|
||||
|
||||
test("拦截空的动作句式", () => {
|
||||
const text = "差旅报销时,[ ]{硬性}。";
|
||||
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
|
||||
expect(() => parseRuleBody(text)).toThrow("动作句式不能为空");
|
||||
});
|
||||
|
||||
test("拦截未包含任何判定标记的纯文字", () => {
|
||||
const text = "这是一段关于差旅报销的日常说明,没有任何裁判条款。";
|
||||
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
|
||||
expect(() => parseRuleBody(text)).toThrow("未包含任何有效的规则标记");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Approval Preference Parser - 偏好引用语法校验", () => {
|
||||
test("校验通过合法的 @{级别} 引用", () => {
|
||||
const text = "满足以下条件:触犯任何 @{硬性} 条款,或触发 @{特殊} 条款,或未满足 @{弹性} 且金额 > 500";
|
||||
expect(validatePreferenceText(text)).toBe(true);
|
||||
});
|
||||
|
||||
test("拦截非法的 @{级别} 引用", () => {
|
||||
const text = "若违反 @{严重} 条款则驳回";
|
||||
expect(() => validatePreferenceText(text)).toThrow(ApprovalRuleValidationError);
|
||||
expect(() => validatePreferenceText(text)).toThrow('非法的偏好引用 "@{严重}"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import {
|
||||
ApprovalRuleValidationError,
|
||||
isValidStrictnessTier,
|
||||
ParsedRule,
|
||||
RuleClause,
|
||||
StrictnessTier,
|
||||
VALID_STRICTNESS_TIERS
|
||||
} from "./types.js";
|
||||
|
||||
const CLAUSE_REGEX = /\[([^\[\]]+)\]\{([^{}]+)\}/g;
|
||||
const ORPHAN_BRACKET_REGEX = /\[([^\[\]]+)\](?!\s*\{)/g;
|
||||
const PREFERENCE_REF_REGEX = /@\{([^{}]+)\}/g;
|
||||
|
||||
/**
|
||||
* 解析并严格校验规则正文
|
||||
*
|
||||
* 规则正文格式:
|
||||
* 采用自然语言,在需要约束的判定点使用 [动作句式]{严格程度} 包裹。
|
||||
* 允许的严格程度:硬性 | 弹性 | 建议 | 特殊
|
||||
*
|
||||
* @throws {ApprovalRuleValidationError} 当语法不合规或严格程度非法时抛出
|
||||
*/
|
||||
export function parseRuleBody(body: string): ParsedRule {
|
||||
if (!body || typeof body !== "string" || body.trim().length === 0) {
|
||||
throw new ApprovalRuleValidationError("规则正文不能为空");
|
||||
}
|
||||
|
||||
// 1. 括号闭合完整性检查
|
||||
checkBracketBalance(body);
|
||||
|
||||
// 2. 检测悬空的中括号(即写了 [动作] 但漏掉了 {级别})
|
||||
const orphanMatches = Array.from(body.matchAll(ORPHAN_BRACKET_REGEX));
|
||||
if (orphanMatches.length > 0) {
|
||||
const firstOrphan = orphanMatches[0]![0];
|
||||
throw new ApprovalRuleValidationError(
|
||||
`检测到未指定严格程度的标记 "${firstOrphan}",请紧跟花括号指定级别,如 "${firstOrphan}{硬性}"`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 提取所有 [动作句式]{级别}
|
||||
const clauses: RuleClause[] = [];
|
||||
const matches = Array.from(body.matchAll(CLAUSE_REGEX));
|
||||
|
||||
for (const match of matches) {
|
||||
const raw = match[0];
|
||||
const rawAction = match[1];
|
||||
const rawTier = match[2];
|
||||
const startIndex = match.index ?? 0;
|
||||
const endIndex = startIndex + raw.length;
|
||||
|
||||
const action = rawAction ? rawAction.trim() : "";
|
||||
const tier = rawTier ? rawTier.trim() : "";
|
||||
|
||||
if (action.length === 0) {
|
||||
throw new ApprovalRuleValidationError(`动作句式不能为空: "${raw}"`);
|
||||
}
|
||||
|
||||
if (!isValidStrictnessTier(tier)) {
|
||||
throw new ApprovalRuleValidationError(
|
||||
`非法严格程度 "${tier}",仅支持:${VALID_STRICTNESS_TIERS.join("、")}`
|
||||
);
|
||||
}
|
||||
|
||||
clauses.push({
|
||||
action,
|
||||
strictness: tier as StrictnessTier,
|
||||
raw,
|
||||
startIndex,
|
||||
endIndex
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 一条合法的业务规约必须至少包含一个裁决要点
|
||||
if (clauses.length === 0) {
|
||||
throw new ApprovalRuleValidationError(
|
||||
`规则正文未包含任何有效的规则标记,格式须为 [动作句式]{${VALID_STRICTNESS_TIERS.join("|")}}`
|
||||
);
|
||||
}
|
||||
|
||||
// 5. 生成剥离语法标记后的纯净自然语言
|
||||
const cleanText = body.replace(CLAUSE_REGEX, (_match, action) => action.trim());
|
||||
|
||||
return {
|
||||
rawBody: body,
|
||||
clauses,
|
||||
cleanText
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验规则正文,合规返回 true,不合规抛出 ApprovalRuleValidationError
|
||||
*/
|
||||
export function validateRuleBody(body: string): boolean {
|
||||
parseRuleBody(body);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验偏好配置文本中的 @{级别} 引用
|
||||
*/
|
||||
export function validatePreferenceText(text: string): boolean {
|
||||
if (!text || typeof text !== "string") return true;
|
||||
|
||||
const matches = Array.from(text.matchAll(PREFERENCE_REF_REGEX));
|
||||
for (const match of matches) {
|
||||
const tier = match[1]?.trim() ?? "";
|
||||
if (!isValidStrictnessTier(tier)) {
|
||||
throw new ApprovalRuleValidationError(
|
||||
`非法的偏好引用 "@{${tier}}",仅支持:${VALID_STRICTNESS_TIERS.map((t) => `@{${t}}`).join("、")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 括号成对匹配与平衡检查
|
||||
*/
|
||||
function checkBracketBalance(text: string): void {
|
||||
let openSquare = 0;
|
||||
let openCurly = 0;
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
if (char === "[") {
|
||||
openSquare++;
|
||||
} else if (char === "]") {
|
||||
openSquare--;
|
||||
if (openSquare < 0) {
|
||||
throw new ApprovalRuleValidationError("检测到未匹配的多余右中括号 ']'");
|
||||
}
|
||||
} else if (char === "{") {
|
||||
openCurly++;
|
||||
} else if (char === "}") {
|
||||
openCurly--;
|
||||
if (openCurly < 0) {
|
||||
throw new ApprovalRuleValidationError("检测到未匹配的多余右花括号 '}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (openSquare > 0) {
|
||||
throw new ApprovalRuleValidationError("检测到未闭合的左中括号 '['");
|
||||
}
|
||||
if (openCurly > 0) {
|
||||
throw new ApprovalRuleValidationError("检测到未闭合的左花括号 '{'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { getApprovalDatabase } from "./db.js";
|
||||
import { parseRuleBody, validatePreferenceText } from "./parser.js";
|
||||
import {
|
||||
AiProLogRecord,
|
||||
ApprovalDecision,
|
||||
ApprovalFindingRecord,
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
PreferenceRecord,
|
||||
RuleRecord,
|
||||
ScopeDetail,
|
||||
ScopeSummary,
|
||||
StrictnessTier
|
||||
} from "./types.js";
|
||||
|
||||
export interface CreateRuleInput {
|
||||
scope: string;
|
||||
body: string;
|
||||
status?: "active" | "draft" | "archived";
|
||||
}
|
||||
|
||||
export interface UpdateRuleInput {
|
||||
scope?: string;
|
||||
body?: string;
|
||||
status?: "active" | "draft" | "archived";
|
||||
}
|
||||
|
||||
export interface ListRulesFilter {
|
||||
scope?: string;
|
||||
status?: "active" | "draft" | "archived";
|
||||
}
|
||||
|
||||
export class ApprovalRepository {
|
||||
private db: Database;
|
||||
|
||||
constructor(db?: Database) {
|
||||
this.db = db ?? getApprovalDatabase();
|
||||
}
|
||||
|
||||
// ===================== 规约管理 (Rules) =====================
|
||||
|
||||
/**
|
||||
* 创建规则:必须先通过语法校验器,校验通过方可入库
|
||||
*/
|
||||
public createRule(input: CreateRuleInput): RuleRecord {
|
||||
// 语法强校验拦截:不合规直接抛错,物理阻止入库
|
||||
parseRuleBody(input.body);
|
||||
|
||||
const now = Date.now();
|
||||
const id = crypto.randomUUID();
|
||||
|
||||
// 自动分配自增可读编号 code
|
||||
const maxCodeRow = this.db
|
||||
.query("SELECT COALESCE(MAX(code), 0) AS maxCode FROM rules")
|
||||
.get() as { maxCode: number } | null;
|
||||
const nextCode = (maxCodeRow?.maxCode ?? 0) + 1;
|
||||
|
||||
const status = input.status ?? "active";
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO rules (id, code, scope, body, status, version, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?)
|
||||
`,
|
||||
[id, nextCode, input.scope.trim(), input.body.trim(), status, now, now]
|
||||
);
|
||||
|
||||
return this.getRuleById(id)!;
|
||||
}
|
||||
|
||||
public getRuleById(id: string): RuleRecord | null {
|
||||
const row = this.db.query("SELECT * FROM rules WHERE id = ?").get(id) as any;
|
||||
return row ? this.mapRuleRow(row) : null;
|
||||
}
|
||||
|
||||
public getRuleByCode(code: number): RuleRecord | null {
|
||||
const row = this.db.query("SELECT * FROM rules WHERE code = ?").get(code) as any;
|
||||
return row ? this.mapRuleRow(row) : null;
|
||||
}
|
||||
|
||||
public listRules(filter?: ListRulesFilter): RuleRecord[] {
|
||||
const conditions: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
if (filter?.scope) {
|
||||
conditions.push("scope = ?");
|
||||
params.push(filter.scope.trim());
|
||||
}
|
||||
if (filter?.status) {
|
||||
conditions.push("status = ?");
|
||||
params.push(filter.status);
|
||||
}
|
||||
|
||||
let sql = "SELECT * FROM rules";
|
||||
if (conditions.length > 0) {
|
||||
sql += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
sql += " ORDER BY code ASC";
|
||||
|
||||
const rows = this.db.query(sql).all(...params) as any[];
|
||||
return rows.map((r) => this.mapRuleRow(r));
|
||||
}
|
||||
|
||||
public countRules(filter?: ListRulesFilter): number {
|
||||
const conditions: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
if (filter?.scope) {
|
||||
conditions.push("scope = ?");
|
||||
params.push(filter.scope.trim());
|
||||
}
|
||||
if (filter?.status) {
|
||||
conditions.push("status = ?");
|
||||
params.push(filter.status);
|
||||
}
|
||||
|
||||
let sql = "SELECT COUNT(*) as cnt FROM rules";
|
||||
if (conditions.length > 0) {
|
||||
sql += " WHERE " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
const row = this.db.query(sql).get(...params) as { cnt: number } | null;
|
||||
return row?.cnt ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取去重后的所有索引(适用场景)列表及统计信息
|
||||
* 每个索引按出现次序/最小编号分配 1-based 索引编号 (1, 2, 3...)
|
||||
*/
|
||||
public listScopes(status: "active" | "draft" | "archived" = "active"): ScopeSummary[] {
|
||||
const rows = this.db
|
||||
.query(`
|
||||
SELECT scope, COUNT(*) as ruleCount, GROUP_CONCAT(code) as codeList
|
||||
FROM rules
|
||||
WHERE status = ?
|
||||
GROUP BY scope
|
||||
ORDER BY MIN(code) ASC
|
||||
`)
|
||||
.all(status) as any[];
|
||||
|
||||
return rows.map((row, idx) => {
|
||||
const ruleCodes = String(row.codeList || "")
|
||||
.split(",")
|
||||
.map((c) => Number(c.trim()))
|
||||
.filter((c) => !isNaN(c))
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
return {
|
||||
index: idx + 1,
|
||||
scope: row.scope,
|
||||
ruleCount: Number(row.ruleCount),
|
||||
ruleCodes
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 1-based 索引号或索引全名,获取该索引下的所有有效规约明细
|
||||
*/
|
||||
public getScopeDetail(indexOrName: number | string): ScopeDetail | null {
|
||||
const scopes = this.listScopes("active");
|
||||
let targetScope: ScopeSummary | undefined;
|
||||
|
||||
const trimmed = String(indexOrName).trim();
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const idx = Number(trimmed);
|
||||
targetScope = scopes.find((s) => s.index === idx);
|
||||
} else {
|
||||
targetScope = scopes.find(
|
||||
(s) => s.scope.toLowerCase() === trimmed.toLowerCase()
|
||||
);
|
||||
}
|
||||
|
||||
if (!targetScope) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rules = this.listRules({ scope: targetScope.scope, status: "active" });
|
||||
const detailedRules = rules.map((r) => {
|
||||
const parsed = parseRuleBody(r.body);
|
||||
return {
|
||||
...r,
|
||||
parsed
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
index: targetScope.index,
|
||||
scope: targetScope.scope,
|
||||
ruleCount: targetScope.ruleCount,
|
||||
rules: detailedRules
|
||||
};
|
||||
}
|
||||
|
||||
public updateRule(id: string, updates: UpdateRuleInput): RuleRecord {
|
||||
const existing = this.getRuleById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的规则`);
|
||||
}
|
||||
|
||||
if (updates.body !== undefined) {
|
||||
parseRuleBody(updates.body);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const newScope = updates.scope !== undefined ? updates.scope.trim() : existing.scope;
|
||||
const newBody = updates.body !== undefined ? updates.body.trim() : existing.body;
|
||||
const newStatus = updates.status !== undefined ? updates.status : existing.status;
|
||||
const newVersion = existing.version + 1;
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE rules
|
||||
SET scope = ?, body = ?, status = ?, version = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[newScope, newBody, newStatus, newVersion, now, id]
|
||||
);
|
||||
|
||||
return this.getRuleById(id)!;
|
||||
}
|
||||
|
||||
public deleteRule(id: string): boolean {
|
||||
const result = this.db.run("DELETE FROM rules WHERE id = ?", [id]);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
// ===================== 风格偏好管理 (Preferences) =====================
|
||||
|
||||
public getDefaultPreference(): PreferenceRecord {
|
||||
const row = this.db
|
||||
.query("SELECT * FROM preferences WHERE is_default = 1 LIMIT 1")
|
||||
.get() as any;
|
||||
|
||||
if (!row) {
|
||||
const fallback = this.db
|
||||
.query("SELECT * FROM preferences ORDER BY updated_at DESC LIMIT 1")
|
||||
.get() as any;
|
||||
if (!fallback) {
|
||||
throw new Error("数据库未初始化默认偏好配置");
|
||||
}
|
||||
return this.mapPreferenceRow(fallback);
|
||||
}
|
||||
|
||||
return this.mapPreferenceRow(row);
|
||||
}
|
||||
|
||||
public getPreferenceById(id: string): PreferenceRecord | null {
|
||||
const row = this.db.query("SELECT * FROM preferences WHERE id = ?").get(id) as any;
|
||||
return row ? this.mapPreferenceRow(row) : null;
|
||||
}
|
||||
|
||||
public updatePreference(
|
||||
id: string,
|
||||
updates: Partial<Omit<PreferenceRecord, "id" | "updatedAt">>
|
||||
): PreferenceRecord {
|
||||
const existing = this.getPreferenceById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的偏好配置`);
|
||||
}
|
||||
|
||||
if (updates.rulesReject !== undefined) validatePreferenceText(updates.rulesReject);
|
||||
if (updates.rulesReview !== undefined) validatePreferenceText(updates.rulesReview);
|
||||
if (updates.rulesPassNote !== undefined) validatePreferenceText(updates.rulesPassNote);
|
||||
if (updates.rulesApprove !== undefined) validatePreferenceText(updates.rulesApprove);
|
||||
|
||||
const now = Date.now();
|
||||
const name = updates.name ?? existing.name;
|
||||
const isDefault = updates.isDefault !== undefined ? (updates.isDefault ? 1 : 0) : existing.isDefault ? 1 : 0;
|
||||
const rulesReject = updates.rulesReject ?? existing.rulesReject;
|
||||
const rulesReview = updates.rulesReview ?? existing.rulesReview;
|
||||
const rulesPassNote = updates.rulesPassNote ?? existing.rulesPassNote;
|
||||
const rulesApprove = updates.rulesApprove ?? existing.rulesApprove;
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE preferences
|
||||
SET name = ?, is_default = ?, rules_reject = ?, rules_review = ?, rules_pass_note = ?, rules_approve = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[name, isDefault, rulesReject, rulesReview, rulesPassNote, rulesApprove, now, id]
|
||||
);
|
||||
|
||||
return this.getPreferenceById(id)!;
|
||||
}
|
||||
|
||||
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
|
||||
|
||||
public createOrResetApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
|
||||
const now = Date.now();
|
||||
if (existing) {
|
||||
// 清理旧要点,重置运行记录
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
return this.getRunById(existing.id)!;
|
||||
}
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO approval_runs (
|
||||
id, flow_id, document_sn, corp_id, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.flowId ?? null,
|
||||
input.documentSn.trim(),
|
||||
input.corpId ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
input.decisionSummary ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
input.documentSnapshot ?? null,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
);
|
||||
|
||||
return this.getRunById(id)!;
|
||||
}
|
||||
|
||||
public getLatestRunBySn(documentSn: string, corpId?: string): ApprovalRunRecord | null {
|
||||
const params: string[] = [documentSn.trim()];
|
||||
let sql = "SELECT * FROM approval_runs WHERE document_sn = ?";
|
||||
if (corpId !== undefined) {
|
||||
sql += " AND corp_id = ?";
|
||||
params.push(corpId);
|
||||
}
|
||||
sql += " ORDER BY created_at DESC LIMIT 1";
|
||||
const row = this.db.query(sql).get(...params) as any;
|
||||
return row ? this.mapRunRow(row) : null;
|
||||
}
|
||||
|
||||
public getRunById(id: string): ApprovalRunRecord | null {
|
||||
const row = this.db.query("SELECT * FROM approval_runs WHERE id = ?").get(id) as any;
|
||||
return row ? this.mapRunRow(row) : null;
|
||||
}
|
||||
|
||||
public updateApprovalRun(
|
||||
id: string,
|
||||
updates: Partial<Omit<ApprovalRunRecord, "id" | "documentSn" | "createdAt">>
|
||||
): ApprovalRunRecord {
|
||||
const existing = this.getRunById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的审批运行记录`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const flowId = updates.flowId !== undefined ? updates.flowId : existing.flowId;
|
||||
const corpId = updates.corpId !== undefined ? updates.corpId : existing.corpId;
|
||||
const decision = updates.decision !== undefined ? updates.decision : existing.decision;
|
||||
const decisionSummary = updates.decisionSummary !== undefined ? updates.decisionSummary : existing.decisionSummary;
|
||||
const matchedRulesCount = updates.matchedRulesCount !== undefined ? updates.matchedRulesCount : existing.matchedRulesCount;
|
||||
const failedRulesCount = updates.failedRulesCount !== undefined ? updates.failedRulesCount : existing.failedRulesCount;
|
||||
const documentSnapshot = updates.documentSnapshot !== undefined ? updates.documentSnapshot : existing.documentSnapshot;
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
flowId ?? null,
|
||||
corpId ?? null,
|
||||
decision ?? "PENDING",
|
||||
decisionSummary ?? null,
|
||||
matchedRulesCount,
|
||||
failedRulesCount,
|
||||
documentSnapshot ?? null,
|
||||
now,
|
||||
id,
|
||||
]
|
||||
);
|
||||
|
||||
return this.getRunById(id)!;
|
||||
}
|
||||
|
||||
public injectFindings(runId: string, findings: CreateFindingInput[]): ApprovalFindingRecord[] {
|
||||
const run = this.getRunById(runId);
|
||||
if (!run) {
|
||||
throw new Error(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
const id = crypto.randomUUID();
|
||||
insertStmt.run(
|
||||
id,
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
);
|
||||
}
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
|
||||
return this.getFindingsByRunId(runId);
|
||||
}
|
||||
|
||||
public getFindingsByRunId(runId: string): ApprovalFindingRecord[] {
|
||||
const rows = this.db
|
||||
.query("SELECT * FROM approval_findings WHERE run_id = ? ORDER BY rowid ASC")
|
||||
.all(runId) as any[];
|
||||
return rows.map((r) => this.mapFindingRow(r));
|
||||
}
|
||||
|
||||
public updateFinding(
|
||||
findingId: string,
|
||||
updates: {
|
||||
checkStatus?: FindingCheckStatus;
|
||||
evidence?: string | null;
|
||||
reasoning?: string | null;
|
||||
}
|
||||
): ApprovalFindingRecord {
|
||||
const row = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
|
||||
if (!row) {
|
||||
throw new Error(`未找到审核要点记录: ${findingId}`);
|
||||
}
|
||||
|
||||
const checkStatus = updates.checkStatus ?? row.check_status;
|
||||
const evidence = updates.evidence !== undefined ? updates.evidence : row.evidence;
|
||||
const reasoning = updates.reasoning !== undefined ? updates.reasoning : row.reasoning;
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_findings
|
||||
SET check_status = ?, evidence = ?, reasoning = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[checkStatus, evidence, reasoning, findingId]
|
||||
);
|
||||
|
||||
const updated = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
|
||||
return this.mapFindingRow(updated);
|
||||
}
|
||||
|
||||
public getAuditChecklist(documentSn: string, corpId?: string): {
|
||||
run: ApprovalRunRecord | null;
|
||||
findings: ApprovalFindingRecord[];
|
||||
} {
|
||||
const run = this.getLatestRunBySn(documentSn, corpId);
|
||||
if (!run) {
|
||||
return { run: null, findings: [] };
|
||||
}
|
||||
const findings = this.getFindingsByRunId(run.id);
|
||||
return { run, findings };
|
||||
}
|
||||
|
||||
// ===================== 内部字段映射 =====================
|
||||
|
||||
private mapRuleRow(row: any): RuleRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
code: Number(row.code),
|
||||
scope: row.scope,
|
||||
body: row.body,
|
||||
status: row.status,
|
||||
version: Number(row.version),
|
||||
createdAt: Number(row.created_at),
|
||||
updatedAt: Number(row.updated_at)
|
||||
};
|
||||
}
|
||||
|
||||
private mapPreferenceRow(row: any): PreferenceRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
isDefault: Boolean(row.is_default),
|
||||
rulesReject: row.rules_reject,
|
||||
rulesReview: row.rules_review,
|
||||
rulesPassNote: row.rules_pass_note,
|
||||
rulesApprove: row.rules_approve,
|
||||
updatedAt: Number(row.updated_at)
|
||||
};
|
||||
}
|
||||
|
||||
private mapRunRow(row: any): ApprovalRunRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
flowId: row.flow_id,
|
||||
documentSn: row.document_sn,
|
||||
corpId: row.corp_id,
|
||||
decision: row.decision as ApprovalDecision,
|
||||
decisionSummary: row.decision_summary,
|
||||
matchedRulesCount: Number(row.matched_rules_count || 0),
|
||||
failedRulesCount: Number(row.failed_rules_count || 0),
|
||||
documentSnapshot: row.document_snapshot,
|
||||
createdAt: Number(row.created_at),
|
||||
updatedAt: Number(row.updated_at),
|
||||
};
|
||||
}
|
||||
|
||||
private mapFindingRow(row: any): ApprovalFindingRecord {
|
||||
let ruleCode: number | undefined;
|
||||
if (row.rule_id) {
|
||||
const rule = this.db.query("SELECT code FROM rules WHERE id = ?").get(row.rule_id) as any;
|
||||
if (rule) ruleCode = Number(rule.code);
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
runId: row.run_id,
|
||||
ruleId: row.rule_id,
|
||||
ruleCode,
|
||||
clauseText: row.clause_text,
|
||||
strictness: row.strictness as StrictnessTier,
|
||||
checkStatus: row.check_status as FindingCheckStatus,
|
||||
evidence: row.evidence,
|
||||
reasoning: row.reasoning,
|
||||
createdAt: Number(row.created_at),
|
||||
};
|
||||
}
|
||||
|
||||
// ===================== AI PRO 审计监控日志 (Audit Logs) =====================
|
||||
|
||||
public logAiProAction(input: CreateAiProLogInput): AiProLogRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const now = Date.now();
|
||||
|
||||
this.db.run(
|
||||
`
|
||||
INSERT INTO aipro_logs (id, action, document_sn, operator, args, status, decision, summary, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.action,
|
||||
input.documentSn ?? null,
|
||||
input.operator ?? null,
|
||||
input.args ?? null,
|
||||
input.status,
|
||||
input.decision ?? null,
|
||||
input.summary ?? null,
|
||||
now,
|
||||
]
|
||||
);
|
||||
|
||||
return {
|
||||
id,
|
||||
action: input.action,
|
||||
documentSn: input.documentSn,
|
||||
operator: input.operator,
|
||||
args: input.args,
|
||||
status: input.status,
|
||||
decision: input.decision,
|
||||
summary: input.summary,
|
||||
createdAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
public listAiProLogs(documentSn?: string, limit = 50): AiProLogRecord[] {
|
||||
let sql = "SELECT * FROM aipro_logs";
|
||||
const params: any[] = [];
|
||||
if (documentSn) {
|
||||
sql += " WHERE document_sn = ?";
|
||||
params.push(documentSn.trim());
|
||||
}
|
||||
sql += " ORDER BY created_at DESC LIMIT ?";
|
||||
params.push(limit);
|
||||
|
||||
const rows = this.db.query(sql).all(...params) as any[];
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
action: r.action,
|
||||
documentSn: r.document_sn,
|
||||
operator: r.operator,
|
||||
args: r.args,
|
||||
status: r.status as "SUCCESS" | "BLOCKED" | "ERROR",
|
||||
decision: r.decision as ApprovalDecision | null,
|
||||
summary: r.summary,
|
||||
createdAt: Number(r.created_at),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateApprovalRunInput {
|
||||
documentSn: string;
|
||||
flowId?: string | null;
|
||||
corpId?: string | null;
|
||||
decision?: ApprovalDecision;
|
||||
decisionSummary?: string | null;
|
||||
matchedRulesCount?: number;
|
||||
failedRulesCount?: number;
|
||||
documentSnapshot?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateFindingInput {
|
||||
ruleId?: string | null;
|
||||
clauseText: string;
|
||||
strictness: StrictnessTier;
|
||||
checkStatus?: FindingCheckStatus;
|
||||
evidence?: string | null;
|
||||
reasoning?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateAiProLogInput {
|
||||
action: string;
|
||||
documentSn?: string | null;
|
||||
operator?: string | null;
|
||||
args?: string | null;
|
||||
status: "SUCCESS" | "BLOCKED" | "ERROR";
|
||||
decision?: ApprovalDecision | null;
|
||||
summary?: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { parseRuleBody } from "./parser.js";
|
||||
import {
|
||||
ApprovalDecision,
|
||||
ApprovalFindingRecord,
|
||||
ApprovalGatewayBlockedError,
|
||||
ApprovalRunRecord,
|
||||
FindingCheckStatus,
|
||||
} from "./types.js";
|
||||
import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js";
|
||||
import type { FormattedBill } from "../bill/types.js";
|
||||
|
||||
export interface InjectPointsResult {
|
||||
run: ApprovalRunRecord;
|
||||
findings: ApprovalFindingRecord[];
|
||||
bill: FormattedBill;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export interface DecideAuditOptions {
|
||||
requestedAction?: "approve" | "reject" | "comment";
|
||||
apply?: boolean;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export interface DecideAuditResult {
|
||||
run: ApprovalRunRecord;
|
||||
decision: ApprovalDecision;
|
||||
decisionSummary: string;
|
||||
hardFailedCount: number;
|
||||
elasticFailedCount: number;
|
||||
suggestFailedCount: number;
|
||||
specialFailedCount: number;
|
||||
appliedAction?: "approve" | "reject" | "comment";
|
||||
actionResult?: unknown;
|
||||
}
|
||||
|
||||
export class ApprovalService {
|
||||
private repo: ApprovalRepository;
|
||||
|
||||
constructor(repo?: ApprovalRepository) {
|
||||
this.repo = repo ?? new ApprovalRepository();
|
||||
}
|
||||
|
||||
/**
|
||||
* 第一步:规则注入,提取单据明细级审核要点清单
|
||||
*/
|
||||
public async injectAuditPoints(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
documentSn: string,
|
||||
options: { scope?: string | number } = {}
|
||||
): Promise<InjectPointsResult> {
|
||||
// 1. 获取单据详情
|
||||
const bills = await getBillByCodeOrId(client, corpId, documentSn);
|
||||
if (bills.length === 0) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`);
|
||||
}
|
||||
const bill = bills[0];
|
||||
const actualSn = bill.billCode || documentSn;
|
||||
|
||||
// 2. 匹配适用场景 (Scope)
|
||||
let scopeDetail = options.scope !== undefined ? this.repo.getScopeDetail(options.scope) : null;
|
||||
|
||||
if (!scopeDetail) {
|
||||
const allScopes = this.repo.listScopes();
|
||||
if (allScopes.length === 0) {
|
||||
throw new Error("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则");
|
||||
}
|
||||
|
||||
// 自动启发式场景匹配
|
||||
const candidates = [bill.title, bill.stage, bill.billName].filter(Boolean) as string[];
|
||||
let matchedSummary = allScopes.find((s) =>
|
||||
candidates.some((c) => c.includes(s.scope) || s.scope.includes(c))
|
||||
);
|
||||
|
||||
// 差旅特化匹配
|
||||
if (!matchedSummary && candidates.some((c) => /差旅|出差|trip|hotel|住宿/i.test(c))) {
|
||||
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
|
||||
}
|
||||
|
||||
// 默认回退至第一个场景
|
||||
matchedSummary = matchedSummary ?? allScopes[0];
|
||||
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
|
||||
}
|
||||
|
||||
if (!scopeDetail || scopeDetail.rules.length === 0) {
|
||||
throw new Error(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`);
|
||||
}
|
||||
|
||||
// 3. 提取所有规则的 AST 条款要点
|
||||
const clauseInputs: Array<{
|
||||
ruleId: string;
|
||||
ruleCode: number;
|
||||
clauseText: string;
|
||||
strictness: any;
|
||||
}> = [];
|
||||
|
||||
for (const rule of scopeDetail.rules) {
|
||||
const parsed = parseRuleBody(rule.body);
|
||||
for (const clause of parsed.clauses) {
|
||||
clauseInputs.push({
|
||||
ruleId: rule.id,
|
||||
ruleCode: rule.code,
|
||||
clauseText: clause.action,
|
||||
strictness: clause.strictness,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (clauseInputs.length === 0) {
|
||||
throw new Error(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`);
|
||||
}
|
||||
|
||||
// 4. 为单据创建/重置审批运行记录
|
||||
const run = this.repo.createOrResetApprovalRun({
|
||||
documentSn: actualSn,
|
||||
flowId: bill.billId,
|
||||
corpId,
|
||||
decision: "PENDING",
|
||||
matchedRulesCount: clauseInputs.length,
|
||||
failedRulesCount: 0,
|
||||
documentSnapshot: JSON.stringify(bill),
|
||||
});
|
||||
|
||||
// 5. 注入待核验要点清单 (Checklist)
|
||||
const findings = this.repo.injectFindings(
|
||||
run.id,
|
||||
clauseInputs.map((c) => ({
|
||||
ruleId: c.ruleId,
|
||||
clauseText: c.clauseText,
|
||||
strictness: c.strictness,
|
||||
checkStatus: "PENDING",
|
||||
}))
|
||||
);
|
||||
|
||||
return {
|
||||
run,
|
||||
findings,
|
||||
bill,
|
||||
scope: scopeDetail.scope,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看单据当前审核清单状态
|
||||
*/
|
||||
public getAuditChecklist(documentSn: string, corpId?: string) {
|
||||
return this.repo.getAuditChecklist(documentSn, corpId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 第二步:对注入的要点逐项进行事实核验判定
|
||||
*/
|
||||
public evaluateAuditPoints(
|
||||
documentSn: string,
|
||||
evaluations: Array<{
|
||||
index?: number;
|
||||
id?: string;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}>,
|
||||
corpId?: string,
|
||||
): ApprovalFindingRecord[] {
|
||||
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
|
||||
if (!run || findings.length === 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
|
||||
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
for (const item of evaluations) {
|
||||
let target: ApprovalFindingRecord | undefined;
|
||||
if (item.id) {
|
||||
target = findings.find((f) => f.id === item.id);
|
||||
} else if (item.index !== undefined) {
|
||||
target = findings[item.index - 1];
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
throw new Error(`未找到要点: ${item.id ?? `#${item.index}`}`);
|
||||
}
|
||||
|
||||
this.repo.updateFinding(target.id, {
|
||||
checkStatus: item.status,
|
||||
evidence: item.evidence,
|
||||
reasoning: item.reasoning,
|
||||
});
|
||||
}
|
||||
|
||||
return this.repo.getFindingsByRunId(run.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 第三步:确定性网关裁决与下游流转
|
||||
*/
|
||||
public async decideAudit(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
documentSn: string,
|
||||
options: DecideAuditOptions = {}
|
||||
): Promise<DecideAuditResult> {
|
||||
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
|
||||
|
||||
// ── 核心门禁 1:如果审核要点列表为空,审批链路物理不通! ────────────────────
|
||||
if (!run || findings.length === 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 核心门禁 2:检查是否有未完成事实核验的 PENDING 要点 ──────────────────────
|
||||
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
|
||||
if (pendingFindings.length > 0) {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚有 ${pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
|
||||
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
|
||||
`待核验项: ${pendingFindings.map((f, i) => `#${i + 1} [${f.strictness}] ${f.clauseText}`).join(";")}`
|
||||
);
|
||||
}
|
||||
|
||||
// ── 核心门禁 3:梯度级别与硬性刚性防线 ───────────────────────────────────────
|
||||
const failedFindings = findings.filter((f) => f.checkStatus === "FAIL");
|
||||
const hardFailed = failedFindings.filter((f) => f.strictness === "硬性");
|
||||
const specialFailed = failedFindings.filter((f) => f.strictness === "特殊");
|
||||
const elasticFailed = failedFindings.filter((f) => f.strictness === "弹性");
|
||||
const suggestFailed = failedFindings.filter((f) => f.strictness === "建议");
|
||||
|
||||
// 硬性条款违规拦截:物理切断 approve 通道
|
||||
if (hardFailed.length > 0 && options.requestedAction === "approve") {
|
||||
const violatedNames = hardFailed.map((f) => `【${f.clauseText}】`).join("、");
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[网关强力阻断] 单据 [${documentSn}] 触犯刚性底线【硬性】违规条款: ${violatedNames}!\n` +
|
||||
`网关物理切断同意分支,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
|
||||
);
|
||||
}
|
||||
|
||||
// 计算网关裁决决策
|
||||
let decision: ApprovalDecision;
|
||||
if (hardFailed.length > 0) {
|
||||
decision = "REJECT";
|
||||
} else if (specialFailed.length > 0) {
|
||||
decision = "REVIEW";
|
||||
} else if (elasticFailed.length > 0) {
|
||||
decision = elasticFailed.length >= 3 ? "REVIEW" : "PASS_WITH_NOTE";
|
||||
} else if (suggestFailed.length > 0) {
|
||||
decision = "PASS_WITH_NOTE";
|
||||
} else {
|
||||
decision = "APPROVE";
|
||||
}
|
||||
|
||||
// 组装格式化合规意见报告
|
||||
const summaryLines: string[] = [];
|
||||
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
|
||||
summaryLines.push(`单号: ${documentSn} | 审核要点总数: ${findings.length} 项`);
|
||||
summaryLines.push(``);
|
||||
summaryLines.push(`[逐项核验事实]`);
|
||||
findings.forEach((f, idx) => {
|
||||
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
|
||||
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
|
||||
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
|
||||
});
|
||||
summaryLines.push(``);
|
||||
|
||||
if (decision === "REJECT") {
|
||||
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
|
||||
} else if (decision === "REVIEW") {
|
||||
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
|
||||
} else if (decision === "PASS_WITH_NOTE") {
|
||||
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
|
||||
} else {
|
||||
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
|
||||
}
|
||||
|
||||
if (options.comment) {
|
||||
summaryLines.push(`[审批附加说明] ${options.comment}`);
|
||||
}
|
||||
|
||||
const decisionSummary = summaryLines.join("\n");
|
||||
|
||||
// 4. 更新数据库中的运行记录状态
|
||||
this.repo.updateApprovalRun(run.id, {
|
||||
decision,
|
||||
decisionSummary,
|
||||
failedRulesCount: failedFindings.length,
|
||||
});
|
||||
|
||||
let appliedAction = options.requestedAction;
|
||||
let actionResult: unknown = undefined;
|
||||
|
||||
// 5. 如果开启了 --apply,由网关在内部安全受控地调用下游接口。
|
||||
// 远端失败时把本地运行标记为 ERROR,避免数据库显示“已决策”但实际未执行。
|
||||
if (options.apply) {
|
||||
if (!appliedAction) {
|
||||
appliedAction = decision === "REJECT" ? "reject" : decision === "APPROVE" || decision === "PASS_WITH_NOTE" ? "approve" : "comment";
|
||||
}
|
||||
|
||||
try {
|
||||
if (appliedAction === "reject") {
|
||||
actionResult = await rejectBill(client, corpId, documentSn, {
|
||||
comment: decisionSummary,
|
||||
});
|
||||
} else if (appliedAction === "approve") {
|
||||
actionResult = await approveBill(client, corpId, documentSn, {
|
||||
comment: decisionSummary,
|
||||
});
|
||||
} else {
|
||||
actionResult = await commentBill(client, corpId, documentSn, {
|
||||
comment: decisionSummary,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.repo.updateApprovalRun(run.id, {
|
||||
decision: "ERROR",
|
||||
decisionSummary: `${decisionSummary}\n[下游执行失败] ${message}`,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const updatedRun = this.repo.getRunById(run.id)!;
|
||||
|
||||
return {
|
||||
run: updatedRun,
|
||||
decision,
|
||||
decisionSummary,
|
||||
hardFailedCount: hardFailed.length,
|
||||
elasticFailedCount: elasticFailed.length,
|
||||
suggestFailedCount: suggestFailed.length,
|
||||
specialFailedCount: specialFailed.length,
|
||||
appliedAction,
|
||||
actionResult,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
export type StrictnessTier = "硬性" | "弹性" | "建议" | "特殊";
|
||||
|
||||
export const VALID_STRICTNESS_TIERS: readonly StrictnessTier[] = [
|
||||
"硬性",
|
||||
"弹性",
|
||||
"建议",
|
||||
"特殊"
|
||||
] as const;
|
||||
|
||||
export function isValidStrictnessTier(value: string): value is StrictnessTier {
|
||||
return (VALID_STRICTNESS_TIERS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export interface RuleClause {
|
||||
/** 抽取的动作句式文本,如 "一定需要上传发票" */
|
||||
action: string;
|
||||
/** 严格程度级别 */
|
||||
strictness: StrictnessTier;
|
||||
/** 原始标记子串,如 "[一定需要上传发票]{硬性}" */
|
||||
raw: string;
|
||||
/** 在正文中的起始字符索引 */
|
||||
startIndex: number;
|
||||
/** 在正文中的结束字符索引 */
|
||||
endIndex: number;
|
||||
}
|
||||
|
||||
export interface ParsedRule {
|
||||
/** 原始正文 */
|
||||
rawBody: string;
|
||||
/** 解析出的所有判定要点 */
|
||||
clauses: RuleClause[];
|
||||
/** 剥离语法包裹后的纯文本,用于全文检索与语境理解 */
|
||||
cleanText: string;
|
||||
}
|
||||
|
||||
export interface ScopeSummary {
|
||||
/** 1-based 索引编号 (1, 2, 3...),供 AI 和 CLI 快捷定位 */
|
||||
index: number;
|
||||
/** 适用场景名称/索引全名 */
|
||||
scope: string;
|
||||
/** 该索引下包含的有效规则总数 */
|
||||
ruleCount: number;
|
||||
/** 归属该索引的所有规则编号数组 (如 [1, 2, 4]) */
|
||||
ruleCodes: number[];
|
||||
}
|
||||
|
||||
export interface ScopeDetail {
|
||||
index: number;
|
||||
scope: string;
|
||||
ruleCount: number;
|
||||
rules: Array<RuleRecord & { parsed: ParsedRule }>;
|
||||
}
|
||||
|
||||
export interface RuleRecord {
|
||||
id: string;
|
||||
code: number;
|
||||
scope: string;
|
||||
body: string;
|
||||
status: "active" | "draft" | "archived";
|
||||
version: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface PreferenceRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
isDefault: boolean;
|
||||
rulesReject: string;
|
||||
rulesReview: string;
|
||||
rulesPassNote: string;
|
||||
rulesApprove: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export type ApprovalDecision = "PENDING" | "APPROVE" | "REJECT" | "PASS_WITH_NOTE" | "REVIEW" | "ERROR";
|
||||
|
||||
export interface ApprovalRunRecord {
|
||||
id: string;
|
||||
flowId?: string | null;
|
||||
documentSn: string;
|
||||
corpId?: string | null;
|
||||
decision: ApprovalDecision;
|
||||
decisionSummary?: string | null;
|
||||
matchedRulesCount: number;
|
||||
failedRulesCount: number;
|
||||
documentSnapshot?: string | null;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export type FindingCheckStatus = "PENDING" | "PASS" | "FAIL" | "SKIP";
|
||||
|
||||
export interface ApprovalFindingRecord {
|
||||
id: string;
|
||||
runId: string;
|
||||
ruleId?: string | null;
|
||||
ruleCode?: number | null;
|
||||
clauseText: string;
|
||||
strictness: StrictnessTier;
|
||||
checkStatus: FindingCheckStatus;
|
||||
evidence?: string | null;
|
||||
reasoning?: string | null;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export class ApprovalRuleValidationError extends Error {
|
||||
public readonly code = "RULE_VALIDATION_ERROR";
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApprovalRuleValidationError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ApprovalGatewayBlockedError extends Error {
|
||||
public readonly code = "APPROVAL_GATEWAY_BLOCKED";
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApprovalGatewayBlockedError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface AiProLogRecord {
|
||||
id: string;
|
||||
action: string;
|
||||
documentSn?: string | null;
|
||||
operator?: string | null;
|
||||
args?: string | null;
|
||||
status: "SUCCESS" | "BLOCKED" | "ERROR";
|
||||
decision?: ApprovalDecision | null;
|
||||
summary?: string | null;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Bill 域说明
|
||||
|
||||
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。
|
||||
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票、关联引用、审批动作与数据实体元数据字典的检索、执行与格式化。
|
||||
|
||||
## 文件结构
|
||||
|
||||
```text
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
└── README.bill.md # 本说明文件
|
||||
@@ -22,3 +22,18 @@ src/domains/bill/
|
||||
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
|
||||
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
|
||||
- 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。
|
||||
4. **关联引用二级解析 (`getBillReferences`)**:
|
||||
- 通过审批详情、组织架构和费用类型目录批量解析提交人、归属人、费用承担部门与费用类型;
|
||||
- 保留原始 ID,并在 JSON 中提供 `name`、`code`、部门 `path` 与未解析 ID;目录在进程内按企业缓存 10 分钟。
|
||||
5. **单据关联链 (`getBillRelations`)**:
|
||||
- 从审批详情中的 `expenseLink`、`loan`、`requisition`、`contract` 等关系字段抽取前置单据树,保留原始对象供 JSON 下钻。
|
||||
6. **附件标准化 (`getBillAttachments`)**:
|
||||
- 递归识别表单中的 `attachments`、`fileId`、`fileName`、`key` 与原件 URL,统一输出附件清单并去重。
|
||||
7. **审批动作套件**:
|
||||
- `approveBill` 调用 `POST /api/flow/v2/backlogs/$<backlogId>`,使用 `freeflow.agree` 节点报文;
|
||||
- `rejectBill` 调用 `POST /api/flow/v2/backlogs/approveListWithNode`,使用 `freeflow.reject` 批量报文,评论会转为 `<p>...</p>`;
|
||||
- `transferBill` 与 `addNodeBill` 共用 backlog 动作接口,分别使用 `SHIFT_NODE`、`PRE_ADD_NODE`/`AFT_ADD_NODE`;
|
||||
- `commentBill` 调用 `POST /api/flow/v1/flows/comment/$<flowId>`,使用 `freeflow.comment`,保留参与人和私密评论参数;
|
||||
- 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。
|
||||
|
||||
CLI 入口为 `hose bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
@@ -1,4 +1,5 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
@@ -8,6 +9,305 @@ import {
|
||||
type EntityMeta,
|
||||
} from "./types.js";
|
||||
|
||||
function quoted(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function flowLookupSelect(): string {
|
||||
return "flowId(form(code,title),`...`),`...`";
|
||||
}
|
||||
|
||||
function flowDetailSelect(): string {
|
||||
return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function listActiveStaffCatalog(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/organization/staffs/actives", {
|
||||
searchParams: { start: "0", count: "2999", corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getDepartmentTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/organization/departments/tree/actives", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] } | unknown[];
|
||||
if (Array.isArray(json)) return json.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getFeeTypeTree(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const response = await client.get("api/v1/form/feeTypes/tree/active", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] } | unknown[];
|
||||
if (Array.isArray(json)) return json.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"));
|
||||
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
||||
}
|
||||
|
||||
export async function getRawBillFlow(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
let match: Record<string, unknown> | undefined;
|
||||
const filters = [
|
||||
`(id==${quoted(target)})||((flowId.id==${quoted(target)})||(flowId.form.code==${quoted(target)}))`,
|
||||
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`,
|
||||
];
|
||||
for (const filterBy of filters) {
|
||||
try {
|
||||
const lookup = await client.post("api/flow/v2/backlogs/search", {
|
||||
searchParams: { corpId },
|
||||
json: {
|
||||
filterBy,
|
||||
limit: { start: 0, count: 100 },
|
||||
select: flowLookupSelect(),
|
||||
},
|
||||
});
|
||||
const lookupJson = (await lookup.json()) as { items?: Record<string, unknown>[] };
|
||||
match = (lookupJson.items ?? []).find((item) => {
|
||||
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
return item.id === target || flow.id === target || form.code === target;
|
||||
});
|
||||
if (match) break;
|
||||
} catch {
|
||||
// Fall through to the broad status lookup or direct detail request.
|
||||
}
|
||||
}
|
||||
const backlogId = typeof match?.id === "string" ? match.id : target;
|
||||
|
||||
const detail = await client.post("api/flow/v2/backlogs/id", {
|
||||
searchParams: (() => {
|
||||
const params = new URLSearchParams({ corpId });
|
||||
for (const join of [
|
||||
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
|
||||
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
|
||||
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
|
||||
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code",
|
||||
]) params.append("join", join);
|
||||
return params;
|
||||
})(),
|
||||
json: {
|
||||
filterBy: `(id==${quoted(backlogId)})`,
|
||||
select: flowDetailSelect(),
|
||||
},
|
||||
});
|
||||
const json = (await detail.json()) as { value?: Record<string, unknown>; items?: Record<string, unknown>[] };
|
||||
return json.value ?? json.items?.[0];
|
||||
}
|
||||
|
||||
export interface BillActionTarget {
|
||||
backlogId: string;
|
||||
flowId: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
nodeId?: string;
|
||||
nodeName?: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillActionOptions {
|
||||
currentStaffId?: string;
|
||||
reminder?: boolean;
|
||||
keepItSecret?: boolean;
|
||||
comment?: string;
|
||||
participants?: string[];
|
||||
approverIds?: string[];
|
||||
rejectTo?: string | null;
|
||||
resubmitMethod?: string;
|
||||
addNodeType?: "PRE_ADD_NODE" | "AFT_ADD_NODE";
|
||||
}
|
||||
|
||||
async function readActionResponse(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return undefined;
|
||||
const text = await response.text();
|
||||
if (!text) return undefined;
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
function htmlComment(comment: string | undefined): string {
|
||||
const value = comment ?? "";
|
||||
return `<p>${value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'")}</p>`;
|
||||
}
|
||||
|
||||
function backlogSearchParams(corpId: string): Record<string, string> {
|
||||
return { messageCode: "debug", corpId };
|
||||
}
|
||||
|
||||
export async function approveBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
node: {
|
||||
flowId: target.flowId,
|
||||
id: target.nodeId,
|
||||
name: "freeflow.agree",
|
||||
},
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
comment: options.comment ?? "",
|
||||
participants: options.participants ?? [],
|
||||
isSingle: true,
|
||||
id: target.backlogId,
|
||||
name: "freeflow.agree",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function rejectBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post("api/flow/v2/backlogs/approveListWithNode", {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
data: [{
|
||||
id: target.backlogId,
|
||||
resubmitMethod: options.resubmitMethod ?? "TO_REJECTOR",
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
rejectTo: options.rejectTo ?? null,
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
name: "freeflow.reject",
|
||||
}],
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function transferBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
approverId: options.approverIds ?? [],
|
||||
type: "SHIFT_NODE",
|
||||
autographImageId: "",
|
||||
comment: options.comment ? htmlComment(options.comment) : "",
|
||||
participants: options.participants ?? [],
|
||||
id: target.backlogId,
|
||||
name: "freeflow.addnode",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function addNodeBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
||||
searchParams: backlogSearchParams(corpId),
|
||||
json: {
|
||||
reminder: options.reminder ?? false,
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
approverId: options.approverIds ?? [],
|
||||
type: options.addNodeType ?? "PRE_ADD_NODE",
|
||||
autographImageId: "",
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
id: target.backlogId,
|
||||
name: "freeflow.addnode",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function commentBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: BillActionTarget,
|
||||
options: BillActionOptions = {},
|
||||
): Promise<unknown> {
|
||||
const response = await client.post(`api/flow/v1/flows/comment/$${target.flowId}`, {
|
||||
searchParams: { messageCode: "debug", corpId },
|
||||
json: {
|
||||
id: target.flowId,
|
||||
params: {
|
||||
comment: htmlComment(options.comment),
|
||||
participants: options.participants ?? [],
|
||||
attachments: [],
|
||||
keepItSecret: options.keepItSecret ?? false,
|
||||
},
|
||||
name: "freeflow.comment",
|
||||
},
|
||||
});
|
||||
return readActionResponse(response);
|
||||
}
|
||||
|
||||
export async function getRawBillRisk(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string,
|
||||
submitterId?: string
|
||||
): Promise<Record<string, unknown>> {
|
||||
const searchParams = (extra: Record<string, string> = {}) => ({ corpId, ...extra });
|
||||
const requests: Array<Promise<unknown>> = [
|
||||
client.get("api/credit/v2/model", { searchParams: searchParams() }).then((response) => response.json()),
|
||||
client.get(`api/credit/v2/rules/byFlowId/withGroup/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/credit/v2/notes/byFlowId/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/flow/v2/riskwarning/coalition/info/$${flowId}`, { searchParams: searchParams({ flowId, privilegeId: "", newUI: "v2" }) }).then((response) => response.json()),
|
||||
client.get(`api/flow/v3/riskwarning/invoice/riskWarning/[${flowId}]`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()),
|
||||
client.get(`api/v1/budget/report/flow/$${flowId}/status`, { searchParams: searchParams({ id: flowId }) }).then((response) => response.json()),
|
||||
];
|
||||
if (submitterId) {
|
||||
requests.push(client.get(`api/credit/v2/stafflog/point/$${submitterId}`, { searchParams: searchParams({ submitterId }) }).then((response) => response.json()));
|
||||
}
|
||||
const results = await Promise.allSettled(requests);
|
||||
const values = results.map((result) => result.status === "fulfilled" ? result.value : {});
|
||||
return {
|
||||
creditModel: values[0] as Record<string, unknown>,
|
||||
rules: values[1] as Record<string, unknown>,
|
||||
notes: values[2] as Record<string, unknown>,
|
||||
coalition: values[3] as Record<string, unknown>,
|
||||
invoice: values[4] as Record<string, unknown>,
|
||||
budget: values[5] as Record<string, unknown>,
|
||||
staff: (submitterId ? values[6] : {}) as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function searchRawBills(
|
||||
@@ -48,6 +348,33 @@ export async function getRawBillsByIds(
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 附件文件元数据与签名下载地址 API ──────────────────────────────────────────
|
||||
|
||||
const AttachmentFileSchema = z.object({
|
||||
id: z.string(),
|
||||
key: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
thumbUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
export type AttachmentFile = z.infer<typeof AttachmentFileSchema>;
|
||||
|
||||
export async function resolveAttachmentFiles(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[],
|
||||
): Promise<AttachmentFile[]> {
|
||||
if (ids.length === 0) return [];
|
||||
|
||||
const response = await client.post("api/v1/attachment/attachments/ids", {
|
||||
searchParams: { corpId },
|
||||
json: { ids },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(AttachmentFileSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
|
||||
|
||||
export async function listEntitySchemas(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { formatSingleBill } from "./tools.js";
|
||||
import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds } from "./tools.js";
|
||||
import { RawBillItemSchema, EntitySchema } from "./types.js";
|
||||
|
||||
describe("Bill Domain", () => {
|
||||
@@ -66,4 +66,219 @@ describe("Bill Domain", () => {
|
||||
expect(formatted.amount).toBe("¥100.00 CNY");
|
||||
expect(formatted.details["客户等级"]).toBe("VIP客户");
|
||||
});
|
||||
|
||||
it("resolves approval references from staff, department and fee type catalogs", async () => {
|
||||
const responses = [
|
||||
{
|
||||
id: "backlog-1",
|
||||
state: "APPROVING",
|
||||
flowId: {
|
||||
id: "flow-1",
|
||||
form: {
|
||||
code: "S26000001",
|
||||
title: "团建申请",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDepartment: "corp:dept-2",
|
||||
details: { feeTypeId: "fee-1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ items: responses })),
|
||||
get: async (path: string) => {
|
||||
if (path.includes("staffs/actives")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "corp:staff-1", userId: "staff-1", name: "张三", code: "1001" }] }));
|
||||
}
|
||||
if (path.includes("departments/tree")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "corp", name: "总公司", children: [{ id: "corp:dept-2", name: "研发部", children: [] }] }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ items: [{ id: "fee-1", name: "差旅费", code: "COST01", children: [] }] }));
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await getBillReferences(client, "corp", "S26000001");
|
||||
expect(result?.submitter?.name).toBe("张三");
|
||||
expect(result?.department?.path).toBe("总公司/研发部");
|
||||
expect(result?.feeTypes[0]?.name).toBe("差旅费");
|
||||
expect(result?.unresolved).toEqual([]);
|
||||
});
|
||||
|
||||
it("extracts linked loan and requisition nodes as a relation tree", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ value: {
|
||||
id: "backlog-2",
|
||||
flowId: {
|
||||
id: "flow-2",
|
||||
form: {
|
||||
code: "E26000001",
|
||||
title: "费用报销",
|
||||
expenseLink: { id: "loan-1", code: "J26000001", title: "员工借款", loanMoney: { standard: "500" } },
|
||||
linkRequisitionInfo: { id: "req-1", code: "Q26000001", title: "出差申请" },
|
||||
},
|
||||
},
|
||||
} })),
|
||||
} as any;
|
||||
const result = await getBillRelations(client, "corp-relations", "E26000001");
|
||||
expect(result?.relations.map((item) => item.id)).toEqual(["loan-1", "req-1"]);
|
||||
expect(result?.relations[0]?.amount).toContain("500");
|
||||
});
|
||||
|
||||
it("normalizes nested bill attachments and removes duplicates", async () => {
|
||||
const client = {
|
||||
post: async () => new Response(JSON.stringify({ value: {
|
||||
id: "backlog-3",
|
||||
flowId: {
|
||||
form: {
|
||||
code: "E26000002",
|
||||
title: "带附件报销",
|
||||
attachments: [
|
||||
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
|
||||
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
|
||||
],
|
||||
},
|
||||
},
|
||||
} })),
|
||||
} as any;
|
||||
const result = await getBillAttachments(client, "corp-files", "E26000002");
|
||||
expect(result?.attachments).toHaveLength(1);
|
||||
expect(result?.attachments[0]?.fileId).toBe("file-1");
|
||||
expect(result?.attachments[0]?.fileName).toBe("receipt.pdf");
|
||||
});
|
||||
|
||||
it("enriches attachment metadata with file-service download URLs", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("attachment/attachments/ids")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [{ id: "file-2", key: "receipt-key", name: "receipt.pdf", url: "https://files.example/receipt.pdf", thumbUrl: "https://files.example/thumb" }],
|
||||
}));
|
||||
}
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillAttachments(client, "corp-files", "E26000003");
|
||||
expect(result?.attachments[0]).toMatchObject({
|
||||
fileId: "file-2",
|
||||
fileName: "receipt.pdf",
|
||||
key: "receipt-key",
|
||||
url: "https://files.example/receipt.pdf",
|
||||
thumbUrl: "https://files.example/thumb",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes risk warnings, budget state and invoice warnings", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } } }));
|
||||
},
|
||||
get: async (path: string) => {
|
||||
if (path.includes("coalition")) return new Response(JSON.stringify({ riskWarning: [{ riskLevel: "WARNING", controlName: "重复报销", messages: ["命中测试规则"] }] }));
|
||||
if (path.includes("budget/report")) return new Response(JSON.stringify({ value: true, status: "OVER" }));
|
||||
if (path.includes("invoice/riskWarning")) return new Response(JSON.stringify({ items: [{ type: "invoice", message: "发票抬头不一致" }] }));
|
||||
return new Response(JSON.stringify({}));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillRisk(client, "corp-risk", "S26000004");
|
||||
expect(result?.flowId).toBe("flow-risk");
|
||||
expect(result?.budgetExceeded).toBe(true);
|
||||
expect(result?.warnings[0]?.controlName).toBe("重复报销");
|
||||
expect(result?.invoiceWarnings).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("calculates approval-node dwell time and automatic skip markers", async () => {
|
||||
const client = {
|
||||
post: async (path: string) => {
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-flow", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" } } }] }));
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { id: "backlog-flow", state: "APPROVING", nodeName: "财务审批", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" }, logs: [
|
||||
{ id: "log-1", time: 1000, operatorId: "staff-1", attributes: { nodeName: "提交" } },
|
||||
{ id: "log-2", time: 2500, operatorId: null, state: "SKIPPED", attributes: { nodeName: "自动校验", isAuto: true, isSkip: true } },
|
||||
], plan: { nodes: [] } } } }));
|
||||
},
|
||||
} as any;
|
||||
const result = await getBillFlow(client, "corp-flow", "S26000005");
|
||||
expect(result?.history[0]?.durationMs).toBe(1500);
|
||||
expect(result?.history[1]?.automatic).toBe(true);
|
||||
expect(result?.history[1]?.skipped).toBe(true);
|
||||
});
|
||||
|
||||
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
|
||||
const calls: Array<{ path: string; options: any }> = [];
|
||||
const client = {
|
||||
post: async (path: string, options: any) => {
|
||||
calls.push({ path, options });
|
||||
if (path.includes("backlogs/search")) {
|
||||
return new Response(JSON.stringify({ items: [{ id: "backlog-action", flowId: { id: "flow-action", form: { code: "E26000007" } } }] }));
|
||||
}
|
||||
if (path.includes("backlogs/id")) {
|
||||
return new Response(JSON.stringify({ value: {
|
||||
id: "backlog-action",
|
||||
nodeId: "FLOW:node-action",
|
||||
nodeName: "直接领导审批",
|
||||
state: "APPROVING",
|
||||
flowId: { id: "flow-action", form: { code: "E26000007" }, plan: { nodes: [] } },
|
||||
} }));
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
} as any;
|
||||
|
||||
await approveBill(client, "corp-action", "E26000007", { comment: "同意" });
|
||||
const approveCall = calls.at(-1);
|
||||
expect(approveCall?.path).toBe("api/flow/v2/backlogs/$backlog-action");
|
||||
expect(approveCall?.options.json).toMatchObject({
|
||||
node: { flowId: "flow-action", id: "FLOW:node-action", name: "freeflow.agree" },
|
||||
comment: "同意",
|
||||
name: "freeflow.agree",
|
||||
});
|
||||
|
||||
await rejectBill(client, "corp-action", "E26000007", { comment: "金额 < 不符" });
|
||||
expect(calls.at(-1)?.path).toBe("api/flow/v2/backlogs/approveListWithNode");
|
||||
expect(calls.at(-1)?.options.json.data[0]).toMatchObject({
|
||||
id: "backlog-action",
|
||||
comment: "<p>金额 < 不符</p>",
|
||||
name: "freeflow.reject",
|
||||
});
|
||||
|
||||
await transferBill(client, "corp-action", "E26000007", { approverIds: ["staff-2"] });
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
approverId: ["staff-2"],
|
||||
type: "SHIFT_NODE",
|
||||
name: "freeflow.addnode",
|
||||
});
|
||||
|
||||
await addNodeBill(client, "corp-action", "E26000007", { approverIds: ["staff-3"], comment: "请协助", addNodeType: "AFT_ADD_NODE" });
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
approverId: ["staff-3"],
|
||||
type: "AFT_ADD_NODE",
|
||||
comment: "<p>请协助</p>",
|
||||
name: "freeflow.addnode",
|
||||
});
|
||||
|
||||
await commentBill(client, "corp-action", "E26000007", { comment: "补充说明" });
|
||||
expect(calls.at(-1)?.path).toBe("api/flow/v1/flows/comment/$flow-action");
|
||||
expect(calls.at(-1)?.options.json).toMatchObject({
|
||||
id: "flow-action",
|
||||
params: { comment: "<p>补充说明</p>", participants: [], attachments: [], keepItSecret: false },
|
||||
name: "freeflow.comment",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves transfer and add-node people by full ID, employee code or unique name", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [
|
||||
{ id: "corp:staff-1", userId: "user-1", code: "101", name: "谢子豪" },
|
||||
{ id: "corp:staff-2", userId: "user-2", code: "111", name: "沈玥妍" },
|
||||
] })),
|
||||
} as any;
|
||||
await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]);
|
||||
});
|
||||
});
|
||||
+892
-2
@@ -1,15 +1,47 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { searchRawBills, getRawBillsByIds, listEntitySchemas } from "./api.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { basename, extname, join, resolve } from "node:path";
|
||||
import {
|
||||
searchRawBills,
|
||||
getRawBillsByIds,
|
||||
listEntitySchemas,
|
||||
getRawBillFlow,
|
||||
getRawBillRisk,
|
||||
listActiveStaffCatalog,
|
||||
getDepartmentTree,
|
||||
getFeeTypeTree,
|
||||
resolveAttachmentFiles,
|
||||
approveBillAction,
|
||||
rejectBillAction,
|
||||
transferBillAction,
|
||||
addNodeBillAction,
|
||||
commentBillAction,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type FormattedBill,
|
||||
type BillPageResult,
|
||||
type EntityMeta,
|
||||
type BillQueryParams,
|
||||
type BillFlowEntry,
|
||||
type BillFlowNode,
|
||||
type BillFlowTimeline,
|
||||
type BillRiskReport,
|
||||
type BillRiskWarning,
|
||||
type BillReference,
|
||||
type BillReferenceReport,
|
||||
type BillRelationNode,
|
||||
type BillRelationsReport,
|
||||
type BillAttachment,
|
||||
type BillAttachmentReport,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { resolveDimension } from "../dimension/tools.js";
|
||||
|
||||
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
|
||||
|
||||
@@ -63,6 +95,15 @@ const COMMON_FIELD_LABELS: Record<string, string> = {
|
||||
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
|
||||
|
||||
type ReferenceCatalog = {
|
||||
timestamp: number;
|
||||
staff: Map<string, Record<string, unknown>>;
|
||||
departments: Map<string, { item: Record<string, unknown>; path: string }>;
|
||||
feeTypes: Map<string, Record<string, unknown>>;
|
||||
};
|
||||
|
||||
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
|
||||
|
||||
export async function getFieldDictionary(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
@@ -89,6 +130,436 @@ export async function getFieldDictionary(
|
||||
return result;
|
||||
}
|
||||
|
||||
function referenceId(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const id = (value as Record<string, unknown>).id;
|
||||
return typeof id === "string" && id.trim() ? id.trim() : undefined;
|
||||
}
|
||||
|
||||
function referenceObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
|
||||
}
|
||||
|
||||
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; path: string }> {
|
||||
for (const item of items) {
|
||||
const name = typeof item.name === "string" ? item.name : "";
|
||||
const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath;
|
||||
const id = typeof item.id === "string" ? item.id : undefined;
|
||||
if (id) output.set(id, { item, path });
|
||||
const children = Array.isArray(item.children)
|
||||
? item.children.filter((child): child is Record<string, unknown> => Boolean(child && typeof child === "object"))
|
||||
: [];
|
||||
flattenDepartments(children, path, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
|
||||
for (const item of items) {
|
||||
const feeType = referenceObject(item.feeType) ?? item;
|
||||
const id = typeof feeType.id === "string" ? feeType.id : undefined;
|
||||
if (id) output.set(id, feeType);
|
||||
const children = Array.isArray(item.children)
|
||||
? item.children.filter((child): child is Record<string, unknown> => Boolean(child && typeof child === "object"))
|
||||
: [];
|
||||
flattenFeeTypes(children, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
|
||||
const cached = referenceCatalogCache.get(corpId);
|
||||
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached;
|
||||
const [staffs, departments, feeTypes] = await Promise.all([
|
||||
listActiveStaffCatalog(client, corpId),
|
||||
getDepartmentTree(client, corpId),
|
||||
getFeeTypeTree(client, corpId),
|
||||
]);
|
||||
const staff = new Map<string, Record<string, unknown>>();
|
||||
for (const item of staffs) {
|
||||
if (typeof item.id === "string") {
|
||||
staff.set(item.id, item);
|
||||
const userId = typeof item.userId === "string" ? item.userId : undefined;
|
||||
if (userId) staff.set(userId, item);
|
||||
}
|
||||
}
|
||||
const result = {
|
||||
timestamp: Date.now(),
|
||||
staff,
|
||||
departments: flattenDepartments(departments),
|
||||
feeTypes: flattenFeeTypes(feeTypes),
|
||||
};
|
||||
referenceCatalogCache.set(corpId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function toReference(
|
||||
value: unknown,
|
||||
kind: BillReference["kind"],
|
||||
source: BillReference["source"],
|
||||
catalog?: Record<string, unknown>,
|
||||
path?: string,
|
||||
): BillReference | undefined {
|
||||
const id = referenceId(value);
|
||||
if (!id) return undefined;
|
||||
const object = referenceObject(value);
|
||||
const sourceObject = object ?? catalog;
|
||||
return {
|
||||
id,
|
||||
name: typeof sourceObject?.name === "string" ? sourceObject.name : undefined,
|
||||
code: typeof sourceObject?.code === "string" ? sourceObject.code : undefined,
|
||||
path,
|
||||
kind,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
function collectFeeTypeIds(value: unknown, output = new Set<string>()): Set<string> {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectFeeTypeIds(item, output);
|
||||
return output;
|
||||
}
|
||||
if (!value || typeof value !== "object") return output;
|
||||
for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (key === "feeTypeId" || key.endsWith("_feeTypeId")) {
|
||||
const id = referenceId(nested);
|
||||
if (id) output.add(id);
|
||||
}
|
||||
collectFeeTypeIds(nested, output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function getBillReferences(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillReferenceReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const catalog = await getReferenceCatalog(client, corpId);
|
||||
const unresolved: string[] = [];
|
||||
const resolveStaff = (value: unknown, fallbackKind: BillReference["kind"]): BillReference | undefined => {
|
||||
const id = referenceId(value);
|
||||
if (!id) return undefined;
|
||||
const found = catalog.staff.get(id) ?? catalog.staff.get(id.split(":").at(-1) ?? id);
|
||||
const reference = toReference(value, fallbackKind, found ? "catalog" : "raw", found);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
return reference;
|
||||
};
|
||||
const departmentValue = form.expenseDepartment;
|
||||
const departmentId = referenceId(departmentValue);
|
||||
const departmentFound = departmentId ? catalog.departments.get(departmentId) ?? catalog.departments.get(departmentId.split(":").at(-1) ?? departmentId) : undefined;
|
||||
const department = toReference(departmentValue, "department", departmentFound ? "catalog" : "raw", departmentFound?.item, departmentFound?.path);
|
||||
if (departmentId && !department?.name) unresolved.push(departmentId);
|
||||
|
||||
const legalEntityValue = form.legalEntity;
|
||||
const submitterObject = referenceObject(form.submitterId);
|
||||
const submitterLegalEntity = submitterObject?.defaultDepartment && typeof submitterObject.defaultDepartment === "object"
|
||||
? referenceObject(submitterObject.defaultDepartment)?.form && typeof referenceObject(submitterObject.defaultDepartment)?.form === "object"
|
||||
? (referenceObject(submitterObject.defaultDepartment)?.form as Record<string, unknown>).legalEntity
|
||||
: undefined
|
||||
: undefined;
|
||||
const legalEntityId = referenceId(legalEntityValue) || referenceId(submitterLegalEntity);
|
||||
const legalEntityCatalog = legalEntityId ? await resolveDimension(client, corpId, "FRST") : undefined;
|
||||
const legalEntityItem = legalEntityCatalog?.items.find((item) => item.id === legalEntityId || item.id.endsWith(`:${legalEntityId}`));
|
||||
const legalEntity = toReference(legalEntityValue || submitterLegalEntity || legalEntityId, "legalEntity", legalEntityItem ? "catalog" : "joined", legalEntityItem as unknown as Record<string, unknown> | undefined);
|
||||
if (referenceId(legalEntityValue) && !legalEntity?.name) unresolved.push(referenceId(legalEntityValue)!);
|
||||
|
||||
const feeTypes = [...collectFeeTypeIds(form)].map((id) => {
|
||||
const found = catalog.feeTypes.get(id) ?? catalog.feeTypes.get(id.split(":").at(-1) ?? id);
|
||||
const reference = toReference(id, "feeType", found ? "catalog" : "raw", found);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
return reference;
|
||||
}).filter((item): item is BillReference => Boolean(item));
|
||||
|
||||
const dimensions: BillReference[] = [];
|
||||
const dimensionTargets: Array<[RegExp, string]> = [[/project|项目/i, "DA001"], [/cost.?center|成本中心/i, "costCenter"]];
|
||||
for (const [keyPattern, dimensionCode] of dimensionTargets) {
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (!keyPattern.test(key)) continue;
|
||||
const id = referenceId(value);
|
||||
if (!id) continue;
|
||||
const resolved = await resolveDimension(client, corpId, dimensionCode);
|
||||
const item = resolved?.items.find((entry) => entry.id === id || entry.id.endsWith(`:${id}`));
|
||||
const reference = toReference(value, "dimension", item ? "catalog" : "raw", item as unknown as Record<string, unknown> | undefined);
|
||||
if (reference) dimensions.push(reference);
|
||||
if (!reference?.name) unresolved.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
billId: typeof raw.id === "string" ? raw.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
submitter: resolveStaff(form.submitterId, "staff"),
|
||||
owner: resolveStaff(form.ownerId, "staff"),
|
||||
department,
|
||||
legalEntity,
|
||||
feeTypes,
|
||||
dimensions,
|
||||
unresolved: [...new Set(unresolved)],
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
function relationAmount(value: Record<string, unknown>): string | undefined {
|
||||
for (const key of ["amount", "money", "expenseMoney", "loanMoney", "requisitionMoney", "payMoney", "writtenOffAmount"]) {
|
||||
const candidate = value[key];
|
||||
if (typeof candidate === "number" || typeof candidate === "string") return String(candidate);
|
||||
if (candidate && typeof candidate === "object") {
|
||||
const money = candidate as Record<string, unknown>;
|
||||
if (money.standard !== undefined) return `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function relationNode(relation: string, value: unknown): BillRelationNode | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const object = value as Record<string, unknown>;
|
||||
const children: BillRelationNode[] = [];
|
||||
for (const [key, nested] of Object.entries(object)) {
|
||||
if (key === "id" || key === "code" || key === "title" || key === "name") continue;
|
||||
if (Array.isArray(nested)) {
|
||||
for (const item of nested) {
|
||||
const arrayChild = relationNode(key, item);
|
||||
if (arrayChild) children.push(arrayChild);
|
||||
}
|
||||
} else if (nested && typeof nested === "object") {
|
||||
const child = relationNode(key, nested);
|
||||
if (child) children.push(child);
|
||||
}
|
||||
}
|
||||
const id = typeof object.id === "string" ? object.id : undefined;
|
||||
const code = typeof object.code === "string" ? object.code : undefined;
|
||||
const title = typeof object.title === "string" ? object.title : typeof object.name === "string" ? object.name : undefined;
|
||||
if (!id && !code && !title && children.length === 0) return undefined;
|
||||
return { relation, id, code, title, amount: relationAmount(object), children, raw: object };
|
||||
}
|
||||
|
||||
export async function getBillRelations(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillRelationsReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const relations: BillRelationNode[] = [];
|
||||
const seen = new Set<string>();
|
||||
const relationPattern = /(link|loan|requisition|contract|pre.?apply|advance)/i;
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (!relationPattern.test(key)) continue;
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
for (const candidate of values) {
|
||||
const node = relationNode(key, candidate);
|
||||
if (!node) continue;
|
||||
const dedupeKey = `${node.relation}:${node.id || node.code || node.title || JSON.stringify(node.raw)}`;
|
||||
if (seen.has(dedupeKey)) continue;
|
||||
seen.add(dedupeKey);
|
||||
relations.push(node);
|
||||
}
|
||||
}
|
||||
return {
|
||||
target,
|
||||
billId: typeof raw.id === "string" ? raw.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
relations,
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
function attachmentFromValue(sourceField: string, value: unknown): BillAttachment | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const object = value as Record<string, unknown>;
|
||||
const nestedFile = object.fileId && typeof object.fileId === "object" ? object.fileId as Record<string, unknown> : undefined;
|
||||
const fileId = typeof object.fileId === "string" ? object.fileId : typeof nestedFile?.id === "string" ? nestedFile.id : undefined;
|
||||
const key = typeof object.key === "string" ? object.key : typeof nestedFile?.key === "string" ? nestedFile.key : undefined;
|
||||
const fileName = typeof object.fileName === "string" ? object.fileName : typeof object.name === "string" ? object.name : undefined;
|
||||
const url = typeof object.url === "string" ? object.url : typeof nestedFile?.url === "string" ? nestedFile.url : undefined;
|
||||
const thumbUrl = typeof object.thumbUrl === "string" ? object.thumbUrl : typeof nestedFile?.thumbUrl === "string" ? nestedFile.thumbUrl : undefined;
|
||||
if (!fileId && !key && !fileName && !url) return undefined;
|
||||
return { fileId, key, fileName, url, thumbUrl, sourceField, raw: object };
|
||||
}
|
||||
|
||||
function collectAttachments(sourceField: string, value: unknown, output: BillAttachment[]): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectAttachments(sourceField, item, output);
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== "object") return;
|
||||
const object = value as Record<string, unknown>;
|
||||
const looksLikeAttachment = sourceField.toLowerCase().includes("attachment") || "fileId" in object || "fileName" in object || "thumbUrl" in object;
|
||||
if (looksLikeAttachment) {
|
||||
const attachment = attachmentFromValue(sourceField, value);
|
||||
if (attachment) output.push(attachment);
|
||||
}
|
||||
for (const [key, nested] of Object.entries(object)) {
|
||||
if (key === "fileId" || key === "fileName" || key === "url" || key === "thumbUrl" || key === "key") continue;
|
||||
if (nested && typeof nested === "object") collectAttachments(sourceField === "form" ? key : `${sourceField}.${key}`, nested, output);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBillAttachments(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
): Promise<BillAttachmentReport | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
let billId: string | undefined;
|
||||
let billCode: string | undefined;
|
||||
let title: string | undefined;
|
||||
let form: Record<string, unknown> = {};
|
||||
if (raw?.flowId && typeof raw.flowId === "object") {
|
||||
billId = typeof raw.id === "string" ? raw.id : undefined;
|
||||
const flow = raw.flowId as Record<string, unknown>;
|
||||
form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
billCode = typeof form.code === "string" ? form.code : undefined;
|
||||
title = typeof form.title === "string" ? form.title : undefined;
|
||||
} else {
|
||||
const search = await searchRawBills(client, corpId, { count: 100 });
|
||||
const item = search.items.find((candidate) => candidate.id === target || candidate.code === target);
|
||||
if (!item) return undefined;
|
||||
billId = item.id;
|
||||
billCode = item.code;
|
||||
title = item.form?.title as string | undefined;
|
||||
form = item.form || {};
|
||||
}
|
||||
const attachments: BillAttachment[] = [];
|
||||
collectAttachments("form", form, attachments);
|
||||
const deduped = [...new Map(attachments.map((item) => [`${item.fileId || ""}|${item.key || ""}|${item.fileName || ""}`, item])).values()];
|
||||
const fileIds = deduped
|
||||
.map((item) => item.fileId)
|
||||
.filter((fileId): fileId is string => Boolean(fileId));
|
||||
let resolved: Awaited<ReturnType<typeof resolveAttachmentFiles>> = [];
|
||||
try {
|
||||
resolved = await resolveAttachmentFiles(client, corpId, fileIds);
|
||||
} catch {
|
||||
// 附件元数据接口不可用时,仍返回审批详情中已经拿到的原始字段。
|
||||
}
|
||||
const resolvedById = new Map(resolved.map((item) => [item.id, item]));
|
||||
const enriched = deduped.map((item) => {
|
||||
const metadata = item.fileId ? resolvedById.get(item.fileId) : undefined;
|
||||
if (!metadata) return item;
|
||||
return {
|
||||
...item,
|
||||
key: item.key ?? metadata.key,
|
||||
fileName: item.fileName ?? metadata.name,
|
||||
url: item.url ?? metadata.url,
|
||||
thumbUrl: item.thumbUrl ?? metadata.thumbUrl,
|
||||
raw: { ...item.raw, resolved: metadata },
|
||||
};
|
||||
});
|
||||
return {
|
||||
target,
|
||||
billId,
|
||||
billCode,
|
||||
title,
|
||||
attachments: enriched,
|
||||
raw: { form },
|
||||
};
|
||||
}
|
||||
|
||||
export interface DownloadedBillAttachment {
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
key?: string;
|
||||
path: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
function safeAttachmentName(value: string): string {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/?%*:|"<>]/g, "_")
|
||||
.replace(/^\.+/, "_")
|
||||
.trim();
|
||||
return cleaned || "attachment";
|
||||
}
|
||||
|
||||
function uniqueAttachmentPath(outputDir: string, fileName: string, fileId: string | undefined, used: Set<string>): string {
|
||||
const extension = extname(fileName);
|
||||
const stem = extension ? fileName.slice(0, -extension.length) : fileName;
|
||||
let index = 0;
|
||||
while (true) {
|
||||
const suffix = index === 0 ? "" : fileId ? `-${fileId}${index > 1 ? `-${index}` : ""}` : `-copy${index > 1 ? `-${index}` : ""}`;
|
||||
const candidate = join(outputDir, `${stem}${suffix}${extension}`);
|
||||
if (!used.has(candidate) && !existsSync(candidate)) {
|
||||
used.add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadBillAttachments(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
outputDir: string,
|
||||
fileId?: string,
|
||||
): Promise<{
|
||||
target: string;
|
||||
outputDir: string;
|
||||
requestedFileId?: string;
|
||||
downloaded: DownloadedBillAttachment[];
|
||||
skipped: number;
|
||||
report: BillAttachmentReport;
|
||||
}> {
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) throw new Error(`未找到单据附件: ${target}`);
|
||||
|
||||
const selected = fileId
|
||||
? report.attachments.filter((item) => item.fileId === fileId)
|
||||
: report.attachments;
|
||||
if (fileId && selected.length === 0) {
|
||||
throw new Error(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
|
||||
}
|
||||
|
||||
const destination = resolve(outputDir);
|
||||
await mkdir(destination, { recursive: true });
|
||||
const usedPaths = new Set<string>();
|
||||
const downloaded: DownloadedBillAttachment[] = [];
|
||||
let skipped = 0;
|
||||
|
||||
for (const attachment of selected) {
|
||||
if (!attachment.url) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
const sourceName = attachment.fileName || attachment.key || attachment.fileId || "attachment";
|
||||
const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths);
|
||||
const response = await fetch(attachment.url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`附件下载失败 (${response.status}): ${sourceName}`);
|
||||
}
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
await writeFile(path, content);
|
||||
downloaded.push({
|
||||
fileId: attachment.fileId,
|
||||
fileName: attachment.fileName,
|
||||
key: attachment.key,
|
||||
path,
|
||||
bytes: content.byteLength,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
target,
|
||||
outputDir: destination,
|
||||
requestedFileId: fileId,
|
||||
downloaded,
|
||||
skipped,
|
||||
report,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function formatSingleBill(
|
||||
@@ -175,6 +646,138 @@ export function formatSingleBill(
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFlowAsBill(
|
||||
raw: Record<string, unknown>,
|
||||
dictionary: Map<string, { label: string; type: string }>
|
||||
): FormattedBill {
|
||||
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
|
||||
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
|
||||
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
|
||||
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
|
||||
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
|
||||
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
|
||||
const state = raw.nodeName
|
||||
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
|
||||
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
|
||||
|
||||
let amountStr: string | undefined;
|
||||
for (const key of ["requisitionMoney", "amount", "expenseMoney", "payMoney"]) {
|
||||
const val = form[key];
|
||||
if (val && typeof val === "object" && (val as any).standard !== undefined) {
|
||||
const money = val as any;
|
||||
amountStr = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let submitterId: string | undefined;
|
||||
const submitter = form.submitterId as Record<string, unknown> | undefined;
|
||||
if (submitter && typeof submitter === "object") {
|
||||
const name = submitter.name || "";
|
||||
const code = submitter.code ? ` (${submitter.code})` : "";
|
||||
const dept = (submitter.defaultDepartment as Record<string, unknown>)?.name;
|
||||
submitterId = `${name}${code}${dept ? ` - ${dept}` : ""}`.trim();
|
||||
} else if (typeof form.submitterId === "string") {
|
||||
submitterId = form.submitterId;
|
||||
}
|
||||
|
||||
let submitDateStr: string | undefined;
|
||||
if (typeof form.submitDate === "number" && form.submitDate > 1000000000000) {
|
||||
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
|
||||
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
|
||||
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
|
||||
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
|
||||
|
||||
const readableDetails: Record<string, any> = {};
|
||||
if (raw.nodeName) readableDetails["当前节点"] = raw.nodeName;
|
||||
if (raw.id) readableDetails["任务 ID"] = raw.id;
|
||||
if (flow.id) readableDetails["流程 ID"] = flow.id;
|
||||
if (flow.formType) readableDetails["表单类型"] = flow.formType;
|
||||
|
||||
const detailsArray = Array.isArray(form.details) ? form.details : [];
|
||||
if (detailsArray.length > 0) {
|
||||
readableDetails["费用明细条数"] = `${detailsArray.length} 笔`;
|
||||
detailsArray.forEach((item, idx) => {
|
||||
const feeForm = (item.feeTypeForm && typeof item.feeTypeForm === "object" ? item.feeTypeForm : {}) as Record<string, unknown>;
|
||||
const feeTypeId = typeof item.feeTypeId === "string" ? item.feeTypeId.split(":").at(-1) || item.feeTypeId : "费用";
|
||||
|
||||
let rowMoney = "";
|
||||
if (feeForm.amount && typeof feeForm.amount === "object") {
|
||||
const m = feeForm.amount as any;
|
||||
rowMoney = `${m.standardSymbol || "¥"}${m.standard} ${m.standardStrCode || "CNY"}`.trim();
|
||||
}
|
||||
|
||||
let cityStr = "";
|
||||
if (typeof feeForm.city === "string") {
|
||||
try {
|
||||
const parsedCity = JSON.parse(feeForm.city);
|
||||
if (Array.isArray(parsedCity) && parsedCity[0]?.label) {
|
||||
cityStr = parsedCity[0].label;
|
||||
} else {
|
||||
cityStr = feeForm.city;
|
||||
}
|
||||
} catch {
|
||||
cityStr = feeForm.city;
|
||||
}
|
||||
}
|
||||
|
||||
let dateStr = "";
|
||||
if (typeof feeForm.feeDate === "number" && feeForm.feeDate > 1000000000000) {
|
||||
dateStr = new Date(feeForm.feeDate).toLocaleDateString("zh-CN");
|
||||
}
|
||||
|
||||
const reason = feeForm.consumptionReasons || feeForm.reason || "";
|
||||
const attachments = Array.isArray(feeForm.attachments) ? feeForm.attachments.length : 0;
|
||||
|
||||
const summaryParts = [
|
||||
`[${feeTypeId}]`,
|
||||
cityStr,
|
||||
rowMoney,
|
||||
dateStr,
|
||||
reason ? `事由: ${reason}` : "",
|
||||
`附件: ${attachments} 个`,
|
||||
].filter(Boolean);
|
||||
|
||||
readableDetails[`明细 #${idx + 1}`] = summaryParts.join(" | ");
|
||||
if (reason) readableDetails[`明细 #${idx + 1} 事由`] = reason;
|
||||
if (cityStr) readableDetails[`明细 #${idx + 1} 城市`] = cityStr;
|
||||
});
|
||||
}
|
||||
|
||||
for (const [k, v] of Object.entries(form)) {
|
||||
if (["code", "title", "details", "submitterId", "submitDate", "requisitionMoney", "amount", "expenseMoney", "logs", "flowPlanId"].includes(k)) continue;
|
||||
if (v === null || v === undefined || v === "") continue;
|
||||
const meta = dictionary.get(k);
|
||||
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
|
||||
const label = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || k);
|
||||
if (typeof v === "object") {
|
||||
readableDetails[label] = JSON.stringify(v);
|
||||
} else {
|
||||
readableDetails[label] = v;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
billId: String(flow.id || raw.id || ""),
|
||||
billCode,
|
||||
billName,
|
||||
title,
|
||||
stage,
|
||||
state,
|
||||
amount: amountStr,
|
||||
submitterId,
|
||||
submitDate: submitDateStr,
|
||||
corporationId: String(flow.corporationId || raw.corporationId || ""),
|
||||
ownerId: typeof flow.ownerId === "object" ? (flow.ownerId as any)?.name : typeof flow.ownerId === "string" ? flow.ownerId : undefined,
|
||||
createTime: createTimeStr,
|
||||
updateTime: updateTimeStr,
|
||||
details: readableDetails,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
|
||||
|
||||
export async function getBillByCodeOrId(
|
||||
@@ -214,7 +817,294 @@ export async function getBillByCodeOrId(
|
||||
return false;
|
||||
});
|
||||
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
if (matched.length > 0) {
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
}
|
||||
|
||||
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
|
||||
try {
|
||||
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
|
||||
if (rawFlow) {
|
||||
return [formatFlowAsBill(rawFlow, dictionary)];
|
||||
}
|
||||
} catch {
|
||||
// 忽略流程回退错误
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function flowPerson(value: unknown): { id?: string; name?: string; code?: string } | undefined {
|
||||
if (typeof value === "string") return { id: value };
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const person = value as Record<string, unknown>;
|
||||
return {
|
||||
id: typeof person.id === "string" ? person.id : undefined,
|
||||
name: typeof person.name === "string" ? person.name : undefined,
|
||||
code: typeof person.code === "string" ? person.code : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function unwrapValue(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object") return {};
|
||||
const object = value as Record<string, unknown>;
|
||||
return object.value && typeof object.value === "object" ? object.value as Record<string, unknown> : object;
|
||||
}
|
||||
|
||||
export async function getBillFlow(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<BillFlowTimeline | undefined> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw) return undefined;
|
||||
const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const nodeState = raw.nodeState && typeof raw.nodeState === "object" ? raw.nodeState as Record<string, unknown> : {};
|
||||
const logs = Array.isArray(flow.logs) ? flow.logs : [];
|
||||
const history: BillFlowEntry[] = logs.map((value, index) => {
|
||||
const log = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
const attributes = log.attributes && typeof log.attributes === "object" ? log.attributes as Record<string, unknown> : {};
|
||||
const currentTime = typeof log.time === "number" ? log.time : undefined;
|
||||
const nextLog = logs[index + 1] && typeof logs[index + 1] === "object" ? logs[index + 1] as Record<string, unknown> : undefined;
|
||||
const nextTime = typeof nextLog?.time === "number" ? nextLog.time : undefined;
|
||||
const durationMs = currentTime !== undefined && nextTime !== undefined && nextTime >= currentTime ? nextTime - currentTime : undefined;
|
||||
const nextOperators = Array.isArray(log.nextOperatorIds)
|
||||
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||
: [];
|
||||
return {
|
||||
id: typeof log.id === "string" ? log.id : undefined,
|
||||
time: currentTime,
|
||||
durationMs,
|
||||
state: typeof log.state === "string" ? log.state : undefined,
|
||||
action: typeof log.action === "string" ? log.action : undefined,
|
||||
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
|
||||
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
|
||||
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
|
||||
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
|
||||
operator: flowPerson(log.operatorId),
|
||||
nextOperators,
|
||||
};
|
||||
});
|
||||
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
|
||||
const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined;
|
||||
const currentNode = typeof raw.nodeName === "string" ? raw.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined;
|
||||
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
|
||||
const pending: BillFlowNode[] = nodes.map((value) => {
|
||||
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
const approvers = Array.isArray(node.counterSigners)
|
||||
? node.counterSigners.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
|
||||
: [];
|
||||
const approver = flowPerson(node.approverId);
|
||||
return {
|
||||
id: typeof node.id === "string" ? node.id : undefined,
|
||||
name: typeof node.name === "string" ? node.name : undefined,
|
||||
type: typeof node.type === "string" ? node.type : undefined,
|
||||
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
|
||||
approver,
|
||||
approvers,
|
||||
};
|
||||
});
|
||||
const lastAttributes = logs.at(-1) && typeof logs.at(-1) === "object" && (logs.at(-1) as Record<string, unknown>).attributes && typeof (logs.at(-1) as Record<string, unknown>).attributes === "object"
|
||||
? (logs.at(-1) as Record<string, unknown>).attributes as Record<string, unknown>
|
||||
: {};
|
||||
return {
|
||||
backlogId: typeof raw.id === "string" ? raw.id : target,
|
||||
flowId: typeof flow.id === "string" ? flow.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
|
||||
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
|
||||
history,
|
||||
pending,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
function actionTarget(raw: Record<string, unknown>, fallback: string): BillActionTarget {
|
||||
const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record<string, unknown> : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const backlogId = typeof raw.id === "string" ? raw.id : fallback;
|
||||
const flowId = typeof flow.id === "string" ? flow.id : undefined;
|
||||
if (!flowId) throw new Error(`未找到单据流程 ID: ${fallback}`);
|
||||
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
|
||||
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
|
||||
const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined;
|
||||
const currentNode = nodes.find((value) => {
|
||||
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
return typeof raw.nodeId === "string" && node.id === raw.nodeId || nodeName && node.name === nodeName;
|
||||
});
|
||||
return {
|
||||
backlogId,
|
||||
flowId,
|
||||
billId: flowId,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
nodeId: typeof raw.nodeId === "string" ? raw.nodeId : currentNode && typeof currentNode === "object" && typeof (currentNode as Record<string, unknown>).id === "string" ? (currentNode as Record<string, unknown>).id as string : undefined,
|
||||
nodeName,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise<BillActionTarget> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw) throw new Error(`未找到单据或审批任务: ${target}`);
|
||||
return actionTarget(raw, target);
|
||||
}
|
||||
|
||||
export interface BillActionResult {
|
||||
action: "approve" | "reject" | "transfer" | "add-node" | "comment";
|
||||
corpId: string;
|
||||
target: string;
|
||||
backlogId: string;
|
||||
flowId: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
nodeId?: string;
|
||||
response?: unknown;
|
||||
}
|
||||
|
||||
export async function resolveBillStaffIds(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
values: string[],
|
||||
): Promise<string[]> {
|
||||
const catalog = await listActiveStaffCatalog(client, corpId);
|
||||
const normalized = (value: string) => value.trim().toLowerCase();
|
||||
const matchesFor = (value: string) => {
|
||||
const target = normalized(value);
|
||||
return catalog.filter((staff) => {
|
||||
const id = typeof staff.id === "string" ? staff.id : "";
|
||||
const userId = typeof staff.userId === "string" ? staff.userId : "";
|
||||
const name = typeof staff.name === "string" ? staff.name : "";
|
||||
const code = typeof staff.code === "string" ? staff.code : "";
|
||||
return [id, userId, name, code].some((candidate) => {
|
||||
const lowered = normalized(candidate);
|
||||
return lowered === target || lowered.endsWith(`:${target}`);
|
||||
});
|
||||
});
|
||||
};
|
||||
const result: string[] = [];
|
||||
for (const value of values) {
|
||||
const matches = matchesFor(value);
|
||||
if (matches.length !== 1) {
|
||||
if (matches.length > 1) throw new Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
|
||||
throw new Error(`未找到员工 [${value}]`);
|
||||
}
|
||||
const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined;
|
||||
if (!id) throw new Error(`员工 [${value}] 缺少可用 ID`);
|
||||
result.push(id);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function runBillAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
action: BillActionResult["action"],
|
||||
options: BillActionOptions = {},
|
||||
): Promise<BillActionResult> {
|
||||
const resolved = await resolveActionTarget(client, corpId, target);
|
||||
if (options.currentStaffId && action !== "comment") {
|
||||
const flow = resolved.raw.flowId && typeof resolved.raw.flowId === "object" ? resolved.raw.flowId as Record<string, unknown> : {};
|
||||
const actions = flow.actions && typeof flow.actions === "object" ? flow.actions as Record<string, unknown> : undefined;
|
||||
if (actions && Object.keys(actions).length > 0) {
|
||||
const current = options.currentStaffId;
|
||||
const currentTail = current.split(":").at(-1) || current;
|
||||
const entry = Object.entries(actions).find(([staffId]) => {
|
||||
const staffTail = staffId.split(":").at(-1) || staffId;
|
||||
return staffId === current || staffId.endsWith(`:${current}`) || current.endsWith(`:${staffId}`) || staffTail === currentTail;
|
||||
});
|
||||
const allowed = entry?.[1];
|
||||
const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode";
|
||||
if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) {
|
||||
throw new Error(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`);
|
||||
}
|
||||
}
|
||||
}
|
||||
let response: unknown;
|
||||
if (action === "approve") response = await approveBillAction(client, corpId, resolved, options);
|
||||
else if (action === "reject") response = await rejectBillAction(client, corpId, resolved, options);
|
||||
else if (action === "transfer") response = await transferBillAction(client, corpId, resolved, options);
|
||||
else if (action === "add-node") response = await addNodeBillAction(client, corpId, resolved, options);
|
||||
else response = await commentBillAction(client, corpId, resolved, options);
|
||||
return {
|
||||
action,
|
||||
corpId,
|
||||
target,
|
||||
backlogId: resolved.backlogId,
|
||||
flowId: resolved.flowId,
|
||||
billId: resolved.billId,
|
||||
billCode: resolved.billCode,
|
||||
nodeId: resolved.nodeId,
|
||||
response,
|
||||
};
|
||||
}
|
||||
|
||||
export function approveBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
return runBillAction(client, corpId, target, "approve", options);
|
||||
}
|
||||
|
||||
export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空");
|
||||
return runBillAction(client, corpId, target, "reject", options);
|
||||
}
|
||||
|
||||
export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "transfer", options);
|
||||
}
|
||||
|
||||
export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("加签审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "add-node", options);
|
||||
}
|
||||
|
||||
export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("评论内容不能为空");
|
||||
return runBillAction(client, corpId, target, "comment", options);
|
||||
}
|
||||
|
||||
export async function getBillRisk(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<BillRiskReport | undefined> {
|
||||
const rawFlow = await getRawBillFlow(client, corpId, target);
|
||||
if (!rawFlow || !rawFlow.flowId || typeof rawFlow.flowId !== "object") return undefined;
|
||||
const flow = rawFlow.flowId as Record<string, unknown>;
|
||||
const flowId = typeof flow.id === "string" ? flow.id : undefined;
|
||||
if (!flowId) return undefined;
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const submitter = form.submitterId && typeof form.submitterId === "object" ? form.submitterId as Record<string, unknown> : {};
|
||||
const submitterId = typeof submitter.id === "string" ? submitter.id : undefined;
|
||||
const rawRisk = await getRawBillRisk(client, corpId, flowId, submitterId);
|
||||
const coalition = unwrapValue(rawRisk.coalition);
|
||||
const rawWarnings = Array.isArray(coalition.riskWarning) ? coalition.riskWarning : [];
|
||||
const warnings: BillRiskWarning[] = rawWarnings.map((value) => {
|
||||
const item = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
return {
|
||||
riskLevel: typeof item.riskLevel === "string" ? item.riskLevel : undefined,
|
||||
type: typeof item.type === "string" ? item.type : undefined,
|
||||
title: typeof item.title === "string" ? item.title : undefined,
|
||||
controlName: typeof item.controlName === "string" ? item.controlName : undefined,
|
||||
messages: Array.isArray(item.messages) ? item.messages.filter((message): message is string => typeof message === "string") : [],
|
||||
raw: item,
|
||||
};
|
||||
});
|
||||
const invoice = unwrapValue(rawRisk.invoice);
|
||||
const budget = unwrapValue(rawRisk.budget);
|
||||
return {
|
||||
flowId,
|
||||
budgetExceeded: budget.value === true,
|
||||
budget,
|
||||
credit: unwrapValue(rawRisk.staff),
|
||||
rules: unwrapValue(rawRisk.rules),
|
||||
notes: unwrapValue(rawRisk.notes),
|
||||
warnings,
|
||||
invoiceWarnings: Array.isArray(invoice.items) ? invoice.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [],
|
||||
raw: rawRisk,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
|
||||
|
||||
@@ -103,3 +103,121 @@ export interface BillQueryParams {
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface BillFlowEntry {
|
||||
id?: string;
|
||||
time?: number;
|
||||
durationMs?: number;
|
||||
state?: string;
|
||||
action?: string;
|
||||
nodeName?: string;
|
||||
comment?: string;
|
||||
automatic?: boolean;
|
||||
skipped?: boolean;
|
||||
operator?: { id?: string; name?: string; code?: string };
|
||||
nextOperators?: Array<{ id?: string; name?: string; code?: string }>;
|
||||
}
|
||||
|
||||
export interface BillFlowNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
state?: string;
|
||||
approver?: { id?: string; name?: string; code?: string };
|
||||
approvers?: Array<{ id?: string; name?: string; code?: string }>;
|
||||
}
|
||||
|
||||
export interface BillFlowTimeline {
|
||||
backlogId: string;
|
||||
flowId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
state?: string;
|
||||
currentNode?: string;
|
||||
history: BillFlowEntry[];
|
||||
pending: BillFlowNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRiskWarning {
|
||||
riskLevel?: string;
|
||||
type?: string;
|
||||
title?: string;
|
||||
controlName?: string;
|
||||
messages: string[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRiskReport {
|
||||
flowId: string;
|
||||
budgetExceeded?: boolean;
|
||||
budget?: Record<string, unknown>;
|
||||
credit?: Record<string, unknown>;
|
||||
rules?: Record<string, unknown>;
|
||||
notes?: Record<string, unknown>;
|
||||
warnings: BillRiskWarning[];
|
||||
invoiceWarnings: Record<string, unknown>[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillReference {
|
||||
id: string;
|
||||
name?: string;
|
||||
code?: string;
|
||||
path?: string;
|
||||
kind: "staff" | "department" | "feeType" | "legalEntity" | "dimension" | "unknown";
|
||||
source: "joined" | "catalog" | "raw";
|
||||
}
|
||||
|
||||
export interface BillReferenceReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
submitter?: BillReference;
|
||||
owner?: BillReference;
|
||||
department?: BillReference;
|
||||
legalEntity?: BillReference;
|
||||
feeTypes: BillReference[];
|
||||
dimensions: BillReference[];
|
||||
unresolved: string[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRelationNode {
|
||||
relation: string;
|
||||
id?: string;
|
||||
code?: string;
|
||||
title?: string;
|
||||
amount?: string;
|
||||
children: BillRelationNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillRelationsReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
relations: BillRelationNode[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillAttachment {
|
||||
fileId?: string;
|
||||
key?: string;
|
||||
fileName?: string;
|
||||
url?: string;
|
||||
thumbUrl?: string;
|
||||
sourceField: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BillAttachmentReport {
|
||||
target: string;
|
||||
billId?: string;
|
||||
billCode?: string;
|
||||
title?: string;
|
||||
attachments: BillAttachment[];
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { StaffSchema, type Staff } from "./types.js";
|
||||
|
||||
export async function fetchStaffs(
|
||||
client: KyInstance,
|
||||
external: boolean = false
|
||||
): Promise<Staff[]> {
|
||||
const response = await client.get("api/easo/common/staffs", {
|
||||
searchParams: { external: String(external) },
|
||||
});
|
||||
const json = (await response.json()) as { data: unknown };
|
||||
return z.array(StaffSchema).parse(json.data ?? []);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { StaffSchema, type Staff } from "./types.js";
|
||||
|
||||
describe("Contact Domain - 通讯录与人员模型", () => {
|
||||
test("StaffSchema 正确解析包含 null 字段的员工对象", () => {
|
||||
const raw = {
|
||||
id: "corp123:staff456",
|
||||
name: "测试员工",
|
||||
email: null,
|
||||
cellphone: null,
|
||||
department: null,
|
||||
};
|
||||
const parsed = StaffSchema.parse(raw);
|
||||
expect(parsed.id).toBe("corp123:staff456");
|
||||
expect(parsed.name).toBe("测试员工");
|
||||
expect(parsed.email).toBeNull();
|
||||
});
|
||||
|
||||
test("StaffSchema 正确解析完整员工信息", () => {
|
||||
const raw = {
|
||||
id: "corp123:staff456",
|
||||
name: "张三",
|
||||
email: "zhangsan@example.com",
|
||||
cellphone: "13800138000",
|
||||
department: "研发部",
|
||||
};
|
||||
const parsed = StaffSchema.parse(raw);
|
||||
expect(parsed.name).toBe("张三");
|
||||
expect(parsed.email).toBe("zhangsan@example.com");
|
||||
expect(parsed.cellphone).toBe("13800138000");
|
||||
expect(parsed.department).toBe("研发部");
|
||||
});
|
||||
|
||||
test("模糊搜索与过滤逻辑可正确按姓名、邮箱、工号匹配", () => {
|
||||
const list: Staff[] = [
|
||||
{ id: "corp:001", name: "王硕", email: "wangshuo@test.com", cellphone: "13911112222" },
|
||||
{ id: "corp:002", name: "李雨笑", email: "liyuxiao@test.com", cellphone: null },
|
||||
{ id: "corp:003", name: "谢子豪", email: "xiezihao@test.com", cellphone: "13933334444" },
|
||||
];
|
||||
|
||||
const search = (kw: string) => {
|
||||
const q = kw.toLowerCase();
|
||||
return list.filter((s) => s.name.includes(q) || (s.email && s.email.includes(q)) || s.id.includes(q));
|
||||
};
|
||||
|
||||
expect(search("王硕").length).toBe(1);
|
||||
expect(search("wangshuo").length).toBe(1);
|
||||
expect(search("003").length).toBe(1);
|
||||
expect(search("003")[0].name).toBe("谢子豪");
|
||||
expect(search("不存在").length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { z } from "zod";
|
||||
import { getEasoClient } from "../../core/auth/easo.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { fetchStaffs } from "./api.js";
|
||||
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
|
||||
|
||||
export const DEFAULT_STAFF_LIST_LIMIT = 20;
|
||||
|
||||
export async function listStaffsProtected(
|
||||
corp: CorpConfig,
|
||||
options: ContactSearchOptions = {}
|
||||
): Promise<ContactListResult> {
|
||||
const { client } = await getEasoClient(corp);
|
||||
const allStaffs = await fetchStaffs(client, options.external ?? false);
|
||||
|
||||
const total = allStaffs.length;
|
||||
const isFull = options.allowFull === true;
|
||||
const limit = isFull ? total : options.limit ?? DEFAULT_STAFF_LIST_LIMIT;
|
||||
const staffs = allStaffs.slice(0, limit);
|
||||
const hasMore = total > staffs.length;
|
||||
|
||||
return {
|
||||
total,
|
||||
limit,
|
||||
hasMore,
|
||||
hint: hasMore
|
||||
? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`
|
||||
: undefined,
|
||||
staffs,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchStaffs(
|
||||
corp: CorpConfig,
|
||||
options: { keyword: string; limit?: number; external?: boolean }
|
||||
): Promise<Staff[]> {
|
||||
const { client } = await getEasoClient(corp);
|
||||
const allStaffs = await fetchStaffs(client, options.external ?? false);
|
||||
|
||||
const kw = options.keyword.trim().toLowerCase();
|
||||
if (!kw) {
|
||||
return allStaffs.slice(0, options.limit ?? DEFAULT_STAFF_LIST_LIMIT);
|
||||
}
|
||||
|
||||
const matched = allStaffs.filter((s) => {
|
||||
const name = s.name?.toLowerCase() || "";
|
||||
const email = s.email?.toLowerCase() || "";
|
||||
const phone = s.cellphone || "";
|
||||
const id = s.id?.toLowerCase() || "";
|
||||
return name.includes(kw) || email.includes(kw) || phone.includes(kw) || id.includes(kw);
|
||||
});
|
||||
|
||||
return matched.slice(0, options.limit ?? 50);
|
||||
}
|
||||
|
||||
export async function getStaffById(
|
||||
corp: CorpConfig,
|
||||
staffId: string
|
||||
): Promise<Staff | null> {
|
||||
const { client } = await getEasoClient(corp);
|
||||
const allStaffs = await fetchStaffs(client, false);
|
||||
|
||||
const cleanId = staffId.trim();
|
||||
const found = allStaffs.find(
|
||||
(s) => s.id === cleanId || s.id.endsWith(`:${cleanId}`) || s.id.split(":")[1] === cleanId
|
||||
);
|
||||
|
||||
return found || null;
|
||||
}
|
||||
|
||||
// ── MCP Tool Definitions ──────────────────────────────────────────────────────
|
||||
|
||||
export const contactTools = [
|
||||
{
|
||||
name: "contact_search",
|
||||
description: "在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",
|
||||
parameters: z.object({
|
||||
keyword: z.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),
|
||||
limit: z.number().optional().describe("最大返回条数,默认 20"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { keyword: string; limit?: number }) => {
|
||||
const results = await searchStaffs(corp, params);
|
||||
return { count: results.length, staffs: results };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "contact_get",
|
||||
description: "根据员工 staffId 或工号精准获取员工详细档案",
|
||||
parameters: z.object({
|
||||
staffId: z.string().describe("员工的完整 staffId 或 ID"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { staffId: string }) => {
|
||||
const staff = await getStaffById(corp, params.staffId);
|
||||
if (!staff) {
|
||||
throw new Error(`未找到员工: ${params.staffId}`);
|
||||
}
|
||||
return staff;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "contact_list",
|
||||
description: "查看企业通讯录(带默认 20 条防爆截断与总数保护)",
|
||||
parameters: z.object({
|
||||
limit: z.number().optional().describe("截断返回条数,默认 20"),
|
||||
allowFull: z.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { limit?: number; allowFull?: boolean }) => {
|
||||
return await listStaffsProtected(corp, params);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const StaffSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string().nullable().optional(),
|
||||
cellphone: z.string().nullable().optional(),
|
||||
department: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type Staff = z.infer<typeof StaffSchema>;
|
||||
|
||||
export interface ContactListResult {
|
||||
total: number;
|
||||
limit: number;
|
||||
hasMore: boolean;
|
||||
hint?: string;
|
||||
staffs: Staff[];
|
||||
}
|
||||
|
||||
export interface ContactSearchOptions {
|
||||
keyword?: string;
|
||||
limit?: number;
|
||||
allowFull?: boolean;
|
||||
external?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Dimension 域说明
|
||||
|
||||
Dimension 域负责“系统配置 → 档案设置 → 扩展档案 → 自定义档案”目录和档案项查询。
|
||||
|
||||
- `listDimensionCatalogs` 调用组织权限目录后,分别拉取系统档案 (`preset==1`) 与自定义档案 (`preset==0`);
|
||||
- `listDimensionItems` 调用档案项接口并保留 `id`、`code`、`name`、`parentId`、`fullPath` 和 `form`;
|
||||
- `tools.ts` 按企业在进程内缓存目录与档案项 10 分钟。
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { DimensionCatalogSchema, DimensionItemSchema, type DimensionCatalog, type DimensionItem } from "./types.js";
|
||||
|
||||
export async function listDimensionCatalogs(client: KyInstance, corpId: string, start = 0, count = 100): Promise<DimensionCatalog[]> {
|
||||
const organizationResponse = await client.get("api/authority/v2/organization/list/$DIMENSION", {
|
||||
searchParams: { start: String(start), count: String(count), model: "DIMENSION", corpId },
|
||||
});
|
||||
const organizationJson = (await organizationResponse.json()) as { items?: Array<{ id?: string }> };
|
||||
const orgId = organizationJson.items?.[0]?.id;
|
||||
if (!orgId) return [];
|
||||
const responses = await Promise.all([0, 1].map((preset) => client.post("api/v1/basedata/dimensions/active", {
|
||||
searchParams: { orgId, corpId },
|
||||
json: {
|
||||
limit: { start, count },
|
||||
select: "id,label,enLabel,code,name,state,type,active",
|
||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||
filterBy: `preset==${preset}`,
|
||||
},
|
||||
})));
|
||||
const items: unknown[] = [];
|
||||
for (const response of responses) {
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
items.push(...(json.items ?? []));
|
||||
}
|
||||
return z.array(DimensionCatalogSchema).parse(items);
|
||||
}
|
||||
|
||||
export async function listDimensionItems(client: KyInstance, corpId: string, dimensionId: string, start = 0, count = 100): Promise<DimensionItem[]> {
|
||||
const response = await client.post(`api/v1/basedata/dimensionItems/$${dimensionId}`, {
|
||||
searchParams: { corpId, dimensionItemId: "" },
|
||||
json: { filterBy: "(active == true)", limit: { start, count } },
|
||||
});
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(DimensionItemSchema).parse(json.items ?? []);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { searchDimensions, resolveDimension } from "./tools.js";
|
||||
|
||||
describe("Dimension Domain - 自定义档案目录", () => {
|
||||
it("loads preset and custom dimension catalogs and filters by name", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [{ id: "org-1" }] })),
|
||||
post: async (_path: string, options: any) => new Response(JSON.stringify({ items: [
|
||||
options.json.filterBy === "preset==0" ? { id: "dim-custom", name: "项目", code: "DA001", type: "normal", active: true } : { id: "dim-system", name: "法人实体", code: "FRST", type: "legal_entity", active: true },
|
||||
] })),
|
||||
} as any;
|
||||
const result = await searchDimensions(client, "corp-dimension", { name: "项目" });
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.code).toBe("DA001");
|
||||
});
|
||||
|
||||
it("loads dimension items by catalog ID", async () => {
|
||||
const client = {
|
||||
get: async () => new Response(JSON.stringify({ items: [{ id: "org-2" }] })),
|
||||
post: async (path: string) => new Response(JSON.stringify(path.includes("dimensionItems") ? { items: [{ id: "item-1", name: "研发项目", code: "P001", parentId: "", active: true }] } : { items: [{ id: "dim-project", name: "项目", code: "DA001", type: "normal", active: true }] })),
|
||||
} as any;
|
||||
const result = await resolveDimension(client, "corp-items", "项目");
|
||||
expect(result?.dimension.id).toBe("dim-project");
|
||||
expect(result?.items[0]?.name).toBe("研发项目");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
|
||||
import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js";
|
||||
|
||||
const cache = new Map<string, { timestamp: number; catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }> {
|
||||
const existing = cache.get(corpId);
|
||||
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
|
||||
const catalogs = await listDimensionCatalogs(client, corpId);
|
||||
const result = { timestamp: Date.now(), catalogs, items: new Map<string, DimensionItem[]>() };
|
||||
cache.set(corpId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise<DimensionCatalog[]> {
|
||||
const { catalogs } = await getCached(client, corpId);
|
||||
const keyword = (query.name || query.code || query.id || "").trim().toLowerCase();
|
||||
if (!keyword) return catalogs;
|
||||
return catalogs.filter((item) => [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword)));
|
||||
}
|
||||
|
||||
export async function getDimensionItems(client: KyInstance, corpId: string, dimension: DimensionCatalog, start = 0, count = 100): Promise<DimensionItem[]> {
|
||||
const catalog = await getCached(client, corpId);
|
||||
const cached = catalog.items.get(dimension.id);
|
||||
if (cached && start === 0 && count >= cached.length) return cached;
|
||||
const items = await listDimensionItems(client, corpId, dimension.id, start, count);
|
||||
if (start === 0) catalog.items.set(dimension.id, items);
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function resolveDimension(client: KyInstance, corpId: string, target: string): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
|
||||
const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target });
|
||||
const dimension = matches[0];
|
||||
if (!dimension) return undefined;
|
||||
return { dimension, items: await getDimensionItems(client, corpId, dimension) };
|
||||
}
|
||||
|
||||
export const dimensionTools = [
|
||||
{
|
||||
name: "dimension_list",
|
||||
description: "列出企业档案管理中的系统/自定义档案维度目录",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const items = await searchDimensions(await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), corp.corpId || corp.id, { name: params.keyword });
|
||||
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DimensionCatalogSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().default(""),
|
||||
code: z.string().optional().default(""),
|
||||
type: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
state: z.string().nullable().optional().transform((value) => value ?? ""),
|
||||
});
|
||||
|
||||
export const DimensionItemSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().default(""),
|
||||
code: z.string().optional().default(""),
|
||||
parentId: z.string().optional().default(""),
|
||||
dimensionId: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
deleted: z.boolean().optional().default(false),
|
||||
fullPath: z.string().nullable().optional(),
|
||||
form: z.record(z.string(), z.any()).optional().default({}),
|
||||
});
|
||||
|
||||
export type DimensionCatalog = z.infer<typeof DimensionCatalogSchema>;
|
||||
export type DimensionItem = z.infer<typeof DimensionItemSchema>;
|
||||
|
||||
export interface DimensionQuery {
|
||||
id?: string;
|
||||
code?: string;
|
||||
name?: string;
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EventStore } from "./store.js";
|
||||
import { pollEvents } from "./poller.js";
|
||||
|
||||
describe("Event poller", () => {
|
||||
it("persists dedupe keys and only returns new events", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hose-events-"));
|
||||
try {
|
||||
const store = new EventStore(join(dir, "events.json"));
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("messages") ? { count: 1, items: [{ id: "m-1", title: "新消息", read: false, updateTime: 10 }] } : { count: 0, items: [] }),), post: async () => new Response(JSON.stringify({ count: 1, items: [{ id: "t-1", updateTime: 11, flowId: { form: { title: "待审单据" } } }] })) } as any;
|
||||
const first = await pollEvents(client, "corp-1", store, 10);
|
||||
const second = await pollEvents(client, "corp-1", store, 10);
|
||||
expect(first.newEvents).toHaveLength(2); expect(second.newEvents).toHaveLength(0); expect(second.duplicateCount).toBe(2);
|
||||
expect(JSON.parse(readFileSync(join(dir, "events.json"), "utf8")).version).toBe(1);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { listMessages } from "../message/tools.js";
|
||||
import { listTasks } from "../task/tools.js";
|
||||
import { EventStore } from "./store.js";
|
||||
import type { EventPollResult, EventRecord } from "./types.js";
|
||||
|
||||
function eventId(kind: EventRecord["kind"], id: string, updatedAt?: number): string { return `${kind}:${id}:${updatedAt ?? 0}`; }
|
||||
|
||||
export async function pollEvents(client: KyInstance, corpId: string, store: EventStore, count = 50): Promise<EventPollResult> {
|
||||
const observedAt = Date.now();
|
||||
const [todo, messages] = await Promise.all([
|
||||
listTasks(client, corpId, "todo", { start: 0, count }),
|
||||
listMessages(client, corpId, { start: 0, count, read: false }),
|
||||
]);
|
||||
const candidates: EventRecord[] = [
|
||||
...todo.items.map((payload) => ({ id: eventId("todo", payload.taskId, payload.updatedAt || payload.actionTime), kind: "todo" as const, corpId, observedAt, payload })),
|
||||
...messages.items.map((payload) => ({ id: eventId("message", payload.id, payload.updateTime || payload.createTime), kind: "message" as const, corpId, observedAt, payload })),
|
||||
];
|
||||
const newEvents = candidates.filter((event) => !store.has(event.id));
|
||||
store.commit(candidates);
|
||||
return { corpId, observedAt, scanned: { todo: todo.items.length, messages: messages.items.length }, newEvents, duplicateCount: candidates.length - newEvents.length };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import type { EventRecord } from "./types.js";
|
||||
|
||||
interface PersistedEvents { version: 1; events: Record<string, number>; }
|
||||
const MAX_EVENTS = 2000;
|
||||
|
||||
export class EventStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
private read(): PersistedEvents {
|
||||
if (!existsSync(this.filePath)) return { version: 1, events: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
|
||||
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
|
||||
} catch { return { version: 1, events: {} }; }
|
||||
}
|
||||
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
|
||||
commit(records: EventRecord[]): void {
|
||||
if (!records.length) return;
|
||||
const data = this.read();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { MessageItem } from "../message/types.js";
|
||||
import type { TaskItem } from "../task/types.js";
|
||||
|
||||
export type EventKind = "todo" | "message";
|
||||
export interface EventRecord { id: string; kind: EventKind; corpId: string; observedAt: number; payload: TaskItem | MessageItem; }
|
||||
export interface EventPollResult { corpId: string; observedAt: number; scanned: { todo: number; messages: number }; newEvents: EventRecord[]; duplicateCount: number; }
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { MessageQueryOptions } from "./types.js";
|
||||
|
||||
export async function fetchMessagePage(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: MessageQueryOptions = {}
|
||||
): Promise<{ count: number; items: Record<string, unknown>[] }> {
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
const read = options.read ?? false;
|
||||
const response = await client.get("api/message/v1/messages", {
|
||||
searchParams: {
|
||||
read: String(read),
|
||||
start: String(start),
|
||||
count: String(count),
|
||||
corpId,
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
export async function markMessageRead(client: KyInstance, corpId: string, messageId: string): Promise<void> {
|
||||
// The downstream route accepts the compound ID with its colon separators intact.
|
||||
await client.put(`api/message/v1/messages/$${messageId}`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: messageId },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { filterMessages, mergeMessages, normalizeMessage } from "./tools.js";
|
||||
|
||||
describe("Message Domain - 消息中心模型", () => {
|
||||
test("normalizes message fields and filters by type", () => {
|
||||
const item = normalizeMessage({
|
||||
id: "msg-1",
|
||||
title: "你的单据被驳回",
|
||||
content: "单据:有效性。",
|
||||
messageType: "INFO",
|
||||
msgTypeName: "审批通知",
|
||||
read: false,
|
||||
sortTime: 1776052034000,
|
||||
});
|
||||
expect(item.id).toBe("msg-1");
|
||||
expect(item.read).toBe(false);
|
||||
expect(filterMessages([item], "审批")).toHaveLength(1);
|
||||
expect(filterMessages([item], "Loan_Repayment")).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("merges read and unread pages by ID and newest time", () => {
|
||||
const older = normalizeMessage({ id: "msg-1", title: "旧标题", read: false, sortTime: 10 });
|
||||
const newer = normalizeMessage({ id: "msg-1", title: "新标题", read: true, sortTime: 20 });
|
||||
const second = normalizeMessage({ id: "msg-2", title: "第二条", read: false, sortTime: 15 });
|
||||
const merged = mergeMessages([older, second, newer]);
|
||||
expect(merged.map((item) => item.id)).toEqual(["msg-2", "msg-1"]);
|
||||
expect(merged[1]?.title).toBe("旧标题");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { fetchMessagePage, markMessageRead } from "./api.js";
|
||||
import type { MessageItem, MessagePageResult, MessageQueryOptions } from "./types.js";
|
||||
|
||||
export function normalizeMessage(raw: Record<string, unknown>): MessageItem {
|
||||
return {
|
||||
id: String(raw.id ?? ""),
|
||||
title: typeof raw.title === "string" ? raw.title : undefined,
|
||||
content: typeof raw.content === "string" ? raw.content : undefined,
|
||||
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
|
||||
msgType: typeof raw.msgType === "string" ? raw.msgType : undefined,
|
||||
msgTypeName: typeof raw.msgTypeName === "string" ? raw.msgTypeName : undefined,
|
||||
msgName: typeof raw.msgName === "string" ? raw.msgName : undefined,
|
||||
read: raw.read === true,
|
||||
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
|
||||
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined,
|
||||
sortTime: typeof raw.sortTime === "number" ? raw.sortTime : undefined,
|
||||
sourceId: typeof raw.sourceId === "string" || raw.sourceId === null ? raw.sourceId : undefined,
|
||||
sourceType: typeof raw.sourceType === "string" ? raw.sourceType : undefined,
|
||||
sourceStatus: typeof raw.sourceStatus === "string" || raw.sourceStatus === null ? raw.sourceStatus : undefined,
|
||||
url: typeof raw.url === "string" ? raw.url : undefined,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listMessages(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: MessageQueryOptions = {}
|
||||
): Promise<MessagePageResult> {
|
||||
const page = await fetchMessagePage(client, corpId, options);
|
||||
return {
|
||||
total: page.count,
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 20,
|
||||
read: options.read ?? false,
|
||||
items: page.items.map(normalizeMessage),
|
||||
};
|
||||
}
|
||||
|
||||
export async function readMessage(client: KyInstance, corpId: string, messageId: string): Promise<void> {
|
||||
await markMessageRead(client, corpId, messageId);
|
||||
}
|
||||
|
||||
export function filterMessages(items: MessageItem[], messageType?: string): MessageItem[] {
|
||||
if (!messageType) return items;
|
||||
const target = messageType.toLowerCase();
|
||||
return items.filter((item) => [item.messageType, item.msgType, item.msgTypeName, item.msgName]
|
||||
.filter(Boolean)
|
||||
.some((value) => String(value).toLowerCase() === target || String(value).toLowerCase().includes(target)));
|
||||
}
|
||||
|
||||
export function mergeMessages(items: MessageItem[]): MessageItem[] {
|
||||
return [...items]
|
||||
.filter((item, index, all) => all.findIndex((candidate) => candidate.id === item.id) === index)
|
||||
.sort((left, right) => (right.sortTime ?? right.createTime ?? 0) - (left.sortTime ?? left.createTime ?? 0));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface MessageQueryOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
read?: boolean;
|
||||
}
|
||||
|
||||
export interface MessageItem {
|
||||
id: string;
|
||||
title?: string;
|
||||
content?: string;
|
||||
messageType?: string;
|
||||
msgType?: string;
|
||||
msgTypeName?: string;
|
||||
msgName?: string;
|
||||
read: boolean;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
sortTime?: number;
|
||||
sourceId?: string | null;
|
||||
sourceType?: string;
|
||||
sourceStatus?: string | null;
|
||||
url?: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface MessagePageResult {
|
||||
total: number;
|
||||
start: number;
|
||||
count: number;
|
||||
read: boolean;
|
||||
items: MessageItem[];
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Permission Domain
|
||||
|
||||
权限域当前提供系统配置 → 权限页面的角色模型权限快照,只读查询:
|
||||
|
||||
- `GET /api/glue/v1/organization/permissions/query?model=ROLE&corpId=...`
|
||||
|
||||
CLI 入口为 `hose permission get`(也支持 `hose permissions get`)。写入权限仍需通过 Web 端明确操作,CLI 不提供写操作。
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { PermissionReportSchema, type PermissionReport } from "./types.js";
|
||||
|
||||
export async function getRolePermissions(client: KyInstance, corpId: string): Promise<PermissionReport> {
|
||||
const response = await client.get("api/glue/v1/organization/permissions/query", { searchParams: { model: "ROLE", corpId } });
|
||||
const json = (await response.json()) as { value?: unknown };
|
||||
return PermissionReportSchema.parse(json.value ?? {});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { getPermissions } from "./tools.js";
|
||||
|
||||
describe("Permission Domain - 角色权限", () => {
|
||||
it("parses the role permission snapshot", async () => {
|
||||
const client = { get: async () => new Response(JSON.stringify({ value: { type: "FREEDOM", permissions: [{ name: "CREATE", auth: true }, { name: "EDIT", auth: false }] } })) } as any;
|
||||
const result = await getPermissions(client, "corp-1");
|
||||
expect(result.type).toBe("FREEDOM"); expect(result.permissions).toHaveLength(2); expect(result.permissions[0]?.auth).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getRolePermissions } from "./api.js";
|
||||
|
||||
export async function getPermissions(client: KyInstance, corpId: string) { return getRolePermissions(client, corpId); }
|
||||
|
||||
export const permissionTools = [{
|
||||
name: "permission_role_get",
|
||||
description: "读取当前企业角色模型的权限开关(只读)",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: any) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
|
||||
return getPermissions(client, corp.corpId || corp.id);
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const PermissionEntrySchema = z.object({ name: z.string(), auth: z.boolean().default(false) });
|
||||
export const PermissionReportSchema = z.object({ type: z.string().default(""), permissions: z.array(PermissionEntrySchema).default([]) });
|
||||
export type PermissionEntry = z.infer<typeof PermissionEntrySchema>;
|
||||
export type PermissionReport = z.infer<typeof PermissionReportSchema>;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analysis.js";
|
||||
import { PlatformSchema } from "./types.js";
|
||||
|
||||
describe("Workflow static analysis", () => {
|
||||
it("accepts nullable app center metadata", () => {
|
||||
const platform = PlatformSchema.parse({ id: "app-1", name: "测试应用", corporationId: "corp-1", adminIds: null, importMethod: null });
|
||||
expect(platform.adminIds).toEqual([]);
|
||||
expect(platform.importMethod).toEqual([]);
|
||||
});
|
||||
|
||||
it("builds a recursive AST and extracts code references", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
}
|
||||
@@ -14,9 +14,9 @@ export const PlatformSchema = z.object({
|
||||
groupType: z.string().default(""),
|
||||
platformType: z.string().default(""),
|
||||
source: z.string().default(""),
|
||||
adminIds: z.array(z.string()).default([]),
|
||||
adminIds: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
desc: z.string().nullable().optional(),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
importMethod: z.array(z.string()).nullish().transform((value) => value ?? []),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Role Domain
|
||||
|
||||
角色域提供企业角色定义、角色组和角色成员的只读查询。
|
||||
|
||||
- `GET /api/v1/organization/roles?start=0&count=2999&corpId=...`:角色定义列表
|
||||
- `GET /api/v1/organization/roleGroups?corpId=...`:角色组及其角色定义
|
||||
- `GET /api/v1/organization/staffs/byRole?roleDefId=...&corpId=...`:指定角色的员工成员
|
||||
|
||||
CLI 入口为 `hose role list`、`hose role groups` 和 `hose role members <角色 ID|编码|名称>`。
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { RoleGroupSchema, RoleMemberSchema, RoleSchema, type Role, type RoleGroup, type RoleMember } from "./types.js";
|
||||
|
||||
export async function listRoles(client: KyInstance, corpId: string, start = 0, count = 2999): Promise<Role[]> {
|
||||
const response = await client.get("api/v1/organization/roles", { searchParams: { start: String(start), count: String(count), corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
|
||||
const response = await client.get("api/v1/organization/roleGroups", { searchParams: { corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleGroupSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleMembers(client: KyInstance, corpId: string, roleDefId: string): Promise<RoleMember[]> {
|
||||
const response = await client.get("api/v1/organization/staffs/byRole", { searchParams: { roleDefId, corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
const items = (json.items ?? []).map((item: any) => item?.staff ?? item);
|
||||
return z.array(RoleMemberSchema).parse(items);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { getRoleMembers, getRoleGroups, searchRoles } from "./tools.js";
|
||||
|
||||
describe("Role Domain - 角色定义与成员", () => {
|
||||
it("loads and filters roles", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("roleGroups")
|
||||
? { items: [{ id: "group-1", name: "未分组", roleDefs: [{ id: "role-1", name: "财务主管", code: "FIN" }] }] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", roleGroupId: "group-1", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const roles = await searchRoles(client, "corp-1", { keyword: "财务" });
|
||||
expect(roles).toHaveLength(1); expect(roles[0]?.id).toBe("role-1");
|
||||
expect((await getRoleGroups(client, "corp-1"))[0]?.name).toBe("未分组");
|
||||
});
|
||||
|
||||
it("resolves a role and loads its members", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("staffs/byRole")
|
||||
? { items: [{ id: "staff-1", name: "张三", code: "1001", departments: [] }] }
|
||||
: path.includes("roleGroups") ? { items: [] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const report = await getRoleMembers(client, "corp-2", "FIN");
|
||||
expect(report?.role.name).toBe("财务主管"); expect(report?.members[0]?.name).toBe("张三");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
|
||||
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
|
||||
|
||||
const cache = new Map<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
|
||||
const existing = cache.get(corpId);
|
||||
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
|
||||
const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]);
|
||||
const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result;
|
||||
}
|
||||
|
||||
export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise<Role[]> {
|
||||
const { roles } = await getCatalog(client, corpId);
|
||||
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
|
||||
if (!keyword) return roles;
|
||||
return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword)));
|
||||
}
|
||||
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
|
||||
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
|
||||
const matches = await searchRoles(client, corpId, { keyword: target });
|
||||
return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0];
|
||||
}
|
||||
export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise<RoleMemberReport | undefined> {
|
||||
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
|
||||
return { role, members: await listRoleMembers(client, corpId, role.id) };
|
||||
}
|
||||
|
||||
export const roleTools = [{
|
||||
name: "role_list", description: "列出当前企业角色定义与角色组",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
|
||||
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
|
||||
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const RoleScopeSchema = z.object({
|
||||
name: z.string().optional().default(""),
|
||||
enName: z.string().nullable().optional().default(""),
|
||||
properties: z.record(z.string(), z.string()).optional().default({}),
|
||||
});
|
||||
|
||||
export const RoleSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleGroupId: z.string().optional().default(""), scope: RoleScopeSchema.optional().default({ name: "", enName: "", properties: {} }),
|
||||
sourceType: z.string().optional().default(""), sourceTypeValue: z.string().nullable().optional(),
|
||||
purposeType: z.string().optional().default(""), purposeName: z.string().optional().default(""),
|
||||
locked: z.boolean().optional().default(false), containSubDept: z.boolean().optional().default(false),
|
||||
applicableToSubDepartments: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export const RoleGroupSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleDefs: z.array(RoleSchema).optional().default([]),
|
||||
});
|
||||
|
||||
export const RoleMemberSchema = z.object({
|
||||
id: z.string(), userId: z.string().optional().default(""), name: z.string().default(""),
|
||||
code: z.string().optional().default(""), enName: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(), cellphone: z.string().nullable().optional(),
|
||||
active: z.boolean().optional().default(true), departments: z.array(z.string()).optional().default([]),
|
||||
defaultDepartment: z.string().nullable().optional(), external: z.boolean().optional().default(false),
|
||||
admin: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export type Role = z.infer<typeof RoleSchema>;
|
||||
export type RoleGroup = z.infer<typeof RoleGroupSchema>;
|
||||
export type RoleMember = z.infer<typeof RoleMemberSchema>;
|
||||
export interface RoleQuery { keyword?: string; id?: string; code?: string; name?: string; }
|
||||
export interface RoleMemberReport { role: Role; members: RoleMember[]; }
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { TaskQueryOptions, TaskView } from "./types.js";
|
||||
|
||||
const JOIN = [
|
||||
"flowId.form.payMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.expenseMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.loanMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.form.requisitionMoney.standardNumCode,standardNumCode,/v1/basedata/enumItems",
|
||||
"flowId.id,nodeState,/flow/v2/backlogs/state",
|
||||
];
|
||||
|
||||
function dateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((updateTime > ${from}) && (updateTime < ${to}))`;
|
||||
}
|
||||
|
||||
function approvedDateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((approvedFlow.updateTime > ${from}) && (approvedFlow.updateTime < ${to}))`;
|
||||
}
|
||||
|
||||
function submittedDateFilter(options: TaskQueryOptions): string {
|
||||
if (options.from === undefined && options.to === undefined) return "";
|
||||
const from = options.from ?? 0;
|
||||
const to = options.to ?? 32503680000000;
|
||||
return `&&((form.submitDate > ${from}) && (form.submitDate < ${to}))`;
|
||||
}
|
||||
|
||||
function selectForBacklog(): string {
|
||||
return "flowId(ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney),`...`),`...`";
|
||||
}
|
||||
|
||||
function selectForCarbonCopy(): string {
|
||||
return "flowId(ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney),`...`),`...`";
|
||||
}
|
||||
|
||||
export async function fetchTaskPage(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
view: TaskView,
|
||||
options: TaskQueryOptions = {}
|
||||
): Promise<{ count: number; items: Record<string, unknown>[] }> {
|
||||
const start = options.start ?? 0;
|
||||
const count = options.count ?? 20;
|
||||
|
||||
if (view === "submitted") {
|
||||
const response = await client.post("api/flow/v1/flows/my", {
|
||||
searchParams: {
|
||||
type: "home5",
|
||||
delegatedFilter: "DELEGATE_TO_ME",
|
||||
corpId,
|
||||
},
|
||||
json: {
|
||||
filterBy: `(state.in("rejected","draft","sending","receiving","receivingExcep","approving","pending","paying","paid"))&&(INSTR(form.specificationId,"${corpId}:system:对账单")==0)${submittedDateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
orderBy: [{ value: "form.submitDate", order: "DESC" }],
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
if (view === "cc") {
|
||||
const searchParams = new URLSearchParams({ corpId });
|
||||
searchParams.append("join", "flowId.id,nodeState,/flow/v2/backlogs/state");
|
||||
const state = options.read ? "READ" : "UNREAD";
|
||||
const response = await client.post("api/flow/v2/carbonCopy/search", {
|
||||
searchParams,
|
||||
json: {
|
||||
filterBy: `(state.in(\"${state}\"))&&((type != \"permit\"))`,
|
||||
limit: { start, count },
|
||||
select: selectForCarbonCopy(),
|
||||
orderBy: [{ value: "updateTime", order: "ASC" }],
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
if (view === "approved") {
|
||||
const response = await client.post("api/flow/v1/flows/approved", {
|
||||
searchParams: {
|
||||
join: "id,nodeState,/flow/v2/backlogs/state",
|
||||
corpId,
|
||||
},
|
||||
json: {
|
||||
query: {
|
||||
filterBy: `(approvedFlow.action==\"APPROVED\")&&((formType != \"permit\"))${approvedDateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
select: "ownerId(id,name,enName),form(title,code,specificationId(active,id,name,enName,nameSpell,code),submitDate,submitterId(id,name,enName,nickName,code,email,cellphone,note),reviewStatus,expenseMoney,loanMoney,requisitionMoney,payMoney,`...`),`...`",
|
||||
},
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
|
||||
const state = view === "todo" ? "APPROVING" : "PROCESSED";
|
||||
const orderBy = view === "todo"
|
||||
? [
|
||||
{ value: "flowId.state", order: "ASC" },
|
||||
{ value: "isUrgent", order: "DESC" },
|
||||
{ value: "updateTime", order: "ASC" },
|
||||
]
|
||||
: [{ value: "updateTime", order: "DESC" }];
|
||||
const searchParams = new URLSearchParams({ corpId });
|
||||
for (const join of JOIN) searchParams.append("join", join);
|
||||
const response = await client.post("api/flow/v2/backlogs/search", {
|
||||
searchParams,
|
||||
json: {
|
||||
filterBy: `(state.in(\"${state}\"))${dateFilter(options)}`,
|
||||
limit: { start, count },
|
||||
select: selectForBacklog(),
|
||||
orderBy,
|
||||
...(view === "todo" ? { creditSearch: true } : {}),
|
||||
},
|
||||
});
|
||||
const json = (await response.json()) as { count?: number; items?: Record<string, unknown>[] };
|
||||
return { count: json.count ?? json.items?.length ?? 0, items: json.items ?? [] };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { normalizeTask } from "./tools.js";
|
||||
|
||||
describe("Task Domain - 待办任务模型", () => {
|
||||
test("normalizes backlog and preserves approval actions", () => {
|
||||
const item = normalizeTask({
|
||||
id: "backlog-1",
|
||||
state: "APPROVING",
|
||||
nodeState: { nodeName: "主管审批" },
|
||||
actions: { "staff-1": ["freeflow.agree", "freeflow.reject"] },
|
||||
flowId: {
|
||||
id: "flow-1",
|
||||
formType: "expense",
|
||||
ownerId: { id: "staff-1", name: "张三" },
|
||||
form: {
|
||||
code: "BX26000001",
|
||||
title: "差旅报销",
|
||||
specificationId: { name: "报销单" },
|
||||
submitterId: { id: "staff-2", name: "李四", code: "1002" },
|
||||
expenseMoney: { standard: "120.00", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(item.taskId).toBe("backlog-1");
|
||||
expect(item.flowId).toBe("flow-1");
|
||||
expect(item.billCode).toBe("BX26000001");
|
||||
expect(item.submitter?.name).toBe("李四");
|
||||
expect(item.amount?.value).toBe("120.00");
|
||||
expect(item.actions).toEqual(["freeflow.agree", "freeflow.reject"]);
|
||||
});
|
||||
|
||||
test("normalizes flows returned by the submitted-bills endpoint", () => {
|
||||
const item = normalizeTask({
|
||||
flow: {
|
||||
id: "flow-submitted-1",
|
||||
state: "approving",
|
||||
ownerId: { id: "staff-1", name: "张三" },
|
||||
},
|
||||
form: {
|
||||
code: "BX26000002",
|
||||
title: "差旅报销",
|
||||
specification: { name: "差旅报销单" },
|
||||
submitterId: { id: "staff-1", name: "张三", code: "1001" },
|
||||
amount: { standard: "88.00", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
},
|
||||
});
|
||||
expect(item.taskId).toBe("flow-submitted-1");
|
||||
expect(item.state).toBe("approving");
|
||||
expect(item.templateName).toBe("差旅报销单");
|
||||
expect(item.amount?.value).toBe("88.00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { fetchTaskPage } from "./api.js";
|
||||
import type { TaskItem, TaskPageResult, TaskPerson, TaskQueryOptions, TaskView } from "./types.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function person(value: unknown): TaskPerson | undefined {
|
||||
const item = record(value);
|
||||
if (!Object.keys(item).length) return undefined;
|
||||
return {
|
||||
id: typeof item.id === "string" ? item.id : undefined,
|
||||
name: typeof item.name === "string" ? item.name : undefined,
|
||||
code: typeof item.code === "string" ? item.code : undefined,
|
||||
email: typeof item.email === "string" ? item.email : undefined,
|
||||
cellphone: typeof item.cellphone === "string" ? item.cellphone : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function money(value: unknown): TaskItem["amount"] {
|
||||
const item = record(value);
|
||||
if (item.standard === undefined) return undefined;
|
||||
return {
|
||||
value: String(item.standard),
|
||||
currency: typeof item.standardStrCode === "string" ? item.standardStrCode : undefined,
|
||||
symbol: typeof item.standardSymbol === "string" ? item.standardSymbol : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeTask(raw: Record<string, unknown>): TaskItem {
|
||||
const flow = record(raw.flowId ?? raw.flow);
|
||||
const form = record(flow.form ?? raw.form);
|
||||
const nodeState = record(raw.nodeState ?? flow.nodeState);
|
||||
const amount = money(form.expenseMoney ?? form.payMoney ?? form.requisitionMoney ?? form.loanMoney ?? form.amount);
|
||||
const specification = record(form.specificationId ?? form.specification);
|
||||
const submitter = person(form.submitterId);
|
||||
const owner = person(flow.ownerId ?? raw.ownerId);
|
||||
const actionsByStaff = record(flow.actions ?? raw.actions);
|
||||
const actionValues = Object.values(actionsByStaff).flatMap((value) => Array.isArray(value) ? value : []);
|
||||
const logs = Array.isArray(flow.logs) ? flow.logs : [];
|
||||
const logIndex = typeof raw.logId === "number" ? raw.logId : -1;
|
||||
const log = record(logs[logIndex] ?? logs[logs.length - 1]);
|
||||
const attributes = record(log.attributes);
|
||||
return {
|
||||
taskId: String(raw.id ?? flow.id ?? ""),
|
||||
flowId: typeof flow.id === "string" ? flow.id : typeof raw.id === "string" ? raw.id : undefined,
|
||||
billId: typeof flow.id === "string" ? flow.id : undefined,
|
||||
billCode: typeof form.code === "string" ? form.code : undefined,
|
||||
title: typeof form.title === "string" ? form.title : undefined,
|
||||
templateName: typeof specification.name === "string" ? specification.name : undefined,
|
||||
formType: typeof flow.formType === "string" ? flow.formType : typeof raw.type === "string" ? raw.type : undefined,
|
||||
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
|
||||
action: typeof log.action === "string" ? log.action : typeof raw.action === "string" ? raw.action : undefined,
|
||||
actionTime: typeof log.time === "number" ? log.time : undefined,
|
||||
comment: typeof attributes.comment === "string" ? attributes.comment : undefined,
|
||||
nodeName: typeof nodeState.nodeName === "string" ? nodeState.nodeName : typeof raw.nodeName === "string" ? raw.nodeName : undefined,
|
||||
submitDate: typeof form.submitDate === "number" ? form.submitDate : undefined,
|
||||
submitter,
|
||||
owner,
|
||||
amount,
|
||||
actions: actionValues.filter((value): value is string => typeof value === "string"),
|
||||
updatedAt: typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : undefined,
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listTasks(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
view: TaskView,
|
||||
options: TaskQueryOptions = {}
|
||||
): Promise<TaskPageResult> {
|
||||
const page = await fetchTaskPage(client, corpId, view, options);
|
||||
let items = page.items.map(normalizeTask);
|
||||
if (options.staffId) {
|
||||
const target = options.staffId.toLowerCase();
|
||||
items = items.filter((item) => [item.submitter?.id, item.submitter?.code, item.owner?.id, item.owner?.code]
|
||||
.filter(Boolean)
|
||||
.some((value) => String(value).toLowerCase().includes(target)));
|
||||
}
|
||||
return {
|
||||
view,
|
||||
total: page.count,
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 20,
|
||||
items,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user