Compare commits

...
134 Commits
Author SHA1 Message Date
yunyingk 70fbbe22df Merge pull request #95 from yunyingk/release/v0.8.13
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.13
2026-10-04 15:09:14 +08:00
gitea ed2dffb091 chore(release): bump version to v0.8.13 2026-10-04 15:09:03 +08:00
yunyingk 27c465491f Merge pull request #94 from yunyingk/chore/pin-bun-version
chore(release): pin Bun toolchain (setup-bun SHA + bun 1.3.14, packageManager/engines)
2026-10-04 14:49:00 +08:00
yunyingk 91d768afd2 Merge pull request #93 from yunyingk/refactor/commands-directories
refactor(cli): split the five oversized command files into directory form
2026-10-04 14:48:55 +08:00
yunyingk 3b40598ced Merge pull request #92 from yunyingk/chore/repo-root-cleanup
chore(repo): consolidate spec artifacts into specs/ and complete README coverage
2026-10-04 14:48:49 +08:00
gitea 160a8977e6 chore(release): pin Bun toolchain for reproducible, supply-chain-safe releases
- Pin oven-sh/setup-bun to v2.2.0 by full commit SHA instead of the
  mutable v2 tag, and pin bun-version to 1.3.14 instead of latest
- Declare packageManager (bun@1.3.14) and engines (>=1.3.14) in
  package.json so local dev and CI use the same Bun toolchain
2026-10-04 14:21:05 +08:00
gitea 8c6ee6ca89 refactor(cli): split commands/bill.ts into bill/{context,approve,search,flow,related,meta,index}.ts
The five closures that captured corp/client/confirmation state move
into a per-invocation createBillActionContext factory; case bodies
become ctx-taking handlers grouped by concern (approval write actions,
list/get, flow/risk/budget, refs/relations/attachments/download,
schema/link/spec). index.ts keeps the original switch semantics.
No behavior change: tsc clean, 316 tests pass.
2026-10-04 14:18:29 +08:00
gitea 6cb05ebc37 refactor(cli): split commands/platform.ts into platform/{shared,app-info,records,record-actions,index}.ts
Verbatim code moves grouped by concern: app metadata & permissions,
record query + ledger audit, and record write actions (incl. batch
safe edit). No behavior change: tsc clean, 316 tests pass.
2026-10-04 14:14:57 +08:00
gitea c8450b9908 refactor(cli): split commands/update.ts into update/{index,releases}.ts
releases.ts carries the GitHub/Gitea release infrastructure (types,
listing, mirrored download, archive extraction, semver compare);
index.ts keeps handleUpdateCommand and re-exports the previously
public members so update.test.ts stays source-compatible.
Verbatim code moves, no behavior change: tsc clean, 316 tests pass.
2026-10-04 14:12:03 +08:00
gitea 6f1f2623a3 refactor(cli): split commands/workflow.ts into directory form (list/lifecycle/draft/history/job/check/analyze)
Verbatim code moves; drops dead WORKFLOW_STATE_DIR const that was
declared but never read. No behavior change: tsc clean, 316 tests pass.
2026-10-04 14:09:34 +08:00
gitea 52342a9b8e refactor(cli): split commands/corps.ts into directory form mirroring domains layout
Pilot for the command-directory form: 1077-line corps.ts becomes
corps/{index,shared,query,context,link,credentials,probe}.ts with
verbatim code moves. index.ts keeps the dispatch switch plus
re-exports so auth.ts and registry.ts consumers stay source-compatible.

No behavior change: tsc clean, 316 tests pass.
2026-10-04 14:06:25 +08:00
gitea a3b64d8c8d chore(repo): consolidate spec artifacts into specs/ and complete README coverage
- Move generated OpenAPI bundles out of dist/ into committed specs/
  (specs/openapi.json, specs/openapi.raw.json); source YAML tree moves
  openapi/ -> specs/openapi/; schemas/workflow-schema.json joins as
  specs/workflow-schema.json
- Update all generators/consumers: bundle-openapi, generate-raw-openapi,
  check-version-sync, bump-version, export-workflow-schema,
  packaging/embedded-openapi
- Rewrite stale .env.example with current HOSE_* environment variables
- Archive stale repo-local enterprise configs (superseded by
  ~/.config/hose-use/enterprises) out of the repo; root enterprises/
  keeps only the tracked example.json plus an explanatory README
- Add missing directory READMEs: approval/contact/message/task/events
  domains, cli/, http/, packaging/
- Fix stale domain doc links in README.domains.md and
  docs/modules/platform.md
