From fbdfbaa8d3e9daa36117fcb2177533883ae14c32 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 00:31:30 +0800 Subject: [PATCH] refactor(cli): introduce declarative CLI command registry and shared runtime helpers --- src/cli/helpers.ts | 17 ++++ src/cli/registry.ts | 212 ++++++++++++++++++++++++++++++++++++++++++++ src/cli/runner.ts | 174 +++--------------------------------- 3 files changed, 241 insertions(+), 162 deletions(-) create mode 100644 src/cli/registry.ts diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index 15a28e0..fb04725 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -90,6 +90,23 @@ export async function createScriptEngineClientForCorp(corp: CorpConfig, platform export const createPiperClientForCorp = createScriptEngineClientForCorp; +export function requireSelectedCorp( + runtime: CliRuntime, + message = "未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。" +): CorpConfig { + if (!runtime.selectedCorp) { + throw new Error(message); + } + return runtime.selectedCorp; +} + +export async function getSessionClientForRuntime(runtime: CliRuntime) { + const corp = requireSelectedCorp(runtime); + const corpId = corp.credentials?.corpId || corp.corpId || corp.id; + const client = await createSessionClient(corp); + return { corp, corpId, client }; +} + export function prompt(question: string): Promise { const rl = readline.createInterface({ input: process.stdin, diff --git a/src/cli/registry.ts b/src/cli/registry.ts new file mode 100644 index 0000000..97eff7a --- /dev/null +++ b/src/cli/registry.ts @@ -0,0 +1,212 @@ +import { handleAuthCommand } from "./commands/auth.js"; +import { handleCorpsCommand } from "./commands/corps.js"; +import { handleConfigCommand } from "./commands/config.js"; +import { handleWorkflowCommand } from "./commands/workflow.js"; +import { handlePlatformCommand } from "./commands/platform.js"; +import { handleAppCommand } from "./commands/app.js"; +import { handleMenuCommand } from "./commands/menu.js"; +import { handleSkillCommand } from "./commands/skill.js"; +import { handleProbeCommand } from "./commands/probe.js"; +import { handleMcpCommand } from "./commands/mcp.js"; +import { handleUpdateCommand } from "./commands/update.js"; +import { handleOpenApiCommand } from "./commands/openapi.js"; +import { handleBillCommand } from "./commands/bill.js"; +import { handleContactCommand } from "./commands/contact.js"; +import { handleServiceCommand } from "./commands/service.js"; +import { handleHttpCommand } from "./commands/http.js"; +import { handleTaskCommand } from "./commands/task.js"; +import { handleMessageCommand } from "./commands/message.js"; +import { handleDimensionCommand } from "./commands/dimension.js"; +import { handleRoleCommand } from "./commands/role.js"; +import { handlePermissionCommand } from "./commands/permission.js"; +import { handleRuleCommand } from "./commands/rule.js"; +import { handleApprovalCommand } from "./commands/approval.js"; +import { handleContextCommand } from "./commands/context.js"; +import { handleKeysCommand } from "./commands/keys.js"; +import { handleStoreCommand } from "./commands/store.js"; +import { handleFeeTypeCommand } from "./commands/feetype.js"; +import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js"; + +export type CliCommandHandler = ( + parsed: CliParsedArgs, + runtime: CliRuntime, + options: CliRunOptions +) => Promise; + +export interface CliCommandDefinition { + area: string; + aliases: string[]; + standing?: boolean | ((args: string[]) => boolean); + handler: CliCommandHandler; +} + +export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [ + { + area: "context", + aliases: ["status", "whoami", "env"], + handler: (parsed, runtime) => handleContextCommand(parsed, runtime), + }, + { + area: "aipro", + aliases: [], + handler: async (parsed) => { + const { runAiProCli } = await import("../aipro-cli.js"); + const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro"); + const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1); + return runAiProCli(subArgs); + }, + }, + { + area: "auth", + aliases: ["login"], + handler: (parsed, runtime) => handleAuthCommand(parsed, runtime), + }, + { + area: "corps", + aliases: ["corp"], + handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime), + }, + { + area: "config", + aliases: ["mode"], + handler: (parsed, runtime) => handleConfigCommand(parsed, runtime), + }, + { + area: "workflow", + aliases: ["workflows", "wf"], + handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime), + }, + { + area: "bill", + aliases: ["bills", "fee", "fees", "invoice", "invoices"], + handler: (parsed, runtime) => handleBillCommand(parsed, runtime), + }, + { + area: "contact", + aliases: ["contacts", "staff", "staffs"], + handler: (parsed, runtime) => handleContactCommand(parsed, runtime), + }, + { + area: "task", + aliases: ["tasks", "todo"], + handler: (parsed, runtime) => handleTaskCommand(parsed, runtime), + }, + { + area: "dimension", + aliases: ["dimensions", "archive", "archives"], + handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime), + }, + { + area: "feetype", + aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"], + handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime), + }, + { + area: "role", + aliases: ["roles"], + handler: (parsed, runtime) => handleRoleCommand(parsed, runtime), + }, + { + area: "permission", + aliases: ["permissions"], + handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime), + }, + { + area: "rule", + aliases: ["rules"], + handler: (parsed, runtime) => handleRuleCommand(parsed, runtime), + }, + { + area: "approval", + aliases: ["approvals", "audit"], + handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime), + }, + { + area: "message", + aliases: ["messages", "notify", "notifications"], + handler: (parsed, runtime) => handleMessageCommand(parsed, runtime), + }, + { + area: "platform", + aliases: ["platforms", "datalink", "data-link"], + handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime), + }, + { + area: "app", + aliases: ["apps", "workbench"], + handler: (parsed, runtime) => handleAppCommand(parsed, runtime), + }, + { + area: "menu", + aliases: ["menus"], + handler: (parsed, runtime) => handleMenuCommand(parsed, runtime), + }, + { + area: "skill", + aliases: ["skills"], + handler: (parsed, runtime) => handleSkillCommand(parsed, runtime), + }, + { + area: "probe", + aliases: ["diagnose"], + handler: (parsed, runtime) => handleProbeCommand(parsed, runtime), + }, + { + area: "update", + aliases: ["upgrade", "self-update", "changelog"], + handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options), + }, + { + area: "openapi", + aliases: ["schema", "spec"], + handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime), + }, + { + area: "keys", + aliases: ["key", "secret", "secrets"], + handler: (parsed, runtime) => handleKeysCommand(parsed, runtime), + }, + { + area: "store", + aliases: ["market"], + handler: (parsed, runtime) => handleStoreCommand(parsed, runtime), + }, + { + area: "http", + aliases: ["server", "web"], + standing: true, + handler: (parsed, runtime) => handleHttpCommand(parsed, runtime), + }, + { + area: "service", + aliases: ["daemon"], + standing: (args) => args[1]?.toLowerCase() === "run", + handler: (parsed, runtime) => handleServiceCommand(parsed, runtime), + }, + { + area: "mcp", + aliases: [], + standing: true, + handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options), + }, +]; + +const COMMAND_LOOKUP = new Map(); +for (const def of CLI_COMMAND_REGISTRY) { + COMMAND_LOOKUP.set(def.area.toLowerCase(), def); + for (const alias of def.aliases) { + COMMAND_LOOKUP.set(alias.toLowerCase(), def); + } +} + +export function findCommandByArea(area?: string): CliCommandDefinition | undefined { + if (!area) return undefined; + return COMMAND_LOOKUP.get(area.toLowerCase()); +} + +export function isStandingCommand(args: string[]): boolean { + if (!args.length) return false; + const def = findCommandByArea(args[0]); + if (!def?.standing) return false; + return typeof def.standing === "function" ? def.standing(args) : def.standing; +} diff --git a/src/cli/runner.ts b/src/cli/runner.ts index f3d0936..8b42141 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -3,46 +3,9 @@ import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser. import { printHelp, printJson, redactSensitiveText } from "./printer.js"; import { classifyCliError } from "./errors.js"; import { initCorpRuntime } from "./helpers.js"; -import { handleAuthCommand } from "./commands/auth.js"; -import { handleCorpsCommand } from "./commands/corps.js"; -import { handleConfigCommand } from "./commands/config.js"; -import { handleWorkflowCommand } from "./commands/workflow.js"; -import { handlePlatformCommand } from "./commands/platform.js"; -import { handleAppCommand } from "./commands/app.js"; -import { handleMenuCommand } from "./commands/menu.js"; -import { handleSkillCommand } from "./commands/skill.js"; -import { handleProbeCommand } from "./commands/probe.js"; -import { handleMcpCommand } from "./commands/mcp.js"; -import { handleUpdateCommand } from "./commands/update.js"; -import { handleOpenApiCommand } from "./commands/openapi.js"; -import { handleBillCommand } from "./commands/bill.js"; -import { handleContactCommand } from "./commands/contact.js"; -import { handleServiceCommand } from "./commands/service.js"; -import { handleHttpCommand } from "./commands/http.js"; -import { handleTaskCommand } from "./commands/task.js"; -import { handleMessageCommand } from "./commands/message.js"; -import { handleDimensionCommand } from "./commands/dimension.js"; -import { handleRoleCommand } from "./commands/role.js"; -import { handlePermissionCommand } from "./commands/permission.js"; -import { handleRuleCommand } from "./commands/rule.js"; -import { handleApprovalCommand } from "./commands/approval.js"; -import { handleContextCommand } from "./commands/context.js"; -import { handleKeysCommand } from "./commands/keys.js"; -import { handleStoreCommand } from "./commands/store.js"; -import { handleFeeTypeCommand } from "./commands/feetype.js"; +import { findCommandByArea, isStandingCommand } from "./registry.js"; import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js"; -const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]); - -function isStandingCommand(args: string[]): boolean { - if (!args.length) return false; - const first = args[0]?.toLowerCase(); - const second = args[1]?.toLowerCase(); - if (STANDING_COMMANDS.has(first)) return true; - if ((first === "service" || first === "daemon") && second === "run") return true; - return false; -} - let runQueue = Promise.resolve(undefined); export function runCli( @@ -175,131 +138,18 @@ async function dispatchCli( }); try { - switch (parsed.area) { - case "context": - case "status": - case "whoami": - case "env": - return await handleContextCommand(parsed, runtime); - case "aipro": { - const { runAiProCli } = await import("../aipro-cli.js"); - const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro"); - const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1); - return await runAiProCli(subArgs); - } - case "auth": - case "login": - return await handleAuthCommand(parsed, runtime); - case "corps": - case "corp": - return await handleCorpsCommand(parsed, runtime); - case "config": - case "mode": - return await handleConfigCommand(parsed, runtime); - case "workflow": - case "workflows": - case "wf": - return await handleWorkflowCommand(parsed, runtime); - case "bill": - case "bills": - case "fee": - case "fees": - case "invoice": - case "invoices": - return await handleBillCommand(parsed, runtime); - case "contact": - case "contacts": - case "staff": - case "staffs": - return await handleContactCommand(parsed, runtime); - case "task": - case "tasks": - case "todo": - return await handleTaskCommand(parsed, runtime); - case "dimension": - case "dimensions": - case "archive": - case "archives": - return await handleDimensionCommand(parsed, runtime); - case "feetype": - case "feetypes": - case "fee-type": - case "fee-types": - case "expense-type": - case "expense-types": - case "costtype": - return await handleFeeTypeCommand(parsed, runtime); - case "role": - case "roles": - return await handleRoleCommand(parsed, runtime); - case "permission": - case "permissions": - return await handlePermissionCommand(parsed, runtime); - case "rule": - case "rules": - return await handleRuleCommand(parsed, runtime); - case "approval": - case "approvals": - case "audit": - return await handleApprovalCommand(parsed, runtime); - case "message": - case "messages": - case "notify": - case "notifications": - return await handleMessageCommand(parsed, runtime); - case "platform": - case "platforms": - case "datalink": - case "data-link": - return await handlePlatformCommand(parsed, runtime); - case "app": - case "apps": - case "workbench": - return await handleAppCommand(parsed, runtime); - case "menu": - case "menus": - return await handleMenuCommand(parsed, runtime); - case "skill": - case "skills": - return await handleSkillCommand(parsed, runtime); - case "probe": - case "diagnose": - return await handleProbeCommand(parsed, runtime); - case "update": - case "upgrade": - case "self-update": - case "changelog": - return await handleUpdateCommand(parsed, runtime, options); - case "openapi": - case "schema": - case "spec": - return await handleOpenApiCommand(parsed, runtime); - case "keys": - case "key": - case "secret": - case "secrets": - return await handleKeysCommand(parsed, runtime); - case "store": - case "market": - return await handleStoreCommand(parsed, runtime); - case "http": - case "server": - case "web": - return await handleHttpCommand(parsed, runtime); - case "service": - case "daemon": - return await handleServiceCommand(parsed, runtime); - case "mcp": - return await handleMcpCommand(parsed, options); - case undefined: - return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 }; - default: - return { - stdout: "", - stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`, - exitCode: 1, - }; + if (!parsed.area) { + return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 }; } + const commandDef = findCommandByArea(parsed.area); + if (!commandDef) { + return { + stdout: "", + stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`, + exitCode: 1, + }; + } + return await commandDef.handler(parsed, runtime, options); } catch (error) { const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error)); const classification = classifyCliError(error);