fix: harden CLI parsing, MCP startup and release integrity
This commit is contained in:
1 parent
f0902f5f20
commit
103ead0fe5
53 files changed
+3713
-1945
No files matched your search
@@ -4,9 +4,10 @@
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层命令唯一声明式注册表(`area` / `aliases` / `standing` 常驻属性 / `handler`)。新增命令先在此注册。
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`)。
|
||||
- `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` 强制。
|
||||
@@ -25,3 +26,9 @@
|
||||
## 嵌入调用与流式输出
|
||||
|
||||
`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` 分发,流式终端回调不会被注入协议通道。
|
||||
@@ -39,6 +39,17 @@ function resolveImportRelativeToSrc(fromFile: string, specifier: string): string
|
||||
}
|
||||
|
||||
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")),
|
||||
|
||||
@@ -0,0 +1,809 @@
|
||||
/** 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)",
|
||||
"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("allow-prod allow-production auto-publish autoPublish detail 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 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 flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId l label log logs max-jobs maxJobs n name node node-id nodeId output output-file outputFile p page page-size pageSize parent parent-id parentId path payload pipeline pipeline-id pipelineId platform-id platformId 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 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: { }
|
||||
}
|
||||
};
|
||||
|
||||
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) };
|
||||
}
|
||||
+7
-15
@@ -1,24 +1,16 @@
|
||||
import { spawn } from "child_process";
|
||||
import { join } from "path";
|
||||
import { usageError } from "../errors.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js";
|
||||
|
||||
export async function handleMcpCommand(
|
||||
parsed: CliParsedArgs,
|
||||
options: CliRunOptions
|
||||
): Promise<CliResult> {
|
||||
const appRoot = options.appRoot || process.cwd();
|
||||
const serverPath = join(appRoot, "src", "server.ts");
|
||||
|
||||
console.error("启动 MCP Server on stdio...");
|
||||
const child = spawn("bun", ["run", serverPath], {
|
||||
stdio: "inherit",
|
||||
cwd: appRoot,
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
child.on("exit", () => resolve());
|
||||
});
|
||||
if (parsed.action && parsed.action !== "serve") {
|
||||
throw usageError(`未知 mcp 子命令: ${parsed.action}。用法: hose-use mcp [serve]`);
|
||||
}
|
||||
// Lazy loading avoids a runner -> registry -> server -> runner startup cycle.
|
||||
const { startServer } = await import("../../server.js");
|
||||
await startServer(options);
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export async function handleSkillCommand(
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install 进行全局安装\n`,
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
detectArch,
|
||||
detectPlatform,
|
||||
downloadFile,
|
||||
downloadVerifiedReleaseAsset,
|
||||
extractTarGz,
|
||||
extractZip,
|
||||
fetchGitHubRelease,
|
||||
@@ -447,14 +448,13 @@ export async function handleUpdateCommand(
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const downloadedFile = join(tmpDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
|
||||
const downloadedFile = await downloadVerifiedReleaseAsset(release, asset, tmpDir, repo, options.sourcePreference);
|
||||
|
||||
let newBinaryPath = downloadedFile;
|
||||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform, arch);
|
||||
} else if (asset.name.endsWith(".zip")) {
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform, arch);
|
||||
}
|
||||
|
||||
chmodSync(newBinaryPath, 0o755);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { downloadVerifiedReleaseAsset, extractTarGz, extractZip, fetchGitHubRelease, verifyAssetChecksum, type GitHubRelease } from "./releases.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
const temp = () => { const root = mkdtempSync(join(tmpdir(), "hose-update-test-")); roots.push(root); return root; };
|
||||
const payload = Buffer.alloc(2048, 42);
|
||||
const assetName = "hose-use-linux-x64.tar.gz";
|
||||
const digest = createHash("sha256").update(payload).digest("hex");
|
||||
const asset = { name: assetName, downloadUrl: `https://github.com/test/repo/releases/download/v9.9.9/${assetName}`, size: payload.length };
|
||||
const release: GitHubRelease = { version: "9.9.9", tagName: "v9.9.9", notes: "", htmlUrl: "", assets: [asset, { name: "checksums.txt", downloadUrl: "https://github.com/test/repo/releases/download/v9.9.9/checksums.txt", size: 100 }] };
|
||||
|
||||
describe("verified self-update assets", () => {
|
||||
test("rejects missing, duplicate and mismatched checksums", () => {
|
||||
const file = join(temp(), "asset"); writeFileSync(file, payload);
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} ${assetName}\n`)).not.toThrow();
|
||||
expect(() => verifyAssetChecksum(file, assetName, `${digest} *${assetName}\r\n`)).not.toThrow();
|
||||
for (const manifest of ["", `${digest} unrelated\n`, `${digest} ${assetName}\n${digest} ${assetName}\n`, `${digest} ${assetName}\ninvalid ${assetName}\n`, `${"0".repeat(64)} ${assetName}\n`]) {
|
||||
expect(() => verifyAssetChecksum(file, assetName, manifest)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test("pins manifest and binary to the release tag and never sends GitHub credentials to proxies", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
const requests: Array<{ url: string; authorization?: string }> = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request, options?: RequestInit) => {
|
||||
const url = String(input);
|
||||
requests.push({ url, authorization: new Headers(options?.headers).get("Authorization") || undefined });
|
||||
return new Response(url.endsWith("checksums.txt") ? `${digest} ${assetName}\n` : payload);
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
const path = await downloadVerifiedReleaseAsset(release, asset, temp(), "test/repo", "github");
|
||||
expect(readFileSync(path)).toEqual(payload);
|
||||
expect(requests).toHaveLength(2);
|
||||
for (const request of requests) {
|
||||
expect(request.url).toContain("/download/v9.9.9/");
|
||||
if (new URL(request.url).hostname !== "github.com") expect(request.authorization).toBeUndefined();
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("does not start downloading a release without a checksum manifest", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("must not fetch"); }) as unknown as typeof fetch;
|
||||
try {
|
||||
await expect(downloadVerifiedReleaseAsset({ ...release, assets: [asset] }, asset, temp())).rejects.toThrow("checksums.txt");
|
||||
expect(requests).toBe(0);
|
||||
} finally { globalThis.fetch = fetchBefore; }
|
||||
});
|
||||
|
||||
test("GitHub API credentials are also excluded from mirror metadata requests", async () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
const tokenBefore = process.env.GITHUB_TOKEN;
|
||||
process.env.GITHUB_TOKEN = "fixture-token";
|
||||
let authorization: string | null = "not-called";
|
||||
globalThis.fetch = (async (_input: string | URL | Request, options?: RequestInit) => {
|
||||
authorization = new Headers(options?.headers).get("Authorization");
|
||||
return Response.json({ tag_name: "v9.9.9", assets: [{ name: "checksums.txt", browser_download_url: "https://example.test/checksums.txt" }] });
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
expect((await fetchGitHubRelease("yunyingk/hose-use", "9.9.9", "gitea"))?.tagName).toBe("v9.9.9");
|
||||
expect(authorization).toBeNull();
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
if (tokenBefore === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = tokenBefore;
|
||||
}
|
||||
});
|
||||
|
||||
test("extracts only a known binary and rejects archives containing no expected member", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const platform = process.platform === "darwin" ? "darwin" : "linux";
|
||||
const name = `hose-use-${platform}-${process.arch === "arm64" ? "arm64" : "x64"}`;
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "unrelated.txt"), "not a binary");
|
||||
const archive = join(target, "release.tar.gz");
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, name, "unrelated.txt"]).status).toBe(0);
|
||||
const extracted = extractTarGz(archive, target, platform);
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "unrelated.txt"))).toBe(false);
|
||||
expect(spawnSync("tar", ["-czf", archive, "-C", source, "unrelated.txt"]).status).toBe(0);
|
||||
expect(() => extractTarGz(archive, target, platform)).toThrow("目标平台二进制");
|
||||
});
|
||||
|
||||
test("extracts the selected Windows ZIP binary without materializing wrappers or extra files", () => {
|
||||
const root = temp(), source = join(root, "source"), target = join(root, "target");
|
||||
mkdirSync(source); mkdirSync(target);
|
||||
const name = "hose-use-windows-x64.exe";
|
||||
writeFileSync(join(source, name), payload);
|
||||
writeFileSync(join(source, "hose-aipro.cmd"), "fixture wrapper");
|
||||
const archive = join(target, "release.zip");
|
||||
expect(spawnSync("zip", ["-q", archive, name, "hose-aipro.cmd"], { cwd: source }).status).toBe(0);
|
||||
const extracted = extractZip(archive, target, "windows", "x64");
|
||||
expect(readFileSync(extracted)).toEqual(payload);
|
||||
expect(existsSync(join(target, "hose-aipro.cmd"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { unlinkSync, writeFileSync } from "node:fs";
|
||||
import { closeSync, mkdtempSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { basename, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { VERSION } from "../../../version.js";
|
||||
|
||||
@@ -79,7 +81,7 @@ export async function fetchGitHubReleases(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
@@ -168,7 +170,7 @@ export async function fetchGitHubRelease(
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { headers: scopedHeaders(headers, url), signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
@@ -181,6 +183,7 @@ export async function fetchGitHubRelease(
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
if (tag && tagName !== tag) continue;
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
@@ -269,13 +272,22 @@ function logProgress(msg: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Credentials for GitHub must never be forwarded to a CDN or the Gitea mirror. */
|
||||
function scopedHeaders(headers: Record<string, string>, url: string): Record<string, string> {
|
||||
const hostname = new URL(url).hostname;
|
||||
if (hostname === "github.com" || hostname === "api.github.com") return headers;
|
||||
const { Authorization: _authorization, ...publicHeaders } = headers;
|
||||
return publicHeaders;
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
sourcePreference: UpdateSourcePreference = "auto",
|
||||
minimumBytes = 1000
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
@@ -326,7 +338,7 @@ export async function downloadFile(
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token && candidate.includes("github.com")) {
|
||||
if (token && ["github.com", "api.github.com"].includes(new URL(candidate).hostname)) {
|
||||
reqHeaders["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
const res = await fetch(candidate, {
|
||||
@@ -341,7 +353,7 @@ export async function downloadFile(
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
if (buffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
@@ -381,7 +393,7 @@ export async function downloadFile(
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
if (completeBuffer.length < minimumBytes) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
@@ -396,56 +408,63 @@ export async function downloadFile(
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
export function verifyAssetChecksum(assetPath: string, assetName: string, manifest: string): void {
|
||||
const matches = manifest.split(/\r?\n/).flatMap(line => {
|
||||
const match = line.match(/^(\S+)\s+\*?(.+)$/);
|
||||
return match?.[2] === assetName ? [match[1].toLowerCase()] : [];
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
if (matches.length !== 1 || !/^[a-f0-9]{64}$/.test(matches[0])) throw new Error(`checksums.txt 缺少、重复或错误列出 ${assetName},拒绝未经校验的更新`);
|
||||
const actual = createHash("sha256").update(readFileSync(assetPath)).digest("hex");
|
||||
if (actual !== matches[0]) throw new Error(`SHA-256 校验失败: ${assetName};现有安装未替换`);
|
||||
}
|
||||
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
export async function downloadVerifiedReleaseAsset(
|
||||
release: GitHubRelease,
|
||||
asset: GitHubAsset,
|
||||
targetDir: string,
|
||||
repo = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<string> {
|
||||
if (basename(asset.name) !== asset.name || /[\\/]/.test(asset.name)) throw new Error("非法 Release 资产文件名");
|
||||
if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(release.tagName)) throw new Error("非法 Release tag");
|
||||
const manifest = release.assets.find(item => item.name === "checksums.txt");
|
||||
if (!manifest) throw new Error(`Release ${release.tagName} 缺少 checksums.txt,拒绝未经校验的更新`);
|
||||
const manifestPath = join(targetDir, "checksums.txt");
|
||||
await downloadFile(manifest.downloadUrl, manifestPath, release.tagName, manifest.name, repo, sourcePreference, 1);
|
||||
const assetPath = join(targetDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, assetPath, release.tagName, asset.name, repo, sourcePreference);
|
||||
verifyAssetChecksum(assetPath, asset.name, readFileSync(manifestPath, "utf8"));
|
||||
return assetPath;
|
||||
}
|
||||
|
||||
/** Extract only a known binary member; never materialize archive paths or aliases. */
|
||||
function extractReleaseBinary(archivePath: string, targetDir: string, platform: string, arch: string, format: "tar" | "zip"): string {
|
||||
const listing = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-tzf", archivePath] : ["-Z1", archivePath], { encoding: "utf8" });
|
||||
if (listing.status !== 0) throw new Error(`无法读取 Release 归档: ${listing.stderr}`);
|
||||
const names = listing.stdout.split(/\r?\n/);
|
||||
const suffix = platform === "windows" ? ".exe" : "";
|
||||
const expected = [`hose-use-${platform}-${arch}${suffix}`, `hose-use${suffix}`];
|
||||
const member = expected.flatMap(name => [name, `./${name}`]).find(name => names.filter(item => item === name).length === 1);
|
||||
if (!member) throw new Error("Release 归档中没有唯一的目标平台二进制");
|
||||
const output = join(mkdtempSync(join(targetDir, ".extract-")), `hose-use${suffix}`);
|
||||
const fd = openSync(output, "wx", 0o700);
|
||||
try {
|
||||
const extraction = spawnSync(format === "tar" ? "tar" : "unzip", format === "tar" ? ["-xOzf", archivePath, member] : ["-p", archivePath, member], { stdio: ["ignore", fd, "pipe"] });
|
||||
if (extraction.status !== 0) throw new Error(`解压 Release 二进制失败: ${extraction.stderr}`);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
if (!statSync(output).size) throw new Error("Release 二进制为空");
|
||||
unlinkSync(archivePath);
|
||||
return output;
|
||||
}
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "tar");
|
||||
}
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string, arch = detectArch()): string {
|
||||
return extractReleaseBinary(archivePath, targetDir, platform, arch, "zip");
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/analysis.js";
|
||||
} from "../../../domains/platform/workflow/analysis/index.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow-alert-store.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow/alert/index.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createWorkflowDraft,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
} from "../../../domains/platform/workflow-state.js";
|
||||
} from "../../../domains/platform/workflow/state/index.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
|
||||
@@ -367,7 +367,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
function formatEvalCliResult(
|
||||
evalResult: import("../../../domains/platform/workflow-script.js").ScriptEvalResult,
|
||||
evalResult: import("../../../domains/platform/workflow/script/index.js").ScriptEvalResult,
|
||||
targetDesc: string
|
||||
): CliResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
+10
-70
@@ -1,80 +1,20 @@
|
||||
export interface HelpTopic {
|
||||
summary: string;
|
||||
usage: string;
|
||||
commands: Record<string, string>;
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
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": "切换默认账号",
|
||||
},
|
||||
},
|
||||
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 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", diff: "对比两个工作流快照的结构与脚本差异", "diff-job": "对比两次执行的节点分支与报错发散点", test: "端到端一键调试单据(替代前端手工调测)", node: "声明式节点编排与增删改 (list|get|add|edit|rm)", tail: "实时监听任务派发与节点执行日志流 (watch|follow)", create: "从零新建工作流草稿", copy: "复制克隆工作流", delete: "删除工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--flow=<单号> 指定测试单据", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志", "--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all / --ndjson 流式 / --stats 画像)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--ndjson 流式逐行下发 JSON Lines ($O(1)内存)", "--flat 剥离底层实体动态字段前缀并提取引用", "--stats 输出总数/启停/重名/编码规则聚类画像", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
task: { summary: "待办中心与审批任务", usage: "hose-use task <子命令>", commands: { todo: "待我审批", approved: "我已审批", submitted: "我发起的", records: "审批记录", cc: "抄送任务" } },
|
||||
contact: { summary: "企业通讯录与人员检索", usage: "hose-use contact <子命令>", commands: { list: "列出员工", search: "搜索员工", get: "查看员工详情" } },
|
||||
dimension: { summary: "系统与自定义档案维度", usage: "hose-use dimension <子命令>", commands: { list: "列出维度", items: "列出维度项" } },
|
||||
role: { summary: "企业角色定义与成员", usage: "hose-use role <子命令>", commands: { list: "列出角色", groups: "列出角色组", members: "查看角色成员" } },
|
||||
permission: { summary: "权限模型快照", usage: "hose-use permission get", commands: { get: "查看角色权限开关" } },
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
service: { summary: "常驻守护进程管理", usage: "hose-use service <start|stop|restart|status|logs|poll>", commands: { start: "启动服务", stop: "停止服务", restart: "重启服务", status: "查看服务状态", logs: "查看服务日志", poll: "轮询事件" } },
|
||||
probe: { summary: "企业连通性诊断", usage: "hose-use probe [corpId]", commands: { probe: "检查认证与 API 连通性" } },
|
||||
http: { summary: "轻量 HTTP Server 与交互文档", usage: "hose-use http [--port=<port>]", commands: { http: "启动 HTTP 服务" } },
|
||||
mcp: { summary: "MCP Server", usage: "hose-use mcp serve", commands: { serve: "启动 MCP 服务" } },
|
||||
aipro: { summary: "AI PRO 确定性审批仲裁", usage: "hose-use aipro <子命令>", commands: { status: "查看网关状态", bind: "绑定单据", review: "核验要点", decide: "执行仲裁" } },
|
||||
};
|
||||
import { COMMAND_METADATA, commandFlags, resolveCommandAction, resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
export type { HelpTopic } from "./command-metadata.js";
|
||||
export const HELP_REGISTRY = COMMAND_METADATA;
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const area = target[0]?.toLowerCase();
|
||||
const topic = area ? HELP_REGISTRY[area] : undefined;
|
||||
if (!topic) return `未找到命令域帮助: ${target.join(" ") || "<empty>"}\n运行 hose-use --help 查看全部命令域。`;
|
||||
const resolved = resolveCommandMetadata(target[0]);
|
||||
if (!resolved) throw usageError(`未找到命令域帮助: ${target.join(" ") || "<empty>"}。运行 hose-use --help 查看全部命令域。`);
|
||||
const { area, metadata: topic } = resolved;
|
||||
|
||||
const action = target[1]?.toLowerCase();
|
||||
const action = resolveCommandAction(area, target[1]);
|
||||
if (action && !Object.hasOwn(topic.commands, action)) throw usageError(`未找到子命令帮助: ${area} ${target[1]}`);
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
lines.push("", "支持选项:", ...Object.entries(commandFlags(area, action)).map(([key, kind]) => ` --${key}${kind === "value" ? "=<值>" : kind === "boolean-or-value" ? "[=<值>]" : ""}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import ts from "typescript";
|
||||
import { commandFlags, COMMAND_METADATA } from "./command-metadata.js";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { CLI_COMMAND_REGISTRY, findCommandByArea } from "./registry.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
|
||||
describe("strict command options", () => {
|
||||
test("rejects misspellings and missing values instead of silently dropping filters", async () => {
|
||||
const typo = await runCli(["bill", "list", "--limitt", "5", "--json"]);
|
||||
expect(typo.exitCode).toBe(2);
|
||||
expect(JSON.parse(typo.stdout).message).toContain("--limit");
|
||||
expect(typo.stderr).toBe("");
|
||||
for (const args of [["bill", "list", "--limit"], ["bill", "get", "-o"], ["--corp"], ["workflow", "get", "--file="], ["bill", "list", "--limit", "--json"]]) {
|
||||
expect((await runCli(args)).exitCode).toBe(2);
|
||||
}
|
||||
expect((await runCli(["mcp", "serve", "--unknwon"])).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("uses command-specific boolean and value options without swallowing IDs", () => {
|
||||
expect(parseArgs(["bill", "list", "--fields", "name,code"]).options.fields).toBe("name,code");
|
||||
expect(parseArgs(["feetype", "get", "--fields", "FT001"]).args).toEqual(["FT001"]);
|
||||
expect(parseArgs(["wf", "job", "--verbose", "JOB_123"]).args).toEqual(["JOB_123"]);
|
||||
expect(parseArgs(["workflow", "create", "-f", "template.json"]).options.f).toBe("template.json");
|
||||
expect(parseArgs(["workflow", "tail", "-f", "PIPE_123"]).args).toEqual(["PIPE_123"]);
|
||||
expect(parseArgs(["auth", "import", "--raw", "curl https://example.test"]).options.raw).toBe("curl https://example.test");
|
||||
expect(parseArgs(["update", "--version", "0.9.0"]).options.version).toBe("0.9.0");
|
||||
expect(parseArgs(["http", "-h", "127.0.0.1"]).options.h).toBe("127.0.0.1");
|
||||
expect(parseArgs(["-c", "corp-test", "bill", "list"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["workflow", "get", "ID", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["status", "-c", "corp-test"], "aipro").options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["platform", "records", "App", "Entity", "-c", "corp-test"]).options.corp).toBe("corp-test");
|
||||
expect(parseArgs(["bind", "R1", "-c", "[1]"], "aipro").options.corp).toBeUndefined();
|
||||
expect(parseArgs(["bill", "list", "-c", "BILL001"]).options.corp).toBeUndefined();
|
||||
expect(parseArgs(["-h", "http"]).options.help).toBe(true);
|
||||
expect(parseArgs(["feetype", "get", "--fields", "1"]).args).toEqual(["1"]);
|
||||
});
|
||||
|
||||
test("preserves explicit booleans, aliases, negative values, and -- boundaries", () => {
|
||||
const parsed = parseArgs(["--json", "--corp", "corp-test", "bill", "list", "--limit=-5", "--mine=false", "--", "--literal"]);
|
||||
expect(parsed.options).toMatchObject({ json: true, corp: "corp-test", limit: "-5", mine: false });
|
||||
expect(parsed.args).toEqual(["--literal"]);
|
||||
expect(parseArgs(["bill", "list", "--limit", "-5"]).options.limit).toBe("-5");
|
||||
expect(parseArgs(["platform", "record", "toggle", "--active=0", "REC_1"]).args).toEqual(["toggle", "REC_1"]);
|
||||
expect(parseArgs(["bill", "get", "ID", "-o", "/tmp/output.json"]).options.outputFile).toBe("/tmp/output.json");
|
||||
expect(() => parseArgs(["bill", "get", "ID", "--json=garbage"])).toThrow("布尔值");
|
||||
});
|
||||
|
||||
test("AI PRO returns structured parse failures before opening its repository", async () => {
|
||||
const result = await runAiProCli(["review", "--findngs", "[]", "--json"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(JSON.parse(result.stdout).message).toContain("--findings");
|
||||
expect(parseArgs(["review", "--run", "R1"], "aipro").options.run).toBe("R1");
|
||||
expect(parseArgs(["decide", "approve", "R1", "--run", "--yes"], "aipro").options.run).toBe(true);
|
||||
const help = await runAiProCli(["review", "--help", "--json"]);
|
||||
expect(help.exitCode).toBe(0);
|
||||
expect(JSON.parse(help.stdout).help).toContain("核验要点");
|
||||
});
|
||||
|
||||
test("all command domains, aliases and declared flags have usable help", async () => {
|
||||
expect(CLI_COMMAND_REGISTRY.map(command => command.area)).toEqual(Object.keys(COMMAND_METADATA));
|
||||
const names = CLI_COMMAND_REGISTRY.flatMap(command => [command.area, ...command.aliases]);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const [area, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
for (const name of [area, ...metadata.aliases]) {
|
||||
expect(findCommandByArea(name)?.area).toBe(area);
|
||||
const result = await runCli(["help", name]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(`${area} -`);
|
||||
if (name === area) {
|
||||
const documentedFlags = result.stdout.split("支持选项:\n")[1].split("\n\n提示:")[0].trim().split("\n").map(line => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documentedFlags).toEqual(Object.keys(commandFlags(area)));
|
||||
}
|
||||
}
|
||||
}
|
||||
const workflow = await runCli(["wf", "--help"]);
|
||||
for (const action of ["enum", "lint-script", "eval-script"]) expect(workflow.stdout).toContain(action);
|
||||
expect((await runCli(["help", "workflow", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "workflow", "constructor"])).exitCode).toBe(2);
|
||||
expect((await runCli(["help", "not-real"])).exitCode).toBe(2);
|
||||
expect((await runCli(["workflow", "help", "enum"])).stdout).toContain("枚举");
|
||||
});
|
||||
|
||||
test("handler option declarations cannot drift outside the shared flag vocabulary", () => {
|
||||
const root = join(import.meta.dir, "commands");
|
||||
function files(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") && !e.name.endsWith(".test.ts") ? [join(dir, e.name)] : []);
|
||||
}
|
||||
const missing: string[] = [];
|
||||
for (const path of files(root)) {
|
||||
const area = relative(root, path).split("/")[0].replace(/\.ts$/, "");
|
||||
const source = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true);
|
||||
function visit(node: ts.Node) {
|
||||
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && /^(booleanOption|stringOption|numberOption|listOption)$/.test(node.expression.text)) {
|
||||
const keys = node.arguments[node.expression.text === "listOption" ? 0 : 1];
|
||||
if (keys && ts.isArrayLiteralExpression(keys)) {
|
||||
for (const key of keys.elements) if (ts.isStringLiteral(key) && !commandFlags(area)[key.text]) missing.push(`${relative(root, path)}: --${key.text}`);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(source);
|
||||
}
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
+95
-185
@@ -1,202 +1,112 @@
|
||||
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||
|
||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"raw",
|
||||
"json",
|
||||
"j",
|
||||
"help",
|
||||
"h",
|
||||
"version",
|
||||
"v",
|
||||
"V",
|
||||
"force",
|
||||
"f",
|
||||
"stateless",
|
||||
"stateful",
|
||||
"check",
|
||||
"check-only",
|
||||
"changelog",
|
||||
"log",
|
||||
"l",
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
"full",
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"y",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"forceWrite",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
"all",
|
||||
"a",
|
||||
"include-disabled",
|
||||
"flat",
|
||||
"flatten",
|
||||
"table",
|
||||
"specs",
|
||||
"spec",
|
||||
"fields",
|
||||
"recursive",
|
||||
"in-place",
|
||||
"inPlace",
|
||||
"value-json",
|
||||
"valueJson",
|
||||
"has-error",
|
||||
"hasError",
|
||||
"errors",
|
||||
"failed",
|
||||
"fail",
|
||||
"fail-on-alert",
|
||||
"failOnAlert",
|
||||
"includeDetail",
|
||||
"detail",
|
||||
"apply",
|
||||
"execute",
|
||||
"do",
|
||||
"refresh",
|
||||
"overwrite",
|
||||
"elevate",
|
||||
"elevate-hose",
|
||||
"as-hose",
|
||||
"no-elevate",
|
||||
"reveal",
|
||||
"plain",
|
||||
"save",
|
||||
"persist",
|
||||
"verify",
|
||||
"workbench",
|
||||
"w",
|
||||
"active-only",
|
||||
"activeOnly",
|
||||
"active",
|
||||
"read",
|
||||
"unread",
|
||||
"clear",
|
||||
"sms",
|
||||
"sync",
|
||||
"interactive",
|
||||
"i",
|
||||
"reminder",
|
||||
"remind",
|
||||
"keep-it-secret",
|
||||
"secret",
|
||||
"private",
|
||||
"mine",
|
||||
"my",
|
||||
"self",
|
||||
"distinct",
|
||||
"risk",
|
||||
"with-risk",
|
||||
"audit",
|
||||
"github",
|
||||
"gh",
|
||||
"gitea",
|
||||
"yingqing",
|
||||
"mirror",
|
||||
]);
|
||||
import { commandFlags, GLOBAL_FLAGS, localCommandFlags, type FlagKind } from "./command-metadata.js";
|
||||
import { usageError } from "./errors.js";
|
||||
|
||||
function isExplicitBooleanLiteral(val: string | undefined): boolean {
|
||||
if (!val) return false;
|
||||
const lower = val.toLowerCase();
|
||||
return lower === "true" || lower === "false";
|
||||
function explicitBoolean(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (value.toLowerCase() === "true" || value === "1") return true;
|
||||
if (value.toLowerCase() === "false" || value === "0") return false;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
// Space-separated numeric tokens may be positional IDs. Numeric booleans use =0/=1.
|
||||
function separatedBoolean(value: string | undefined): boolean | undefined {
|
||||
return value && /^(true|false)$/i.test(value) ? explicitBoolean(value) : undefined;
|
||||
}
|
||||
|
||||
function findContext(raw: string[], areaOverride?: string): { area?: string; action?: string } {
|
||||
let area = areaOverride;
|
||||
let action: string | undefined;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (arg.startsWith("-") && arg !== "-") {
|
||||
const key = arg.replace(/^-+/, "").split("=")[0];
|
||||
const flags = commandFlags(area, action);
|
||||
const kind = flags[key] || flags[Object.keys(flags).find(k => k.toLowerCase() === key.toLowerCase()) || ""];
|
||||
if (!arg.includes("=") && ((kind === "value" && raw[i + 1] && !raw[i + 1].startsWith("-")) || (kind !== "value" && separatedBoolean(raw[i + 1]) !== undefined))) i++;
|
||||
continue;
|
||||
}
|
||||
if (!area) area = arg.toLowerCase();
|
||||
else { action = arg.toLowerCase(); break; }
|
||||
}
|
||||
return { area, action };
|
||||
}
|
||||
|
||||
function distance(left: string, right: string): number {
|
||||
let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
|
||||
for (let i = 0; i < left.length; i++) {
|
||||
const row = [i + 1];
|
||||
for (let j = 0; j < right.length; j++) row.push(Math.min(row[j] + 1, previous[j + 1] + 1, previous[j] + Number(left[i] !== right[j])));
|
||||
previous = row;
|
||||
}
|
||||
return previous[right.length];
|
||||
}
|
||||
|
||||
/** Read just the global JSON switch, even when strict parsing will fail. */
|
||||
export function isJsonRequested(raw: string[]): boolean {
|
||||
let enabled = false;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const arg = raw[i];
|
||||
if (arg === "--") break;
|
||||
if (/^--(?:json|j)(?:=|$)/i.test(arg) || /^-j$/i.test(arg)) {
|
||||
const inline = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : undefined;
|
||||
enabled = (inline !== undefined ? explicitBoolean(inline) : separatedBoolean(raw[i + 1])) ?? true;
|
||||
}
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[], areaOverride?: string): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const positional: string[] = [];
|
||||
const context = findContext(rawArgs, areaOverride);
|
||||
const flags = commandFlags(context.area, context.action);
|
||||
const localFlags = localCommandFlags(context.area, context.action);
|
||||
|
||||
for (let i = 0; i < rawArgs.length; i++) {
|
||||
const arg = rawArgs[i];
|
||||
if (arg === "--") { positional.push(...rawArgs.slice(i + 1)); break; }
|
||||
if (!arg.startsWith("-") || arg === "-") { positional.push(arg); continue; }
|
||||
|
||||
if (arg === "--") {
|
||||
positional.push(...rawArgs.slice(i + 1));
|
||||
break;
|
||||
const body = arg.replace(/^-+/, "");
|
||||
const eqIdx = body.indexOf("=");
|
||||
const inputKey = eqIdx === -1 ? body : body.slice(0, eqIdx);
|
||||
const key = Object.hasOwn(flags, inputKey) ? inputKey : Object.keys(flags).find(k => k.toLowerCase() === inputKey.toLowerCase());
|
||||
if (!key) {
|
||||
const nearest = Object.keys(flags).sort((a, b) => distance(inputKey, a) - distance(inputKey, b))[0];
|
||||
const suggestion = nearest && distance(inputKey, nearest) <= Math.max(1, Math.floor(inputKey.length / 3)) ? `。是否想用 --${nearest}?` : "";
|
||||
throw usageError(`未知选项: ${arg.split("=")[0]}${suggestion}`);
|
||||
}
|
||||
const globalPrefix = positional.length === 0 && Object.hasOwn(GLOBAL_FLAGS, key);
|
||||
const kind: FlagKind = globalPrefix ? GLOBAL_FLAGS[key] : flags[key];
|
||||
const inline = eqIdx === -1 ? undefined : body.slice(eqIdx + 1);
|
||||
const next = rawArgs[i + 1];
|
||||
let value: string | boolean;
|
||||
if (kind === "boolean") {
|
||||
if (inline !== undefined) {
|
||||
const parsed = explicitBoolean(inline);
|
||||
if (parsed === undefined) throw usageError(`选项 --${key} 需要布尔值 true/false 或 1/0`);
|
||||
value = parsed;
|
||||
} else if (separatedBoolean(next) !== undefined) {
|
||||
value = separatedBoolean(next)!;
|
||||
i++;
|
||||
} else value = true;
|
||||
} else if (inline !== undefined) {
|
||||
if (!inline.length) throw usageError(`选项 --${key} 缺少值`);
|
||||
value = kind === "boolean-or-value" ? explicitBoolean(inline) ?? inline : inline;
|
||||
} else if (next !== undefined && next !== "--" && (!next.startsWith("-") || /^-\d+(?:\.\d+)?$/.test(next))) {
|
||||
value = kind === "boolean-or-value" ? separatedBoolean(next) ?? next : next;
|
||||
i++;
|
||||
} else if (kind === "boolean-or-value") value = true;
|
||||
else throw usageError(`选项 --${key} 缺少值`);
|
||||
|
||||
if (arg.startsWith("--")) {
|
||||
const eqIdx = arg.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const key = arg.slice(2, eqIdx);
|
||||
const val = arg.slice(eqIdx + 1);
|
||||
options[key] = val;
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
const keyLower = key.toLowerCase();
|
||||
const next = rawArgs[i + 1];
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
if (isExplicitBooleanLiteral(next)) {
|
||||
const boolVal = next!.toLowerCase() === "true";
|
||||
options[key] = boolVal;
|
||||
if (key !== keyLower) options[keyLower] = boolVal;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
}
|
||||
} else {
|
||||
if (next && !next.startsWith("-")) {
|
||||
options[key] = next;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg.startsWith("-") && arg.length > 1) {
|
||||
const flag = arg.slice(1);
|
||||
const flagLower = flag.toLowerCase();
|
||||
if (flagLower === "h" || flag === "?") {
|
||||
options.help = true;
|
||||
} else if (flagLower === "j") {
|
||||
options.json = true;
|
||||
} else if (flagLower === "v") {
|
||||
options.version = true;
|
||||
} else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
i++;
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else if (flag === "c") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.c = next;
|
||||
i++;
|
||||
} else {
|
||||
options.c = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
positional.push(arg);
|
||||
options[key] = value;
|
||||
// Preserve command-specific short names; global short names also get their semantic key.
|
||||
const globalNames: Record<string, string> = { h: "help", "?": "help", j: "json", v: "version", V: "version", c: "corp", o: "outputFile" };
|
||||
if (globalNames[key] && (globalPrefix || !Object.hasOwn(localFlags, key) || key === "j" || key === "o" || key === "V")) options[globalNames[key]] = value;
|
||||
}
|
||||
|
||||
const area = positional[0]?.toLowerCase();
|
||||
const action = positional[1]?.toLowerCase();
|
||||
const args = positional.slice(2);
|
||||
|
||||
return {
|
||||
area,
|
||||
action,
|
||||
args,
|
||||
positional,
|
||||
options,
|
||||
raw: rawArgs,
|
||||
};
|
||||
return { area: positional[0]?.toLowerCase(), action: positional[1]?.toLowerCase(), args: positional.slice(2), positional, options, raw: rawArgs };
|
||||
}
|
||||
|
||||
export function stringOption(
|
||||
|
||||
+3
-31
@@ -2,7 +2,7 @@ import { writeFileSync } from "node:fs";
|
||||
import { formatVersionLabel } from "../version.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
import { PayloadTooLargeError } from "./errors.js";
|
||||
import { renderScopedHelp } from "./help.js";
|
||||
import { renderScopedHelp, HELP_REGISTRY } from "./help.js";
|
||||
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
@@ -186,35 +186,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
|
||||
核心命令域:
|
||||
context 查看全局运行上下文与身份诊断 (context, status, whoami, env)
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts, switch-account)
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, node, tail, job, create, copy, delete, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
|
||||
openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys)
|
||||
keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r])
|
||||
store 应用中心已购应用与应用商店探查 (list, search <关键词>, get <ID>)
|
||||
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
|
||||
mcp MCP Server 运行 (serve)
|
||||
${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${topic.summary} (${Object.keys(topic.commands).join(", ")})`).join("\n")}
|
||||
version 查看版本信息
|
||||
|
||||
全局选项:
|
||||
@@ -295,7 +267,7 @@ export function printHelp(target: string[] = []): string {
|
||||
hose-use service status # 查看守护进程运行状态与接口地址
|
||||
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use skill install --yes # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
hose-use update --github # 强制走官方 GitHub 源升级
|
||||
hose-use update --changelog # 查看版本发布历史
|
||||
|
||||
+31
-31
@@ -26,6 +26,7 @@ import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
@@ -34,9 +35,8 @@ export type CliCommandHandler = (
|
||||
options: CliRunOptions
|
||||
) => Promise<CliResult>;
|
||||
|
||||
export interface CliCommandDefinition {
|
||||
export interface CliCommandDefinition extends CliCommandMetadata {
|
||||
area: string;
|
||||
aliases: string[];
|
||||
standing?: boolean | ((args: string[]) => boolean);
|
||||
handler: CliCommandHandler;
|
||||
}
|
||||
@@ -44,12 +44,12 @@ export interface CliCommandDefinition {
|
||||
export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "context",
|
||||
aliases: ["status", "whoami", "env"],
|
||||
...COMMAND_METADATA.context,
|
||||
handler: (parsed, runtime) => handleContextCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "aipro",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.aipro,
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
@@ -59,139 +59,139 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
aliases: ["login"],
|
||||
...COMMAND_METADATA.auth,
|
||||
handler: (parsed, runtime) => handleAuthCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "corps",
|
||||
aliases: ["corp"],
|
||||
...COMMAND_METADATA.corps,
|
||||
handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "config",
|
||||
aliases: ["mode"],
|
||||
...COMMAND_METADATA.config,
|
||||
handler: (parsed, runtime) => handleConfigCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "workflow",
|
||||
aliases: ["workflows", "wf"],
|
||||
...COMMAND_METADATA.workflow,
|
||||
handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "bill",
|
||||
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
|
||||
...COMMAND_METADATA.bill,
|
||||
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "flow",
|
||||
aliases: ["flows", "trace"],
|
||||
...COMMAND_METADATA.flow,
|
||||
handler: (parsed, runtime) => handleFlowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "contact",
|
||||
aliases: ["contacts", "staff", "staffs"],
|
||||
...COMMAND_METADATA.contact,
|
||||
handler: (parsed, runtime) => handleContactCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "task",
|
||||
aliases: ["tasks", "todo"],
|
||||
...COMMAND_METADATA.task,
|
||||
handler: (parsed, runtime) => handleTaskCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "dimension",
|
||||
aliases: ["dimensions", "archive", "archives"],
|
||||
...COMMAND_METADATA.dimension,
|
||||
handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "feetype",
|
||||
aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"],
|
||||
...COMMAND_METADATA.feetype,
|
||||
handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "role",
|
||||
aliases: ["roles"],
|
||||
...COMMAND_METADATA.role,
|
||||
handler: (parsed, runtime) => handleRoleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "permission",
|
||||
aliases: ["permissions"],
|
||||
...COMMAND_METADATA.permission,
|
||||
handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "rule",
|
||||
aliases: ["rules"],
|
||||
...COMMAND_METADATA.rule,
|
||||
handler: (parsed, runtime) => handleRuleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "approval",
|
||||
aliases: ["approvals", "audit"],
|
||||
...COMMAND_METADATA.approval,
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
aliases: ["messages", "notify", "notifications"],
|
||||
...COMMAND_METADATA.message,
|
||||
handler: (parsed, runtime) => handleMessageCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "platform",
|
||||
aliases: ["platforms", "datalink", "data-link"],
|
||||
...COMMAND_METADATA.platform,
|
||||
handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "app",
|
||||
aliases: ["apps", "workbench"],
|
||||
...COMMAND_METADATA.app,
|
||||
handler: (parsed, runtime) => handleAppCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "menu",
|
||||
aliases: ["menus"],
|
||||
...COMMAND_METADATA.menu,
|
||||
handler: (parsed, runtime) => handleMenuCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "skill",
|
||||
aliases: ["skills"],
|
||||
...COMMAND_METADATA.skill,
|
||||
handler: (parsed, runtime) => handleSkillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "probe",
|
||||
aliases: ["diagnose"],
|
||||
...COMMAND_METADATA.probe,
|
||||
handler: (parsed, runtime) => handleProbeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "update",
|
||||
aliases: ["upgrade", "self-update", "changelog"],
|
||||
...COMMAND_METADATA.update,
|
||||
handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options),
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
aliases: ["schema", "spec"],
|
||||
...COMMAND_METADATA.openapi,
|
||||
handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "keys",
|
||||
aliases: ["key", "secret", "secrets"],
|
||||
...COMMAND_METADATA.keys,
|
||||
handler: (parsed, runtime) => handleKeysCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "store",
|
||||
aliases: ["market"],
|
||||
...COMMAND_METADATA.store,
|
||||
handler: (parsed, runtime) => handleStoreCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "http",
|
||||
aliases: ["server", "web"],
|
||||
...COMMAND_METADATA.http,
|
||||
standing: true,
|
||||
handler: (parsed, runtime) => handleHttpCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
aliases: ["daemon"],
|
||||
...COMMAND_METADATA.service,
|
||||
standing: (args) => args[1]?.toLowerCase() === "run",
|
||||
handler: (parsed, runtime) => handleServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
aliases: [],
|
||||
...COMMAND_METADATA.mcp,
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
|
||||
+29
-25
@@ -1,6 +1,7 @@
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions, isJsonRequested } from "./parser.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { resolveCommandMetadata } from "./command-metadata.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { findCommandByArea, isStandingCommand } from "./registry.js";
|
||||
@@ -29,7 +30,7 @@ async function runCliOnce(
|
||||
): Promise<CliResult> {
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
|
||||
const machineJson = isJsonRequested(rawArgs);
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
|
||||
@@ -62,7 +63,7 @@ async function runCliOnce(
|
||||
|
||||
function isHelpRequested(parsed: CliParsedArgs): boolean {
|
||||
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?") return true;
|
||||
if (normArea === "help" || normArea === "h" || normArea === "?" || parsed.action === "help") return true;
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
@@ -79,6 +80,9 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
|
||||
for (const [key, val] of Object.entries(parsed.options)) {
|
||||
const normKey = key.replace(/^-+/, "").toLowerCase();
|
||||
const localFlags = resolveCommandMetadata(parsed.area)?.metadata.flags;
|
||||
if (key === "v" && localFlags?.v) continue;
|
||||
if (key === "version" && localFlags?.version === "value" && typeof val !== "boolean") continue;
|
||||
if (normKey === "version" || normKey === "v") {
|
||||
if (val === true || val === "true" || val === "") return true;
|
||||
}
|
||||
@@ -90,10 +94,28 @@ function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action].filter((value): value is string => Boolean(value));
|
||||
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
try {
|
||||
return await dispatchParsedCli(rawArgs, options);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
|
||||
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
return {
|
||||
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
|
||||
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
async function dispatchParsedCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
@@ -117,7 +139,7 @@ async function dispatchCli(
|
||||
};
|
||||
}
|
||||
|
||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||
const corpIdOption = stringOption(parsed.options, ["corp"]);
|
||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||
const outputOpts = outputOptions(parsed.options);
|
||||
@@ -152,24 +174,6 @@ async function dispatchCli(
|
||||
}
|
||||
return await commandDef.handler(parsed, runtime, options);
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
if (jsonMode) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
error: true,
|
||||
message: errorMsg,
|
||||
exitCode: classification.exitCode,
|
||||
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
|
||||
}, null, 2),
|
||||
stderr: "",
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
return cliErrorResult(error, jsonMode);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user