#!/usr/bin/env bun import { isDryRun, mutationPreview } from "./cli/mutation.js"; import { parseArgs, stringOption, booleanOption, isJsonRequested } from "./cli/parser.js"; import { cliErrorResult } from "./cli/runner.js"; import { printHelp, printJson, redactSensitiveText } from "./cli/printer.js"; import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js"; import { ApprovalService, ApprovalRepository, ApprovalGatewayBlockedError, } from "./domains/approval/index.js"; import { formatVersionLabel, getVersionInfo } from "./version.js"; import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js"; import { handleAiProChecklist, handleAiProPoints, handleAiProRules, handleAiProScopes, } from "./cli/commands/aipro/rules.js"; import { handleAiProBind, handleAiProDecide, handleAiProInit, handleAiProReview, handleAiProTranslate, } from "./cli/commands/aipro/session.js"; import type { AiProExecutionContext } from "./cli/commands/aipro/types.js"; export async function runAiProCli( rawArgs: string[] ): Promise<{ stdout: string; stderr: string; exitCode: number }> { try { return await runAiProCliOnce(rawArgs); } catch (error) { return cliErrorResult(error, isJsonRequested(rawArgs)); } } async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> { const parsed = parseArgs(rawArgs, "aipro"); const jsonMode = booleanOption(parsed.options, ["json", "j"]); if (booleanOption(parsed.options, ["help", "h", "?"])) { const help = printHelp(["aipro", ...(parsed.area && parsed.area !== "help" ? [parsed.area] : [])]); return { stdout: jsonMode ? printJson({ help }) : `${help}\n`, stderr: "", exitCode: 0 }; } const runtime = initCorpRuntime({ corpId: stringOption(parsed.options, ["corp"]), jsonMode, }); const corp = runtime.selectedCorp; const previewPositional = parsed.positional || []; const previewCommand = (previewPositional[0] || "help").toLowerCase(); const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3); if (mutating && isDryRun(parsed, runtime)) { return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) }); } const repo = new ApprovalRepository(); const service = new ApprovalService(repo); let cachedSession: Awaited> | undefined; const positional = parsed.positional ?? [parsed.area, parsed.action, ...parsed.args].filter((v): v is string => Boolean(v)); const command = (positional[0] || "help").toLowerCase(); const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]); const corpId = corp?.corpId || corp?.id; const operator = corp?.credentials?.staffId || corp?.staffId || corp?.name || "AI-Agent"; const requireCorpId = () => { const selected = requireSelectedCorp(runtime); return selected.corpId || selected.id; }; const getClient = async () => { cachedSession ??= await getSessionClientForRuntime(runtime); return { client: cachedSession.client, corpId: cachedSession.corpId }; }; const ctx: AiProExecutionContext = { rawArgs, parsed, runtime, corp, corpId, operator, positional, command, targetSn, jsonMode, repo, service, requireCorpId, getClient, }; try { if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) { return { stdout: jsonMode ? printJson(getVersionInfo("hose-aipro")) + "\n" : `${formatVersionLabel("hose-aipro")}\n`, stderr: "", exitCode: 0, }; } switch (command) { case "status": case "whoami": case "context": case "info": return await handleAiProStatus(ctx); case "init": case "start": return await handleAiProInit(ctx); case "scopes": case "index": case "indexes": return await handleAiProScopes(ctx); case "translate": case "doc": case "markdown": case "render": return await handleAiProTranslate(ctx); case "rules": case "rule": return await handleAiProRules(ctx); case "bind": case "mount": return await handleAiProBind(ctx); case "points": case "clauses": return await handleAiProPoints(ctx); case "checklist": case "list": return await handleAiProChecklist(ctx); case "review": case "eval": case "evaluate": return await handleAiProReview(ctx); case "decide": case "approve": case "reject": return await handleAiProDecide(ctx); case "logs": case "log": case "history": case "trail": return await handleAiProLogs(ctx); case "help": default: return handleAiProHelp(ctx); } } catch (err: any) { if (err instanceof ApprovalGatewayBlockedError) { repo.logAiProAction({ action: command, documentSn: targetSn, operator, args: JSON.stringify(rawArgs), status: "BLOCKED", summary: err.message.replace(/\n+/g, " "), }); return { stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "", stderr: jsonMode ? "" : `\n${err.message}\n`, exitCode: 1, }; } repo.logAiProAction({ action: command, documentSn: targetSn, operator, args: JSON.stringify(rawArgs), status: "ERROR", summary: String(err?.message || err), }); return { stdout: jsonMode ? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n" : "", stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`, exitCode: 1, }; } } if (import.meta.main) { const rawArgs = process.argv.slice(2); const result = await runAiProCli(rawArgs); if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout)); if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr)); process.exit(result.exitCode); }