import { VERSION } from "../version.js"; import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js"; import { printHelp, printJson, redactSensitiveText } from "./printer.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 { 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 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( rawArgs: string[], options: CliRunOptions = {} ): Promise { if (isStandingCommand(rawArgs)) { return dispatchCli(rawArgs, options); } const run = runQueue.then(() => runCliOnce(rawArgs, options)); runQueue = run.then( () => undefined, () => undefined ); return run; } async function runCliOnce( rawArgs: string[], options: CliRunOptions = {} ): Promise { const stdoutChunks: string[] = []; const stderrChunks: string[] = []; const originalLog = console.log; const originalError = console.error; console.log = (...values: unknown[]) => { stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" ")); }; console.error = (...values: unknown[]) => { stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" ")); }; try { const result = await dispatchCli(rawArgs, options); const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : ""; const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : ""; return { stdout: redactSensitiveText(extraStdout + (result.stdout || "")), stderr: redactSensitiveText(extraStderr + (result.stderr || "")), exitCode: result.exitCode, }; } finally { console.log = originalLog; console.error = originalError; } } function isHelpRequested(parsed: CliParsedArgs): boolean { const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase(); if (normArea === "help" || normArea === "h" || normArea === "?") return true; for (const [key, val] of Object.entries(parsed.options)) { const normKey = key.replace(/^-+/, "").toLowerCase(); if (normKey === "help" || normKey === "h" || normKey === "?") { if (val === true || val === "true" || val === "") return true; } } return false; } function isVersionRequested(parsed: CliParsedArgs): boolean { const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase(); if (normArea === "version" || normArea === "v") return true; for (const [key, val] of Object.entries(parsed.options)) { const normKey = key.replace(/^-+/, "").toLowerCase(); if (normKey === "version" || normKey === "v") { if (val === true || val === "true" || val === "") return true; } } return false; } async function dispatchCli( rawArgs: string[], options: CliRunOptions = {} ): Promise { const parsed = parseArgs(rawArgs); if (isHelpRequested(parsed)) { return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 }; } if (isVersionRequested(parsed)) { return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 }; } const jsonMode = booleanOption(parsed.options, ["json", "j"]); const corpIdOption = stringOption(parsed.options, ["corp", "c"]); const statelessOption = booleanOption(parsed.options, ["stateless"]); const statefulOption = booleanOption(parsed.options, ["stateful"]); const outputOpts = outputOptions(parsed.options); const runtime = initCorpRuntime({ corpId: corpIdOption, stateless: statelessOption, stateful: statefulOption, jsonMode, outputOptions: outputOpts, appRoot: options.appRoot, entryFile: options.entryFile, launcher: options.launcher, }); 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 "role": case "roles": return await handleRoleCommand(parsed, runtime); case "permission": case "permissions": return await handlePermissionCommand(parsed, runtime); case "rule": case "rules": return await handleRuleCommand(parsed, runtime); case "approval": case "approvals": case "audit": return await handleApprovalCommand(parsed, runtime); case "message": case "messages": case "notify": case "notifications": return await handleMessageCommand(parsed, runtime); case "platform": case "platforms": case "app": case "apps": return await handlePlatformCommand(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 "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() + "\n", stderr: "", exitCode: 0 }; default: return { stdout: "", stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`, exitCode: 1, }; } } catch (error) { const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error)); if (jsonMode) { return { stdout: printJson({ error: true, message: errorMsg }), stderr: "", exitCode: 1, }; } return { stdout: "", stderr: `[ERROR] ${errorMsg}\n`, exitCode: 1, }; } }