2026-10-04 14:00:03 +08:00
yunyingk 6d532fc719 Merge pull request #91 from yunyingk/refactor/architecture-cleanup
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
refactor(architecture): unify layering, command registry, SQLite persistence, and token caching (v0.8.12)
2026-09-30 09:23:24 +08:00
gitea 0c745fdb0c chore(release): bump version to v0.8.12 2026-09-30 09:22:15 +08:00
gitea fd24e844b0 docs(architecture): update AGENTS.md and README.domains.md with full layering and 14-domain matrix 2026-09-30 00:37:49 +08:00
gitea 88c57558e1 refactor(aipro): modularize 1181-line aipro-cli.ts into src/cli/commands/aipro and reuse shared CLI helpers 2026-09-30 00:35:27 +08:00
gitea fbdfbaa8d3 refactor(cli): introduce declarative CLI command registry and shared runtime helpers 2026-09-30 00:31:30 +08:00
gitea 27c86e052a refactor(core,packaging): relocate embedded assets and binary runtime to src/packaging and enforce core whitelist 2026-09-30 00:29:20 +08:00
gitea 3864f0ffd0 refactor(db,persistence): unify EventStore and WorkflowAlertStore onto core/db SQLite 2026-09-30 00:26:49 +08:00
gitea 5a0c277993 refactor(architecture): eliminate direct domains/*/api imports in CLI entrypoints and add boundary tests 2026-09-30 00:22:36 +08:00
gitea fb11fedb76 docs(architecture): sync core and domain READMEs with refactored modules and layering 2026-09-30 00:14:54 +08:00
gitea c15d622ba2 refactor(errors): unify EkbError hierarchy across domains and structured CLI error classification 2026-09-30 00:13:35 +08:00
gitea 2b220bc5d9 refactor(auth,config): split 2260-line login.ts into focused modules and normalize CorpConfig fields 2026-09-30 00:04:28 +08:00
gitea 2d744d283b perf(http,auth): persist EASO, Unity, and Piper tokens across CLI invocations via token-store 2026-09-29 23:45:38 +08:00
gitea 76f7832522 refactor(mcp): remove deprecated fine-grained MCP tool definitions and simplify server to single CLI gateway 2026-09-29 23:42:12 +08:00
gitea c60d49fb8c fix(cli): prevent boolean flags from swallowing positional args and unify aipro arg parsing 2026-09-29 23:36:18 +08:00
gitea d0af46b445 fix(security,config): enforce 0600 file permissions, dynamic account store path, and HTTP origin protection 2026-09-29 23:34:06 +08:00
yunyingk bd585db889 Merge pull request #90 from yunyingk/feat/workflow-job-and-datalink-enhancements
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(platform,datalink,bill): workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11)
2026-09-29 20:02:06 +08:00
gitea a0ec7f95a7 feat(platform,datalink,bill): add workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11) 2026-09-29 20:00:55 +08:00
yunyingk 2ec08033e0 Merge pull request #89 from yunyingk/feat/openapi-persistent-auth
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(auth): support OpenAPI persistent credentials, auto-refresh, and Web login link generation (v0.8.10)
2026-09-28 16:51:49 +08:00
gitea 96c5a3f242 feat(auth): support OpenAPI persistent credentials, auto-refresh, and Web login link generation (v0.8.10) 2026-09-28 16:50:18 +08:00
yunyingk 1d825269f4 Merge pull request #88 from yunyingk/fix/update-ensure-aipro-symlink
fix(update): ensure hose-aipro symlink exists upon binary update
2026-09-18 12:01:46 +08:00
gitea 3573ef71aa fix(update): automatically ensure hose-aipro symlink exists upon binary update 2026-09-18 12:01:28 +08:00
yunyingk c18ff02386 Merge pull request #87 from yunyingk/feat/update-archive-priority-and-bump
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.9 and prioritize archive updates
2026-09-18 11:44:16 +08:00
gitea 64c0fafcf6 chore(release): bump version to v0.8.9 and prioritize archive updates 2026-09-18 11:43:55 +08:00
yunyingk db2b256fcd Merge pull request #86 from yunyingk/fix/consolidate-config-paths
fix: consolidate config paths and prioritize archive download in install.sh
2026-09-18 11:41:48 +08:00
gitea aa5ec6b6ce fix(install): prioritize compressed archives with raw binary fallback and auto-extraction 2026-09-18 11:41:07 +08:00
gitea 8c444efc85 fix(auth): point account-store and token-store directly to ~/.config/hose-use 2026-09-18 11:22:41 +08:00
yunyingk c72f07f582 Merge pull request #85 from yunyingk/release/v0.8.8
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.8.8
2026-09-17 16:03:07 +08:00
gitea edeb2a56f8 chore(release): bump version to v0.8.8 and update docs/skill 2026-09-17 16:02:48 +08:00
yunyingk 28eab40145 Merge pull request #84 from yunyingk/feat/bill-search-fields
feat(bill): 支持服务端跨字段检索与 --search-fields 参数
2026-09-17 16:00:18 +08:00
gitea bcb77feabb feat(bill): 支持服务端跨字段检索与 --search-fields 参数 2026-09-17 15:59:56 +08:00
yunyingk 7e16a6a312 Merge pull request #83 from yunyingk/refactor/complete-semantic-cleanup
refactor(core): 全量语义化客户端迁移并移除历史兼容桥接层
2026-09-17 15:44:45 +08:00
gitea d0f3d2738a refactor(core): 全量语义化客户端迁移并移除历史兼容桥接层 2026-09-17 15:44:25 +08:00
yunyingk 29ac24248e Merge pull request #82 from yunyingk/refactor/semantic-http-clients
refactor(core): 抽象语义化 HTTP 客户端与统一防爬指纹管理
2026-09-17 15:33:35 +08:00
gitea aa69b50e6e refactor(core): 抽象语义化 HTTP 客户端与统一防爬指纹管理 2026-09-17 15:32:56 +08:00
yunyingk 1322e2eab9 Merge pull request #81 from yunyingk/feat/bill-server-filtering
feat(bill): add server-side filterBy support and clarify status skill rules
2026-09-17 15:26:09 +08:00
gitea 139e50395d feat(bill): expose raw filterBy, select, distinct, and join in search API and CLI 2026-09-17 15:08:38 +08:00
gitea ca713cfafc feat(bill): add server-side filterBy support and clarify status skill rules 2026-09-17 14:58:02 +08:00
yunyingk 4b75132b43 feat(agents): add .agents modular rules with manual trigger (keep .agents, omit .agent) (#80)
- Match seal-use repository layout with .agents/rules and skills.json
- Ensure no .agent singular directory or symlink exists
- Set trigger: 'manual' on all rules to prevent automatic prompt injection
- Track .agents/ in git by updating .gitignore
2026-09-17 10:20:10 +08:00
yunyingk 240ec92931 Revert "feat(agents): add .agents modular rules with manual trigger and .agent symlink (#78)" (#79)
This reverts commit 1855815aeb.
2026-09-17 10:17:40 +08:00
yunyingk 1855815aeb feat(agents): add .agents modular rules with manual trigger and .agent symlink (#78)
- Match seal-use repository layout with .agents/rules and skills.json
- Create symlink .agent -> .agents for backward and naming compatibility
- Configure trigger: 'manual' on all rules to avoid prompt bloat
- Add production-safety.md, tenant-and-credential.md, cli-protocol.md, testing-and-dev-hygiene.md, typescript-style.md
- Remove .agents/ ignore from .gitignore to track rules in git
2026-09-17 10:13:55 +08:00
yunyingk dd647b65a6 Merge pull request #77 from yunyingk/fix/sqlite-cache-migration-and-bill-mine
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix: sqlite cache migration, bill timeout protection with --mine, and add-link overwrite UX (v0.8.7)
2026-09-17 10:06:30 +08:00
gitea 43595e2410 fix: sqlite cache migration, bill timeout protection with --mine, and add-link overwrite UX (v0.8.7) 2026-09-17 10:06:08 +08:00
yunyingk b08b99c45e Merge pull request #76 from yunyingk/revert/ekuaibao-child-skills-verbatim
revert(skill): 子技能按原样内嵌(去掉端点参数化与上级标注)
2026-09-15 16:31:34 +08:00
gitea 7e4f218313 revert(skill): 子技能保持原样,去掉端点参数化与上级标注
按项目所有者要求,multi/ 下两个子技能按原始内容原样内嵌:

- ekuaibao-nodes/SKILL.md:恢复原开通服务地址,去掉 HOSE_WORKFLOW_NODE_URL
  参数化与相关提示,域名判断示例恢复原文
- ekuaibao-mvel/SKILL.md:移除「本文件是下级技能」标注行
- 结构、内嵌清单(18)、测试均不变
2026-09-15 16:30:55 +08:00
yunyingk 05569243ec Merge pull request #75 from yunyingk/feat/ekuaibao-suite-and-mvel-skill
feat(skill): 合思系列统一入口 + MVEL / 节点开通子技能
2026-09-15 16:23:32 +08:00
gitea ebed61d6b4 feat(skill): 合思系列统一入口,新增 MVEL 与节点开通子技能
- skills/hose-use 收敛为合思/易快报系列唯一入口,新增「本套件结构」路由表
- 新增子技能 multi/ekuaibao-mvel:工作流 MVEL 代码节点脚本生成与排错
- 新增子技能 multi/ekuaibao-nodes:工作流节点批量开通(自 curl 提取 token/corpId/baseUrl)
- 开通服务地址改为 HOSE_WORKFLOW_NODE_URL 环境变量,不再硬编码实例
- embedded-skill 内嵌清单 14 -> 18,installer 递归保留 multi/ 层级;测试同步更新
2026-09-15 16:21:15 +08:00
yunyingk 90e7ac22bb Merge pull request #74 from yunyingk/feat/dev-version-visibility
feat: make development builds visibly identifiable
2026-09-13 14:25:35 +08:00
gitea 2ed9bf0236 feat: make development builds visibly identifiable 2026-09-13 14:24:27 +08:00
yunyingk 0554f41d12 Merge pull request #73 from yunyingk/codex/release-v0.8.6
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.8.6
2026-09-13 13:43:51 +08:00
gitea 8e4535a812 chore(release): bump version to v0.8.6 2026-09-13 13:42:56 +08:00
yunyingk 68c7541cf6 Merge pull request #72 from yunyingk/fix/dev-check-symlink-awareness
fix: recognize canonical Skill symlinks
2026-09-12 23:36:00 +08:00
gitea 134ebf0d2e fix: treat canonical skill symlinks as healthy 2026-09-12 23:34:50 +08:00
yunyingk 5d441d9e90 Merge pull request #71 from yunyingk/feat/dev-hygiene-check
feat: 增加开发环境卫生检查与安全清理
2026-09-12 23:29:20 +08:00
gitea 3db5907357 feat: add development hygiene checks and cleanup 2026-09-12 23:26:08 +08:00
yunyingk b6551497d7 Merge pull request #70 from yunyingk/fix/canonical-skill-install
fix: 统一 Agent Skill 全局安装目录
2026-09-12 23:13:02 +08:00
gitea 33db72f863 fix: install skill only in canonical global directory 2026-09-12 23:02:25 +08:00
gitea f26eae7b08 fix: make dry-run next steps executable 2026-09-11 17:41:58 +08:00
gitea 1571c524c1 feat: protect all CLI state mutations 2026-09-11 17:40:47 +08:00
gitea 3e072b490e feat: install development build globally 2026-09-11 17:35:29 +08:00
gitea 7cfb68e434 feat: migrate legacy hose configuration paths 2026-09-11 17:24:08 +08:00
gitea d15fa65517 feat: sync release version plugin and OpenAPI artifacts 2026-09-11 17:21:41 +08:00
gitea 34983e1c07 feat: add layered CLI help registry 2026-09-11 17:18:39 +08:00
gitea a5c0146c8d feat: add semantic CLI exit codes 2026-09-11 17:11:51 +08:00
gitea 45eb83a609 feat: unify CLI dry-run and write confirmation 2026-09-11 16:53:14 +08:00
gitea 639aaa9271 feat: embed keys and store skill guidance 2026-09-11 16:35:21 +08:00
yunyingk cd7bb44f04 Merge pull request #69 from yunyingk/codex/release-v0.8.5
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.5 workflow lifecycle and monitoring
2026-09-09 18:43:03 +08:00
gitea 0cdd62161f feat: add workflow lifecycle controls and monitoring 2026-09-09 18:41:36 +08:00
yunyingk 9f9f3abe22 Merge pull request #68 from yunyingk/feat/feetype-domain
feat(feetype): add fee type domain CRUD CLI commands and specifications
2026-09-09 16:25:24 +08:00
gitea fb700a4c86 feat(feetype): add fee type domain CRUD CLI commands and specifications 2026-09-09 16:25:03 +08:00
yunyingk 0be629778f Merge pull request #67 from yunyingk/fix/clean-platform-test-spies
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix(test): clean up mock spies in platform.test.ts after each test
2026-09-09 16:03:08 +08:00
gitea a415bf38c3 fix(test): clean up mock spies in platform.test.ts after each test 2026-09-09 16:02:55 +08:00
yunyingk d447426d48 Merge pull request #66 from yunyingk/release/v0.8.4
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.4
2026-09-09 16:00:43 +08:00
gitea 03d2337e13 chore(release): bump version to v0.8.4 2026-09-09 16:00:26 +08:00
yunyingk 6f49bfc8a4 Merge pull request #65 from yunyingk/feat/datalink-record-actions
feat(datalink): record actions (get, toggle, edit, recompute) and active display fix
2026-09-09 15:55:34 +08:00
gitea 97b67c71da feat(datalink): add record get, toggle, edit, and recompute actions and fix active display 2026-09-09 15:55:12 +08:00
yunyingk 09c4e7df4a Merge pull request #64 from yunyingk/fix/align-app-platform-terminology-and-skill-version
fix(skill): 对齐应用管理与自建应用术语规范并同步 skill 至 v0.8.3
2026-09-09 15:21:44 +08:00
gitea 69c6396d38 fix(skill): align app and platform terminology and sync skill to v0.8.3 2026-09-09 15:21:18 +08:00
yunyingk 3c680d0ed3 Merge pull request #63 from yunyingk/feat/workbench-apps-and-menu
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat: add workbench apps, desktop menu domain, and bump to v0.8.3
2026-09-09 15:07:03 +08:00
gitea 215bc5e2a1 feat(app): add workbench apps, desktop menu domain and bump to v0.8.3 2026-09-09 15:06:34 +08:00
yunyingk 3d0bc2ebff Merge pull request #62 from yunyingk/feat/corps-search-and-aliases
feat(cli): add corps search command and intuitive aliases
2026-09-09 15:01:03 +08:00
gitea 1cd8901f7a feat(cli): add corps search command and intuitive aliases
- Implement hose-use corps search <keyword> with case-insensitive fuzzy matching across id, name, corpId, staffId, staffName, and accountId
- Format terminal table output with matched cell brackets, hit labels, active corp markers, and friendly no-match fallback
- Support --json structured output conforming to CliResult specification
- Add intuitive aliases for frequently guessed commands: auth list -> auth accounts, corps find -> corps search, config show -> config paths
- Enhance CorpSummary and CorpContext with corpId, staffName, and getAllCorps
- Add comprehensive unit tests in corps.test.ts, auth.test.ts, and config.test.ts
2026-09-09 14:42:58 +08:00
yunyingk 8efce4342a Merge pull request #61 from yunyingk/feat/datalink-business-object-query
feat: 通用 DataLink 应用对象与记录查询
2026-09-09 14:05:24 +08:00
gitea 893fc47ac6 feat(datalink): add generic app object and record queries 2026-09-09 13:57:45 +08:00
yunyingk 2502a49fb9 Merge pull request #60 from yunyingk/release/v0.8.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.1
2026-09-09 09:24:54 +08:00
gitea 212371eb03 chore(release): bump version to v0.8.1 2026-09-09 09:23:47 +08:00
yunyingk e852dbfd47 Merge pull request #59 from yunyingk/feat/store-and-openapi-keys
feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力
2026-09-09 09:23:02 +08:00
gitea 0c953df30e feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力 2026-09-08 16:59:57 +08:00
yunyingk 9a2d4529f5 Merge pull request #58 from yunyingk/release/v0.8.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.0
2026-09-08 15:53:54 +08:00
gitea 3937d3799b chore(release): bump version to v0.8.0 2026-09-08 15:53:41 +08:00
yunyingk bcf8ac0de6 Merge pull request #57 from yunyingk/refactor_db_cache_cleanup
refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
2026-09-08 15:49:57 +08:00
gitea 3a15b064fe refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
2026-09-08 15:49:27 +08:00
gitea 00cbf039eb chore(release): bump version to v0.7.5
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-08 14:04:03 +08:00
yunyingk a2eb04c4c1 Merge pull request #56 from yunyingk/codex/issue-55-auth-bill
fix(auth): guard temporary token refresh and translate bill flow
2026-09-08 12:11:35 +08:00
gitea 3f015d8e22 fix(auth): guard temporary token refresh and translate bill flow 2026-09-08 12:08:12 +08:00
yunyingk 2b467dc076 Merge pull request #54 from yunyingk/feat/global-config-test-dir-and-remove-cwd-enterprises
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(config): align with seal-use to remove cwd enterprises and support testEnterprisesDir (v0.7.4)
2026-09-07 16:26:06 +08:00
gitea a5b5f1918e feat(config): align with seal-use to remove cwd enterprises and support testEnterprisesDir (v0.7.4) 2026-09-07 16:25:45 +08:00
yunyingk b72b5d7f71 Merge pull request #53 from yunyingk/feat/translator-full-fidelity-invoice-and-datalink
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(bill): high-fidelity bill translation with invoice validation and datalink cards (v0.7.3)
2026-09-07 15:48:15 +08:00
gitea a8e32cff32 feat(bill): support full invoice validation details, datalink cards, and department paths (v0.7.3) 2026-09-07 15:47:44 +08:00
yunyingk 5e06429d6c Merge pull request #52 from yunyingk/feat/translator-modular-and-inline-attachments
feat(bill): refactor translator to modular functions and preserve inline positions
2026-09-07 15:20:54 +08:00
gitea 3777e81ee7 feat(bill): refactor translator to modular functions and preserve inline positions for attachments and invoices 2026-09-07 15:20:27 +08:00
yunyingk 0ee5031dc8 Merge pull request #51 from yunyingk/feat/corps-add-link-and-multi-cluster
feat: 支持协助链接秒级导入 (corps add-link) 与多集群 (wx2等) 动态换票
2026-09-07 14:45:03 +08:00
gitea 2bf8d22810 feat: 支持协助链接秒级导入 (corps add-link) 与多集群 (wx2等) 动态鉴权换票 2026-09-07 14:44:37 +08:00
yunyingk f2b0f15a6e Merge pull request #50 from yunyingk/chore/embed-approval-skill-reference
chore(skill): embed references/approval.md into embedded skill assets
2026-09-07 14:26:20 +08:00
gitea 065ba42bfe chore(skill): embed references/approval.md into embedded skill assets 2026-09-07 14:26:06 +08:00
yunyingk 6260b824a0 Merge pull request #49 from yunyingk/feat/context-introspection-and-aipro-status
feat: 全局运行上下文一键自省与 hose-aipro status 支持 (免读源码构建环境)
2026-09-07 14:17:59 +08:00
gitea 7efa83ff30 feat(cli): add context introspection command and hose-aipro status for zero-source-reading AX 2026-09-07 14:17:35 +08:00
yunyingk 1b5ae12254 Merge pull request #48 from yunyingk/feat/configurable-approval-gateway
feat(approval): introduce configurable gateway policy script and enforce strict reject/approve guardrails
2026-09-07 14:04:52 +08:00
gitea 27660bed92 feat(approval): introduce configurable gateway policy script and enforce strict reject/approve guardrails 2026-09-07 14:03:22 +08:00
yunyingk 01a3263423 Merge pull request #47 from yunyingk/fix/update-download-timeout
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(aipro): approval lifecycle, gateway guardrails, update timeouts, and bump to v0.7.2
2026-09-07 00:02:06 +08:00
gitea 052fa77df6 chore(release): bump version to v0.7.2 2026-09-07 00:01:41 +08:00
gitea ca00e9a2cc feat(aipro): implement bind, review, decide with gateway guardrail and <150 chars opinion validation 2026-09-06 23:54:36 +08:00
gitea 7e39d95b36 feat(aipro): translate JSON output field names to Chinese in scopes and rules commands 2026-09-06 23:32:25 +08:00
gitea b0149ed32d feat(aipro): introduce init session with 6-char short runId and 6h TTL, support --run audit logging in scopes, translate, rules and logs 2026-09-06 23:23:57 +08:00
gitea a16d429d44 feat(aipro): add standalone document field translator and translate command 2026-09-06 22:58:34 +08:00
gitea 2afde446d2 feat(aipro): require wrapped array for rules input and flatten output by code 2026-09-06 22:46:37 +08:00
gitea 950dd6d8fa feat(aipro): add multi-index rules command outputting matched scopes and rules 2026-09-06 22:44:00 +08:00
gitea 8d203fc230 feat(aipro): format scopes command output as pure json with index and scope 2026-09-06 22:39:45 +08:00
gitea 62025cb6f1 feat(aipro): add scopes index command and decouple points from bills 2026-09-06 22:36:58 +08:00
gitea 2f8bcb90c9 refactor(cli): purge short hose alias and standardize on hose-use across docs, scripts, and prompts 2026-09-06 22:26:04 +08:00
gitea 304a8c0d98 fix(update): relax binary download timeout to 600s and pass auth token for github assets 2026-09-06 22:20:47 +08:00
yunyingk 86b88d8785 Merge pull request #46 from yunyingk/fix/approval-corp-isolation-and-release-packaging
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix(approval): isolate runs by corp, handle execution error, bundle hose-aipro alias, and bump to v0.7.1
2026-09-06 21:58:15 +08:00
gitea 9fa4cfe38f fix(approval): isolate runs by corp, handle execution error, bundle hose-aipro alias, and bump to v0.7.1 2026-09-06 21:57:53 +08:00
248 changed files with 27406 additions and 4405 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
# Agent Customizations & Modular Rules Policy
This directory (`.agents/`) maintains modular configuration, skills, and guidelines for AI coding assistants working in the `hose-use` repository.
---
## 1. Directory Structure
```
.agents/
├── README.md # This document: architecture & trigger policy
├── skills.json # Declarative skill path and exclusion filters
└── rules/ # Modular, domain-specific rule definitions (trigger: "manual")
├── production-safety.md # 生产环境安全红线、免读源码与写操作防护原则
├── cli-protocol.md # CLI stdout/stderr stream contract & exit codes
├── tenant-and-credential.md # 多租户凭据管理、协助链接与单据检索最佳实践
├── testing-and-dev-hygiene.md # 单元测试规范、非交互环境防护与发布流程
└── typescript-style.md # ESM, explicit .js imports, and TypeScript styles
```
---
## 2. Trigger Strategy & Context Budget Management
### Why `trigger: "manual"`?
In Antigravity (`agy`), rule files located in `.agents/rules/*.md` support YAML frontmatter:
```yaml
---
description: "..."
globs: "src/..."
trigger: "manual"
---
```
1. **Token Economy**: If set to `trigger: "always_on"`, every turn of the conversation unconditionally injects all rules into the system prompt (`<user_rules>`), consuming substantial context tokens on every request regardless of task relevance.
2. **On-Demand Activation**: Setting `trigger: "manual"` prevents automatic background injection into the prompt budget. The rules remain available on-demand when explicitly referenced or requested by the user or agent.
3. **Cross-Agent Neutrality**: Non-agy agents (e.g. OpenAI Codex, Claude Code, Cursor, generic LLMs) do not recognize `agy`'s private frontmatter triggers. Storing modular guidelines as plain Markdown with a manual trigger ensures they function as clean, standalone reference docs that any agent can read on demand via standard file reading tools without unexpected prompt pollution.
---
## 3. Modular Rules Inventory
| Rule File | Domain / Scope | Key Responsibilities |
| :--- | :--- | :--- |
| [`rules/production-safety.md`](./rules/production-safety.md) | 全局行为 | **生产安全最高红线**、严禁私自翻阅源码配置 (Zero Source-Reading)、两阶段确认写保护。 |
| [`rules/tenant-and-credential.md`](./rules/tenant-and-credential.md) | 凭证与单据 | 同等凭据原则、协助链接导入与 `--overwrite` 保护、个人单据 (`task submitted` / `bill list --mine`) 快速通道。 |
| [`rules/cli-protocol.md`](./rules/cli-protocol.md) | `src/cli/**/*.ts` | 严格 `stdout` JSON vs `stderr` 诊断输出契约、200KB 大报文防爆拦截、退出码规范。 |
| [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md) | 测试与流程 | `bun:test` 规范、测试环境禁止阻塞交互输入、`bun run check` + `bun test` 门禁与发布更新规范。 |
| [`rules/typescript-style.md`](./rules/typescript-style.md) | `src/**/*.ts` | ES Modules、强制携带 `.js` 后缀、Zod 运行时校验与代码规范。 |
---
## 4. Usage Instructions for AI Agents
- **Production Operations**: Always consult [`rules/production-safety.md`](./rules/production-safety.md) and [`rules/tenant-and-credential.md`](./rules/tenant-and-credential.md) before interacting with configured enterprise tenants.
- **CLI Development**: When adding or refactoring CLI commands under `src/cli/`, consult [`rules/cli-protocol.md`](./rules/cli-protocol.md).
- **Writing Tests**: When creating or modifying tests, consult [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md).
- **TypeScript & Modules**: When adding new TypeScript files or resolving local imports, refer to [`rules/typescript-style.md`](./rules/typescript-style.md).
+26
View File
@@ -0,0 +1,26 @@
---
description: "CLI stdout/stderr stream contract, volume explosion protection, and exit codes for hose-use commands"
globs: "src/cli/**/*.ts"
trigger: "manual"
---
# CLI 输出流协议与退出码规范
在实现或重构 `src/cli/` 下的命令行交互时:
1. **机器解析通道 (`stdout`)**:
- 数据类命令在 `--json` 模式下,`stdout` 必须仅输出纯净、可解析的 JSON 结构体;
- 严禁将调试日志、进度动画、交互式提示语输出到 `stdout`,确保下游脚本和 Agent Harness 能够直接可靠解析。
2. **诊断与引导通道 (`stderr`)**:
- 运行时警告、网络诊断信息以及下一步操作引导(如 `下一步: hose-use ...`)统一写入 `stderr`。
3. **大报文体积保护(Volume Explosion Protection)**:
- 默认受 200KB 体积防爆限制,防止海量单据明细一次性撑爆上下文;
- 提示并支持通过 `--limit` 分页、`--output-file / -o` 直接落盘至本地文件,或通过 `--mine` 筛选关键子集。
4. **退出码规范**:
- 正常执行成功退出码为 `0`;
- 语法错误、参数缺失、上游 API 报错退出码为非 0(如 `1`);
- 写操作未确认拦截退出码为 `10`(`MutationConfirmationRequired`);
- 不要在领域代码深处直接调用 `process.exit()`,应抛出带有结构化语义的错误,由外层统一捕获和分配退出码。
+27
View File
@@ -0,0 +1,27 @@
---
description: "生产环境安全红线、免读源码(Zero Source-Reading)与写操作防护原则"
globs: "**/*"
trigger: "manual"
---
# 生产环境安全与行为红线
在操作、排错或开发 `hose-use` 时,必须严格恪守以下生产安全与操作红线:
1. **生产环境安全第一(Production Safety First)**:
- 企业租户(如“转转正式”、“钰泰半导体”等)多为生产真实业务环境,**严禁**未经用户明确确认擅自执行写操作(包括但不限于单据同意、驳回、转交、前/后加签、费用类型修改/停用、数据记录编辑等)。
- 单据检索与排障默认仅使用只读查询(如 `probe`、`task submitted`、`bill list --mine`、`bill get`、`bill flow` 等)。
2. **零源码翻阅自省(Zero Source-Reading)**:
- **严禁翻阅用户的本地配置文件、凭证快照(如 `~/.config/hose-use/enterprises/*.json`、`seal_tokens.json`)、SQLite 数据库或源码目录来探查企业和员工信息**。
- 探查配置与上下文必须统一使用标准 CLI 命令(如 `hose-use context`、`hose-use corps list`、`hose-use probe`)。
3. **两阶段确认与写操作防护**:
- 所有写操作必须严格遵循两阶段确认机制:
- 第一阶段:使用 `--dry-run` 预览操作目标与变更明细;
- 第二阶段:经用户明确确认后,追加 `--yes`(或 `--confirm`)执行写入。
- 导入链接若检测到目标企业已存在,必须在第一阶段提示中直接给出带有 `--overwrite` 的命令,杜绝二次报错阻断。
4. **敏感信息与凭证脱敏**:
- 严禁将明文密码、`appSecurity`、完整 `accessToken`、会话 Cookie 或第三方授权直链打印到公共日志、提交到代码仓库或在回复中裸露传播。
- CLI 默认输出必须进行严格掩码脱敏。
+24
View File
@@ -0,0 +1,24 @@
---
description: "多租户凭据管理、合思免密/协助链接导入与个人单据检索最佳实践"
globs: "src/{domains,core,cli}/**/*.{ts,md}"
trigger: "manual"
---
# 租户凭据与业务操作最佳实践
1. **同等凭据原则(Equal Credential Scope Principle)**:
- 合思第三方免密/协助链接 (`https://.../web/thirdparty.html?...`) 与在合思管理员后台抓取的 cURL 在凭据范围上等价,均携带完整的 Web 前台会话权限(`accessToken` / `ekbCorpId`)。
- 面对协助链接或 cURL 时,可通过 `corps add-link <url>` 直接导入或更新租户。
2. **协助链接导入与覆盖(add-link)**:
- 导入协助链接时,系统会自动预解析 `ekbCorpId` 与 JWT Session。
- 若本地已存在该企业配置,必须显式追加 `--overwrite` 参数(如 `hose-use corps add-link <url> --overwrite --yes`)。
3. **单据查询的业务分流与避坑**:
- **查“我的单据” / 当前员工发起的单据**:
- 优先使用 `hose-use task submitted` 或 `hose-use bill list --mine`;
- 响应速度为秒级,包含完整表单明细、提交时间、审批状态与金额。
- **查“待办任务”**:
- 使用 `hose-use task todo`,支持分页与节点状态查看。
- **全局发票大盘(`bill list`)**:
- 底层调用全量账表接口 `/api/v2/invoice/search`;在像转转这样的大企业或发票量级巨大的租户中耗时较长,避免在无过滤条件时频繁调用;遇超时应引导使用轻量化的 `task submitted` / `bill list --mine`。
+31
View File
@@ -0,0 +1,31 @@
---
description: "测试套件规范、非交互环境防护与版本发布更新全流程"
globs: "{src,scripts}/**/*.test.ts"
trigger: "manual"
---
# 测试与开发发布流程规范
1. **测试框架与单测编写**:
- 统一采用 `bun:test`(`describe`, `test`, `it`, `expect`);
- 测试文件与被测模块同级存放,命名为 `*.test.ts`;
- 测试若修改了 `process.env` 或全局状态,必须在 `afterEach()` 中完成自愈清理。
2. **非交互测试环境防挂起**:
- 包含终端输入提示(`prompt()` / `readline`)的命令逻辑中,必须加入 `process.env.NODE_ENV === "test"` 或 `process.env.CI` 保护,在单测环境下直接抛出确认错误,绝对禁止阻塞等待 stdin。
3. **提交前双重门禁验收**:
- 任何代码改动在提交前必须 100% 通过以下检查:
```bash
bun run check # tsc --noEmit 静态类型检查零错误
bun test # 完整测试套件全部通过
```
4. **版本发布与全局更新标准流程**:
- 若涉及功能增强、Bug 修复或结构变更:
1. 运行 `bun run bump patch`(或 minor)同步各文件版本号并重建 bundles;
2. 运行 `bun run check:version` 确认版本严格一致;
3. 创建特性分支并提交 PR,合入 `main` 主分支;
4. 双远端同步:推送 `main` 分支至 GitHub (`origin`) 与内部镜像 (`home`);
5. 打正式发布 Tag(如 `v0.8.7`)并推送到双远端;
6. 运行 `bun run dev:override` 重新构建本机全局二进制(`/opt/homebrew/bin/hose-use`)并同步 Agent Skill(`~/.agents/skills/hose-use`)。
+31
View File
@@ -0,0 +1,31 @@
---
description: "TypeScript and ESM coding conventions for hose-use codebase"
globs: "src/**/*.ts"
trigger: "manual"
---
# TypeScript & ESM Conventions
When modifying or adding TypeScript files in `src/`:
1. **Module System & Import Extensions**:
- Use ES modules exclusively (`"type": "module"` in `package.json`).
- Local file imports MUST include explicit `.js` extensions (e.g. `import { getGlobalDb } from "../db/connection.js"`).
- Do NOT omit the `.js` extension, or runtime Node/Bun ESM resolution will fail.
2. **Validation & Typing**:
- Validate external inputs, environment variables, and external HTTP/JSON responses using Zod schemas or strictly typed models.
- Avoid `any`. Prefer precise domain types defined in `src/domains/*/types.ts` or `src/types.ts`.
- Never suppress type errors with `// @ts-ignore`; resolve type discrepancies cleanly.
3. **Code Style & Formatting**:
- 2-space indentation.
- Double quotes (`"`).
- `camelCase` for functions and variables, `PascalCase` for classes, types, and interfaces.
- Kebab-case filenames (e.g. `query-options.ts`, `task-service.ts`).
4. **Architecture & Separation of Concerns**:
- `src/core/`: Database (SQLite), HTTP client factory, encryption, global configuration, logger.
- `src/domains/`: Domain services, models, and business logic (e.g. `bill`, `corps`, `task`, `workflow`, `key-center`).
- `src/cli/`: Command-line definitions, option parsing, user feedback, table rendering, exit handling.
- Keep domain services independent of CLI formatting.
+16
View File
@@ -0,0 +1,16 @@
{
"entries": [
{
"path": "~/.agents/skills",
"exclude": [
"^\\..*",
".*-(deprecated|draft|backup|bak|old|test|tmp)$",
"^lark.*",
"^dingtalk.*",
"^dws.*",
"^seal.*",
"^yingqing.*"
]
}
]
}
+20 -7
View File
@@ -1,10 +1,23 @@
# EKB MCP 配置示例
# hose-use 环境变量示例(全部可选,不设置即使用默认值)
# 企业配置目录(默认 ./enterprises)
# EKB_CONFIG_DIR=./enterprises
# 企业配置目录覆盖(默认 ~/.config/hose-use/enterprises,目录权限 0700)
# HOSE_ENTERPRISES_DIR=~/.config/hose-use/enterprises
# Token 缓存目录(默认 ~/.cache/ekb-mcp)
# EKB_TOKEN_CACHE_DIR=~/.cache/ekb-mcp
# 全局配置文件覆盖(默认 ~/.config/hose-use/config.json)
# HOSE_CONFIG_FILE=~/.config/hose-use/config.json
# 默认 API 基础 URL
# EKB_BASE_URL=https://app.ekuaibao.com
# 账号与 Token 缓存文件覆盖(默认位于 ~/.config/hose-use/,文件权限 0600)
# HOSE_ACCOUNTS_FILE=~/.config/hose-use/accounts.json
# HOSE_TOKENS_FILE=~/.config/hose-use/tokens.json
# 本地状态目录(审批引擎 / Token 缓存 / 守护进程状态,默认 ~/.config/hose-use)
# HOSE_STATE_DIR=~/.config/hose-use
# 本地 HTTP Daemon(默认 127.0.0.1,建议保持回环地址)
# HOST=127.0.0.1
# PORT=8888
# HOSE_HTTP_TOKEN=<访问令牌>
# HOSE_HTTP_CORS_ORIGIN=http://localhost:7788
# MCP Server 总开关(默认关闭)
# HOSE_USE_MCP_ENABLED=true
+24 -9
View File
@@ -18,9 +18,9 @@ jobs:
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
bun-version: 1.3.14
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -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:
@@ -98,7 +113,7 @@ jobs:
local filename
filename=$(basename "$file")
echo " [start] Uploading ${filename} to Gitea..."
RESP=$(curl -s -m 120 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}")
STATUS=$(echo "$RESP" | tail -n 1)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.0",
"version": "0.8.13",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+42 -33
View File
@@ -4,37 +4,44 @@
## 项目定位
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力):
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 与本地 HTTP 网关适配能力):
- **CLI 工具 (`hose-use` / `hose`)**:面向运维/实施/开发者的高性能交互与自动化命令行
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力
- **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力)
- **Agent Skill (`skills/hose-use`)**:内嵌 AI 智能体技能标准定义(支持 `hose-use skill install` 一键分发)
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者与 AI Agent 的高性能交互与确定性审批命令行
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务编排、API 传输、SQLite 持久化与换票能力
- **MCP Server (`src/server.ts`)**:极简核心单工具网关(`hose_cli` -> `runCli`)
- **本地 HTTP Daemon (`src/http/`)**:常驻 HTTP API 网关与交互式 OpenAPI 文档服务
- **构建与分发内嵌层 (`src/packaging/`)**:OpenAPI 规范与 Agent Skill (`skills/hose-use`) 内嵌分发、二进制运行态自省
## 架构总览
```text
CLI (src/cli.ts) / MCP (src/server.ts)
│ │
└──────────┬─────────┘
▼
domains/ (业务编排与平台引擎)
│
▼
core/ (认证、配置与 HTTP 基础设施)
├── auth/ Token 登录、换票与缓存
├── config/ 多账号与企业配置管理
└── http/ HTTP 客户端工厂
CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/http/)
│ │ │ │
└─────────────────────┴───────────┬───────────┴───────────────────┘
▼
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
│
▼
domains/ (14 个业务子域:编排 tools/services + 传输 api)
│
▼
core/ (严格基础设施白名单)
├── auth/ Token 登录、双通道续期、多账号与跨进程 Token 缓存
├── config/ 多账号与企业配置管理(0600 权限与字段归一化)
├── http/ 语义化 HTTP 客户端工厂(Session / OpenAPI / Unity / Piper)
├── cache/ L1 内存 + L2 SQLite 多级协同缓存
├── db/ 统一 SQLite 连接单例与结构化版本迁移 (migrations)
└── errors.ts 统一异常语义体系 (EkbError 子类)
```
核心原则:
- `server.ts` 只做 MCP 协议适配(tools 注册、参数解析、结果序列化)
- 业务编排统一放在 `domains/*/tools.ts`
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验
- `core/auth/` 负责各子域的 Token 获取与刷新
- `core/config/` 负责本地认证配置读写
- `core/errors.ts` 负责统一异常语义
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
- 所有本地 SQLite 持久化(审批引擎、多级缓存、事件轮询去重、工作流错误指纹)统一收敛至 `core/db/` 并通过版本迁移管理
## 文档索引
@@ -52,35 +59,37 @@ CLI (src/cli.ts) / MCP (src/server.ts)
新增或调整功能时,优先遵循下面这条链路:
1. 先明确 `domains/` 的业务边界
2. 再实现 `core/auth/` 或复用现有认证层
3. 再接入 `server.ts` 注册 MCP tools
2. 再实现 `core/auth/` 或复用现有认证与 `core/db/` 基础设施
3. 再接入 `src/cli/commands/*` 并在 `src/cli/registry.ts` 注册
4. 最后更新对应层级文档,而不是把细节补到根目录
同步更新顺序:
1. `domains/*/api.ts` — 传输层
2. `domains/*/tools.ts` — 业务层
3. `server.ts` — 注册 tools
2. `domains/*/tools.ts` / `services.ts` — 业务编排层
3. `cli/commands/*` & `cli/registry.ts` — CLI 命令层
4. 对应目录下的 `README*.md`
5. 只有在总纲真的变化时,才更新本文件
## 分层导入约束
## 分层导入约束(由 `src/cli/architecture-boundaries.test.ts` 自动化强制卡点)
以下导入关系严格禁止:
| 禁止方向 | 说明 |
|---|---|
| `server.ts -> domains/*/api.ts` | Server 不得直接调用 API 层 |
| `(cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts) -> domains/*/api.ts` | 任何入口层不得绕过 `tools.ts`/`services.ts` 直接调用 API 传输层 |
| `domains/** -> (cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | 域层必须保持纯 SDK 零 UI/入口绑定 |
| `core/** -> (domains/** \| cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | Core 基础设施层严禁向上反向依赖业务域或入口层 |
正确路径:
- `server.ts -> domains/*/tools.ts -> domains/*/api.ts -> core/http/*`
- `domains/*/tools.ts -> core/auth/*`
- `entrypoints -> cli/registry.ts -> cli/commands/* -> domains/*/(tools|services).ts -> domains/*/api.ts -> core/http/*`
- `domains/*/(tools|services).ts -> core/{auth,cache,config,db,errors,http}`
## 异常规则
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`)
- `server.ts` 统一负责 MCP error 映射
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`:`NotLoggedInError`, `AuthenticationError`, `PermissionError`, `NotFoundError`, `ValidationError`, `BusinessError`, `EkbApiError`)
- `src/cli/errors.ts` 统一按 `EkbError` 子类与状态码映射 CLI 退出码与下一步恢复建议
- tools 文件里不要重复做局部异常体系
## 文档规则
@@ -100,7 +109,7 @@ CLI (src/cli.ts) / MCP (src/server.ts)
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>`
- 维护优化:`chore/<task-name>`、`refactor/<task-name>` 或 `fix/<issue-name>`
3. **Pull Request 提交流程**:
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
- 推送分支至远端:`git push origin <branch>`;
+31 -5
View File
@@ -1,4 +1,4 @@
# hose-use (v0.7.0)
# hose-use (v0.8.13)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -17,6 +17,19 @@ bun install
bun run cli <command>
```
### 方式三:将当前工作区安装为全局开发版
开发过程中需要让 PATH 中的 `hose-use` 立即使用当前源码时:
```bash
bun run dev:override
hose-use version
```
该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。开发构建会把 Git 信息编译进版本,例如 `hose-use v0.8.6-dev.1+gabc1234 [DEV BUILD]`,不会再与正式版混淆;`hose-use version --json` 还会返回 `channel`、`isRelease` 和 `git` 元数据。只预览动作可运行 `bun run dev:override -- --dry-run`。
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
---
### CLI 常用命令速查 (`hose-use`)
@@ -29,6 +42,7 @@ hose-use auth refresh # 批量刷新账号名下全部
# 2. 多企业租户管理
hose-use corps list # 列出名下所有已配置企业
hose-use corps search <关键词> # 模糊搜索已保存的企业与员工 (别名: corps find)
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
@@ -38,15 +52,26 @@ hose-use config paths # 查看多级企业目录发现
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
# 4. 平台与工作流管理 (跨自建应用聚合)
# 4. 工作台应用、菜单与工作流管理 (跨自建应用聚合)
hose-use app list # 查看工作台应用管理列表 (含套件/制度/模板/自建)
hose-use app get <应用ID|名称> # 查看具体应用详情与 Web 直达路由
hose-use menu list # 查看桌面端全站一级主导航与模块列表
hose-use workflow list # 汇总查看全部工作流列表
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use workflow toggle <pipelineId> --state=1 --yes # 启用/停用工作流
hose-use workflow save <pipelineId> --file=workflow.json --yes # 按完整快照保存草稿
hose-use workflow patch <pipelineId> --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
hose-use workflow history <pipelineId> # 查看服务端版本快照历史
hose-use workflow logs <pipelineId> --state=FAILED # 查看工作流运行错误日志
hose-use workflow check --json --fail-on-alert # 检查错误管道并按错误计数去重提醒
hose-use workflow publish <pipelineId> --yes # 保存后的发布/启用
hose-use platform list # 查看企业下所有启用的自建应用
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
hose-use bill list --keyword=打车 --search-fields=name,form # 跨字段复合检索单据名称与表单明细
hose-use bill list --since=7d # 相对时间服务端极速索引过滤 (防大租户全量拉取超时)
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
@@ -84,7 +109,8 @@ hose-use mcp # 启动 MCP Server (默认暴露
### 模块化 Agent Skill 与 IDE 插件规范
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
@@ -92,7 +118,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
```text
src/
├── cli.ts # CLI 入口 (bin: hose)
├── cli.ts # CLI 入口 (bin: hose-use, hose-aipro)
├── cli/ # CLI 核心引擎 (runner, parser, printer, commands)
├── core/ # 基础设施与底层 SDK
│ ├── auth/ # 认证与换票 (RSA 账密, TokenStore, AccountStore)
+1449 -295
View File
File diff suppressed because it is too large. Load diff
+25 -1
View File
@@ -10,6 +10,12 @@ src/domains/platform/
├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装)
└── tools.ts # MCP tool 注册 + 服务层聚合函数
src/domains/datalink/
├── types.ts # 应用、业务对象、字段、记录与权限模型
├── api.ts # DataLink HTTP 接口封装
├── services.ts # 应用/对象解析与过滤辅助
└── tools.ts # DataLink MCP tools
src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
```
@@ -40,6 +46,18 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
## MCP Tools
### DataLink 应用与业务对象
| Tool | 说明 | 后端 |
|---|---|---|
| `datalink_platform_list` | 列出当前企业账号可见的启用自建应用 | EKB |
| `datalink_platform_get` | 获取应用详情及管理员、人员、角色、部门权限 | EKB |
| `datalink_entity_list` | 获取应用下业务对象、字段、操作和可见性配置 | EKB |
| `datalink_record_search` | 分页检索业务对象记录,支持 `filterBy` | EKB |
| `datalink_import_jobs` | 查看对象导入任务及最近导入结果 | EKB |
CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、`schema`、`records`、`permissions` 和 `imports`。
| Tool | 说明 | 后端 |
|---|---|---|
| `platform_list` | 列出企业下所有启用的自建应用 | EKB |
@@ -48,6 +66,12 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
| `platform_workflow_charge` | 查询企业工作流用量配额 | EASO |
| `platform_workflow_detail` | 获取工作流详情(含节点配置) | EASO / Piper |
| `platform_workflow_toggle` | 启用/停用工作流 | EASO / Piper |
| `workflow save` (CLI) | 按完整快照保存工作流草稿并校验版本 | Piper |
| `workflow history` (CLI) | 读取工作流服务端版本快照历史 | Piper |
| `workflow patch` (CLI) | 在本地完整快照上修改节点路径,生成新草稿文件 | 本地 |
| `workflow logs` (CLI) | 查询指定工作流运行日志 | Piper |
| `workflow check` (CLI) | 扫描错误管道并持久化去重提醒 | 本地 + EASO |
| `workflow publish` (CLI) | 将已保存的工作流状态切换为启用 | Piper |
| `platform_workflow_jobs` | 查询工作流运行中的任务 | EASO / Piper |
| `platform_workflow_dsl` | 获取工作流 DSL 配置列表 | EASO / Piper |
| `platform_workflow_staffs` | 获取企业员工列表 | EASO / Piper |
@@ -81,7 +105,7 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发
```bash
bun run export:workflow-schema
# 输出:schemas/workflow-schema.json
# 输出:specs/workflow-schema.json
```
## 工作流数据结构要点
+5
View File
@@ -0,0 +1,5 @@
# enterprises/ 目录说明
本目录仅保留 `example.json`(企业配置字段示例,随 git 分发),用于说明企业配置文件的格式。
**运行时数据不在这里。** CLI 实际读取的企业配置目录为 `~/.config/hose-use/enterprises/`(可用环境变量 `HOSE_ENTERPRISES_DIR` 覆盖),文件权限强制 `0600`、目录权限 `0700`,且已被 `.gitignore` 排除。解析逻辑见 `src/core/config/loader.ts`。
+12 -1
View File
@@ -1,12 +1,16 @@
{
"name": "hose-use",
"version": "0.7.0",
"version": "0.8.13",
"module": "src/server.ts",
"type": "module",
"bin": {
"hose-use": "src/cli.ts",
"hose-aipro": "src/cli.ts"
},
"packageManager": "bun@1.3.14",
"engines": {
"bun": ">=1.3.14"
},
"scripts": {
"cli": "bun run src/cli.ts",
"aipro": "bun run src/aipro-cli.ts",
@@ -15,11 +19,18 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/bump-version.ts",
"sync:release": "bun run scripts/bump-version.ts",
"check:version": "bun run scripts/check-version-sync.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"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:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"dev:status": "bun run scripts/dev-hygiene.ts status",
"dev:check": "bun run scripts/dev-hygiene.ts check",
"dev:clean": "bun run scripts/dev-hygiene.ts clean",
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
+66 -8
View File
@@ -1,4 +1,4 @@
import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
import { mkdirSync, readFileSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -17,20 +17,77 @@ const TARGET_MAP = {
const args = process.argv.slice(2);
const isAll = args.includes("--all") || args.includes("--matrix");
const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", "");
const isRelease = args.includes("--release") ||
process.env.HOSE_BUILD_RELEASE === "1" ||
(Boolean(process.env.CI) && process.env.GITHUB_REF_TYPE === "tag");
function getBuildInfo(releaseMode) {
const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
if (releaseMode) return { version: pkg.version, channel: "release", isRelease: true };
try {
const result = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { cwd: root, encoding: "utf8" });
if (result.status === 0 && result.stdout) {
const trimmed = result.stdout.trim();
const dirty = trimmed.endsWith("-dirty");
const clean = dirty ? trimmed.slice(0, -6) : trimmed;
const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);
let baseVersion = pkg.version;
let commitsAhead = 0;
let commit = "";
if (longMatch) {
baseVersion = longMatch[1];
commitsAhead = Number.parseInt(longMatch[2], 10);
commit = longMatch[3];
} else {
const revision = spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" });
if (revision.status === 0 && revision.stdout) commit = revision.stdout.trim();
}
const dirtySuffix = dirty ? ".dirty" : "";
const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : "";
return {
version: `${baseVersion}-dev.${commitsAhead}${commitSuffix}`,
channel: "dev",
isRelease: false,
git: { baseVersion, commitsAhead, commit, dirty, describe: trimmed }
};
}
} catch {
// Fall back below if git is unavailable.
}
return { version: `${pkg.version}-dev.0+local`, channel: "dev", isRelease: false };
}
const buildInfo = getBuildInfo(isRelease);
const buildEnv = {
...process.env,
HOSE_BUILD_VERSION: buildInfo.version,
HOSE_BUILD_CHANNEL: buildInfo.channel,
HOSE_BUILD_IS_RELEASE: String(buildInfo.isRelease),
...(buildInfo.git ? {
HOSE_BUILD_GIT_BASE: buildInfo.git.baseVersion,
HOSE_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead),
HOSE_BUILD_GIT_COMMIT: buildInfo.git.commit,
HOSE_BUILD_GIT_DIRTY: String(buildInfo.git.dirty),
HOSE_BUILD_GIT_DESCRIBE: buildInfo.git.describe
} : {})
};
console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`);
if (isAll) {
for (const [name, config] of Object.entries(TARGET_MAP)) {
buildTarget(name, config.bunTarget, resolve(root, config.outfile));
buildTarget(name, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv);
}
} else if (targetArg) {
const config = TARGET_MAP[targetArg];
if (!config) {
throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`);
}
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv);
} else {
const outputHose = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, outputHose, "src/cli.ts");
buildTarget("host", null, outputHose, "src/cli.ts", buildEnv);
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
const outputAipro = resolve(root, "dist/bin/hose-aipro");
@@ -43,16 +100,16 @@ if (isAll) {
}
}
function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
function buildTarget(name, bunTarget, output, entry = "src/cli.ts", env = process.env) {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
const buildArgs = ["build", "--compile", "--env=HOSE_BUILD_*"];
if (bunTarget) {
buildArgs.push(`--target=${bunTarget}`);
}
buildArgs.push("--outfile", output, entry);
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
run(bun, buildArgs);
run(bun, buildArgs, { env });
if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) {
try {
@@ -71,7 +128,8 @@ function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
function run(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: root,
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit"
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit",
env: options.env ?? process.env
});
if (result.error) throw result.error;
if (result.status !== 0) {
+19 -17
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
@@ -35,35 +35,33 @@ pkg.version = nextVersion;
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
console.log("✓ Updated package.json");
// 2. src/version.ts
const versionTsPath = join(ROOT, "src", "version.ts");
writeFileSync(versionTsPath, `export const VERSION = "${nextVersion}";\n`);
console.log("✓ Updated src/version.ts");
// 3. README.md
// 2. README.md
const readmePath = join(ROOT, "README.md");
let readmeContent = readFileSync(readmePath, "utf-8");
readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
writeFileSync(readmePath, readmeContent);
console.log("✓ Updated README.md");
// 4. skills/hose-use/SKILL.md
// 3. skills/hose-use/SKILL.md
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
let skillContent = readFileSync(skillPath, "utf-8");
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
skillContent = skillContent.replace(/v[\d.]+: 合思/g, `v${nextVersion}: 合思`);
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/hose-use/SKILL.md");
// 5. openapi/openapi.yaml
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
// 4. specs/openapi/openapi.yaml
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
if (existsSync(openapiPath)) {
let openapiContent = readFileSync(openapiPath, "utf-8");
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated openapi/openapi.yaml");
console.log("✓ Updated specs/openapi/openapi.yaml");
}
// 5.5 .zcode-plugin/plugin.json
// 4.5 .zcode-plugin/plugin.json
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
if (existsSync(pluginJsonPath)) {
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
@@ -72,20 +70,24 @@ if (existsSync(pluginJsonPath)) {
console.log("✓ Updated .zcode-plugin/plugin.json");
}
// 6. Sync to global ~/.agents/skills/hose-use/ if present
// 5. Sync to global ~/.agents/skills/hose-use/ if present
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
if (existsSync(globalSkillDir)) {
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
const srcDir = join(ROOT, "skills", "hose-use");
for (const item of readdirSync(srcDir)) {
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
}
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
}
// 7. Rebuild OpenAPI bundles
console.log("==> Rebuilding OpenAPI bundles...");
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
console.log("==> Rebuilding OpenAPI and plugin bundles...");
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log(` 1. Update CHANGELOG.md (if exists)`);
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
console.log(` 4. git push origin main --tags\n`);
console.log(` 4. git push origin <feature-branch>\n`);
+2 -2
View File
@@ -6,8 +6,8 @@ import YAML from "yaml";
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
const inputFile = resolve("openapi/openapi.yaml");
const outputFile = resolve("dist/openapi.json");
const inputFile = resolve("specs/openapi/openapi.yaml");
const outputFile = resolve("specs/openapi.json");
const bundled = bundle(inputFile, new Set());
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bun
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
const root = join(import.meta.dirname, "..");
const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
const expected: Array<[string, string | undefined]> = [
["package.json", packageVersion],
[".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")],
["specs/openapi/openapi.yaml", readFileSync(join(root, "specs/openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
["specs/openapi.json", readJsonVersion("specs/openapi.json", ["info", "version"])],
];
const mismatches = expected.filter(([, value]) => value !== packageVersion);
if (mismatches.length) {
console.error(`Version drift detected; expected ${packageVersion}:`);
for (const [file, value] of mismatches) console.error(` ${file}: ${value ?? "missing"}`);
process.exit(1);
}
console.log(`Version synchronized: ${packageVersion}`);
function readJsonVersion(file: string, path: string[] = ["version"]): string | undefined {
const fullPath = join(root, file);
if (!existsSync(fullPath)) return undefined;
let value: unknown = JSON.parse(readFileSync(fullPath, "utf8"));
for (const key of path) {
if (!value || typeof value !== "object") return undefined;
value = (value as Record<string, unknown>)[key];
}
return typeof value === "string" ? value : undefined;
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test";
import { buildCleanupPlan, classifyExitCode, isCompatibleBinaryVersion, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts";
describe("dev hygiene tooling", () => {
test("only accepts development-scoped modes and confirmation flags", () => {
expect(parseDevHygieneArgs(["status"])).toEqual({ mode: "status", dryRun: false, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--dry-run"])).toEqual({ mode: "clean", dryRun: true, yes: false, pruneUnreachable: false, help: false });
expect(parseDevHygieneArgs(["clean", "--yes", "--prune-unreachable"])).toEqual({ mode: "clean", dryRun: false, yes: true, pruneUnreachable: true, help: false });
});
test("uses semantic exit codes for clean, warning, and blocked states", () => {
const finding = (level: Finding["level"]): Finding => ({ id: level, level, message: level });
expect(classifyExitCode([])).toBe(0);
expect(classifyExitCode([finding("info")])).toBe(0);
expect(classifyExitCode([finding("warning")])).toBe(2);
expect(classifyExitCode([finding("blocked")])).toBe(3);
});
test("accepts a development build based on the current stable version", () => {
expect(isCompatibleBinaryVersion("0.8.6", "0.8.6")).toBe(true);
expect(isCompatibleBinaryVersion("0.8.6-dev.2+gabc1234", "0.8.6")).toBe(true);
expect(isCompatibleBinaryVersion("0.8.5-dev.1+gold", "0.8.6")).toBe(false);
expect(isCompatibleBinaryVersion(undefined, "0.8.6")).toBe(false);
});
test("only plans deletion for clean merged worktrees and local branches", () => {
const snapshot = {
repository: {} as any,
worktrees: [
{ path: "/tmp/merged", head: "a", branch: "feat/merged", current: false, exists: true, clean: true },
{ path: "/tmp/dirty", head: "b", branch: "feat/dirty", current: false, exists: true, clean: false },
],
branches: [
{ name: "main", sha: "m", merged: true, gone: false },
{ name: "feat/merged", sha: "a", merged: true, gone: false },
{ name: "feat/dirty", sha: "b", merged: true, gone: false },
{ name: "feat/live", sha: "c", merged: false, gone: false },
],
unreachableCommits: ["deadbeef"],
skill: {} as any,
binaries: [],
legacyConfig: {} as any,
};
const plan = buildCleanupPlan(snapshot, false);
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
expect(plan[1]?.kind).toBe("branch-delete");
expect(plan.some((action) => action.kind === "git-prune")).toBe(false);
});
});
+521
View File
@@ -0,0 +1,521 @@
#!/usr/bin/env bun
import { createHash } from "node:crypto";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use");
const NON_CANONICAL_SKILL_DIRS = [
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
join(homedir(), ".codex", "skills", "hose-use"),
];
export type FindingLevel = "info" | "warning" | "blocked";
export type HygieneMode = "status" | "check" | "clean";
export interface Finding {
id: string;
level: FindingLevel;
message: string;
details?: Record<string, unknown>;
nextAction?: string;
}
export interface HygieneArgs {
mode: HygieneMode;
dryRun: boolean;
yes: boolean;
pruneUnreachable: boolean;
help: boolean;
}
export interface CleanupAction {
kind: "worktree-remove" | "worktree-prune" | "branch-delete" | "git-prune";
target: string;
command: string;
reason: string;
}
interface GitBranch {
name: string;
sha: string;
upstream?: string;
gone: boolean;
merged: boolean;
}
interface GitWorktree {
path: string;
head: string;
branch?: string;
current: boolean;
exists: boolean;
clean?: boolean;
}
interface HygieneSnapshot {
repository: {
root: string;
branch: string;
head: string;
upstream?: string;
ahead: number;
behind: number;
clean: boolean;
stagedChanges: number;
unstagedChanges: number;
untrackedFiles: number;
};
worktrees: GitWorktree[];
branches: GitBranch[];
unreachableCommits: string[];
skill: {
canonicalDir: string;
canonicalExists: boolean;
canonicalIsSymlink: boolean;
missingFiles: string[];
mismatchedFiles: string[];
nonCanonicalCopies: Array<{ dir: string; exists: boolean; isSymlink: boolean; pointsToCanonical: boolean }>;
};
binaries: Array<{
name: string;
path?: string;
version?: string;
expectedVersion: string;
matches: boolean;
error?: string;
}>;
legacyConfig: {
enterprisesDir: string;
configFile: string;
enterprisesDirExists: boolean;
configFileExists: boolean;
};
}
export interface HygieneReport {
schemaVersion: 1;
mode: HygieneMode;
generatedAt: string;
repository: string;
snapshot: HygieneSnapshot;
findings: Finding[];
counts: Record<FindingLevel, number>;
nextActions: string[];
exitCode: number;
}
export function parseDevHygieneArgs(argv: string[]): HygieneArgs {
const requestedMode = argv.find((arg) => !arg.startsWith("--")) || "check";
const mode: HygieneMode = requestedMode === "status" || requestedMode === "clean" ? requestedMode : "check";
return {
mode,
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
yes: argv.includes("--yes") || argv.includes("--confirm"),
pruneUnreachable: argv.includes("--prune-unreachable"),
help: argv.includes("--help") || argv.includes("-h"),
};
}
export function classifyExitCode(findings: Finding[]): number {
if (findings.some((finding) => finding.level === "blocked")) return 3;
if (findings.some((finding) => finding.level === "warning")) return 2;
return 0;
}
function git(args: string[], cwd = ROOT): string {
try {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`git ${args.join(" ")} 失败: ${detail}`);
}
}
function gitMaybe(args: string[], cwd = ROOT): string | undefined {
try {
return git(args, cwd).trim() || undefined;
} catch {
return undefined;
}
}
function parseRepository(): HygieneSnapshot["repository"] {
const status = git(["status", "--porcelain=v1", "-b"]);
const lines = status.split("\n").filter(Boolean);
const branchLine = lines.shift() || "## HEAD";
const branch = branchLine.replace(/^##\s+/, "").split("...")[0] || "HEAD";
const changes = lines.filter((line) => !line.startsWith("##"));
const stagedChanges = changes.filter((line) => line !== "??" && line[0] !== " " && line[0] !== "?").length;
const unstagedChanges = changes.filter((line) => line !== "??" && line[1] !== " " && line.slice(0, 2) !== "??").length;
const untrackedFiles = changes.filter((line) => line.startsWith("??")).length;
const upstream = gitMaybe(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]);
const divergence = upstream ? gitMaybe(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]) : undefined;
const [ahead, behind] = (divergence || "0 0").split(/\s+/).map((value) => Number(value) || 0);
return {
root: ROOT,
branch,
head: git(["rev-parse", "--short", "HEAD"]).trim(),
...(upstream ? { upstream } : {}),
ahead,
behind,
clean: changes.length === 0,
stagedChanges,
unstagedChanges,
untrackedFiles,
};
}
function parseWorktrees(): GitWorktree[] {
const records: GitWorktree[] = [];
let current: Partial<GitWorktree> = {};
const flush = () => {
if (!current.path) return;
const path = resolve(current.path);
const exists = existsSync(path);
let clean: boolean | undefined;
if (exists) {
try {
clean = git(["status", "--porcelain=v1"], path).trim() === "";
} catch {
clean = undefined;
}
}
records.push({
path,
head: current.head || "",
...(current.branch ? { branch: current.branch } : {}),
current: path === ROOT,
exists,
...(clean === undefined ? {} : { clean }),
});
current = {};
};
for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) {
if (!line) {
flush();
continue;
}
const [key, ...rest] = line.split(" ");
const value = rest.join(" ");
if (key === "worktree") current.path = value;
if (key === "HEAD") current.head = value;
if (key === "branch") current.branch = value.replace(/^refs\/heads\//, "");
}
flush();
return records;
}
function parseBranches(): GitBranch[] {
const merged = new Set(git(["branch", "--merged", "main", "--format=%(refname:short)"]).split("\n").filter(Boolean));
return git(["for-each-ref", "--format=%(refname:short)%09%(objectname:short)%09%(upstream:short)%09%(upstream:track)", "refs/heads"])
.split("\n")
.filter(Boolean)
.map((line) => {
const [name, sha, upstream, track] = line.split("\t");
return { name, sha, ...(upstream ? { upstream } : {}), gone: track === "[gone]", merged: merged.has(name) };
});
}
function parseUnreachableCommits(): string[] {
return git(["fsck", "--full", "--no-reflogs", "--unreachable"])
.split("\n")
.filter((line) => line.includes(" commit "))
.map((line) => line.trim().split(/\s+/)[2])
.filter(Boolean);
}
function listFiles(dir: string, base = dir): string[] {
if (!existsSync(dir)) return [];
const files: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory() && !entry.isSymbolicLink()) files.push(...listFiles(fullPath, base));
else files.push(relative(base, fullPath));
}
return files.sort();
}
function fileHash(path: string): string | undefined {
try {
return createHash("sha256").update(readFileSync(path)).digest("hex");
} catch {
return undefined;
}
}
function parseSkill(): HygieneSnapshot["skill"] {
const expectedFiles = git(["ls-files", "skills/hose-use"]).split("\n").filter(Boolean).map((path) => path.slice("skills/hose-use/".length));
const missingFiles = expectedFiles.filter((file) => !existsSync(join(CANONICAL_SKILL_DIR, file)));
const mismatchedFiles = expectedFiles.filter((file) => {
const sourceHash = fileHash(join(ROOT, "skills", "hose-use", file));
const targetHash = fileHash(join(CANONICAL_SKILL_DIR, file));
return sourceHash !== undefined && targetHash !== undefined && sourceHash !== targetHash;
});
return {
canonicalDir: CANONICAL_SKILL_DIR,
canonicalExists: existsSync(CANONICAL_SKILL_DIR),
canonicalIsSymlink: existsSync(CANONICAL_SKILL_DIR) && lstatSync(CANONICAL_SKILL_DIR).isSymbolicLink(),
missingFiles,
mismatchedFiles,
nonCanonicalCopies: NON_CANONICAL_SKILL_DIRS.map((dir) => ({
dir,
exists: existsSync(dir),
isSymlink: existsSync(dir) && lstatSync(dir).isSymbolicLink(),
pointsToCanonical: (() => {
try {
return lstatSync(dir).isSymbolicLink() && realpathSync(dir) === CANONICAL_SKILL_DIR;
} catch {
return false;
}
})(),
})),
};
}
function resolveCommand(name: string): string | undefined {
const result = spawnSync("which", [name], { encoding: "utf8" });
if (result.status === 0 && result.stdout?.trim()) return result.stdout.trim();
return undefined;
}
export function isCompatibleBinaryVersion(actual: string | undefined, expected: string): boolean {
return actual === expected || actual?.startsWith(`${expected}-dev.`) === true;
}
function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
const path = resolveCommand(name);
if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" };
const result = spawnSync(path, ["version", "--json"], { cwd: ROOT, encoding: "utf8", timeout: 5000 });
if (result.status !== 0) {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: result.stderr?.trim() || `退出码 ${result.status ?? 1}` };
}
try {
const version = (JSON.parse(result.stdout) as { version?: string }).version;
return { name, path, version, expectedVersion: PACKAGE.version, matches: isCompatibleBinaryVersion(version, PACKAGE.version) };
} catch {
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" };
}
}
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
const home = homedir();
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
}
function collectSnapshot(): HygieneSnapshot {
return {
repository: parseRepository(),
worktrees: parseWorktrees(),
branches: parseBranches(),
unreachableCommits: parseUnreachableCommits(),
skill: parseSkill(),
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
legacyConfig: parseLegacyConfig(),
};
}
function buildFindings(snapshot: HygieneSnapshot): Finding[] {
const findings: Finding[] = [];
const repo = snapshot.repository;
if (!repo.clean) {
findings.push({ id: "repo.dirty", level: "warning", message: "当前开发工作树存在未提交修改", details: { stagedChanges: repo.stagedChanges, unstagedChanges: repo.unstagedChanges, untrackedFiles: repo.untrackedFiles }, nextAction: "先确认这些修改属于当前工作,必要时提交或单独保存" });
}
if (repo.branch === "HEAD") findings.push({ id: "repo.detached", level: "blocked", message: "当前处于 detached HEAD", nextAction: "切换到明确的开发分支后再进行清理" });
if (repo.behind > 0) findings.push({ id: "repo.behind", level: "warning", message: "当前分支落后于上游分支", details: { upstream: repo.upstream, behind: repo.behind }, nextAction: "确认远程变化后再执行开发清理" });
for (const worktree of snapshot.worktrees) {
if (!worktree.exists) {
findings.push({ id: "worktree.missing", level: "blocked", message: "Git 记录了不存在的工作树路径", details: { path: worktree.path, branch: worktree.branch }, nextAction: "先用 git worktree prune 清理失效记录" });
} else if (!worktree.current && worktree.clean === false) {
findings.push({ id: "worktree.dirty", level: "warning", message: "额外工作树存在未提交修改", details: { path: worktree.path, branch: worktree.branch }, nextAction: "不要自动删除;先进入该工作树确认修改归属" });
} else if (!worktree.current) {
findings.push({ id: "worktree.extra", level: "info", message: "存在额外工作树,需人工确认是否仍有用途", details: { path: worktree.path, branch: worktree.branch } });
}
}
for (const branch of snapshot.branches) {
if (branch.name === snapshot.repository.branch) continue;
if (branch.name !== "main" && branch.merged) {
const linked = snapshot.worktrees.some((worktree) => worktree.branch === branch.name);
findings.push({ id: "branch.merged", level: linked ? "warning" : "info", message: linked ? "已合并分支仍被工作树占用" : "发现已合并的本地分支", details: { branch: branch.name, sha: branch.sha, linkedWorktree: linked } });
} else if (branch.gone) {
findings.push({ id: "branch.gone", level: "warning", message: "本地分支的上游远程分支已不存在", details: { branch: branch.name, upstream: branch.upstream }, nextAction: "确认本地分支不再需要后再删除" });
}
}
if (snapshot.unreachableCommits.length) {
findings.push({ id: "git.unreachable", level: "warning", message: "发现无分支或标签引用的 Git commit", details: { count: snapshot.unreachableCommits.length, commits: snapshot.unreachableCommits }, nextAction: "先检查内容,确认后使用 dev:clean --yes --prune-unreachable" });
}
const skill = snapshot.skill;
if (!skill.canonicalExists || skill.missingFiles.length || skill.mismatchedFiles.length) {
findings.push({ id: "skill.canonical-drift", level: "warning", message: "canonical Skill 缺失或与当前源码不一致", details: { dir: skill.canonicalDir, missingFiles: skill.missingFiles, mismatchedFiles: skill.mismatchedFiles }, nextAction: "运行 bun run dev:override 同步开发版 Skill" });
}
for (const copy of skill.nonCanonicalCopies.filter((item) => item.exists && !item.pointsToCanonical)) {
findings.push({ id: "skill.noncanonical-copy", level: "warning", message: "发现非 canonical Skill 副本;检查不会删除它", details: copy, nextAction: "确认外部工具不再使用后,再单独设计迁移或软链接" });
}
for (const binary of snapshot.binaries) {
if (!binary.path) {
findings.push({ id: "binary.missing", level: "info", message: `${binary.name} 未安装到 PATH`, details: binary, nextAction: "如需全局开发版,运行 bun run dev:override" });
} else if (!binary.matches) {
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
}
}
const legacy = snapshot.legacyConfig;
if (legacy.enterprisesDirExists || legacy.configFileExists) {
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
}
return findings;
}
export function buildCleanupPlan(snapshot: HygieneSnapshot, pruneUnreachable: boolean): CleanupAction[] {
const actions: CleanupAction[] = [];
if (snapshot.worktrees.some((worktree) => !worktree.exists)) {
actions.push({ kind: "worktree-prune", target: "stale-worktree-records", command: "git worktree prune", reason: "移除 Git 记录中已经不存在的工作树" });
}
const removableWorktreeBranches = new Set(
snapshot.worktrees
.filter((worktree) => !worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
const linkedPaths = new Set(
snapshot.worktrees
.filter((worktree) => !removableWorktreeBranches.has(worktree.branch || ""))
.map((worktree) => worktree.branch)
.filter((branch): branch is string => Boolean(branch))
);
for (const worktree of snapshot.worktrees) {
if (!worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) {
actions.push({ kind: "worktree-remove", target: worktree.path, command: `git worktree remove ${JSON.stringify(worktree.path)}`, reason: `工作树干净且分支 ${worktree.branch} 已合并` });
}
}
for (const branch of snapshot.branches) {
if (branch.name !== "main" && branch.merged && !linkedPaths.has(branch.name)) {
actions.push({ kind: "branch-delete", target: branch.name, command: `git branch -d ${branch.name}`, reason: "本地分支已合并且没有关联工作树" });
}
}
if (pruneUnreachable && snapshot.unreachableCommits.length) {
actions.push({ kind: "git-prune", target: "unreachable-objects", command: "git reflog expire --expire=now --all && git gc --prune=now", reason: "明确启用 unreachable 对象清理" });
}
return actions;
}
function applyCleanup(actions: CleanupAction[]): Array<{ action: CleanupAction; ok: boolean; error?: string }> {
return actions.map((action) => {
try {
if (action.kind === "worktree-remove") git(["worktree", "remove", action.target]);
else if (action.kind === "worktree-prune") git(["worktree", "prune"]);
else if (action.kind === "branch-delete") git(["branch", "-d", action.target]);
else {
git(["reflog", "expire", "--expire=now", "--all"]);
git(["gc", "--prune=now"]);
}
return { action, ok: true };
} catch (error) {
return { action, ok: false, error: error instanceof Error ? error.message : String(error) };
}
});
}
function createReport(mode: HygieneMode): HygieneReport {
const snapshot = collectSnapshot();
const findings = buildFindings(snapshot);
const counts = {
info: findings.filter((finding) => finding.level === "info").length,
warning: findings.filter((finding) => finding.level === "warning").length,
blocked: findings.filter((finding) => finding.level === "blocked").length,
};
const exitCode = classifyExitCode(findings);
return {
schemaVersion: 1,
mode,
generatedAt: new Date().toISOString(),
repository: ROOT,
snapshot,
findings,
counts,
nextActions: findings.map((finding) => finding.nextAction).filter((action): action is string => Boolean(action)),
exitCode,
};
}
function emit(value: unknown): void {
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function emitSummary(report: HygieneReport): void {
console.error(`[dev:${report.mode}] ${report.repository}`);
console.error(`发现 ${report.counts.info} 条提示、${report.counts.warning} 条警告、${report.counts.blocked} 条阻塞项;退出码 ${report.exitCode}`);
for (const finding of report.findings) console.error(`- [${finding.level}] ${finding.message}`);
}
function usage(): string {
return [
"开发环境检查(不会进入 hose-use 用户命令):",
" bun run dev:status 输出当前开发环境快照",
" bun run dev:check 只读检查并返回语义化退出码",
" bun run dev:clean --dry-run 预览安全清理动作",
" bun run dev:clean --yes 执行干净且已合并的本地清理",
" bun run dev:clean --yes --prune-unreachable 额外清理无引用 Git 对象",
"",
"stdout 始终为 JSON;人类提示和进度写入 stderr。远程分支和非 canonical Skill 目录不会被自动删除。",
].join("\n");
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const args = parseDevHygieneArgs(argv);
if (args.help) {
emit({ ok: true, usage: usage().split("\n") });
console.error(usage());
return 0;
}
try {
if (args.mode !== "clean") {
const report = createReport(args.mode);
emit(report);
emitSummary(report);
return args.mode === "status" ? 0 : report.exitCode;
}
const report = createReport("clean");
const plan = buildCleanupPlan(report.snapshot, args.pruneUnreachable);
if (args.dryRun || !args.yes) {
emit({ ...report, plan, dryRun: true, nextAction: "bun run dev:clean --yes" });
emitSummary(report);
console.error(plan.length ? "[dev:clean] 当前仅预览,追加 --yes 才会执行。" : "[dev:clean] 没有满足安全条件的本地清理动作。");
return report.exitCode;
}
if (report.snapshot.repository.branch === "HEAD") {
emit({ ...report, plan, applied: false, error: "detached HEAD 下拒绝清理" });
return 3;
}
const results = applyCleanup(plan);
const failed = results.filter((result) => !result.ok);
emit({ ...report, plan, applied: true, results, failed: failed.length });
console.error(`[dev:clean] 已执行 ${results.length - failed.length} 项,失败 ${failed.length} 项。`);
return failed.length ? 4 : 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
emit({ ok: false, error: message });
console.error(`[dev:hygiene] ${message}`);
return 4;
}
}
if (import.meta.main) {
main().then((exitCode) => {
process.exitCode = exitCode;
});
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import { globalBinCandidates, parseDevOverrideArgs } from "./dev-override.js";
describe("dev:override", () => {
test("parses dry-run and explicit target path without touching the host", () => {
expect(parseDevOverrideArgs(["--dry-run", "--target-path=/tmp/hose-use-test"])).toEqual({
dryRun: true,
targetPath: "/tmp/hose-use-test",
});
});
test("uses stable global binary locations", () => {
const candidates = globalBinCandidates("hose-use-test");
expect(candidates.some((candidate) => candidate.endsWith("/hose-use-test"))).toBe(true);
expect(candidates).toHaveLength(4);
});
});
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env bun
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export interface DevOverrideOptions {
dryRun: boolean;
targetPath?: string;
}
export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions {
return {
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length),
};
}
export function globalBinCandidates(commandName = "hose-use"): string[] {
return [
"/opt/homebrew/bin",
"/usr/local/bin",
join(homedir(), ".local", "bin"),
join(homedir(), "bin"),
].map((dir) => join(dir, commandName));
}
export function resolveTargetBinaryPath(commandName = "hose-use"): string {
try {
const whichRes = spawnSync("which", [commandName], { encoding: "utf8" });
if (whichRes.status === 0 && whichRes.stdout) {
const path = whichRes.stdout.trim();
if (path && existsSync(path)) return path;
}
} catch {
// Fall back to conventional user-level locations.
}
for (const candidate of globalBinCandidates(commandName)) {
if (existsSync(dirname(candidate))) return candidate;
}
const defaultDir = join(homedir(), ".local", "bin");
mkdirSync(defaultDir, { recursive: true });
return join(defaultDir, commandName);
}
function runBuild(): string {
const result = spawnSync("node", ["scripts/build-binary.mjs"], {
cwd: ROOT,
stdio: ["ignore", "inherit", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`);
const localBinary = join(ROOT, "dist", "bin", "hose-use");
if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`);
return localBinary;
}
function stopRunningService(targetPath: string): boolean {
try {
const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" });
if (statusRes.status !== 0 || !statusRes.stdout) return false;
const status = JSON.parse(statusRes.stdout) as { running?: boolean };
if (!status.running) return false;
console.error("==> [dev:override] 停止正在运行的后台服务...");
const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作");
return true;
} catch (error) {
if (error instanceof Error && error.message.includes("无法停止")) throw error;
return false;
}
}
function installBinary(localBinary: string, targetPath: string): void {
const targetDir = dirname(targetPath);
mkdirSync(targetDir, { recursive: true });
const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
try {
copyFileSync(localBinary, temporaryPath);
chmodSync(temporaryPath, 0o755);
if (process.platform === "darwin") {
spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" });
}
// copyFileSync follows an existing symlink, so a package-manager shim is not
// accidentally replaced by a regular file.
copyFileSync(temporaryPath, targetPath);
chmodSync(targetPath, 0o755);
} finally {
rmSync(temporaryPath, { force: true });
}
}
function syncAgentSkill(): string | undefined {
const source = join(ROOT, "skills", "hose-use");
const target = join(homedir(), ".agents", "skills", "hose-use");
if (!existsSync(source)) return undefined;
mkdirSync(dirname(target), { recursive: true });
cpSync(source, target, { recursive: true, force: true });
return target;
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const options = parseDevOverrideArgs(argv);
const targetPath = options.targetPath || resolveTargetBinaryPath();
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
console.error(` 工作区: ${ROOT}`);
console.error(` 目标: ${targetPath}`);
if (options.dryRun) {
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
return 0;
}
const builtBinary = runBuild();
const serviceWasRunning = stopRunningService(targetPath);
installBinary(builtBinary, targetPath);
const aiproPath = join(dirname(targetPath), "hose-aipro");
if (aiproPath !== targetPath) {
rmSync(aiproPath, { force: true });
symlinkSync(targetPath, aiproPath);
}
try {
const skillTarget = syncAgentSkill();
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
} catch (error) {
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
}
if (serviceWasRunning) {
console.error("==> [dev:override] 使用新二进制重启后台服务...");
const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start");
}
const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" });
if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败");
console.error("✨ [dev:override] 全局开发版安装完成");
process.stdout.write(versionRes.stdout || "");
return 0;
}
if (import.meta.main) {
main().catch((error) => {
console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
}
+1 -1
View File
@@ -6,7 +6,7 @@ import {
WorkflowSchema,
} from "../src/domains/platform/types.js";
const OUTPUT_DIR = join(process.cwd(), "schemas");
const OUTPUT_DIR = join(process.cwd(), "specs");
const OUTPUT_FILE = join(OUTPUT_DIR, "workflow-schema.json");
function writeJson(path: string, data: unknown): void {
+1 -1
View File
@@ -3,7 +3,7 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const outputFile = resolve("dist/raw-hose-openapi.json");
const outputFile = resolve("specs/openapi.raw.json");
function standardResponse(description: string, dataSchema: any) {
return {
+64 -18
View File
@@ -116,30 +116,67 @@ download_candidate() {
echo "==> Target install location: ${TARGET_PATH}"
TMP_FILE="$(mktemp)"
DOWNLOAD_SUCCESS=false
DOWNLOADED_FORMAT="archive"
# Candidate mirrors
GITEA_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/latest/${ASSET_NAME}"
GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
# Resolve latest Gitea tag if available
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
LATEST_TAG=""
if command -v curl >/dev/null 2>&1; then
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
fi
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
# 1. Try Gitea mirror
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="archive"
fi
fi
# 2. Try direct GitHub Releases
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="archive"
fi
fi
# 3. Try Fast CDN Proxy Fallback
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="archive"
fi
fi
# 2. Second priority: Raw Executable (Fallback)
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="raw"
fi
fi
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="raw"
fi
fi
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="raw"
fi
fi
fi
@@ -149,18 +186,26 @@ if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
exit 1
fi
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
# Also create 'hose' symlink if possible
if [ -w "$TARGET_DIR" ]; then
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose" 2>/dev/null || true
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
echo "==> Extracting archive to ${TARGET_DIR}..."
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
rm -f "$TMP_FILE"
chmod +x "$TARGET_PATH"
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
else
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
# Create hose-aipro multicall alias pointing at the single binary.
if [ -w "$TARGET_DIR" ]; then
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
fi
fi
# Ad-hoc sign on macOS
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
echo "==> Applying macOS code signature..."
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
fi
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
@@ -177,4 +222,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 ""
+178 -84
View File
@@ -1,27 +1,57 @@
---
name: hose-use
description: "v0.6.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.6.0
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.6.0)
version: 0.8.13
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.7.0)
# hose-use (v0.8.13)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
---
## 本套件结构(先看这里)
本 skill 是**合思/易快报系列的唯一入口**,下级技能不在模型目录中,按需读取:
| 需要做什么 | 去哪里 |
|---|---|
| 登录/租户/单据/审批/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
| 写或排错**工作流 MVEL 代码节点**脚本 | `multi/ekuaibao-mvel/SKILL.md` |
| **批量开通工作流节点**(从浏览器 curl 提取 token/corpId/baseUrl) | `multi/ekuaibao-nodes/SKILL.md` |
---
## Agent 执行原则 (First Rules)
0. **一键构建上下文(Zero Source-Reading)**:在开始执行任务前,优先执行 `hose-use context --json` 或 `hose-aipro status --json` 一键获取当前账号、企业租户、登录凭证、运行模式与 AI PRO 网关状态。**严禁翻阅源码目录探查配置与企业列表**。
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose-use corps list` 或 `hose-use context`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
3. **输出防护与大报文处理**:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
8. **工具域强隔离(Zero External Tool Cross-Calling)**:在处理合思/易快报相关诉求时,严格在 `hose-use` 体系内完成,**严禁跨域调用任何外部系统的 CLI(如 `seal-use` 等)**,绝不把其他系统的状态或数据强行拼接进来。
9. **企业状态与信息分级披露(Progressive Disclosure & Stop Rules)**:
- **4 大状态命令正交语义(严禁概念混淆)**:
* `hose-use probe [--corp=<id>]`:**企业接入连通性与 Token 时效探针(回答“某某企业状态怎么样/连通性如何/过期没有”的唯一标准命令)**。输出仅限网络 Session、EASO 换票、自建应用网关连通性以及 Token 剩余有效时长。
* `hose-use auth status`:统一用户中心 (IDP) 主账号登录态与会话检查。
* `hose-use context`:Agent 本地运行环境与配置全景自省(纯本地零网络 IO)。
* `hose-use corps list`:本地企业租户名录与工号花名册。
- **行为分级与终止准则**:
* **L1 基础设施与连通性(默认)**:用户询问企业状态时,**仅执行一次 `hose-use probe`**,以简短卡片输出核心连通性与时效,**立即停止工具调用并结束 Turn**。
* **L2 业务待办与通知(按需)**:仅在用户明确询问“有我的待办吗 / 有新消息吗”时,才调用 `task todo` 或 `message count`。
* **L3 深度排查与健康巡检(明确指令)**:严禁在日常状态询问中擅自执行 `workflow check` 巡检错误或无条件拉取全量单据,仅在用户下达“排查系统故障 / 检查工作流报错”等明确指令时才可触发。
10. **单据检索服务端过滤优先(Server-Side Filtering First)**:
- 查询单据列表优先使用服务端时间过滤 `--since=7d`、`--since=30d`、`--start-date`、`--end-date` 或指定 `--code`,服务端毫秒级利用索引返回;
- 在海量单据租户下,严禁无参数滥用全量检索,优先引导用户查看个人发起单据(`hose-use bill list --mine`)或待办(`hose-use task todo`)。
---
@@ -29,100 +59,162 @@ metadata:
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|---|---|---|
| 首次登录 / 账密认证 / 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) |
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](references/auth.md) |
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) |
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) |
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose-use bill refs <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据关联关系 / 冲借款与前置申请追溯 | `hose-use bill relations <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据预算状态 / 超预算与占用信息 | `hose-use bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) |
| 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) |
| 费用类型全生命周期与表单规格 (增删查改/停启用/移动/字段) | `hose-use feetype list`, `hose-use feetype create`, `hose-use feetype get <ID>` | [references/feetype.md](references/feetype.md) |
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](references/workflow.md) |
| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record <get|toggle|edit|batch-edit|recompute>` | [references/workflow.md](references/workflow.md) |
| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断(禁用/SKIP风险/联动覆盖) | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) |
| 待办/消息事件轮询与去重 | `hose-use service poll --corp=<id>` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use 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` |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose-use openapi`, `hose-use openapi --raw` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | `hose-use update`, `hose-use update --changelog` | `hose-use update --help` |
---
## 常用命令速查
```bash
# 0. 全局上下文一键自省 (免读源码构建环境)
hose-use context # 文本格式仪表盘 (当前账号/企业/工号/Token/AI PRO/路径)
hose-use context --json # 结构化 JSON (供 Agent 零解析直接构建完整上下文)
hose-aipro status # 查看 AI PRO 审批网关状态、当前连接企业与规则场景库
hose-aipro # 首页直接展示动态企业页眉与快速工作流
# 1. 认证与企业
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose auth status # 查看 Token 剩余有效期与登录账号
hose corps list # 查看企业租户列表
hose corps switch ID01MCcOgJl1td # 切换工作企业
hose probe # 诊断当前企业接口连通性
hose-use auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose-use auth status # 查看 Token 剩余有效期与登录账号
hose-use corps list # 查看企业租户列表 (标注 * 为统一默认企业)
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
hose-use probe # 诊断当前企业接口连通性
# 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 contact search 王硕 # 模糊搜索员工工号、邮箱与电话
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose-use contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
hose-use 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 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 # 查询单据实体元数据字典
hose-use bill list --since=7d # 推荐:服务端按近 7 天极速索引检索(防大租户超时)
hose-use bill list --since=30d --count=10 # 检索近 30 天最新 10 笔单据
hose-use bill list --start-date=2026-09-01 --end-date=2026-09-17 # 指定明确日期区间服务端过滤
hose-use bill list --keyword=打车 # 单据关键字跨字段复合匹配 (默认匹配 name,code,form)
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose-use bill 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 111 --yes # 转交给工号/员工 ID/唯一姓名
hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
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 feetype list # 树形层级查看企业费用类型
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
hose-use feetype create --name="市内打车" --parent="交通费" --dry-run # 先预览新建
hose-use feetype create --name="市内打车" --parent="交通费" --yes # 确认新建
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes # 修改费用类型属性
hose-use feetype disable 市内打车 --yes # 停用费用类型 (软删除)
hose-use feetype enable 市内打车 --yes # 重新启用费用类型
hose-use feetype move 市内打车 --parent="差旅费用" --yes # 移动费用类型到新父级
hose-use role list # 查看企业角色定义
hose-use role groups # 查看角色组及其角色
hose-use role members 财务主管 # 查看指定角色成员
hose-use permission get # 查看角色权限开关(只读)
hose-use bill schema # 查询单据实体元数据字典
hose-use bill spec ID01TxgE3fhD6n # 查看单据模板字段配置、赋值优先级与联动规则
# 4. 待办与消息
hose task submitted # 查看我发起的单据
hose message list --unread # 查看未读消息
hose message list --all # 合并查看已读和未读消息
hose message count # 查看未读数量
hose message read <messageId> # 标记单条消息已读
hose-use task submitted # 查看我发起的单据
hose-use message list --unread # 查看未读消息
hose-use message list --all # 合并查看已读和未读消息
hose-use message count # 查看未读数量
hose-use message read <messageId> # 标记单条消息已读
# 5. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
# 5. 应用管理、自建应用与工作流
hose-use app list # 查看应用管理列表(桌面端工作台业务应用集成)
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
hose-use platform list # 列出企业可见的自建应用平台
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"我方签约主体":"ID01..."}' --dry-run # Read-Modify-Write 安全合并预览
hose-use platform record batch-edit 新转转集团 合同 --ids=id1,id2 --data='{"字段":"值"}' --dry-run # 批量安全更新预览
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
hose-use menu list # 查看桌面端主框架一级导航树
hose-use workflow list # 聚合扫描全部自建应用下的工作流
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断(含联动覆盖/SKIP守卫检查)
hose-use workflow logs wf_01k83y... --has-error # 筛选包含报错节点(含被 SKIP 吞掉错误)的运行历史
hose-use workflow job 892809886382563347 --failed # 一键定位单次运行失败节点、入参出参与错误原因
hose-use workflow job 892809886382563347 --parent=<executionId> # 下钻查看循环/分支容器内子节点执行明细
hose-use workflow job 892809886382563347 --logs=<executionId> # 查看指定节点(如 MVEL 脚本)底层执行日志
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
# 6. 服务与守护进程
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose service start # 后台启动常驻守护进程服务
hose service status # 查看常驻守护进程运行状态与端点
hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
hose service logs # 查看常驻守护进程日志
hose service stop # 停止后台常驻守护进程
# 6. OpenAPI 密钥与应用中心
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
hose-use keys --reveal # 仅在用户明确授权时查看完整 appSecurity
hose-use store list --all # 查看当前企业已购/已开通应用
hose-use store search "开放接口" # 搜索应用商店
hose-use store get <应用ID> # 查看应用详情(ID 可带或不带前导 $)
# 7. 服务与守护进程
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看常驻守护进程运行状态与端点
hose-use service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
hose-use service logs # 查看常驻守护进程日志
hose-use service stop # 停止后台常驻守护进程
```
---
@@ -135,4 +227,6 @@ hose service stop # 停止后台常驻守护
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
- `--stateless`:单次命令强制以无状态模式执行
- `--stateful`:单次命令强制以有状态模式执行
- `--dry-run`:预览写操作,不发起写请求或落盘
- `--yes`, `--confirm`:显式确认执行写操作
- `--help, -h`:查看命令帮助与参数说明
+2 -2
View File
@@ -5,12 +5,12 @@ auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
description: "执行合思/易快报 hose-use CLI 命令,包括 keys 凭证查询与 store 应用探查。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
properties:
command:
type: "string"
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow check --json', 'workflow get <pipelineId> --json -o workflow.json', 'workflow save <pipelineId> --file=workflow.json', 'service status'"
required:
- "command"
@@ -0,0 +1,146 @@
---
name: ekuaibao-mvel
description: Generate and debug MVEL code-node scripts for 合思/易快报/Ekuaibao workflows.
---
# 合思 MVEL 代码节点
## Core Rule
Generate code for Ekuaibao's modified MVEL 2.x runtime, not JavaScript, Groovy, or standard Java. First match the syntax style the user has already proven in their tenant or node.
- If the user provides a working snippet, preserve that dialect. For example, if `a = action_xxx; ... result;` works, use bare assignments and final-expression return.
- If the user has not provided a working snippet, prefer conservative MVEL and be ready to simplify to a probe script.
- Do not use `def` for variables.
- Use `return`, `import`, or `var` only when they match the user's known working environment; otherwise avoid them in favor of final-expression return and fully qualified JDK classes.
- Use Java collection methods: `.get()`, `.put()`, `.add()`, `.size()`.
- For Chinese or dynamic field names, prefer `map.get("字段名")` instead of dot access.
- Every `if`, `&&`, and `||` operand must be a strict boolean expression. Never write `if (data)`.
## Code Node Template
Use this style when the user has shown bare assignments and final-expression return work:
```groovy
a = action_xxxxxx;
result = new java.util.HashMap();
result.put("ok", true);
result;
```
When the user's environment supports `var/import/return`, it is acceptable to use that style, but do not mix styles unnecessarily within one answer.
## Tenant-Proven Short Syntax
This tenant has verified that these short forms work:
- Map literal: `["key": value]`
- List literal: `[item1, item2]`
- Final-expression return
- Upstream node references use node ID variables such as `action_xxxxxx`
When the user asks to hard-return a config object, prefer Map/List literals first:
```groovy
[
"config": [
"key": "value",
"list": ["a", "b"]
]
]
```
If Map/List literals fail in a different tenant or node, fall back to `new java.util.HashMap()` and `new java.util.ArrayList()`.
## Upstream Node Reference
When the user says the upstream node is referenced by ID, assign the node ID variable to a semantic local name first:
```groovy
inputData = action_xxxxxx;
```
Do not assume the platform provides a built-in variable named `inputData` unless the user explicitly says so. Replace `action_xxxxxx` with the real upstream node ID the user provides.
## Defensive Patterns
### Read First Item Only
When the user says to read only the first upstream record, do not loop.
```groovy
a = action_xxxxxx;
firstItem = null;
if (a != null && a.size() > 0) {
firstItem = a.get(0);
}
```
### Read Nested Form Field
```groovy
value = "";
if (firstItem != null && firstItem.get("form") != null) {
form = firstItem.get("form");
rawValue = form.get("E_xxx_字段名");
if (rawValue != null && String.valueOf(rawValue).trim() != "") {
value = String.valueOf(rawValue).trim();
}
}
```
### Generate Next 6-Digit Number
Use this for JS logic like `parseInt(num, 10) || 0` and `.padStart(6, "0")`:
```groovy
num = "";
nextStr = "000001";
if (rawNum != null && String.valueOf(rawNum).trim() != "") {
num = String.valueOf(rawNum).trim();
}
if (num != null && num.trim() != "" && num.trim().matches("[0-9]+")) {
cleanNum = num.trim();
nextNumber = java.lang.Integer.parseInt(cleanNum) + 1;
rawNextStr = String.valueOf(nextNumber);
if (rawNextStr.length() < 6) {
padded = "000000" + rawNextStr;
nextStr = padded.substring(padded.length() - 6);
} else {
nextStr = rawNextStr;
}
}
```
## Avoid
- Do not use JavaScript methods: `.push()`, `.length` as a property, `parseInt`, `padStart`.
- Do not use Groovy sugar: `?.`, `?:`.
- Do not use `try/catch` unless the user has already verified it works in their tenant.
- Do not use third-party imports such as Fastjson.
- Do not use `String.valueOf(map)` when downstream needs valid JSON; manually concatenate JSON strings.
- In enhanced loops, write `for (item : list)`, never `for (var item : list)`.
## Debugging Silent Failures
If the platform gives no detailed error, simplify toward a probe script:
```groovy
a = action_xxxxxx;
result = new java.util.HashMap();
result.put("isNull", a == null);
result.put("total", a != null ? a.size() : 0);
result;
```
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
@@ -0,0 +1,4 @@
interface:
display_name: "合思 MVEL"
short_description: "生成、改写和排查合思 MVEL 代码节点运行兼容问题"
default_prompt: "Use $ekuaibao-mvel to write a 合思 MVEL code-node script."
@@ -0,0 +1,46 @@
---
name: ekuaibao-nodes
description: |
合思(易快报)工作流节点批量开通工具。
当用户提到"合思"、"易快报"、"ekuaibao"、"工作流节点"、"开通节点"时使用。
---
# 合思工作流节点开通
批量开通合思工作流节点。
节点名称与 type 对照见 [灰度节点清单](references/gray-nodes.md)。 **`nodes` 参数填清单中的 `type` 列值(如 `code`、`risk`),不是中文名。** 遇到同名节点或用户只提供模糊名称时,先根据 type 核对并向用户确认。
## 参数提取
用户通常会贴浏览器请求(curl),从请求中自动提取参数:
| 参数 | 提取位置 | 说明 |
|------|----------|------|
| token | Header `accesstoken` 或 Cookie `ekb-access-token` | accessToken |
| corpId | Header `corpid` 或 URL query `corpId` | 企业 ID |
| baseUrl | URL 协议+域名部分(如 `https://dd2.hosecloud.com`) | 自定义合思地址 |
| nodes | 向用户确认 | 节点名,逗号分隔 |
**域名判断**:URL 不是 `*.hosecloud.com` 而是 `dd2.hosecloud.com` 这类就是自定义域名,必须提取为 `baseUrl`。
## 执行
```bash
curl -s -X POST 'https://d9jxeccs5j.sealosgzg.site/hose-workflow-node' \
-H 'Content-Type: application/json' \
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
```
可选参数:
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
## 结果处理
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
**失败排查**:
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
- `认证失败` + 其他 — token 过期,让用户重新获取
- 节点名错误 — 核对名称拼写
@@ -0,0 +1,119 @@
# 灰度节点清单
来源:`合思工作流开通节点_节点开通-节点列表_灰度节点.csv`。共 109 条非空记录,去重后 108 条。
开通请求的 `nodes` 使用本表的 **`type` 列值**(第三列),如 `code`、`risk`。第二列"节点名称"仅用于展示和核对。
> 注意:`数据映射`有两个可用类型(`mapping`、`dmn`);同名节点需先与用户确认具体类型。`单据查询详情(跨租户)`在源文件中有重复记录,以下仅保留一条。
| 显示名称 | 节点名称(nodes) | type |
| --- | --- | --- |
| JS节点(新) | JS节点(新) | `code-js2` |
| 重算审批流 | 重算审批流 | `recalculate-the-approval-flow` |
| 提示框 | 提示框 | `ui-notification` |
| 定时任务节点 | 定时任务节点 | `start` |
| 推送飞书消息 | 推送飞书消息 | `feishu-sendMsg` |
| 飞书消息 | 飞书消息 | `message-feishu` |
| if节点 | if节点 | `if` |
| http节点 | http节点 | `http` |
| 遍历数组 | 遍历数组 | `loop` |
| 循环节点 | 循环节点 | `while` |
| 企业微信开放平台获取子部门ID列表 | 企业微信开放平台获取子部门ID列表 | `wecom-department` |
| 易桥参数转化 | 易桥参数转化 | `eBridge-mapData` |
| 代码节点 | 代码节点 | `code` |
| 数据映射 | 数据映射 | `mapping` |
| 纷享销客鉴权 | 纷享销客鉴权 | `fxiaoke-auth` |
| 纷享销客数据列表 | 纷享销客数据列表 | `fxiaoke-list` |
| NetSuite数据列表 | NetSuite数据列表 | `netsuite-sync` |
| NetSuite数据创建 | NetSuite数据创建 | `netsuite-create` |
| 易桥鉴权 | 易桥鉴权 | `ebridge-auth` |
| 新增业务对象数据 | 新增业务对象数据 | `ekuaibao-datalink-create` |
| 定时触发 | 定时触发 | `clock` |
| 纷享销客触发器 | 纷享销客触发器 | `fxiaoke-trigger` |
| 到达业务对象数据中的日期时触发 | 到达业务对象数据中的日期时触发 | `ekuaibao-datalink-time-trigger` |
| 发送邮件 | 发送邮件 | `email` |
| 查找业务对象数据 | 查找业务对象数据 | `ekuaibao-datalink-filter` |
| 修改业务对象数据 | 修改业务对象数据 | `ekuaibao-datalink-edit` |
| NetSuite数据删除 | NetSuite数据删除 | `netsuite-delete` |
| 薪人薪事触发器 | 薪人薪事触发器 | `xrxs-trigger` |
| 新增业务对象数据时触发 | 新增业务对象数据时触发 | `ekuaibao-datalink-create-trigger` |
| 变更业务对象数据时触发 | 变更业务对象数据时触发 | `ekuaibao-datalink-change-trigger` |
| 单据审批事件触发器 | 单据审批事件触发器 | `ekuaibao-flowform-trigger` |
| 发送短信 | 发送短信 | `message` |
| webhook触发器 | webhook触发器 | `webhook` |
| 对话框 | 对话框 | `ui-dialog` |
| 流程日志 | 流程日志 | `task-log` |
| 动态节点测试 | 动态节点测试 | `task-dynamic-test` |
| 条件节点 | 条件节点 | `condition` |
| OpenAPI | OpenAPI | `task-openapi` |
| 终止节点 | 终止节点 | `stop` |
| 收集节点 | 收集节点 | `context` |
| 到达单据日期时触发 | 到达单据日期时触发 | `flow-change-trigger` |
| 获取钉钉考勤 | 获取钉钉考勤 | `task-dynamic-ding-attendance` |
| 摊销节点 | 摊销节点 | `apportion` |
| 创建单据 | 创建单据 | `flow-create-task` |
| 站内信 | 站内信 | `message-internet` |
| 钉钉消息 | 钉钉消息 | `message-dingtalk` |
| 修改角色 | 修改角色 | `role-update` |
| 依次执行 | 依次执行 | `every` |
| 查询申请事项详情 | 查询申请事项详情 | `ekuaibao-requision-detail` |
| 查询单据详情 | 查询单据详情 | `flow-detail` |
| 查询单据历史详情 | 查询单据历史详情 | `flow-detail-versioned` |
| 业务对象数据按钮触发 | 业务对象数据按钮触发 | `datalink-button-trigger` |
| 查找行程数据 | 查找行程数据 | `ekuaibao-tmc-datalink-filter` |
| 新增行程数据时触发 | 新增行程数据时触发 | `ekuaibao-tmc-datalink-create-trigger` |
| 变更行程数据时触发 | 变更行程数据时触发 | `ekuaibao-tmc-datalink-change-trigger` |
| 到达行程日期时触发 | 到达行程日期时触发 | `ekuaibao-tmc-datalink-time-trigger` |
| 查询发票 | 查询发票 | `ekuaibao-invoice-datalink-filter` |
| 结果输出 | 结果输出 | `output` |
| EBOT触发 | EBOT触发 | `ekuaibao-ebot-trigger` |
| 补充发票触发 | 补充发票触发 | `other-event-trigger` |
| 发票验真 | 发票验真 | `invoice-verification` |
| JS节点 | JS节点 | `code-js` |
| 数据转化 | 数据转化 | `data-convert` |
| 新摊销 | 新摊销 | `amortization` |
| 数据映射 | 数据映射 | `dmn` |
| 查询人员 | 查询人员 | `ekuaibao-staff-filter` |
| 查询单据列表 | 查询单据列表 | `flow-list` |
| HAB触发器 | HAB触发器 | `hab-trigger-task` |
| 申请事项触发器 | 申请事项触发器 | `ekuaibao-requisition-trigger` |
| 创建部门 | 创建部门 | `department-create` |
| 部门查询 | 部门查询 | `department-filter` |
| 新增人员 | 新增人员 | `staff-create` |
| 查询随手记列表 | 查询随手记列表 | `ekuaibao-ecard-fee-filter` |
| 查询人员详情 | 查询人员详情 | `ekuaibao-staff-detail` |
| 查询部门详情 | 查询部门详情 | `ekuaibao-department-detail` |
| 查询易商卡申请事项列表 | 查询易商卡申请事项列表 | `ekuaibao-ecard-requisition-filter` |
| 查询飞书部门 | 查询飞书部门 | `feishu-department-filter` |
| 修改部门 | 修改部门 | `ekuaibao-department-update` |
| 站外信 | 站外信 | `message-outnet` |
| AI节点 | AI节点 | `ekb-ai` |
| 修改单据 | 修改单据 | `flow-update-task` |
| 提取文本(word,PDF) | 提取文本(word,PDF) | `ekb-ai-pdf` |
| 单据风险写入 | 单据风险写入 | `risk` |
| 天润工单查询 | 天润工单查询 | `tr-select` |
| 天润工单评论 | 天润工单评论 | `tr-comment` |
| 天润工单查询详情 | 天润工单查询详情 | `tr-detail` |
| Dify接入 | Dify接入 | `dify` |
| 图片URL识别 | 图片URL识别 | `ekb-ai-url` |
| AI文本理解 | AI文本理解 | `ekb-minimax-text` |
| AI图像理解 | AI图像理解 | `ekb-minimax-photo` |
| 查询角色下的人员 | 查询角色下的人员 | `search-staff-by-role` |
| 发票巡检 | 发票巡检 | `ekuaibao-invoice-inspector` |
| 招商银行商务卡查询 | 招商银行商务卡查询 | `task-zs` |
| 单据查询详情(跨租户) | 单据查询详情(跨租户) | `escape` |
| 海亮单据查询详情 | 海亮单据查询详情 | `hl-detail` |
| 单据查询详情AI审批专用 | 单据查询详情AI审批专用 | `mapping-detail` |
| 海亮数据集列表 | 海亮数据集列表 | `hl` |
| 查询易商卡流水的费用信息 | 查询易商卡流水的费用信息 | `ekuaibao-ecard-fee-detail-filter` |
| Ebot审批 | Ebot审批 | `ebot-approval-flow` |
| 给OA账号发送提醒 | 给OA账号发送提醒 | `oa` |
| 查询历史单据测试集 | 查询历史单据测试集 | `flow-sample-list` |
| 分类汇总 | 分类汇总 | `aggregation` |
| 单据转译节点 | 单据转译节点 | `flow-format` |
| 导出表格 | 导出表格 | `excel` |
| AI附件理解 | AI附件理解 | `ai-attachment` |
| AI智能匹配 | AI智能匹配 | `ai-classification` |
| AI智能提取 | AI智能提取 | `ai-extraction` |
| 延迟执行节点 | 延迟执行节点 | `task-dynamic-delay` |
+85
View File
@@ -0,0 +1,85 @@
# 合思 AI PRO 确定性审批仲裁网关 (Approval Gateway & AI PRO Guide)
本参考专卷面向开发者与 AI 智能体,系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
---
## 1. 架构与定位
- **双向命令入口**:可通过独立二进制 `hose-aipro <子命令>` 或统一入口 `hose-use aipro <子命令>` 唤起。
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/config.json` 与 `enterprises` 凭证目录)。
- **零源码阅读自省**:运行 `hose-aipro status` 或 `hose-use context` 即可直接构建完整的运行时上下文,无需翻阅代码。
- **强确定性硬条款阻断**:AI 仅负责事实核验打标(PASS / FAIL / SKIP);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】分级硬编码规则仲裁,物理切断幻觉可能导致的违规放行。
---
## 2. 核心工作流与命令
### 步骤 0:查看运行上下文与当前绑定企业
```bash
hose-aipro status
hose-aipro status --json
```
- 输出当前连接的企业 ID/名称、操作员工号、Token 有效期、已加载场景库统计与待决断会话数。
### 步骤 1:查看规约场景索引库
```bash
hose-aipro scopes
# 或使用 hose-use:
hose-use rule scopes
```
- 输出本地 SQLite 数据库中所有生效场景(如 `#1 差旅报销`、`#2 业务招待`)及规则条数。
### 步骤 2:查看场景审核要点清单
```bash
hose-aipro points 1
# 或通过场景名称:
hose-aipro points 差旅报销
```
- 查看场景下的所有审核要点、判定依据与严格级别(`硬性` / `弹性` / `建议` / `特殊`)。
### 步骤 3:为单据挂载审核要点清单
```bash
hose-aipro bind S26000001 1
```
- 将场景 #1 的要点清单初始化并绑定至单号 `S26000001`。
### 步骤 4:查看单据审核清单与核验进度
```bash
hose-aipro checklist S26000001
```
- 检查当前单据下各要点的打标状态(`PENDING` / `PASS` / `FAIL` / `SKIP`)。
### 步骤 5:逐项录入事实核验打标
```bash
# 批量快速打标:
hose-aipro review S26000001 --eval "1=PASS:发票合规; 2=FAIL:住宿超标; 3=SKIP"
# 单项精准打标:
hose-aipro review S26000001 --point 2 --status FAIL --reason "住宿费超过差旅标准 200 元"
```
### 步骤 6:确定性网关仲裁与审批执行
```bash
# 预审仿真 (Dry Run - 仅仲裁不改变下游单据状态):
hose-aipro decide S26000001
# 真实驱动下游执行 (需加 --apply --yes 确认):
hose-aipro decide S26000001 --apply --yes
```
### 步骤 7:审计流水全流程追溯
```bash
hose-aipro logs [单号]
```
- 追溯单据从初始化、打标到决断的每一步本地不可篡改审计记录。
---
## 3. 规约语法与严格程度等级
规则正文中必须包含合法的条款判定标记:
- `[必须上传真实发票]{硬性}`:硬性条款违规时,网关物理阻断同意操作,必须驳回。
- `[尽量提供行程水单]{弹性}`:弹性条款允许按策略放行或转人工复核。
- `[建议补充备注说明]{建议}`:仅作提醒,不构成驳回条件。
- `[金额大于10万需特殊说明]{特殊}`:直接触发人工会签或复核分支。
+68 -2
View File
@@ -2,6 +2,21 @@
本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。
## 0. 全局运行上下文与环境自省 (`context`)
面向开发者与 AI 智能体的一键自省命令。**无需翻阅任何源码**即可直接获知当前登录主账号、当前激活企业、操作工号、Token 状态、多企业列表统计、AI PRO 规约库及配置文件路径。
```bash
# 文本格式仪表盘
hose-use context
# 结构化 JSON 输出 (推荐 Agent 首选使用)
hose-use context --json
```
- **别名**:`hose-use status`, `hose-use whoami`, `hose-use env`
- **两端互通**:`hose-use` 与 `hose-aipro` 共享同一套企业与身份凭证上下文。
---
## 1. 账号认证与登录 (`auth`)
@@ -27,15 +42,58 @@ hose-use auth refresh
```
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
### 第三方免密/协助链接一键导入与自动提权持久化 (`corps add-link` / `auth add-link`)
```bash
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接(默认自动探测并持久化保存 OpenAPI appKey + appSecurity)
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..." --yes
# 显式强制要求提取 OpenAPI 持久化密钥(多套密钥时可附加 --app-key 或 --force)
hose-use corps add-link "<url>" --elevate --force --overwrite --yes
# 未提供服务端 expTime 时,可显式指定本地有效期
hose-use corps add-link "<url>" --ttl 3d --yes
```
- **全自动识别与双通道持久化**:
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员;
- **自动提取 OpenAPI 持久化密钥**:导入链接或账密登录时,自动尝试调用 `/api/innerapi/v1/key` 提取企业启用状态的 `appKey + appSecurity` 并写入 `enterprises/<corpId>.json`;
- **双通道无感自动续期**:当会话 `accessToken` 过期时,客户端优先尝试用户级主账号 (`cloudAuthToken`) 换票,或自动通过企业级 OpenAPI 持久化密钥调用 `/api/openapi/v1/auth/getAccessToken` + `/api/openapi/v1.1/provisional/getProvisionalAuth` 签发全新会话令牌并落盘,彻底告别临时链接过期失效。
### 生成企业合思 Web 免密登录直达链接 (`corps link` / `auth hose-link`)
```bash
# 为已配置企业生成 2 小时有效期的 Web 免密直达链接 (thirdparty.html)
hose-use corps link 新转转集团
hose-use corps link ID01PH4Q5CJboX --json
hose-use auth hose-link --corp=ID01PH4Q5CJboX
```
- 若企业已配置 OpenAPI `appKey + appSecurity`,直接调用 `getProvisionalAuth` 动态签发全新的 `thirdparty.html` 免密登录链接;
- 若企业尚未持久化密钥,会先尝试利用当前有效会话自动提权提取 `appKey + appSecurity`,再签发直达链接。
### OpenAPI 持久化密钥直接接入与存量提权 (`add-persistent` / `extract-keys` / `elevate`)
```bash
# 1. 直接使用 appKey + appSecurity 持久化接入企业(自动探测 6 大合思域名与主管理员)
hose-use corps add-persistent --app-key=<key> --app-security=<secret> --force --yes
# 2. 从协助链接中提取查看 OpenAPI 密钥(附加 --save --yes 可直接持久化落盘)
hose-use corps extract-keys "<url>"
hose-use corps extract-keys "<url>" --save --yes
# 3. 为本地已配置企业(或 --all 全部企业)提取并持久化保存 OpenAPI 密钥
hose-use corps elevate ID01PH4Q5CJboX --yes
hose-use corps elevate --all --yes
hose-use keys --corp=ID01PH4Q5CJboX --save --yes
```
### 代客协助凭证导入
```bash
hose-use auth import \
--name="CSM代客" \
--corp-id="Cxa3oOtQi2eS$g" \
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b" \
--yes
```
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
### 多账号清单
```bash
@@ -53,6 +111,14 @@ hose-use corps list
hose-use corps list --json
```
### 模糊搜索企业 (`corps search` / `corps find`)
```bash
# 支持根据企业名称、企业 ID、员工工号、员工姓名或所属账号模糊搜索
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps search 周某某 --json
```
### 切换当前活跃企业
```bash
hose-use corps switch uzU7pcWfScck00
+50 -25
View File
@@ -15,15 +15,31 @@ hose-use bill list
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)。
### 过滤与检索选项
- `--keyword=<keyword>` / `-k`: 按关键字模糊搜索,原生走服务端 `INSTR` 索引检索;
- `--search-fields=<fields>` / `--sf`: 指定 keyword 检索匹配的字段列表,默认 `name,code,form`;可传入单字段(如 `--search-fields=name` 或 `--search-fields=code`)或逗号分隔字段列表(如 `--search-fields=name,form`),服务端自动组装为嵌套复合 OR 检索;
- `--code=<code>` / `-c`: 按单据编号(单号)服务端索引精准匹配;
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿);
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`);
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
- `--distinct`: 是否对单据记录去重。
```bash
# 查询审批通过的差旅报销单
hose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50
# 跨单据名称与表单字段检索含“打车”的最近 7 天单据
hose-use bill list --keyword=打车 --search-fields=name,form --since=7d
# 仅按单据名称检索
hose-use bill list --keyword=差旅 --search-fields=name --count=10
# 按精确单号服务端极速定位
hose-use bill list --code=CL20260901001
# 查询近 30 天已支付的报销单
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
```
---
@@ -41,8 +57,8 @@ hose-use bill flow CL20260903001
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
```bash
hose bill get S26000001 --risk
hose bill get S26000001 --risk --json
hose-use bill get S26000001 --risk
hose-use bill get S26000001 --risk --json
```
### 中文字段智能映射字典
@@ -74,19 +90,19 @@ hose-use bill risk CL20260903001
```bash
# 同意:可附带纯文本审批意见
hose bill approve S26000001 --comment "同意" --yes
hose-use bill approve S26000001 --comment "同意" --yes
# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标
hose bill reject S26000001 --comment "请补充发票" --yes
hose-use bill reject S26000001 --comment "请补充发票" --yes
# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名
hose bill transfer S26000001 --approver-id 111 --yes
hose-use bill transfer S26000001 --approver-id 111 --yes
# 加签:默认前加签,--mode post 表示后加签
hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
hose-use bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
# 评论:支持 --participants 传入逗号分隔的人员 ID
hose bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
hose-use bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
```
动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。
@@ -96,8 +112,8 @@ hose bill comment S26000001 --comment "补充说明" --participants <staffId> --
读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID:
```bash
hose bill refs S26000001
hose bill refs S26000001 --json
hose-use bill refs S26000001
hose-use bill refs S26000001 --json
```
JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。
@@ -107,8 +123,8 @@ JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTyp
从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树:
```bash
hose bill relations S26000001
hose bill relations S26000001 --json
hose-use bill relations S26000001
hose-use bill relations S26000001 --json
```
表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。
@@ -118,8 +134,8 @@ hose bill relations S26000001 --json
读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段:
```bash
hose bill budget S26000001
hose bill budget S26000001 --json
hose-use bill budget S26000001
hose-use bill budget S26000001 --json
```
### 单据附件列表 (`bill attachments`)
@@ -127,18 +143,18 @@ hose bill budget S26000001 --json
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
```bash
hose bill attachments S26000001
hose bill attachments S26000001 --json
hose-use bill attachments S26000001
hose-use 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
hose-use bill download S26000001 --output-dir ./downloads
hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
```
## 5. 单据实体元数据字典 (`bill schema`)
## 5. 单据实体元数据字典 (`bill schema`) 与单据模板规格诊断 (`bill spec`)
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
@@ -147,6 +163,15 @@ hose-use bill schema
hose-use bill schema --json
```
当需要查看某个具体单据/申请模板(如工作流 `flow-create-task` 节点绑定的 `specificationId`)的完整字段列表、必填属性、赋值优先级(`priorityList`)以及字段联动覆盖规则(`assignmentRule` / `isLinkageAssignment`)时,使用 `bill spec`(同义别名:`feetype spec`):
```bash
hose-use bill spec ID01TxgE3fhD6n
hose-use bill spec ID01TxgE3fhD6n --json
```
该命令会自动标记所有配置了 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`(自动联动高于手动填写/工作流传入)的业务对象字段,帮助快速排查“工作流传入字段被单据模板联动静默清空或覆盖”的隐蔽问题。
---
## 6. 上下文防爆保护与安全转储
+13 -13
View File
@@ -9,8 +9,8 @@
企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**
因此,`hose-use` 遵循以下防爆安全原则:
1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
1. **搜索优先 (Search First)**:优先使用 `hose-use contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
2. **列表默认限流截断 (Default Limit 20)**:`hose-use contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;
4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。
@@ -20,22 +20,22 @@
```bash
# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)
hose contact search 王硕
hose contact search xiezihao@hosecloud.com
hose contact search 18600612659
hose-use contact search 王硕
hose-use contact search xiezihao@hosecloud.com
hose-use contact search 18600612659
# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)
hose contact list
hose contact list --limit=50
hose-use contact list
hose-use contact list --limit=50
# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)
hose contact list --json -o /tmp/all_staffs.json
hose-use contact list --json -o /tmp/all_staffs.json
# 4. 精确下钻查看指定人员详细档案
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000
# 5. 指定特定企业租户检索
hose contact search 李 --corp=ID01MCcOgJl1td
hose-use contact search 李 --corp=ID01MCcOgJl1td
```
---
@@ -60,6 +60,6 @@ hose contact search 李 --corp=ID01MCcOgJl1td
### 1. 查找某人发起的单据
当用户要求“帮我查一下王硕提交的报销单”时:
1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。
1. 先通过 `hose-use contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose-use bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose-use bill link <单号>` 生成官方 Web 直达链接反馈给用户。
+4 -4
View File
@@ -4,12 +4,12 @@
```bash
# 查看系统/自定义档案维度目录
hose dimension list
hose dimension list --keyword=项目
hose-use dimension list
hose-use dimension list --keyword=项目
# 查看某个维度的档案项(支持维度 ID、编码或名称)
hose dimension items 项目
hose dimension items DA001 --json
hose-use dimension items 项目
hose-use dimension items DA001 --json
```
目录来源于 `/api/v1/basedata/dimensions/active`,档案项来源于 `/api/v1/basedata/dimensionItems/$<dimensionId>`。结果在同一进程内按企业缓存 10 分钟,JSON 会保留底层 ID、编码、父项 ID 和表单字段。
+33
View File
@@ -0,0 +1,33 @@
# 费用类型与表单字段规格管理 (feetype)
费用类型 (FeeType) 是合思/易快报费控系统的底层核心业务实体,涵盖企业报销科目树、单据表单字段规则规格以及申请/报账控件配置。
## 常用命令
```bash
# 1. 列表与树形层级
hose-use feetype list # 树形层级展示当前企业所有活跃费用类型
hose-use feetype list --all # 包含已停用的全量费用类型
hose-use feetype list --keyword="差旅" # 模糊搜索名称、编码或路径
hose-use feetype list --flat # 以平铺表格格式展示
hose-use feetype list --json # JSON 结构化输出 (Agent 推荐)
# 2. 单项详情与字段规格
hose-use feetype get 交通费 # 查看费用类型基本配置、层级与父子节点
hose-use feetype get 交通费 --specs # 同时输出报账字段与申请字段配置摘要
hose-use feetype fields 交通费 # 查看完整的报账与申请字段表格 (字段名、类型、必填、可编辑)
# 3. 创建与修改 (增改)
hose-use feetype create --name="市内打车费" --parent="交通费" # 在指定父级下创建,自动继承父级字段规则
hose-use feetype create --name="公杂费" --code="COST88" # 自定义编码并建在顶级
hose-use feetype update 市内打车费 --desc="包含出租车与网约车" # 修改描述或属性
hose-use feetype update 市内打车费 --color="#4caf50" # 修改标识颜色
# 4. 停用与启用 (删查)
hose-use feetype disable 市内打车费 # 停用费用类型 (软删除,用户端隐藏)
hose-use feetype enable 市内打车费 # 重新启用费用类型 (支持 --recursive 级联启用)
# 5. 调整层级结构
hose-use feetype move 市内打车费 --parent="差旅费用" # 移动至差旅费用之下
hose-use feetype move 市内打车费 --parent=root # 移至企业顶级根节点
```
+7 -7
View File
@@ -3,13 +3,13 @@
消息中心是 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
hose-use message list --unread
hose-use message list --read
hose-use message list --all
hose-use message list --type=Approve
hose-use message count
hose-use message read <messageId>
hose-use message read-all
```
`message list --json` 返回消息 ID、标题、内容、消息类型、已读状态和原始字段;`--all` 会并行拉取已读与未读页面并去重后按时间排序;`--type` 在 CLI 层按 `messageType`、`msgType`、`msgTypeName` 或 `msgName` 做兼容过滤。`message read-all` 会分页读取全部未读消息再逐条标记,避免只处理首 100 条。
+7 -7
View File
@@ -3,11 +3,11 @@
角色页对应的只读 CLI:
```bash
hose role list
hose role list --keyword=财务
hose role groups
hose role members 财务主管
hose role members CODE15 --json
hose-use role list
hose-use role list --keyword=财务
hose-use role groups
hose-use role members 财务主管
hose-use role members CODE15 --json
```
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
@@ -15,6 +15,6 @@ hose role members CODE15 --json
权限页的角色权限快照:
```bash
hose permission get
hose permission get --json
hose-use permission get
hose-use permission get --json
```
+36
View File
@@ -0,0 +1,36 @@
# OpenAPI 密钥与应用中心
本专卷覆盖 v0.8.1 引入的企业 OpenAPI 接入密钥查询,以及企业已购应用和合思应用商店探查。执行前先确认目标企业;可用 `hose-use context --json` 或 `hose-use corps list`,跨企业任务优先显式传入 `--corp=<id>`。
## 密钥查询 (`keys`)
```bash
hose-use keys # 当前企业的密钥列表,appSecurity 默认脱敏
hose-use keys --json # 结构化结果,appSecurity 仍默认脱敏
hose-use openapi keys # 同一能力的 OpenAPI 别名
hose-use store keys # 同一能力的 store 别名
hose-use keys --reveal # 用户明确要求时才显示完整 appSecurity
```
`keys` 返回密钥备注、`appKey`、状态和创建时间。`appSecurity` 是接入密码:默认输出会遮罩;`--reveal`/`-r`/`--plain` 才请求完整值。
安全边界:
- 没有用户明确授权时,不要使用 `--reveal`,也不要从结果中推断或复述明文密钥。
- 不要把明文密钥放进聊天、日志、命令历史、提交内容或共享目录;不要使用 `--reveal -o <path>`。
- 只需判断密钥是否存在、状态或匹配某个 `appKey` 时,使用默认脱敏输出即可。
- 需要交给脚本处理时优先使用不带 `--reveal` 的 `--json`;若确实必须取得明文,先确认接收方和落盘位置,再尽量短暂使用并及时清理。
## 应用中心与应用商店 (`store`)
```bash
hose-use store list # 当前企业已购/已开通应用
hose-use store list --all # 请求完整已购应用列表
hose-use store list <关键词> # 按名称或简介筛选已购应用
hose-use store search <关键词> # 搜索应用商店商品
hose-use store get <应用ID> # 查看商品详情;ID 可带或不带前导 $
```
`store list` 展示应用 ID、名称、开通状态、有效期限、配置支持和绑定能力;`store search` 返回商店结果总数及当前结果;`store get` 用于查看指定应用的详情。上述命令均支持 `--json`,适合 Agent 解析。
若用户说“查 OpenAPI 密钥”,路由到 `keys`;若用户说“看企业买了什么应用/查应用市场”,路由到 `store list` 或 `store search`;若已有应用 ID,再用 `store get` 下钻。`openapi keys` 与 `store keys` 只作为 `keys` 的兼容别名。
+9 -9
View File
@@ -3,15 +3,15 @@
## 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
hose-use task todo # 待我审批
hose-use task approved # 我已审批
hose-use task records # 审批记录
hose-use task submitted # 我发起的单据
hose-use task cc --unread # 未读抄送
hose-use task cc --read # 已读抄送
hose-use task todo --staff <员工工号或ID> # 在当前页结果中按人员过滤
hose-use task todo --json --count 50
hose-use task records --from 2026-01-01 --to 2026-09-05
```
任务结果包含任务 ID、流程 ID、单号、标题、单据模板、提交人、金额、状态、当前节点和可用动作。分页使用 `--start` 与 `--count`。
+192 -22
View File
@@ -1,42 +1,111 @@
# 工作流与自建应用指南 (Workflow & Platform Guide)
# 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide)
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。
> **核心概念辨析(严禁混淆)**:
> - **【应用管理】(唯一命令:`hose-use app`)**:对应合思桌面端顶层一级导航【应用管理】。聚合了企业为员工开通的**全部前台业务落地应用**,既包括用车补贴、用车制度、E商卡等官方套件与制度,也包括新转转集团、差旅申请等挂载了视图的自建应用前台入口。
> - **【自建应用】(唯一命令:`hose-use platform` / `datalink`)**:对应企业后台【应用中心 -> 自建应用】(开放平台/PaaS)。负责业务对象建模(entities)、字段定义(schema)、权限快照与底层业务记录(records)。**切勿将自建应用称为“应用管理”**。
> - **【工作流】(唯一命令:`hose-use workflow`)**:自建应用下的任务流水线、拓扑节点(如自定义 JS 脚本 `code-js2`、Webhook 通知等)。
---
## 1. 自建应用管理 (`platform`)
## 1. 应用管理 (`app`)
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
查看员工工作台开通的业务应用列表与详情:
```bash
# 列出当前企业下全部已开通的自建应用
hose-use platform list
hose-use platform list --json
```
# 列出工作台开通的全部业务应用(用车、制度、模板、自建前台等)
hose-use app list
hose-use app list --keyword="差旅"
hose-use app list --json
**输出关键字段**:
- `appId`:应用全局唯一标识
- `appName`:应用中文名称
- `status`:应用运行状态(ENABLE / DISABLE)
- `createdAt` / `updatedAt`:创建与最后更新时间
# 查看某个应用的详情与配置
hose-use app get 用车补贴
hose-use app get ID01RKbEvQsWbd
```
---
## 2. 跨应用工作流聚合检索 (`workflow list`)
## 2. 自建应用与数据模型 (`platform` / `datalink`)
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
合思企业支持创建多个自建应用,每个自建应用可承载多个业务对象、字段模型与业务数据记录:
```bash
# 列出当前企业下全部已开通的自建应用平台
hose-use platform list
hose-use platform list --json
# 查看指定自建应用包含的业务对象清单
hose-use platform entities 新转转集团
# 查看业务对象的完整字段定义(schema)
hose-use platform schema 新转转集团 合同
hose-use platform schema 新转转集团 合同 --keyword="金额"
# 检索业务对象的底层真实数据记录(支持 --all 自动翻页拉取全量记录)
hose-use platform records 新转转集团 合同 --limit=5
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
hose-use platform records 新转转集团 支付计划表 --all --json -o /tmp/payment_plans.json
```
### 2.1 业务对象记录操作 (`platform record`) 与安全全量合并 (Read-Modify-Write)
> **关键防坑说明**:合思 DataLink `PUT /api/v2.2/datalink/platformDataLink/$id` 是**整单覆盖接口**,而非局部 PATCH。若只传修改的 1 个字段,未传字段会被清空、对象引用若未提取 `.id` 会报 417、`visibility` 漏传会导致全员不可见。`hose-use platform record edit` 与 `batch-edit` 默认内置 **Read-Modify-Write 安全合并引擎**,自动拉取原记录与 Schema、归一化嵌套引用 ID、保留全部存量字段与 `visibility` 权限,并支持字段中英文短名自动解析。
```bash
# 1. 查看单条记录详情 (支持直接传 recordId 免传应用与业务对象)
hose-use platform record get ID01TqE4yUG6hF
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF --json
# 2. 切换记录停用/启用状态 (默认自动翻转,支持 --state 显式指定)
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --dry-run
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false --yes # 停用
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true --yes # 启用
# 3. 安全编辑单条记录字段 (默认 Read-Modify-Write 安全合并,支持字段短名/中文标签)
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --dry-run
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --yes
# 4. 批量安全编辑多条记录 (支持 --ids / --filter / --file,内置并发控制与逐条 diff 预览)
hose-use platform record batch-edit 新转转集团 支付计划表 \
--ids=ID01A,ID01B \
--data='{"我方签约主体":"ID01RnG3b79daL"}' \
--dry-run
hose-use platform record batch-edit 新转转集团 支付计划表 --file=./patches.json --yes
# 5. 重新计算记录关联的全部台账
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF --yes
```
### 2.2 业务对象健康度巡检 (`platform audit`)
一键扫描指定业务对象全量记录的三大高频隐患,并自动生成可直接用于修复的 `suggestedPatches`:
1. **必填/关键字段缺失 (`MISSING_FIELD`)**:检测 Schema 必填字段或 `--check-fields` 指定字段为空的记录;
2. **引用已停用档案 (`DISABLED_REFERENCE`)**:检测引用字段指向 `active: false` 档案的记录;
3. **跨台账冗余字段失步 (`CROSS_LEDGER_MISSING_SYNC` / `CROSS_LEDGER_MISMATCH`)**:当子台账(如《支付计划表》)关联父台账(如《合同流程》)且存在同名冗余字段(如 `我方签约主体`)时,自动比对子表与父表值是否一致,若父表有值而子表缺失则自动生成修复补丁。
```bash
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体"
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体" --active-only --json
```
---
## 3. 跨应用工作流聚合检索 (`workflow list`)
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描(同时支持 `--platform-id` 与 `--app-id`):
```bash
# 查看所有自建应用下的全部工作流汇总
hose-use workflow list
# 查看指定自建应用下的工作流
hose-use workflow list --app-id=app_01j72x...
hose-use workflow list --app-id=ID01RKbEvQsWbd
```
---
## 3. 工作流任务节点精准扫描 (`workflow find`)
## 4. 工作流任务节点精准扫描 (`workflow find`)
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
@@ -53,7 +122,7 @@ hose-use workflow find --keyword="自动审批"
---
## 4. 工作流详情查询 (`workflow get`)
## 5. 工作流详情查询 (`workflow get`)
获取工作流的完整节点拓扑、参数配置与表达式定义:
@@ -64,7 +133,7 @@ hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
---
## 5. 工作流启用与关闭 (`workflow toggle`)
## 6. 工作流启用与关闭 (`workflow toggle`)
```bash
# 激活/启用指定工作流
@@ -74,10 +143,111 @@ hose-use workflow toggle wf_01k83y... --enable
hose-use workflow toggle wf_01k83y... --disable
```
## 6. 工作流静态分析 (`workflow analyze`)
## 7. 工作流静态分析 (`workflow analyze`)
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。内置以下核心风险检测:
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内的创单节点(`flow-create-task`)配置了 `onError.defaultAction === "SKIP"`,且后续台账更新节点(`ekuaibao-datalink-edit`)未守卫创单节点的 `$status`,会导致创单失败时仍将台账状态改成“创建成功”;
- `LINKAGE_PRIORITY_OVERRIDE`:创单节点绑定了 `dataLink` 台账字段,同时目标单据模板对应字段开启了自动联动赋值且优先级 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`,导致单据模板联动静默覆盖工作流显式传入的值。
```bash
hose-use workflow analyze wf_01k83y... --json
hose-use workflow analyze 886351399301758976 --json
```
## 8. 工作流单次运行实例排障 (`workflow job`)
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
```bash
# 1. 查看 Job 概览与顶层节点执行树
hose-use workflow job 892809886382563347
# 2. 直接列出该次运行中所有报错节点、错误原因(outputs.error)及入参快照(含关联业务对象 ID)
hose-use workflow job 892809886382563347 --failed --json
# 3. 展开循环(every)或分支(switch)容器内的子节点迭代明细
hose-use workflow job 892809886382563347 --parent=892809893789696012
# 4. 查看指定节点(如 MVEL 代码节点)的底层控制台输出与异常堆栈
hose-use workflow job 892809886382563347 --logs=892809893789696012
```
## 9. 工作流草稿保存 (`workflow save`)
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
```bash
hose-use workflow get <pipelineId> --json -o workflow.json
# 修改 workflow.json 中的 tasks / inputs / $snapshot 等字段
hose-use workflow save <pipelineId> --file=workflow.json
```
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
## 10. 本地节点草稿修改 (`workflow patch`)
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
```bash
hose-use workflow patch <pipelineId> \
--file=workflow.json \
--path=tasks.1.form.title \
--value="新的标题" \
--output=workflow.patched.json
```
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
## 11. 工作流版本历史 (`workflow history`)
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
```bash
hose-use workflow history <pipelineId> --json
```
## 12. 运行日志与错误管道提醒 (`workflow logs` / `workflow check`)
查询单个工作流的运行日志(表格默认展示 `successTaskCount`、`errorTaskCount`、`hasError`;即使工作流整体状态因 `SKIP` 显示为 `COMPLETED`,也可通过 `--has-error` 精准揪出内部含报错节点的运行记录):
```bash
hose-use workflow logs <pipelineId> --has-error
hose-use workflow logs <pipelineId> --state=FAILED --json
```
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
```bash
hose-use workflow check --json
hose-use workflow check --json --fail-on-alert
```
## 13. 发布工作流 (`workflow publish`)
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
```bash
hose-use workflow publish <pipelineId>
```
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
---
## 14. 工作流排障与创单排错三大黄金法则(必读)
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
### 法则一:先跑 `workflow analyze <pipelineId>` 排除停用与静默吞错
- 检查是否命中 `WORKFLOW_DISABLED`(许多名为“【生产】xxx”的工作流实际处于 `state: 0` 停用状态,切勿被名称误导);
- 检查是否命中 `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`(`every` 循环中 `flow-create-task` 配置了失败跳过 `SKIP`,导致外层 Job 状态变为 `COMPLETED`,且后续 `ekuaibao-datalink-edit` 无视创单失败直接把台账改成“已发起”)。
### 法则二:用 `workflow logs --has-error` 与 `workflow job <jobId> --failed` 直击真实报错与源记录 ID
- 不要只看 `--state=FAILED`!只要节点配置了 `SKIP`,Job 顶层 `state` 就会是 `COMPLETED`,必须用 `hose-use workflow logs <pipelineId> --has-error` 找出 `errorTaskCount > 0` 的 `jobId`;
- 拿到 `jobId` 后,立即执行 `hose-use workflow job <jobId> --failed --json`,从 `outputs.error` 读取精确报错(例如 `我方签约主体未填写`),并从 `inputs.form` 中提取触发本次创单的源业务对象记录 ID。
### 法则三:遇到“工作流明明传了字段但创单仍报未填”,立即用 `bill spec <specificationId>` 检查联动覆盖优先级
- 当工作流 `flow-create-task` 已经给某字段(如 `u_我方签约主体`)传了值,但仍报该字段未填写时,根因往往在**单据模板字段的赋值优先级 (`priorityList`) 与联动规则 (`assignmentRule`)**:
- 执行 `hose-use bill spec <specificationId>`(或直接看 `workflow analyze` 的 `LINKAGE_PRIORITY_OVERRIDE` 告警);
- 若单据模板中某业务对象字段(如 `u_关联合同流程`)开启了联动赋值,且目标字段的优先级为 `LINKAGE_ASSIGNMENT (自动联动) > MANUALLY_FILL_IN (手动填写/工作流传入)`,则单据保存时会用被关联主表(如《合同流程》)上的字段值强行覆盖工作流传入的值;若主表对应字段为空,工作流传入的值就会被清空!
- 定位到缺失字段的台账记录后,使用 `hose-use platform audit <应用> <对象> --check-fields="..."` 巡检全量存量数据,并用 `hose-use platform record edit` / `batch-edit`(先 `--dry-run` 再 `--yes`)安全修复。
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.7.0",
"version": "0.8.13",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
File renamed without changes.
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.7.0
version: 0.8.13
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+162
View File
@@ -0,0 +1,162 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runAiProCli } from "./aipro-cli.js";
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
import { ApprovalRepository } from "./domains/approval/repository.js";
import { getVersionInfo } from "./version.js";
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置规约规则
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传真实发票]{硬性},[建议填写详细事由]{建议}。",
});
repo.createRule({
scope: "差旅报销",
body: "住宿费标准执行城市限额,[超标住宿必须有前置特批邮件]{硬性}。",
});
});
afterEach(() => {
closeApprovalDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
test("version/help --json only emit machine-readable stdout", async () => {
const version = await runAiProCli(["version", "--json"]);
const help = await runAiProCli(["help", "--json"]);
expect(JSON.parse(version.stdout)).toEqual(getVersionInfo("hose-aipro"));
expect(JSON.parse(help.stdout).help).toContain("hose-aipro");
expect(version.stderr).toBe("");
expect(help.stderr).toBe("");
});
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 1. 创建审批会话
const run = repo.createApprovalRun({
documentSn: "TEST-SN-999",
corpId: "test-corp",
documentSnapshot: "# 单据测试快照",
});
const runId = run.shortId!;
expect(runId).toHaveLength(6);
// 2. bind 挂载规则并拆解为要点清单
const bindRes = await runAiProCli(["bind", "--run", runId, "--rules", "[1, 2]"]);
expect(bindRes.exitCode).toBe(0);
const bindData = JSON.parse(bindRes.stdout);
expect(bindData.length).toBe(3);
expect(bindData[0]["要点编号"]).toBe(1);
expect(bindData[0]["严格程度"]).toBe("硬性");
expect(bindData[0]["归属规则"]).toBe(1);
expect(bindData[0]["审核要点"]).toBe("必须上传真实发票");
expect(bindData[0]["核验状态"]).toBe("待核验");
expect(bindData[1]["要点编号"]).toBe(2);
expect(bindData[1]["严格程度"]).toBe("建议");
expect(bindData[1]["归属规则"]).toBe(1);
expect(bindData[2]["要点编号"]).toBe(3);
expect(bindData[2]["严格程度"]).toBe("硬性");
expect(bindData[2]["归属规则"]).toBe(2);
// 3. 门禁测试:要点处于 PENDING 时,尝试执行 approve 必须被网关阻拦
const block1 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "尝试盲目放行"]);
expect(block1.exitCode).toBe(1);
expect(block1.stderr).toContain("待核验");
// 4. review 事实打标录入(要点 3 硬性违规,缺少特批邮件)
const reviewRes = await runAiProCli([
"review",
"--run",
runId,
"--eval",
"1=PASS:已上传增值税普通发票; 2=PASS:已注明详细出差事由; 3=FAIL:住宿费超标500元且无特批邮件",
]);
expect(reviewRes.exitCode).toBe(0);
const reviewData = JSON.parse(reviewRes.stdout);
expect(reviewData["要点总数"]).toBe(3);
expect(reviewData["已通过"]).toBe(2);
expect(reviewData["未通过"]).toBe(1);
expect(reviewData["待核验"]).toBe(0);
// 5. 门禁测试:硬性违规未通过时,尝试执行 approve 必须被物理一票否决
const block2 = await runAiProCli(["decide", "approve", "--run", runId, "--opinion", "强行同意放水"]);
expect(block2.exitCode).toBe(1);
expect(block2.stderr).toContain("硬性违规条款未通过");
// 6. 门禁测试:审批意见超过 150 字符时,必须被参数校验阻断
const over150Text = "测试超长文字。".repeat(30);
const block3 = await runAiProCli(["decide", "reject", "--run", runId, "--opinion", over150Text]);
expect(block3.exitCode).toBe(1);
expect(block3.stderr).toContain("不可超过 150 字符");
// 7. 正确决策:执行 reject 驳回,提供小于 150 字的专业意见(Dry-run)
const rejectRes = await runAiProCli([
"decide",
"reject",
"--run",
runId,
"--opinion",
"住宿费超标500元且未见前置特批邮件,不符合差旅规约第2条,予以驳回,请补充特批后重提。",
]);
expect(rejectRes.exitCode).toBe(0);
const rejectData = JSON.parse(rejectRes.stdout);
expect(rejectData["会话ID"]).toBe(runId);
expect(rejectData["执行动作"]).toBe("驳回");
expect(rejectData["网关状态"]).toBe("放行");
// 8. 审计监控流水验证:会话账本包含全链路记录
const logsRes = await runAiProCli(["logs", "--run", runId, "--json"]);
expect(logsRes.exitCode).toBe(0);
const logsData = JSON.parse(logsRes.stdout);
const actions = logsData.logs.map((l: any) => l.action);
expect(actions).toContain("bind");
expect(actions).toContain("review");
expect(actions).toContain("decide");
});
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
const run = repo.createApprovalRun({
documentSn: "CLEAN-BILL-001",
corpId: "test-corp",
documentSnapshot: "# 正常单据快照",
});
const runId = run.shortId!;
// 挂载规则 1 并打标为全部 PASS
await runAiProCli(["bind", "--run", runId, "--rules", "[1]"]);
await runAiProCli([
"review",
"--run",
runId,
"--eval",
"1=PASS:发票已上传; 2=PASS:事由已补充",
]);
// 尝试在无违规情况下驳回,必须被网关拦截
const blockReject = await runAiProCli([
"decide",
"reject",
"--run",
runId,
"--opinion",
"单据完全合规但尝试无故驳回",
]);
expect(blockReject.exitCode).toBe(1);
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
});
});
+113 -365
View File
@@ -1,402 +1,149 @@
#!/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 { parseArgs, stringOption, booleanOption } from "./cli/parser.js";
import { printJson, redactSensitiveText } from "./cli/printer.js";
import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js";
import {
ApprovalService,
ApprovalRepository,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "./domains/approval/index.js";
import { VERSION } from "./version.js";
import { formatVersionLabel, getVersionInfo } from "./version.js";
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js";
import {
handleAiProChecklist,
handleAiProPoints,
handleAiProRules,
handleAiProScopes,
} from "./cli/commands/aipro/rules.js";
import {
handleAiProBind,
handleAiProDecide,
handleAiProInit,
handleAiProReview,
handleAiProTranslate,
} from "./cli/commands/aipro/session.js";
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
export async function runAiProCli(
rawArgs: string[]
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const parsed = parseArgs(rawArgs);
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const runtime = initCorpRuntime({
corpId: stringOption(parsed.options, ["corp", "c"]),
jsonMode: booleanOption(parsed.options, ["json"]),
jsonMode,
});
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。\n",
exitCode: 1,
};
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const repo = new ApprovalRepository();
const service = new ApprovalService(repo);
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | 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 positional =
parsed.positional ??
[parsed.area, parsed.action, ...parsed.args].filter((v): v is string => Boolean(v));
const command = (positional[0] || "help").toLowerCase();
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const operator = corp.staffId || corp.name || "AI-Agent";
const corpId = corp?.corpId || corp?.id;
const operator = corp?.credentials?.staffId || corp?.staffId || corp?.name || "AI-Agent";
const requireCorpId = () => {
const selected = requireSelectedCorp(runtime);
return selected.corpId || selected.id;
};
const getClient = async () => {
cachedSession ??= await getSessionClientForRuntime(runtime);
return { client: cachedSession.client, corpId: cachedSession.corpId };
};
const ctx: AiProExecutionContext = {
rawArgs,
parsed,
runtime,
corp,
corpId,
operator,
positional,
command,
targetSn,
jsonMode,
repo,
service,
requireCorpId,
getClient,
};
try {
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
return {
stdout: jsonMode
? printJson(getVersionInfo("hose-aipro")) + "\n"
: `${formatVersionLabel("hose-aipro")}\n`,
stderr: "",
exitCode: 0,
};
}
switch (command) {
// ── 1. 明细级规则注入(出审核要点清单)────────────────────────────────
case "status":
case "whoami":
case "context":
case "info":
return await handleAiProStatus(ctx);
case "init":
case "start":
return await handleAiProInit(ctx);
case "scopes":
case "index":
case "indexes":
return await handleAiProScopes(ctx);
case "translate":
case "doc":
case "markdown":
case "render":
return await handleAiProTranslate(ctx);
case "rules":
case "rule":
return await handleAiProRules(ctx);
case "bind":
case "mount":
return await handleAiProBind(ctx);
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro points <单号> [--scope <1|场景>]");
}
case "clauses":
return await handleAiProPoints(ctx);
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, 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 <单号>");
}
return await handleAiProChecklist(ctx);
const { run, findings } = service.getAuditChecklist(targetSn);
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 '...'");
}
case "evaluate":
return await handleAiProReview(ctx);
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 updatedFindings = service.evaluateAuditPoints(targetSn, updates);
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]");
}
case "reject":
return await handleAiProDecide(ctx);
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 decisionResult = await service.decideAudit(client, 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);
case "trail":
return await handleAiProLogs(ctx);
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 };
}
default:
return handleAiProHelp(ctx);
}
} catch (err: any) {
// 将阻断或异常统一记录至审计日志
if (err instanceof ApprovalGatewayBlockedError) {
repo.logAiProAction({
action: command,
@@ -407,8 +154,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
stderr: jsonMode ? "" : `\n${err.message}\n`,
exitCode: 1,
};
}
@@ -423,14 +170,15 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
stdout: jsonMode
? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n"
: "",
stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
}
// 直接作为可执行脚本运行时
if (import.meta.main) {
const rawArgs = process.argv.slice(2);
const result = await runAiProCli(rawArgs);
+22
View File
@@ -0,0 +1,22 @@
# CLI 引擎层说明
本目录是三个入口(`src/cli.ts` 主 CLI、`src/aipro-cli.ts` AI PRO CLI、`src/server.ts` MCP 网关)共享的命令引擎:声明式注册、参数解析、写防护、输出渲染与错误映射。入口层只做薄壳,业务编排统一在 `domains/`。
## 文件职责
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层命令唯一声明式注册表(`area` / `aliases` / `standing` 常驻属性 / `handler`)。新增命令先在此注册。
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
- `parser.ts`:参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`)。
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
- `help.ts`:帮助文本组织。
- `commands/`:每个顶层命令域一个 handler 文件,与 `src/domains/` 一一对应;复杂命令(如 `aipro/`)可用子目录形态。
- `architecture-boundaries.test.ts`:分层导入约束的机器卡点(入口层禁触 `domains/*/api.ts`、域层禁反向依赖、core 白名单)。
## 约定
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
+131
View File
@@ -0,0 +1,131 @@
import { describe, expect, test } from "bun:test";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
const SRC_ROOT = join(import.meta.dir, "..");
function collectTsFiles(dir: string, includeTests = false): string[] {
const results: string[] = [];
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
const stat = statSync(full);
if (stat.isDirectory()) {
results.push(...collectTsFiles(full, includeTests));
} else if (full.endsWith(".ts") && (includeTests || !full.endsWith(".test.ts"))) {
results.push(full);
}
}
return results;
}
function extractImportSpecifiers(source: string): string[] {
const specifiers: string[] = [];
const staticImportRe = /(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g;
const dynamicImportRe = /import\(\s*["']([^"']+)["']\s*\)/g;
for (const match of source.matchAll(staticImportRe)) {
if (match[1]) specifiers.push(match[1]);
}
for (const match of source.matchAll(dynamicImportRe)) {
if (match[1]) specifiers.push(match[1]);
}
return specifiers;
}
function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null {
if (!specifier.startsWith(".")) return null;
const abs = resolve(dirname(fromFile), specifier).replace(/\.[jt]s$/, "");
return relative(SRC_ROOT, abs);
}
describe("Architecture Layering Boundaries", () => {
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
const entrypointFiles = [
...collectTsFiles(join(SRC_ROOT, "cli")),
...collectTsFiles(join(SRC_ROOT, "http")),
join(SRC_ROOT, "server.ts"),
join(SRC_ROOT, "cli.ts"),
join(SRC_ROOT, "aipro-cli.ts"),
];
const violations: string[] = [];
for (const file of entrypointFiles) {
const content = readFileSync(file, "utf8");
const specifiers = extractImportSpecifiers(content);
for (const spec of specifiers) {
const targetRel = resolveImportRelativeToSrc(file, spec);
if (targetRel && /^domains\/[^/]+\/api$/.test(targetRel)) {
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
}
}
}
expect(violations).toEqual([]);
});
test("src/domains/ must remain pure SDK and never import from cli, http, or server entrypoints", () => {
const domainFiles = collectTsFiles(join(SRC_ROOT, "domains"));
const violations: string[] = [];
for (const file of domainFiles) {
const content = readFileSync(file, "utf8");
const specifiers = extractImportSpecifiers(content);
for (const spec of specifiers) {
const targetRel = resolveImportRelativeToSrc(file, spec);
if (
targetRel &&
(targetRel.startsWith("cli/") ||
targetRel.startsWith("http/") ||
targetRel === "server" ||
targetRel === "cli" ||
targetRel === "aipro-cli")
) {
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
}
}
}
expect(violations).toEqual([]);
});
test("src/core/ must never depend upward on domains, cli, http, or server entrypoints", () => {
const coreFiles = collectTsFiles(join(SRC_ROOT, "core"));
const violations: string[] = [];
for (const file of coreFiles) {
const content = readFileSync(file, "utf8");
const specifiers = extractImportSpecifiers(content);
for (const spec of specifiers) {
const targetRel = resolveImportRelativeToSrc(file, spec);
if (
targetRel &&
(targetRel.startsWith("domains/") ||
targetRel.startsWith("cli/") ||
targetRel.startsWith("http/") ||
targetRel === "server" ||
targetRel === "cli" ||
targetRel === "aipro-cli")
) {
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
}
}
}
expect(violations).toEqual([]);
});
test("src/core/ must only contain whitelisted infrastructure modules", () => {
const allowedTopLevel = new Set([
"README.core.md",
"auth",
"cache",
"config",
"db",
"errors.ts",
"http",
]);
const entries = readdirSync(join(SRC_ROOT, "core"));
const unexpected = entries.filter((entry) => !allowedTopLevel.has(entry));
expect(unexpected).toEqual([]);
});
});
+299
View File
@@ -0,0 +1,299 @@
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
export async function handleAiProScopes(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, operator, rawArgs } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
let runRecord: ApprovalRunRecord | null = null;
if (runHandle) {
runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
}
repo.logAiProAction({
action: "scopes",
runId: runRecord?.shortId || runRecord?.id,
documentSn: runRecord?.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: runRecord ? `在会话 [${runRecord.shortId}] 查阅规约场景索引` : "查阅规约场景索引",
});
const scopes = repo.listScopes().map((s) => ({
索引号: s.index,
适用场景: s.scope,
}));
return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 };
}
export async function handleAiProRules(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, operator, rawArgs } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]);
const rawIndexes =
stringOption(parsed.options, ["indexes", "index", "i", "scope", "s"]) ||
positional[1] ||
positional[2];
let runRecord: ApprovalRunRecord | null = null;
if (runHandle) {
runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
}
const targetIndexes = parseIntegerList(rawIndexes);
const uniqueIndexes = [...new Set(targetIndexes)].sort((a, b) => a - b);
if (uniqueIndexes.length === 0) {
return {
stdout: "",
stderr: `请提供具名参数,例如:\n hose-aipro rules --run <runId> --indexes "[1]"\n hose-aipro rules --run <runId> --indexes "[1, 2]"\n`,
exitCode: 1,
};
}
const rulesMap = new Map<number, { 编号: number; 适用场景: string; 规则明细: string }>();
const notFound: number[] = [];
for (const idx of uniqueIndexes) {
const detail = repo.getScopeDetail(idx);
if (!detail) {
notFound.push(idx);
continue;
}
for (const r of detail.rules) {
if (!rulesMap.has(r.code)) {
rulesMap.set(r.code, {
编号: r.code,
适用场景: detail.scope,
规则明细: r.body,
});
}
}
}
if (notFound.length > 0 && rulesMap.size === 0) {
return {
stdout: "",
stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: [${notFound.join(", ")}]\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
exitCode: 1,
};
}
const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.编号 - b.编号);
repo.logAiProAction({
action: "rules",
runId: runRecord?.shortId || runRecord?.id,
documentSn: runRecord?.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: runRecord
? `在会话 [${runRecord.shortId}] 查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`
: `查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`,
});
return {
stdout: JSON.stringify(flattenedRules, null, 2) + "\n",
stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "",
exitCode: 0,
};
}
export async function handleAiProPoints(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, service, runtime, operator, rawArgs, getClient } = ctx;
const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]);
const arg2 = positional[2];
// 兼容双参数调用: 如果同时提供了单号和索引号,走单据绑定流
if (arg1 && arg2) {
const billSn = arg1;
const scopeTarget = arg2;
const context = await getClient();
const result = await service.injectAuditPoints(context.client, context.corpId, billSn, {
scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined,
});
repo.logAiProAction({
action: "bind",
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 };
}
const targetScope = arg1;
if (!targetScope) {
const allScopes = repo.listScopes("active");
if (allScopes.length === 0) {
return {
stdout: "规约库中暂无生效规则。可使用 hose-use rule add <场景> <正文> 新增规则。\n",
stderr: "",
exitCode: 0,
};
}
const lines: string[] = [
`====== [AI PRO] 规约审核要点总览 (共 ${allScopes.length} 个适用场景) ======\n`,
];
for (const s of allScopes) {
const detail = repo.getScopeDetail(s.index);
if (!detail) continue;
lines.push(`▶ 场景 [${detail.index}] ${detail.scope} (包含 ${detail.ruleCount} 条规则):`);
let count = 0;
detail.rules.forEach((r) => {
r.parsed.clauses.forEach((c) => {
count++;
lines.push(` ${count}. [${c.strictness}] (规则 #${r.code}) ${c.action}`);
});
});
lines.push("");
}
lines.push(`提示: 输入 "hose-aipro points <索引号|场景名称>" 查看指定场景要点明细。\n`);
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
}
const detail = repo.getScopeDetail(targetScope);
if (!detail) {
return {
stdout: "",
stderr: `[NOT FOUND] 未找到索引号或场景为 "${targetScope}" 的规约场景。\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
exitCode: 1,
};
}
const points: Array<{ index: number; strictness: string; ruleCode: number; clauseText: string }> = [];
let count = 0;
for (const rule of detail.rules) {
for (const clause of rule.parsed.clauses) {
count++;
points.push({
index: count,
strictness: clause.strictness,
ruleCode: rule.code,
clauseText: clause.action,
});
}
}
if (runtime.jsonMode) {
return {
stdout: printJson({
index: detail.index,
scope: detail.scope,
ruleCount: detail.ruleCount,
pointsCount: points.length,
points,
}),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容 (Clause)"];
const rows = points.map((p) => [p.index, `[${p.strictness}]`, `#${p.ruleCode}`, p.clauseText]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 适用场景 [${detail.index}] ${detail.scope} - 审核要点清单 (共 ${points.length} 条要点) ======\n`;
const tip =
`\n说明: 审核要点为规约条款提取出的判定标准,纯规则元数据,与具体单据无关。\n` +
`绑定单据: 运行 "hose-aipro bind <单号> ${detail.index}" 将此要点清单挂载到具体单据。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
export async function handleAiProChecklist(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { targetSn, requireCorpId, service, repo, operator, rawArgs, runtime } = ctx;
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 bind ${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} 审核清单核验进度 (适用场景: [${run.scope || "未关联"}] | 总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
+499
View File
@@ -0,0 +1,499 @@
import {
type ApprovalRunRecord,
type CreateFindingInput,
type FindingCheckStatus,
type RuleRecord,
parseRuleBody,
validateGatewayAction,
} from "../../../domains/approval/index.js";
import {
approveBill,
getRawBillFlow,
getTranslatorContext,
rejectBill,
} from "../../../domains/bill/tools.js";
import { translateBillFlowToMarkdown } from "../../../domains/bill/translator.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
export async function handleAiProInit(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { positional, parsed, getClient, repo, operator, rawArgs } = ctx;
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
if (!billSn) {
throw new Error("请提供单号: hose-aipro init <单号>");
}
const context = await getClient();
const raw = await getRawBillFlow(context.client, context.corpId, billSn);
if (!raw) {
throw new Error(`在当前企业下未找到单号为 [${billSn}] 的单据`);
}
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<
string,
any
>;
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<
string,
any
>;
const title = form.title || flowIdObj.title || "<无标题>";
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
() => undefined
);
const snapshot = translateBillFlowToMarkdown(raw, translatorContext);
const run = repo.createApprovalRun({
documentSn: form.code || billSn,
corpId: context.corpId,
flowId: flowIdObj.id || raw.id,
documentSnapshot: snapshot,
});
repo.logAiProAction({
action: "init",
runId: run.shortId || run.id,
documentSn: run.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `初始化审批会话成功,签发 6 位短 ID: ${run.shortId} (有效期 6 小时)`,
});
return {
stdout:
JSON.stringify(
{
runId: run.shortId,
documentSn: run.documentSn,
title,
corpId: run.corpId,
status: run.decision,
expiresIn: "6h",
createdAt: run.createdAt,
},
null,
2
) + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleAiProTranslate(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, operator, rawArgs, getClient } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]);
const specifiedSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
let runRecord: ApprovalRunRecord | null = null;
if (runHandle) {
runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
} else if (specifiedSn) {
const maybeRun = repo.getRunByHandle(specifiedSn);
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === specifiedSn.toUpperCase()) {
runRecord = maybeRun;
}
}
let targetSn: string | undefined;
let isSessionPrimary = false;
if (runRecord) {
if (specifiedSn && specifiedSn !== runRecord.shortId) {
targetSn = specifiedSn;
} else {
targetSn = runRecord.documentSn;
isSessionPrimary = true;
}
} else {
targetSn = specifiedSn;
}
if (!targetSn) {
throw new Error("请提供会话 ID 或单号: hose-aipro translate [单号] --run <runId>");
}
if (isSessionPrimary && runRecord?.documentSnapshot) {
repo.logAiProAction({
action: "translate",
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `在会话 [${runRecord.shortId}] 读取主单据快照 [${runRecord.documentSn}]`,
});
return {
stdout: runRecord.documentSnapshot.endsWith("\n")
? runRecord.documentSnapshot
: runRecord.documentSnapshot + "\n",
stderr: "",
exitCode: 0,
};
}
const context = await getClient();
const raw = await getRawBillFlow(context.client, context.corpId, targetSn);
if (!raw) {
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
}
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
() => undefined
);
const markdown = translateBillFlowToMarkdown(raw, translatorContext);
repo.logAiProAction({
action: "translate",
runId: runRecord?.shortId || runRecord?.id,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: runRecord
? `在会话 [${runRecord.shortId}] 查阅关联单据 [${targetSn}] 转译文本`
: `查阅单据 [${targetSn}] 转译文本`,
});
return {
stdout: markdown.endsWith("\n") ? markdown : markdown + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleAiProBind(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, operator, rawArgs } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro bind --run <runId> --rules '[1, 2]'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
const rawRules = stringOption(parsed.options, ["rules", "rule", "codes", "c"]);
const rawIndexes = stringOption(parsed.options, ["indexes", "index", "i", "scopes", "scope", "s"]);
const fallbackRaw = positional
.slice(1)
.find((p) => p !== runHandle && p.startsWith("[") && p.endsWith("]"));
const ruleCodes = parseIntegerList(rawRules || fallbackRaw);
const indexNums = parseIntegerList(rawIndexes);
if (ruleCodes.length === 0 && indexNums.length === 0) {
throw new Error("请指定要挂载的规则或场景索引,例如: hose-aipro bind --run <runId> --rules '[1, 2]'");
}
const targetRulesMap = new Map<number, RuleRecord>();
for (const code of ruleCodes) {
const r = repo.getRuleByCode(code);
if (r && r.status === "active") {
targetRulesMap.set(r.code, r);
}
}
for (const idx of indexNums) {
const detail = repo.getScopeDetail(idx);
if (detail) {
for (const r of detail.rules) {
if (r.status === "active") {
targetRulesMap.set(r.code, r);
}
}
}
}
if (targetRulesMap.size === 0) {
throw new Error("未找到任何有效规则,请先运行 hose-aipro scopes 和 hose-aipro rules 查看规约");
}
const sortedRules = Array.from(targetRulesMap.values()).sort((a, b) => a.code - b.code);
const findingsToInject: CreateFindingInput[] = [];
for (const r of sortedRules) {
const parsedRule = parseRuleBody(r.body);
for (const clause of parsedRule.clauses) {
findingsToInject.push({
ruleId: r.id,
clauseText: clause.action,
strictness: clause.strictness,
checkStatus: "PENDING",
});
}
}
const injected = repo.injectFindings(runRecord.id, findingsToInject);
repo.logAiProAction({
action: "bind",
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `在会话 [${runRecord.shortId}] 挂载 ${injected.length} 条审核要点清单(涵盖规则: ${sortedRules.map((r) => `#${r.code}`).join(", ")})`,
});
const output = injected.map((f, i) => ({
要点编号: i + 1,
严格程度: f.strictness,
归属规则: f.ruleCode ?? "-",
审核要点: f.clauseText,
核验状态: "待核验",
}));
return {
stdout: JSON.stringify(output, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleAiProReview(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, repo, operator, rawArgs } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro review --run <runId> --eval '...'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
const findings = repo.getFindingsByRunId(runRecord.id);
if (findings.length === 0) {
throw new Error(
`会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何审核要点清单,请先执行 hose-aipro bind --run ${runRecord.shortId || runRecord.id} --rules '...'`
);
}
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"]);
const normalizeStatus = (raw: string): FindingCheckStatus => {
const upper = raw.trim().toUpperCase();
if (["PASS", "通过", "合规", "OK", "YES"].includes(upper)) return "PASS";
if (["FAIL", "未通过", "不通过", "违规", "NO"].includes(upper)) return "FAIL";
if (["SKIP", "跳过", "不适用", "NA", "N/A"].includes(upper)) return "SKIP";
return "PENDING";
};
const updates: Array<{
index: number;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({ index: pointIndex, status: normalizeStatus(statusInput), evidence, reasoning });
} else if (evalStr) {
const segments = evalStr
.split(/[;\n]+/)
.map((s) => s.trim())
.filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*([A-Za-z\u4e00-\u9fa5]+)(?::(.*))?$/);
if (match) {
const idx = parseInt(match[1], 10);
const status = normalizeStatus(match[2]);
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 --run ${runRecord.shortId || runRecord.id} --eval "1=PASS:已上传发票; 2=FAIL:住宿超标; 3=SKIP"\n`
);
}
for (const item of updates) {
const target = findings[item.index - 1];
if (!target) {
throw new Error(`要点编号超出范围: #${item.index} (当前要点总数: ${findings.length})`);
}
repo.updateFinding(target.id, {
checkStatus: item.status,
evidence: item.evidence,
reasoning: item.reasoning,
});
}
const updatedFindings = repo.getFindingsByRunId(runRecord.id);
const passCount = updatedFindings.filter((f) => f.checkStatus === "PASS").length;
const failCount = updatedFindings.filter((f) => f.checkStatus === "FAIL").length;
const skipCount = updatedFindings.filter((f) => f.checkStatus === "SKIP").length;
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
repo.logAiProAction({
action: "review",
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `在会话 [${runRecord.shortId || runRecord.id}] 录入 ${updates.length} 项要点核验(通过: ${passCount}, 违规: ${failCount}, 待核验: ${pendingCount})`,
});
const checklistOutput = updatedFindings.map((f, i) => ({
要点编号: i + 1,
严格程度: f.strictness,
归属规则: f.ruleCode ?? "-",
审核要点: f.clauseText,
核验状态:
f.checkStatus === "PASS"
? "通过"
: f.checkStatus === "FAIL"
? "未通过"
: f.checkStatus === "SKIP"
? "已跳过"
: "待核验",
事实依据: Array.from(new Set([f.evidence, f.reasoning].filter(Boolean))).join(" - ") || "-",
}));
const resultObj = {
会话ID: runRecord.shortId || runRecord.id,
单号: runRecord.documentSn,
要点总数: updatedFindings.length,
已通过: passCount,
未通过: failCount,
已跳过: skipCount,
待核验: pendingCount,
核验清单: checklistOutput,
};
return {
stdout: JSON.stringify(resultObj, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleAiProDecide(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, positional, command, repo, operator, rawArgs, getClient } = ctx;
const runHandle =
stringOption(parsed.options, ["run", "r"]) ||
positional
.slice(1)
.find(
(p) => !["approve", "reject", "pass", "同意", "通过", "驳回", "拒绝"].includes(p.toLowerCase())
);
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro decide <approve|reject> --run <runId> --opinion '...'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
let actionRaw: string | undefined = positional[1]?.toLowerCase();
if (actionRaw === runHandle?.toLowerCase()) {
actionRaw = positional[2]?.toLowerCase();
}
if (!actionRaw || actionRaw.startsWith("-")) {
actionRaw = stringOption(parsed.options, ["action", "a"])?.toLowerCase();
}
if (command === "approve") {
actionRaw = "approve";
} else if (command === "reject") {
actionRaw = "reject";
}
let action: "APPROVE" | "REJECT" | undefined;
if (["approve", "pass", "同意", "通过"].includes(actionRaw || "")) {
action = "APPROVE";
} else if (["reject", "refuse", "驳回", "拒绝"].includes(actionRaw || "")) {
action = "REJECT";
}
if (!action) {
throw new Error("请指定要执行的审批动作: hose-aipro decide approve 或 hose-aipro decide reject");
}
const opinion = (
stringOption(parsed.options, ["opinion", "comment", "message", "m", "审批意见", "意见"]) || ""
).trim();
if (!opinion) {
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
}
const findings = repo.getFindingsByRunId(runRecord.id);
validateGatewayAction({
documentSn: runRecord.documentSn,
findings,
requestedAction: action === "APPROVE" ? "approve" : "reject",
opinion,
});
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)";
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(
`[AI PRO] 即将向合思系统真实执行审批流转 [${action === "APPROVE" ? "同意" : "驳回"}],确认执行?输入 yes: `
);
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
const context = await getClient();
if (action === "APPROVE") {
await approveBill(context.client, context.corpId, runRecord.documentSn, {
comment: opinion,
});
} else {
await rejectBill(context.client, context.corpId, runRecord.documentSn, {
comment: opinion,
});
}
executionStatus = "已真实下发合思系统流转";
}
repo.updateApprovalRun(runRecord.id, {
decision: action,
decisionSummary: opinion,
failedRulesCount: findings.filter((f) => f.checkStatus === "FAIL").length,
});
repo.logAiProAction({
action: "decide",
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: action,
summary: `审批动作 [${action === "APPROVE" ? "同意" : "驳回"}] (${executionStatus})`,
});
const resultObj = {
会话ID: runRecord.shortId || runRecord.id,
单号: runRecord.documentSn,
执行动作: action === "APPROVE" ? "同意" : "驳回",
审批意见: opinion,
流转状态: executionStatus,
网关状态: "放行",
};
return {
stdout: JSON.stringify(resultObj, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
+206
View File
@@ -0,0 +1,206 @@
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
import { VERSION } from "../../../version.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { formatExpiresAt, printJson, printTable } from "../../printer.js";
import type { AiProCommandResult, AiProExecutionContext } from "./types.js";
export async function handleAiProStatus(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { repo, corp, corpId, operator, runtime, parsed } = ctx;
const scopes = repo.listScopes("active");
const rules = repo.listRules();
const runs = corpId ? repo.listRuns({ corpId }) : repo.listRuns();
const pendingRuns = runs.filter((r) => r.decision === "PENDING");
const recentLogs = repo.listAiProLogs(undefined, 5);
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
const corpStaffId = corp?.credentials?.staffId || corp?.staffId || "-";
const corpStaffName = corp?.staffName || corp?.session?.staffName || null;
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
if (isJson) {
return {
stdout:
JSON.stringify(
{
tool: "hose-aipro",
version: VERSION,
corp: corp
? {
id: corp.id,
name: corp.name,
staffId: corpStaffId,
userName: corpStaffName,
source: corp.source,
expiresAt: corpExpiresAt,
expired: corpExpiresAt ? corpExpiresAt <= Date.now() : false,
baseUrl: corp.baseUrl,
}
: null,
operator,
ruleEngine: {
scopesCount: scopes.length,
rulesCount: rules.length,
scopes: scopes.map((s) => ({
index: s.index,
scope: s.scope,
ruleCount: s.ruleCount,
})),
},
sessions: {
total: runs.length,
pending: pendingRuns.length,
},
recentLogsCount: recentLogs.length,
},
null,
2
) + "\n",
stderr: "",
exitCode: 0,
};
}
const lines = [
`====== 合思 AI PRO 确定性审批网关运行上下文 (v${VERSION}) ======`,
` 当前连接企业 : ${corp ? `${corp.name} (${corp.id})` : "⚠️ 未指定企业"}`,
` 当前操作工号 : ${corpStaffId}`,
` 操作员标识 : ${operator}`,
` 凭证有效状态 : ${corp ? formatExpiresAt(corpExpiresAt) : "-"}`,
` 主站 BaseURL : ${corp?.baseUrl || "-"}`,
` 规约场景库 : 已加载 ${scopes.length} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ") || "无"}),共 ${rules.length} 条仲裁规则`,
` 未结审批会话 : ${pendingRuns.length} 个待决断会话 (当前企业历史总会话: ${runs.length} 个)`,
"",
"提示:",
" - 查看规约场景列表: hose-aipro scopes",
" - 切换全局工作企业: hose-use corps switch <企业ID>",
" - 临时指定执行企业: hose-aipro --corp=<企业ID> <子命令>",
" - 单据审批全流程 : hose-aipro bind <单号> <索引号> -> hose-aipro review -> hose-aipro decide",
"",
];
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
}
export async function handleAiProLogs(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
const { parsed, repo, runtime, targetSn } = ctx;
const runHandle = stringOption(parsed.options, ["run", "r"]);
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
let runRecord: ApprovalRunRecord | null = null;
if (runHandle) {
runRecord = repo.getRunByHandle(runHandle);
} else if (targetSn) {
const maybeRun = repo.getRunByHandle(targetSn);
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) {
runRecord = maybeRun;
}
}
const filter: { runId?: string; documentSn?: string } = {};
if (runRecord) {
filter.runId = runRecord.shortId || runRecord.id;
} else if (runHandle) {
filter.runId = runHandle;
}
if (targetSn && targetSn !== runRecord?.shortId) {
filter.documentSn = targetSn;
}
const logs = repo.listAiProLogs(filter, limit);
if (runtime.jsonMode) {
return {
stdout: printJson({ total: logs.length, logs }),
stderr: "",
exitCode: 0,
};
}
if (logs.length === 0) {
const targetDesc = filter.runId
? ` (会话: ${filter.runId})`
: filter.documentSn
? ` (单号: ${filter.documentSn})`
: "";
return {
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetDesc}。\n`,
stderr: "",
exitCode: 0,
};
}
const headers = [
"#",
"发生时间",
"会话 ID",
"动作 (Action)",
"单号",
"操作人",
"状态",
"网关决策",
"摘要说明",
];
const rows = logs.map((l, i) => [
i + 1,
new Date(l.createdAt).toLocaleString("zh-CN"),
l.runId || "-",
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 };
}
export function handleAiProHelp(ctx: AiProExecutionContext): AiProCommandResult {
const { corp, operator, jsonMode } = ctx;
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
const corpBanner = corp
? `[当前连接企业: ${corp.name} (${corp.id}) | 操作人: ${operator} | 凭证状态: ${formatExpiresAt(corpExpiresAt)}]\n[全局切换: hose-use corps switch <企业ID> | 临时指定: hose-aipro --corp=<企业ID>]`
: `[当前企业: 未指定 | 请先运行 hose-use auth login 或带上 --corp=<企业ID>]`;
const helpText = `
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
${corpBanner}
核心工作流:
0. 查看 AI PRO 运行上下文与当前绑定企业:
hose-aipro status # 查看当前企业、操作人、规则库统计与待办会话
1. 查看规约场景索引库 (获取规则索引号):
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
2. 查看场景审核要点清单 (纯规则元数据,与单据无关):
hose-aipro points <索引号|场景名称> # 例如: hose-aipro points 1
3. 显式绑定单据并挂载审核要点:
hose-aipro bind <单号> <索引号> # 例如: hose-aipro bind S26000001 1
4. 查看单据审核清单与核验进度:
hose-aipro checklist <单号> # 查看当前单据要点核验进度与挂载场景
5. 逐项录入事实核验打标:
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
6. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
hose-aipro decide <单号> # 预审仿真 (Dry Run)
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
7. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
`;
return {
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
stderr: "",
exitCode: 0,
};
}
+48
View File
@@ -0,0 +1,48 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import type { ApprovalRepository, ApprovalService } from "../../../domains/approval/index.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
export interface AiProExecutionContext {
rawArgs: string[];
parsed: CliParsedArgs;
runtime: CliRuntime;
corp: CorpConfig | null;
corpId?: string;
operator: string;
positional: string[];
command: string;
targetSn?: string;
jsonMode: boolean;
repo: ApprovalRepository;
service: ApprovalService;
requireCorpId: () => string;
getClient: () => Promise<{ client: KyInstance; corpId: string }>;
}
export type AiProCommandResult = CliResult;
export function parseIntegerList(input?: string): number[] {
if (!input) return [];
const trimmed = input.trim();
const list: number[] = [];
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
try {
const parsedJson = JSON.parse(trimmed);
if (Array.isArray(parsedJson)) {
for (const item of parsedJson) {
const n = Number(item);
if (!isNaN(n)) list.push(n);
}
return list;
}
} catch {}
}
const inner = trimmed.replace(/[\[\]]/g, "");
const parts = inner.split(/[,,\s]+/).filter(Boolean);
for (const p of parts) {
const n = Number(p.replace(/['"]/g, ""));
if (!isNaN(n)) list.push(n);
}
return list;
}
+183
View File
@@ -0,0 +1,183 @@
import { describe, it, expect, spyOn } from "bun:test";
import { handleAppCommand } from "./app.js";
import * as menuTools from "../../domains/menu/tools.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("cli/commands/app > handleAppCommand", () => {
const dummyRuntimeNoCorp: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
const mockCorp: CorpConfig = {
id: "corp123",
name: "转转二手交易网",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp123",
staffId: "mock-staff",
},
};
const dummyRuntimeWithCorp: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
it("fails with exitCode 1 when no corp is selected", async () => {
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: {},
raw: ["app", "list"],
},
dummyRuntimeNoCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("lists workbench apps in table format", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
type: "MENU",
},
{
id: "ID01PIqCA1Di0v",
name: "用车制度",
code: "dataLinkItem",
href: "/third-party-item/ID01PIqCA1Di0v",
type: "REGULATION",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: {},
raw: ["app", "list"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作台应用管理列表");
expect(res.stdout).toContain("用车补贴");
expect(res.stdout).toContain("用车制度");
expect(res.stdout).toContain("用车/商旅套件");
expect(res.stdout).toContain("制度与规约");
spy.mockRestore();
});
it("filters workbench apps with --keyword", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
{
id: "ID01PIqCA1Di0v",
name: "差旅申请",
code: "dataLinkItem",
href: "/third-party-item/ID01PIqCA1Di0v",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: { keyword: "补贴" },
raw: ["app", "list", "--keyword", "补贴"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("用车补贴");
expect(res.stdout).not.toContain("差旅申请");
spy.mockRestore();
});
it("supports --json output for app list", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
const res = await handleAppCommand(
{
area: "app",
action: "list",
args: [],
options: { json: true },
raw: ["app", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.total).toBe(1);
expect(parsed.apps[0].id).toBe("SCGY:corp123");
expect(parsed.apps[0].name).toBe("用车补贴");
spy.mockRestore();
});
it("returns error for unknown subcommand", async () => {
const res = await handleAppCommand(
{
area: "app",
action: "unknownAction",
args: [],
options: {},
raw: ["app", "unknownAction"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未知 app 子命令");
});
});
+149
View File
@@ -0,0 +1,149 @@
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
import { getPlatform } from "../../domains/datalink/services.js";
import { createClientsForCorp } from "../helpers.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function inferCategory(app: { id: string; name: string; type?: string | null }): string {
if (app.id.startsWith("SCGY:") || app.type === "PRIVATE_CAR") return "用车/商旅套件";
if (app.type === "REGULATION") return "制度与规约";
if (app.type === "VCM") return "商旅卡与金融";
if (app.name.includes("[模板]") || app.name.includes("模板")) return "预置模板";
return "自建业务应用";
}
export async function handleAppCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!runtime.selectedCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action || "list";
switch (action) {
case "list":
case "ls":
case "apps":
case "workbench": {
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"])?.toLowerCase();
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
const filtered = keyword
? apps.filter((app) =>
[app.id, app.name, app.code, app.href]
.filter((val): val is string => Boolean(val))
.some((val) => val.toLowerCase().includes(keyword))
)
: apps;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: runtime.selectedCorp.credentials.corpId,
corpName: runtime.selectedCorp.name,
total: apps.length,
count: filtered.length,
keyword: keyword ?? null,
apps: filtered,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (filtered.length === 0) {
const msg = keyword
? `企业 [${runtime.selectedCorp.name}] 下未找到匹配 "${keyword}" 的工作台应用\n`
: `企业 [${runtime.selectedCorp.name}] 下暂无工作台应用配置\n`;
return { stdout: msg, stderr: "", exitCode: 0 };
}
const headers = ["#", "应用 ID", "应用名称", "应用分类", "功能代码", "Web 直达路由"];
const rows = filtered.map((app, i) => [
i + 1,
app.id,
app.name,
inferCategory(app),
app.code || "dataLinkItem",
app.href,
]);
const title = `====== [${runtime.selectedCorp.name}] 工作台应用管理列表 (${filtered.length} 个应用) ======\n`;
return {
stdout: title + printTable(headers, rows) + "\n",
stderr: "",
exitCode: 0,
};
}
case "get":
case "show": {
const target = parsed.args[0] || stringOption(parsed.options, ["id", "name", "app"]);
if (!target) {
return {
stdout: "",
stderr: "请提供应用 ID 或名称: hose-use app get <应用 ID|名称>\n",
exitCode: 1,
};
}
const apps = await fetchWorkbenchAppsList(runtime.selectedCorp);
const matched = apps.find(
(a) =>
a.id.toLowerCase() === target.toLowerCase() ||
a.name.toLowerCase().includes(target.toLowerCase())
);
const appId = matched ? matched.id : target;
const appName = matched ? matched.name : target;
const clients = await createClientsForCorp(runtime.selectedCorp);
const corpId = runtime.selectedCorp.credentials.corpId;
try {
const detail = await getPlatform(clients.ekbClient, corpId, appId);
if (runtime.jsonMode) {
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const infoRows = [
["应用 ID", detail.id],
["应用名称", detail.name],
["应用分类", inferCategory(detail)],
["启用状态", detail.active ? "🟢 已启用" : "⚪ 未启用"],
["Web 路由", matched?.href || `/third-party-item/${detail.id}`],
["管理员数", detail.adminIds.length],
["可见人员数", detail.staffIds.length],
["可见角色数", detail.roleIds.length],
["可见部门数", detail.departmentIds.length],
];
const text = `====== 工作台应用详情: ${appName} ======\n${printTable(["属性", "信息"], infoRows)}\n`;
return { stdout: text, stderr: "", exitCode: 0 };
} catch (err) {
return {
stdout: "",
stderr: `获取应用详情失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
}
default:
return {
stdout: "",
stderr: `未知 app 子命令: ${action}。支持: list, get\n用法: hose-use app list [--keyword <关键词>]\n`,
exitCode: 1,
};
}
}
+5 -5
View File
@@ -1,7 +1,7 @@
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 { createSessionClient } from "../../core/http/session-client.js";
import {
ApprovalService,
ApprovalGatewayBlockedError,
@@ -19,7 +19,7 @@ export async function handleApprovalCommand(
);
}
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const corpId = corp.corpId || corp.id;
const service = new ApprovalService();
@@ -101,7 +101,7 @@ export async function handleApprovalCommand(
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn);
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
if (!run || findings.length === 0) {
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
@@ -195,7 +195,7 @@ export async function handleApprovalCommand(
}
try {
const updatedFindings = service.evaluateAuditPoints(targetSn, updates);
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
@@ -308,7 +308,7 @@ export async function handleApprovalCommand(
}
// 检查当前是否已注入要点
const { run } = service.getAuditChecklist(targetSn);
const { run } = service.getAuditChecklist(targetSn, corpId);
if (!run) {
// 自动触发第一步:注入并出审核要点
return await handleApprovalCommand(
+83
View File
@@ -0,0 +1,83 @@
import { describe, it, expect } from "bun:test";
import { handleAuthCommand } from "./auth.js";
import type { CliRuntime } from "../types.js";
describe("cli/commands/auth > aliases and subcommands", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("maps auth list to handleAccounts smoothly", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "list",
args: [],
options: {},
raw: ["auth", "list"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
// 应该输出已保存账号表格或无账号提示
expect(res.stdout).toMatch(/(已保存账号列表|暂无保存的账号)/);
});
it("supports auth accounts with --json mode", async () => {
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
const res = await handleAuthCommand(
{
area: "auth",
action: "list",
args: [],
options: { json: true },
raw: ["auth", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data).toHaveProperty("accounts");
});
it("handles auth status / current aliases without crash", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "current",
args: [],
options: {},
raw: ["auth", "current"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("当前登录与企业状态");
});
it("supports auth sync-seal --dry-run", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "sync-seal",
args: [],
options: { "dry-run": true },
raw: ["auth", "sync-seal", "--dry-run"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("从 seal-use 同步企业 OpenAPI 持久化密钥");
});
});
+229 -48
View File
@@ -1,24 +1,41 @@
import {
canRefreshCorpAccessToken,
fullPasswordLogin,
fullSmsLogin,
fullBrowserSyncLogin,
hasOpenApiPersistentCredentials,
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
importFromLink,
parseHeadersOrCurl,
refreshAccountCorporations,
refreshSingleCorpAccessToken,
} from "../../core/auth/login.js";
import {
listAccounts,
getActiveAccount,
setActiveAccount,
} from "../../core/auth/account-store.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import {
handleAddPersistent,
handleElevateCorp,
handleExtractKeys,
handleGenerateCorpLink,
handleSyncFromSeal,
resolveTargetCorpByArgOrContext,
} from "./corps/index.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function isHttpUrl(val?: string): boolean {
return Boolean(val && /^https?:\/\//i.test(val.trim()));
}
export async function handleAuthCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -30,19 +47,58 @@ export async function handleAuthCommand(
return handleLogin(parsed, runtime);
case "status":
case "whoami":
case "current":
return handleStatus(parsed, runtime);
case "refresh":
case "renew":
return handleRefresh(parsed, runtime);
case "import":
case "add":
return handleImport(parsed, runtime);
case "add-link":
case "import-link":
return handleAddLink(parsed, runtime);
case "link": {
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
if (isHttpUrl(maybeUrl)) {
return handleAddLink(parsed, runtime);
}
return handleGenerateCorpLink(parsed, runtime);
}
case "hose-link":
case "auth-link":
case "login-link":
return handleGenerateCorpLink(parsed, runtime);
case "add-persistent":
case "add-hose-persistent":
case "add-openapi":
case "add-hose":
return handleAddPersistent(parsed, runtime);
case "extract-keys":
case "extract-key":
case "hose-extract-keys":
case "extract-hose-keys":
return handleExtractKeys(parsed, runtime);
case "elevate":
case "elevate-hose":
return handleElevateCorp(parsed, runtime);
case "sync-seal":
case "sync-from-seal":
case "import-seal":
return handleSyncFromSeal(parsed, runtime);
case "accounts":
case "list":
case "account":
case "accs":
return handleAccounts(parsed, runtime);
case "switch-account":
case "switch":
case "use-account":
return handleSwitchAccount(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, accounts, switch-account\n`,
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`,
exitCode: 1,
};
}
@@ -55,6 +111,14 @@ async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
const isSync = booleanOption(parsed.options, ["sync"]);
const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), {
mode: isSync ? "browser-sync" : isSms ? "sms" : "password",
saveAll: true,
});
}
requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`);
// 1. 浏览器同步
if (isSync) {
const res = await fullBrowserSyncLogin({ saveAll: true });
@@ -144,7 +208,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
if (currentCorp) {
try {
const client = await createEkbClient(currentCorp);
const client = await createSessionClient(currentCorp);
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
sessionValid = !!res.value;
sessionData = res.value;
@@ -153,6 +217,9 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
}
}
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
const isPersistent = canRefreshCorpAccessToken(currentCorp);
const statusObj = {
activeAccount: activeAccount?.accountId || null,
currentCorp: currentCorp
@@ -162,6 +229,8 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
staffId: currentCorp.credentials.staffId,
source: currentCorp.source,
accountId: currentCorp.accountId,
persistent: isPersistent,
hasOpenApiKey: hasOpenApi,
tokenValid: sessionValid,
}
: null,
@@ -177,9 +246,14 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source),
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
"持久化状态": isPersistent
? hasOpenApi
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
};
if (currentCorp?.session) {
@@ -217,6 +291,57 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const accountId = stringOption(parsed.options, ["account", "a"]);
const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]);
const targetCorp = explicitCorp
? resolveTargetCorpByArgOrContext(explicitCorp, runtime)
: !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp)
? runtime.selectedCorp
: null;
if (targetCorp && !accountId) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, {
corpId: targetCorp.id,
hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp),
});
}
requireMutationConfirmation(
parsed,
runtime,
"刷新单企业凭证",
`hose-use auth refresh ${targetCorp.id} --yes`
);
const newToken = await refreshSingleCorpAccessToken(targetCorp);
if (!newToken) {
return {
stdout: "",
stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({
corpId: targetCorp.id,
corpName: targetCorp.name,
refreshed: true,
expiresAt: targetCorp.auth?.expiresAt,
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`,
stderr: "",
exitCode: 0,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
}
requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`);
const res = await refreshAccountCorporations(accountId, { saveAll: true });
if (runtime.jsonMode) {
@@ -231,69 +356,120 @@ async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
let raw = stringOption(parsed.options, ["raw", "headers", "curl"]);
let raw = parsed.args[0] || stringOption(parsed.options, ["raw", "headers", "curl", "url", "link"]);
let accessToken = stringOption(parsed.options, ["token", "accessToken"]);
let corpId = stringOption(parsed.options, ["corp", "corpId"]);
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
let name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"], false);
if (!raw && !accessToken) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
source: raw ? "captured-input" : "manual-input",
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
overwrite,
ttl: ttl || null,
expires: expires || null,
});
}
requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`);
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
}
let baseUrl: string | undefined;
if (raw) {
const parsedObj = parseHeadersOrCurl(raw);
if (parsedObj.accessToken) accessToken = parsedObj.accessToken;
if (parsedObj.corpId) corpId = parsedObj.corpId;
if (parsedObj.staffId) staffId = parsedObj.staffId;
if (parsedObj.baseUrl) baseUrl = parsedObj.baseUrl;
}
if (!accessToken) accessToken = await prompt("请输入 accessToken: ");
if (!corpId) corpId = await prompt("请输入 corpId: ");
if (!staffId) staffId = await prompt("请输入 staffId: ");
if (!accessToken && process.stdin.isTTY) accessToken = await prompt("请输入 accessToken: ");
if (!corpId && process.stdin.isTTY) corpId = await prompt("请输入 corpId: ");
if (!accessToken || !corpId || !staffId) {
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
if (!accessToken || !corpId) {
return { stdout: "", stderr: "accessToken 与 corpId 均为必填!\n", exitCode: 1 };
}
const imported = await importCredentials({
accessToken,
corpId,
staffId,
name,
});
try {
const imported = await importCredentials({
accessToken,
corpId,
staffId,
name,
baseUrl,
overwrite,
ttl,
expires,
appKey,
keyId,
elevate: elevate ? true : noElevate ? false : undefined,
autoElevate: !noElevate,
force,
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
});
if (runtime.jsonMode) {
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
}
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"凭证来源": formatSourceLabel(imported.source),
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
if (runtime.jsonMode) {
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
const hasOpenApi = hasOpenApiPersistentCredentials(imported);
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"集群环境": imported.cluster || "app",
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"手机号码": imported.session?.cellphone || "-",
"是否管理": imported.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(imported.source, hasOpenApi),
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
"服务节点": imported.baseUrl,
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
} catch (error) {
return {
stdout: "",
stderr: `[ERROR] 导入凭证失败: ${error instanceof Error ? error.message : String(error)}\n`,
exitCode: 1,
};
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
return handleImport({ ...parsed, args: linkUrl ? [linkUrl] : [] }, runtime);
}
async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
@@ -309,7 +485,7 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi
}
if (accounts.length === 0) {
return { stdout: "暂无保存的账号,请使用 hose auth login 登录\n", stderr: "", exitCode: 0 };
return { stdout: "暂无保存的账号,请使用 hose-use auth login 登录\n", stderr: "", exitCode: 0 };
}
const rows = accounts.map((acc, i) => [
@@ -327,9 +503,14 @@ async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promi
async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const target = parsed.args[0] || stringOption(parsed.options, ["account", "a"]);
if (!target) {
return { stdout: "", stderr: "用法: hose auth switch-account <accountId>\n", exitCode: 1 };
return { stdout: "", stderr: "用法: hose-use auth switch-account <accountId>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target });
}
requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`);
const success = setActiveAccount(target);
if (!success) {
return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 };
-601
View File
@@ -1,601 +0,0 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.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(
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 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: {
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
code,
keyword,
stage,
state,
count,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
const rows = result.items.map((b, idx) => [
idx + 1,
b.billCode,
b.billName,
b.stage || "-",
b.state || "-",
b.amount || "-",
b.submitDate || b.createTime || "-",
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
stdout: title + tableOutput + tip,
stderr: "",
exitCode: 0,
};
}
case "get":
case "show":
case "find": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
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(
{
corpId,
corpName: corp.name,
count: bills.length,
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outputs: string[] = [];
for (let i = 0; i < bills.length; i++) {
const b = bills[i];
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
outputs.push(` 单据 ID : ${b.billId}`);
outputs.push(` 单据名称 : ${b.billName}`);
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
outputs.push(` 创建时间 : ${b.createTime}`);
outputs.push(` 更新时间 : ${b.updateTime}`);
outputs.push(`\n --- 结构化表单字段明细 ---`);
const detailEntries = Object.entries(b.details);
if (detailEntries.length === 0) {
outputs.push(` (无额外字段数据)`);
} else {
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
for (const [k, v] of detailEntries) {
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
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 {
stdout: outputs.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
const rows = entities.map((e, idx) => [
idx + 1,
e.id,
e.name || "-",
e.type || "-",
e.fields.length,
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
return {
stdout: title + tableOutput + "\n",
stderr: "",
exitCode: 0,
};
}
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 <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
}
}
+67
View File
@@ -0,0 +1,67 @@
import { addNodeBill, approveBill, commentBill, rejectBill, transferBill } from "../../../domains/bill/tools.js";
import { printJson } from "../../printer.js";
import { isDryRun, mutationPreview } from "../../mutation.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
export async function handleApprove(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
await ctx.requireWriteConfirmation();
const target = ctx.actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, ctx.actionOptions());
const result = await approveBill(await ctx.getClient(), corpId, target, ctx.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 };
}
export async function handleReject(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
await ctx.requireWriteConfirmation();
const target = ctx.actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
const options = ctx.actionOptions();
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
const result = await rejectBill(await ctx.getClient(), 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 };
}
export async function handleTransfer(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
await ctx.requireWriteConfirmation();
const target = ctx.actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
const rawOptions = ctx.actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
const result = await transferBill(await ctx.getClient(), 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 };
}
export async function handleAddNode(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
await ctx.requireWriteConfirmation();
const target = ctx.actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
const rawOptions = ctx.actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
const result = await addNodeBill(await ctx.getClient(), 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 };
}
export async function handleComment(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
await ctx.requireWriteConfirmation();
const target = ctx.actionTarget();
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
const options = ctx.actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
const result = await commentBill(await ctx.getClient(), corpId, target, options);
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 };
}
+76
View File
@@ -0,0 +1,76 @@
import { createSessionClient } from "../../../core/http/session-client.js";
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
import { booleanOption, stringOption } from "../../parser.js";
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
/**
* bill 命令族共享的执行上下文:封装 corp 解析、会话客户端懒加载缓存、
* 写确认与审批动作选项解析。由 handleBillCommand 每次调用时构建一次。
*/
export type BillActionContext = ReturnType<typeof createBillActionContext>;
export function createBillActionContext(parsed: CliParsedArgs, runtime: CliRuntime) {
const corp = runtime.selectedCorp!;
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
const getClient = async () => {
client ??= await createSessionClient(corp);
return client;
};
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
const requireWriteConfirmation = async () => {
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
requireMutationConfirmation(
parsed,
runtime,
"单据审批动作",
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
);
}
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(await getClient(), corpId, values);
};
return {
parsed,
runtime,
corp,
corpId,
action,
getClient,
actionTarget,
requireWriteConfirmation,
listOption,
actionOptions,
resolveApproverIds,
};
}
+101
View File
@@ -0,0 +1,101 @@
import { formatBillFlowOperator, getBillFlow, getBillRisk } from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
export async function handleFlow(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
const flow = await getBillFlow(await ctx.getClient(), 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 || "-",
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
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 };
}
export async function handleRisk(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
const report = await getBillRisk(await ctx.getClient(), 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 };
}
export async function handleBudget(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
const report = await getBillRisk(await ctx.getClient(), 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 };
}
+105
View File
@@ -0,0 +1,105 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createBillActionContext } from "./context.js";
import { handleApprove, handleReject, handleTransfer, handleAddNode, handleComment } from "./approve.js";
import { handleList, handleGet } from "./search.js";
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
import { handleSchema, handleLink, handleSpec } from "./meta.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const ctx = createBillActionContext(parsed, runtime);
const action = ctx.action;
switch (action) {
case "approve":
case "agree":
return handleApprove(ctx);
case "reject":
case "deny":
return handleReject(ctx);
case "transfer":
case "shift":
return handleTransfer(ctx);
case "add-node":
case "addnode":
case "countersign":
case "counter-sign":
return handleAddNode(ctx);
case "comment":
case "remark":
return handleComment(ctx);
case "list":
case "search":
case undefined:
return handleList(ctx);
case "get":
case "show":
case "find":
return handleGet(ctx);
case "schema":
case "schemas":
case "entities":
return handleSchema(ctx);
case "flow":
case "records":
case "timeline":
return handleFlow(ctx);
case "risk":
case "review":
case "warnings":
return handleRisk(ctx);
case "budget":
case "budgets":
return handleBudget(ctx);
case "refs":
case "references":
case "resolve":
return handleRefs(ctx);
case "relations":
case "relation":
case "links":
return handleRelations(ctx);
case "attachments":
case "attachment":
case "files":
return handleAttachments(ctx);
case "download":
case "file-download":
return handleDownload(ctx);
case "link":
case "url":
return handleLink(ctx);
case "spec":
case "specification":
return handleSpec(ctx);
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
}
}
+197
View File
@@ -0,0 +1,197 @@
import {
formatFormPriorityList,
getFieldDictionary,
getBillByCodeOrId,
hasLinkageOverridePriority,
inspectFormSpecification,
} from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
export async function handleSchema(ctx: BillActionContext): Promise<CliResult> {
const { runtime, corp, corpId } = ctx;
const { entities } = await getFieldDictionary(await ctx.getClient(), corpId, true);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
const rows = entities.map((e, idx) => [
idx + 1,
e.id,
e.name || "-",
e.type || "-",
e.fields.length,
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
return {
stdout: title + tableOutput + "\n",
stderr: "",
exitCode: 0,
};
}
export async function handleLink(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
if (!target) {
return {
stdout: "",
stderr: "用法: hose-use bill link <单号或ID>",
exitCode: 1,
};
}
const items = await getBillByCodeOrId(await ctx.getClient(), 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,
};
}
export async function handleSpec(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
if (!target) {
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
}
const inspection = await inspectFormSpecification(await ctx.getClient(), corpId, target);
if (!inspection) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
exitCode: 1,
};
}
const { specification: spec, warnings } = inspection;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
...spec,
warnings,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const rows = spec.components.map((comp, idx) => {
const priorityStr = formatFormPriorityList(comp.priorityList);
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
return [
idx + 1,
comp.name,
comp.label || "-",
comp.type,
comp.optional === false ? "🔴 必填" : "⚪ 选填",
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
comp.assignmentRule || "-",
priorityStr,
overrideRisk,
];
});
const outLines = [
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
` 模板 ID : ${spec.id}`,
` 模板名称 : ${spec.name || "-"}`,
` 单据类型 : ${spec.type || "-"}`,
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
` 字段总数 : ${spec.components.length} 个`,
"",
rows.length
? printTable(
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
rows
)
: "暂无表单组件定义",
];
if (warnings.length > 0) {
outLines.push("");
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
for (const w of warnings) {
outLines.push(` • ${w}`);
}
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
+116
View File
@@ -0,0 +1,116 @@
import { downloadBillAttachments, getBillAttachments, getBillReferences, getBillRelations } from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
export async function handleRefs(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
const report = await getBillReferences(await ctx.getClient(), 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 };
}
export async function handleRelations(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
const report = await getBillRelations(await ctx.getClient(), 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 };
}
export async function handleAttachments(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
const report = await getBillAttachments(await ctx.getClient(), 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 };
}
export async function handleDownload(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use 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(await ctx.getClient(), 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 };
}
+200
View File
@@ -0,0 +1,200 @@
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills } from "../../../domains/bill/tools.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
if (mine) {
const { handleTaskCommand } = await import("./../task.js");
return handleTaskCommand(
{
...parsed,
area: "task",
action: "submitted",
},
runtime
);
}
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const since = stringOption(parsed.options, ["since", "days", "d"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
const select = stringOption(parsed.options, ["select", "fields"]);
const distinct = booleanOption(parsed.options, ["distinct"]);
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
code,
keyword,
searchFields,
stage,
state,
count,
since,
startDate,
endDate,
order,
filterBy,
select,
distinct,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
const rows = result.items.map((b, idx) => [
idx + 1,
b.billCode,
b.billName,
b.stage || "-",
b.state || "-",
b.amount || "-",
b.submitDate || b.createTime || "-",
]);
const filterSummary: string[] = [];
if (since) filterSummary.push(`近 ${since}`);
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
if (code) filterSummary.push(`单号: ${code}`);
if (keyword) {
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
}
if (stage) filterSummary.push(`阶段: ${stage}`);
if (state) filterSummary.push(`状态: ${state}`);
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
stdout: title + tableOutput + tip,
stderr: "",
exitCode: 0,
};
}
export async function handleGet(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(await ctx.getClient(), corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
const riskReports = withRisk
? await Promise.all(bills.map(async (bill) => getBillRisk(await ctx.getClient(), corpId, bill.billId || bill.billCode)))
: [];
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
count: bills.length,
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outputs: string[] = [];
for (let i = 0; i < bills.length; i++) {
const b = bills[i];
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
outputs.push(` 单据 ID : ${b.billId}`);
outputs.push(` 单据名称 : ${b.billName}`);
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
outputs.push(` 创建时间 : ${b.createTime}`);
outputs.push(` 更新时间 : ${b.updateTime}`);
outputs.push(`\n --- 结构化表单字段明细 ---`);
const detailEntries = Object.entries(b.details);
if (detailEntries.length === 0) {
outputs.push(` (无额外字段数据)`);
} else {
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
for (const [k, v] of detailEntries) {
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
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 {
stdout: outputs.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
+87
View File
@@ -0,0 +1,87 @@
import { describe, it, expect } from "bun:test";
import { handleConfigCommand } from "./config.js";
import type { CliRuntime } from "../types.js";
describe("cli/commands/config > aliases and path mapping", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("maps config show to config paths diagnosis", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "show",
args: [],
options: {},
raw: ["config", "show"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
expect(res.stdout).toContain("当前生效配置文件");
expect(res.stdout).toContain("运行模式 (Mode)");
});
it("supports config paths directly", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "paths",
args: [],
options: {},
raw: ["config", "paths"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("配置路径诊断 (Config Paths)");
});
it("supports config show --json structured output", async () => {
const jsonRuntime = { ...dummyRuntime, jsonMode: true };
const res = await handleConfigCommand(
{
area: "config",
action: "show",
args: [],
options: { json: true },
raw: ["config", "show", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data).toHaveProperty("configFile");
expect(data).toHaveProperty("writableDir");
expect(data).toHaveProperty("mode");
});
it("supports config get for inspecting global stateful configuration", async () => {
const res = await handleConfigCommand(
{
area: "config",
action: "get",
args: [],
options: {},
raw: ["config", "get"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("全局运行配置");
expect(res.stdout).toContain("运行模式 (Mode)");
});
});
+101 -11
View File
@@ -1,3 +1,4 @@
import { resolve } from "node:path";
import {
loadGlobalConfig,
saveGlobalConfig,
@@ -6,32 +7,39 @@ import {
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { booleanOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleConfigCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "show";
const action = parsed.action || "paths";
switch (action) {
case "show":
case "get":
case "list":
return handleShow(parsed, runtime);
case "paths":
case "path":
case "dirs":
case "show":
case "list":
return handlePaths(parsed, runtime);
case "get":
case "status":
case "info":
return handleShow(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "test-dir":
case "test-enterprises-dir":
return handleTestDir(parsed, runtime);
case "set":
return handleSet(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
stderr: `未知 config 子命令: ${action}。支持: paths, show, get, mode <stateful|stateless>, test-dir <path|--clear>, set <key> <val>\n`,
exitCode: 1,
};
}
@@ -47,6 +55,7 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId || null,
defaultAccountId: globalConfig.defaultAccountId || null,
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
updateRepo: globalConfig.updateRepo || null,
updateSource: globalConfig.updateSource || "auto",
@@ -61,13 +70,14 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"测试企业目录": globalConfig.testEnterprisesDir || "未配置 (仅读全局用户企业)",
"默认自更新仓库": 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 更新源设置: hose config set updateSource <auto|github|gitea>\n`,
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n`,
stderr: "",
exitCode: 0,
};
@@ -79,12 +89,16 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (!targetMode || (targetMode !== "stateful" && targetMode !== "stateless")) {
return {
stdout: "",
stderr: "用法: hose config mode <stateful|stateless>\n",
stderr: "用法: hose-use config mode <stateful|stateless>\n",
exitCode: 1,
};
}
const isStateful = targetMode === "stateful";
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换全局运行模式", targetMode, { stateful: isStateful });
}
requireMutationConfirmation(parsed, runtime, "切换全局运行模式", `hose-use config mode ${targetMode} --yes`);
const updated = saveGlobalConfig({ stateful: isStateful });
if (runtime.jsonMode) {
@@ -98,6 +112,62 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
};
}
async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const isClear = booleanOption(parsed.options, ["clear"]) || parsed.args[0] === "--clear" || parsed.args[0] === "clear";
const globalConfig = loadGlobalConfig();
if (isClear) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "清除测试企业目录配置", globalConfig.testEnterprisesDir || "当前未设置", { testEnterprisesDir: null });
}
requireMutationConfirmation(parsed, runtime, "清除测试企业目录配置", "hose-use config test-dir --clear --yes");
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: "[SUCCESS] 已清除测试企业目录配置,恢复默认全局目录。\n",
stderr: "",
exitCode: 0,
};
}
const dirArg = parsed.args[0];
if (!dirArg) {
const info = {
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
configFile: resolveGlobalConfigFile(),
};
if (runtime.jsonMode) {
return { stdout: printJson(info), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前测试企业目录": globalConfig.testEnterprisesDir || "未配置 (当前只读全局企业目录)",
"全局配置文件路径": resolveGlobalConfigFile(),
});
return {
stdout: `====== 测试企业目录配置 ======\n${output}\n\n提示:\n 设置测试目录: hose-use config test-dir <path>\n 清除测试目录: hose-use config test-dir --clear\n`,
stderr: "",
exitCode: 0,
};
}
const resolved = resolve(dirArg);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "设置测试企业目录", resolved, { testEnterprisesDir: resolved });
}
requireMutationConfirmation(parsed, runtime, "设置测试企业目录", `hose-use config test-dir ${dirArg} --yes`);
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: `[SUCCESS] 测试企业目录已设置为: ${resolved}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const rawKey = parsed.args[0];
const val = parsed.args[1];
@@ -105,7 +175,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
if (!rawKey || val === undefined) {
return {
stdout: "",
stderr: "用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)\n",
stderr: "用法: hose-use config set <key> <val> (如 hose-use config set defaultCorpId uzU7pcWfScck00)\n",
exitCode: 1,
};
}
@@ -123,6 +193,13 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
} else if (keyLower === "defaultaccountid") {
resolvedKey = "defaultAccountId";
partial.defaultAccountId = val;
} else if (keyLower === "testenterprisesdir" || keyLower === "testdir") {
resolvedKey = "testEnterprisesDir";
if (val === "clear" || val === "none" || val === "" || val === "null") {
partial.testEnterprisesDir = undefined;
} else {
partial.testEnterprisesDir = resolve(val);
}
} else if (keyLower === "updaterepo") {
resolvedKey = "updateRepo";
partial.updateRepo = val;
@@ -140,11 +217,15 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
} else {
return {
stdout: "",
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, updateRepo, updateSource\n`,
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource\n`,
exitCode: 1,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "更新全局配置", resolvedKey, partial);
}
requireMutationConfirmation(parsed, runtime, "更新全局配置", `hose-use config set ${rawKey} ${val} --yes`);
const updated = saveGlobalConfig(partial);
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
@@ -165,11 +246,17 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
const writableDir = resolveWritableEnterprisesDir();
const configFile = resolveGlobalConfigFile();
const candidates = getEnterprisesDirCandidates();
const globalConfig = loadGlobalConfig();
const currentCorp = runtime.selectedCorp;
const data = {
configFile,
writableDir,
existingDirs,
mode: globalConfig.stateful ? "stateful" : "stateless",
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
env: {
HOSE_ENTERPRISES_DIR: envDir || null,
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
@@ -179,13 +266,16 @@ async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
};
if (runtime.jsonMode) {
return { stdout: printJson(data), stderr: "", exitCode: 0 };
return { stdout: printJson(data, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前生效配置文件": configFile,
"凭证保存写入目录": writableDir,
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
"全部目录候选链": candidates.join("\n "),
});
+6 -6
View File
@@ -16,7 +16,7 @@ export async function handleContactCommand(
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",
stderr: "未指定或未找到有效企业配置。请运行 'hose-use corps list' 或指定 '--corp=<id>'",
exitCode: 1,
};
}
@@ -24,13 +24,13 @@ export async function handleContactCommand(
const action = parsed.action || parsed.args[0] || "list";
const limit = numberOption(parsed.options, ["limit", "l"]);
// 1. 搜索: hose contact search <keyword> 或 hose contact find <keyword>
// 1. 搜索: hose-use contact search <keyword> 或 hose-use 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 <关键词 (姓名/邮箱/工号)>",
stderr: "用法: hose-use contact search <关键词 (姓名/邮箱/工号)>",
exitCode: 1,
};
}
@@ -67,13 +67,13 @@ export async function handleContactCommand(
};
}
// 2. 详情: hose contact get <staffId>
// 2. 详情: hose-use 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>",
stderr: "用法: hose-use contact get <staffId>",
exitCode: 1,
};
}
@@ -110,7 +110,7 @@ export async function handleContactCommand(
};
}
// 3. 列表采样: hose contact list (默认限流截断防爆)
// 3. 列表采样: hose-use contact list (默认限流截断防爆)
if (action === "list") {
const isFull = runtime.outputOptions?.allowFull === true;
const result = await listStaffsProtected(corp, {
+97
View File
@@ -0,0 +1,97 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
import { runAiProCli } from "../../aipro-cli.js";
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
import { ApprovalRepository } from "../../domains/approval/repository.js";
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{硬性}。",
});
repo.createRule({
scope: "业务招待",
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。",
});
});
afterEach(() => {
closeApprovalDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
test("hose-use context 打印文本格式仪表盘", async () => {
const res = await runCli(["context"]);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("全局运行上下文与身份诊断");
expect(res.stdout).toContain("AI PRO 规约库");
expect(res.stdout).toContain("差旅报销");
expect(res.stdout).toContain("业务招待");
});
test("hose-use context --json 输出完备的结构化数据", async () => {
const res = await runCli(["context", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.tool).toBe("hose-use");
expect(data.corporationsSummary).toBeDefined();
expect(data.aiProGateway).toBeDefined();
expect(data.aiProGateway.scopesCount).toBe(2);
expect(data.aiProGateway.rulesCount).toBe(2);
expect(data.runtime.mode).toBeDefined();
expect(data.runtime.configFile).toBeDefined();
});
test("hose-use status 与 whoami 别名成功解析至 context", async () => {
const resStatus = await runCli(["status", "--json"]);
expect(resStatus.exitCode).toBe(0);
const dataStatus = JSON.parse(resStatus.stdout);
expect(dataStatus.tool).toBe("hose-use");
const resWhoami = await runCli(["whoami", "--json"]);
expect(resWhoami.exitCode).toBe(0);
const dataWhoami = JSON.parse(resWhoami.stdout);
expect(dataWhoami.tool).toBe("hose-use");
});
test("hose-aipro status 输出 AI PRO 专属上下文", async () => {
const res = await runAiProCli(["status"]);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("合思 AI PRO 确定性审批网关运行上下文");
expect(res.stdout).toContain("规约场景库");
expect(res.stdout).toContain("差旅报销");
});
test("hose-aipro status --json 输出结构化数据", async () => {
const res = await runAiProCli(["status", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.tool).toBe("hose-aipro");
expect(data.ruleEngine.scopesCount).toBe(2);
expect(data.ruleEngine.rulesCount).toBe(2);
expect(data.sessions).toBeDefined();
});
test("hose-use aipro status 双向桥接成功转发", async () => {
const res = await runCli(["aipro", "status", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.tool).toBe("hose-aipro");
expect(data.ruleEngine.scopesCount).toBe(2);
});
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
const res = await runAiProCli(["help"]);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[当前");
expect(res.stdout).toContain("hose-aipro status");
});
});
+156
View File
@@ -0,0 +1,156 @@
import { getActiveAccount } from "../../core/auth/account-store.js";
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
import {
resolveGlobalConfigFile,
resolvePrimaryEnterprisesDir,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { ApprovalRepository } from "../../domains/approval/index.js";
import { VERSION } from "../../version.js";
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleContextCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
const allCorps = runtime.corpContext.listCorps();
const activeAccount = getActiveAccount();
const isStateful = runtime.corpContext.isStateful();
const configFile = resolveGlobalConfigFile();
const enterprisesDir = resolvePrimaryEnterprisesDir() || resolveWritableEnterprisesDir();
let scopesCount = 0;
let rulesCount = 0;
let scopes: Array<{ index: number; scope: string; ruleCount: number }> = [];
let totalRunsCount = 0;
let pendingRunsCount = 0;
try {
const repo = new ApprovalRepository();
const loadedScopes = repo.listScopes("active");
scopesCount = loadedScopes.length;
scopes = loadedScopes.map((s) => ({
index: s.index,
scope: s.scope,
ruleCount: s.ruleCount,
}));
const loadedRules = repo.listRules();
rulesCount = loadedRules.length;
const runs = currentCorp?.id ? repo.listRuns({ corpId: currentCorp.id }) : repo.listRuns();
totalRunsCount = runs.length;
pendingRunsCount = runs.filter((r) => r.decision === "PENDING").length;
} catch {
// 容错处理(如 SQLite 尚未初始化等场景)
}
const now = Date.now();
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
const currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
tool: "hose-use",
version: VERSION,
account: activeAccount
? {
accountId: activeAccount.accountId,
userId: activeAccount.userId || null,
corporationCount: activeAccount.corporations.length,
}
: currentCorp?.accountId
? {
accountId: currentCorp.accountId,
userId: null,
corporationCount: allCorps.filter((c) => c.accountId === currentCorp.accountId).length,
}
: null,
activeCorporation: currentCorp
? {
id: currentCorp.id,
name: currentCorp.name,
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
source: currentCorp.source,
persistent: currentPersistent,
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
expired: currentPersistent
? false
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
: false,
baseUrl: currentCorp.baseUrl,
accountId: currentCorp.accountId || null,
}
: null,
corporationsSummary: {
total: allCorps.length,
validCount: validCorps.length,
expiredCount: expiredCorps.length,
activeCorpId: currentCorp?.id || null,
},
aiProGateway: {
connectedCorpId: currentCorp?.id || null,
scopesCount,
rulesCount,
scopes,
pendingRunsCount,
totalRunsCount,
},
runtime: {
mode: isStateful ? "stateful" : "stateless",
configFile,
enterprisesDir,
candidates: getEnterprisesDirCandidates(),
},
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const accountStr = activeAccount?.accountId || currentCorp?.accountId || "-";
const userIdStr = activeAccount?.userId ? ` (用户 ID: ${activeAccount.userId})` : "";
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
const scopesStr =
scopes.length > 0
? `已加载 ${scopesCount} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ")}),共 ${rulesCount} 条仲裁规则`
: "暂未配置场景规则 (可使用 hose-use rule add 添加)";
const lines = [
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
` 当前活跃账号 : ${accountStr}${userIdStr}`,
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
` AI PRO 规约库 : ${scopesStr}`,
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
` 全局配置文件 : ${configFile}`,
` 企业凭证目录 : ${enterprisesDir}`,
"",
"提示:",
" - hose-use 与 hose-aipro 默认共享同一套企业与身份凭证上下文,无须重复配置。",
" - 切换全局默认企业: hose-use corps switch <企业ID>",
" - 单次临时指定企业: hose-use --corp=<企业ID> <命令> 或 hose-aipro --corp=<企业ID> <子命令>",
" - AI PRO 专属上下文: hose-aipro status",
"",
];
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
}
+366
View File
@@ -0,0 +1,366 @@
import { describe, it, expect } from "bun:test";
import { parseHeadersOrCurl } from "../../core/auth/login.js";
import { resolveCorpCluster } from "../../core/http/unity-client.js";
import { handleCorpsCommand } from "./corps/index.js";
import type { CliRuntime } from "../types.js";
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
it("successfully parses standard thirdparty.html assistance links", () => {
const url = "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=token123&ekbCorpId=corpABC&pageType=home";
const parsed = parseHeadersOrCurl(url);
expect(parsed.baseUrl).toBe("https://wx2.ekuaibao.com");
expect(parsed.accessToken).toBe("token123");
expect(parsed.corpId).toBe("corpABC");
});
it("extracts custom staffId and standard corpId query params", () => {
const url = "https://app.ekuaibao.com/thirdparty.html?token=secret999&corpId=corpXYZ&staffId=corpXYZ:user1";
const parsed = parseHeadersOrCurl(url);
expect(parsed.baseUrl).toBe("https://app.ekuaibao.com");
expect(parsed.accessToken).toBe("secret999");
expect(parsed.corpId).toBe("corpXYZ");
expect(parsed.staffId).toBe("corpXYZ:user1");
});
it("handles curl command lines with assistance URL", () => {
const curl = `curl "https://wx.ekuaibao.com/web/thirdparty.html?accessToken=testToken&ekbCorpId=testCorp" -H "User-Agent: Mozilla"`;
const parsed = parseHeadersOrCurl(curl);
expect(parsed.baseUrl).toBe("https://wx.ekuaibao.com");
expect(parsed.accessToken).toBe("testToken");
expect(parsed.corpId).toBe("testCorp");
});
});
describe("core/http/unity-client > resolveCorpCluster", () => {
it("prioritizes explicit cluster config", () => {
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
});
it("extracts cluster from hostname subdomain", () => {
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
expect(resolveCorpCluster({ baseUrl: "https://wx.ekuaibao.com" })).toBe("wx");
expect(resolveCorpCluster({ baseUrl: "https://app.ekuaibao.com" })).toBe("app");
});
it("falls back to app when unknown", () => {
expect(resolveCorpCluster({})).toBe("app");
expect(resolveCorpCluster({ baseUrl: "https://custom-domain.com" })).toBe("app");
});
});
describe("cli/commands/corps > handleCorpsCommand add-link", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("returns error exit code when no link URL is provided", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "add-link",
args: [],
options: {},
raw: ["corps", "add-link"],
},
dummyRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("必须提供协助/免密链接 URL");
});
});
describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
const mockCorps = [
{
id: "corpAlpha",
name: "阿尔法网络科技有限公司",
corpId: "alphaPhysicalId",
staffId: "STAFF_001",
staffName: "张三",
accountId: "13800000001",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "token-alpha",
corpId: "alphaPhysicalId",
staffId: "STAFF_001",
},
},
{
id: "corpBeta@13900000002",
name: "贝塔云端信息系统",
corpId: "corpBeta",
staffId: "STAFF_002",
staffName: "李四",
accountId: "13900000002",
source: "link",
baseUrl: "https://wx2.ekuaibao.com",
credentials: {
accessToken: "token-beta",
corpId: "corpBeta",
staffId: "STAFF_002",
},
session: {
staffName: "李四",
cellphone: "13900000002",
},
},
];
const searchRuntime: CliRuntime = {
corpContext: {
getAllCorps: () => mockCorps,
listCorps: () => mockCorps.map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId,
staffId: c.staffId,
staffName: c.staffName,
accountId: c.accountId,
source: c.source,
current: c.id === "corpAlpha",
})),
getCurrent: () => mockCorps[0],
switchCorp: (id: string) => mockCorps.some((c) => c.id === id),
resolve: () => mockCorps[0],
} as any,
selectedCorp: mockCorps[0] as any,
jsonMode: false,
};
it("returns error exit code when search keyword is empty", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: [],
options: {},
raw: ["corps", "search"],
},
searchRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use corps search <关键词>");
});
it("searches by name with case-insensitive substring match", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["阿尔法"],
options: {},
raw: ["corps", "search", "阿尔法"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
expect(res.stdout).toContain("命中企业名称");
expect(res.stdout).toContain("* 1"); // 当前激活标记
});
it("searches by staffName and highlights the matched cell", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["李四"],
options: {},
raw: ["corps", "search", "李四"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[李四]");
expect(res.stdout).toContain("命中员工姓名");
expect(res.stdout).toContain("corpBeta");
});
it("searches by staffId case-insensitively", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["staff_001"],
options: {},
raw: ["corps", "search", "staff_001"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[STAFF_001]");
expect(res.stdout).toContain("命中员工工号");
});
it("searches by physical corpId", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["alphaPhysicalId"],
options: {},
raw: ["corps", "search", "alphaPhysicalId"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("阿尔法网络科技有限公司");
expect(res.stdout).toContain("命中企业ID");
});
it("searches by accountId", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["13900000002"],
options: {},
raw: ["corps", "search", "13900000002"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[13900000002]");
expect(res.stdout).toContain("命中所属账号");
});
it("supports find alias for search", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "find",
args: ["阿尔法"],
options: {},
raw: ["corps", "find", "阿尔法"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[阿尔法网络科技有限公司]");
});
it("outputs friendly message when no corps match", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["nonexistent_keyword"],
options: {},
raw: ["corps", "search", "nonexistent_keyword"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toBe("未找到匹配 \"nonexistent_keyword\" 的企业配置\n");
});
it("supports --json mode with structured output", async () => {
const jsonRuntime = { ...searchRuntime, jsonMode: true };
const res = await handleCorpsCommand(
{
area: "corps",
action: "search",
args: ["阿尔法"],
options: { json: true },
raw: ["corps", "search", "阿尔法", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.keyword).toBe("阿尔法");
expect(data.count).toBe(1);
expect(data.activeCorpId).toBe("corpAlpha");
expect(data.corporations).toHaveLength(1);
expect(data.corporations[0].id).toBe("corpAlpha");
expect(data.corporations[0].name).toBe("阿尔法网络科技有限公司");
expect(data.corporations[0].matchedFields).toContain("name");
});
it("outputs help message via corps help", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "help",
args: [],
options: {},
raw: ["corps", "help"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("hose-use corps <子命令>");
expect(res.stdout).toContain("search <关键词>");
expect(res.stdout).toContain("find");
});
it("generates login link via corps link [corp] with preserveSensitiveStdout=true", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { "content-type": "application/json" },
})) as unknown as typeof fetch;
try {
const res = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: {},
raw: ["corps", "link", "corpAlpha"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.preserveSensitiveStdout).toBe(true);
expect(res.stdout).toContain("thirdparty.html?accessToken=token-alpha&ekbCorpId=alphaPhysicalId");
} finally {
globalThis.fetch = originalFetch;
}
});
it("supports corps add-persistent --dry-run", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "add-persistent",
args: [],
options: {
"app-key": "key-1",
"app-security": "sec-1",
"dry-run": true,
},
raw: ["corps", "add-persistent", "--app-key=key-1", "--app-security=sec-1", "--dry-run"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
});
});
@@ -1,83 +1,24 @@
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../../core/auth/login.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
export async function handleCorpsCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "list";
switch (action) {
case "list":
return handleList(parsed, runtime);
case "switch":
case "use":
return handleSwitch(parsed, runtime);
case "current":
return handleCurrent(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current\n`,
exitCode: 1,
};
}
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corps = runtime.corpContext.listCorps();
if (runtime.jsonMode) {
return {
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (corps.length === 0) {
return { stdout: "未找到任何企业配置,请先运行 hose auth login\n", stderr: "", exitCode: 0 };
}
const rows = corps.map((c, i) => [
c.current ? `* ${i + 1}` : ` ${i + 1}`,
c.id,
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt),
c.accountId || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
return {
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose corps switch <企业ID> 切换工作企业\n`,
stderr: "",
exitCode: 0,
};
}
async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corpId = parsed.args[0];
if (!corpId) {
return { stdout: "", stderr: "用法: hose corps switch <企业ID>\n", exitCode: 1 };
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId });
}
requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`);
const success = runtime.corpContext.switchCorp(corpId);
if (!success) {
return {
stdout: "",
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose corps list 查看可用列表。\n`,
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose-use corps list 查看可用列表。\n`,
exitCode: 1,
};
}
@@ -94,7 +35,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
};
}
async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const current = runtime.selectedCorp;
if (!current) {
return { stdout: "", stderr: "未选中任何企业\n", exitCode: 1 };
@@ -104,15 +45,20 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const hasOpenApi = hasOpenApiPersistentCredentials(current);
const isPersistent = canRefreshCorpAccessToken(current);
const pairs: Record<string, unknown> = {
"企业 ID": current.id,
"企业名称": current.name,
"员工工号": current.credentials.staffId,
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source),
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
"所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
};
if (current.session) {
+395
View File
@@ -0,0 +1,395 @@
import { join } from "node:path";
import {
elevateCorpWithOpenApiKey,
extractOpenApiKeysFromLink,
hasOpenApiPersistentCredentials,
maskOpenApiSecurity,
onboardHosePersistent,
syncOpenApiFromSealUse,
} from "../../../core/auth/login.js";
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
import { stringOption, booleanOption } from "../../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
export async function handleAddPersistent(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
let jsonPayload: Record<string, unknown> = {};
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
if (rawJsonArg) {
try {
jsonPayload = JSON.parse(rawJsonArg);
} catch {
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
}
}
const appKey =
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
const appSecurity =
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
const domain =
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
const corpId =
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
const staffId =
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
const staffName =
stringOption(parsed.options, ["staff-name", "staffName"]) ||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
const staffPhone =
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
const role =
stringOption(parsed.options, ["role"]) ||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
const name =
stringOption(parsed.options, ["name"]) ||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
if (!appKey || !appSecurity) {
return {
stdout: "",
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
exitCode: 1,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
source: "openapi",
appKey,
domain: domain || "auto-probe",
staffId: staffId || "auto-discover",
overwrite,
});
}
requireMutationConfirmation(
parsed,
runtime,
"通过 OpenAPI 持久化密钥接入企业",
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
);
const saved = await onboardHosePersistent({
name,
appKey,
appSecurity,
domain,
corpId,
staffId,
staffName,
staffPhone,
role,
force,
overwrite,
});
if (runtime.jsonMode) {
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const targetDir = resolveWritableEnterprisesDir();
const savedPath = join(targetDir, `${saved.id}.json`);
const summaryText = printKeyValue({
"企业名称": saved.name,
"企业 ID": saved.id,
"服务节点": saved.baseUrl,
"员工工号": saved.credentials.staffId,
"员工姓名": saved.staffName || saved.session?.staffName || "-",
"接入账号 (appKey)": saved.credentials.appKey,
"凭证来源": formatSourceLabel(saved.source, true),
"保存路径": savedPath,
});
return {
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
}
export async function handleExtractKeys(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
if (!linkUrl) {
return {
stdout: "",
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
exitCode: 1,
};
}
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
const name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
const force = booleanOption(parsed.options, ["force", "f"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
if (save) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
save: true,
overwrite,
appKey: appKey || "auto-select",
});
}
requireMutationConfirmation(
parsed,
runtime,
"从协助链接提取并持久化 OpenAPI 密钥",
`hose-use corps extract-keys "<url>" --save --yes`
);
}
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
save,
name,
overwrite,
force,
appKey,
keyId,
});
const formattedKeys = extracted.keys.map((k) => ({
id: k.id,
name: k.name || "-",
appKey: k.appKey,
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
active: k.active,
createTime: k.createTime,
updateTime: k.updateTime,
}));
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: extracted.corpId,
corpName: extracted.corpName || extracted.corpId,
baseUrl: extracted.baseUrl,
staffId: extracted.staffId,
keyCount: formattedKeys.length,
keys: formattedKeys,
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
const rows = formattedKeys.map((k, i) => [
i + 1,
k.name,
k.appKey,
k.appSecurity,
k.active ? "🟢 启用" : "⚪ 停用",
]);
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
const savedNotice = extracted.savedCorp
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
: "";
return {
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
export async function handleElevateCorp(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"], true);
if (elevateAll) {
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: [];
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
count: allCorps.length,
});
}
requireMutationConfirmation(
parsed,
runtime,
"批量提取并持久化全部企业 OpenAPI 密钥",
`hose-use corps elevate --all --yes`
);
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
for (const corp of allCorps) {
if (hasOpenApiPersistentCredentials(corp)) {
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
continue;
}
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
if (selected) {
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
} else {
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
}
}
if (runtime.jsonMode) {
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
return {
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
stderr: "",
exitCode: 0,
};
}
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
if (!targetCorp) {
return {
stdout: "",
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
exitCode: 1,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
corpId: targetCorp.id,
appKey: appKey || "auto-select",
});
}
requireMutationConfirmation(
parsed,
runtime,
"提取并持久化企业 OpenAPI 密钥",
`hose-use corps elevate ${targetCorp.id} --yes`
);
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
appKey,
keyId,
force,
});
if (!selected) {
return {
stdout: "",
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: targetCorp.id,
corpName: targetCorp.name,
appKey: selected.appKey,
appSecurity: maskOpenApiSecurity(selected.appSecurity),
keyName: selected.name || "-",
persistent: true,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
stderr: "",
exitCode: 0,
};
}
export async function handleSyncFromSeal(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
const verify = booleanOption(parsed.options, ["verify"], false);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
filter: filter || null,
verify,
overwrite,
});
}
requireMutationConfirmation(
parsed,
runtime,
"从 seal-use 同步企业 OpenAPI 持久化密钥",
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
);
const synced = await syncOpenApiFromSealUse({
filter,
sealEnterprisesDir: sealDir,
verify,
overwrite,
});
if (runtime.jsonMode) {
return {
stdout: printJson(synced, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (synced.items.length === 0) {
return {
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
stderr: "",
exitCode: 0,
};
}
const rows = synced.items.map((item, idx) => [
idx + 1,
item.corpId,
item.name,
item.appKey,
item.staffId,
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
]);
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
return {
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
stderr: "",
exitCode: 0,
};
}
+122
View File
@@ -0,0 +1,122 @@
import { stringOption } from "../../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { handleList, handleSearch } from "./query.js";
import { handleSwitch, handleCurrent } from "./context.js";
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
import { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
// 供 auth.ts 等跨命令复用的 handler 与 helper 维持原有命名导出。
export { handleGenerateCorpLink } from "./link.js";
export { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
export { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
export async function handleCorpsCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "list";
switch (action) {
case "list":
case "ls":
return handleList(parsed, runtime);
case "search":
case "find":
case "query":
case "filter":
return handleSearch(parsed, runtime);
case "switch":
case "use":
return handleSwitch(parsed, runtime);
case "current":
case "whoami":
case "status":
case "active":
return handleCurrent(parsed, runtime);
case "add-link":
case "import-link":
return handleAddLink(parsed, runtime);
case "link": {
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
if (isHttpUrl(maybeUrl)) {
return handleAddLink(parsed, runtime);
}
return handleGenerateCorpLink(parsed, runtime);
}
case "hose-link":
case "auth-link":
case "login-link":
return handleGenerateCorpLink(parsed, runtime);
case "add-persistent":
case "add-hose-persistent":
case "add-openapi":
case "add-hose":
return handleAddPersistent(parsed, runtime);
case "extract-keys":
case "extract-key":
case "hose-extract-keys":
case "extract-hose-keys":
return handleExtractKeys(parsed, runtime);
case "elevate":
case "elevate-hose":
return handleElevateCorp(parsed, runtime);
case "sync-seal":
case "sync-from-seal":
case "import-seal":
return handleSyncFromSeal(parsed, runtime);
case "probe-hose":
return handleProbeHose(parsed, runtime);
case "hose-staffs":
return handleHoseStaffs(parsed, runtime);
case "help":
return handleCorpsHelp();
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
exitCode: 1,
};
}
}
export function printCorpsHelp(): string {
return `
用法:
hose-use corps <子命令> [参数] [选项]
子命令:
list 列出本地已保存的所有企业配置 (别名: ls)
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
选项:
--json, -j 以 JSON 格式输出
--help, -h 查看帮助信息
示例:
hose-use corps list
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
hose-use corps link 新转转集团
hose-use corps add-link "<url>" --elevate --yes
hose-use corps add-persistent --app-key=... --app-security=... --yes
`.trim();
}
function handleCorpsHelp(): CliResult {
return {
stdout: printCorpsHelp() + "\n",
stderr: "",
exitCode: 0,
};
}
+200
View File
@@ -0,0 +1,200 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { getCorpProvisionalAuthLink, hasOpenApiPersistentCredentials, importFromLink } from "../../../core/auth/login.js";
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
import { stringOption, booleanOption } from "../../parser.js";
import { prompt } from "../../helpers.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
export async function handleGenerateCorpLink(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const targetArg = parsed.args[0];
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
if (!targetCorp) {
return {
stdout: "",
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
exitCode: 1,
};
}
const expiresIn =
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
expiresIn,
pageType,
force,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: linkRes.corpId,
corpName: linkRes.corpName,
staffId: linkRes.staffId,
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
link: linkRes.url,
expiresAt: linkRes.expiresAt,
expiresIn: linkRes.expiresIn,
token: linkRes.token,
persistent: linkRes.persistent,
method: linkRes.method,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: true,
};
}
const lines = [
`====== 合思企业 Web 免密登录直达链接 ======`,
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
` 过期时间 : ${linkRes.expiresAt}`,
` 直达链接 :`,
` ${linkRes.url}`,
``,
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
];
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: true,
};
}
export async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
const name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"], false);
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
}
if (!linkUrl) {
return {
stdout: "",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
exitCode: 1,
};
}
let targetCorpId = "";
try {
const parsedUrl = new URL(linkUrl);
targetCorpId = parsedUrl.searchParams.get("ekbCorpId") || "";
} catch {}
const targetDir = resolveWritableEnterprisesDir();
const existsAlready = Boolean(targetCorpId && existsSync(join(targetDir, `${targetCorpId}.json`)));
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"从协助链接导入企业凭证",
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
{
source: "assistance-link",
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
overwrite,
alreadyExists: existsAlready,
ttl: ttl || null,
expires: expires || null,
note: existsAlready && !overwrite ? "检测到本地已存在该企业配置,导入执行时请带上 --overwrite 参数" : undefined,
}
);
}
const nextConfirmCmd = existsAlready && !overwrite
? `hose-use corps add-link <url> --overwrite --yes`
: `hose-use corps add-link <url> --yes`;
const confirmOp = existsAlready && !overwrite
? `从协助链接导入企业凭证(检测到目标企业 [${targetCorpId}] 已存在,需覆盖更新)`
: "从协助链接导入企业凭证";
requireMutationConfirmation(parsed, runtime, confirmOp, nextConfirmCmd);
try {
const corp = await importFromLink(linkUrl, {
name,
overwrite,
ttl,
expires,
appKey,
keyId,
elevate: elevate ? true : noElevate ? false : undefined,
autoElevate: !noElevate,
force,
});
if (runtime.jsonMode) {
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const savedPath = join(targetDir, `${corp.id}.json`);
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
const summaryPairs: Record<string, unknown> = {
"企业名称": corp.name,
"企业 ID": corp.id,
"集群环境": corp.cluster || "app",
"员工工号": corp.credentials.staffId,
"员工姓名": corp.staffName || corp.session?.staffName || "-",
"手机号码": corp.session?.cellphone || "-",
"是否管理": corp.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
"服务节点": corp.baseUrl,
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
"保存路径": savedPath,
};
if (corp.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (corp.session.operationUserName || corp.session.operationUserId) {
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
}
if (corp.session.assistId) {
summaryPairs["协助会话 ID"] = corp.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
} catch (error) {
return {
stdout: "",
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
exitCode: 1,
};
}
}
+70
View File
@@ -0,0 +1,70 @@
import { fetchHoseRoleDefGroups, listHoseStaffsByOpenApi, probeHoseDomain } from "../../../core/auth/login.js";
import { stringOption } from "../../parser.js";
import { printJson, printKeyValue, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
const domain = stringOption(parsed.options, ["domain", "base-url"]);
if (!appKey || !appSecurity) {
return {
stdout: "",
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
exitCode: 1,
};
}
const probe = await probeHoseDomain(appKey, appSecurity, domain);
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
const payload = {
domain: probe.domain,
corpId: probe.corpId,
name: probe.corpName || probe.corpId,
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
roleGroups,
};
if (runtime.jsonMode) {
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
"企业 ID": payload.corpId,
"企业名称": payload.name,
"服务节点": payload.domain,
"角色数量": payload.roleCount,
})}\n`,
stderr: "",
exitCode: 0,
};
}
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
const domain = stringOption(parsed.options, ["domain", "base-url"]);
const role = stringOption(parsed.options, ["role", "roleDefId"]);
if (!appKey || !appSecurity) {
return {
stdout: "",
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
exitCode: 1,
};
}
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
if (runtime.jsonMode) {
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
return {
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\n`,
stderr: "",
exitCode: 0,
};
}
+194
View File
@@ -0,0 +1,194 @@
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable, formatExpiresAt } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
const FIELD_LABEL_MAP: Record<string, string> = {
id: "配置ID",
name: "企业名称",
corpId: "企业ID",
staffId: "员工工号",
staffName: "员工姓名",
accountId: "所属账号",
};
export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k", "q", "name", "id"]);
if (!keyword || !keyword.trim()) {
return {
stdout: "",
stderr: "用法: hose-use corps search <关键词>\n",
exitCode: 1,
};
}
const kw = keyword.trim().toLowerCase();
// 从 CorpContext 中获取企业列表
const rawCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: null;
const normalizedCorps = rawCorps
? rawCorps.map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId || c.credentials?.corpId || c.id,
staffId: c.staffId || c.credentials?.staffId || "",
staffName: c.staffName || c.session?.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c),
}))
: runtime.corpContext.listCorps().map((c) => ({
id: c.id,
name: c.name,
corpId: c.corpId || c.id,
staffId: c.staffId || "",
staffName: c.staffName || "",
accountId: c.accountId || "",
source: c.source || "manual",
baseUrl: c.baseUrl,
current: c.current || c.id === runtime.selectedCorp?.id,
expiresAt: c.expiresAt,
persistent: c.persistent,
}));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
for (const corp of normalizedCorps) {
const matchedFields: string[] = [];
if (corp.id && corp.id.toLowerCase().includes(kw)) {
matchedFields.push("id");
}
if (corp.name && corp.name.toLowerCase().includes(kw)) {
matchedFields.push("name");
}
if (corp.corpId && corp.corpId.toLowerCase().includes(kw) && !matchedFields.includes("corpId") && corp.corpId !== corp.id) {
matchedFields.push("corpId");
}
if (corp.staffId && corp.staffId.toLowerCase().includes(kw)) {
matchedFields.push("staffId");
}
if (corp.staffName && corp.staffName.toLowerCase().includes(kw)) {
matchedFields.push("staffName");
}
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
matchedFields.push("accountId");
}
if (matchedFields.length > 0) {
matches.push({ ...corp, matchedFields });
}
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
keyword: keyword.trim(),
count: matches.length,
activeCorpId: runtime.selectedCorp?.id,
corporations: matches.map((m) => ({
id: m.id,
name: m.name,
corpId: m.corpId,
staffId: m.staffId,
staffName: m.staffName || undefined,
accountId: m.accountId || undefined,
source: m.source,
baseUrl: m.baseUrl,
current: m.current,
expiresAt: m.expiresAt,
persistent: m.persistent,
matchedFields: m.matchedFields,
})),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (matches.length === 0) {
return {
stdout: `未找到匹配 "${keyword.trim()}" 的企业配置\n`,
stderr: "",
exitCode: 0,
};
}
const rows = matches.map((m, i) => {
const isCurrent = m.current;
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
return [
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
matchLabels.map((l) => `命中${l}`).join(", "),
formatExpiresAt(m.expiresAt, m.persistent),
];
});
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
rows
);
return {
stdout: `====== 企业搜索结果 (关键词: "${keyword.trim()}", 找到 ${matches.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业\n - 标记 [...] 为命中关键词的字段\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
stderr: "",
exitCode: 0,
};
}
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corps = runtime.corpContext.listCorps();
if (runtime.jsonMode) {
return {
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
if (corps.length === 0) {
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
}
const rows = corps.map((c, i) => [
c.current ? `* ${i + 1}` : ` ${i + 1}`,
c.id,
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt, c.persistent),
c.accountId || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
return {
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
stderr: "",
exitCode: 0,
};
}
+30
View File
@@ -0,0 +1,30 @@
import type { CorpConfig } from "../../../core/config/types.js";
import type { CliRuntime } from "../../types.js";
export function isHttpUrl(val?: string): boolean {
return Boolean(val && /^https?:\/\//i.test(val.trim()));
}
export function resolveTargetCorpByArgOrContext(
targetArg: string | undefined,
runtime: CliRuntime
): CorpConfig | null {
if (targetArg && !isHttpUrl(targetArg)) {
try {
return runtime.corpContext.resolve(targetArg);
} catch {
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: [];
const kw = targetArg.trim().toLowerCase();
const matched = allCorps.find(
(c) =>
c.id.toLowerCase() === kw ||
(c.corpId && c.corpId.toLowerCase() === kw) ||
c.name.toLowerCase().includes(kw)
);
if (matched) return matched;
}
}
return runtime.selectedCorp;
}
+4 -4
View File
@@ -1,13 +1,13 @@
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 { createSessionClient } from "../../core/http/session-client.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);
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
const client = await createSessionClient(corp);
const corpId = corp.corpId || corp.id;
const action = parsed.action?.toLowerCase() || "list";
if (["list", "search", "catalogs", undefined].includes(action)) {
@@ -19,7 +19,7 @@ export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: Cli
}
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 <维度>");
if (!target) throw new Error("请提供档案维度 ID、编码或名称: hose-use 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 };
+448
View File
@@ -0,0 +1,448 @@
import { describe, it, expect, spyOn } from "bun:test";
import { handleFeeTypeCommand } from "./feetype.js";
import * as feetypeTools from "../../domains/feetype/tools.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
import { FeeTypeNode } from "../../domains/feetype/types.js";
describe("CLI - feetype 费用类型管理命令", () => {
const dummyRuntimeNoCorp: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
const mockCorp: CorpConfig = {
id: "corp_test",
name: "测试科技企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp_test",
staffId: "mock-staff",
},
};
const dummyRuntimeWithCorp: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
const mockTree = [
{
feeType: {
id: "ft_travel",
name: "差旅费用",
code: "COST19",
active: true,
parentId: "",
order: 1000,
color: "#90caf9",
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
description: "员工差旅相关费用",
},
children: [
{
feeType: {
id: "ft_flight",
name: "飞机票",
code: "COST54",
active: true,
parentId: "ft_travel",
order: 1001,
color: "#90caf9",
icon: "",
description: "",
},
children: [],
},
],
},
{
feeType: {
id: "ft_disabled",
name: "已停用费用",
code: "COST99",
active: false,
parentId: "",
order: 2000,
color: "#ccc",
icon: "",
description: "",
},
children: [],
},
] as unknown as FeeTypeNode[];
it("未选中企业时抛出友好错误", async () => {
expect(
handleFeeTypeCommand(
{
area: "feetype",
action: "list",
args: [],
options: {},
raw: ["feetype", "list"],
},
dummyRuntimeNoCorp
)
).rejects.toThrow("未指定或未找到有效企业");
});
it("feetype list 默认以树形层级展示活跃费用类型", async () => {
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
total: 3,
items: mockTree,
rawTree: mockTree,
});
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "list",
args: [],
options: {},
raw: ["feetype", "list"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型列表");
expect(res.stdout).toContain("差旅费用");
expect(res.stdout).toContain("飞机票");
expect(res.stdout).toContain("COST19");
expect(res.stdout).toContain("🟢 启用");
spy.mockRestore();
});
it("feetype list --json 支持结构化输出", async () => {
const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({
total: 2,
items: mockTree,
rawTree: mockTree,
});
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "list",
args: [],
options: { json: true },
raw: ["feetype", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.corpId).toBe("corp_test");
expect(parsed.total).toBe(2);
expect(parsed.items.length).toBe(2);
spy.mockRestore();
});
it("feetype get 查询单个费用类型详情及字段规格", async () => {
const mockDetail = {
feeType: {
id: "ft_travel",
name: "差旅费用",
code: "COST19",
active: true,
parentId: "",
path: "差旅费用",
parentName: "顶级 (根节点)",
childrenCount: 1,
color: "#90caf9",
icon: "https://images.ekuaibao.com/feetype/sf_100.png",
description: "差旅综合报销",
},
specifications: {
expenseComponents: [
{ field: "amount", cnLabel: "报销金额", type: "money", optional: false },
],
requisitionComponents: [
{ field: "amount", cnLabel: "预计金额", type: "money", optional: true },
],
},
};
const spy = spyOn(feetypeTools, "getFeeTypeDetail").mockResolvedValue(mockDetail as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "get",
args: ["差旅费用"],
options: { specs: true },
raw: ["feetype", "get", "差旅费用", "--specs"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("差旅费用");
expect(res.stdout).toContain("COST19");
expect(res.stdout).toContain("报销金额 (amount) - money [必填]");
expect(res.stdout).toContain("预计金额 (amount) - money [选填]");
spy.mockRestore();
});
it("feetype create 创建费用类型并展示卡片", async () => {
const mockCreated = {
id: "ft_hotel",
name: "酒店住宿",
code: "COST66",
active: true,
parentId: "ft_travel",
path: "差旅费用 / 酒店住宿",
parentName: "差旅费用",
childrenCount: 0,
color: "#90caf9",
icon: "",
description: "出差酒店",
};
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue(mockCreated as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "create",
args: [],
options: {
name: "酒店住宿",
parent: "差旅费用",
yes: true,
},
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型创建成功");
expect(res.stdout).toContain("酒店住宿");
expect(res.stdout).toContain("COST66");
expect(res.stdout).toContain("差旅费用 / 酒店住宿");
spy.mockRestore();
});
it("feetype update 修改费用类型属性", async () => {
const mockUpdated = {
id: "ft_hotel",
name: "酒店住宿(改)",
code: "COST66",
active: true,
parentId: "ft_travel",
path: "差旅费用 / 酒店住宿(改)",
parentName: "差旅费用",
childrenCount: 0,
color: "#90caf9",
icon: "",
description: "新说明",
};
const spy = spyOn(feetypeTools, "updateFeeTypeInfo").mockResolvedValue(mockUpdated as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "update",
args: ["酒店住宿"],
options: { desc: "新说明", yes: true },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型修改成功");
expect(res.stdout).toContain("新说明");
spy.mockRestore();
});
it("feetype disable 停用费用类型", async () => {
const spy = spyOn(feetypeTools, "disableFeeTypeItem").mockResolvedValue({
success: true,
item: {
id: "ft_hotel",
name: "酒店住宿",
code: "COST66",
active: false,
} as any,
});
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "disable",
args: ["酒店住宿"],
options: { yes: true },
raw: ["feetype", "disable", "酒店住宿", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("已成功停用");
expect(res.stdout).toContain("酒店住宿");
spy.mockRestore();
});
it("feetype enable 重新启用费用类型", async () => {
const spy = spyOn(feetypeTools, "enableFeeTypeItem").mockResolvedValue({
success: true,
item: {
id: "ft_hotel",
name: "酒店住宿",
code: "COST66",
active: true,
} as any,
});
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "enable",
args: ["酒店住宿"],
options: { yes: true },
raw: ["feetype", "enable", "酒店住宿", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("已成功启用");
expect(res.stdout).toContain("酒店住宿");
spy.mockRestore();
});
it("feetype move 移动费用类型父级节点", async () => {
const spy = spyOn(feetypeTools, "moveFeeTypeItem").mockResolvedValue({
success: true,
item: {
id: "ft_hotel",
name: "酒店住宿",
code: "COST66",
active: true,
path: "办公费 / 酒店住宿",
} as any,
parentName: "办公费",
});
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "move",
args: ["酒店住宿"],
options: { parent: "办公费", yes: true },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费", "--yes"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型移动成功");
expect(res.stdout).toContain("新所属父级 : 办公费");
spy.mockRestore();
});
it("feetype create --dry-run 不创建费用类型", async () => {
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue({} as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "create",
args: [],
options: { name: "酒店住宿", parent: "差旅费用", "dry-run": true },
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--dry-run"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("DRY-RUN");
expect(res.stdout).toContain("新建费用类型");
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it("feetype fields 打印报账与申请字段表格", async () => {
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
feeType: {
id: "ft_travel",
name: "差旅费用",
code: "COST19",
} as any,
expenseFields: [
{
field: "amount",
label: "金额",
type: "money",
required: true,
editable: true,
hidden: false,
},
],
requisitionFields: [],
});
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "fields",
args: ["差旅费用"],
options: {},
raw: ["feetype", "fields", "差旅费用"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("费用类型字段配置");
expect(res.stdout).toContain("报账字段列表");
expect(res.stdout).toContain("amount");
expect(res.stdout).toContain("🔴 必填");
spy.mockRestore();
});
it("未知 feetype 子命令时抛出支持说明", async () => {
expect(
handleFeeTypeCommand(
{
area: "feetype",
action: "invalidCmd",
args: [],
options: {},
raw: ["feetype", "invalidCmd"],
},
dummyRuntimeWithCorp
)
).rejects.toThrow("未知 feetype 子命令");
});
});
+601
View File
@@ -0,0 +1,601 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { booleanOption, stringOption } from "../parser.js";
import { createSessionClient } from "../../core/http/session-client.js";
import {
createFeeType,
disableFeeTypeItem,
enableFeeTypeItem,
findFeeType,
FlatFeeTypeItem,
flattenFeeTypeTree,
getFeeTypeDetail,
getFeeTypeFieldsList,
listFeeTypes,
moveFeeTypeItem,
updateFeeTypeInfo,
} from "../../domains/feetype/tools.js";
import { FeeTypeNode } from "../../domains/feetype/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
/**
* 递归渲染树形层级格式
*/
function renderTreeRows(
nodes: FeeTypeNode[],
depth = 0,
prefix = "",
isLast = true,
acc: (string | number)[][] = []
): (string | number)[][] {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const item = node.feeType;
if (!item) continue;
const currentIsLast = i === nodes.length - 1;
const branch = depth === 0 ? "" : isLast ? "└─ " : "├─ ";
const indent = depth === 0 ? "" : prefix + branch;
const nextPrefix = depth === 0 ? "" : prefix + (isLast ? " " : "│ ");
const children = Array.isArray(node.children) ? node.children : [];
acc.push([
acc.length + 1,
`${indent}${item.name}`,
item.code || "-",
item.id,
item.active ? "🟢 启用" : "🔴 停用",
children.length ? `${children.length} 项` : "-",
]);
if (children.length > 0) {
renderTreeRows(children, depth + 1, nextPrefix, currentIsLast, acc);
}
}
return acc;
}
export async function handleFeeTypeCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const corpId = corp.corpId || corp.id;
const action = (parsed.action?.toLowerCase() || "list").trim();
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
const getClient = async () => {
client ??= await createSessionClient(corp);
return client;
};
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
if (["list", "tree", "all", "search"].includes(action)) {
const includeAll =
action === "all" ||
booleanOption(parsed.options, ["all", "a", "include-disabled"]) ||
false;
const isFlat =
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
const keyword =
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
const result = await listFeeTypes(await getClient(), corpId, {
all: includeAll,
flat: isFlat,
keyword,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
includeDisabled: includeAll,
keyword: keyword || null,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
let rows: (string | number)[][] = [];
if (!isFlat && !keyword) {
rows = renderTreeRows(result.rawTree);
} else {
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
rows = flatItems.map((item, idx) => [
idx + 1,
item.path || item.name,
item.code || "-",
item.id,
item.active ? "🟢 启用" : "🔴 停用",
item.childrenCount ? `${item.childrenCount} 项` : "-",
]);
}
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
includeAll ? ",含停用" : ""
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
const tableStr = rows.length
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
: "暂无匹配的费用类型";
return {
stdout: `${title}\n${tableStr}\n`,
stderr: "",
exitCode: 0,
};
}
// ── 2. 单条详情 (get / show / detail) ─────────────────────────────────────────
if (["get", "show", "detail", "info"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "name"]);
if (!target) {
throw new Error("请提供费用类型 ID、编码或名称: hose-use feetype get <ID|编码|名称>");
}
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
const detail = await getFeeTypeDetail(await getClient(), corpId, target, { includeSpecs });
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
...detail,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const ft = detail.feeType;
const lines = [
`====== 费用类型详情 (${ft.name}) ======`,
` 名称 : ${ft.name}${ft.enName ? ` (${ft.enName})` : ""}`,
` 编码 : ${ft.code}`,
` ID : ${ft.id}`,
` 当前状态 : ${ft.active ? "🟢 启用中" : "🔴 已停用"}`,
` 层级全路径 : ${ft.path || ft.name}`,
` 父级节点 : ${ft.parentName || "顶级 (根节点)"} (${ft.parentId || "-"})`,
` 子类型数量 : ${ft.childrenCount || 0} 项`,
` 标识颜色 : ${ft.color || "-"}`,
` 图标链接 : ${ft.icon || "-"}`,
` 说明描述 : ${ft.description || "-"}`,
];
if (includeSpecs && detail.specifications) {
const exp = detail.specifications.expenseComponents || [];
const req = detail.specifications.requisitionComponents || [];
lines.push("");
lines.push(` ── 报账字段列表 (${exp.length} 项) ──`);
for (const c of exp) {
const reqStr = c.optional === false ? "[必填]" : "[选填]";
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
}
lines.push("");
lines.push(` ── 申请字段列表 (${req.length} 项) ──`);
for (const c of req) {
const reqStr = c.optional === false ? "[必填]" : "[选填]";
lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`);
}
}
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
// ── 3. 新建费用类型 (create / add) ──────────────────────────────────────────
if (["create", "add", "new"].includes(action)) {
const name =
stringOption(parsed.options, ["name", "title"]) || parsed.args[0];
if (!name?.trim()) {
throw new Error(
"请提供费用类型名称: hose-use feetype create --name=\"费用名称\" [--code=...] [--parent=...]"
);
}
const code = stringOption(parsed.options, ["code"]);
const parent = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
const enName = stringOption(parsed.options, ["en-name", "enName"]);
const description = stringOption(parsed.options, ["desc", "description"]);
const color = stringOption(parsed.options, ["color"]);
const icon = stringOption(parsed.options, ["icon"]);
requireMutationConfirmation(
parsed,
runtime,
"新建费用类型",
`hose-use feetype create --name="${name.trim()}" --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新建费用类型", name.trim(), {
corpId,
name: name.trim(),
code: code || null,
parentId: parent || null,
enName: enName || null,
description: description || null,
color: color || null,
icon: icon || null,
});
}
const created = await createFeeType(await getClient(), corpId, {
name: name.trim(),
code,
parentId: parent,
enName,
description,
color,
icon,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
action: "create",
corpId,
feeType: created,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`🎉 费用类型创建成功!`,
` 名称 : ${created.name}`,
` 编码 : ${created.code}`,
` ID : ${created.id}`,
` 层级路径 : ${created.path}`,
` 所属父级 : ${created.parentName || "顶级 (根节点)"}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 4. 更新费用类型 (update / edit / modify) ─────────────────────────────────
if (["update", "edit", "modify", "set"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
if (!target?.trim()) {
throw new Error(
"请指定待修改的费用类型: hose-use feetype update <ID|编码|名称> [--name=...] [--code=...] [--desc=...]"
);
}
const name = stringOption(parsed.options, ["name"]);
const code = stringOption(parsed.options, ["code"]);
const enName = stringOption(parsed.options, ["en-name", "enName"]);
const description = stringOption(parsed.options, ["desc", "description"]);
const color = stringOption(parsed.options, ["color"]);
const icon = stringOption(parsed.options, ["icon"]);
if (
name === undefined &&
code === undefined &&
enName === undefined &&
description === undefined &&
color === undefined &&
icon === undefined
) {
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
}
requireMutationConfirmation(
parsed,
runtime,
"修改费用类型",
`hose-use feetype update ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "修改费用类型", target, {
corpId,
name: name ?? null,
code: code ?? null,
enName: enName ?? null,
description: description ?? null,
color: color ?? null,
icon: icon ?? null,
});
}
const updated = await updateFeeTypeInfo(await getClient(), corpId, target, {
name,
code,
enName,
description,
color,
icon,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
action: "update",
corpId,
feeType: updated,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`✅ 费用类型修改成功!`,
` 名称 : ${updated.name}`,
` 编码 : ${updated.code}`,
` ID : ${updated.id}`,
` 说明描述 : ${updated.description || "-"}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 5. 停用费用类型 (disable / block / stop) ─────────────────────────────────
if (["disable", "block", "stop"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
if (!target?.trim()) {
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
}
requireMutationConfirmation(
parsed,
runtime,
"停用费用类型",
`hose-use feetype disable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "停用费用类型", target, { corpId, active: false });
}
const res = await disableFeeTypeItem(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: res.success,
action: "disable",
corpId,
feeType: res.item,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `🔴 费用类型 [${res.item.name}] (${res.item.code}) 已成功停用。\n`,
stderr: "",
exitCode: 0,
};
}
// ── 6. 启用费用类型 (enable / restore / start) ───────────────────────────────
if (["enable", "restore", "start"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
if (!target?.trim()) {
throw new Error("请指定待启用的费用类型: hose-use feetype enable <ID|编码|名称>");
}
const recursive =
booleanOption(parsed.options, ["recursive", "r"]) !== false;
requireMutationConfirmation(
parsed,
runtime,
"启用费用类型",
`hose-use feetype enable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "启用费用类型", target, {
corpId,
active: true,
recursive,
});
}
const res = await enableFeeTypeItem(await getClient(), corpId, target, { recursive });
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: res.success,
action: "enable",
corpId,
feeType: res.item,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `🟢 费用类型 [${res.item.name}] (${res.item.code}) 已成功启用。\n`,
stderr: "",
exitCode: 0,
};
}
// ── 7. 移动费用类型层级 (move) ───────────────────────────────────────────────
if (["move"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
const parentTarget =
stringOption(parsed.options, ["parent", "to"]) || parsed.args[1];
if (!target?.trim()) {
throw new Error("请指定待移动的费用类型: hose-use feetype move <ID|编码|名称> --parent=<新父级|root>");
}
if (parentTarget === undefined) {
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
}
requireMutationConfirmation(
parsed,
runtime,
"移动费用类型",
`hose-use feetype move ${target} --parent=${parentTarget} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "移动费用类型", target, {
corpId,
parent: parentTarget,
});
}
const res = await moveFeeTypeItem(await getClient(), corpId, target, parentTarget);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: res.success,
action: "move",
corpId,
feeType: res.item,
parentName: res.parentName,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`🚚 费用类型移动成功!`,
` 名称 : ${res.item.name} (${res.item.code})`,
` 新所属父级 : ${res.parentName}`,
` 更新后路径 : ${res.item.path}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 8. 查看单据模板定义 (spec / specification) ─────────────────────────────
if (["spec", "specification"].includes(action)) {
const { handleBillCommand } = await import("./bill/index.js");
return handleBillCommand({ ...parsed, area: "bill", action: "spec" }, runtime);
}
// ── 9. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
if (["fields", "specs", "schema"].includes(action)) {
const target =
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
if (!target?.trim()) {
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
}
const res = await getFeeTypeFieldsList(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
feeType: res.feeType,
expenseFields: res.expenseFields,
requisitionFields: res.requisitionFields,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const expRows = res.expenseFields.map((f, i) => [
i + 1,
f.label,
f.field,
f.type,
f.required ? "🔴 必填" : "⚪ 选填",
f.editable ? "是" : "只读",
f.hidden ? "是" : "否",
]);
const reqRows = res.requisitionFields.map((f, i) => [
i + 1,
f.label,
f.field,
f.type,
f.required ? "🔴 必填" : "⚪ 选填",
f.editable ? "是" : "只读",
f.hidden ? "是" : "否",
]);
const outLines = [
`====== 费用类型字段配置 (${res.feeType.name} | ${res.feeType.code}) ======`,
"",
`── 报账字段列表 (${res.expenseFields.length} 个) ──`,
expRows.length
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], expRows)
: "暂无自定义报账字段",
"",
`── 申请字段列表 (${res.requisitionFields.length} 个) ──`,
reqRows.length
? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], reqRows)
: "暂无自定义申请字段",
];
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
throw new Error(
`未知 feetype 子命令: "${action}"。\n支持的子命令:\n` +
` • hose-use feetype list [--all] [--flat] [--keyword=...] (查看费用类型树)\n` +
` • hose-use feetype get <ID|编码|名称> [--specs] (获取详情与字段配置)\n` +
` • hose-use feetype create --name=... [--code=...] [--parent=...] (新建费用类型)\n` +
` • hose-use feetype update <ID|编码|名称> [--name=...] [--desc=...] (修改属性)\n` +
` • hose-use feetype disable <ID|编码|名称> (停用)\n` +
` • hose-use feetype enable <ID|编码|名称> (启用)\n` +
` • hose-use feetype move <ID|编码|名称> --parent=<新父级|root> (移动父级)\n` +
` • hose-use feetype fields <ID|编码|名称> (查看报账与申请字段清单)`
);
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, expect, test, spyOn } from "bun:test";
import { handleKeysCommand } from "./keys.js";
import { handleOpenApiCommand } from "./openapi.js";
import type { CliRuntime, CliParsedArgs } from "../types.js";
import * as storeTools from "../../domains/store/tools.js";
describe("CLI - keys 顶级命令与凭证提取", () => {
const dummyCorp: any = {
id: "test-corp-id",
name: "测试企业A",
corpId: "test-corp-id",
credentials: { corpId: "test-corp-id", accessToken: "token123" },
};
const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({
corpContext: {} as any,
selectedCorp: corp,
jsonMode,
});
test("未选中企业时返回提示并报错", async () => {
const runtime = createRuntime(null);
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
test("keys 默认脱敏显示 appSecurity 接入密码", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "开发测试密钥",
appKey: "545f8b6a-75a7-4f99-86e1-bca747c985e7",
appSecurity: "9bc91727-e96e-4924-abcb-d8ed77557f58",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("开发测试密钥");
expect(res.stdout).toContain("545f8b6a-75a7-4f99-86e1-bca747c985e7");
// 默认脱敏
expect(res.stdout).toContain("9bc91727...7f58");
expect(res.stdout).not.toContain("9bc91727-e96e-4924-abcb-d8ed77557f58");
spy.mockRestore();
});
test("keys --reveal 显式输出完整接入密码明文", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "生产密钥",
appKey: "key-full-123",
appSecurity: "secret-super-long-plain-text",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "keys",
options: { reveal: true },
args: [],
raw: ["keys", "--reveal"],
};
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("secret-super-long-plain-text");
spy.mockRestore();
});
test("keys --json 模式正常序列化", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "JSON密钥",
appKey: "json-app-key",
appSecurity: "secret-for-json-test",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp, true);
const parsed: CliParsedArgs = { area: "keys", options: { json: true }, args: [], raw: ["keys", "--json"] };
const res = await handleKeysCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(Array.isArray(data)).toBe(true);
expect(data[0].appKey).toBe("json-app-key");
// 默认 json 脱敏
expect(data[0].appSecurity).toContain("...");
spy.mockRestore();
});
test("openapi keys 子命令平滑转发至同一执行器", async () => {
const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() =>
Promise.resolve([
{
id: "k-1",
name: "OpenAPI子命令测试",
appKey: "sub-app-key",
appSecurity: "sub-app-security-123456",
active: true,
createTime: 1751357077503,
updateTime: 1769063905460,
},
])
);
const runtime = createRuntime(dummyCorp);
const parsed: CliParsedArgs = {
area: "openapi",
action: "keys",
options: {},
args: [],
raw: ["openapi", "keys"],
};
const res = await handleOpenApiCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("OpenAPI子命令测试");
expect(res.stdout).toContain("sub-app-key");
spy.mockRestore();
});
});
+174
View File
@@ -0,0 +1,174 @@
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
import { selectOpenApiKey } from "../../core/auth/login.js";
import { saveCorpConfig } from "../../core/config/loader.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function formatDate(ts: number): string {
if (!ts) return "-";
const d = new Date(ts);
if (isNaN(d.getTime())) return "-";
const Y = d.getFullYear();
const M = String(d.getMonth() + 1).padStart(2, "0");
const D = String(d.getDate()).padStart(2, "0");
const h = String(d.getHours()).padStart(2, "0");
const m = String(d.getMinutes()).padStart(2, "0");
return `${Y}/${M}/${D} ${h}:${m}`;
}
function maskSecret(secret: string): string {
if (!secret) return "-";
if (secret.length <= 12) return "******";
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
}
export async function handleKeysCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const reveal =
booleanOption(parsed.options, ["reveal", "r", "plain"]) ||
parsed.action === "reveal" ||
parsed.args[0] === "reveal";
const save =
booleanOption(parsed.options, ["save", "persist", "elevate"]) ||
parsed.action === "save" ||
parsed.args[0] === "save";
const appKeyOpt = stringOption(parsed.options, ["app-key", "appKey"]);
const keyIdOpt = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"]);
if (save) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${currentCorp.name} (${currentCorp.id})`, {
corpId: currentCorp.id,
appKey: appKeyOpt || "auto-select",
keyId: keyIdOpt || null,
});
}
requireMutationConfirmation(
parsed,
runtime,
"提取并持久化企业 OpenAPI 密钥",
`hose-use keys --corp=${currentCorp.id} --save --yes`
);
}
try {
const keys = await fetchOpenApiKeys(currentCorp);
if (save) {
const selected = selectOpenApiKey(
keys.map((k) => ({
id: k.id,
name: k.name || undefined,
appKey: k.appKey,
appSecurity: k.appSecurity,
active: k.active,
createTime: k.createTime,
updateTime: k.updateTime,
})),
currentCorp.id,
{ appKey: appKeyOpt, keyId: keyIdOpt, force }
);
currentCorp.credentials.appKey = selected.appKey;
currentCorp.credentials.appSecurity = selected.appSecurity;
const savedPath = saveCorpConfig(currentCorp);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
saved: true,
corpId: currentCorp.id,
corpName: currentCorp.name,
appKey: selected.appKey,
appSecurity: reveal ? selected.appSecurity : maskSecret(selected.appSecurity),
keyName: selected.name || "-",
path: savedPath,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
return {
stdout: `[SUCCESS] 已为企业 [${currentCorp.name}] 持久化保存 OpenAPI 密钥 (appKey: ${selected.appKey})!\n保存路径: ${savedPath}\n`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
if (runtime.jsonMode) {
const outputData = reveal
? keys
: keys.map((k) => ({
...k,
appSecurity: maskSecret(k.appSecurity),
}));
return {
stdout: printJson(outputData, runtime.outputOptions),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
if (keys.length === 0) {
return {
stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`,
stderr: "",
exitCode: 0,
};
}
const rows = keys.map((k, i) => [
i + 1,
k.name || "-",
k.appKey,
reveal ? k.appSecurity : maskSecret(k.appSecurity),
k.active ? "🟢 启用" : "⚪ 停用",
formatDate(k.createTime),
]);
const table = printTable(
["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"],
rows
);
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
const hint = reveal
? ""
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
return {
stdout: `${title}\n\n${table}\n${hint}`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
} catch (err: any) {
return {
stdout: "",
stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect, spyOn } from "bun:test";
import { handleMenuCommand } from "./menu.js";
import * as menuTools from "../../domains/menu/tools.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("cli/commands/menu > handleMenuCommand", () => {
const dummyRuntimeNoCorp: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
const mockCorp: CorpConfig = {
id: "corp123",
name: "转转二手交易网",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp123",
staffId: "mock-staff",
},
};
const dummyRuntimeWithCorp: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
it("fails with exitCode 1 when no corp is selected", async () => {
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: {},
raw: ["menu", "list"],
},
dummyRuntimeNoCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("lists desktop menus in table format", async () => {
const mockMenus = [
{
id: "newHomePage",
label: "首页",
appId: "100-home",
href: "/home",
children: [],
},
{
id: "dataLink",
label: "应用管理",
appId: "160-datalink-platform",
href: "/datalink",
children: [
{ id: "sub1", label: "用车补贴" },
{ id: "sub2", label: "用车制度" },
],
},
];
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: {},
raw: ["menu", "list"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("桌面端主框架导航与模块列表");
expect(res.stdout).toContain("首页");
expect(res.stdout).toContain("应用管理");
expect(res.stdout).toContain("160-datalink-platform");
spy.mockRestore();
});
it("supports --json output for menu list", async () => {
const mockMenus = [
{
id: "newHomePage",
label: "首页",
appId: "100-home",
href: "/home",
},
];
const spy = spyOn(menuTools, "fetchDesktopMenus").mockResolvedValue(mockMenus as any);
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
const res = await handleMenuCommand(
{
area: "menu",
action: "list",
args: [],
options: { json: true },
raw: ["menu", "list", "--json"],
},
jsonRuntime
);
expect(res.exitCode).toBe(0);
const parsed = JSON.parse(res.stdout);
expect(parsed.count).toBe(1);
expect(parsed.menus[0].id).toBe("newHomePage");
spy.mockRestore();
});
it("delegates menu apps to handleAppCommand", async () => {
const mockApps = [
{
id: "SCGY:corp123",
name: "用车补贴",
code: "dataLinkItem",
href: "/third-party-item/SCGY:corp123",
},
];
const spy = spyOn(menuTools, "fetchWorkbenchAppsList").mockResolvedValue(mockApps as any);
const res = await handleMenuCommand(
{
area: "menu",
action: "apps",
args: [],
options: {},
raw: ["menu", "apps"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作台应用管理列表");
expect(res.stdout).toContain("用车补贴");
spy.mockRestore();
});
it("returns error for unknown menu subcommand", async () => {
const res = await handleMenuCommand(
{
area: "menu",
action: "badsub",
args: [],
options: {},
raw: ["menu", "badsub"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未知 menu 子命令");
});
});
+71
View File
@@ -0,0 +1,71 @@
import { fetchDesktopMenus } from "../../domains/menu/tools.js";
import { handleAppCommand } from "./app.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleMenuCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!runtime.selectedCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action || "list";
switch (action) {
case "apps":
case "workbench":
return handleAppCommand(parsed, runtime);
case "list":
case "ls":
case "tree": {
const items = await fetchDesktopMenus(runtime.selectedCorp);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: runtime.selectedCorp.credentials.corpId,
corpName: runtime.selectedCorp.name,
count: items.length,
menus: items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "模块 ID", "导航名称", "模块标识 (appId)", "子菜单数", "默认路由"];
const rows = items.map((m, i) => [
i + 1,
m.id,
m.label,
m.appId || "-",
m.children?.length || 0,
m.href || "-",
]);
const title = `====== [${runtime.selectedCorp.name}] 桌面端主框架导航与模块列表 (共 ${items.length} 个一级导航) ======\n`;
return {
stdout: title + printTable(headers, rows) + "\n",
stderr: "",
exitCode: 0,
};
}
default:
return {
stdout: "",
stderr: `未知 menu 子命令: ${action}。支持: list, tree, apps\n用法: hose-use menu list\n`,
exitCode: 1,
};
}
}
+17 -4
View File
@@ -1,9 +1,10 @@
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 { createSessionClient } from "../../core/http/session-client.js";
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
import type { MessageItem } from "../../domains/message/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
function formatTime(value: number | undefined): string {
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
@@ -24,12 +25,12 @@ function renderItems(items: MessageItem[]): string {
export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose corps list 或指定 --corp=<id>");
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use 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 client = await createSessionClient(corp);
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 };
@@ -37,13 +38,23 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
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 };
if (!messageId) return { stdout: "", stderr: "用法: hose-use message read <messageId>\n", exitCode: 1 };
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true });
}
requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`);
const client = await createSessionClient(corp);
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") {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true });
}
requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes");
const client = await createSessionClient(corp);
const ids: string[] = [];
let start = 0;
let total = 0;
@@ -63,6 +74,8 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
}
const client = await createSessionClient(corp);
const read = booleanOption(parsed.options, ["read"]);
const unread = booleanOption(parsed.options, ["unread"]);
const all = booleanOption(parsed.options, ["all"]);
+8 -2
View File
@@ -1,19 +1,25 @@
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core/embedded-openapi.js";
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../packaging/embedded-openapi.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { handleKeysCommand } from "./keys.js";
export async function handleOpenApiCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action?.toLowerCase();
if (action === "keys" || action === "key") {
return handleKeysCommand(parsed, runtime);
}
const isRaw =
booleanOption(parsed.options, ["raw"]) ||
parsed.action === "raw" ||
parsed.args[0] === "raw";
const type: OpenApiType = isRaw ? "raw" : "wrapped";
const action = parsed.action?.toLowerCase();
switch (action) {
case "paths":
+3 -3
View File
@@ -1,14 +1,14 @@
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { createSessionClient } from "../../core/http/session-client.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 登录。");
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use 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 client = await createSessionClient(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 ? "启用" : "停用"]);
+258
View File
@@ -0,0 +1,258 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handlePlatformCommand } from "./platform/index.js";
import * as api from "../../domains/datalink/api.js";
import * as services from "../../domains/datalink/services.js";
import * as helpers from "../helpers.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("CLI - platform 命令与 record 动作", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
const mockCorp: CorpConfig = {
id: "corp-1",
name: "测试企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: "mock-token",
corpId: "corp-1",
staffId: "staff-1",
},
};
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
};
const mockPlatform = {
id: "platform-1",
name: "项目台账",
code: "PJ",
active: true,
adminIds: ["staff-1"],
staffIds: [],
roleIds: [],
departmentIds: [],
departmentsIncludeChildren: false,
};
const mockEntity = {
id: "entity-1",
name: "项目",
code: "PROJECT",
type: "DIMENSION",
active: true,
fields: [
{ name: "code", label: "编码", type: "text" },
{ name: "name", label: "名称", type: "text" },
{ name: "customField", label: "自定义字段", type: "text" },
],
actions: [],
importMethod: [],
};
it("未选中企业时报错并返回 exitCode 1", async () => {
const res = await handlePlatformCommand(
{ area: "platform", action: "list", args: [], options: {}, raw: [] },
{ ...dummyRuntime, selectedCorp: null }
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("records 正确解析嵌套 dataLink 的停启用状态和更新时间", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
total: 2,
data: [
{
id: "r-1",
dataLink: { id: "r-1", name: "项目1", code: "P1", active: false, updateTime: "2026-09-09" },
},
{
id: "r-2",
dataLink: { id: "r-2", name: "项目2", code: "P2", active: true, updateTime: "2026-09-09" },
},
],
actions: [],
components: [],
path: null,
template: null,
}));
const res = await handlePlatformCommand(
{ area: "platform", action: "records", args: ["platform-1", "entity-1"], options: {}, raw: [] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("停用");
expect(res.stdout).toContain("启用");
});
it("record get 获取记录详情", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(spyOn(api, "getRecordDetail").mockResolvedValue({
dataLink: {
id: "r-1",
name: "测试项目",
code: "P-100",
active: true,
createTime: 12345678,
updateTime: 12345679,
form: { customField: "测试值" },
},
}));
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["get", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("测试项目");
expect(res.stdout).toContain("P-100");
expect(res.stdout).toContain("测试值");
});
it("record toggle 切换停启用状态", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const toggleSpy = spyOn(api, "toggleRecordState").mockResolvedValue({ recordId: "r-1", active: true });
spies.push(toggleSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "toggle", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("状态已成功切换为");
expect(toggleSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1", undefined);
});
it("record edit 编辑字段", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
spies.push(editSpy);
const res = await handlePlatformCommand(
{
area: "platform",
action: "record",
args: ["edit", "platform-1", "entity-1", "r-1"],
options: { data: '{"name":"更新后的名称"}', yes: true },
raw: ["platform", "record", "edit", "platform-1", "entity-1", "r-1", "--yes"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("字段更新成功");
expect(editSpy).toHaveBeenCalledWith(
expect.anything(),
"corp-1",
expect.objectContaining({
dataLinkEntityId: "entity-1",
dataLinkId: "r-1",
form: { name: "更新后的名称" },
})
);
});
it("record recompute 触发台账重算", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
const recomputeSpy = spyOn(api, "recomputeRecordLedger").mockResolvedValue({ id: "ok" });
spies.push(recomputeSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "recompute", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("台账重算任务已成功触发");
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
});
it("record get 支持仅传 <recordId> 免传应用与业务对象", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(
spyOn(api, "getRecordDetail").mockResolvedValue({
dataLink: {
id: "ID01DirectRecord",
name: "直查记录",
code: "DR-01",
entityId: "entity-1",
active: true,
},
})
);
spies.push(spyOn(api, "listPlatforms").mockResolvedValue([mockPlatform] as any));
spies.push(spyOn(api, "listPlatformEntities").mockResolvedValue([mockEntity] as any));
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["get", "ID01DirectRecord"], options: {}, raw: [] },
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("直查记录");
expect(res.stdout).toContain("DR-01");
});
it("record batch-edit --dry-run 生成安全合并预览且不发送真实写请求", async () => {
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
spies.push(
spyOn(api, "getRecordDetail").mockResolvedValue({
dataLink: {
id: "r-1",
active: true,
name: "旧名称",
code: "P-1",
},
})
);
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
spies.push(editSpy);
const res = await handlePlatformCommand(
{
area: "platform",
action: "record",
args: ["batch-edit", "platform-1", "entity-1"],
options: { ids: "r-1", data: '{"名称":"新名称"}', "dry-run": true },
raw: ["platform", "record", "batch-edit", "platform-1", "entity-1", "--ids=r-1", "--dry-run"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("Dry-Run 预览");
expect(editSpy).not.toHaveBeenCalled();
});
});
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff. Show more