Compare commits

..
342 Commits
Author SHA1 Message Date
yunyingk 4e53c88a51 Merge pull request #134 from yunyingk/release/v0.8.17
CI / validate (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.17 — 合思协助平台自动化运营、免密进入与工单转交闭环
2026-10-21 12:45:45 +08:00
gitea 33ea49c9fe release: v0.8.17 — 合思协助平台自动化运营、免密进入与工单转交闭环 2026-10-21 12:44:37 +08:00
yunyingk b671b63e99 Merge pull request #133 from yunyingk/feat/assist-transfer-and-qr-watch
CI / validate (push) Has been cancelled
feat(assist): 支持协助工单权限转交 (transfer) 与候选人检索
2026-10-21 11:59:00 +08:00
gitea 7a396f8a95 feat(assist): 支持协助工单权限转交 (transfer) 并实测交接给陈龙
- 实现 domains/assist-platform 转交 API: searchTransferCandidatesApi (POST /api/userRole/search) 与 transferAssistTicketApi (POST /api/assistPlatform/transfer)
- 提供智能接收人解析 (resolveTransferRecipient): 支持姓名模糊匹配、工号或账号精确匹配
- 实现 CLI 命令 hose-use assist-platform transfer: 支持 --candidates 人员字典查询与 --dry-run 安全预览
- 实测将沈玥妍测试企业有效工单 ID01Xenwiu9w0D 成功转交至陈龙 (chenlong3016, 工号 3016)
- 补充 domains 与 cli 全套单元测试并在 SKILL.md 与 assist-platform.md 沉淀转交指南
2026-10-21 11:57:52 +08:00
yunyingk 82fa0fca0c Merge pull request #132 from yunyingk/feat/workflow-toolchain-defense
CI / validate (push) Has been cancelled
feat(workflow): add docs domain & powerCode diagnostics, webhook sample injector, and snapshot sanitizer
2026-10-21 11:48:26 +08:00
gitea 8d72e94d52 chore: merge origin/main into feat/workflow-toolchain-defense 2026-10-21 11:47:05 +08:00
gitea 3c2c82c3f7 chore(mcp): update bundled server.js artifact 2026-10-21 11:45:01 +08:00
gitea 6e40faccff feat(workflow): add docs domain and unlicensed powerCode diagnostics, webhook sample injector, and snapshot sanitizer 2026-10-21 11:42:50 +08:00
yunyingk b3371ee327 Merge pull request #131 from yunyingk/feat/assist-identity-and-role-risk-guard
CI / validate (push) Has been cancelled
feat(assist): 支持协助身份与角色权限穿透呈现及高管防误用警示
2026-10-21 11:40:04 +08:00
gitea 2ace4e2378 feat(assist): 支持协助身份与角色权限穿透呈现及高管防误用警示
- 实测澄清协助平台时长限制: 服务端 POST /api/assistPlatform/create 硬性单次上限为 24 小时 (1 天),超过直接报错 400,支持 --days/--hours 并在超限时清晰提示
- 协助直通会话生成及落盘时实时穿透解析组织架构: 提取人员姓名、工号、手机、所属部门、所配角色清单及核心系统权限
- 建立高管身份与特权角色风控评级体系 (analyzeStaffRoleRisk): 自动识别总监、主管理员、财务负责人、总经理等高危身份并输出安全风控警示框
- 将完整人员身份画像与风控元数据注入持久化企业配置 (enterprises/<corpId>.json)
- 在 SKILL.md 追加 Rule 13 及更新 assist-platform.md 说明文档
2026-10-21 11:39:00 +08:00
yunyingk 60d0b8ffc1 Merge pull request #130 from yunyingk/feat/assist-platform-approve-and-fix-enter
CI / validate (push) Has been cancelled
feat(assist-platform): add approve command and support direct link generation for enter
2026-10-21 11:26:47 +08:00
gitea 16507da470 chore: sync bundled dist/mcp/server.js 2026-10-21 11:25:59 +08:00
gitea f0fc7148ec feat(assist-platform): add approve command and support direct link generation for enter 2026-10-21 11:24:26 +08:00
yunyingk e98948529e Merge pull request #129 from yunyingk/feat/assist-platform-apply-and-trust-rules
CI / validate (push) Has been cancelled
feat(assist-platform): add ticket application command and enforce local config trust rules
2026-10-21 11:08:32 +08:00
gitea 1e45c441c6 feat(assist-platform): add ticket application command and enforce local config trust rules 2026-10-21 11:07:35 +08:00
yunyingk 2e6fe1a94a Merge pull request #128 from yunyingk/fix/raw-dollar-in-unity-paths
CI / validate (push) Has been cancelled
fix(assist-platform): preserve literal dollar in Jersey path routes
2026-10-21 10:47:55 +08:00
gitea e2e730c07d fix(assist-platform): preserve literal dollar in Jersey path routes
Jersey matching expects literal $ rather than %24 in paths like
corporation/$id/getCorporationDetail and assistPlatform/$id/search.
2026-10-21 10:47:00 +08:00
yunyingk 9b4b9b3756 Merge pull request #127 from yunyingk/feat/assist-platform-query-refinement
CI / validate (push) Has been cancelled
feat(assist-platform): adapt to live assist backend query and id dialect
2026-10-21 10:45:29 +08:00
gitea 35552944d1 feat(assist-platform): adapt to live assist backend query and id dialect
- Support filterBy in corporation search for server-side name/id resolution
- Normalize corporation ID with leading dollar prefix for detail and ticket endpoints
- Include required query object in ticket search payloads
- Improve ticket status mapping for live numeric states
- Rebuild plugin mcp bundle
2026-10-21 10:44:27 +08:00
yunyingk 37cf784ba1 Merge pull request #126 from yunyingk/feat/assist-platform-automation
CI / validate (push) Has been cancelled
feat(assist-platform): add assist platform automation and tenant onboarding
2026-10-21 10:36:09 +08:00
gitea 6816ea7a75 build: update bundled mcp server for assist-platform commands 2026-10-21 10:35:21 +08:00
gitea ed9fa979e0 feat(assist-platform): add assist platform automation and tenant onboarding
- Add SSO QR status poller and assist platform HTTP client
- Add assist-platform session store with 0600 secure permissions
- Implement domains/assist-platform (api, services, types) for corporation search, detail, tickets, staff query and passwordless token generation
- Implement cli/commands/assist-platform with aliases assist-center and ap
- Support seamless --save --switch --elevate pipeline to import tenant and extract persistent OpenAPI credentials
- Update embedded skill documentation, reference guide, and test suites
2026-10-21 10:33:27 +08:00
yunyingk d839fcbe2b Merge pull request #125 from yunyingk/release/v0.8.16
CI / validate (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.16 — 全局审查修复与脚本沙箱隔离
2026-10-20 23:25:40 +08:00
gitea 080341b7ca release: v0.8.16 — global review fixes and isolated script runtime 2026-10-20 23:24:32 +08:00
yunyingk 3d1286f62d Merge pull request #124 from yunyingk/fix/review-all-integration
CI / validate (push) Has been cancelled
fix: resolve 20 global review findings across approvals and workflows
2026-10-20 23:23:13 +08:00
gitea 9d895866e6 fix(packaging): use runtime filename for reproducible plugin bundles 2026-10-20 23:21:47 +08:00
gitea 3c1237ff31 docs: record global review fixes and validation 2026-10-20 23:06:58 +08:00
gitea 2e5e3c208c merge: integrate review-20-trigger-removal-guard 2026-10-20 23:04:05 +08:00
gitea 1e09b5b85e merge: integrate review-19-formula-diagnostics 2026-10-20 23:03:57 +08:00
gitea ec7584c194 merge: integrate review-18-watch-timeout 2026-10-20 23:03:48 +08:00
gitea ae76b33c38 merge: integrate review-17-event-pagination 2026-10-20 23:03:40 +08:00
gitea 4537c6eb53 merge: integrate review-16-node-grant-failure 2026-10-20 23:03:31 +08:00
gitea 1197b5b985 merge: integrate review-15-snapshot-config-diff 2026-10-20 23:03:23 +08:00
gitea e872beaab8 merge: integrate review-14-script-json-output 2026-10-20 23:03:14 +08:00
gitea fae36f8c96 merge: integrate review-13-set-literal-types 2026-10-20 23:03:05 +08:00
gitea c705cffaf4 merge: integrate review-12-set-quoted-separators 2026-10-20 23:02:57 +08:00
gitea 6f4608635b merge: integrate review-11-session-expiry 2026-10-20 23:02:48 +08:00
gitea 2be973ddf4 merge: integrate review-10-client-auth-refresh 2026-10-20 23:02:40 +08:00
gitea bf80273891 merge: integrate review-09-service-dry-run 2026-10-20 23:02:31 +08:00
gitea d1a75c011a merge: integrate review-08-update-dry-run 2026-10-20 23:02:23 +08:00
gitea 0f781fda53 merge: integrate review-07-patch-prototype-guard 2026-10-20 23:02:15 +08:00
gitea 29841a2374 merge: integrate review-06-node-index-resolution 2026-10-20 23:02:07 +08:00
gitea a1527246da merge: integrate review-05-node-grant-confirmation 2026-10-20 23:01:59 +08:00
gitea b2059ec350 merge: integrate review-04-approval-dry-run 2026-10-20 23:01:50 +08:00
gitea e7cac3aec3 merge: integrate review-03-finding-status-validation 2026-10-20 23:01:43 +08:00
gitea 51e4b39807 merge: integrate review-02-approval-corp-boundary 2026-10-20 23:01:34 +08:00
gitea 6269dd21ab merge: include shell fixture validation headroom 2026-10-20 23:01:26 +08:00
gitea 70d619e464 fix(workflow): propagate cancellation in latest-job snapshots 2026-10-20 23:01:00 +08:00
gitea 48ab35a8ac test: allow headroom for shell fixture subprocesses 2026-10-20 23:00:39 +08:00
gitea 813d190524 fix(approval): apply expiry checks to checklist operations and scoped handles 2026-10-20 18:10:46 +08:00
gitea e86c05d51a fix(workflow): protect the sole trigger when deleting task nodes 2026-10-20 18:09:11 +08:00
gitea 55c3521c48 fix(workflow): require typed evidence before blocking formula-like mappings 2026-10-20 18:08:06 +08:00
gitea 98ceb85a5c fix(workflow): distinguish watch completion from timeout and cancellation 2026-10-20 18:06:53 +08:00
gitea b91b5d2635 fix(events): scan paginated queues without losing active event deduplication 2026-10-20 18:05:48 +08:00
gitea 3141cc3b29 fix(workflow): propagate rejected node grants to CLI failure status 2026-10-20 18:04:48 +08:00
gitea 2aea435116 fix(workflow): include mappings and structural movement in snapshot diffs 2026-10-20 18:03:45 +08:00
gitea 4c4cd42edd fix(workflow): return script JSON reports and honor output options 2026-10-20 18:02:31 +08:00
gitea 6451c120f0 fix(datalink): preserve quoted literal types and text identifiers 2026-10-20 18:01:57 +08:00
gitea 298a02a3a3 fix(datalink): preserve quoted commas and reject malformed assignments 2026-10-20 18:00:50 +08:00
gitea 85384bc136 fix(approval): treat zero expiry consistently across session handles 2026-10-20 17:59:19 +08:00
gitea b69b78fc30 fix(approval): enforce session expiry for every operation handle 2026-10-20 17:58:33 +08:00
gitea 53689e89d0 fix(auth): renew cached subdomain tokens before bounded request replay 2026-10-20 17:57:41 +08:00
gitea b232e934fc fix(service): preview lifecycle actions without process mutations 2026-10-20 17:53:48 +08:00
gitea 32610e0b11 fix(update): preview updates before network or installation side effects 2026-10-20 17:52:50 +08:00
gitea d2e0d564ca fix(workflow): prevent prototype traversal and inherited CLI authorization 2026-10-20 17:52:14 +08:00
gitea f46e0e7b0a fix(workflow): distinguish hierarchical node selectors from global indices 2026-10-20 17:51:31 +08:00
gitea 0e6090a92c fix(workflow): require confirmation and honor dry-run for node grants 2026-10-20 17:50:45 +08:00
gitea ae2a1a9d60 fix(approval): keep dry-run paths free of remote and local mutations 2026-10-20 17:50:06 +08:00
gitea a5abfbe077 fix(approval): validate finding states and fail closed on corrupt data 2026-10-20 17:48:48 +08:00
gitea 221b9596b8 fix(approval): reject execution across session corporation boundaries 2026-10-20 17:48:03 +08:00
gitea 2844fd49dd fix(workflow): isolate local scripts in bounded QuickJS runtime 2026-10-20 17:47:08 +08:00
yunyingk fac81b08e8 Merge pull request #123 from yunyingk/release/v0.8.15
CI / validate (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.15 — 工作流节点字典探针、灰度开通收敛与静态分析硬门禁边界
2026-10-20 13:32:47 +08:00
gitea 74954b3e7a release: v0.8.15 — 工作流节点字典探针、灰度开通收敛与静态分析硬门禁边界 2026-10-20 13:32:05 +08:00
yunyingk 99e1e0c4b6 Merge pull request #122 from yunyingk/feat/workflow-analyzer-hard-soft-boundaries
CI / validate (push) Has been cancelled
feat(workflow): 静态分析诊断边界显式化(硬门禁 vs 软建议)与架构演进文档
2026-10-20 13:31:18 +08:00
gitea 18da4cc066 feat(workflow): 显式化静态分析硬门禁与软建议边界、完善发布门禁与架构演进文档 2026-10-20 13:30:23 +08:00
yunyingk c1e94ce63e Merge pull request #121 from yunyingk/feat/workflow-nodes-probe-grant
CI / validate (push) Has been cancelled
feat(workflow): 企业可用节点探针、灰度开通收敛与DataLink公式硬规则校验
2026-10-20 13:11:40 +08:00
gitea 9ca9af97e5 build(mcp): 同步重新打包 dist/mcp/server.js 2026-10-20 13:10:54 +08:00
gitea 0768b94d65 feat(workflow): 企业可用节点探针、灰度开通收敛与DataLink公式硬规则校验 2026-10-20 13:08:36 +08:00
yunyingk 4f0eea5725 Merge pull request #120 from yunyingk/fix/gitea-release-retry
CI / validate (push) Has been cancelled
fix(release): 恢复 Gitea 镜像上传并限制并发
2026-10-18 00:50:00 +08:00
gitea 9a9e857606 fix(release): retry bounded Gitea uploads and support mirror recovery 2026-10-18 00:46:40 +08:00
yunyingk 07031f58a0 Merge pull request #119 from yunyingk/codex/release-v0.8.14
CI / validate (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.14 — CLI、MCP 与分发完整性修复
2026-10-17 20:39:16 +08:00
gitea 3151897a9a chore(release): bump version to v0.8.14 2026-10-17 20:35:39 +08:00
gitea 103ead0fe5 fix: harden CLI parsing, MCP startup and release integrity 2026-10-17 20:32:36 +08:00
yunyingk f0902f5f20 Merge pull request #118 from yunyingk/feat/workflow-action-enums-and-lint
feat(workflow): add action enums, EKB_ENUM resolver, and condition dead-filter lint
2026-10-16 13:30:48 +08:00
gitea 1876e8a8f2 feat(workflow): add action enums, EKB_ENUM resolver, and condition dead-filter lint 2026-10-16 13:27:32 +08:00
yunyingk 627e17e0f2 Merge pull request #117 from yunyingk/feat/corp-env-flag
feat(corps): 企业配置增加环境属性与生产安全保护机制
2026-10-16 12:46:00 +08:00
gitea af1e11c018 feat(corps): 企业配置增加环境属性与生产安全保护机制
- Schema 扩展: CorpConfigSchema 增加 env ('prod' | 'test' | 'demo') 与 isTest 字段,未知企业保守兜底为 prod
- 智能初判与归一化: inferCorpEnvFromName 依据名称初判环境,normalizeCorpConfig 确保配置持久化时环境对齐
- CLI 视图升级: corps list 与 search 增加「环境」列 (🏭 正式 / 🧪 测试 / 🎪 演示),支持 --test/--prod/--env 筛选
- 环境打标与迁移: 新增 hose-use corps tag 命令,支持单个企业标记与 --migrate-all 批量显式升级持久化
- 生产安全阻断: workflow test 等敏感调试在正式生产环境 (prod) 阻断执行,需显式附加 --force 确认生产风险
- 上下文与探针增强: context、probe、corps current 全面输出企业环境属性
- 测试与文档补全: 覆盖 489 项全量测试并通过 tsc 类型检查
2026-10-16 12:30:08 +08:00
yunyingk 908286c1df Merge pull request #116 from yunyingk/refactor/platform-workflow-submodules
refactor(platform): organize workflow capabilities into structured submodules
2026-10-15 17:10:02 +08:00
gitea 5aef332026 refactor(platform): organize workflow capabilities into structured submodules 2026-10-15 17:09:37 +08:00
yunyingk c917df13cc Merge pull request #115 from yunyingk/feat/workflow-script-lint-and-eval
feat(workflow): implement script linting and offline sandbox evaluation
2026-10-15 16:50:57 +08:00
gitea d293bb47a4 feat(workflow): implement script linting and offline sandbox evaluation 2026-10-15 16:50:24 +08:00
yunyingk 97eaed1066 Merge pull request #114 from yunyingk/feat/workflow-tail-and-watch
feat(workflow): implement real-time workflow tail and watch commands
2026-10-15 16:37:57 +08:00
gitea 53201ba4e1 feat(workflow): implement real-time workflow tail and watch commands 2026-10-15 16:37:27 +08:00
yunyingk 71f9879f68 Merge pull request #113 from yunyingk/feat/workflow-node-declarative-edit
feat(workflow): implement declarative node editing commands
2026-10-15 16:25:00 +08:00
gitea 3261b6ebdb feat(workflow): implement declarative node editing commands 2026-10-15 16:24:25 +08:00
yunyingk 61123ad550 Merge pull request #112 from yunyingk/feat/workflow-create-pure
feat(workflow): implement workflow create command from scratch with draft state defense
2026-10-15 15:55:12 +08:00
gitea 02b197c119 feat(workflow): implement workflow create command from scratch with draft state defense 2026-10-15 15:54:33 +08:00
yunyingk aa58dd7f6f Merge pull request #111 from yunyingk/feat/workflow-copy-and-lifecycle
feat(workflow): implement workflow copy and delete lifecycle commands
2026-10-15 15:19:38 +08:00
gitea b043cb614e feat(workflow): implement workflow copy and delete lifecycle commands 2026-10-15 15:18:49 +08:00
yunyingk fec25bff8a Merge pull request #110 from yunyingk/feat/webhook-samples-and-trigger-catalog
feat(workflow): support webhook sample records, params preview and expand trigger catalog
2026-10-15 15:02:00 +08:00
gitea c56460716f feat(workflow): support webhook sample records, params preview and expand trigger catalog 2026-10-15 15:01:20 +08:00
yunyingk 8531530ccd Merge pull request #109 from yunyingk/fix/recent-pr-stability
fix: stabilize auth identity, record operations, and workflow diagnostics
2026-10-15 14:57:25 +08:00
gitea b605d7c2bb Merge origin/main and preserve debug safeguards across trigger paths 2026-10-15 14:56:11 +08:00
gitea 7ec369f77e fix: stabilize auth identity, record operations, and workflow diagnostics 2026-10-15 14:54:10 +08:00
yunyingk f333c7f1fb Merge pull request #108 from yunyingk/feat/workflow-debug-trigger-path-branching
feat(workflow): implement trigger-aware debug path branching for clock, webhook, datalink and flowform
2026-10-15 14:33:41 +08:00
gitea c8d9e409c6 feat(workflow): implement trigger-aware debug path branching for clock, webhook, datalink and flowform 2026-10-15 14:32:56 +08:00
yunyingk c74fdda7da Merge pull request #107 from yunyingk/feat/workflow-debug-prod-allow-with-prompt
feat(workflow): allow enabled workflow debugging with full security prompts instead of hard block
2026-10-15 14:19:20 +08:00
gitea c507879896 feat(workflow): allow enabled workflow debugging with full security prompts instead of hard block 2026-10-15 14:19:00 +08:00
yunyingk f6227f277a Merge pull request #106 from yunyingk/fix/workflow-prod-debug-guard
fix(workflow): intercept production debug on enabled workflows without force and document platform vulnerability
2026-10-15 14:14:13 +08:00
gitea 0b4519652b fix(workflow): intercept production debug on enabled workflows without force and document platform vulnerability 2026-10-15 14:13:50 +08:00
yunyingk 36a3c3b28d Merge pull request #105 from yunyingk/chore/workflow-help-docs
chore(cli): document diff, diff-job, and test subcommands in workflow help
2026-10-15 13:26:13 +08:00
gitea 86d6c1d340 chore(cli): document diff, diff-job, and test subcommands in workflow help 2026-10-15 13:26:03 +08:00
yunyingk ed3f38f1ab Merge pull request #104 from yunyingk/feat/workflow-debug-test-and-branch-diagnosis
feat(workflow): end-to-end workflow debug test command and condition branch explanation
2026-10-15 13:24:50 +08:00
gitea fe6183dd44 feat(workflow): add end-to-end workflow debug test command and condition branch explanation 2026-10-15 13:24:14 +08:00
yunyingk febeecdec7 Merge pull request #103 from yunyingk/feat/datalink-ref-card-display
feat(datalink): support card data.dataLink unwrapping in normalizeDatalinkRecord
2026-10-15 11:05:38 +08:00
gitea 0b3b022edf feat(datalink): support card data.dataLink unwrapping in normalizeDatalinkRecord 2026-10-15 11:05:12 +08:00
yunyingk 0e2fb6a9b8 Merge pull request #102 from yunyingk/feat/datalink-compact-reference-normalization
fix(datalink): compact reference and card object flattening in normalizeDatalinkRecord
2026-10-15 11:03:17 +08:00
gitea 2c32758e34 fix(datalink): compact reference and card object flattening in normalizeDatalinkRecord 2026-10-15 11:02:57 +08:00
yunyingk 1ee26d786a Merge pull request #101 from yunyingk/feat/platform-records-streaming-and-stats
feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface
2026-10-15 11:01:23 +08:00
gitea 03195bbbe5 feat(platform): add streaming ndjson, stats profiling, flat normalization, and public sdk surface 2026-10-15 11:00:18 +08:00
yunyingk 26a6b7318c Merge pull request #100 from yunyingk/feat/platform-ledger-audit-and-batch-ops
feat(datalink,platform): add ledger math audit, continuity check, and in-line declarative batch update (Phase 4 & 5)
2026-10-14 22:26:27 +08:00
gitea cd0aa2bf41 feat(datalink,platform): add ledger math audit, continuity check, and in-line declarative batch update 2026-10-14 22:25:48 +08:00
yunyingk d3f7d3efbc Merge pull request #99 from yunyingk/feat/workflow-diff-suite
feat(workflow): add workflow snapshot diff and job execution diff suite (Phase 3)
2026-10-14 22:13:32 +08:00
gitea 2f94768184 feat(workflow): add workflow snapshot diff and job execution diff suite (Phase 3) 2026-10-14 22:13:05 +08:00
yunyingk d37ebb7fcd Merge pull request #98 from yunyingk/feat/flow-trace-diagnostics
feat(bill,flow): add unified bill trace and flow get diagnostic engine (Phase 2)
2026-10-14 22:01:35 +08:00
gitea ffec604ed9 feat(bill,flow): add unified bill trace and flow get diagnostic engine (Phase 2) 2026-10-14 22:00:55 +08:00
yunyingk 7891959853 Merge pull request #97 from yunyingk/feat/observable-ops-phase1
feat(ops): add dynamic staff link switching and deep failed job inspection (Phase 1)
2026-10-14 18:33:06 +08:00
gitea 0c6a3ee660 feat(workflow,corps): add dynamic staff link switching and deep failed job inspection 2026-10-14 18:32:14 +08:00
gitea 0499ccb2cc refactor(corps): normalize credential categories and format workflow history logs 2026-10-14 18:19:13 +08:00
yunyingk f91a80f9dd Merge pull request #96 from yunyingk/chore/legacy-cleanup
chore(legacy): remove ekb-mcp migration layer and other compat residue
2026-10-05 16:29:33 +08:00
gitea 95eb8ee676 chore(legacy): remove ekb-mcp migration layer, approval db compat shim, and stale daily notes
The ekb-mcp -> hose-use rename migration (LEGACY_* constants,
syncLegacyEnterprisesDir/syncLegacyGlobalConfig with 7-day grace
cleanup, dual-source enterprises resolution) has completed its job:
legacy data self-deleted on active machines years of grace ago.
Config resolution now returns the single primary
~/.config/hose-use source; startup no longer scans the legacy dir.

- core/config/loader.ts: drop legacy constants, sync functions, and
  LEGACY path from diagnostics candidates; loader.test.ts drops the
  three legacy-migration cases
- domains/approval/db.ts deleted: pure pass-through over core/db whose
  consumers (repository.ts) already call core/db directly; the four
  test files now import getDatabase/closeDatabase from core/db
- scripts/dev-hygiene.ts: drop the config.legacy finding and
  legacyConfig snapshot field
- docs/daily/* removed: Python-era (ekb-cli/ekb-mcp) notes describing
  commands and architecture that no longer exist (preserved in git
  history)

No behavior change on machines without legacy data: tsc clean,
313 tests pass (316 minus the 3 removed legacy cases).
2026-10-05 16:29:19 +08:00
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
yunyingk 77bd125ef3 Merge pull request #45 from yunyingk/feat/approval-sqlite-engine
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
2026-09-06 19:07:40 +08:00
gitea 644c3d2005 fix(cli): unify hose-aipro as multicall symlink alias to hose-use binary 2026-09-06 19:05:07 +08:00
gitea 4e36a1d9a5 feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
- Pure Rule Model & AST Parser:
  - Eliminate redundant title field; model rules purely via scope (scene index) and natural language body.
  - Implement AST parser for inline clauses: [action]{硬性|弹性|建议|特殊}.
  - Validate and enforce preference references with @{级别} syntax, strictly blocking invalid grammar.

- Embedded SQLite Database & Repository:
  - Native bun:sqlite integration with zero external dependencies, stored at ~/.config/hose-use/approval.db.
  - 5 core schemas: rules, preferences, approval_runs, approval_findings, and aipro_logs.
  - Support deduplicated scope indexing (listScopes with 1-based indices) and scope drill-down (getScopeDetail).

- Bill Requisition & Backlog Query Extension:
  - Add formatFlowAsBill adapter in domains/bill/tools.ts.
  - Fall back to flow and backlog inspection when bills are not found in invoice endpoints, unlocking full structured inspection for requisitions (such as S26000001) and loan requests.

- Deterministic Approval Gateway & Lifecycle:
  - Enforce mandatory approval lifecycle: points -> checklist -> review -> decide.
  - Physical gateway blocking: forbid decision if audit checklist is missing or empty, or if pending points remain unverified.
  - Hard tier severance: automatically sever and throw GatewayBlockError on approval attempts violating {硬性} clauses.

- Dedicated hose-aipro Global CLI & Immutable Audit Ledger:
  - Register secondary global binary hose-aipro alongside hose-use in package.json and build-binary.mjs.
  - Automatically record every AI Pro invocation, document context, args snapshot, operator, status, and verdict in aipro_logs.
  - Provide intuitive subcommands: points, checklist, review, decide, logs, rules.
  - Bump project version to v0.7.0 and regenerate OpenAPI bundles.
2026-09-06 19:03:06 +08:00
yunyingk 7c0bdb7518 Merge pull request #44 from yunyingk/feat/update-sources-and-repo-opt
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(cli): enhance update sources, normalize repo, upgrade MCP to 2.0, bump to v0.6.2
2026-09-05 22:32:55 +08:00
gitea 2865728885 feat(cli): enhance update sources, normalize repo, upgrade to MCP 2.0, and bump to v0.6.2 2026-09-05 22:32:39 +08:00
yunyingk eaa2b9391f Merge pull request #43 from yunyingk/fix/update-asset-fallback
fix(update): fall back to GitHub releases when Gitea mirror has empty assets
2026-09-05 22:21:03 +08:00
gitea 51502fada5 fix(update): fall back to GitHub releases when Gitea mirror has empty assets 2026-09-05 22:20:45 +08:00
yunyingk cf5d12b0a5 Merge pull request #42 from yunyingk/fix/case-insensitive-version-and-help
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
fix(cli): support case-insensitive version & help aliases and bump to v0.6.1
2026-09-05 22:17:48 +08:00
gitea 535404871c chore(release): bump version to v0.6.1 2026-09-05 22:17:32 +08:00
gitea 269b7e8f0f fix(cli): support case-insensitive version and help flags and subcommands 2026-09-05 22:16:56 +08:00
yunyingk c99c5d98ec Merge pull request #41 from yunyingk/fix/version-and-help-aliases
fix(cli): support version and help aliases (v, V, -V, h, -h)
2026-09-05 22:14:22 +08:00
gitea 4fbd737402 fix(cli): support version and help aliases (v, V, -V, h, -h) 2026-09-05 22:13:57 +08:00
yunyingk 40b3b29ca5 Merge pull request #40 from yunyingk/codex/release-v0.6.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.6.0
2026-09-05 22:05:23 +08:00
gitea 04d3dbcc02 chore(release): bump version to v0.6.0 2026-09-05 22:03:33 +08:00
yunyingk 39fb3a47f5 Merge pull request #39 from yunyingk/codex/issue-8-approval-actions
feat: add bill approval action suite
2026-09-05 21:57:06 +08:00
gitea aa2a61d44f feat: add bill approval action suite 2026-09-05 21:56:38 +08:00
yunyingk 507bf6ab91 Merge pull request #38 from yunyingk/feat/issue-6-flow-durations
feat: add approval flow dwell time metadata
2026-09-05 21:16:48 +08:00
gitea 9ddbd0390d feat: add approval flow dwell time metadata 2026-09-05 21:16:26 +08:00
yunyingk a2d078aafe Merge pull request #37 from yunyingk/feat/issue-11-message-pagination
feat: complete message listing and read-all pagination
2026-09-05 21:14:40 +08:00
gitea 85bbc9bbb4 feat: add complete message listing and pagination 2026-09-05 21:13:05 +08:00
yunyingk e84cae7f80 Merge pull request #36 from yunyingk/feat/issue-7-bill-audit
feat: include risk snapshot in bill details
2026-09-05 21:08:24 +08:00
gitea 2b4bf49663 feat: include risk snapshot in bill details 2026-09-05 21:07:48 +08:00
yunyingk 06da94152d Merge pull request #35 from yunyingk/feat/issue-9-attachment-download
feat: add bill attachment download command
2026-09-05 20:56:16 +08:00
gitea 17e5418005 feat: add bill attachment download command 2026-09-05 20:55:39 +08:00
yunyingk a5bfaafa10 Merge pull request #34 from yunyingk/feat/issue-12-event-poller
feat: add durable service event poller
2026-09-05 20:48:45 +08:00
gitea 84e6fa58fd feat: add durable service event poller 2026-09-05 20:48:32 +08:00
yunyingk f72deb01b1 Merge pull request #33 from yunyingk/feat/issue-32-role-permissions
feat: add read-only permission snapshot CLI
2026-09-05 20:45:54 +08:00
gitea acd187b616 feat: add read-only permission snapshot CLI 2026-09-05 20:45:34 +08:00
yunyingk 43d923f567 Merge pull request #31 from yunyingk/fix/issue-9-draft-attachments
fix: resolve attachments from draft bills
2026-09-05 20:40:05 +08:00
gitea e44b120cc2 fix: resolve attachments from draft bills 2026-09-05 20:39:54 +08:00
yunyingk 7d9f656567 Merge pull request #30 from yunyingk/chore/platform-null-test
test: cover nullable app metadata
2026-09-05 20:36:14 +08:00
gitea c14338f1bc test: cover nullable app metadata 2026-09-05 20:36:03 +08:00
yunyingk 9d351ed15d Merge pull request #29 from yunyingk/feat/issue-1-workflow-analysis
feat: add workflow static analysis CLI
2026-09-05 20:34:42 +08:00
gitea 373fb11a81 feat: add workflow static analysis CLI 2026-09-05 20:34:25 +08:00
yunyingk 2a06cf58b7 Merge pull request #28 from yunyingk/feat/issue-2-roles
feat: add role definitions and member CLI
2026-09-05 20:29:58 +08:00
gitea 6d61ece8cd feat: add role definitions and member CLI 2026-09-05 20:29:36 +08:00
yunyingk 3d963e9a7e Merge pull request #27 from yunyingk/feat/issue-15-bill-reference-join
feat: resolve archive references in bill details
2026-09-05 20:20:52 +08:00
gitea 96d28da862 feat(bill): resolve archive references in bill details 2026-09-05 20:20:40 +08:00
yunyingk 1d1170526b Merge pull request #26 from yunyingk/feat/issue-15-dimensions
feat: query custom archive dimensions
2026-09-05 20:17:43 +08:00
gitea 1f3334bfbd feat(dimension): query custom archive catalogs and items 2026-09-05 20:17:19 +08:00
yunyingk a0d13ca36a Merge pull request #25 from yunyingk/feat/issue-9-bill-attachments
feat: normalize bill attachment metadata
2026-09-05 20:11:44 +08:00
gitea 9e1a13c1fe feat(bill): normalize attachment metadata 2026-09-05 20:11:33 +08:00
yunyingk 334c72617c Merge pull request #24 from yunyingk/feat/issue-13-bill-budget
feat: expose bill budget status
2026-09-05 20:06:29 +08:00
gitea 0514291d2d feat(bill): expose budget status from approval risk checks 2026-09-05 20:06:19 +08:00
yunyingk cbeeca746b Merge pull request #23 from yunyingk/feat/issue-14-bill-relations
feat: trace linked bill relations
2026-09-05 20:04:28 +08:00
gitea 7a8f2f6931 feat(bill): trace linked loan and requisition records 2026-09-05 20:04:08 +08:00
yunyingk 3df9201a5e Merge pull request #22 from yunyingk/feat/issue-5-bill-references
feat: resolve bill reference IDs
2026-09-05 19:59:36 +08:00
gitea 60866efa2e feat(bill): resolve referenced IDs for approval details 2026-09-05 19:59:15 +08:00
yunyingk dbf8dd942e Merge pull request #21 from yunyingk/feat/issue-7-bill-risk
feat: add CLI bill risk review
2026-09-05 19:46:09 +08:00
gitea 6468710730 feat: add CLI bill risk review 2026-09-05 19:45:21 +08:00
yunyingk 85d5f8f13a Merge pull request #20 from yunyingk/feat/issue-6-bill-flow
feat: add CLI bill approval flow timeline
2026-09-05 19:41:09 +08:00
gitea a8bdb67293 feat: add CLI bill approval flow timeline 2026-09-05 19:40:45 +08:00
yunyingk 155f179fcd Merge pull request #19 from yunyingk/feat/issue-11-message-center
feat: add CLI message center commands
2026-09-05 14:06:07 +08:00
gitea 621c8cb7dc feat: add CLI message center commands 2026-09-05 14:05:05 +08:00
yunyingk 0be1365289 Merge pull request #18 from yunyingk/feat/issue-10-submitted-tasks
feat: add CLI submitted task query
2026-09-05 13:52:00 +08:00
gitea 97abdb4f96 feat: add CLI submitted task query 2026-09-05 13:51:33 +08:00
yunyingk 12247fd350 Merge pull request #17 from yunyingk/feat/issue-10-carbon-copy
feat: add CLI carbon copy task query
2026-09-05 13:41:48 +08:00
gitea 49b0359adb feat: add CLI carbon copy task query 2026-09-05 13:40:20 +08:00
yunyingk 1ef611eeab Merge pull request #16 from yunyingk/feat/issue-10-task-center
feat: add CLI task center queries
2026-09-05 13:35:06 +08:00
gitea d28b0c92d9 feat: add CLI task center queries 2026-09-05 13:33:33 +08:00
yunyingk 6c0f4dc567 Merge pull request #4 from yunyingk/chore/align-release-guidelines
docs: 固化分支管理与发布流程,严格对齐 seal-use
2026-09-03 17:33:29 +08:00
gitea 8aa401ab79 docs: formalize hard-enforced PR workflow and push order matching seal-use 2026-09-03 17:25:48 +08:00
yunyingk a381fa2698 Merge pull request #3 from yunyingk/chore/repo-standards-and-pr-flow
chore: 规范化分支管理与 PR 合并流程(对标 seal-use)
2026-09-03 16:10:34 +08:00
gitea 88e8c384a6 docs: enforce PR merge workflow and branch standards matching seal-use 2026-09-03 16:10:11 +08:00
gitea 68d570022d feat: release v0.5.2 with protected contact domain and bill web link
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:58:20 +08:00
gitea 188a0fb5dc feat: release v0.5.1 with multi-file skill system and IDE plugin manifest
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:32:01 +08:00
gitea c1dc9f1616 feat: release v0.5.0 with embedded HTTP server and resident daemon service
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:19:12 +08:00
gitea 07b4e14e59 fix(test): 增强 server.test.ts 在无凭证全新 CI 容器环境下的兼容断言
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:41:10 +08:00
gitea ba30c1a6cb feat(cli): 支持大输出防爆保护、本地文件转储与敏感凭证全链路脱敏并发布 v0.4.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:40:32 +08:00
gitea cf44c7dcdf feat(config): 支持多层级企业配置发现、读写分离安全落盘与路径诊断并发布 v0.4.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:34:29 +08:00
gitea 9e20caf4a3 feat(mcp): 引入 MCP 单工具网关模式 (hose_cli) 与并发流调度并发布 v0.4.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:28:41 +08:00
gitea 4f510efc1b feat(auth): 支持代客协助平台凭证智能识别、Token过期感知与单据字典增强并发布 v0.3.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:08:47 +08:00
gitea 5cf6c9e014 feat(bill): 引入费控单据与费用明细检索(支持按单号精准查询与 DataLink 字典自动还原)并发布 v0.3.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:48:20 +08:00
gitea 0372698ff9 ci: 添加 openapi:all 构建步骤并集成 GitHub 与 Gitea 自动双发布
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:33:45 +08:00
gitea b13959451a feat(openapi): 引入双层 OpenAPI 规范管理 (原始下游 & 包装层工具) 并升级版本至 v0.2.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:29:32 +08:00
gitea 2dfcf67b00 feat(update): 实现多镜像源自更新机制 (update/upgrade) 并升级版本至 v0.2.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:19:13 +08:00
gitea 6e73de697b docs: 更新仓库名称与一键安装链接至 yunyingk/hose-use 2026-08-27 11:10:06 +08:00
398 changed files with 62489 additions and 2175 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
+36
View File
@@ -0,0 +1,36 @@
name: CI
on:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
- run: bun install --frozen-lockfile
- run: bun run check:version
- run: bun run check
- run: bun test
- run: bun run build:binary
- run: bun run scripts/verify-binary.ts dist/bin/hose-use
- run: bun run build:plugin
- run: git diff --exit-code -- dist/mcp/server.js
- run: bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
+190 -15
View File
@@ -5,52 +5,227 @@ on:
tags:
- "v*"
workflow_dispatch:
inputs:
tag:
description: Release tag already merged into main (e.g. v0.8.14)
required: true
type: string
mirror_only:
description: Reuse the existing GitHub assets and repair only the Gitea mirror
required: false
default: false
type: boolean
concurrency:
group: release-${{ inputs.tag || github.ref_name }}
cancel-in-progress: false
permissions:
contents: write
contents: read
jobs:
build-and-publish:
name: 🚀 Build & Publish Multi-Platform Binaries
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: write
env:
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
MIRROR_ONLY: ${{ inputs.mirror_only || false }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ inputs.tag || github.ref }}
fetch-depth: 0
- 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
# A tag alone does not prove review. Also verify the commit actually being
# compiled, so manual dispatch cannot validate one tag and ship another ref.
- name: Verify release commit and version
run: |
git fetch --no-tags origin main:refs/remotes/origin/main
bun run scripts/verify-release.ts "$RELEASE_TAG"
- name: Install dependencies
if: ${{ !inputs.mirror_only }}
run: bun install --frozen-lockfile
- name: Check committed version consistency
if: ${{ !inputs.mirror_only }}
run: bun run check:version
- name: Generate & bundle OpenAPI
if: ${{ !inputs.mirror_only }}
run: bun run openapi:all
- name: Type-check
if: ${{ !inputs.mirror_only }}
run: bun run check
- name: Test
if: ${{ !inputs.mirror_only }}
run: bun test
- name: Compile multi-target binaries
if: ${{ !inputs.mirror_only }}
run: |
mkdir -p dist/bin
node scripts/build-binary.mjs --all
node scripts/build-binary.mjs --all --release
- name: Verify packaged MCP entrypoint
if: ${{ !inputs.mirror_only }}
run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64
- name: Verify plugin bundle runtime
if: ${{ !inputs.mirror_only }}
run: |
bun run build:plugin
bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
- name: Package release archives
if: ${{ !inputs.mirror_only }}
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}"
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
- name: Publish GitHub Release
if: ${{ !inputs.mirror_only }}
env:
GH_TOKEN: ${{ github.token }}
run: |
TAG_MSG=$(git tag -l --format='%(contents)' "${GITHUB_REF_NAME}" | sed '/^$/d')
TAG_MSG=$(git tag -l --format='%(contents)' "${RELEASE_TAG}" | sed '/^$/d')
if [ -n "$TAG_MSG" ]; then
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "$TAG_MSG" --generate-notes
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --notes "$TAG_MSG" --generate-notes
else
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --generate-notes
fi
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
gh release upload "${RELEASE_TAG}" dist/bin/hose-use-* dist/bin/checksums.txt --repo "${GITHUB_REPOSITORY}" --clobber
- name: Publish Gitea Release
env:
GH_TOKEN: ${{ github.token }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/hose-use"
run: |
set -euo pipefail
if [ -z "$GITEA_TOKEN" ]; then
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
echo "::error::GITEA_TOKEN is required to repair the mirror."
exit 1
fi
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
exit 0
fi
TAG_NAME="${RELEASE_TAG}"
if [ "${MIRROR_ONLY:-false}" = "true" ]; then
# Preserve the published bytes and checksums; never rebuild or replace GitHub assets.
mkdir -p dist/bin
gh release download "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --dir dist/bin --pattern 'hose-use-*' --pattern checksums.txt
(cd dist/bin && sha256sum --strict -c checksums.txt)
fi
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
echo "==> Creating release on Gitea for ${TAG_NAME}..."
RELEASE_RESP=$(curl -sS --connect-timeout 15 --max-time 60 -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
if [ -z "$RELEASE_ID" ]; then
RELEASE_ID=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
fi
if [ -z "$RELEASE_ID" ]; then
echo "::error::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
exit 1
fi
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
upload_asset() {
local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed
filename=$(basename "$file")
expected_hash=$(sha256sum "$file" | awk '{ print $1 }')
for attempt in 1 2 3; do
if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi
echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..."
if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then
continue
fi
existing=$(printf '%s' "$info" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id')
if [ -n "$existing" ]; then
if ! remote_hash=$(curl -fLsS --connect-timeout 15 --max-time 600 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/${GITEA_REPO}/releases/download/${TAG_NAME}/${filename}" | sha256sum | awk '{ print $1 }'); then
continue
fi
if [ "$remote_hash" = "$expected_hash" ]; then
echo " [skip] ${filename} already matches SHA-256"
return 0
fi
# Match GitHub --clobber only when the existing bytes differ.
delete_failed=0
for asset_id in $existing; do
curl -fsS --connect-timeout 15 --max-time 60 -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" || delete_failed=1
done
if [ "$delete_failed" -ne 0 ]; then continue; fi
fi
if response=$(curl -fsS --connect-timeout 15 --max-time 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}"); then
echo " [done] ${filename} -> $(printf '%s' "$response" | tail -n 1)"
return 0
fi
done
echo "::error::Failed to upload ${filename} after 3 attempts."
return 1
}
# Bound outbound traffic: large raw binaries must not compete with all archives.
pids=()
failed=0
for file in dist/bin/hose-use-* dist/bin/checksums.txt; do
upload_asset "$file" &
pids+=($!)
if [ "${#pids[@]}" -eq 2 ]; then
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
pids=()
fi
done
if [ "${#pids[@]}" -gt 0 ]; then
for pid in "${pids[@]}"; do wait "$pid" || failed=1; done
fi
if [ "$failed" -ne 0 ]; then
echo "::error::One or more Gitea assets failed to upload."
exit 1
fi
echo "✓ Successfully published release assets to Gitea!"
+7 -4
View File
@@ -3,7 +3,8 @@ node_modules
# output
out
dist
dist/bin/
dist/hose-use-*
*.tgz
# code coverage
@@ -43,6 +44,8 @@ data/
*.db
*.sqlite
# 环境变量
.env
.env.local
# Local roadmaps & scratch notes
*.local.md
# Exports
exports/
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"hose-use": {
"type": "stdio",
"command": "bun",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
},
"timeoutMs": 120000
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "hose-use",
"version": "0.8.17",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
"title": "启用 MCP 服务",
"description": "开启后向 Agent 暴露 hose_cli 单工具网关;默认关闭。保存后重新连接该插件的 MCP 服务。",
"default": false
}
}
}
+76 -32
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/ (业务子域:编排 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 文件里不要重复做局部异常体系
## 文档规则
@@ -89,3 +98,38 @@ CLI (src/cli.ts) / MCP (src/server.ts)
- 目录细节写进对应目录的 `README.{dirname}.md`
- 文件细节写进对应文件旁的说明文档
- 子域的 API 路径、枚举值、字段语义不要继续回填到根目录
## 分支管理与 PR 合并规范(严格对标 seal-use)
为了保证代码变更可追溯、CI 校验完备与版本安全,本仓库实施**硬性约束(通过 Git pre-push hook 与 PR 流程双重卡点)**:
1. **严禁直接推送到 `main` 分支**:
- 仓库已内置 `.git/hooks/pre-push` 钩子,本地直接执行 `git push origin main` 将被直接拦截拒绝;
- 日常功能开发、Bug 修复和版本发布必须且只能走独立分支;
2. **分支命名规范**:
- 特性分支:`feat/<feature-name>` 或 `codex/issue-<id>-<name>`
- 发布分支:`codex/release-v<X.Y.Z>` 或 `release/v<X.Y.Z>`
- 维护优化:`chore/<task-name>`、`refactor/<task-name>` 或 `fix/<issue-name>`
3. **Pull Request 提交流程**:
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
- 推送分支至远端:`git push origin <branch>`;
- 发起 PR:`gh pr create --base main --head <branch> --title "..." --body "..."`(如有对应 Issue 需关联 `Fixes #...`);
- 等待 CI 检查:`gh pr checks <pr-number> --watch`;
- 审查通过后合入:`gh pr merge <pr-number> --merge --delete-branch`;
4. **版本发布与 Tag 推送标准流程(严格对齐 seal-use)**:
- PR 合并后,切回本地 `main` 分支并同步:
```bash
git switch main
git pull --ff-only origin main
git push home main
```
- 打 Release Tag:
```bash
git tag -a vX.Y.Z -m "🚀 Release summary text describing key changes"
```
- **推送顺序极关键**:先推 `home` (Gitea),再推 `origin` (GitHub)。最后推 GitHub 触发 Release Action:
```bash
git push home refs/tags/vX.Y.Z
git push origin refs/tags/vX.Y.Z
```
- 监控云端 Release 构建并验证产物发布完成。
+77 -10
View File
@@ -1,4 +1,4 @@
# hose-use (v0.2.0)
# hose-use (v0.8.17)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -7,9 +7,11 @@
### 方式一:一键脚本安装独立二进制(推荐)
```bash
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-serve-tool/main/scripts/install.sh | bash
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
```
安装与自更新会校验 Release 的 SHA-256 清单;版本固定、镜像设置及发布流程见 [构建与分发说明](./src/packaging/README.packaging.md)。
### 方式二:本地 Bun 源码开发
```bash
@@ -17,6 +19,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,31 +44,83 @@ hose-use auth refresh # 批量刷新账号名下全部
# 2. 多企业租户管理
hose-use corps list # 列出名下所有已配置企业
hose-use corps search <关键词> # 模糊搜索已保存的企业与员工 (别名: corps find)
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
# 3. 运行模式管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式与默认企业
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. Agent Skill 与连通性诊断
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
# 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 查询单据结构化详情
hose-use bill schema # 查看企业全部单据实体与数据模型字典
# 6. OpenAPI 规范导出 (原始下游契约 & 包装层工具规范)
hose-use openapi paths # 查看包装层 API 路径与概要一览
hose-use openapi --raw paths # 查看合思原生下游全量 API 路径
hose-use openapi info # 查看 OpenAPI 规范元数据概览
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
# 7. 内置 HTTP Server 与常驻 Service 守护进程
hose-use http --port=8888 # 前台启动 HTTP 服务与 Scalar 交互式文档 (http://localhost:8888/docs)
hose-use service start # 后台启动常驻守护进程
hose-use service status # 查看常驻服务运行状态、PID 与接口端点
hose-use service logs # 查看守护进程日志
hose-use service stop # 优雅停止常驻守护进程
# 8. Agent Skill 与连通性诊断
hose-use skill install --yes # 一键将 Agent Skill 安装到 ~/.agents/skills/
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
# 9. MCP Server (单工具网关模式)
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
```
### AI 智能体与 MCP 单工具网关 (`hose_cli`)
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
- 避免数十个业务工具占用大量 Prompt Tokens;
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
- 内部同进程调用 CLI 分发层,零子进程开销;
- `HOSE_MCP_MODE` 始终采用 `single`;通过 `HOSE_USE_MCP_ENABLED=false` 可关闭工具暴露,写操作沿用 CLI 的预览与确认约定。
### 模块化 Agent Skill 与 IDE 插件规范
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
## 架构
```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)
@@ -99,7 +166,7 @@ src/
- **Runtime**: Bun
- **HTTP Client**: ky
- **Schema**: Zod
- **MCP SDK**: @modelcontextprotocol/sdk
- **MCP Protocol**: @modelcontextprotocol/server & @modelcontextprotocol/core (v2.0+)
## 面向 AI 智能体
+16 -159
View File
@@ -5,211 +5,68 @@
"": {
"name": "ekb-mcp",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
"zod": "^4.4.3",
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"typescript": "^5.9.3",
},
},
},
"packages": {
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@jitl/quickjs-ffi-types": ["@jitl/quickjs-ffi-types@0.32.0", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@jitl/quickjs-singlefile-cjs-release-sync": ["@jitl/quickjs-singlefile-cjs-release-sync@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-NjUUcw26PoeJHND6nmflAH8nIvAJvxJ2qkSPi95wfiBqPim80GtcdWommroiWb8hh1/7fVettEwodAsGt2Mrsg=="],
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.3", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg=="],
"hono": ["hono@4.12.19", "", {}, "sha512-xa3eYXYXx68XTT4hZ7dRzsXBhaq85ToSrlUJNoR0gwz/1Ap/CNwX47wfvV7pc/xWhjKVVkLT7zBJy8chhNguqQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
}
}
+2293
View File
File diff suppressed because it is too large. Load diff
-84
View File
@@ -1,84 +0,0 @@
# 2026-04-06 开发日报
> 截止提交:`792314a`(日报本身所在提交)
> 下一个实例可用 `git log 792314a` 查看全部历史,或 `git checkout 792314a` 还原此状态。
## 今日目标
从零搭建 ekb-cli,实现快报智能审核 Agent 的命令行管理,替代图形界面操作。
---
## 完成事项
### 一、项目骨架
- 初始化 Python 包结构(uv + pyproject.toml)
- 实现认证机制:自定义 Header(accesstoken / corpid / staffid),支持多企业存储与切换
- 解决 SOCKS5 代理兼容问题(补充 `httpx[socks]` 依赖)
### 二、ekb auth 命令组
| 命令 | 功能 |
|---|---|
| `ekb auth add` | 添加企业认证 |
| `ekb auth list` | 列出所有企业 |
| `ekb auth use` | 切换当前企业 |
| `ekb auth remove` | 删除企业 |
| `ekb auth whoami` | 查看当前企业 |
### 三、ekb agent 命令组
**Agent 管理**
| 命令 | 功能 |
|---|---|
| `ekb agent list` | 列出所有 Agent |
| `ekb agent get <id>` | 查看 Agent 详情(含四类条款、关联规则列表) |
| `ekb agent get <id> --full` | 不截断规则字段,提示完整文本总字符数 |
| `ekb agent update <id>` | patch 式修改(只改传入字段,其余保持原值) |
| `ekb agent logs` | 查看审核日志(待实现) |
**规则管理**
| 命令 | 功能 |
|---|---|
| `ekb agent rules` | 列出企业全部审核规则 |
| `ekb agent rules --level 严重` | 按风险等级筛选 |
| `ekb agent rules --full` | 不截断描述字段 |
| `ekb agent rule-get <编码或ID>` | 查看规则详情,含关联 Agent 列表 |
> 编码输入自适应:`1` / `01` / `0001` / `#0001` 均可识别,自动补零对齐。
### 四、ekb commands
`ekb commands` / `ekb commands agent` — 分层展示命令树,引导向下钻取。
### 五、API 封装(api/agent.py)
对接接口:
```
GET /api/engine/hab/agent/list
GET /api/engine/hab/agent/detail
POST /api/engine/hab/agent/save
GET /api/engine/hab/agent/rule/list
POST /api/engine/hab/agent/rule/save
POST /api/engine/hab/agent/rule/update
```
---
## 设计决策
- **截断提示展示字符总数**:CLI 是生产环境唯一入口(无 MCP),AI 读输出时需要知道是否值得拉全量数据,所以截断时提示完整文本总字符数而非截断标准。
- **patch 式 update**:先 GET 当前值,再合并传入字段,避免覆盖未传字段。
- **文档分层**:`CLAUDE.md`(项目级全图)→ `README.agent.md`(agent 语义/常量)→ `README.rule.md`(rule 语义/常量)。枚举常量不写在顶层文件。
---
## 待办
- [ ] `ekb agent logs` — 需抓包确认 API 结构
- [ ] 规则关联管理 — 给 Agent 增删关联规则(`ruleIds` 字段)
- [ ] `ekb rule update` — 修改规则内容(API 已封装,命令未实现)
-72
View File
@@ -1,72 +0,0 @@
# 2026-04-08 开发日报
> 截止提交:`c041966`(日报本身所在提交)
> 下一个实例可用 `git log c041966` 查看全部历史,或 `git checkout c041966` 还原此状态。
## 今日目标
在昨日基础上扩展写操作命令,完善 API 层架构。
---
## 完成事项
### 一、新增写操作命令
**规则管理**
| 命令 | 功能 |
|---|---|
| `ekb agent rule-create` | 新建审核规则(`--purpose` / `--desc` / `--level`) |
**Agent 管理**
| 命令 | 功能 |
|---|---|
| `ekb agent create` | 新建 Agent(支持全部字段,含关联规则 ID) |
| `ekb agent copy <id>` | 复制 Agent,名称自动追加「(副本)」,检测重名 |
| `ekb agent delete <id>` | 删除 Agent,方向键交互确认,不可恢复 |
### 二、API 层重构
- **拆分文件**:`api/agent.py`(Agent 接口)+ `api/rule.py`(Rule 接口)+ `api/schemas.py`(Pydantic 模型)
- **统一 re-export**:所有 commands 只从 `ekb_cli.api` 导入,内部拆分对上层透明
- **引入 Pydantic 校验**:所有接口响应经 `model_validate` 强制校验,字段变更时抛 `ValidationError` 精确定位,而非静默返回空值
- 新增接口:`GET /engine/hab/agent/checkName`、`GET /engine/hab/agent/active`
### 三、交互体验优化
- `ekb agent delete` 默认使用 `questionary` 方向键选择器,默认停在「取消」
- 非 tty 环境(管道/AI调用)自动降级为 `y/N` 文字输入;`--ai` 参数可强制指定;`--yes` 跳过确认
- 修复 `checkName` 接口语义反转 bug(`data=false` 表示名称可用)
### 四、文档补全
- 新增 `api/README.api.md`:三层架构说明、各接口签名、Pydantic 应对策略
- 补全 `README.agent.md`:`state` 枚举含义(0=启用 / 1=禁用 / 2=已删除)及对应接口
- 补全 `README.rule.md`:`rule-create` 命令速查
---
## 新增接口
```
GET /api/engine/hab/agent/checkName?name=xxx # 检查名称唯一性(data=false 表示可用)
GET /api/engine/hab/agent/active?id=xxx&state= # 变更 Agent 状态(0启用/1禁用/2删除)
```
---
## 设计决策
- **"删除"是状态变更**:快报无真正的 DELETE 接口,`state=2` 即为删除,通过 `/active` 接口实现。
- **Pydantic `extra="allow"`**:允许快报新增字段,但已知字段强制类型,兼顾前向兼容与变更感知。
- **`questionary` 仅在 tty 下启用**:`sys.stdin.isatty()` 自动检测,无需用户关心环境差异。
---
## 待办
- [ ] `ekb agent logs` — 需抓包确认 API 结构
- [ ] `ekb agent rule update` — 修改规则内容(API 已封装,命令未实现)
- [ ] `ekb agent rule delete` — 删除规则(接口待确认)
-107
View File
@@ -1,107 +0,0 @@
# 2026-05-18 开发日报
> 截止提交:`298e114`(当前 feature/workflow-control 分支)
> 下一个实例可用 `git log 298e114` 查看全部历史,或 `git checkout 298e114` 还原此状态。
## 今日目标
讨论并确定 ekb-mcp 项目的数据库方案。
---
## 讨论内容
### 一、数据库选型分析
**时间:2026-05-18 18:30**
针对项目是否需要数据库进行了深入讨论:
| 方案 | 优点 | 缺点 | 适用场景 |
|------|------|------|----------|
| PostgreSQL | 功能强大,支持复杂查询和并发 | 需要额外部署,运维复杂 | 多用户并发,复杂查询 |
| SQLite | 轻量级,嵌入式,无需额外服务 | 并发支持有限 | 单机部署,小规模应用 |
| 内存缓存 + JSON 文件 | 简单,无依赖,性能最高 | 重启后缓存丢失 | 单实例,数据量小 |
### 二、项目特点分析
**当前状态:**
- 配置存储在 `enterprises/*.json` 文件中
- 企业配置数量少(几个到几十个)
- 结构简单,只需按 ID 读取
- MCP 服务器单实例运行
**性能问题:**
- `loadCorpConfigs()` 每次调用都读取文件系统
- `getCorpTokens()` 每次调用都读取文件系统
- 没有任何缓存机制
- 大量重复查询会导致频繁的文件 I/O
### 三、中间件方案讨论
**时间:2026-05-18 19:00**
曾考虑实现存储中间件(Repository 模式),支持多种存储后端:
```
src/core/storage/
├── types.ts # 接口定义
├── memory.ts # 内存存储实现
├── sqlite.ts # SQLite 实现
├── postgres.ts # PostgreSQL 实现
└── factory.ts # 工厂函数
```
**反思:**
- 过度设计:对于当前项目来说太复杂
- 维护成本:需要维护多个存储后端的代码
- 依赖管理:需要处理可选依赖
- 学习成本:新开发者需要理解抽象层
### 四、最终决策
**时间:2026-05-18 19:30**
**选择方案:内存缓存 + JSON 文件**
**理由:**
1. **数据量小** - 企业配置通常不多,文件足够
2. **结构简单** - 不需要复杂查询,只需按 ID 读取
3. **运维简单** - 无额外依赖,易于备份和版本控制
4. **单实例运行** - MCP 服务器通常单实例,无需高并发支持
5. **性能足够** - 内存缓存可以解决重复查询的性能问题
**实现方案:**
```typescript
// 简单的内存缓存
const cache = new Map<string, CorpConfig>();
function getConfig(id: string): CorpConfig | undefined {
if (cache.has(id)) return cache.get(id);
const config = loadFromFile(id);
if (config) cache.set(id, config);
return config;
}
```
**清理工作:**
- 移除了 `src/core/storage/` 目录(过度设计的中间件方案)
- 移除了 `scripts/migrate-configs.ts`(不再需要的迁移脚本)
---
## 后续计划
1. 实现内存缓存机制,解决重复查询的性能问题
2. 保持现有 JSON 文件方案,简化架构
3. 如果未来数据量增长,再考虑 SQLite 作为轻量级方案
---
## 技术笔记
- 项目使用 TypeScript + Bun 运行时
- 配置文件位于 `enterprises/*.json`
- Token 缓存位于 `~/.cache/ekb-mcp/tokens.json`
- 当前分支:`feature/workflow-control`
- 最新提交:`298e114` - feat(platform): 新增工作流控制及辅助工具
+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
```
## 工作流数据结构要点
+201
View File
@@ -0,0 +1,201 @@
# hose-use 全局审查修复完成报告
日期:2026-10-20。基线:`fac81b0`(v0.8.15)。
已完成已确认范围内的 20 项修复,每项保留独立本地分支和对应测试,并全部合入 `fix/review-all-integration`。功能整合提交为 `2e5e3c2`;本报告随后独立提交。原工作区 `/Users/yingqing/Code/hose-use` 的 `main` 保持基线且干净。未推送远端、创建 PR、合入 main 或发布版本。
整合工作树:`/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use`。下列链接指向此次实际整合后的文件;可用 `git show <提交>` 或 `git diff fac81b0...<分支>` 分别复查独立修复。
## 逐项实际修改
### 01. 脚本执行隔离
分支:`fix/review-01-script-sandbox`;提交:`2844fd4`。
原来的 node:vm 共享宿主构造器,代码可能间接访问宿主能力。改为独立 QuickJS WASM 上下文,输入经 JSON 复制;构造器、日志回调和内建对象均属于客体运行时。默认执行预算 3 秒、客体堆上限 32 MiB、栈上限 512 KiB,输入/返回值上限各 1 MiB,日志上限 64 KiB/500 条。Promise 返回值明确失败;普通同步代码、输入、日志和错误行号继续支持。
实现:[src/domains/platform/workflow/script/sandbox.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/script/sandbox.ts)。回归:[src/domains/platform/workflow/script/index.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/script/index.test.ts)。验证宿主构造器逃逸、输入与原型隔离、死循环、分配/日志边界、Promise 拒绝及失败后再次执行;打包冒烟额外验证 WASM 随插件和独立二进制可用。
### 02. 审批企业边界
分支:`fix/review-02-approval-corp-boundary`;提交:`221b959`。
原来可在企业 B 的上下文使用企业 A 的审批结果执行同号单据。现在 apply 前校验会话企业、当前配置企业和取得的客户端企业,任何缺失或不一致均拒绝远端审批。
实现:[src/cli/commands/aipro/session.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/aipro/session.ts)。回归:[src/cli/commands/aipro/session-corp.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/aipro/session-corp.test.ts)。跨企业批准、驳回均被阻止;同企业路径仍能提交。
### 03. 审批检查状态校验
分支:`fix/review-03-finding-status-validation`;提交:`a5abfbe`。
原来未知检查状态可能绕过审批门禁。统一状态类型守卫,在批量写入、更新和评估结果应用前校验,网关对历史非法状态按失败处理;批量数据先整体校验再修改,避免留下半批结果。
实现:[src/domains/approval/repository.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/repository.ts)。回归:[src/domains/approval/status-validation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/status-validation.test.ts)。覆盖非法写入/更新、批量写入原子性和历史异常状态的门禁处理;配套修改 service.ts、gateway.ts、types.ts。
### 04. 审批命令预演
分支:`fix/review-04-approval-dry-run`;提交:`ae2a1a9`。
原来的 dry-run 仍可能初始化数据库、改审批状态或进入提交路径。approval 与 aipro 的变更命令现在在构造仓储和客户端之前返回预演;--dry-run 同时遇到 --apply/--yes 时仍优先预演。恢复建议保留正确的 aipro 命令入口。
实现:[src/cli/commands/approval.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/approval.ts)。回归:[src/cli/approval-dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/approval-dry-run.test.ts)。覆盖 11 条命令路径,断言无请求且不创建数据库;同时修改 src/aipro-cli.ts。
### 05. 节点开通确认
分支:`fix/review-05-node-grant-confirmation`;提交:`0e6090a`。
原来管理密码通过后即可开通灰度节点,未使用统一变更确认。现在 grant 在取密码或调用网关之前要求显式确认,并支持 dry-run;密码校验与用户确认分别执行。
实现:[src/cli/commands/workflow/node.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/node.ts)。回归:[src/cli/commands/workflow-nodes-confirmation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow-nodes-confirmation.test.ts)。验证缺少确认被阻止、预演零网关调用、确认后继续;原有开通测试同步传入 --yes。
### 06. 节点索引定位
分支:`fix/review-06-node-index-resolution`;提交:`f46e0e7`。
原来 CLI 字符串索引 3 可能被当作全局遍历序号,命中 2.1 的子节点。字符串现在只按节点名或层级索引定位;SDK 的数字参数保留原有全局遍历语义。
实现:[src/domains/platform/workflow/nodes/locator.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/locator.ts)。回归:[src/domains/platform/workflow/nodes/locator-index.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/locator-index.test.ts)。嵌套工作流中验证定位、编辑和删除均作用于所选节点。
### 07. 路径原型污染与继承选项
分支:`fix/review-07-patch-prototype-guard`;提交:`d2e0d56`。
路径补丁拒绝 __proto__、constructor、prototype 等危险段,只遍历对象自有属性。CLI 参数表改为无原型对象,选项读取和变更确认也只接受自有属性,阻止继承来的 yes/confirmed 等标记授权写操作。
实现:[src/domains/platform/workflow/state/index.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/state/index.ts)。回归:[src/cli/prototype-guard.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/prototype-guard.test.ts)。覆盖危险路径被拒、普通补丁可用,以及继承选项无法确认或改变命令;配套修改 parser.ts、mutation.ts。
### 08. 升级预演
分支:`fix/review-08-update-dry-run`;提交:`32610e0`。
update dry-run 现在在网络查询、安装、源码更新或二进制替换前返回预演;只读 check/changelog 保留原有行为。
实现:[src/cli/commands/update/index.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/update/index.ts)。回归:[src/cli/commands/update/dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/update/dry-run.test.ts)。源码与二进制模式下,均断言无 fetch、子进程和 Skill 安装调用。
### 09. 服务生命周期预演
分支:`fix/review-09-service-dry-run`;提交:`b232e93`。
service start/stop/restart/run 的 dry-run 在分发前返回,不创建或修改 PID、日志和后台进程;status 仍可读取服务状态。
实现:[src/cli/commands/service.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/service.ts)。回归:[src/cli/commands/service-dry-run.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/service-dry-run.test.ts)。覆盖生命周期预演及只读状态查询。
### 10. 认证续期与单次重放
分支:`fix/review-10-client-auth-refresh`;提交:`53689e8`。
原来的脚本引擎和 Unity 客户端闭包继续使用旧票据,401 后也可能重复续期。现在每次取最新缓存,失效后重新换票,Unity 同步清除失效的 eas 持久票据;认证最多重放一次,并在发送前克隆请求以保留 POST 请求体。
实现:[src/core/http/factory.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/core/http/factory.ts)。回归:[src/core/http/token-renewal.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/core/http/token-renewal.test.ts)。覆盖 Piper、EASO、Unity 三类客户端续期成功及持续 401 的最多两次请求;断言 POST 请求体完整。配套修改 script-engine-client.ts、unity-client.ts。
### 11. 审批会话有效期
分支:`fix/review-11-session-expiry`;提交:`813d190`。
短 ID、UUID、单号以及常规审批检查统一执行 TTL 校验,避免换一种句柄绕过过期限制;expires_at=0 正确视为过期。显式重新初始化刷新有效期。历史日志单独允许读取过期记录,并保持企业作用域校验。
实现:[src/domains/approval/repository.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/repository.ts)。回归:[src/domains/approval/session-expiry.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/approval/session-expiry.test.ts)。覆盖三类句柄、常规审批检查、零时间戳、重新初始化和历史读取;配套修改 aipro/status.ts。
### 12. 赋值分隔符解析
分支:`fix/review-12-set-quoted-separators`;提交:`298a02a`。
原来 --set 按逗号直接拆分,name="ACME, Inc.", code=C 会产生错误赋值。现在复用识别引号和转义的解析器;缺少等号、空字段或不匹配引号在写入前报错。
实现:[src/domains/datalink/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/services.ts)。回归:[src/domains/datalink/set-separators.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/set-separators.test.ts)。覆盖引号内逗号、转义引号、多项赋值与非法输入;与第 13 项累计验证。
### 13. 显式字符串类型
分支:`fix/review-13-set-literal-types`;提交:`6451c12`。
原来去掉引号后再做自动转换,使 "001"、"true"、"null" 变成数字、布尔或空值。现在带引号值按字符串解码并保留类型;未加引号的 1、true、null 仍按既有规则转换。
实现:[src/domains/datalink/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/services.ts)。回归:[src/domains/datalink/set-literals.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/datalink/set-literals.test.ts)。覆盖前导零、布尔/空值文本与未加引号值的类型差异。
### 14. 脚本 JSON 输出
分支:`fix/review-14-script-json-output`;提交:`4c4cd42`。
lint/eval 的本地与远端四个 JSON 分支原来遗漏返回输出。现在统一返回 printJson 结果并遵循 runtime.jsonMode、--json/-j 和文件输出选项;失败仍返回非零退出码。
实现:[src/cli/commands/workflow/script.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/script.ts)。回归:[src/cli/commands/workflow/script-json.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/script-json.test.ts)。覆盖本地/远端 lint 与 eval、JSON 可解析、文件输出及失败退出码。
### 15. 工作流快照比较完整性
分支:`fix/review-15-snapshot-config-diff`;提交:`2aea435`。
原来的配置字段白名单漏掉映射、请求头等真实修改。现在比较节点自身配置的全部字段,保留 code/filter 等已有专项比较;用实际树路径记录顺序和父节点变化,不依赖已保存的索引元数据。空 tasks 也可处理。
实现:[src/domains/platform/services.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/services.ts)。回归:[src/domains/platform/snapshot-config-diff.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/snapshot-config-diff.test.ts)。覆盖 mapping、inputs、fields、form、header、params、onError、自定义配置,以及节点移动和无变化快照。
### 16. 节点开通失败退出码
分支:`fix/review-16-node-grant-failure`;提交:`3141cc3`。
网关 success=false 原来仍可能输出成功文案并退出 0。现在 JSON 与人类输出都返回退出码 1;人类输出写入失败原因且不显示成功信息。
实现:[src/cli/commands/workflow/node.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow/node.ts)。回归:[src/cli/commands/workflow-nodes-failure.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/cli/commands/workflow-nodes-failure.test.ts)。覆盖网关业务失败的两种输出模式,并与第 5 项确认流程共同验证。
### 17. 事件全量分页与去重
分支:`fix/review-17-event-pagination`;提交:`b91b5d2`。
原来只扫描首批事件,且超过固定去重容量会反复通知。现在完整读取待办和未读消息的所有分页,再统一提交去重状态;保留本轮活跃事件的全部 ID。分页失败、重复页不前进或超过 10000 页时整轮失败,不提交半轮状态。
实现:[src/domains/events/poller.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/events/poller.ts)。回归:[src/domains/events/pagination.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/events/pagination.test.ts)。覆盖第 51 条事件、2501 条活跃事件重复轮询、停滞与失败分页;store.ts 同步调整 SQLite/JSON 存储容量策略。
### 18. 监听超时与取消状态
分支:`fix/review-18-watch-timeout`;提交:`70d619e`。
原来预算耗尽或取消后仍可能上报 job_completed。现在仅真实终态上报完成,分别返回 timeout/cancelled 事件与状态;单任务、连续监听和最新任务快照均传递标记。CLI 遇到超时/取消返回 1,连续监听向子任务传递剩余预算。
实现:[src/domains/platform/workflow/watch/pipeline-watcher.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/watch/pipeline-watcher.ts)。回归:[src/domains/platform/workflow/watch/timeout.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/watch/timeout.test.ts)。覆盖单任务超时、取消、once 快照及最新任务取消传播;CLI tail-timeout.test.ts 验证退出码。types.ts、single-job.ts、formatter.ts 和 tail.ts 配套更新。
### 19. 公式误报边界
分支:`fix/review-19-formula-diagnostics`;提交:`55c3521`。
原来文本里出现 ROUND/IF 等片段就可能被硬拦截。现在只识别完整公式表达式;明确文本字段不拦截,类型未知仅给建议,明确数字/日期等强类型字段才产生硬阻断。
实现:[src/domains/platform/workflow/analysis/analyzer.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/analysis/analyzer.ts)。回归:[src/domains/platform/workflow/analysis/formula-boundaries.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/analysis/formula-boundaries.test.ts)。覆盖普通句子、文本公式、未知类型软建议和明确强类型硬阻断;旧测试补充日期类型以保留原本意图。
### 20. 唯一触发器删除保护
分支:`fix/review-20-trigger-removal-guard`;提交:`e86c05d`。
原来只有多个顶层节点时才执行触发器保护,单节点工作流可以删除唯一触发器。现在无论节点数量都禁止删除触发器;正常动作节点仍可删除。
实现:[src/domains/platform/workflow/nodes/mutations.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/mutations.ts)。回归:[src/domains/platform/workflow/nodes/trigger-removal.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/src/domains/platform/workflow/nodes/trigger-removal.test.ts)。覆盖单个 webhook、定时和数据联动触发器,以及普通动作节点。
## 验证结果
- 每个修复分支均执行完整 `bun test`(部分使用 `--timeout 60000`)、`bun run check` 和 `bun run build:plugin` 后提交。
- 整合从第 01 项开始,逐项合并其余 19 项;每一步均重新执行完整测试、类型检查和插件构建。最终默认命令 `bun test`:**606 通过、0 失败,87 个测试文件**(基线 547 项,净增 59 项)。
- 最终 `bun run check`、`bun run check:version`、`git diff --check` 通过。
- `bun run build:plugin` 通过;`bun scripts/verify-binary.ts dist/mcp/server.js --plugin` 通过,验证版本、沙箱求和/宿主隔离和 MCP stdio 单工具协议。
- `bun run build:binary` 及 `bun scripts/verify-binary.ts dist/bin/hose-use` 通过;冒烟在临时目录执行,PATH 不含 Bun 或源码,使用本地假凭据且不提交业务请求。
- `bun run build:binary --all` 编译 Darwin arm64/x64、Linux arm64/x64 和 Windows x64 五个目标通过。跨平台编译不等于这些系统上的运行验证。
- 所有 20 个修复分支头及测试维护分支均已确认是整合分支的祖先;生成的 `dist/mcp/server.js` 已按最终源码重新构建并提交。
- 详细最终验证日志:`/tmp/hose-review-final-validation-20261020.log`;逐步整合日志:`/tmp/hose-integration-review-*.log`。日志保存在本机,测试代码与分支提交可重复执行。
## 相对方案的补充与影响
1. 增加测试维护分支 `fix/review-validation-fixture-deadlines`(`48ab35a`)。验证期间原有安装/发布 Shell 测试的固定 5 秒/10 秒子进程截止导致 `status=null`,单独重跑成功。仅将测试子进程上限设为 30 秒、对应测试上限设为 60 秒;断言、重试次数及生产超时均不变。[scripts/release-validation.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/scripts/release-validation.test.ts)、[scripts/install.test.ts](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/scripts/install.test.ts)。第 18 项的后续提交也包含该维护分支,功能修复仍独立于其他 19 项。
2. 认证重放验证要求保留 POST 请求体,因此补充发送前的请求克隆;会话有效期验证补充常规审批入口和显式重置;监听验证补充最新任务的取消传播。这些均是对应问题在不同入口的同范围修复。
3. 沙箱新增两个精确版本依赖 `quickjs-emscripten-core@0.32.0`、`@jitl/quickjs-singlefile-cjs-release-sync@0.32.0` 并更新锁文件。插件产物约从 1.53 MB 增至 2.9 MB。执行仅接受可 JSON 复制的输入和同步返回值;日志/输出、内存和时间限制可能使之前无限制的脚本失败。[package.json](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/package.json)、[bun.lock](/Users/yingqing/.codex/worktrees/review-fix-01-sandbox/hose-use/bun.lock)。
4. 按实际实现更新对应域层、CLI/Core/HTTP 文档,根目录规则和版本号未调整。整合时保留各分支文档补充;生成文件冲突以重新构建解决。未做跨模块重构或数据库结构迁移。
## 未覆盖与重点复查
- 业务网络路径使用模拟客户端验证,未对真实企业进行审批、节点开通或工作流写操作;真实上游服务的票据换取、权限和动态分页变化仍需集成环境验收。
- 二进制运行冒烟仅在当前 macOS 主机执行;Linux、Windows 与其他 CPU 架构本轮仅完成编译。尚未运行远端 CI。
- 安全相关测试证明已覆盖的逃逸/原型路径被阻止,不代表对 QuickJS 或全部 SDK 的形式化安全证明。客体 32 MiB 是运行时堆限制,并非整个宿主进程内存上限。
- 建议审阅重点:QuickJS 兼容性与新增依赖、认证单次重放的票据刷新、审批企业/TTL 门禁、事件全量分页的上游稳定性。20 项确认问题在本轮覆盖范围内均已解决,无已知待修项。
- 此次交付停留在本地提交;后续进入 PR/发布时仍需遵循仓库规定的远端 CI、审查和发布顺序。
## 发布前 CI 补充
首次远端 CI 中,606 项测试、类型检查、版本检查和 Linux 独立二进制冒烟均通过,但插件重建一致性检查失败。完整日志确认唯一差异是 Bun 为 QuickJS CommonJS 模块注入的构建机绝对 `__filename`。
在 `scripts/build-plugin.mjs` 为构建添加 `__filename=import.meta.path` 定义,使嵌入加载器使用运行时插件路径,并重新生成 `dist/mcp/server.js`。在两个独立目录安装锁定依赖并分别构建,SHA-256 完全一致;本机插件与独立二进制冒烟、606 项测试和类型/版本检查再次通过。该补充只修复插件产物的可重现构建,不改变 20 项业务修复的范围。远端最终结果以 PR #124 和发布工作流记录为准。
+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`。
+30 -3
View File
@@ -1,28 +1,55 @@
{
"name": "hose-use",
"version": "0.2.0",
"version": "0.8.17",
"module": "src/server.ts",
"type": "module",
"exports": {
".": "./src/server.ts",
"./sdk": "./src/sdk.ts"
},
"bin": {
"hose-use": "src/cli.ts",
"hose": "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",
"probe": "bun run src/cli.ts probe",
"check": "tsc --noEmit",
"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"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"typescript": "^5.9.3"
}
+78 -10
View File
@@ -1,4 +1,4 @@
import { mkdirSync } 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,32 +17,99 @@ 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 output = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, output);
const outputHose = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, outputHose, "src/cli.ts", buildEnv);
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
const outputAipro = resolve(root, "dist/bin/hose-aipro");
try {
if (existsSync(outputAipro)) unlinkSync(outputAipro);
symlinkSync("hose-use", outputAipro);
console.log(`[build:binary] created multicall symlink: ${outputAipro} -> hose-use`);
} catch {
// 忽略软链接异常
}
}
function buildTarget(name, bunTarget, output) {
function buildTarget(name, bunTarget, output, entry = "src/cli.ts", 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, "src/cli.ts");
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 {
@@ -61,7 +128,8 @@ function buildTarget(name, bunTarget, output) {
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) {
+26
View File
@@ -0,0 +1,26 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
function run(args) {
const result = spawnSync(bun, args, {
cwd: root,
stdio: "inherit",
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${bun} ${args.join(" ")} failed with status ${result.status}`);
}
}
const mcpOutput = resolve(root, "dist/mcp/server.js");
mkdirSync(dirname(mcpOutput), { recursive: true });
// The shared CLI uses bun:sqlite; the plugin manifest must use this runtime too.
// Embedded CommonJS loaders must use the bundle path, not the build host's absolute checkout path.
run(["build", "src/server.ts", "--minify", "--target=bun", "--define", "__filename=import.meta.path", "--outfile", mcpOutput]);
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { execFileSync } from "node:child_process";
export function bumpVersion(ROOT: string, input: string, rebuild = () => {
execFileSync(process.execPath, ["run", "openapi:all"], { cwd: ROOT, stdio: "inherit" });
execFileSync(process.execPath, ["run", "build:plugin"], { cwd: ROOT, stdio: "inherit" });
execFileSync(process.execPath, ["run", "check:version"], { cwd: ROOT, stdio: "inherit" });
}): string {
const pkgPath = join(ROOT, "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
const currentVersion: string = pkg.version;
if (!input) {
console.error("Usage: bun run bump <version | patch | minor | major>");
console.error(`Current version: ${currentVersion}`);
throw new Error("A release version is required");
}
let nextVersion = input.replace(/^v/, "");
if (input === "patch" || input === "minor" || input === "major") {
const [major, minor, patch] = currentVersion.split("-")[0].split(".").map(Number);
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
if (input === "major") nextVersion = `${major + 1}.0.0`;
}
if (!isReleaseVersion(nextVersion)) throw new Error(`Invalid SemVer format: '${nextVersion}'`);
if (Bun.semver.order(nextVersion, currentVersion) <= 0) throw new Error(`Version must increase: ${currentVersion} -> ${nextVersion}`);
const git = (args: string[]) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
if (git(["status", "--porcelain"])) throw new Error("Release preparation requires a clean working tree");
const branch = git(["branch", "--show-current"]);
if (!["codex/release-v", "release/v"].some(prefix => branch === `${prefix}${nextVersion}`)) {
throw new Error(`Prepare the release on codex/release-v${nextVersion} or release/v${nextVersion}; current branch: ${branch || "detached HEAD"}`);
}
if (git(["tag", "--list", `v${nextVersion}`])) throw new Error(`Tag v${nextVersion} already exists`);
// Read all versioned sources before writing any of them.
for (const file of ["README.md", "skills/hose-use/SKILL.md"]) readFileSync(join(ROOT, file), "utf8");
for (const file of ["specs/openapi/openapi.yaml", ".zcode-plugin/plugin.json"]) {
if (existsSync(join(ROOT, file))) {
const content = readFileSync(join(ROOT, file), "utf8");
if (file.endsWith(".json")) JSON.parse(content);
}
}
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
// 1. package.json
pkg.version = nextVersion;
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
console.log("✓ Updated package.json");
// 2. README.md
const readmePath = join(ROOT, "README.md");
let readmeContent = readFileSync(readmePath, "utf-8");
readmeContent = readmeContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
writeFileSync(readmePath, readmeContent);
console.log("✓ Updated README.md");
// 3. skills/hose-use/SKILL.md
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
let skillContent = readFileSync(skillPath, "utf-8");
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/hose-use/SKILL.md");
// 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+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated specs/openapi/openapi.yaml");
}
// 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"));
pluginJson.version = nextVersion;
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
console.log("✓ Updated .zcode-plugin/plugin.json");
}
// 5. Sync to global ~/.agents/skills/hose-use/ is now an explicit dev:override step.
// A version bump must not overwrite personal Skill files in the user's environment.
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
console.log("==> Rebuilding OpenAPI and plugin bundles...");
rebuild();
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log(` 1. Review the diff, then run bun test && bun run check && bun run check:version`);
console.log(` 2. Commit on ${branch}, push that branch and open a PR to main`);
console.log(` 3. Wait for CI and review, then merge the PR`);
console.log(` 4. Switch to main; git pull --ff-only origin main; git push home main`);
console.log(` 5. Create annotated tag v${nextVersion} on the merged release commit`);
console.log(` 6. git push home refs/tags/v${nextVersion} (first), then git push origin refs/tags/v${nextVersion}`);
console.log(` 7. Verify the Release build, binary archives and checksums on both sources`);
console.log(` Optional: bun run dev:override to explicitly sync your global development binary and Skill`);
return nextVersion;
}
export function isReleaseVersion(value: string): boolean {
const match = value.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*))?$/);
return !!match && (!match[4] || match[4].split(".").every(part => !/^0\d+$/.test(part)));
}
if (import.meta.main) {
try {
bumpVersion(join(import.meta.dirname, ".."), process.argv[2]?.trim() || "");
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
}
}
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bun
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import YAML from "yaml";
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
const inputFile = resolve("specs/openapi/openapi.yaml");
const outputFile = resolve("specs/openapi.json");
const bundled = bundle(inputFile, new Set());
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(bundled, null, 2)}\n`);
console.log(`✓ Bundled wrapped OpenAPI: ${outputFile}`);
function bundle(filePath: string, seen: Set<string>): Json {
const absolutePath = resolve(filePath);
if (seen.has(absolutePath)) {
throw new Error(`Circular OpenAPI reference: ${absolutePath}`);
}
const parsed = YAML.parse(readFileSync(absolutePath, "utf8")) as Json;
return resolveReferences(parsed, absolutePath, new Set([...seen, absolutePath]));
}
function resolveReferences(value: Json, currentFile: string, seen: Set<string>): Json {
if (Array.isArray(value)) {
return value.map((item) => resolveReferences(item, currentFile, seen));
}
if (!isObject(value)) return value;
if (typeof value.$ref === "string" && isFileReference(value.$ref)) {
const [refPath, pointer = ""] = value.$ref.split("#");
const refFile = refPath ? resolve(dirname(currentFile), refPath) : currentFile;
const target = pointer ? resolvePointer(bundle(refFile, seen), pointer) : bundle(refFile, seen);
return resolveReferences(target, refFile, seen);
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
resolveReferences(item as Json, currentFile, seen),
])
);
}
function isFileReference(ref: string) {
return !ref.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(ref);
}
function resolvePointer(document: Json, pointer: string): Json {
const path = pointer.replace(/^#/, "");
if (!path) return document;
return path
.split("/")
.filter(Boolean)
.map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"))
.reduce((target: Json, key) => {
if (!isObject(target) && !Array.isArray(target)) {
throw new Error(`Invalid JSON pointer segment "${key}" in ${pointer}`);
}
const next = (target as Record<string, Json>)[key];
if (next === undefined) {
throw new Error(`Missing JSON pointer segment "${key}" in ${pointer}`);
}
return next;
}, document);
}
function isObject(value: Json): value is { [key: string]: Json } {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+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;
}
+48
View File
@@ -0,0 +1,48 @@
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: [],
};
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);
});
});
+503
View File
@@ -0,0 +1,503 @@
#!/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;
}>;
}
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 collectSnapshot(): HygieneSnapshot {
return {
repository: parseRepository(),
worktrees: parseWorktrees(),
branches: parseBranches(),
unreachableCommits: parseUnreachableCommits(),
skill: parseSkill(),
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
};
}
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 同步全局开发版" });
}
}
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 {
+768
View File
@@ -0,0 +1,768 @@
#!/usr/bin/env bun
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const outputFile = resolve("specs/openapi.raw.json");
function standardResponse(description: string, dataSchema: any) {
return {
"200": {
description,
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: dataSchema,
code: { type: "string", example: "SUCCESS" },
message: { type: "string", example: "成功" },
},
},
},
},
},
"401": {
description: "未授权或 Token 已失效",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
"400": {
description: "请求参数错误或鉴权异常",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
};
}
const spec = {
openapi: "3.1.0",
info: {
title: "Hose / Ekuaibao Downstream Native API",
version: "1.0.0",
description: "Raw downstream Ekuaibao (合思/易快报), EASO, and Piper business API contracts.",
},
servers: [
{
url: "https://app.ekuaibao.com",
description: "合思/易快报主站与统一认证中心",
},
{
url: "https://easo.ekuaibao.com",
description: "合思 EASO 开放平台网关",
},
{
url: "https://piper.ekuaibao.com",
description: "合思 Piper 工作流与集成网关",
},
],
tags: [
{ name: "SSO & Security", description: "统一认证中心、RSA 公钥密码加密与多企业身份切换" },
{ name: "EASO & Piper Auth", description: "开放平台 OAuth2 免登握手、换票与 Token 自动刷新" },
{ name: "Platforms & Apps", description: "自建应用列表与集成检索" },
{ name: "Workflows & Pipelines", description: "跨应用工作流聚合、运行日志、节点详情与启停" },
{ name: "Bills & Invoices", description: "费控单据、报销单、借款单、发票与 DataLink 实体字典" },
{ name: "Jobs & Execution", description: "工作流任务运行实例与调试" },
{ name: "Staffs & Webhooks", description: "企业通讯录人员与 Webhook 触发配置" },
],
paths: {
"/api/v2/invoice/search": {
post: {
tags: ["Bills & Invoices"],
summary: "检索企业费用单据与发票池",
description: "检索企业名下的费用单据、报销借款单、发票与审批流记录,支持分页与阶段过滤。",
operationId: "rawSearchInvoices",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 50 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "单据列表响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
count: { type: "integer" },
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/invoice": {
post: {
tags: ["Bills & Invoices"],
summary: "批量按 ID 精确获取单据详情",
description: "根据单据物理 ID 列表批量拉取完整的表单数据与状态。",
operationId: "rawGetInvoicesByIds",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["ids"],
properties: {
ids: { type: "array", items: { type: "string" } },
},
},
},
},
},
responses: {
"200": {
description: "单据详情列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/datalink/entity/search": {
post: {
tags: ["Bills & Invoices"],
summary: "查询 DataLink 实体定义与字段字典",
description: "获取企业全部单据实体模型、字段 Label 中文映射与类型定义。",
operationId: "rawSearchEntities",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 100 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "实体定义字典",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/common/security/getPublicKey": {
post: {
tags: ["SSO & Security"],
summary: "获取统一认证中心 RSA 公钥",
description: "获取用于登录密码加密的 RSA Public Key 模数与指数 (PKCS#1)。",
operationId: "getPublicKey",
responses: {
"200": {
description: "RSA 公钥响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
publicKey: { type: "string", description: "RSA 公钥字符串" },
modulus: { type: "string", description: "RSA Modulus" },
exponent: { type: "string", description: "RSA Exponent" },
},
},
},
},
},
},
},
},
},
},
"/api/common/login/verifyPhone": {
post: {
tags: ["SSO & Security"],
summary: "手机号与加密密码纯 API 登录",
description: "使用 RSA 加密后的密码和手机号发起统一认证,换取全企业 AccessToken 与 Session Cookie。",
operationId: "loginVerifyPhone",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["phone", "password"],
properties: {
phone: { type: "string", description: "手机号" },
password: { type: "string", description: "RSA 加密后的密码密文" },
countryCode: { type: "string", default: "+86" },
},
},
},
},
},
responses: {
"200": {
description: "登录成功并下发凭证",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
accessToken: { type: "string", description: "全局访问令牌" },
user: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
phone: { type: "string" },
},
},
},
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations": {
get: {
tags: ["SSO & Security"],
summary: "获取账号名下可访问企业列表",
description: "拉取当前已登录账号授权的所有企业租户及其 Staff 身份。",
operationId: "listCorporations",
responses: {
"200": {
description: "企业与身份列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/CorporationItem" },
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations/{corpId}/switch": {
post: {
tags: ["SSO & Security"],
summary: "切换工作企业上下文",
description: "切换当前会话至指定企业租户,并签发该企业的专属 Session。",
operationId: "switchCorporation",
parameters: [
{ name: "corpId", in: "path", required: true, schema: { type: "string" }, description: "目标企业 ID" },
],
responses: {
"200": {
description: "切换结果",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
activeCorpId: { type: "string" },
staffId: { type: "string" },
},
},
},
},
},
},
},
},
},
},
"/api/open/oauth2/auth": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 1: 获取授权码",
description: "使用主站会话 Cookie 和 appKey 获取临时 code。",
operationId: "easoGetAuthCode",
responses: {
"200": {
description: "临时授权码",
content: {
"application/json": {
schema: {
type: "object",
properties: {
code: { type: "string", description: "临时授权码" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 2: 换取 AccessToken",
description: "使用授权码 code 换取平台接口访问 Token 与 RefreshToken。",
operationId: "easoGetToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["code", "appKey", "appSecret"],
properties: {
code: { type: "string" },
appKey: { type: "string" },
appSecret: { type: "string" },
grant_type: { type: "string", default: "authorization_code" },
},
},
},
},
},
responses: {
"200": {
description: "平台 Token 响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/user_info": {
get: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 3: 获取当前开放平台用户信息",
description: "使用 AccessToken 获取当前用户的 openId 与企业绑定身份。",
operationId: "easoGetUserInfo",
responses: {
"200": {
description: "用户信息",
content: {
"application/json": {
schema: {
type: "object",
properties: {
openId: { type: "string" },
corpId: { type: "string" },
name: { type: "string" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token/refresh": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 令牌无感刷新",
description: "使用 refresh_token 换取新的 30 天 accessToken。",
operationId: "easoRefreshToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["refresh_token"],
properties: {
refresh_token: { type: "string" },
grant_type: { type: "string", default: "refresh_token" },
},
},
},
},
},
responses: {
"200": {
description: "新 Token",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/v2/datalink/platform/search": {
get: {
tags: ["Platforms & Apps"],
summary: "获取企业自建应用列表",
description: "查询指定企业下已启用的自建应用与平台实例列表。",
operationId: "searchPlatforms",
parameters: [
{ name: "corpId", in: "query", required: true, schema: { type: "string" }, description: "企业 ID" },
{ name: "scope", in: "query", schema: { type: "string", default: "enable" } },
],
responses: {
"200": {
description: "应用列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/PlatformItem" },
},
},
},
},
},
},
},
},
},
"/api/easo/pipelines/logs": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取应用下的工作流列表与日志",
description: "按自建应用 ID 分页查询名下的工作流及最近执行日志。",
operationId: "listWorkflowsByPlatform",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
{ name: "number", in: "query", schema: { type: "integer", default: 1 } },
{ name: "pageSize", in: "query", schema: { type: "integer", default: 20 } },
],
responses: standardResponse("工作流分页列表", { $ref: "#/components/schemas/WorkflowPageData" }),
},
},
"/api/easo/stats": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流运行统计",
description: "统计指定应用下工作流的成功、失败及总触发次数。",
operationId: "getWorkflowStats",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流运行统计", { $ref: "#/components/schemas/WorkflowStatsData" }),
},
},
"/api/easo/charge": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流配额与计费信息",
description: "查询当前企业工作流运行调用次数与配额剩余。",
operationId: "getWorkflowCharge",
responses: standardResponse("配额信息", { $ref: "#/components/schemas/WorkflowChargeData" }),
},
},
"/api/easo/pipelines/{pipelineId}": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流详情与 DSL 节点图",
description: "查询指定工作流的完整配置、触发器与节点链路图谱(code-js2, loop, sql 等)。",
operationId: "getWorkflowDetail",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流完整详情", { $ref: "#/components/schemas/WorkflowDetailData" }),
},
},
"/api/easo/pipelines/state/{pipelineId}": {
put: {
tags: ["Workflows & Pipelines"],
summary: "启用或停用工作流",
description: "切换工作流运行状态(1: 启用, 0: 停用)。",
operationId: "toggleWorkflowState",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
{ name: "state", in: "query", required: true, schema: { type: "integer", enum: [0, 1] } },
],
responses: {
"200": {
description: "状态更新成功",
},
},
},
},
"/api/easo/jobs/running": {
get: {
tags: ["Jobs & Execution"],
summary: "获取运行中的任务实例",
description: "查询工作流正在执行的调试(DEBUG)或生产(PROD)任务列表。",
operationId: "listRunningJobs",
parameters: [
{ name: "pipelineId", in: "query", required: true, schema: { type: "string" } },
{ name: "runType", in: "query", schema: { type: "string", enum: ["DEBUG", "PROD"], default: "DEBUG" } },
],
responses: standardResponse("任务实例列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowJobItem" },
}),
},
},
"/api/easo/dsl/all": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取企业全部 DSL 规则配置",
description: "查询企业下所有生效的 DSL 脚本规则。",
operationId: "listAllDsl",
responses: standardResponse("DSL 规则列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowDslItem" },
}),
},
},
"/api/easo/common/staffs": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取企业员工通讯录列表",
description: "查询企业内部或外部员工名单,用于工作流执行人与节点通知映射。",
operationId: "listCommonStaffs",
parameters: [
{ name: "external", in: "query", schema: { type: "boolean", default: false } },
],
responses: standardResponse("员工列表", {
type: "array",
items: { $ref: "#/components/schemas/StaffItem" },
}),
},
},
"/api/webhook/{pipelineId}": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取工作流 Webhook 触发配置",
description: "查询指定工作流的 Webhook URL 入口与密钥配置。",
operationId: "getWebhookInfo",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("Webhook 配置", { $ref: "#/components/schemas/WebhookInfoData" }),
},
},
"/api/easo/pipelines/{pipelineId}/sampleData": {
post: {
tags: ["Workflows & Pipelines"],
summary: "提取工作流调试/采样数据",
description: "触发工作流节点采样数据提取,用于脚本调试与输入校验。",
operationId: "sampleWorkflowData",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: {
"200": {
description: "采样数据",
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: { type: "object" },
type: { type: "string" },
},
},
},
},
},
},
},
},
},
components: {
schemas: {
ErrorResponse: {
type: "object",
properties: {
code: { type: "string" },
message: { type: "string" },
details: { type: "object" },
},
},
CorporationItem: {
type: "object",
properties: {
id: { type: "string", description: "企业 ID" },
name: { type: "string", description: "企业名称" },
staffId: { type: "string", description: "员工 ID" },
role: { type: "string", description: "角色权限" },
},
},
PlatformItem: {
type: "object",
properties: {
id: { type: "string", description: "自建应用 ID" },
name: { type: "string", description: "应用名称" },
code: { type: "string", description: "应用标识 Code" },
icon: { type: "string" },
status: { type: "string" },
},
},
WorkflowPageData: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/WorkflowItem" },
},
total: { type: "integer" },
number: { type: "integer" },
pageSize: { type: "integer" },
},
},
WorkflowItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
description: { type: "string" },
state: { type: "integer", description: "1: 启用, 0: 停用" },
platformId: { type: "string" },
updatedAt: { type: "string" },
},
},
WorkflowStatsData: {
type: "object",
properties: {
totalCount: { type: "integer" },
successCount: { type: "integer" },
failCount: { type: "integer" },
},
},
WorkflowChargeData: {
type: "object",
properties: {
used: { type: "integer" },
total: { type: "integer" },
remaining: { type: "integer" },
},
},
WorkflowDetailData: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
state: { type: "integer" },
nodes: { type: "array", items: { type: "object" }, description: "节点列表 (含 code-js2, loop, sql 等)" },
links: { type: "array", items: { type: "object" }, description: "节点连线" },
},
},
WorkflowJobItem: {
type: "object",
properties: {
jobId: { type: "string" },
pipelineId: { type: "string" },
status: { type: "string" },
startTime: { type: "string" },
},
},
WorkflowDslItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
content: { type: "string" },
},
},
StaffItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string" },
cellphone: { type: "string" },
},
},
WebhookInfoData: {
type: "object",
properties: {
webhookUrl: { type: "string" },
token: { type: "string" },
},
},
},
},
};
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(spec, null, 2)}\n`);
console.log(`✓ Generated raw downstream OpenAPI: ${outputFile}`);
+130 -32
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -e
set -euo pipefail
REPO="yunyingk/hose-serve-tool"
REPO="yunyingk/hose-use"
echo "==> Detecting platform and architecture..."
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
@@ -34,9 +34,10 @@ case "$ARCH" in
esac
# Resolve best writable bin directory without requiring sudo
TARGET_DIR=""
TARGET_DIR="${HOSE_USE_INSTALL_DIR:-}"
if [ -n "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR"; fi
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
if [ -z "$TARGET_DIR" ] && [ -d "$candidate" ] && [ -w "$candidate" ]; then
TARGET_DIR="$candidate"
break
fi
@@ -49,6 +50,10 @@ fi
ASSET_NAME="hose-use-${PLATFORM}-${ARCH_NAME}"
TARGET_PATH="${TARGET_DIR}/hose-use"
if [ -d "$TARGET_PATH" ] || { [ -d "${TARGET_DIR}/hose-aipro" ] && [ ! -L "${TARGET_DIR}/hose-aipro" ]; }; then
echo "Error: an install target is a directory; refusing to replace it." >&2
exit 1
fi
get_file_size() {
local file="$1"
@@ -102,7 +107,7 @@ download_candidate() {
if curl -fL --progress-bar "$url" -o "$dest"; then
local size_bytes
size_bytes="$(get_file_size "$dest")"
if [ "$size_bytes" -gt 1000000 ]; then
if [ "$size_bytes" -gt 0 ]; then
echo "✓ Download complete! Total size: $(format_bytes "$size_bytes")"
echo "✓ Successfully fetched from host: ${host}"
return 0
@@ -114,48 +119,139 @@ download_candidate() {
}
echo "==> Target install location: ${TARGET_PATH}"
TMP_FILE="$(mktemp)"
TMP_DIR="$(mktemp -d)"
TMP_FILE="${TMP_DIR}/download"
CHECKSUM_FILE="${TMP_DIR}/checksums.txt"
INSTALL_STAGE=""
trap 'rm -rf "$TMP_DIR"; if [ -n "$INSTALL_STAGE" ]; then rm -f "$INSTALL_STAGE"; fi' EXIT
DOWNLOAD_SUCCESS=false
DOWNLOADED_FORMAT="archive"
# Candidate mirrors
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}"
# 1. Try direct GitHub Releases
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
DOWNLOAD_SUCCESS=true
if ! command -v curl >/dev/null 2>&1; then
echo "Error: curl is required." >&2
exit 1
fi
# 2. Try Fast CDN Proxy Fallback
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
DOWNLOAD_SUCCESS=true
fi
fi
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
echo "Error: Failed to download ${ASSET_NAME} from all candidate mirrors." >&2
rm -f "$TMP_FILE"
if command -v sha256sum >/dev/null 2>&1; then
hash_file() { sha256sum "$1" | awk '{ print tolower($1) }'; }
elif command -v shasum >/dev/null 2>&1; then
hash_file() { shasum -a 256 "$1" | awk '{ print tolower($1) }'; }
else
echo "Error: SHA-256 verification requires sha256sum or shasum." >&2
exit 1
fi
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
MIRROR="${HOSE_USE_MIRROR:-auto}"
case "$MIRROR" in auto|github|gitea) ;; *) echo "Invalid HOSE_USE_MIRROR: $MIRROR" >&2; exit 1 ;; esac
# Also create 'hose' symlink if possible
if [ -w "$TARGET_DIR" ]; then
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose" 2>/dev/null || true
# Resolve latest Gitea tag if available. Resolve once, then pin every mirror and
# checksum request to that exact version instead of guessing an old release.
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
GITHUB_API_URL="https://api.github.com/repos/${REPO}/releases/latest"
LATEST_TAG="${HOSE_USE_VERSION:-}"
if [ -n "$LATEST_TAG" ]; then
LATEST_TAG="v${LATEST_TAG#v}"
else
api_urls=()
if [ "$MIRROR" != "github" ]; then api_urls+=("$GITEA_API_URL"); fi
if [ "$MIRROR" != "gitea" ]; then api_urls+=("$GITHUB_API_URL"); fi
for api_url in "${api_urls[@]}"; do
if release_json=$(curl -fsSL --connect-timeout 4 --max-time 15 "$api_url"); then
LATEST_TAG=$(printf '%s' "$release_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^" ]*\)".*/\1/p' | head -n 1)
if [ -n "$LATEST_TAG" ]; then break; fi
fi
done
fi
if ! [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then
echo "Error: could not resolve a release version; set HOSE_USE_VERSION explicitly." >&2
exit 1
fi
release_bases=()
if [ "$MIRROR" != "github" ]; then release_bases+=("https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}"); fi
if [ "$MIRROR" != "gitea" ]; then
release_bases+=("https://github.com/${REPO}/releases/download/${LATEST_TAG}")
release_bases+=("https://ghfast.top/https://github.com/${REPO}/releases/download/${LATEST_TAG}")
fi
verified_download() {
local base="$1" asset="$2" expected actual
if ! download_candidate "${base}/checksums.txt" "$CHECKSUM_FILE" "Release checksums"; then
echo " ↳ Missing checksums.txt for ${LATEST_TAG}; refusing an unverified install." >&2
return 1
fi
expected=$(awk -v name="$asset" '{ sub(/\r$/, "") } $2 == name || $2 == "*" name { count++; if (length($1) == 64 && $1 ~ /^[0-9a-fA-F]+$/) value=tolower($1); else invalid=1 } END { if (count == 1 && !invalid) print value; else exit 1 }' "$CHECKSUM_FILE") || {
echo " ↳ Missing or ambiguous checksum for ${asset}." >&2
return 1
}
if ! download_candidate "${base}/${asset}" "$TMP_FILE" "Release ${LATEST_TAG}"; then return 1; fi
actual=$(hash_file "$TMP_FILE")
if [ "$actual" != "$expected" ]; then
echo " ↳ SHA-256 mismatch for ${asset}; refusing this download." >&2
return 1
fi
echo "✓ SHA-256 verified: ${asset}"
}
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
# 2. Second priority: Raw Executable (Fallback), with the same checksum requirement.
for format in archive raw; do
asset="$ASSET_NAME"
if [ "$format" = "archive" ]; then asset="${asset}.tar.gz"; fi
for base in "${release_bases[@]}"; do
if verified_download "$base" "$asset"; then
DOWNLOAD_SUCCESS=true
DOWNLOADED_FORMAT="$format"
break
fi
done
if [ "$DOWNLOAD_SUCCESS" = "true" ]; then break; fi
done
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
echo "Error: Failed to obtain a verified ${ASSET_NAME} for ${LATEST_TAG} from all candidate mirrors." >&2
exit 1
fi
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
echo "==> Extracting selected binary in temporary staging..."
member=""
listing=$(tar -tzf "$TMP_FILE")
for candidate in "$ASSET_NAME" "./$ASSET_NAME" hose-use ./hose-use; do
if printf '%s\n' "$listing" | awk -v name="$candidate" '$0 == name { count++ } END { exit count != 1 }'; then
member="$candidate"
break
fi
done
if [ -z "$member" ]; then echo "Error: release archive has no expected platform binary." >&2; exit 1; fi
# Stream only the exact member; archive paths and aliases never get written to bin.
tar -xOzf "$TMP_FILE" "$member" > "${TMP_DIR}/hose-use"
if [ ! -s "${TMP_DIR}/hose-use" ]; then echo "Error: release binary is empty." >&2; exit 1; fi
else
mv "$TMP_FILE" "${TMP_DIR}/hose-use"
fi
# Stage on the target filesystem so the final rename is atomic.
INSTALL_STAGE=$(mktemp "${TARGET_DIR}/.hose-use-install.XXXXXX")
cp "${TMP_DIR}/hose-use" "$INSTALL_STAGE"
chmod 755 "$INSTALL_STAGE"
# 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
codesign --force --sign - "$INSTALL_STAGE" 2>/dev/null || true
fi
mv -f "$INSTALL_STAGE" "$TARGET_PATH"
INSTALL_STAGE=""
# Create hose-aipro multicall alias pointing at the single binary.
ln -sfn hose-use "${TARGET_DIR}/hose-aipro"
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
if "$TARGET_PATH" skill install --yes; then
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
else
echo "Error: binary installed to ${TARGET_PATH}, but Agent Skill installation failed. Retry: hose-use skill install --yes" >&2
exit 1
fi
echo ""
echo "✨ hose-use successfully installed to ${TARGET_PATH}!"
@@ -166,4 +262,6 @@ echo " 1. Login: hose-use auth login --phone=177... --password=..."
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 ""
+138
View File
@@ -0,0 +1,138 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createHash } from "node:crypto";
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readlinkSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";
// Shell fixtures start several processes; allow headroom on a busy host.
const fixtures: string[] = [];
afterEach(() => { for (const root of fixtures.splice(0)) rmSync(root, { recursive: true, force: true }); });
const hash = (data: Buffer | string) => createHash("sha256").update(data).digest("hex");
function fixture(options: { badHash?: boolean; missingEntry?: boolean; duplicate?: boolean; rawOnly?: boolean } = {}) {
const root = mkdtempSync(join(tmpdir(), "hose-installer-test-"));
fixtures.push(root);
const tools = join(root, "tools"), source = join(root, "release"), target = join(root, "bin");
for (const dir of [tools, source, target]) mkdirSync(dir);
const binary = `#!/bin/sh
if [ "$1" = "skill" ]; then
printf '%s\\n' "$*" > "$HOSE_FIXTURE_LOG"
[ "$2" = "install" ] && [ "$3" = "--yes" ] || exit 10
[ "\${HOSE_FIXTURE_SKILL_FAIL:-0}" != "1" ] || exit 3
else
printf 'hose-use v9.9.9\\n'
fi
`;
const asset = "hose-use-linux-x64";
writeFileSync(join(source, asset), binary, { mode: 0o755 });
symlinkSync(asset, join(source, "hose-aipro"));
writeFileSync(join(source, "unrelated.txt"), "must not reach the install directory");
const archive = `${asset}.tar.gz`;
expect(spawnSync("tar", ["-czf", join(source, archive), "-C", source, asset, "hose-aipro", "unrelated.txt"]).status).toBe(0);
const entry = `${options.badHash ? "0".repeat(64) : hash(readFileSync(join(source, archive)))} ${archive}\n`;
writeFileSync(join(source, "checksums.txt"), (options.missingEntry ? "" : entry + (options.duplicate ? entry : "")) + `${options.badHash ? "0".repeat(64) : hash(binary)} ${asset}\n`);
if (options.rawOnly) rmSync(join(source, archive));
const curl = `#!/bin/bash
set -eu
url=""; dest=""; head_only=false
while [ "$#" -gt 0 ]; do
case "$1" in
-o) dest="$2"; shift 2 ;;
--connect-timeout|--max-time) shift 2 ;;
-fIs) head_only=true; shift ;;
https://*) url="$1"; shift ;;
*) shift ;;
esac
done
printf '%s\\n' "$url" >> "$HOSE_FIXTURE_REQUESTS"
if [ "\${HOSE_FIXTURE_GITEA_FAIL:-0}" = "1" ] && [[ "$url" == *git.ying-qing.cn* ]]; then exit 22; fi
if [[ "$url" == */releases/latest ]]; then
[ "\${HOSE_FIXTURE_NO_TAG:-0}" != "1" ] || exit 22
printf '{"tag_name": "v9.9.9"}'
exit 0
fi
name="\${url##*/}"
if [ "$name" = "checksums.txt" ] && [ "\${HOSE_FIXTURE_NO_MANIFEST:-0}" = "1" ]; then exit 22; fi
file="$HOSE_FIXTURE_SOURCE/$name"
[ -f "$file" ] || exit 22
if [ "$head_only" = "true" ]; then exit 0; fi
if [ -n "$dest" ]; then cp "$file" "$dest"; else cat "$file"; fi
`;
writeFileSync(join(tools, "curl"), curl, { mode: 0o755 });
writeFileSync(join(tools, "uname"), '#!/bin/sh\nif [ "$1" = "-s" ]; then echo Linux; else echo x86_64; fi\n', { mode: 0o755 });
const run = (env: Record<string, string> = {}) => spawnSync("bash", [resolve(import.meta.dir, "install.sh")], {
cwd: root,
env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, HOSE_USE_INSTALL_DIR: target, HOSE_USE_VERSION: "9.9.9", HOSE_USE_MIRROR: "auto", HOSE_FIXTURE_SOURCE: source, HOSE_FIXTURE_LOG: join(root, "skill.log"), HOSE_FIXTURE_REQUESTS: join(root, "requests.log"), ...env },
encoding: "utf8", timeout: 30_000,
});
return { root, source, target, run, binary };
}
describe("verified standalone installer", () => {
test("installs a platform-named archive and alias, then explicitly confirms Skill setup", () => {
const f = fixture();
const result = f.run();
expect(result.status).toBe(0);
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
expect(readFileSync(join(f.root, "skill.log"), "utf8").trim()).toBe("skill install --yes");
expect(readdirSync(f.target).sort()).toEqual(["hose-aipro", "hose-use"]);
}, 60_000);
for (const options of [{ badHash: true }, { missingEntry: true }, { duplicate: true }]) {
test(`rejects an invalid manifest/archive and preserves the old binary: ${JSON.stringify(options)}`, () => {
const f = fixture(options);
// Remove raw fallback, so a missing archive entry cannot be hidden by another valid asset.
rmSync(join(f.source, "hose-use-linux-x64"));
writeFileSync(join(f.target, "hose-use"), "old binary");
const result = f.run();
expect(result.status).toBe(1);
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
expect(existsSync(join(f.root, "skill.log"))).toBe(false);
}, 60_000);
}
test("does not silently bypass missing checksums or guess an old tag", () => {
const f = fixture();
expect(f.run({ HOSE_FIXTURE_NO_MANIFEST: "1" }).status).toBe(1);
const unknown = f.run({ HOSE_USE_VERSION: "", HOSE_FIXTURE_NO_TAG: "1" });
expect(unknown.status).toBe(1);
expect(unknown.stderr).toContain("could not resolve");
expect(existsSync(join(f.target, "hose-use"))).toBe(false);
expect(readFileSync(join(f.root, "requests.log"), "utf8")).not.toContain("v0.8.9");
}, 60_000);
test("uses a verified raw fallback and a fixed tag when the first mirror fails", () => {
const f = fixture({ rawOnly: true });
const result = f.run({ HOSE_FIXTURE_GITEA_FAIL: "1", HOSE_USE_VERSION: "" });
expect(result.status).toBe(0);
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
const requests = readFileSync(join(f.root, "requests.log"), "utf8");
expect(requests).toContain("/download/v9.9.9/");
expect(requests).not.toContain("/latest/download/");
}, 60_000);
test("reports Skill failure without claiming it was installed", () => {
const f = fixture();
const result = f.run({ HOSE_FIXTURE_SKILL_FAIL: "1" });
expect(result.status).toBe(1);
expect(result.stderr).toContain("binary installed");
expect(result.stdout).not.toContain("Agent skill installed");
expect(result.stdout).not.toContain("successfully installed");
}, 60_000);
test("does not replace directories or follow an existing alias into a directory", () => {
const f = fixture();
mkdirSync(join(f.root, "personal"));
symlinkSync(join(f.root, "personal"), join(f.target, "hose-aipro"));
expect(f.run().status).toBe(0);
expect(readdirSync(join(f.root, "personal"))).toEqual([]);
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
rmSync(join(f.target, "hose-aipro"));
mkdirSync(join(f.target, "hose-aipro"));
writeFileSync(join(f.target, "hose-use"), "old binary");
expect(f.run().status).toBe(1);
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe("old binary");
}, 60_000);
});
+201
View File
@@ -0,0 +1,201 @@
import { afterEach, describe, expect, test } from "bun:test";
import { execFileSync, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse } from "yaml";
import { bumpVersion } from "./bump-version.js";
import { verifyReleaseTag } from "./verify-release.js";
// Shell fixtures start several processes; allow headroom on a busy host.
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
function repository() {
const root = mkdtempSync(join(tmpdir(), "hose-release-test-"));
roots.push(root);
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
git("init", "--initial-branch=main");
git("config", "user.name", "Release fixture");
git("config", "user.email", "fixture@example.test");
git("config", "core.hooksPath", "/dev/null");
git("config", "commit.gpgsign", "false");
git("config", "tag.gpgsign", "false");
for (const dir of ["skills/hose-use", "specs/openapi", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true });
writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n');
writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n");
writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n");
writeFileSync(join(root, "specs/openapi/openapi.yaml"), "info:\n version: 1.0.0\n");
writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n');
git("add", ".");
git("commit", "-m", "fixture");
git("update-ref", "refs/remotes/origin/main", "HEAD");
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
}
function mirrorFixture(mode: "retry" | "skip" | "concurrency", mirrorOnly = false) {
const f = repository();
const tools = join(f.root, "tools"), published = join(f.root, "published");
mkdirSync(tools); mkdirSync(published); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
const names = mode === "concurrency" ? Array.from({ length: 5 }, (_, i) => `hose-use-fixture-${i}`) : ["hose-use-linux-x64"];
const manifest = names.map(name => {
const data = `published bytes for ${name}`;
writeFileSync(join(published, name), data);
return `${createHash("sha256").update(data).digest("hex")} ${name}\n`;
}).join("");
writeFileSync(join(published, "checksums.txt"), manifest);
const files = [...names, "checksums.txt"];
if (!mirrorOnly) for (const name of files) writeFileSync(join(f.root, "dist/bin", name), readFileSync(join(published, name)));
writeFileSync(join(f.root, "info.json"), JSON.stringify({ assets: mode === "skip" ? files.map((name, i) => ({ id: i + 1, name })) : [] }));
writeFileSync(join(tools, "gh"), '#!/bin/sh\nprintf "%s\\n" "$*" > "$MIRROR_FIXTURE/gh.log"\ncp "$MIRROR_FIXTURE"/published/* dist/bin/\n', { mode: 0o755 });
writeFileSync(join(tools, "curl"), `#!/bin/bash
url=""
for arg in "$@"; do case "$arg" in https://*) url="$arg" ;; esac; done
case "$url" in
*/assets?*)
name="\${url##*name=}"
printf 'start\\n' >> "$MIRROR_FIXTURE/events"
if [ "$MIRROR_MODE" = "skip" ]; then printf 'unexpected upload\\n' >> "$MIRROR_FIXTURE/uploads"; exit 22; fi
count_file="$MIRROR_FIXTURE/count-$name"
count=0; [ ! -f "$count_file" ] || count=$(cat "$count_file")
count=$((count + 1)); printf '%s' "$count" > "$count_file"
if [ "$MIRROR_MODE" = "retry" ] && [ "$count" -eq 1 ]; then printf 'end\\n' >> "$MIRROR_FIXTURE/events"; exit 28; fi
if [ "$MIRROR_MODE" = "concurrency" ]; then sleep 0.1; fi
printf 'end\\n' >> "$MIRROR_FIXTURE/events"
printf '{"id":100}\\nHTTP_STATUS:201'
;;
*/download/*) cat "$MIRROR_FIXTURE/published/\${url##*/}" ;;
*/releases) printf '{"id":42}' ;;
*/releases/42) cat "$MIRROR_FIXTURE/info.json" ;;
*) exit 22 ;;
esac
`, { mode: 0o755 });
const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8"));
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
return { ...f, files, run: () => spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0", MIRROR_ONLY: String(mirrorOnly), GITHUB_REPOSITORY: "test/repo", MIRROR_FIXTURE: f.root, MIRROR_MODE: mode }, encoding: "utf8", timeout: 30_000 }) };
}
describe("release preparation and publication guards", () => {
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
const f = repository();
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("release-v1.0.1");
f.git("switch", "-c", "codex/release-v1.0.1");
writeFileSync(join(f.root, "untracked.txt"), "work in progress");
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("clean working tree");
rmSync(join(f.root, "untracked.txt"));
for (const version of ["1.0.0", "0.9.9", "1.0.01", "1.0.1-rc.01", "invalid"]) expect(() => bumpVersion(f.root, version, () => {})).toThrow();
expect(f.version()).toBe("1.0.0");
expect(f.git("status", "--porcelain")).toBe("");
}, 60_000);
test("bump updates sources on its release branch and explicitly invokes regeneration", () => {
const f = repository();
f.git("switch", "-c", "release/v1.0.1");
let rebuilt = false;
expect(bumpVersion(f.root, "patch", () => { rebuilt = true; })).toBe("1.0.1");
expect(rebuilt).toBe(true);
expect(f.version()).toBe("1.0.1");
expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1");
expect(parse(readFileSync(join(f.root, "specs/openapi/openapi.yaml"), "utf8")).info.version).toBe("1.0.1");
}, 60_000);
test("an existing release tag cannot be reused during bump", () => {
const f = repository();
f.git("switch", "-c", "release/v1.0.1");
f.git("tag", "v1.0.1");
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("already exists");
expect(f.version()).toBe("1.0.0");
}, 60_000);
test("publication validates the actual HEAD, main ancestry and package version", () => {
const f = repository();
f.git("tag", "v1.0.0");
expect(() => verifyReleaseTag(f.root, "v1.0.0")).not.toThrow();
expect(() => verifyReleaseTag(f.root, "main")).toThrow("Invalid release tag");
f.git("tag", "v9.9.9");
expect(() => verifyReleaseTag(f.root, "v9.9.9")).toThrow("does not match");
f.git("switch", "-c", "unmerged");
writeFileSync(join(f.root, "change"), "unreviewed");
f.git("add", "."); f.git("commit", "-m", "unmerged fixture");
expect(() => verifyReleaseTag(f.root, "v1.0.0")).toThrow("exact tagged commit");
f.git("tag", "v1.0.1");
expect(() => verifyReleaseTag(f.root, "v1.0.1")).toThrow("ancestor");
}, 60_000);
test("workflows validate committed versions before generation and ship the checksum manifest", () => {
const root = join(import.meta.dir, "..");
const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"));
const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8"));
expect(ci.on.pull_request.branches).toContain("main");
expect(ci.permissions.contents).toBe("read");
const steps = release.jobs["build-and-publish"].steps;
const runs = steps.map((s: { run?: string }) => s.run || "");
expect(runs.findIndex((s: string) => s.includes("check:version"))).toBeLessThan(runs.findIndex((s: string) => s.includes("openapi:all")));
expect(steps[0].with.ref).toContain("inputs.tag");
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
for (const name of ["Compile multi-target binaries", "Package release archives", "Publish GitHub Release"]) {
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
}
}, 60_000);
test("a failed background Gitea upload makes the Release step fail", () => {
const f = repository();
const workflow = parse(readFileSync(join(import.meta.dir, "../.github/workflows/release.yml"), "utf8"));
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture");
writeFileSync(join(f.root, "dist/bin/checksums.txt"), "fixture checksums");
writeFileSync(join(f.root, "tools/curl"), `#!/bin/sh
for arg in "$@"; do
case "$arg" in
*/assets?*) exit 22 ;;
*/releases) printf '{"id":42}'; exit 0 ;;
*/releases/42) printf '{"assets":[]}'; exit 0 ;;
esac
done
exit 22
`, { mode: 0o755 });
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 30_000 });
expect(result.status).toBe(1);
expect(result.stdout).toContain("assets failed to upload");
expect(result.stdout).not.toContain("Successfully published");
}, 60_000);
test("transient asset upload failures are retried", () => {
const f = mirrorFixture("retry");
const result = f.run();
expect(result.status).toBe(0);
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
expect(result.stdout).toContain("attempt 2/3");
}, 60_000);
test("correct mirror assets are verified and retained without uploading replacements", () => {
const f = mirrorFixture("skip");
const result = f.run();
expect(result.status).toBe(0);
expect(result.stdout.match(/already matches SHA-256/g)).toHaveLength(f.files.length);
}, 60_000);
test("mirror-only recovery downloads and verifies the existing GitHub assets", () => {
const f = mirrorFixture("skip", true);
expect(f.run().status).toBe(0);
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
}, 60_000);
test("asset transfers never exceed two concurrent workers", () => {
const f = mirrorFixture("concurrency");
expect(f.run().status).toBe(0);
let active = 0, peak = 0;
for (const event of readFileSync(join(f.root, "events"), "utf8").trim().split("\n")) {
active += event === "start" ? 1 : -1;
peak = Math.max(peak, active);
}
expect(active).toBe(0);
expect(peak).toBeLessThanOrEqual(2);
}, 60_000);
});
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bun
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { resolve, join } from "node:path";
import { spawnSync } from "node:child_process";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
const binary = resolve(process.argv[2] || "dist/bin/hose-use");
const plugin = process.argv.includes("--plugin");
const command = plugin ? process.execPath : binary;
const prefix = plugin ? [binary] : [];
const cwd = mkdtempSync(join(tmpdir(), "hose-binary-smoke-"));
// The binary must work without Bun on PATH or a source checkout in cwd.
const env = { PATH: process.platform === "win32" ? process.env.SystemRoot || "C:\\Windows" : "/usr/bin:/bin", HOSE_USE_MCP_ENABLED: "true", HOSE_CONFIG_FILE: join(cwd, "config.json"), HOSE_ENTERPRISES_DIR: cwd };
const client = new Client({ name: "hose-binary-smoke", version: "1.0.0" });
const transport = new StdioClientTransport({ command, args: plugin ? prefix : ["mcp", "serve"], cwd, env, stderr: "pipe" });
let stderr = "";
transport.stderr?.on("data", chunk => { stderr += chunk.toString(); });
const deadline = setTimeout(() => { void client.close(); }, 15_000);
try {
const version = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "version", "--json"], { cwd, env, encoding: "utf8", timeout: 5000 });
assert.equal(version.status, 0, version.stderr);
assert.ok(JSON.parse(version.stdout).version);
writeFileSync(join(cwd, "smoke.json"), JSON.stringify({ id: "smoke", name: "Smoke", source: "manual", credentials: { accessToken: "fixture", corpId: "smoke", staffId: "smoke:staff" } }));
const sandbox = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "workflow", "eval-script", "--code", 'return { total: items.reduce((a, b) => a + b, 0), host: typeof process };', "--input", '{"items":[1,2,3]}', "--corp", "smoke"], { cwd, env, encoding: "utf8", timeout: 5000 });
assert.equal(sandbox.status, 0, sandbox.stderr);
assert.match(sandbox.stdout, /"total": 6/);
assert.match(sandbox.stdout, /"host": "undefined"/);
await client.connect(transport, { timeout: 5000 });
const tools = await client.listTools();
assert.deepEqual(tools.tools.map(tool => tool.name), ["hose_cli"]);
const result = await client.callTool({ name: "hose_cli", arguments: { command: "version --json" } });
assert.ok(!result.isError, JSON.stringify(result));
const text = (result.content as Array<{ type: string; text?: string }>).find(c => c.type === "text")?.text;
assert.equal(JSON.parse(text || "").version, JSON.parse(version.stdout).version);
const invalid = await client.callTool({ name: "hose_cli", arguments: { command: "bill list --limitt 5 --json" } });
assert.equal(invalid.isError, true);
assert.match(JSON.stringify(invalid.content), /未知选项/);
console.log(plugin ? "Plugin bundle version and MCP stdio verified with its Bun runtime." : "Binary version and MCP stdio verified without Bun or source files.");
} catch (error) {
throw new Error(`Binary smoke failed: ${error instanceof Error ? error.message : error}\n${stderr}`);
} finally {
clearTimeout(deadline);
await client.close();
rmSync(cwd, { recursive: true, force: true });
}
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bun
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { isReleaseVersion } from "./bump-version.js";
export function verifyReleaseTag(root: string, tag: string): void {
if (!tag.startsWith("v") || !isReleaseVersion(tag.slice(1))) throw new Error(`Invalid release tag: ${tag}`);
const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const taggedCommit = git(["rev-parse", "--verify", `refs/tags/${tag}^{commit}`]);
if (git(["rev-parse", "HEAD"]) !== taggedCommit) throw new Error("Release HEAD must be the exact tagged commit");
try {
git(["merge-base", "--is-ancestor", taggedCommit, "refs/remotes/origin/main"]);
} catch {
throw new Error("Release tag must be an ancestor of origin/main; merge the PR before tagging");
}
const { version } = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
if (tag !== `v${version}`) throw new Error(`Release tag ${tag} does not match package.json v${version}`);
}
if (import.meta.main) {
verifyReleaseTag(resolve(import.meta.dir, ".."), process.argv[2] || "");
console.log("Release tag, HEAD, main ancestry and package version verified.");
}
+240 -77
View File
@@ -1,105 +1,268 @@
---
name: hose-use
description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底层 SDK。支持多账号纯 API 登录、30天 Token 自动无感续杯、多企业租户管理、有状态/无状态模式切换、自建应用扫描与跨应用工作流聚合检索。
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.8.17
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (合思/易快报企业级 CLI 与底层 SDK)
# hose-use (v0.8.17)
`hose-use` 是面向合思/易快报 SaaS、开发者与 AI 智能体的高性能交互工具。
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
## 核心架构原则
---
- **纯 API 认证**:内置 RSA PKCS#1 密码加密与统一认证中心握手,无需浏览器滑块即可登录。
- **全自动无感续杯**:内置 401 拦截与预检换票机制,Token 到期自动刷新并重试,零人工介入。
- **多账号与多身份分层**:支持一个手机号管理 13+ 家企业;支持同一企业下多身份(`corpId@accountId`)共存。
- **有状态 / 无状态双模式**:
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
## 本套件结构(先看这里)
本 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-use corps list` 或 `hose-use context`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
3. **输出防护与大报文处理**:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
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`)。
11. **本地企业名录最高可信度与合思 payType 混淆防范(Local Config as Source of Truth & PayType Trap)**:
- **本地配置具有最高权威性**:本地企业名录(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)经过人工审核确认,是判断企业真实性质的唯一权威来源;
- **合思云端 payType 极度混乱陷阱**:合思数据库中的元数据 `payType`(如 `TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式客户租户在系统底层依然被标记为 `TRYOUT`(试用)**;
- **严禁仅凭云端标记臆断测试沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"`、或企业名称简短/包含英文就盲目认定为测试沙箱。任何写操作(包括发起协助工单 `assist-platform apply`、单据或配置变更)必须严格核对本地企业环境,仅在明确标记为 🧪 测试 的企业中进行,正式企业必须有用户显式指令与二次确认。
12. **工作流草稿非隔离副本与生产介入明确知情权(Draft != Isolated Clone & Explicit Awareness)**:
- **草稿绝非独立副本**:合思工作流处于草稿态(`state: 0`)仅代表“修改尚未发布生效”,它与生产流程是**同一个实体**。若直接在原流程上修改草稿,一旦点击发布就会直接覆盖生产运行逻辑,绝不可将其误认为互不影响的沙箱副本;
- **排障或改造的知情选择权**:客户现场常存在“原本有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。Agent 介入排障或调整前,**必须向用户明确揭示实体归属与当前状态**,并提供两条明确路径供用户决策:
1. **克隆独立副本(推荐稳健路径)**:使用 `hose-use workflow copy <pipelineId>` 创建真正的独立工作流副本(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
13. **协助会话人员身份角色穿透与高管权限防误用守则 (Assist Identity Profile & Executive Privilege Guard)**:
- **身份与角色权限第一时间穿透呈现**:通过协助链接进入企业(`hose-use assist-platform enter`)或生成免密会话时,系统自动穿透解析并输出当前获得的员工姓名、工号、所属部门、所配角色清单以及核心系统权限;并自动将该人员画像与风控等级持久化落盘至本地企业配置(`enterprises/<corpId>.json`);
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
---
## 意图路由导航 (Route By Intent)
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|---|---|---|
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `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) |
| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通/权限转交 | `hose-use assist-platform login/search/detail/tickets/staff/apply/enter/transfer` | [references/assist-platform.md](references/assist-platform.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) |
| 工作流节点树、代码依赖与静态门禁诊断(硬门禁/软建议/权限/DataLink公式) | `hose-use workflow analyze <pipelineId> [--fail]` | [references/workflow.md](references/workflow.md) |
| 企业已开通工作流节点字典探针与灰度开通 | `hose-use workflow nodes [--all]`, `hose-use workflow nodes grant <type...>` | [references/workflow.md](references/workflow.md) |
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow 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-use openapi`, `hose-use openapi --raw` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | `hose-use update`, `hose-use update --changelog` | `hose-use update --help` |
---
## 常用命令速查
### 1. 认证管理 (`hose-use auth`)
```bash
# 纯 API 账密全自动登录(自动获取 RSA 公钥加密并拉取旗下所有企业)
hose-use auth login --phone=17718556446 --password=...
# 0. 全局上下文一键自省 (免读源码构建环境)
hose-use context # 文本格式仪表盘 (当前账号/企业/工号/Token/AI PRO/路径)
hose-use context --json # 结构化 JSON (供 Agent 零解析直接构建完整上下文)
hose-aipro status # 查看 AI PRO 审批网关状态、当前连接企业与规则场景库
hose-aipro # 首页直接展示动态企业页眉与快速工作流
# 导入 F12 抓包复制的 cURL 或 Request Headers
hose-use auth import --raw="curl ..."
# 1. 认证与企业
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 # 诊断当前企业接口连通性
# 查看当前登录状态与活跃账号
hose-use auth status
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
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 # 精准获取指定员工档案
# 一键批量刷新名下所有企业的最新 30 天 AccessToken
hose-use auth refresh
# 3. 单据与费用
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 # 查看单据模板字段配置、赋值优先级与联动规则
# 查看已保存的全部主账号
hose-use auth accounts
```
# 4. 待办与消息
hose-use task submitted # 查看我发起的单据
hose-use message list --unread # 查看未读消息
hose-use message list --all # 合并查看已读和未读消息
hose-use message count # 查看未读数量
hose-use message read <messageId> # 标记单条消息已读
### 2. 多企业租户管理 (`hose-use corps`)
# 5. 应用管理、自建应用与工作流
hose-use app list # 查看应用管理列表(桌面端工作台业务应用集成)
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
hose-use platform list # 列出企业可见的自建应用平台
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
hose-use platform 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 # 将保存后的工作流发布/启用
hose-use workflow nodes # 探查当前企业已开通的工作流节点字典(动作/控制/触发器)
hose-use workflow nodes --all # 对照官方 108 个灰度节点清单查看全量开通状态
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
hose-use workflow tail wf_01k83y... --failed-only # 仅在有报错或异常跳过 (SKIPPED) 时即时打印详情
hose-use workflow tail wf_01k83y... --once --json # 检视最新或当前运行中的 Job 进度快照并返回结构化数据
hose-use workflow lint-script wf_01k83y... # 批量静态校验代码节点语法规范与上游依赖 (支持 --file/--code)
hose-use workflow eval-script wf_01k83y... <节点> --sample=1 # 离线沙箱仿真运行 JS 节点并复用样本数据 (支持 --input/--timeout)
```bash
# 列出名下所有已授权企业
hose-use corps list
# 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 可带或不带前导 $)
# 切换当前工作企业 (有状态模式下自动持久化)
hose-use corps switch uzU7pcWfScck00
# 查看当前激活企业信息
hose-use corps current
```
### 3. 全局运行模式 (`hose-use config`)
```bash
# 查看全局运行模式与配置文件路径
hose-use config show
# 切换为无状态模式 (Stateless)
hose-use config mode stateless
# 切换为有状态模式 (Stateful)
hose-use config mode stateful
```
### 4. 平台与工作流管理 (`hose-use workflow` / `hose-use platform`)
```bash
# 汇总查看企业下所有工作流 (跨自建应用聚合)
hose-use workflow list
# 查看指定工作流详情与节点结构
hose-use workflow get 829729467412037634
# 搜索包含指定节点类型的工作流 (如 code-js2, http 等)
hose-use workflow find --task=code-js2
# 启用 / 停用工作流 (1: 启用, 0: 停用)
hose-use workflow toggle <pipelineId> --state=1
# 查看企业下所有启用的自建应用
hose-use platform list
```
### 5. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
```bash
# 连通性与 EASO 平台鉴权诊断
hose-use probe
hose-use probe --corp=uzU7pcWfScck00
# 启动极简 MCP stdio 服务
hose-use mcp serve
# 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 # 停止后台常驻守护进程
```
---
## 全局选项
- `--corp=<id>`:临时指定操作的企业/身份 ID
- `--json`, `-j`:输出 JSON 结构化格式(适合脚本解析)
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
- `--json`, `-j`:以标准 JSON 结构化输出结果
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
- `--stateless`:单次命令强制以无状态模式执行
- `--stateful`:单次命令强制以有状态模式执行
- `--dry-run`:预览写操作,不发起写请求或落盘
- `--yes`, `--confirm`:显式确认执行写操作
- `--help, -h`:查看命令帮助与参数说明
+16
View File
@@ -0,0 +1,16 @@
schema_version: "v1"
name: "hose-use"
description: "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业多租户切换、单据明细检索、自建应用工作流管理、内置 HTTP 服务与常驻守护进程。"
auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令,包括 keys 凭证查询与 store 应用探查。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
properties:
command:
type: "string"
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万需特殊说明]{特殊}`:直接触发人工会签或复核分支。
@@ -0,0 +1,202 @@
# 合思协助平台(Unity 运营中心)
本专卷覆盖对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其统一身份认证(SSO,`https://sso.hosecloud.com`)的自动化能力。
合思协助平台是面向实施、运维与服务团队的专属运营系统(管理 34 万+ 企业租户库),与终端企业 SaaS 门户(`app.ekuaibao.com`)互为独立站点。通过本模块,Agent 可完成从扫码登录、多租户全量库检索、协助工单提取、指定员工身份免密换票,到自动将目标企业一键持久化落盘至本地名录的全流程。
支持顶层命令:`hose-use assist-platform`(别名:`hose-use assist-center`, `hose-use ap`)。
---
## 1. 协助平台会话登录 (`login`)
协助平台基于合思 SSO 进行钉钉扫码登录。本工具支持自动轮询二维码状态,也支持直接导入已有 Session Token。
```bash
# 检查当前协助平台的登录状态与有效性
hose-use assist-platform login --status
# 交互式二维码登录(输出终端二维码,并监听钉钉扫码与确认事件)
hose-use assist-platform login
# 直接绑定已有 Token 会话并持久化
hose-use assist-platform login --token <session-token>
# 退出协助平台登录态
hose-use assist-platform login --logout
```
凭证安全落盘位置:`~/.config/hose-use/assist-platform.json`(权限 0600)。
---
## 2. 检索企业库 (`search` / `detail`)
在拥有 34 万+ 企业的全量库中检索目标租户,获取企业 ID 与基本信息。
```bash
# 按关键词或企业 ID 检索企业
hose-use assist-platform search "示例公司"
hose-use assist-platform search "Cxa3oOtQi2eS$g" --json
# 查看企业详细画像(创建时间、版本、授权范围、联系人及备注)
hose-use assist-platform detail "Cxa3oOtQi2eS$g"
```
---
## 3. 协助工单探查 (`tickets`)
协助平台进入客户租户必须依赖有效的协助工单。
```bash
# 查询指定企业当前所有协助工单
hose-use assist-platform tickets <企业ID>
# 查看历史全部工单(包含已结束/已撤回)
hose-use assist-platform tickets <企业ID> --all --limit 20
```
工单信息包含:工单编号 (`ticketId`)、申请人、申请事由、起始时间与过期时间。
> [!WARNING] 合思底层 payType 混淆与本地企业名录可信度原则
> 1. **合思付费模式混乱**:合思数据库中的 `payType`(`TRYOUT` 试用 / `PAY` 付费)存在严重的业务历史包袱,**大量真实商业付费的正式生产客户在系统中依然被标记为 `TRYOUT`(试用)**。
> 2. **严禁仅凭云端标记臆断沙箱**:严禁仅凭云端返回的 `payType: "TRYOUT"` 擅自推断企业为测试沙箱!
> 3. **本地配置权威优先**:判断企业性质必须以本地企业配置(`hose-use corps list` / `enterprises/*.json`)标注的环境类别(🏭 正式 / 🧪 测试 / 🎪 演示)为准,本地配置具有最高权威性。任何写操作(如发起协助工单 `apply`)严禁在未经授权的正式企业上执行。
---
## 4. 员工名录检索 (`staff`)
当需要以客户企业内特定员工身份(而非主管理员)代客进入时,可通过 `staff` 检索目标人员的 `staffId`。
```bash
# 按姓名精确或模糊搜索员工
hose-use assist-platform staff <企业ID> --name "李志财"
# 按手机号或工号过滤
hose-use assist-platform staff <企业ID> --mobile "13800000000"
```
---
## 5. 发起协助申请工单 (`apply`)
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作仅限在本地确认的 🧪 测试企业中进行,正式企业必须获得用户明确指示。**
> [!IMPORTANT] 协助时长服务端硬性上限与 24 小时限制
> 合思协助平台服务端(`POST /api/assistPlatform/create`)实施了底层的硬性安全管控:
> - 单次协助工单最长有效期限为 **24 小时 (1天)**;
> - 超过 24 小时(如 48 小时或 7 天)服务端会直接报错 `{"errorCode":400,"errorMessage":"参数错误,申请时间不能超过24小时"}` 并拒绝受理;
> - 命令行同时支持 `--hours <小时>` 与 `--days <天数>`,传入超过 24 小时(> 1 天)将即时给出阻断与友好提示。如需持续维护,可在工单到期后再次发起或在端内续签。
```bash
# 查看变更预览(安全 Dry-Run)
hose-use assist-platform apply ID01ofWoOC1wiX --dry-run
# 向测试企业发起 24 小时(1天)协助工单申请
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --hours 24 --yes
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --days 1 --yes
```
提交后工单初始状态为 `🟡 待提供`,等待企业管理员登录合思 Web/桌面端确认开启授权即可激活。
---
## 6. 企业端通过协助授权 (`approve`)
当企业端收到协助申请后,企业管理员可在 Web 端【系统配置 ➔ 合思助手 ➔ 工单列表】中点击“授权”,亦可通过本 CLI 命令直接审批通过工单(需要本地具备该企业的管理员会话凭证)。
```bash
# 查看变更预览(安全 Dry-Run)
hose-use assist-platform approve --corp ID01ofWoOC1wiX --dry-run
# 自动寻找最新待提供工单并批准生效
hose-use assist-platform approve --corp ID01ofWoOC1wiX --yes
# 显式指定工单编号批准生效
hose-use assist-platform approve ID01Xeno3GpoNV --corp ID01ofWoOC1wiX --yes
```
批准通过后,工单状态立即变为 `🟢 生效中`,可由运维侧立即免密进入。
---
## 7. 免密代客进入、身份穿透与高管风控 (`enter`)
基于选定工单与身份(管理员或指定员工),向协助平台换取免密直通链接,并支持一键落盘到本地企业库和自动提权。
### 7.1 人员身份画像穿透与高管权限防误用守则
> [!WARNING] 高阶管理人员权限风控警示 (Executive Role Risk Warning)
> 1. **人员身份全景穿透**:通过协助链接进入企业或生成免密会话时,CLI 会自动向合思组织架构服务下钻查询,第一时间提取当前获得的员工姓名、工号、绑定手机、所属部门、所配角色清单以及核心系统权限;
> 2. **持久化落盘安全标记**:落盘至本地(`enterprises/<corpId>.json`)时,会将 `departmentName`, `roles`, `roleTitles`, `isSeniorExecutive`, `riskLevel`, `permissions` 完整写入 `session` 元数据中,确保后续执行可知;
> 3. **高管身份命中与警示框**:当角色命中总监、主管理员、财务负责人、总经理、CEO/CFO 等高级头衔,或包含 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 时,终端将输出醒目的高管权限风控警示框;
> 4. **严禁越权业务审批**:一线实施、运维人员或 AI Agent 严禁代用高管身份进行业务审批通过、款项拨付或非授权单据提交,仅限用于排障与配置诊断。
```bash
# 1. 仅获取免密直达 URL 与临时 Token(默认自动寻找最新有效工单,即时输出身份画像与风控警示)
hose-use assist-platform enter <企业ID>
# 2. 以主管理员身份进入
hose-use assist-platform enter <企业ID> --admin
# 3. 指定员工姓名代客进入(内部自动匹配员工库 staffId)
hose-use assist-platform enter <企业ID> --name "李志财"
# 4. 指定工单 ID 与 staffId 进入
hose-use assist-platform enter <企业ID> --ticket <ticketId> --staff <staffId>
# 5. 【推荐一键流】获取免密链接后,自动落盘至本地企业名录并切换为当前上下文(持久化保存身份与权限元数据)
hose-use assist-platform enter <企业ID> --name "李志财" --save --switch
# 6. 【高阶全自动】落盘并自动提权(换取永久 OpenAPI 密钥,避免 2 小时临时 Token 过期中断业务)
hose-use assist-platform enter <企业ID> --name "李志财" --save --switch --elevate
```
### 参数说明
| 参数 | 说明 |
|---|---|
| `<corpId>` | 目标企业 ID(必填) |
| `--ticket <id>` | 指定协助工单 ID(缺省时自动采用最新有效工单) |
| `--admin` | 以企业主管理员身份进入 |
| `--staff <id>` | 指定代客员工的内部 ID (`staffId`) |
| `--name <姓名>` | 指定代客员工的真实姓名(自动检索匹配并转换) |
| `--save` | 换取成功后直接调用底层能力导入本地企业名录(`enterprises/<id>.json`) |
| `--switch` | 导入后自动切换为当前活跃企业租户 |
| `--elevate` | 导入后自动探测并保存持久化 OpenAPI Key 与 Secret,实现长期免密接入 |
| `--json` | 输出结构化 JSON 结果 |
---
## 8. 协助工单转交 (`transfer`)
当已获得客户授权的工单需要移交给其他运维、实施或研发同事时,可使用转交功能直接将权限移交给目标人员,**无需客户侧重新发起审批授权**。
```bash
# 查看具备协助权限的可转交人员列表
hose-use assist-platform transfer --candidates
hose-use assist-platform transfer --candidates "陈龙"
# 查看转交预览(安全 Dry-Run)
hose-use assist-platform transfer <企业ID> --to "陈龙" --dry-run
# 一键转交指定企业的当前生效协助工单
hose-use assist-platform transfer <企业ID> --to "陈龙" --remarks "排障任务交接" --yes
# 显式指定工单号转交
hose-use assist-platform transfer <企业ID> <工单ID> --to "陈龙" --yes
```
### 参数说明
| 参数 | 说明 |
|---|---|
| `<corpId>` | 目标企业 ID(必填) |
| `[ticketId]` | 指定转交的协助工单编号(缺省时自动采用企业当前生效的工单) |
| `--to <姓名\|工号\|账号>` | 转交接收人,支持输入姓名(如“陈龙”)、工号(如“3016”)或账号(如“chenlong3016”) |
| `--candidates` | 查询内部具备协助权限的可转交人员名单 |
| `--remarks <备注>` | 添加转交附言或任务交接说明(100 字以内) |
| `--dry-run` | 预览转交参数与接收人匹配结果,不发起网络写操作 |
| `--yes, -y` | 显式确认执行转交 |
+177
View File
@@ -0,0 +1,177 @@
# 认证、多租户与运行模式指南 (Authentication & Multi-Tenant Guide)
本参考专卷详细说明 `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`)
`hose-use` 实现了**纯 API 级 RSA 密码加密登录**,无需通过浏览器抓包或人工复制 Cookie。
### 纯 API 账密自动登录
```bash
# 自动通过公钥加密密码,登录并拉取名下全部企业凭据写入本地配置
hose-use auth login --phone=17718556446 --password=YourPassword123
```
- **核心逻辑**:向合思主站请求 RSA 公钥,将密码密文提交到 `/api/auth/login`;成功后自动遍历用户关联的企业租户,调用换票接口写入对应的企业配置。
### 查看登录状态与 Token 有效期
```bash
hose-use auth status
```
- 自动计算并输出自然语言剩余有效期(如 `29天23小时后过期`),清晰展示当前账号与当前企业。
### 30 天无感 Token 刷新
```bash
hose-use auth refresh
```
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
### 第三方免密/协助链接一键导入与自动提权持久化 (`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" \
--yes
```
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
### 多账号清单
```bash
hose-use auth accounts
```
- 查看本地已记录的手机号多账号清单及其关联的企业列表。
---
## 2. 企业租户管理 (`corps`)
### 列出所有企业
```bash
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
```
- 在有状态(stateful)模式下,此命令将更新全局默认企业 ID。
### 查看当前企业
```bash
hose-use corps current
```
---
## 3. 全局配置与模式管理 (`config`)
### 运行模式(有状态 vs 无状态)
- **有状态模式 (Stateful,默认)**:
- 会话状态保存在 `~/.config/hose-use/config.json` 中;
- 执行 `corps switch` 后,后续命令自动继承当前选中的企业。
- **无状态模式 (Stateless,推荐给 Agent)**:
- 不依赖全局状态切换,所有命令通过 `--corp=<id>` 显式指定,防止并发操作相互干扰;
- 通过环境变量 `HOSE_STATELESS=1` 或单次参数 `--stateless` 开启。
```bash
# 查看当前配置
hose-use config show
# 查看多层级配置发现路径诊断
hose-use config paths
# 切换全局运行模式
hose-use config mode stateless
hose-use config mode stateful
```
### 多层级配置发现顺序
1. 环境变量 `HOSE_ENTERPRISES_DIR`(最高优先级)
2. 当前工作区根目录下的 `enterprises/`
3. 用户主目录配置:`~/.config/hose-use/enterprises/`
4. 历史兼容缓存:`~/.cache/ekb-mcp/enterprises/`
---
## 4. 连通性探针 (`probe`)
```bash
# 诊断当前企业的鉴权链路与平台可用性
hose-use probe
# 诊断指定企业的连通性
hose-use probe --corp=uzU7pcWfScck00
```
- **探针行为**:
1. 验证主站 Session 是否有效;
2. 测试 EASO 平台 SSO 握手是否成功;
3. 输出各环节毫秒级延迟与 HTTP 状态。
+210
View File
@@ -0,0 +1,210 @@
# 单据与费用明细指南 (Bill & Expense Guide)
本参考专卷详细说明合思单据检索、费用报销明细下钻、中文标签映射字典以及大报文防爆机制。
---
## 1. 单据列表检索 (`bill list`)
### 基础查询
```bash
# 查看当前企业最近的单据与报销列表 (默认表格格式)
hose-use bill list
# 指定企业查询并以 JSON 输出
hose-use bill list --corp=uzU7pcWfScck00 --json
```
### 过滤与检索选项
- `--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
# 跨单据名称与表单字段检索含“打车”的最近 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
```
---
## 2. 单据详情精准下钻 (`bill get`)
支持传入**单据编号**(如 `CL20260903001`)或合思全局**单据 ID**(如 `n0GMIM0dkQmKbS`):
```bash
hose-use bill get n0GMIM0dkQmKbS
hose-use bill get CL20260903001 --json
hose-use bill flow CL20260903001
```
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
```bash
hose-use bill get S26000001 --risk
hose-use bill get S26000001 --risk --json
```
### 中文字段智能映射字典
合思底层原生单据接口通常返回类似 `c0_1`, `d1_4`, `u_fee_amount` 等混淆字段。
`hose-use` 内置**动态中文 Label 字典转换引擎**:
- 自动提取单据所属模板的中文配置定义;
- 将 `c0_1` 翻译为清晰的 `费用发生日期`;
- 将 `d1_4` 翻译为 `费用类型/科目`;
- 将 `u_fee_amount` 翻译为 `报销金额`;
- 向 AI 与用户同时提供规范化的结构体与原始值对照。
---
## 3. 单据审批流程 (`bill flow`)
读取单据右侧审批流程面板的真实业务接口,输出历史流转日志、处理人、审批意见、节点停留时长、自动跳过标记、当前节点和后续节点;使用 `--json` 可获得结构化时间线。
```bash
hose-use bill flow CL20260903001
hose-use bill flow CL20260903001 --json
hose-use bill risk CL20260903001
```
`bill risk` 聚合审批页“审查”面板的风控预警、信用规则、预算状态与发票风险接口;默认只输出摘要,`--json` 保留结构化原始结果。
## 4. 单据审批动作套件
审批动作直接复用合思 Web 点击时的业务接口。写操作必须显式带 `--yes`;交互终端未带该参数时会进行二次确认,非交互终端会直接拒绝,避免脚本误写业务状态。
```bash
# 同意:可附带纯文本审批意见
hose-use bill approve S26000001 --comment "同意" --yes
# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标
hose-use bill reject S26000001 --comment "请补充发票" --yes
# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名
hose-use bill transfer S26000001 --approver-id 111 --yes
# 加签:默认前加签,--mode post 表示后加签
hose-use bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes
# 评论:支持 --participants 传入逗号分隔的人员 ID
hose-use bill comment S26000001 --comment "补充说明" --participants <staffId> --yes
```
动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。
### 单据引用 ID 二级解析 (`bill refs`)
读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID:
```bash
hose-use bill refs S26000001
hose-use bill refs S26000001 --json
```
JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes`、`dimensions` 和 `unresolved`。单据里出现法人实体、项目或成本中心 ID 时,会联动 `dimension` 目录补充名称与编码;目录在当前进程内按企业缓存 10 分钟。
### 单据关联链 (`bill relations`)
从审批详情中的冲借款、前置申请、合同和费用关联字段抽取关系树:
```bash
hose-use bill relations S26000001
hose-use bill relations S26000001 --json
```
表格模式按树形缩进显示关联 ID、单号、标题和金额;JSON 模式保留每个节点的原始字段,便于继续下钻。
### 单据预算状态 (`bill budget`)
读取审批页使用的预算状态接口,查看单据是否超预算及接口返回的可用/占用金额字段:
```bash
hose-use bill budget S26000001
hose-use bill budget S26000001 --json
```
### 单据附件列表 (`bill attachments`)
从审批详情中递归提取普通附件与发票原件的文件名、`fileId`、`key`、URL 和来源字段,并通过附件文件服务补齐可下载地址:
```bash
hose-use bill attachments S26000001
hose-use bill attachments S26000001 --json
```
需要落盘时使用 `bill download`。命令会创建目标目录、清理文件名中的路径字符,并返回本地路径和字节数;指定 `--file-id` 可只下载一个附件:
```bash
hose-use bill download S26000001 --output-dir ./downloads
hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
```
## 5. 单据实体元数据字典 (`bill schema`) 与单据模板规格诊断 (`bill spec`)
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
```bash
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. 上下文防爆保护与安全转储
合思复杂的报销单通常携带大量明细行、发票 OCR 原生报文与附件列表,查询结果动辄数万行(几百 KB 到数 MB)。
### 默认 200KB 体积熔断保护
在未附加放行参数时,若序列化报文超过 200,000 字节,`hose-use` 会自动阻断并返回防御提示:
```text
[Output Protected] 输出内容超过 200KB 体积保护阈值 (284,520 bytes)。
为防止过大输出打爆 AI 智能体上下文窗口,建议使用:
-o, --output-file <path> 将全量结果保存至本地文件
--full 强制全量输出
```
### 本地安全转储 (`--output-file` / `-o`)
将巨型报文直接直写到磁盘,终端/AI 仅输出轻量摘要:
```bash
hose-use bill list --json -o /tmp/bills_full.json
```
**返回摘要**:
```json
{
"outputFile": "/tmp/bills_full.json",
"bytes": 284520
}
```
### 强制全量放行 (`--full`)
明确需要捕获全部 stdout 时添加 `--full`:
```bash
hose-use bill list --json --full
```
### 全链路敏感信息脱敏
输出流中的 `accessToken`、`token`、`Bearer` 以及密码、秘钥等均由底层的 `redactSensitiveText` 自动清洗过滤,保障会话与调用日志安全。
+65
View File
@@ -0,0 +1,65 @@
# hose-use 专卷:企业通讯录与人员档案 (Contact Domain)
本文件是 `skills/hose-use/` 的领域参考专卷,详述合思/易快报企业通讯录的人员检索、防爆保护机制与单人档案下钻。
---
## 核心设计与防爆原则
企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**
因此,`hose-use` 遵循以下防爆安全原则:
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`。
---
## CLI 命令速查
```bash
# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)
hose-use contact search 王硕
hose-use contact search xiezihao@hosecloud.com
hose-use contact search 18600612659
# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)
hose-use contact list
hose-use contact list --limit=50
# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)
hose-use contact list --json -o /tmp/all_staffs.json
# 4. 精确下钻查看指定人员详细档案
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000
# 5. 指定特定企业租户检索
hose-use contact search 李 --corp=ID01MCcOgJl1td
```
---
## MCP 工具调用
在单工具网关模式下,推荐使用 `hose_cli` 触发:
```json
{
"command": "contact search 王硕"
}
```
在全量模式(`HOSE_MCP_MODE=all`)下,提供以下细粒度工具:
- `contact_search(keyword: string, limit?: number)`:返回匹配的员工列表
- `contact_get(staffId: string)`:获取单条员工详情
- `contact_list(limit?: number, allowFull?: boolean)`:带保护的企业通讯录列表
---
## 业务联动典型场景
### 1. 查找某人发起的单据
当用户要求“帮我查一下王硕提交的报销单”时:
1. 先通过 `hose-use contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose-use bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose-use bill link <单号>` 生成官方 Web 直达链接反馈给用户。
+15
View File
@@ -0,0 +1,15 @@
# 自定义档案与核算维度
合思前端“系统配置 → 档案设置 → 扩展档案 → 自定义档案”对应 CLI 的 `dimension` 域。
```bash
# 查看系统/自定义档案维度目录
hose-use dimension list
hose-use dimension list --keyword=项目
# 查看某个维度的档案项(支持维度 ID、编码或名称)
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 # 移至企业顶级根节点
```
+15
View File
@@ -0,0 +1,15 @@
# 消息中心
消息中心是 CLI-only 能力,不新增 MCP tool。命令默认查询未读消息。
```bash
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 条。
+20
View File
@@ -0,0 +1,20 @@
# 角色与角色组
角色页对应的只读 CLI:
```bash
hose-use role list
hose-use role list --keyword=财务
hose-use role groups
hose-use role members 财务主管
hose-use role members CODE15 --json
```
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
权限页的角色权限快照:
```bash
hose-use permission get
hose-use permission get --json
```
+114
View File
@@ -0,0 +1,114 @@
# 服务、守护进程与 API 网关指南 (Service & HTTP Gateway Guide)
本参考专卷详细说明 `hose-use` 内置的轻量 HTTP Server、常驻 Service 守护进程、Scalar 交互式文档以及 OpenAPI 规范导出能力。
---
## 1. 常驻 Service 守护进程 (`service`)
常驻守护进程允许 `hose-use` 在后台全天候运行,支持远程/本地无子进程开销调用 CLI,同时持久化存储 PID 与运行日志。
### 常用指令
```bash
# 启动常驻后台守护进程 (自动落盘 PID 到 ~/.config/hose-use/service.pid)
hose-use service start
# 检查常驻服务运行状态、PID、端口与访问端点
hose-use service status
# 查看常驻服务最近运行日志
hose-use service logs
# 重启常驻服务
hose-use service restart
# 优雅停止常驻服务 (清理 PID 文件)
hose-use service stop
# 容器/前台守护运行模式 (供 Dockerfile 或 Supervisor 使用)
hose-use service run
```
### 自愈保护机制
每次执行 `service status` 或 `service start` 时,系统会自动探测记录的 PID:
- 若进程已终止(孤儿 PID)或 PID 被其它非 `hose` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
### 事件轮询与去重 (`service poll`)
单次读取待办和未读消息,按事件 ID 写入 `~/.config/hose-use/events-<corpId>.json`,重复轮询不会重复返回已观察事件:
```bash
hose-use service poll --corp=<corpId>
hose-use service poll --corp=<corpId> --limit=100 --json
```
---
## 2. 前台 HTTP 服务 (`http` / `serve`)
在当前终端前台启动 HTTP 服务并输出直观的服务信息面板,按 `Ctrl+C` 即可平滑退出:
```bash
# 启动本地 HTTP 服务 (默认端口 8888,主机 127.0.0.1)
hose-use http
# 指定自定义端口与主机
hose-use http --port=9999 --host=0.0.0.0
```
---
## 3. HTTP 路由端点一览
| 方法 | 端点 | 说明 |
|---|---|---|
| `GET` | `/` | 服务元信息、版本号与端点导航 |
| `GET` | `/health` | 存活健康探针(返回 `{ "status": "ok", "version": "..." }`) |
| `GET` | `/docs` | 基于 **Scalar API Reference** 的沉浸式交互文档界面 |
| `GET` | `/openapi.json` | 包装层标准 OpenAPI 3.1.0 JSON 规范 |
| `GET` | `/raw-openapi.json` | 合思原生下游 OpenAPI 规范 |
| `POST` | `/api/cli` | **CLI 同进程执行网关**(免 spawn 子进程) |
| `GET` | `/v1/corps` | RESTful 风格企业租户列表与运行模式 |
### 同进程 CLI 执行网关 (`POST /api/cli`)
通过 HTTP POST 提交任意 CLI 命令字符串,在主服务进程内部直接分发执行,毫秒级响应,无需拉起 Node/Bun 子进程:
```bash
curl -X POST http://127.0.0.1:8888/api/cli \
-H "Content-Type: application/json" \
-d '{"command": "corps list --json"}'
```
**响应结构**:
```json
{
"success": true,
"stdout": "...",
"stderr": "",
"exitCode": 0,
"data": {
"corporations": [ ... ]
}
}
```
---
## 4. OpenAPI 规范导出 (`openapi`)
```bash
# 查看所有 API 路径与概要一览
hose-use openapi paths
# 查看合思原生下游全量 API 路径
hose-use openapi --raw paths
# 查看 OpenAPI 规范元数据概览
hose-use openapi info
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Apifox)
hose-use openapi
# 输出原生下游全量 OpenAPI 3.1.0 JSON
hose-use openapi --raw
```
+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` 的兼容别名。
+21
View File
@@ -0,0 +1,21 @@
# hose-use 专卷:待办中心与审批任务
## CLI
```bash
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`。
当前实现对接合思 Web 待办工作台实际使用的业务接口:待审批/审批记录走 `/api/flow/v2/backlogs/search`,已审批走 `/api/flow/v1/flows/approved`。接口响应的完整原始对象保留在 JSON 结果的 `raw` 字段中,便于后续接入“我发起的”和“抄送我的”视图。
当前只通过 CLI 暴露任务查询;MCP 不新增待办专用工具。
+443
View File
@@ -0,0 +1,443 @@
# 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide)
本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。
> **核心概念辨析(严禁混淆)**:
> - **【应用管理】(唯一命令:`hose-use app`)**:对应合思桌面端顶层一级导航【应用管理】。聚合了企业为员工开通的**全部前台业务落地应用**,既包括用车补贴、用车制度、E商卡等官方套件与制度,也包括新转转集团、差旅申请等挂载了视图的自建应用前台入口。
> - **【自建应用】(唯一命令:`hose-use platform` / `datalink`)**:对应企业后台【应用中心 -> 自建应用】(开放平台/PaaS)。负责业务对象建模(entities)、字段定义(schema)、权限快照与底层业务记录(records)。**切勿将自建应用称为“应用管理”**。
> - **【工作流】(唯一命令:`hose-use workflow`)**:自建应用下的任务流水线、拓扑节点(如自定义 JS 脚本 `code-js2`、Webhook 通知等)。
---
## 1. 应用管理 (`app`)
查看员工工作台开通的业务应用列表与详情:
```bash
# 列出工作台开通的全部业务应用(用车、制度、模板、自建前台等)
hose-use app list
hose-use app list --keyword="差旅"
hose-use app list --json
# 查看某个应用的详情与配置
hose-use app get 用车补贴
hose-use app get ID01RKbEvQsWbd
```
---
## 2. 自建应用与数据模型 (`platform` / `datalink`)
合思企业支持创建多个自建应用,每个自建应用可承载多个业务对象、字段模型与业务数据记录:
```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=ID01RKbEvQsWbd
```
---
## 4. 工作流任务节点精准扫描 (`workflow find`)
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
```bash
# 搜索包含自定义代码节点 (code-js2) 的所有工作流
hose-use workflow find --task=code-js2
# 搜索包含飞书通知节点的工作流
hose-use workflow find --task=feishu-notify
# 模糊搜索包含关键词的工作流
hose-use workflow find --keyword="自动审批"
```
---
## 5. 工作流详情查询 (`workflow get`)
获取工作流的完整节点拓扑、参数配置与表达式定义:
```bash
hose-use workflow get wf_01k83y...
hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
```
---
## 6. 工作流启用与关闭 (`workflow toggle`)
```bash
# 激活/启用指定工作流
hose-use workflow toggle wf_01k83y... --enable
# 停用指定工作流
hose-use workflow toggle wf_01k83y... --disable
```
## 7. 工作流静态分析与发布门禁 (`workflow analyze`)
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。
诊断结果显式划分为 **⛔ 硬门禁 (Hard Block)** 与 **💡 软建议 (Soft Advice)**:
- **⛔ 硬门禁**(必挂致命缺陷):
- `PERMISSION_MISSING_NODE`:使用了租户未开通的灰度节点(如未开通时的 `code-js2`);
- `MISPLACED_FORMULA_IN_DATALINK_MAPPING`:在底层 DataLink 数据写入节点中配置了前端表单公式(如 `AddMonths(...)`);
- `DOCS_DOMAIN_USED`:HTTP 节点误配开放平台文档域名 `docs.ekuaibao.com`(接口实际网关为 `app.ekuaibao.com`);
- `UNLICENSED_POWER_CODE`:HTTP 节点携带了未开通功能代码(如 `TICKET_AUDIT_switch`),网关将返回 403 Forbidden;
- `EMPTY_CODE`:代码节点缺少可执行脚本;
- `DEADLOCK_TRIGGER_STATE_FILTER` / `DEADLOCK_CONDITION_STATE_FILTER`:单据状态误配置导致事件静默丢弃或条件恒假;
- `INVALID_ACTION_ENUM_TEXT_VALUE`:枚举字段误配纯中文文本导致无法匹配。
- **💡 软建议**(最佳实践与潜在风险):
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内创单节点配置了 SKIP 跳过,但后续节点未校验前序状态;
- `LINKAGE_PRIORITY_OVERRIDE`:单据模板联动优先级高于手工/API 传入。
```bash
# 1. 静态分析指定工作流(直观展示硬门禁与软建议分类表格)
hose-use workflow analyze 886351399301758976
# 2. 作为 CI/CD 或脚本门禁运行(存在硬门禁时 exitCode = 2 阻断发布)
hose-use workflow analyze 886351399301758976 --fail
# 3. 输出结构化 JSON
hose-use workflow analyze 886351399301758976 --json
```
## 7.1 企业已开通节点探针与灰度开通 (`workflow nodes`)
合思微前端(Piper)仅向开通了权限的租户展示对应节点,未开通节点在界面中隐身且运行时直接报错:
```bash
# 1. 查看当前企业已开通的节点字典(动作/控制/触发)
hose-use workflow nodes
# 2. 与官方全量 108 个灰度节点清单进行完整对照
hose-use workflow nodes --all
# 3. 申请开通灰度节点(支持节点拼音与中文名)
hose-use workflow nodes grant code-js2
```
## 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. 从零创建、复制与删除工作流 (`workflow create` / `copy` / `delete`)
对标合思 EASO/Piper 网页端“新建工作流”、“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁,且新流程初始状态**强制锁定为草稿未启用(`state = 0`)**:
> [!IMPORTANT]
> **核心避坑认知:草稿不等于隔离副本(Draft != Isolated Clone)**
> - **草稿态实质**:合思工作流的草稿状态(`state: 0`)仅表示“改动尚未发布对线上生效”,它与线上流程是**同一个实体**。直接在生产工作流上改草稿,一旦点击发布就会直接覆盖线上运行逻辑,绝不可将其误认为独立的沙箱副本;
> - **生产排障与改造的知情权**:客户现场常存在“原有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。介入排障或调整前,**必须向用户明确说明当前实体性质**,并提供清晰决策路径:
> 1. **克隆独立副本(推荐稳健路径)**:使用 `workflow copy` 克隆出新流水线(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
> 2. **就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并同意直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
```bash
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
hose-use workflow create --name="外部风险推送" --trigger=webhook --yes
hose-use workflow create --name="每日发票对账" --trigger=clock --platform-id=ID01uzxB4x07fh --yes
# 2. 从本地 JSON 模板文件一键新建
hose-use workflow create --file=workflow-template.json --name="生产流程-A" --yes
# 别名支持 new, add
hose-use workflow new --name="合同归档触发" --trigger=datalink --yes
# 3. 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本)
hose-use workflow copy <pipelineId> --dry-run
hose-use workflow copy <pipelineId> --name="发票监控克隆版" --yes
# 别名支持 cp, clone
hose-use workflow cp <pipelineId> --yes
# 4. 删除指定工作流(不可逆,必须确认)
hose-use workflow delete <pipelineId> --dry-run
hose-use workflow delete <pipelineId> --yes
# 别名支持 rm, remove
hose-use workflow rm <pipelineId> --yes
```
---
## 15. 工作流节点级声明式编排与编辑 (`workflow node`)
针对合思 EASO/Piper 任务流水线内部的复杂节点树(支持 `every` 循环、`condition` 分支多层深度嵌套),提供直接按节点标识(如 `action_xxx`)或层级序号(如 `1`, `2.1`, `2.2.1`)定向查看、追加、修改与移除的能力,避免手动拼接庞大 JSON 报文的低效与格式错误:
```bash
# 1. 树形层级索引查看工作流中所有任务节点与配置摘要 (别名: ls)
hose-use workflow node list <pipelineId>
hose-use workflow node list <pipelineId> --json
# 2. 定向查看指定节点的完整属性与映射详情 (别名: show, info)
# 支持传节点 name (如 action_dx9cci) 或序号 (如 2 或 2.1)
hose-use workflow node get <pipelineId> action_dx9cci
hose-use workflow node get <pipelineId> 2 --json
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
# 4. 定向修改指定节点配置 (别名: update, set)
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
# 自动标准化重排同层 index 与 levelIndex;内置首节点触发器保护,严禁误删流程唯一的触发源
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
hose-use workflow node rm <pipelineId> action_dx9cci --yes
hose-use workflow node rm <pipelineId> 3 --yes
```
---
## 16. 实时任务监听与执行日志流 (`workflow tail` / `watch` / `follow`)
类似 Unix `tail -f` 实时监听工作流在合思云端的任务派发与节点执行树跃迁。当有外部 Webhook 推送、定时 CRON 调度或业务单据流转触发工作流时,无需反复手动敲 `workflow logs` 或 `workflow job` 轮询,即时流式打出节点状态跃迁与详细报错:
```bash
# 1. 类似 tail -f 实时监听流水线任务派发与各节点执行状态跃迁 (别名: watch, follow)
hose-use workflow tail <pipelineId>
hose-use workflow watch <pipelineId> --interval=1
# 2. 针对指定单次运行中的 Job 进行实时跟踪直至执行完成
hose-use workflow tail <pipelineId> --job=<jobId>
hose-use workflow tail 898268773466365973 --job=898577624451395602
# 3. 仅在有报错或异常跳过 (SKIPPED) 节点时即时告警并打出底层错误
hose-use workflow tail <pipelineId> --failed-only
# 4. 检视最新或当前运行中的 Job 进度快照 (不进入持续循环,适合脚本快速检查)
hose-use workflow tail <pipelineId> --once
hose-use workflow tail <pipelineId> --once --json
# 5. 设置最长监听超时 (秒)
hose-use workflow tail <pipelineId> --timeout=60
```
---
## 17. 工作流代码节点静态校验与离线沙箱仿真 (`workflow lint-script` / `eval-script`)
合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力:
```bash
# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用
hose-use workflow lint-script <pipelineId>
hose-use workflow lint <pipelineId> --json
# 2. 定向检查指定代码节点(支持节点名称或 #序号)
hose-use workflow lint-script <pipelineId> action_dx9cci
# 3. 静态检查本地脚本文件或命令行传入的代码片段
hose-use workflow lint-script --file=./scripts/clean.js
hose-use workflow lint-script --code="const a = 1; return a * 2;"
hose-use workflow lint-script --code="var a = control_123; return a;" --type=mvel
# 4. 在离线安全沙箱中仿真运行工作流中的某个 JavaScript 节点 (code-js2)
# 自动复用最近一次历史真实样本数据作为入参,打印返回值与全部 console.log 日志:
hose-use workflow eval-script <pipelineId> action_dx9cci
# 5. 指定历史测试样本序号(如第 2 条样本)进行离线仿真
hose-use workflow eval-script <pipelineId> action_dx9cci --sample=2
# 6. 自定义输入参数执行离线仿真 (JSON 字符串或本地 JSON 文件)
hose-use workflow eval-script <pipelineId> action_dx9cci --input='{"info":{"amount":100}}'
hose-use workflow eval-script <pipelineId> action_dx9cci --input-file=./mock_input.json
# 7. 纯本地行内代码沙箱快速求值与死循环超时控制 (--timeout 默认 3000ms)
hose-use workflow eval-script --code="console.log(items); return items.filter(x => x.active);" --input='{"items":[{"id":1,"active":true},{"id":2,"active":false}]}'
```
---
## 18. 工作流排障与创单排错三大黄金法则(必读)
在排查“工作流明明运行了但没生成单据”、“工作流显示 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`)安全修复。
---
## 19. Webhook 触发器测试样本打桩与注入 (`workflow webhook send`)
当在合思 Web 控制台复制或新建 Webhook 触发的工作流时,经常遇到点击【获取更多数据样本】一直转圈等待外部事件打过来的情况。`hose-use` 提供了直接向工作流专属 Webhook 发送测试载荷的注入命令:
```bash
# 1. 抓取真实单据数据作为测试载荷发送,立即生成最新数据样本
hose-use workflow webhook send <pipelineId> --bill=<单号或ID> --yes
# 2. 发送自定义 JSON 请求体
hose-use workflow webhook send <pipelineId> --body='{"event":"test","amount":100}' --yes
# 3. 从文件读取载荷
hose-use workflow webhook send <pipelineId> --file=./mock_payload.json --yes
# 4. 预演检查(查看目标 Webhook 真实地址与组装后的 Payload)
hose-use workflow webhook send <pipelineId> --bill=<单号> --dry-run
```
发送成功后,Piper 后端立刻捕获该记录,在 Web 界面点击【获取更多数据样本】即可秒级看到该样本;在命令行也可以直接用 `hose-use workflow test <pipelineId> --sample=1` 进行沙箱调测。
+1152
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+167
View File
@@ -0,0 +1,167 @@
ErrorResponse:
type: object
properties:
error:
type: boolean
example: true
message:
type: string
example: 操作失败原因
AuthLoginRequest:
type: object
required:
- phone
- password
properties:
phone:
type: string
description: 登录手机号
example: "17718556446"
password:
type: string
description: 登录明文密码 (由客户端自动完成 RSA 加密)
autoSwitch:
type: boolean
description: 是否自动切换到首个企业
default: true
AuthStatusResponse:
type: object
properties:
loggedIn:
type: boolean
activeCorpId:
type: string
activeCorpName:
type: string
totalAccounts:
type: integer
totalCorps:
type: integer
CorpConfig:
type: object
properties:
corpId:
type: string
description: 企业唯一标识
corpName:
type: string
description: 企业名称
staffId:
type: string
description: 员工身份 ID
accountId:
type: string
description: 归属账号手机号
PlatformItem:
type: object
properties:
id:
type: string
description: 自建应用 ID
name:
type: string
description: 自建应用名称
code:
type: string
description: 应用编码
status:
type: string
description: 应用状态
WorkflowSummary:
type: object
properties:
id:
type: string
description: 工作流 ID
name:
type: string
description: 工作流名称
platformId:
type: string
description: 归属自建应用 ID
platformName:
type: string
description: 归属自建应用名称
state:
type: integer
description: "1: 启用, 0: 停用"
updatedAt:
type: string
WorkflowDetail:
type: object
properties:
id:
type: string
name:
type: string
state:
type: integer
nodes:
type: array
items:
type: object
description: 工作流节点列表 (code-js2, loop, sql 等)
links:
type: array
items:
type: object
ProbeResult:
type: object
properties:
corpId:
type: string
corpName:
type: string
mainSession:
type: boolean
description: 主站会话是否有效
easoToken:
type: boolean
description: EASO 平台 Token 是否有效
platformsReachable:
type: boolean
description: 自建应用接口是否可访问
FormattedBill:
type: object
properties:
billId:
type: string
description: 单据 ID
billCode:
type: string
description: 单据业务编号 (单号)
billName:
type: string
description: 单据名称
title:
type: string
description: 单据标题
stage:
type: string
description: 业务阶段 (如 expense, loan, payment)
state:
type: string
description: 审批/支付状态 (如 paid, approving, draft)
amount:
type: string
description: 格式化金额 (如 ¥100.00 CNY)
submitterId:
type: string
description: 提交人员 ID
submitDate:
type: string
description: 提交时间
corporationId:
type: string
description: 归属企业 ID
details:
type: object
description: DataLink 字段字典还原后的中文字段键值对
+54
View File
@@ -0,0 +1,54 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.17
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
- url: http://localhost:3000
description: Local hose-use CLI / MCP Runtime Gateway
tags:
- name: Auth & SSO
description: 统一认证、多账号管理与 30 天 Token 自动无感续杯
- name: Corps & Tenancy
description: 多企业租户管理与工作空间切换
- name: Platforms
description: 自建应用检索与实例枚举
- name: Workflows
description: 跨自建应用工作流聚合检索、DSL 图谱与启停
- name: Bills & Documents
description: 费控单据、报销借款单、发票明细与 DataLink 实体字典
- name: Probe & Diagnostics
description: 会话有效性与 EASO 鉴权连通性诊断
paths:
/api/auth/login:
$ref: ./paths/auth.yaml#/login
/api/auth/status:
$ref: ./paths/auth.yaml#/status
/api/auth/refresh:
$ref: ./paths/auth.yaml#/refresh
/api/corps:
$ref: ./paths/corps.yaml#/list
/api/corps/switch:
$ref: ./paths/corps.yaml#/switch
/api/platforms:
$ref: ./paths/platform.yaml#/list
/api/workflows:
$ref: ./paths/workflow.yaml#/list
/api/workflows/find:
$ref: ./paths/workflow.yaml#/find
/api/workflows/{pipelineId}:
$ref: ./paths/workflow.yaml#/detail
/api/workflows/{pipelineId}/toggle:
$ref: ./paths/workflow.yaml#/toggle
/api/bills:
$ref: ./paths/bill.yaml#/list
/api/bills/{code}:
$ref: ./paths/bill.yaml#/get
/api/bills/schema:
$ref: ./paths/bill.yaml#/schema
/api/probe:
$ref: ./paths/probe.yaml#/probe
components:
schemas:
$ref: ./components/schemas/index.yaml
+68
View File
@@ -0,0 +1,68 @@
login:
post:
tags:
- Auth & SSO
summary: 纯 API 账密自动全流程登录
description: 自动拉取公钥进行 RSA PKCS#1 加密,发起统一认证中心握手并批量获取名下所有企业身份。
operationId: authLogin
requestBody:
required: true
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthLoginRequest
responses:
"200":
description: 登录成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
totalCorps:
type: integer
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
"401":
description: 账密错误或鉴权失败
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ErrorResponse
status:
get:
tags:
- Auth & SSO
summary: 查看当前登录与活跃企业状态
description: 查询本地或无状态下的当前账号、工作企业与凭证有效期。
operationId: authStatus
responses:
"200":
description: 状态正常
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthStatusResponse
refresh:
post:
tags:
- Auth & SSO
summary: 批量刷新企业 30 天 AccessToken
description: 自动无感为当前账号名下的所有企业租户更新最新 30 天访问令牌。
operationId: authRefresh
responses:
"200":
description: 刷新完成
content:
"application/json":
schema:
type: object
properties:
refreshed:
type: integer
total:
type: integer
+101
View File
@@ -0,0 +1,101 @@
list:
get:
tags:
- Bills & Documents
summary: 检索费用单据与发票明细列表
description: 查询企业名下的费用单据、报销单、借款单与发票列表,支持按单号、阶段、状态过滤。
operationId: listBills
parameters:
- name: code
in: query
required: false
description: 按单据编号/单号过滤(如 jO1it3cIufDjNS)
schema:
type: string
- name: keyword
in: query
required: false
description: 按关键字搜索标题、名称或内容
schema:
type: string
- name: stage
in: query
required: false
description: 按业务阶段过滤(expense 报销, loan 借款, payment 付款)
schema:
type: string
- name: state
in: query
required: false
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
schema:
type: string
- name: count
in: query
required: false
description: 返回条数限制
schema:
type: integer
default: 20
responses:
"200":
description: 格式化后的单据列表
content:
"application/json":
schema:
type: object
properties:
total:
type: integer
returned:
type: integer
items:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
get:
get:
tags:
- Bills & Documents
summary: 根据单号或 ID 查询单据结构化详情
description: 自动结合 DataLink 字段字典将代码字段还原为业务中文字段。
operationId: getBillByCode
parameters:
- name: code
in: path
required: true
description: 单据编号(如 n0GMIM0dkQmKbS)或单据 ID(如 ID01TRzg7HMLcb)
schema:
type: string
responses:
"200":
description: 单据详情列表
content:
"application/json":
schema:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
schema:
get:
tags:
- Bills & Documents
summary: 获取单据实体与数据模型字典
description: 获取企业全部表单实体、中文字段 Label 与类型定义。
operationId: getBillSchemas
responses:
"200":
description: 实体模型字典
content:
"application/json":
schema:
type: object
properties:
totalEntities:
type: integer
entities:
type: array
items:
type: object
+48
View File
@@ -0,0 +1,48 @@
list:
get:
tags:
- Corps & Tenancy
summary: 列出当前账号名下所有已配置企业租户
description: 支持单账号管理多家企业与同一企业下的多员工身份分层展示。
operationId: listCorps
responses:
"200":
description: 企业租户列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/CorpConfig
switch:
post:
tags:
- Corps & Tenancy
summary: 切换当前工作企业
description: 在有状态模式下切换并记忆工作企业,后续操作自动以该企业身份执行。
operationId: switchCorp
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- corpId
properties:
corpId:
type: string
description: 目标企业 ID 或身份 ID (corpId@accountId)
responses:
"200":
description: 切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
+23
View File
@@ -0,0 +1,23 @@
list:
get:
tags:
- Platforms
summary: 查询企业下所有启用的自建应用
description: 枚举当前企业已配置的自建应用及 EASO 平台实例。
operationId: listPlatforms
parameters:
- name: corpId
in: query
required: false
schema:
type: string
description: 目标企业 ID (未指定时使用默认工作企业)
responses:
"200":
description: 自建应用列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/PlatformItem
+20
View File
@@ -0,0 +1,20 @@
probe:
get:
tags:
- Probe & Diagnostics
summary: 诊断当前企业鉴权与接口连通性
description: 依次校验企业主站 Session Cookie、EASO 换票握手与自建应用接口可访问性。
operationId: probeCorp
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 诊断报告
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ProbeResult
+113
View File
@@ -0,0 +1,113 @@
list:
get:
tags:
- Workflows
summary: 跨自建应用汇总查看全部工作流
description: 自动遍历当前企业下所有自建应用,聚合返回全量工作流列表及运行状态。
operationId: listAllWorkflows
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 聚合工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
find:
get:
tags:
- Workflows
summary: 按节点类型递归搜索工作流
description: 递归解析所有工作流的 DSL 节点图谱,检索包含特定任务类型(如 code-js2, loop, sql 等)的工作流。
operationId: findWorkflowsByTask
parameters:
- name: task
in: query
required: true
schema:
type: string
example: "code-js2"
description: 目标节点任务类型
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 匹配的工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
detail:
get:
tags:
- Workflows
summary: 获取单个工作流详情与节点结构
description: 查询指定工作流的完整节点链、输入输出参数映射与触发器配置。
operationId: getWorkflowDetail
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
description: 工作流 ID
responses:
"200":
description: 工作流详情
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/WorkflowDetail
toggle:
put:
tags:
- Workflows
summary: 启用或停用工作流
description: "切换工作流的运行开关(1: 启用, 0: 停用)。"
operationId: toggleWorkflow
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- state
properties:
state:
type: integer
enum: [0, 1]
description: "目标状态 (1=启用, 0=停用)"
responses:
"200":
description: 状态切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
state:
type: integer
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 { closeDatabase, getDatabase } from "./core/db/index.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 = getDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置规约规则
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传真实发票]{硬性},[建议填写详细事由]{建议}。",
});
repo.createRule({
scope: "差旅报销",
body: "住宿费标准执行城市限额,[超标住宿必须有前置特批邮件]{硬性}。",
});
});
afterEach(() => {
closeDatabase();
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 = getDatabase(":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 = getDatabase(":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("严禁无故或恶意驳回");
});
});
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env bun
import { isDryRun, mutationPreview } from "./cli/mutation.js";
import { parseArgs, stringOption, booleanOption, isJsonRequested } from "./cli/parser.js";
import { cliErrorResult } from "./cli/runner.js";
import { printHelp, printJson, redactSensitiveText } from "./cli/printer.js";
import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js";
import {
ApprovalService,
ApprovalRepository,
ApprovalGatewayBlockedError,
} from "./domains/approval/index.js";
import { formatVersionLabel, getVersionInfo } from "./version.js";
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js";
import {
handleAiProChecklist,
handleAiProPoints,
handleAiProRules,
handleAiProScopes,
} from "./cli/commands/aipro/rules.js";
import {
handleAiProBind,
handleAiProDecide,
handleAiProInit,
handleAiProReview,
handleAiProTranslate,
} from "./cli/commands/aipro/session.js";
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
export async function runAiProCli(
rawArgs: string[]
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
try {
return await runAiProCliOnce(rawArgs);
} catch (error) {
return cliErrorResult(error, isJsonRequested(rawArgs));
}
}
async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const parsed = parseArgs(rawArgs, "aipro");
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
if (booleanOption(parsed.options, ["help", "h", "?"])) {
const help = printHelp(["aipro", ...(parsed.area && parsed.area !== "help" ? [parsed.area] : [])]);
return { stdout: jsonMode ? printJson({ help }) : `${help}\n`, stderr: "", exitCode: 0 };
}
const runtime = initCorpRuntime({
corpId: stringOption(parsed.options, ["corp"]),
jsonMode,
});
const corp = runtime.selectedCorp;
const previewPositional = parsed.positional || [];
const previewCommand = (previewPositional[0] || "help").toLowerCase();
const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3);
if (mutating && isDryRun(parsed, runtime)) {
return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
}
const repo = new ApprovalRepository();
const service = new ApprovalService(repo);
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | undefined;
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 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) {
case "status":
case "whoami":
case "context":
case "info":
return await handleAiProStatus(ctx);
case "init":
case "start":
return await handleAiProInit(ctx);
case "scopes":
case "index":
case "indexes":
return await handleAiProScopes(ctx);
case "translate":
case "doc":
case "markdown":
case "render":
return await handleAiProTranslate(ctx);
case "rules":
case "rule":
return await handleAiProRules(ctx);
case "bind":
case "mount":
return await handleAiProBind(ctx);
case "points":
case "clauses":
return await handleAiProPoints(ctx);
case "checklist":
case "list":
return await handleAiProChecklist(ctx);
case "review":
case "eval":
case "evaluate":
return await handleAiProReview(ctx);
case "decide":
case "approve":
case "reject":
return await handleAiProDecide(ctx);
case "logs":
case "log":
case "history":
case "trail":
return await handleAiProLogs(ctx);
case "help":
default:
return handleAiProHelp(ctx);
}
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
stderr: jsonMode ? "" : `\n${err.message}\n`,
exitCode: 1,
};
}
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "ERROR",
summary: String(err?.message || err),
});
return {
stdout: 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);
if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout));
if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr));
process.exit(result.exitCode);
}
+14 -3
View File
@@ -3,6 +3,7 @@
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
import { runCli } from "./cli/runner.js";
import { writeStdoutChunk } from "./cli/printer.js";
process.stdout.on("error", (err: any) => {
if (err?.code === "EPIPE") process.exit(0);
@@ -14,11 +15,21 @@ process.stderr.on("error", (err: any) => {
const entryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(entryFile));
const result = await runCli(process.argv.slice(2), {
appRoot,
entryFile,
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
const isAiPro = candidates.some((c) => {
const base = c.split("/").pop() || "";
return base.includes("hose-aipro") || base === "aipro" || base.includes("aipro-cli");
});
const result = isAiPro
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
: await runCli(process.argv.slice(2), {
appRoot,
entryFile,
writeStdout: writeStdoutChunk,
});
try {
if (result.stdout) process.stdout.write(result.stdout);
} catch (err: any) {
+36
View File
@@ -0,0 +1,36 @@
# CLI 引擎层说明
本目录是三个入口(`src/cli.ts` 主 CLI、`src/aipro-cli.ts` AI PRO CLI、`src/server.ts` MCP 网关)共享的命令引擎:声明式注册、参数解析、写防护、输出渲染与错误映射。入口层只做薄壳,业务编排统一在 `domains/`。
## 文件职责
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `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` 子类。
## 嵌入调用与流式输出
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
参数解析与运行时初始化也经过统一异常边界。`--json` 的错误对象继续写入 `stdout`,保留退出码和恢复建议;人类日志写入 `stderr`。`help <域>`、`<域> --help` 支持同一份域别名,帮助主题不存在时返回用法错误。处理器自身保留的详细用法说明仍可供直接嵌入调用使用。
优先用 `--corp` 明确指定企业。短参数 `-c` 在命令之前表示全局企业选择;在声明了同名参数的命令之后,遵循该命令的含义(例如 `bill list -c` 为单号)。布尔值可写 `--active=false` 或 `--active false`;数字形式使用 `=0` / `=1`,空格后的数字保留为可能的位置 ID。`--` 之后的内容全部作为位置参数。
`hose-use mcp [serve]` 在当前进程启动服务,不派生 Bun 或访问源码脚本;MCP 调用继续只通过 `hose_cli` 分发,流式终端回调不会被注入协议通道。
`update --dry-run` 返回源码或二进制更新计划,不请求发布源、不执行 git/依赖安装、不替换二进制或同步技能;`update check` 和发布历史查询保留只读查询行为。
+33
View File
@@ -0,0 +1,33 @@
import { afterEach, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { runAiProCli } from "../aipro-cli.js";
import { runCli } from "./runner.js";
import { closeDatabase } from "../core/db/index.js";
const keys = ["HOSE_APPROVAL_DB", "HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
const original = keys.map(key => process.env[key]);
afterEach(() => { closeDatabase(); keys.forEach((key, i) => { if (original[i] === undefined) delete process.env[key]; else process.env[key] = original[i]; }); });
test("approval and aipro dry-runs override apply/yes without requests or database creation", async () => {
const root = mkdtempSync(join(tmpdir(), "hose-approval-preview-"));
const corps = join(root, "corps"); mkdirSync(corps);
writeFileSync(join(corps, "corp.json"), JSON.stringify({ id: "corp", name: "Preview", source: "manual", credentials: { accessToken: "fixture", corpId: "corp", staffId: "staff" } }));
process.env.HOSE_ENTERPRISES_DIR = corps;
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
process.env.HOSE_APPROVAL_DB = join(root, "approval.db");
const originalFetch = globalThis.fetch;
let requests = 0;
globalThis.fetch = (async () => { requests++; throw new Error("No network during preview"); }) as any;
try {
for (const action of ["points", "review", "decide", "approve", "reject"]) {
const result = await runCli(["approval", action, "SN", "--apply", "--yes", "--dry-run", "--json"]);
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
}
for (const action of ["init", "bind", "review", "decide", "approve", "reject"]) {
const result = await runAiProCli([action, "approve", "--run", "ABC123", "--apply", "--yes", "--dry-run", "--json"]);
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-use aipro ");
}
expect(requests).toBe(0); expect(existsSync(process.env.HOSE_APPROVAL_DB)).toBe(false);
} finally { globalThis.fetch = originalFetch; }
});
+142
View File
@@ -0,0 +1,142 @@
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("workflow imports use the module directories after the platform migration", () => {
const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/;
const violations: string[] = [];
for (const file of collectTsFiles(SRC_ROOT, true)) {
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
const target = resolveImportRelativeToSrc(file, specifier);
if (target && legacy.test(target)) violations.push(`${relative(SRC_ROOT, file)} -> ${target}`);
}
}
expect(violations).toEqual([]);
});
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([]);
});
});
+861
View File
@@ -0,0 +1,861 @@
/** Static command vocabulary shared by dispatch, parsing and help. No handler imports. */
export type FlagKind = "boolean" | "value" | "boolean-or-value";
export interface HelpTopic {
summary: string; usage: string; commands: Record<string, string>; options?: string[];
}
export interface CliCommandMetadata extends HelpTopic {
aliases: string[]; commandAliases: Record<string, string>; flags: Record<string, FlagKind>;
}
export const GLOBAL_FLAGS: Record<string, FlagKind> = {
...Object.fromEntries("json j help h ? version v V full allow-full allowFull summary stateless stateful dry-run dryRun dryrun yes y confirm force-write forceWrite force".split(" ").map(k => [k, "boolean" as const])),
...Object.fromEntries("corp c output-file outputFile o".split(" ").map(k => [k, "value" as const])),
};
function flagList(keys: string, kind: FlagKind): Record<string, FlagKind> {
return Object.fromEntries(keys.split(" ").filter(Boolean).map(key => [key, kind]));
}
export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"context": {
"summary": "全局运行上下文与身份诊断",
"usage": "hose-use context [--json]",
"commands": {
"context": "输出当前企业、账号、运行模式与认证状态"
},
"aliases": [
"status",
"whoami",
"env"
],
"commandAliases": {},
flags: { }
},
"aipro": {
"summary": "AI PRO 确定性审批仲裁",
"usage": "hose-use aipro <子命令>",
"commands": {
"status": "查看网关状态",
"bind": "绑定单据",
"review": "核验要点",
"decide": "执行仲裁",
"init": "初始化审批上下文",
"scopes": "列出审批规则场景",
"translate": "转译单据",
"rules": "查看审批规则",
"points": "查看审核要点",
"checklist": "查看核验清单",
"logs": "查看审批日志",
"help": "help 命令"
},
"aliases": [],
"commandAliases": {
"whoami": "status",
"context": "status",
"info": "status",
"start": "init",
"index": "scopes",
"indexes": "scopes",
"doc": "translate",
"markdown": "translate",
"render": "translate",
"rule": "rules",
"mount": "bind",
"clauses": "points",
"list": "checklist",
"eval": "review",
"evaluate": "review",
"approve": "decide",
"reject": "decide",
"log": "logs",
"history": "logs",
"trail": "logs"
},
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
},
"auth": {
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
"usage": "hose-use auth <子命令>",
"commands": {
"login": "登录并保存企业凭证",
"status": "查看当前认证状态",
"refresh": "刷新账号或企业 AccessToken",
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
"extract-keys": "从协助链接提取 OpenAPI 密钥",
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
"accounts": "列出已保存账号",
"switch-account": "切换默认账号",
"import": "导入抓包或协助凭证",
"hose-link": "生成企业免密登录链接",
"sync-seal": "导入已保存的企业配置"
},
"aliases": [
"login"
],
"commandAliases": {
"whoami": "status",
"current": "status",
"renew": "refresh",
"add": "import",
"import-link": "add-link",
"auth-link": "hose-link",
"login-link": "hose-link",
"add-hose-persistent": "add-persistent",
"add-openapi": "add-persistent",
"add-hose": "add-persistent",
"extract-key": "extract-keys",
"hose-extract-keys": "extract-keys",
"extract-hose-keys": "extract-keys",
"elevate-hose": "elevate",
"sync-from-seal": "sync-seal",
"import-seal": "sync-seal",
"list": "accounts",
"account": "accounts",
"accs": "accounts",
"switch": "switch-account",
"use-account": "switch-account"
},
flags: { ...flagList("a p app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user accessToken account curl headers phone pwd raw token", "value"), ...flagList("add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite persist plain prod production r refresh reveal save save-staff t test upgrade-all verify i interactive sms sync", "boolean") }
},
"corps": {
"summary": "多企业租户管理",
"usage": "hose-use corps <子命令>",
"commands": {
"list": "列出本地企业配置",
"search": "搜索企业与员工",
"switch": "切换当前工作企业",
"current": "查看当前企业",
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
"extract-keys": "从协助链接提取 OpenAPI 密钥",
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
"tag": "标记企业环境",
"hose-link": "生成企业免密登录链接",
"sync-seal": "导入已有企业配置",
"probe-hose": "检查企业接口连通性",
"hose-staffs": "查询企业员工",
"help": "help 命令"
},
"aliases": [
"corp"
],
"commandAliases": {
"ls": "list",
"find": "search",
"query": "search",
"filter": "search",
"set-env": "tag",
"mark": "tag",
"use": "switch",
"whoami": "current",
"status": "current",
"active": "current",
"import-link": "add-link",
"auth-link": "hose-link",
"login-link": "hose-link",
"add-hose-persistent": "add-persistent",
"add-openapi": "add-persistent",
"add-hose": "add-persistent",
"extract-key": "extract-keys",
"hose-extract-keys": "extract-keys",
"extract-hose-keys": "extract-keys",
"elevate-hose": "elevate",
"sync-from-seal": "sync-seal",
"import-seal": "sync-seal"
},
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
},
"config": {
"summary": "全局运行模式与路径配置",
"usage": "hose-use config <子命令>",
"commands": {
"paths": "诊断配置目录链",
"get": "查看全局配置",
"mode": "切换 stateful/stateless",
"set": "更新指定配置项",
"test-dir": "设置测试企业目录"
},
"aliases": [
"mode"
],
"commandAliases": {
"path": "paths",
"dirs": "paths",
"show": "paths",
"list": "paths",
"status": "get",
"info": "get",
"test-enterprises-dir": "test-dir"
},
flags: { ...flagList("clear", "boolean") }
},
"workflow": {
"summary": "工作流查询、草稿、运行排障与生命周期管理",
"usage": "hose-use workflow <子命令> [参数] [选项]",
"commands": {
"list": "列出工作流",
"get": "查看工作流详情",
"find": "按节点类型搜索",
"analyze": "静态分析工作流(含禁用/SKIP/联动覆盖检查)",
"job": "查看单次运行实例树、报错节点与MVEL日志",
"diff": "对比两个工作流快照的结构与脚本差异",
"diff-job": "对比两次执行的节点分支与报错发散点",
"test": "端到端一键调试单据(替代前端手工调测)",
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
"nodes": "查询企业已开通工作流节点字典或开通灰度节点 (list|grant)",
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
"create": "从零新建工作流草稿",
"copy": "复制克隆工作流",
"delete": "删除工作流",
"patch": "生成草稿字段补丁",
"save": "保存草稿到远端",
"toggle": "切换启停状态",
"publish": "发布并启用工作流",
"history": "查看版本历史",
"logs": "查看运行日志",
"check": "检查错误管道",
"enum": "查询在线枚举字典(不可用时使用内置字典)",
"lint-script": "静态检查 JavaScript / MVEL 脚本",
"eval-script": "在本地沙箱中模拟执行脚本"
},
"options": [
"--flow=<单号> 指定测试单据",
"--file=<workflow.json> 指定工作流快照",
"--failed 只看失败节点",
"--parent=<executionId> 展开循环/分支子节点",
"--logs=<executionId> 查看节点执行日志",
"--dry-run 只预览写操作",
"--yes/--confirm 确认写操作"
],
"aliases": [
"workflows",
"wf"
],
"commandAliases": {
"list-all": "list",
"ls": "list",
"detail": "get",
"info": "get",
"search": "find",
"enable": "publish",
"update": "save",
"snapshots": "history",
"log": "logs",
"execution": "job",
"health": "check",
"analyse": "analyze",
"diff-snapshot": "diff",
"diff-snapshots": "diff",
"compare": "diff",
"diff-jobs": "diff-job",
"compare-job": "diff-job",
"debug": "test",
"run-test": "test",
"cp": "copy",
"clone": "copy",
"rm": "delete",
"remove": "delete",
"new": "create",
"add": "create",
"nodes": "node",
"watch": "tail",
"follow": "tail",
"lint": "lint-script",
"lint-code": "lint-script",
"eval": "eval-script",
"eval-code": "eval-script",
"run-script": "eval-script",
"enums": "enum",
"dictionary": "enum",
"dict": "enum"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a admin-key adminKey after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
"usage": "hose-use bill <子命令> [单号|ID] [选项]",
"commands": {
"list": "查询单据",
"get": "查看单据详情",
"spec": "查看单据模板字段配置与联动覆盖规则",
"flow": "查看审批流程",
"approve": "同意审批",
"reject": "驳回审批",
"transfer": "转交审批",
"add-node": "加签审批",
"comment": "添加评论",
"trace": "穿透诊断单据与当前待办",
"schema": "查看单据实体模型",
"risk": "查看风险信息",
"budget": "查看预算状态",
"refs": "解析关联人员与部门",
"relations": "查看关联单据",
"attachments": "列出附件",
"download": "下载附件",
"link": "生成单据详情链接"
},
"options": [
"--dry-run 只预览审批动作",
"--yes/--confirm 确认执行审批动作",
"--comment=<原因> 驳回或评论内容"
],
"aliases": [
"bills",
"fee",
"fees",
"invoice",
"invoices"
],
"commandAliases": {
"agree": "approve",
"deny": "reject",
"shift": "transfer",
"addnode": "add-node",
"countersign": "add-node",
"counter-sign": "add-node",
"remark": "comment",
"search": "list",
"show": "get",
"find": "get",
"inspect": "trace",
"diagnose": "trace",
"schemas": "schema",
"entities": "schema",
"records": "flow",
"timeline": "flow",
"review": "risk",
"warnings": "risk",
"budgets": "budget",
"references": "refs",
"resolve": "refs",
"relation": "relations",
"links": "relations",
"attachment": "attachments",
"files": "attachments",
"file-download": "download",
"url": "link",
"specification": "spec"
},
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
},
"flow": {
"summary": "审批流全域透视与穿透诊断",
"usage": "hose-use flow <子命令> [单号|ID]",
"commands": {
"get": "穿透诊断单据流转",
"history": "查看审批流转时间线",
"risk": "查看风险信息",
"list": "查询单据",
"approve": "审批同意",
"reject": "审批驳回"
},
"aliases": [
"flows",
"trace"
],
"commandAliases": {
"records": "history",
"timeline": "history",
"search": "list",
"agree": "approve",
"deny": "reject",
"trace": "get",
"inspect": "get",
"diagnose": "get",
"show": "get",
"find": "get"
},
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
},
"contact": {
"summary": "企业通讯录与人员检索",
"usage": "hose-use contact <子命令>",
"commands": {
"list": "列出员工",
"search": "搜索员工",
"get": "查看员工详情"
},
"aliases": [
"contacts",
"staff",
"staffs"
],
"commandAliases": {},
flags: { ...flagList("id k keyword l limit query staff-id", "value") }
},
"task": {
"summary": "待办中心与审批任务",
"usage": "hose-use task <子命令>",
"commands": {
"todo": "待我审批",
"approved": "我已审批",
"submitted": "我发起的",
"records": "审批记录",
"cc": "抄送任务"
},
"aliases": [
"tasks",
"todo"
],
"commandAliases": {},
flags: { ...flagList("read unread", "boolean"), ...flagList("count end-date from limit n offset staff staff-id staffId start start-date to", "value") }
},
"dimension": {
"summary": "系统与自定义档案维度",
"usage": "hose-use dimension <子命令>",
"commands": {
"list": "列出维度",
"items": "列出维度项"
},
"aliases": [
"dimensions",
"archive",
"archives"
],
"commandAliases": {},
flags: { ...flagList("code count dimension id keyword limit n name q query", "value") }
},
"feetype": {
"summary": "费用类型全生命周期管理与模板规格查询",
"usage": "hose-use feetype <子命令> [参数]",
"commands": {
"list": "查看费用类型树",
"get": "查看详情与字段",
"spec": "查看单据/申请模板字段与联动规则",
"create": "新建费用类型",
"update": "修改属性",
"disable": "停用",
"enable": "启用",
"move": "移动层级",
"fields": "查看字段配置"
},
"options": [
"--dry-run 只预览写操作",
"--yes/--confirm 确认写操作"
],
"aliases": [
"feetypes",
"fee-type",
"fee-types",
"expense-type",
"expense-types",
"costtype"
],
"commandAliases": {},
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
},
"role": {
"summary": "企业角色定义与成员",
"usage": "hose-use role <子命令>",
"commands": {
"list": "列出角色",
"groups": "列出角色组",
"members": "查看角色成员"
},
"aliases": [
"roles"
],
"commandAliases": {},
flags: { ...flagList("code count id keyword limit n name q query role", "value") }
},
"permission": {
"summary": "权限模型快照",
"usage": "hose-use permission get",
"commands": {
"get": "查看角色权限开关"
},
"aliases": [
"permissions"
],
"commandAliases": {},
flags: { }
},
"rule": {
"summary": "本地审批规约管理",
"usage": "hose-use rule <子命令> [参数]",
"commands": {
"scopes": "列出适用场景",
"scope": "查看场景明细",
"list": "列出规则",
"get": "查看规则详情",
"add": "新增规则",
"delete": "删除规则"
},
"options": [
"--dry-run 只预览增删",
"--yes/--confirm 确认增删"
],
"aliases": [
"rules"
],
"commandAliases": {},
flags: { ...flagList("all", "boolean"), ...flagList("b body code id index name s scope status target", "value") }
},
"approval": {
"summary": "确定性审批网关与要点仲裁",
"usage": "hose-use approval audit <子命令> [单号]",
"commands": {
"points": "查看审核要点",
"checklist": "查看核验清单",
"review": "核验事实",
"decide": "生成或执行仲裁决定",
"audit": "审批核验与仲裁入口"
},
"options": [
"--apply --yes 执行真实审批流转"
],
"aliases": [
"approvals",
"audit"
],
"commandAliases": {},
flags: { ...flagList("apply confirm do execute run y yes", "boolean"), ...flagList("action code comment data e eval evidence findings i id index m message p point proof r reason reasoning s scope sn state status target", "value") }
},
"message": {
"summary": "消息中心与通知管理",
"usage": "hose-use message <子命令>",
"commands": {
"list": "查询消息",
"count": "查看未读数",
"read": "标记消息已读",
"read-all": "全部标记已读"
},
"aliases": [
"messages",
"notify",
"notifications"
],
"commandAliases": {},
flags: { ...flagList("all read unread", "boolean"), ...flagList("count id limit message-id message-type n offset start type", "value") }
},
"platform": {
"summary": "自建应用、业务对象、全量记录安全更新与台账体检",
"usage": "hose-use platform <子命令> [参数]",
"commands": {
"list": "列出自建应用",
"entities": "列出业务对象",
"schema": "查看字段定义",
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
"permissions": "查看权限",
"imports": "查看导入任务",
"get": "查看应用详情"
},
"options": [
"--all 自动翻页拉取全量记录",
"--ndjson 流式逐行下发 JSON Lines ($O(1)内存)",
"--flat 剥离底层实体动态字段前缀并提取引用",
"--stats 输出总数/启停/重名/编码规则聚类画像",
"--dry-run 只预览记录写操作",
"--yes/--confirm 确认记录写操作",
"--raw 跳过安全合并直接发送原始补丁"
],
"aliases": [
"platforms",
"datalink",
"data-link"
],
"commandAliases": {
"ls": "list",
"apps": "list",
"show": "get",
"objects": "entities",
"fields": "schema",
"data": "records",
"search": "records",
"stats": "records",
"profile": "records",
"check": "audit",
"health": "audit",
"record-get": "record",
"record-toggle": "record",
"record-edit": "record",
"record-batch-edit": "record",
"batch-edit": "record",
"record-update": "record",
"update": "record",
"batch-update": "record",
"record-recompute": "record",
"permission": "permissions",
"auth": "permissions",
"import-jobs": "imports"
},
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
},
"app": {
"summary": "桌面端工作台应用管理",
"usage": "hose-use app <子命令>",
"commands": {
"list": "列出应用",
"get": "查看应用详情"
},
"aliases": [
"apps",
"workbench"
],
"commandAliases": {
"ls": "list",
"apps": "list",
"workbench": "list",
"show": "get"
},
flags: { ...flagList("app id k keyword name q query", "value") }
},
"menu": {
"summary": "桌面端主导航菜单树",
"usage": "hose-use menu list",
"commands": {
"list": "查看主导航",
"apps": "查看应用入口"
},
"aliases": [
"menus"
],
"commandAliases": {
"workbench": "apps",
"ls": "list",
"tree": "list"
},
flags: { }
},
"skill": {
"summary": "Agent Skill 管理",
"usage": "hose-use skill <install|status|dump>",
"commands": {
"install": "安装内嵌 Skill",
"status": "查看安装状态",
"dump": "导出 Skill 文件"
},
"aliases": [
"skills"
],
"commandAliases": {
"cat": "dump",
"show": "dump",
"init": "install",
"sync": "install",
"get": "status"
},
flags: { ...flagList("local workspace", "boolean"), ...flagList("dir target", "value") }
},
"probe": {
"summary": "企业连通性诊断",
"usage": "hose-use probe [corpId]",
"commands": {
"probe": "检查认证与 API 连通性"
},
"aliases": [
"diagnose"
],
"commandAliases": {},
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
},
"update": {
"summary": "版本自更新与发布记录",
"usage": "hose-use update [check|--changelog]",
"commands": {
"update": "检查并升级版本",
"check": "只检查可用版本",
"changelog": "查看发布记录"
},
"aliases": [
"upgrade",
"self-update",
"changelog"
],
"commandAliases": {},
flags: { ...flagList("c changelog check check-only f force gh gitea github l log mirror yingqing", "boolean"), ...flagList("limit n repo t tag target version", "value") }
},
"openapi": {
"summary": "OpenAPI 规范导出与路径查询",
"usage": "hose-use openapi [paths|info|--raw|keys]",
"commands": {
"paths": "列出路径概要",
"info": "查看规范元数据",
"keys": "查看企业接入密钥",
"dump": "导出规范"
},
"aliases": [
"schema",
"spec"
],
"commandAliases": {
"list": "paths",
"ls": "paths",
"summary": "info",
"export": "dump",
"raw": "dump"
},
flags: { ...flagList("raw elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
},
"keys": {
"summary": "企业 OpenAPI 接入凭证",
"usage": "hose-use keys [--json] [--reveal] [--save]",
"commands": {
"keys": "读取当前企业密钥(默认脱敏)"
},
"options": [
"--reveal 仅在明确授权后查看明文",
"--save --yes 提取并持久化保存到本地企业配置"
],
"aliases": [
"key",
"secret",
"secrets"
],
"commandAliases": {},
flags: { ...flagList("elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
},
"store": {
"summary": "已购应用与应用商店探查",
"usage": "hose-use store <list|search|get>",
"commands": {
"list": "列出已购应用",
"search": "搜索应用商店",
"get": "查看应用详情",
"keys": "查看企业接入密钥"
},
"aliases": [
"market"
],
"commandAliases": {
"key": "keys",
"ls": "list",
"find": "search",
"info": "get",
"detail": "get"
},
flags: { ...flagList("a all elevate f force persist plain r reveal save", "boolean"), ...flagList("id k keyword name app-key appKey key-id keyId", "value") }
},
"http": {
"summary": "轻量 HTTP Server 与交互文档",
"usage": "hose-use http [--port=<port>]",
"commands": {
"http": "启动 HTTP 服务"
},
"aliases": [
"server",
"web"
],
"commandAliases": {},
flags: { ...flagList("h", "boolean-or-value"), ...flagList("host p port", "value") }
},
"service": {
"summary": "常驻守护进程管理",
"usage": "hose-use service <start|stop|restart|status|logs|poll>",
"commands": {
"start": "启动服务",
"stop": "停止服务",
"restart": "重启服务",
"status": "查看服务状态",
"logs": "查看服务日志",
"poll": "轮询事件"
},
"aliases": [
"daemon"
],
"commandAliases": {},
flags: { ...flagList("count host limit n p port state-file stateFile", "value"), ...flagList("h", "boolean-or-value") }
},
"mcp": {
"summary": "MCP Server",
"usage": "hose-use mcp serve",
"commands": {
"serve": "启动 MCP 服务"
},
"aliases": [],
"commandAliases": {},
flags: { }
},
"assist-platform": {
"summary": "合思协助/运营平台 (Assist Platform) 自动化运维",
"usage": "hose-use assist-platform <子命令> [参数] [选项]",
"commands": {
"login": "查看或保存协助平台凭证会话",
"search": "在协助中心 34 万家企业库中分页检索企业",
"detail": "查看企业详细业务配置与开通商品能力",
"tickets": "查询指定企业的协助工单与授权码",
"staff": "查询企业内部员工工号与角色",
"apply": "向目标企业发起新的协助授权工单申请",
"approve": "审批通过协助授权工单申请(端内管理员授权)",
"enter": "一键换取免密直通链接并落盘为本地工作企业",
"transfer": "转交协助工单权限给其他同事",
"help": "查看帮助信息"
},
"aliases": [
"assist-center",
"ap"
],
"commandAliases": {
"auth": "login",
"status": "login",
"find": "search",
"list": "search",
"ls": "search",
"info": "detail",
"config": "detail",
"ticket": "tickets",
"order": "tickets",
"orders": "tickets",
"user": "staff",
"users": "staff",
"apply": "apply",
"create": "apply",
"request": "apply",
"new": "apply",
"approve": "approve",
"authorize": "approve",
"pass": "approve",
"import": "enter",
"token": "enter",
"get-token": "enter",
"transfer": "transfer",
"transmit": "transfer",
"forward": "transfer"
},
flags: {
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
...flagList("logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
}
}
};
export function resolveCommandMetadata(area?: string): { area: string; metadata: CliCommandMetadata } | undefined {
if (!area) return undefined;
const normalized = area.toLowerCase();
for (const [name, metadata] of Object.entries(COMMAND_METADATA)) {
if (name === normalized || metadata.aliases.includes(normalized)) return { area: name, metadata };
}
}
export function resolveCommandAction(area: string | undefined, action?: string): string | undefined {
const metadata = resolveCommandMetadata(area)?.metadata;
const key = action?.toLowerCase();
return key ? (metadata && Object.hasOwn(metadata.commandAliases, key) ? metadata.commandAliases[key] : key) : undefined;
}
export function localCommandFlags(area?: string, action?: string): Record<string, FlagKind> {
const resolved = resolveCommandMetadata(area);
const flags = { ...resolved?.metadata.flags };
const canonical = resolveCommandAction(area, action);
// Most commands retain -c as the global corp selector. A few actions declare
// a local meaning (bill code, node code, batch concurrency or bound rule codes).
const localC = resolved?.area === "update"
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|| (resolved?.area === "workflow" && canonical === "node")
|| (resolved?.area === "platform" && canonical === "record")
|| (resolved?.area === "aipro" && canonical === "bind");
if (!localC) delete flags.c;
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
// --run historically accepts a session ID and, for decide, an apply boolean.
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
return flags;
}
export function commandFlags(area?: string, action?: string): Record<string, FlagKind> {
return { ...GLOBAL_FLAGS, ...localCommandFlags(area, action) };
}
+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 };
}
@@ -0,0 +1,30 @@
import { afterEach, expect, mock, spyOn, test } from "bun:test";
import { getDatabase, closeDatabase } from "../../../core/db/index.js";
import { ApprovalRepository } from "../../../domains/approval/repository.js";
import * as bills from "../../../domains/bill/tools.js";
import { handleAiProDecide } from "./session.js";
afterEach(() => { closeDatabase(); });
for (const action of ["approve", "reject"] as const) {
test(`blocks cross-corp ${action} before creating a client or changing the run`, async () => {
const repo = new ApprovalRepository(getDatabase(":memory:"));
const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" });
repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: action === "approve" ? "PASS" : "FAIL" }]);
const getClient = mock(async () => ({ client: {} as any, corpId: "corp-B" }));
await expect(handleAiProDecide({ repo, corpId: "corp-B", command: action, positional: [action, run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient } as any)).rejects.toThrow("不一致");
expect(getClient).not.toHaveBeenCalled();
expect(repo.getRunById(run.id)?.decision).toBe("PENDING");
});
}
test("uses the checked corp client for same-corp approval", async () => {
const repo = new ApprovalRepository(getDatabase(":memory:"));
const run = repo.createApprovalRun({ documentSn: "SAME-SN", corpId: "corp-A" });
repo.injectFindings(run.id, [{ clauseText: "invoice", strictness: "硬性", checkStatus: "PASS" }]);
const approve = spyOn(bills, "approveBill").mockResolvedValue({} as any);
const client = {} as any;
try {
const result = await handleAiProDecide({ repo, corpId: "corp-A", command: "approve", positional: ["approve", run.shortId!], parsed: { options: { apply: true, yes: true, opinion: "checked" } }, getClient: async () => ({ client, corpId: "corp-A" }), rawArgs: [], operator: "staff" } as any);
expect(result.exitCode).toBe(0);
expect(approve).toHaveBeenCalledWith(client, "corp-A", "SAME-SN", { comment: "checked" });
} finally { approve.mockRestore(); }
});
+504
View File
@@ -0,0 +1,504 @@
import { PermissionError } from "../../../core/errors.js";
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) {
if (!runRecord.corpId || ctx.corpId !== runRecord.corpId) {
throw new PermissionError(`审批会话所属企业 [${runRecord.corpId || "未知"}] 与当前企业 [${ctx.corpId || "未选择"}] 不一致,请显式选择会话所属企业。`);
}
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 (context.corpId !== runRecord.corpId) throw new PermissionError("审批客户端企业与会话所属企业不一致");
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, undefined, { allowExpired: true });
} else if (targetSn) {
const maybeRun = repo.getRunByHandle(targetSn, undefined, { allowExpired: true });
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,
};
}
}
+335
View File
@@ -0,0 +1,335 @@
import { isDryRun, mutationPreview } from "../mutation.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, booleanOption, numberOption } from "../parser.js";
import { createSessionClient } from "../../core/http/session-client.js";
import {
ApprovalService,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "../../domains/approval/index.js";
export async function handleApprovalCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const corpId = corp.corpId || corp.id;
// 解析命令层级:
// 形式 A: hose-use approval audit points S26000001
// 形式 B: hose-use approval points S26000001
// 形式 C: hose-use approval audit S26000001
let subAction = parsed.action?.toLowerCase();
let args = [...parsed.args];
if (subAction === "audit" && args.length > 0) {
const candidateSub = args[0]?.toLowerCase();
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
subAction = candidateSub;
args.shift();
}
}
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
if (targetSn && isDryRun(parsed, runtime) && ["audit", "points", "inject", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(subAction || "audit")) {
return mutationPreview(parsed, runtime, "预览审批操作", targetSn, { action: subAction || "audit", corpId, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
}
const client = await createSessionClient(corp);
const service = new ApprovalService();
switch (subAction) {
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
return {
stdout: title + table + tip,
stderr: "",
exitCode: 0,
};
}
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
if (!run || findings.length === 0) {
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
return {
stdout: title + table,
stderr: "",
exitCode: 0,
};
}
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({
index: pointIndex,
status: statusInput,
evidence,
reasoning,
});
} else if (evalStr) {
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({
index: idx,
status,
evidence: desc,
reasoning: desc,
});
}
}
}
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
try {
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
const msg =
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
}
throw err;
}
}
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("../helpers.js");
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
try {
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
return {
stdout: outLines.join("\n"),
stderr: "",
exitCode: 0,
};
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
throw err;
}
}
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
case "audit":
case undefined: {
if (!targetSn) {
return {
stdout:
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
`用法:\n` +
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
stderr: "",
exitCode: 0,
};
}
// 检查当前是否已注入要点
const { run } = service.getAuditChecklist(targetSn, corpId);
if (!run) {
// 自动触发第一步:注入并出审核要点
return await handleApprovalCommand(
{ ...parsed, action: "points", args: [targetSn] },
runtime
);
} else {
// 已有要点,展示清单与进度
return await handleApprovalCommand(
{ ...parsed, action: "checklist", args: [targetSn] },
runtime
);
}
}
default:
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
}
}
+263
View File
@@ -0,0 +1,263 @@
import { describe, expect, it, beforeEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { handleAssistPlatformCommand } from "./assist-platform/index.js";
import {
saveAssistPlatformSession,
clearAssistPlatformSession,
} from "../../core/auth/assist-platform-store.js";
import type { CliParsedArgs, CliRuntime } from "../types.js";
function createMockRuntime(enterprisesDir: string): CliRuntime {
return {
jsonMode: false,
selectedCorp: null,
corpContext: {
enterprisesDir,
corps: new Map(),
stateful: true,
current: undefined,
defaultCorpId: undefined,
getCorp: () => undefined,
switchCorp: () => true,
listCorps: () => [],
getAllCorps: () => [],
} as any,
};
}
describe("CLI Commands - assist-platform (合思协助平台)", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-assist-test-"));
process.env.HOSE_STATE_DIR = tempDir;
clearAssistPlatformSession();
});
it("assist-platform help 输出完整使用指南与子命令", async () => {
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "help",
args: [],
options: {},
raw: ["assist-platform", "help"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("合思协助平台");
expect(res.stdout).toContain("login");
expect(res.stdout).toContain("search");
expect(res.stdout).toContain("tickets");
expect(res.stdout).toContain("enter");
expect(res.stdout).toContain("assist-center");
});
it("assist-platform login 无凭证时给出指引", async () => {
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "login",
args: [],
options: {},
raw: ["assist-platform", "login"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未检测到协助平台登录凭证");
});
it("assist-platform login --logout 能够注销凭证", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "login",
args: [],
options: { logout: true },
raw: ["assist-platform", "login", "--logout"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("已成功注销");
});
it("未登录时运行 tickets 提示需要先登录", async () => {
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "tickets",
args: ["Cxa3oOtQi2eS$g"],
options: {},
raw: ["assist-platform", "tickets", "Cxa3oOtQi2eS$g"],
};
try {
await handleAssistPlatformCommand(parsed, runtime);
expect(true).toBe(false);
} catch (err: any) {
expect(err.message).toContain("未检测到协助平台登录凭证");
}
});
it("assist-platform enter --save --dry-run 能够输出变更预览", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "enter",
args: ["Cxa3oOtQi2eS$g"],
options: { save: true, dryRun: true },
raw: ["assist-platform", "enter", "Cxa3oOtQi2eS$g", "--save", "--dry-run"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("Cxa3oOtQi2eS$g");
});
it("assist-platform apply --dry-run 能够输出申请工单变更预览", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "apply",
args: ["ID01KrLMQJWdMH"],
options: { dryRun: true, hours: 12, message: "测试联调" },
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--dry-run", "--hours", "12"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("ID01KrLMQJWdMH");
expect(res.stdout).toContain("12 小时");
});
it("assist-platform approve --dry-run 能够输出工单审批变更预览", async () => {
const runtime = createMockRuntime(tempDir);
runtime.selectedCorp = {
id: "ID01ofWoOC1wiX",
name: "沈玥妍测试企业",
corpId: "ID01ofWoOC1wiX",
credentials: { accessToken: "mock-token" },
} as any;
const parsed: CliParsedArgs = {
action: "approve",
args: ["ID01Xeno3GpoNV"],
options: { dryRun: true },
raw: ["assist-platform", "approve", "ID01Xeno3GpoNV", "--dry-run"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("ID01Xeno3GpoNV");
expect(res.stdout).toContain("同意授权");
});
it("assist-platform apply 传入超过 24 小时或多天时返回明确拒绝提示", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "apply",
args: ["ID01KrLMQJWdMH"],
options: { days: 2 },
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "2"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("申请协助时长不能超过 24 小时 (1 天)");
expect(res.stderr).toContain("2 天 (48 小时)");
expect(res.stderr).toContain("POST /api/assistPlatform/create");
expect(res.stderr).toContain("单次协助工单最长有效期限为 24 小时");
});
it("assist-platform apply --days 1 --dry-run 成功换算为 24 小时并预览", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "apply",
args: ["ID01KrLMQJWdMH"],
options: { days: 1, dryRun: true },
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "1", "--dry-run"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("24 小时");
});
it("assist-platform transfer 缺少 --to 参数时报错提示", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "transfer",
args: ["ID01ofWoOC1wiX"],
options: {},
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("必须通过 --to 指定接收人员姓名、工号或账号");
});
it("assist-platform transfer --dry-run 能够输出工单转交变更预览", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "transfer",
args: ["ID01ofWoOC1wiX", "ID01Xenwiu9w0D"],
options: { to: "陈龙", dryRun: true },
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("ID01Xenwiu9w0D");
expect(res.stdout).toContain("陈龙");
});
});
+110
View File
@@ -0,0 +1,110 @@
import { applyAssistTicket } from "../../../domains/assist-platform/services.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { numberOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleApply(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
runtime.selectedCorp?.id;
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform apply <企业ID> [--message <事由>] [--hours <小时数(1-24)>] [--dry-run/--yes]\n示例: hose-use assist-platform apply ID01KrLMQJWdMH --message \"测试环境接口联调\" --hours 24 --yes\n",
exitCode: 1,
};
}
const days = numberOption(parsed.options, ["days", "day"]);
let hours = numberOption(parsed.options, ["hours", "hour", "duration"]);
if (days !== undefined) {
hours = days * 24;
}
if (hours === undefined) {
hours = 24;
}
if (hours < 1 || hours > 24) {
return {
stdout: "",
stderr:
`[ERROR] 申请协助时长不能超过 24 小时 (1 天),当前传入: ${days !== undefined ? `${days} 天 (${hours} 小时)` : `${hours} 小时`}。\n` +
`提示: 合思协助平台服务端(POST /api/assistPlatform/create)实施了硬性安全限制:单次协助工单最长有效期限为 24 小时 (1天),超过 24 小时服务端将直接拒绝受理。\n` +
`如需持续协助支持,可在工单到期后再次快速发起或在端内续签。\n`,
exitCode: 1,
};
}
const message =
stringOption(parsed.options, ["message", "msg", "reason", "matter"]) ||
"测试环境接口联调与问题排查";
const targetCorp =
runtime.corpContext?.getAllCorps?.()?.find((c) => c.id === corpId || c.corpId === corpId) ||
(runtime.selectedCorp?.id === corpId || runtime.selectedCorp?.corpId === corpId
? runtime.selectedCorp
: undefined);
const corpName = targetCorp?.name || corpId;
const nextConfirmCmd = `hose-use assist-platform apply ${corpId} --message "${message}" --hours ${hours} --yes`;
// 写操作两阶段确认守卫
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"发起合思协助工单申请",
`${corpName} (${corpId})`,
{
申请事项: message,
申请时长: `${hours} 小时 (${hours * 3600 * 1000} ms)`,
初始状态: "待提供 (需企业管理员在端内开启授权)",
}
);
}
requireMutationConfirmation(
parsed,
runtime,
`向企业 [${corpName}] 发起协助授权申请 (时长: ${hours}h, 事由: ${message})`,
nextConfirmCmd
);
const res = await applyAssistTicket(client, {
corporationId: corpId,
applyMessage: message,
assistTime: hours * 3600 * 1000,
});
if (runtime.jsonMode) {
return {
stdout: printJson(res, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, string> = {
企业名称: corpName,
企业ID: res.corporationId,
新建工单ID: res.id,
工单状态: "🟡 待提供 (等待客户管理员在企业端授权)",
申请时长: `${hours} 小时`,
申请事项: res.applyMessage,
申请人: res.userName || "运营实施人员",
};
return {
stdout: `====== 合思协助工单申请提交成功 ======\n${printKeyValue(pairs)}\n\n后续步骤:\n 1. 提示企业管理员登录合思 Web/桌面端,在【远程协助/授权中心】确认开启授权;\n 2. 授权通过后工单变为【🟢 生效中】,即可运行: hose-use assist-platform enter ${corpId} --staff <员工姓名> --save --yes\n`,
stderr: "",
exitCode: 0,
};
}
+146
View File
@@ -0,0 +1,146 @@
import { createSessionClient } from "../../../core/http/session-client.js";
import {
approveAssistTicket,
listAssistTickets,
} from "../../../domains/assist-platform/services.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleApprove(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const explicitCorpId =
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
parsed.args[0] ||
runtime.selectedCorp?.id;
if (!explicitCorpId) {
return {
stdout: "",
stderr:
"用法: hose-use assist-platform approve [工单ID] [--corp <企业ID>] [--dry-run/--yes]\n" +
"示例: hose-use assist-platform approve ID01Xeno3GpoNV --corp ID01ofWoOC1wiX --yes\n" +
" hose-use assist-platform approve --corp ID01ofWoOC1wiX --yes (自动审批最新待授权工单)\n",
exitCode: 1,
};
}
// 1. 识别 corpId 与 ticketId
const allCorps = runtime.corpContext?.getAllCorps?.() || [];
let targetCorp =
allCorps.find((c) => c.id === explicitCorpId || c.corpId === explicitCorpId) ||
(runtime.selectedCorp?.id === explicitCorpId || runtime.selectedCorp?.corpId === explicitCorpId
? runtime.selectedCorp
: undefined);
let ticketId = stringOption(parsed.options, ["ticket", "ticket-id"]);
// 如果第 0 个参数不是企业,可能是工单编号
if (!targetCorp && parsed.args[0]) {
ticketId = parsed.args[0];
targetCorp = runtime.selectedCorp ?? undefined;
} else if (targetCorp && parsed.args[1]) {
ticketId = parsed.args[1];
}
if (!targetCorp) {
return {
stdout: "",
stderr: `[ERROR] 未在本地企业配置中找到企业 [${explicitCorpId}]。审批工单需要企业管理员权限凭证,请先确保目标企业已配置在本地并具备管理员会话。\n`,
exitCode: 1,
};
}
const corpName = targetCorp.name || targetCorp.id;
const actualCorpId = targetCorp.corpId || targetCorp.id;
// 2. 若未显式传入工单编号,自动查询该企业当前处于【待提供】(status: 0) 的工单
if (!ticketId) {
try {
const assistClient = resolveAssistClient(parsed, runtime);
const tickets = await listAssistTickets(assistClient, actualCorpId);
const pendingTicket = tickets.find(
(t) => t.state === "0" || t.state.includes("待提供")
);
if (pendingTicket?.ticketId) {
ticketId = pendingTicket.ticketId;
}
} catch {
// 容错降级
}
}
if (!ticketId) {
return {
stdout: "",
stderr: `[WARN] 企业 [${corpName}] (${actualCorpId}) 协助中心未查询到待授权的工单。可指定 --ticket <工单ID>,或使用 hose-use assist-platform tickets ${actualCorpId} 查看工单列表。\n`,
exitCode: 1,
};
}
const nextConfirmCmd = `hose-use assist-platform approve ${ticketId} --corp ${actualCorpId} --yes`;
// 3. 写操作两阶段确认守卫
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"审批通过合思协助授权申请",
`${corpName} (${actualCorpId})`,
{
工单编号: ticketId,
审批动作: "同意授权 (通过并生效)",
授权范围: "允许运维与技术实施人员在有效期限内免密进入系统协助",
}
);
}
requireMutationConfirmation(
parsed,
runtime,
`审批通过企业 [${corpName}] 的协助授权工单 [${ticketId}]`,
nextConfirmCmd
);
// 4. 调用企业会话客户端执行审批
const sessionClient = await createSessionClient(targetCorp);
const res = await approveAssistTicket(sessionClient, {
ticketId,
corporationId: actualCorpId,
status: 1,
});
if (runtime.jsonMode) {
return {
stdout: printJson(res, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const startStr = res.startTime ? new Date(res.startTime).toLocaleString("zh-CN", { hour12: false }) : "-";
const endStr = res.endTime ? new Date(res.endTime).toLocaleString("zh-CN", { hour12: false }) : "-";
const pairs: Record<string, string> = {
企业名称: corpName,
企业ID: res.corporationId,
授权工单: res.id,
工单状态: "🟢 生效中 (授权已开启)",
有效期限: `${startStr} 至 ${endStr}`,
申请事项: res.applyMessage || "-",
申请人: res.userName || "运营实施人员",
};
return {
stdout:
`====== 合思协助工单授权通过成功 ======\n${printKeyValue(pairs)}\n\n后续步骤:\n` +
` 1. 工单已处于生效状态,可直接换取免密链接调试: hose-use assist-platform enter ${actualCorpId} --save --yes\n` +
` 2. 查看实时工单列表: hose-use assist-platform tickets ${actualCorpId}\n`,
stderr: "",
exitCode: 0,
};
}
@@ -0,0 +1,27 @@
import { loadAssistPlatformSession } from "../../../core/auth/assist-platform-store.js";
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
import { stringOption } from "../../parser.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
import { AuthenticationError } from "../../../core/errors.js";
import type { KyInstance } from "ky";
export function resolveAssistClient(
parsed: CliParsedArgs,
_runtime: CliRuntime
): KyInstance {
const explicitToken = stringOption(parsed.options, ["token", "t"]);
const session = loadAssistPlatformSession();
const token = explicitToken || session?.token;
if (!token || !token.trim()) {
throw new AuthenticationError(
"未检测到协助平台登录凭证。请先运行: hose-use assist-platform login --token <TOKEN>"
);
}
return createAssistPlatformClient({
token: token.trim(),
hoseAccessToken: session?.hoseAccessToken,
baseUrl: session?.baseUrl,
});
}
@@ -0,0 +1,78 @@
import { getCorporationDetail } from "../../../domains/assist-platform/services.js";
import { stringOption } from "../../parser.js";
import { printJson, printKeyValue, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleDetail(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
runtime.selectedCorp?.id;
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform detail <企业ID>\n示例: hose-use assist-platform detail Cxa3oOtQi2eS$g\n",
exitCode: 1,
};
}
const detail = await getCorporationDetail(client, corpId);
if (runtime.jsonMode) {
return {
stdout: printJson(detail, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const corp = detail.corporation || {};
const basic = detail.basic || {};
const summaryPairs: Record<string, string> = {
企业名称: String(corp.name || "-"),
企业ID: String(corp.id || corpId),
基础状态: String(basic.status || corp.state || "-"),
付费模式: String(corp.payType || "-"),
部署集群: String(corp.platformName || "app"),
灰度版本: String(corp.grayver || "-"),
数据库版本: String(corp.dbVersion || "-"),
授权人数: String(basic.peopleCount || "-"),
生效时间: basic.startTime ? new Date(Number(basic.startTime)).toLocaleDateString() : "-",
到期时间: basic.endTime ? new Date(Number(basic.endTime)).toLocaleDateString() : "-",
};
const packageRows = detail.corporationPackageVos.map((p, i) => [
String(i + 1),
p.name,
p.packageId,
p.enable ? "🟢 已启用" : "⚪ 未开通",
]);
const packageTable = printTable(["#", "套餐版本", "套餐 ID", "开通状态"], packageRows);
const goodsRows = detail.otherGoodsList.slice(0, 30).map((g, i) => [
String(i + 1),
String(g.name || "-"),
String(g.catName || "-"),
String(g.status || "-"),
String(g.model || "-"),
]);
const goodsTable = printTable(["#", "商品/功能名称", "业务类别", "状态", "类型"], goodsRows);
const moreNotice = detail.otherGoodsList.length > 30
? `\n(已显示前 30 项商品能力,全部 ${detail.otherGoodsList.length} 项可使用 --json 查看)\n`
: "";
return {
stdout: `====== 企业 [${corpId}] 协助中心全量业务配置 ======\n${printKeyValue(summaryPairs)}\n\n--- 原生套餐包规格 ---\n${packageTable}\n\n--- 已开通商品与扩展能力 ---\n${goodsTable}${moreNotice}\n`,
stderr: "",
exitCode: 0,
};
}
+190
View File
@@ -0,0 +1,190 @@
import {
generateAssistSession,
importAssistSessionToLocal,
} from "../../../domains/assist-platform/services.js";
import type { AssistIdentityProfile } from "../../../domains/assist-platform/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
function formatIdentityLines(ident?: AssistIdentityProfile): {
profilePairs: Record<string, string>;
warningText: string;
} {
const profilePairs: Record<string, string> = {};
let warningText = "";
if (!ident) {
return { profilePairs, warningText };
}
profilePairs["获取员工身份"] = `${ident.staffName} (${ident.staffId || "-"})`;
if (ident.departmentName) profilePairs["所属部门"] = ident.departmentName;
if (ident.cellphone) profilePairs["绑定手机"] = ident.cellphone;
if (ident.roleNames.length > 0) profilePairs["所配角色清单"] = ident.roleNames.join("、");
if (ident.readablePermissions.length > 0) {
const permSummary = ident.readablePermissions.slice(0, 5).join("、");
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
}
if (ident.isSeniorExecutive && ident.riskWarning) {
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
warningText =
`\n⚠️ 【高阶管理人员权限风控警示 (Executive Role Risk Warning)】\n` +
`当前协助会话获取的是企业【${titles}】身份(${ident.staffName})。\n` +
`防范越权与误用守则:\n` +
` 1. 该身份在企业内具备高级审批、财务支配与全系统管理权限;\n` +
` 2. 经理与一线实施人员严禁代用高管身份进行业务审批通过或非授权表单提交;\n` +
` 3. 请严格将此会话权限限定在必要的系统排障、配置诊断与接口联调中!\n`;
}
return { profilePairs, warningText };
}
export async function handleEnter(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
runtime.selectedCorp?.id;
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform enter <企业ID> [--admin] [--staff <姓名>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n",
exitCode: 1,
};
}
const ticketId = stringOption(parsed.options, ["ticket", "ticket-id", "auth-code"]);
const staffName = stringOption(parsed.options, ["staff", "user", "name"]);
const forceAdmin = booleanOption(parsed.options, ["admin"]);
// 如果显式指定了 staffName 且未显式指定 --admin,则为用户模式;否则默认为管理员模式
const isAdmin = forceAdmin || !staffName;
const shouldSave = booleanOption(parsed.options, ["save", "import", "persist"]);
const shouldSwitch = booleanOption(parsed.options, ["switch", "current"]);
const overwrite = booleanOption(parsed.options, ["overwrite"]);
const saveName = stringOption(parsed.options, ["alias", "corp-name"]);
// 1. 若不要求保存落盘,仅生成直通免密链接输出
if (!shouldSave && !shouldSwitch) {
const sessionRes = await generateAssistSession(client, {
corpId,
ticketId,
isAdmin,
staffName,
});
if (runtime.jsonMode) {
return {
stdout: printJson(sessionRes, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, string> = {
企业ID: sessionRes.corporationId,
授权模式: sessionRes.isAdmin ? "👑 企业管理员 (Admin)" : `👤 普通员工 (${sessionRes.staffName || "-"})`,
授权工单: sessionRes.ticketId,
会话Token: sessionRes.token,
免密直通链接: sessionRes.loginUrl,
};
const { profilePairs, warningText } = formatIdentityLines(sessionRes.identity);
Object.assign(pairs, profilePairs);
return {
stdout:
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
`${warningText}\n操作提示:\n` +
` - 在浏览器中打开以上链接可直接进入协助调试工作台\n` +
` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`,
stderr: "",
exitCode: 0,
};
}
// 2. 要求持久化落盘 / 切换为工作企业
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"从协助平台换取免密凭证并落盘为本地企业配置",
saveName || `企业 [${corpId}]`,
{
corpId,
isAdmin,
staffName: staffName || null,
ticketId: ticketId || "自动选择最新有效工单",
switchCurrent: shouldSwitch,
overwrite,
}
);
}
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
requireMutationConfirmation(
parsed,
runtime,
`从协助平台换取凭证并导入企业 [${corpId}]`,
nextConfirmCmd
);
const { sessionResult, corpConfig } = await importAssistSessionToLocal(client, {
corpId,
ticketId,
isAdmin,
staffName,
saveName,
overwrite: overwrite ?? true,
});
// 若指定了 --switch,切换当前激活企业
if (shouldSwitch) {
runtime.corpContext.switchCorp(corpConfig.id, true);
}
if (runtime.jsonMode) {
return {
stdout: printJson({
success: true,
sessionResult,
enterprise: {
id: corpConfig.id,
name: corpConfig.name,
staffId: corpConfig.credentials.staffId,
hasOpenApi: Boolean(corpConfig.credentials.appKey),
switched: shouldSwitch,
},
}, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const successPairs: Record<string, string> = {
企业标识: corpConfig.id,
企业名称: corpConfig.name,
执行身份: sessionResult.isAdmin ? "👑 企业管理员" : `👤 ${sessionResult.staffName || "员工"} (${corpConfig.credentials.staffId})`,
授权工单: sessionResult.ticketId,
凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话",
配置文件: `enterprises/${corpConfig.id}.json`,
激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
};
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
Object.assign(successPairs, profilePairs);
return {
stdout: `[SUCCESS] 协助企业凭证获取并落盘成功!\n${printKeyValue(successPairs)}\n${warningText}`,
stderr: "",
exitCode: 0,
};
}
+118
View File
@@ -0,0 +1,118 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { handleLogin } from "./login.js";
import { handleSearch } from "./search.js";
import { handleDetail } from "./detail.js";
import { handleTickets } from "./tickets.js";
import { handleStaff } from "./staff.js";
import { handleEnter } from "./enter.js";
import { handleApply } from "./apply.js";
import { handleApprove } from "./approve.js";
import { handleTransfer } from "./transfer.js";
export async function handleAssistPlatformCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = (parsed.action || "help").toLowerCase();
switch (action) {
case "login":
case "auth":
case "status":
return handleLogin(parsed, runtime);
case "search":
case "find":
case "list":
case "ls":
return handleSearch(parsed, runtime);
case "detail":
case "info":
case "config":
return handleDetail(parsed, runtime);
case "tickets":
case "ticket":
case "order":
case "orders":
return handleTickets(parsed, runtime);
case "staff":
case "user":
case "users":
return handleStaff(parsed, runtime);
case "enter":
case "import":
case "token":
case "get-token":
return handleEnter(parsed, runtime);
case "apply":
case "create":
case "request":
case "new":
return handleApply(parsed, runtime);
case "approve":
case "authorize":
case "pass":
return handleApprove(parsed, runtime);
case "transfer":
case "transmit":
case "forward":
return handleTransfer(parsed, runtime);
case "help":
case "--help":
case "-h":
default:
return printHelp();
}
}
function printHelp(): CliResult {
const helpText = `用法: hose-use assist-platform <子命令> [参数] [选项]
别名: assist-center, ap
合思协助平台(https://unity.ekuaibao.com/platform-charge/)自动化运维交互命令。
提供跨企业 34万+ 检索、协助工单状态查询、员工定位与免密直通链接一键换票持久化能力。
子命令列表:
login 查看当前协助平台会话,或传入 --token <TOKEN> 进行登录保存
search <关键词> 在协助中心 34 万家企业库中分页检索企业
detail <企业ID> 查看企业全量业务配置(套餐规格、基础参数、已开通商品扩展能力)
tickets <企业ID> 查询指定企业的协助工单(申请人、授权码、剩余时长、工单状态)
staff <企业ID> <姓名> 查询企业内部指定员工的工号、账号、邮箱及 admin 属性
apply <企业ID> 向目标企业发起新的协助授权工单申请(待客户管理员审批)
approve [工单ID] 审批通过协助授权工单申请(端内管理员通过授权)
enter <企业ID> 一键换取协助免密直通链接并进入(可选 --save 落盘为本地工作企业)
transfer <企业ID> 转交协助工单权限给其他同事(可指定 --to 与 --ticket,支持 --candidates 查询人员)
常用选项:
--token, -t <TOKEN> 显式指定当前操作使用的协助平台 Token
--admin 指定使用企业管理员模式换取免密链接(默认)
--staff <员工姓名> 指定使用特定员工身份换取免密链接
--save 一键将换取的免密会话持久化落盘至本地企业列表(自动提取 OpenAPI 密钥)
--switch 配合 --save,导入后自动切换为当前激活工作企业
--json 输出结构化 JSON 格式结果
--dry-run 预览副作用操作,不真实落盘
--yes, -y 跳过确认提示直接执行写操作
示例:
hose-use assist-platform login --token c31e9bb7-b0ed-4238-91bd-12ec14e05a5b
hose-use assist-platform search "CSM"
hose-use assist-platform tickets Cxa3oOtQi2eS$g
hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财
hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --switch --yes
`;
return {
stdout: helpText,
stderr: "",
exitCode: 0,
};
}
+100
View File
@@ -0,0 +1,100 @@
import {
loadAssistPlatformSession,
saveAssistPlatformSession,
clearAssistPlatformSession,
} from "../../../core/auth/assist-platform-store.js";
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
import { searchCorporations } from "../../../domains/assist-platform/services.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
export async function handleLogin(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const logout = booleanOption(parsed.options, ["logout"]);
if (logout) {
clearAssistPlatformSession();
return {
stdout: "[SUCCESS] 已成功注销并清理协助平台本地会话。\n",
stderr: "",
exitCode: 0,
};
}
const explicitToken = stringOption(parsed.options, ["token", "t"]);
const userName = stringOption(parsed.options, ["user", "name", "u"]);
const hoseAccessToken = stringOption(parsed.options, ["hose-token", "jwt"]);
if (explicitToken) {
// 验证 Token 连通性
const testClient = createAssistPlatformClient({
token: explicitToken,
hoseAccessToken,
});
try {
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
} catch (err) {
return {
stdout: "",
stderr: `[ERROR] 协助平台 Token 校验失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
saveAssistPlatformSession({
token: explicitToken,
hoseAccessToken,
userName: userName || "运营实施人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, token: explicitToken, userName }),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] 协助平台登录凭证保存成功!\n操作人员: ${userName || "运营人员"}\n会话 Token: ${explicitToken}\n`,
stderr: "",
exitCode: 0,
};
}
// 查看当前协助平台会话状态
const existing = loadAssistPlatformSession();
if (!existing || !existing.token) {
return {
stdout: "",
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(existing),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, string> = {
协助平台状态: "🟢 已登录",
操作员工姓名: existing.userName || "运营实施人员",
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
};
return {
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
stderr: "",
exitCode: 0,
};
}
@@ -0,0 +1,64 @@
import { searchCorporations } from "../../../domains/assist-platform/services.js";
import { numberOption, stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleSearch(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const keyword =
parsed.args[0] ||
stringOption(parsed.options, ["keyword", "query", "q", "name", "id"]) ||
"";
const count = numberOption(parsed.options, ["count", "limit", "n"]) || 20;
const start = numberOption(parsed.options, ["start", "offset"]) || 0;
const state = stringOption(parsed.options, ["state", "status"]);
const res = await searchCorporations(client, {
keyword: keyword.trim() || undefined,
state: state?.trim() || undefined,
limit: { start, count },
});
if (runtime.jsonMode) {
return {
stdout: printJson(res, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (res.items.length === 0) {
return {
stdout: `协助平台企业库中未找到匹配 "${keyword}" 的企业记录。\n`,
stderr: "",
exitCode: 0,
};
}
const rows = res.items.map((c, i) => [
String(start + i + 1),
c.id,
c.name,
c.platformName || "app",
c.state || "-",
c.payType === "TRYOUT" ? "试用" : c.payType === "PAY" ? "付费" : c.payType || "-",
c.sumPeople !== null && c.sumPeople !== undefined ? String(c.sumPeople) : "-",
c.tel || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "集群", "状态", "类型", "授权人数", "联系电话"],
rows
);
return {
stdout: `====== 合思协助平台企业搜索结果 (共匹配 ${res.count} 家,当前显示 ${res.items.length} 条) ======\n${table}\n\n提示: 可使用 hose-use assist-platform tickets <企业ID> 查询协助工单\n`,
stderr: "",
exitCode: 0,
};
}
+67
View File
@@ -0,0 +1,67 @@
import { findStaff } from "../../../domains/assist-platform/services.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleStaff(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
runtime.selectedCorp?.id;
const staffName =
parsed.args[1] ||
stringOption(parsed.options, ["name", "user", "staff"]);
if (!corpId || !staffName) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform staff <企业ID> <员工姓名>\n示例: hose-use assist-platform staff Cxa3oOtQi2eS$g 李志财\n",
exitCode: 1,
};
}
const staffList = await findStaff(client, corpId, staffName);
if (runtime.jsonMode) {
return {
stdout: printJson({ corporationId: corpId, queryName: staffName, items: staffList }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (staffList.length === 0) {
return {
stdout: `企业 [${corpId}] 中未找到名为 "${staffName}" 的员工。\n`,
stderr: "",
exitCode: 0,
};
}
const rows = staffList.map((s, i) => [
String(i + 1),
s.name,
s.code || "-",
s.admin ? "👑 是" : "否",
s.cellphone || "-",
s.email || "-",
s.id,
]);
const table = printTable(
["#", "姓名", "工号", "管理员", "手机号码", "邮箱地址", "员工全局 ID (Staff ID)"],
rows
);
return {
stdout: `====== 企业 [${corpId}] 员工查询结果 ("${staffName}") ======\n${table}\n\n操作提示: 可使用 hose-use assist-platform enter ${corpId} --staff ${staffName} --save --yes 一键换票导入\n`,
stderr: "",
exitCode: 0,
};
}
@@ -0,0 +1,69 @@
import { listAssistTickets } from "../../../domains/assist-platform/services.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleTickets(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
runtime.selectedCorp?.id;
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform tickets <企业ID>\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
exitCode: 1,
};
}
const tickets = await listAssistTickets(client, corpId);
if (runtime.jsonMode) {
return {
stdout: printJson({ corporationId: corpId, count: tickets.length, tickets }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (tickets.length === 0) {
return {
stdout: `企业 [${corpId}] 协助中心未查询到任何协助工单记录。\n`,
stderr: "",
exitCode: 0,
};
}
const rows = tickets.map((t, i) => [
String(i + 1),
t.ticketId,
t.applicant,
t.principal || "-",
t.state === "已提供" || t.state === "1"
? "🟢 生效中"
: t.state === "待提供" || t.state === "0"
? "🟡 待提供"
: t.state === "已过期" || t.state === "2"
? "⚪ 已结束"
: t.state,
t.duration ? `${t.duration}h` : "-",
t.usePeriodDesc || (t.startTime && t.endTime ? `${new Date(t.startTime).toLocaleDateString()} - ${new Date(t.endTime).toLocaleDateString()}` : "-"),
]);
const table = printTable(
["#", "授权码 (Ticket ID)", "申请人", "负责人", "工单状态", "时长", "有效期限"],
rows
);
return {
stdout: `====== 企业 [${corpId}] 协助工单列表 (共 ${tickets.length} 条) ======\n${table}\n\n操作提示:\n - 一键管理员直通调试: hose-use assist-platform enter ${corpId} --save --yes\n - 一键指定员工身份进入: hose-use assist-platform enter ${corpId} --staff <员工姓名> --save --yes\n`,
stderr: "",
exitCode: 0,
};
}
@@ -0,0 +1,175 @@
import {
listAssistTickets,
listTransferCandidates,
resolveTransferRecipient,
transferAssistTicket,
} from "../../../domains/assist-platform/services.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleTransfer(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const isListMode = booleanOption(parsed.options, ["candidates", "list-candidates"]);
// 1. 列出可转交候选人员清单
if (isListMode) {
const keyword = stringOption(parsed.options, ["keyword", "query", "q", "name"]) || parsed.args[0];
const candidates = await listTransferCandidates(client, keyword);
if (runtime.jsonMode) {
return {
stdout: printJson({ count: candidates.length, items: candidates }),
stderr: "",
exitCode: 0,
};
}
if (candidates.length === 0) {
return {
stdout: `未找到匹配的可转交人员${keyword ? ` (关键词: ${keyword})` : ""}。\n`,
stderr: "",
exitCode: 0,
};
}
const lines = candidates.map(
(c) => ` • ${c.name.padEnd(8, " ")} | 账号: ${c.id.padEnd(16, " ")} | 工号: ${c.code || "-"} | 角色: ${c.roles.join("、") || "-"}`
);
return {
stdout:
`====== 协助平台可转交人员列表 (共 ${candidates.length} 人) ======\n` +
lines.join("\n") +
"\n",
stderr: "",
exitCode: 0,
};
}
// 2. 转交指定工单
const targetCorpId = parsed.args[0] || stringOption(parsed.options, ["corp", "corpid", "id"]);
const targetRecipient = stringOption(parsed.options, ["to", "recipient", "target", "user", "name"]);
const remarks = stringOption(parsed.options, ["remarks", "message", "msg", "comment"]);
if (!targetCorpId) {
return {
stdout: "",
stderr:
"[ERROR] 必须指定企业 ID 或工单编号。\n" +
"用法:\n" +
" hose-use assist-platform transfer <企业ID> [--ticket <工单号>] --to <姓名|工号|账号> [--remarks <备注>] --yes\n" +
" hose-use assist-platform transfer --candidates [关键词] (查看可转交人员列表)\n",
exitCode: 1,
};
}
if (!targetRecipient) {
return {
stdout: "",
stderr:
"[ERROR] 必须通过 --to 指定接收人员姓名、工号或账号。\n" +
"可运行 hose-use assist-platform transfer --candidates 查询人员名录。\n",
exitCode: 1,
};
}
// 解析工单编号:如果 args[1] 提供了则用 args[1],或 --ticket,否则自动在指定企业中查找当前生效中的工单
let ticketId = parsed.args[1] || stringOption(parsed.options, ["ticket", "ticket-id"]);
let resolvedRecipient;
try {
resolvedRecipient = await resolveTransferRecipient(client, targetRecipient);
} catch (err) {
if (isDryRun(parsed, runtime)) {
resolvedRecipient = {
id: targetRecipient,
name: targetRecipient,
userRoleId: "",
roles: [],
};
} else {
return {
stdout: "",
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
}
if (!ticketId) {
if (isDryRun(parsed, runtime)) {
ticketId = "PREVIEW-ACTIVE-TICKET";
} else {
const tickets = await listAssistTickets(client, targetCorpId);
const activeTicket = tickets.find((t) => t.state === "已提供" || t.state === "1");
if (!activeTicket) {
return {
stdout: "",
stderr: `[ERROR] 企业 ${targetCorpId} 下未找到处于“已提供”生效状态的协助工单。\n可通过 hose-use assist-platform tickets ${targetCorpId} 查看历史工单。\n`,
exitCode: 1,
};
}
ticketId = activeTicket.ticketId;
}
}
const operation = "协助工单转交";
const target = `企业 ${targetCorpId} 的工单 [${ticketId}] 转交给 ${resolvedRecipient.name} (${resolvedRecipient.id})`;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, operation, target, {
ticketId,
recipientId: resolvedRecipient.id,
recipientName: resolvedRecipient.name,
recipientCode: resolvedRecipient.code,
remarks,
});
}
requireMutationConfirmation(
parsed,
runtime,
operation,
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.name}" --yes`
);
const result = await transferAssistTicket(client, {
ticketId,
recipient: resolvedRecipient.id,
remarks,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
success: true,
ticketId,
corpId: targetCorpId,
recipient: resolvedRecipient,
remarks,
}),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, string> = {
转交状态: "🟢 转交成功",
目标工单: ticketId,
所属企业: targetCorpId,
转交接收人: `${resolvedRecipient.name} (${resolvedRecipient.id}${resolvedRecipient.code ? `, 工号: ${resolvedRecipient.code}` : ""})`,
};
if (remarks) pairs["转交备注"] = remarks;
return {
stdout: `[SUCCESS] 协助工单转交成功!\n${printKeyValue(pairs)}\n`,
stderr: "",
exitCode: 0,
};
}
+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 持久化密钥");
});
});
+262 -30
View File
@@ -1,23 +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 } from "../printer.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
@@ -29,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,
};
}
@@ -54,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 });
@@ -143,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;
@@ -152,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
@@ -161,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,
@@ -171,13 +241,46 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(statusObj), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const pairs: Record<string, unknown> = {
"当前活跃账号": activeAccount?.accountId || "未登录",
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"凭证来源类型": currentCorp?.source || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
"持久化状态": isPersistent
? hasOpenApi
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
});
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp?.source),
};
if (currentCorp?.session) {
if (currentCorp.session.loginTime) {
pairs["会话创建时间"] = new Date(currentCorp.session.loginTime).toLocaleString("zh-CN", { hour12: false });
}
if (currentCorp.session.platform) {
pairs["官方平台类型"] = currentCorp.session.platform;
}
if (currentCorp.session.isAssistPlatform) {
pairs["协助调试模式"] = "是 (Assist Platform)";
if (currentCorp.session.operationUserName || currentCorp.session.operationUserId) {
pairs["协助操作人员"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
}
if (currentCorp.session.assistId) {
pairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
if (currentCorp.session.cellphone) {
pairs["绑定手机号码"] = currentCorp.session.cellphone;
}
if (currentCorp.session.isAdmin !== undefined) {
pairs["是否企业管理"] = currentCorp.session.isAdmin ? "是" : "否";
}
}
const summary = printKeyValue(pairs);
return {
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
@@ -188,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) {
@@ -202,47 +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("请粘贴 F12 抓包文本 / 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 importF12Credentials({
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 };
if (runtime.jsonMode) {
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
}
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,
};
}
}
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n企业名称: ${imported.name}\n企业 ID: ${imported.id}\n员工工号: ${imported.credentials.staffId}\n保存路径: enterprises/${imported.id}.json\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> {
@@ -258,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) => [
@@ -276,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 };
+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 };
}
Loaded 100 of 398 files, more files were not shown because too many files have changed in this diff. Show more