Group CLI modules into parse, run, output, and help
Move parser, tokenize, and area-aliases under cli/parse; runner and read-only under cli/run; printer under cli/output; help plus the docs/naming contract tests under cli/help. types.ts and helpers.ts stay at the cli root. Update imports, the app-root depth calculation, test fixtures, and the CLI doc generator path. No behavior change.
This commit is contained in:
1 parent
37b54065d9
commit
ca9d87e13f
80 files changed
+196
-195
No files matched your search
Executable
+389
@@ -0,0 +1,389 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { VERSION_INFO } from "../../version.js";
|
||||
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../../core/update/update-cache.js";
|
||||
import { classifyCliError, usageError, validationError } from "../../core/errors.js";
|
||||
import { isCorpDisabledError } from "../../core/config/active.js";
|
||||
import {
|
||||
booleanOption,
|
||||
materialPackFilePolicyOptions,
|
||||
numberOption,
|
||||
parseArgs,
|
||||
stringOption
|
||||
} from "../parse/parser.js";
|
||||
import { extractHelpRequest } from "../help/help.js";
|
||||
import { isNewerVersion } from "../../core/util/semver.js";
|
||||
import { getSkillVersionStatus } from "../../core/skill/skill-version.js";
|
||||
import {
|
||||
formatConsoleOutput,
|
||||
joinOutput,
|
||||
printHelp,
|
||||
printJson,
|
||||
redactSensitiveText
|
||||
} from "../output/printer.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
|
||||
|
||||
const DEFAULT_APP_ROOT = dirname(dirname(dirname(dirname(fileURLToPath(import.meta.url)))));
|
||||
export { UPDATE_ALIASES } from "../parse/area-aliases.js";
|
||||
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "../parse/area-aliases.js";
|
||||
|
||||
type LocalCommand = (args: ParsedArgs, runtime: CliRuntime) => Promise<void>;
|
||||
type CorpCommand = (args: ParsedArgs, corp: CorpConfig) => Promise<void>;
|
||||
type ClientCommand = (args: ParsedArgs, corp: CorpConfig, client: KyInstance) => Promise<void>;
|
||||
|
||||
// Handler tables also define the known command surface. Imports stay lazy so
|
||||
// local discovery never loads the tenant, Excel, or zip implementation graphs.
|
||||
const LOCAL_COMMANDS: Record<string, LocalCommand> = {
|
||||
"mcp-config": async () => (await import("../commands/mcp.js")).printMcpConfig(),
|
||||
skill: async (args) => (await import("../commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args),
|
||||
mcp: async (args) => (await import("../commands/mcp.js")).handleMcpCommand(args.command[1]),
|
||||
probe: async (args) => (await import("../commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args),
|
||||
doctor: async (args) => (await import("../commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args),
|
||||
langfuse: async (args) => (await import("../commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args),
|
||||
test: async (args) => (await import("../commands/test.js")).handleTestCommand(args.command[1], args.command[2], args),
|
||||
config: async (args) => (await import("../commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args),
|
||||
update: dispatchUpdate,
|
||||
changelog: dispatchUpdate,
|
||||
corps: async (args) => {
|
||||
const action = args.command[1];
|
||||
// Local discovery must not initialize onboarding, sync or the capability registry.
|
||||
if (!action || ["list", "search", "find"].includes(action)) {
|
||||
await (await import("../commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args);
|
||||
return;
|
||||
}
|
||||
if (action === "regression" || action === "test-regression") {
|
||||
await (await import("../commands/test.js")).handleTestCommand("regression", args.command[2], args);
|
||||
return;
|
||||
}
|
||||
await (await import("../commands/corps.js")).handleCorpsCommand(action, args.command[2], args);
|
||||
}
|
||||
};
|
||||
|
||||
const CORP_COMMANDS: Record<string, CorpCommand> = {
|
||||
source: async (args, corp) => (await import("../commands/source.js")).handleSourceCommand(args.command[1], corp),
|
||||
auth: async (args, corp) => (await import("../commands/auth.js")).handleAuthCommand(args.command[1], corp, args)
|
||||
};
|
||||
|
||||
const CLIENT_COMMANDS: Record<string, ClientCommand> = {
|
||||
"users": async (args, corp, client) => (await import("../commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"contacts": async (args, corp, client) => (await import("../commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"data": async (args, corp, client) => (await import("../commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
|
||||
"invoices": async (args, corp, client) => (await import("../commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"expenses": async (args, corp, client) => (await import("../commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
|
||||
"llm": async (args, corp, client) => (await import("../commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
|
||||
"permissions": async (args, corp, client) => (await import("../commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
|
||||
"billing": async (args, corp, client) => (await import("../commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
|
||||
"webhook": async (args, corp, client) => (await import("../commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"context": async (args, corp, client) => (await import("../commands/context.js")).handleContextCommand(client, corp, args),
|
||||
"documents": async (args, corp, client) => (await import("../commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"rules": async (args, corp, client) => (await import("../commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"approval-runs": async (args, corp, client) => (await import("../commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"analytics": async (args, corp, client) => (await import("../commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"report": async (args, corp, client) => (await import("../commands/report.js")).handleReportCommand(args.command[1], client, corp, args),
|
||||
"simulation": async (args, corp, client) => (await import("../commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"deploy": async (args, corp, client) => (await import("../commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args),
|
||||
"hose-ebot": async (args, corp, client) => (await import("../commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args),
|
||||
"preference": async (args, corp, client) => (await import("../commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args),
|
||||
};
|
||||
|
||||
export const KNOWN_AREAS = new Set([
|
||||
...Object.keys(LOCAL_COMMANDS),
|
||||
...Object.keys(CORP_COMMANDS),
|
||||
...Object.keys(CLIENT_COMMANDS),
|
||||
...Object.keys(AREA_ALIASES)
|
||||
]);
|
||||
|
||||
export type { CliResult, CliRunOptions } from "../types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["server", "mcp"]);
|
||||
|
||||
function isStandingCommand(argv: string[]): boolean {
|
||||
if (!argv.length) return false;
|
||||
const first = argv[0]?.toLowerCase();
|
||||
if (first && STANDING_COMMANDS.has(first)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let runQueue = Promise.resolve();
|
||||
|
||||
export function runCli(argv: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
if (isStandingCommand(argv)) {
|
||||
return runCliOnce(argv, options);
|
||||
}
|
||||
const run = runQueue.then(() => runCliOnce(argv, options));
|
||||
runQueue = run.then(
|
||||
() => undefined,
|
||||
() => undefined
|
||||
);
|
||||
return run;
|
||||
}
|
||||
|
||||
async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliResult> {
|
||||
const stdout: string[] = [];
|
||||
const stderr: string[] = [];
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
const runtime: CliRuntime = {
|
||||
appRoot: options.appRoot ?? DEFAULT_APP_ROOT,
|
||||
entryFile: options.entryFile ?? join(options.appRoot ?? DEFAULT_APP_ROOT, "src", "cli.ts"),
|
||||
launcher: options.launcher
|
||||
};
|
||||
|
||||
console.log = (...values: unknown[]) => {
|
||||
stdout.push(formatConsoleOutput(values));
|
||||
};
|
||||
console.error = (...values: unknown[]) => {
|
||||
const line = redactSensitiveText(formatConsoleOutput(values));
|
||||
stderr.push(line);
|
||||
options.onStderr?.(`${line}\n`);
|
||||
};
|
||||
|
||||
try {
|
||||
await dispatch(argv, runtime);
|
||||
return {
|
||||
stdout: joinOutput(stdout),
|
||||
stderr: joinOutput(stderr),
|
||||
isError: false,
|
||||
exitCode: 0
|
||||
};
|
||||
} catch (error) {
|
||||
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
console.error(message);
|
||||
if (classification.nextAction && !message.includes("Next action:")) {
|
||||
console.error(`👉 Next action: ${classification.nextAction}`);
|
||||
}
|
||||
return {
|
||||
stdout: joinOutput(stdout),
|
||||
stderr: joinOutput(stderr),
|
||||
isError: true,
|
||||
exitCode: classification.exitCode
|
||||
};
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
console.error = originalError;
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<void> {
|
||||
const [rawArea, action] = args.command;
|
||||
const isUpdate = rawArea ? UPDATE_ALIASES.has(rawArea.toLowerCase()) : false;
|
||||
const area = rawArea?.toLowerCase();
|
||||
if (isUpdate && rawArea !== "update") {
|
||||
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
|
||||
}
|
||||
|
||||
const lowerAction = action?.toLowerCase();
|
||||
const isChangelog =
|
||||
area === "changelog" ||
|
||||
lowerAction === "changelog" ||
|
||||
lowerAction === "log" ||
|
||||
lowerAction === "history" ||
|
||||
booleanOption(args.options.changelog) === true;
|
||||
|
||||
const isCheck =
|
||||
lowerAction === "check" ||
|
||||
booleanOption(args.options.check) === true ||
|
||||
booleanOption(args.options["check-only"]) === true;
|
||||
|
||||
const isBgSave =
|
||||
booleanOption(args.options["bg-save"]) === true ||
|
||||
booleanOption(args.options["silent-save"]) === true;
|
||||
|
||||
const isSystem = booleanOption(args.options.system) === true || lowerAction === "system";
|
||||
const isUser = booleanOption(args.options.user) === true || lowerAction === "user";
|
||||
|
||||
if (isSystem && isUser) {
|
||||
throw validationError("Cannot specify both --system and --user.");
|
||||
}
|
||||
|
||||
if (rawArea === "migrate" && !isSystem && !isUser) {
|
||||
throw usageError("Usage: seal-use migrate --system | --user", "seal-use migrate --user");
|
||||
}
|
||||
|
||||
const targetVersion =
|
||||
stringOption(args.options.version) ??
|
||||
stringOption(args.options.tag) ??
|
||||
(!isChangelog && !isCheck && !isBgSave && !isSystem && !isUser && action && !action.startsWith("-") ? action : undefined);
|
||||
|
||||
await (await import("../commands/update.js")).handleUpdateCommand(runtime, {
|
||||
checkOnly: isCheck || isBgSave,
|
||||
changelogOnly: isChangelog,
|
||||
limit: numberOption(args.options.limit),
|
||||
force: booleanOption(args.options.force),
|
||||
targetVersion,
|
||||
repo: stringOption(args.options.repo),
|
||||
bgSave: isBgSave,
|
||||
system: isSystem,
|
||||
user: isUser
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
const args = parseArgs(argv);
|
||||
const [rawArea, action, maybeName] = args.command;
|
||||
const lowerArea = rawArea?.toLowerCase();
|
||||
const area = lowerArea ? normalizeCliArea(lowerArea) : undefined;
|
||||
|
||||
if (
|
||||
area === "version" ||
|
||||
area === "v" ||
|
||||
(!area && (Boolean(args.options.version) || Boolean(args.options.v) || Boolean(args.options.V)))
|
||||
) {
|
||||
const cache = loadUpdateCache();
|
||||
const isUpgrade = cache?.latestVersion ? isNewerVersion(cache.latestVersion, VERSION_INFO.version) : false;
|
||||
|
||||
const payload = {
|
||||
...VERSION_INFO,
|
||||
skill: getSkillVersionStatus(VERSION_INFO.version),
|
||||
...(cache?.latestVersion
|
||||
? {
|
||||
latestVersion: cache.latestVersion,
|
||||
updateAvailable: isUpgrade,
|
||||
lastCheckedAt: cache.checkedAt
|
||||
}
|
||||
: {})
|
||||
};
|
||||
|
||||
if (isUpgrade && cache?.latestVersion) {
|
||||
console.error(`💡 发现新版本可用: v${VERSION_INFO.version} -> v${cache.latestVersion}`);
|
||||
console.error(`👉 Next action: seal-use update\n`);
|
||||
}
|
||||
if (["skill_newer", "cli_newer", "unknown"].includes(payload.skill.status)) {
|
||||
console.error(`技能版本与 CLI 需要核对: CLI ${payload.skill.cliVersion}, Skill ${payload.skill.installedVersion ?? "无法识别"}`);
|
||||
console.error(`👉 Next action: ${payload.skill.nextAction}`);
|
||||
}
|
||||
|
||||
printJson(payload);
|
||||
|
||||
if (isUpdateCacheExpired(cache)) {
|
||||
triggerBackgroundUpdateCheck(runtime.launcher);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const helpRequest = extractHelpRequest(args);
|
||||
if (helpRequest.isHelp) {
|
||||
printHelp(helpRequest.target);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!area || !KNOWN_AREAS.has(area)) {
|
||||
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
if (
|
||||
area === "webhook" &&
|
||||
(action === "resource-pack" || action === "pack" || action === "material-pack") &&
|
||||
maybeName === "preview"
|
||||
) {
|
||||
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack preview <资源包.zip>");
|
||||
await (await import("../commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
area === "report" &&
|
||||
(action === "validate" ||
|
||||
action === "render" ||
|
||||
action === "export" ||
|
||||
action === "template" ||
|
||||
action === "chart" ||
|
||||
action === "review" ||
|
||||
Boolean(args.options.ledger))
|
||||
) {
|
||||
await (await import("../commands/report.js")).handleLocalReportCommand(action, args);
|
||||
return;
|
||||
}
|
||||
|
||||
// These handlers intentionally run before enterprise selection, including
|
||||
// Langfuse's compile-time credentials and purely local discovery commands.
|
||||
const localCommand = LOCAL_COMMANDS[area];
|
||||
if (localCommand) {
|
||||
await localCommand(args, runtime);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
|
||||
let corp: CorpConfig;
|
||||
try {
|
||||
corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp));
|
||||
} catch (error) {
|
||||
// Local lint tolerates a missing enterprise config, but a disabled tenant
|
||||
// is an explicit block: never degrade into the synthetic workspace corp.
|
||||
if (isCorpDisabledError(error)) throw error;
|
||||
corp = {
|
||||
id: "local",
|
||||
name: "Local Workspace",
|
||||
source: { type: "native" }
|
||||
} as any;
|
||||
}
|
||||
await (await import("../commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
area === "auth" &&
|
||||
(action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys")
|
||||
) {
|
||||
await (await import("../commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
area === "auth" &&
|
||||
(action === "link" || action === "seal-link") &&
|
||||
("from-link" in args.options || maybeName === "from-link")
|
||||
) {
|
||||
await (await import("../commands/auth.js")).handleAuthCommand(action, null, args);
|
||||
return;
|
||||
}
|
||||
|
||||
// Local task observation and previews must not authenticate or contact a tenant.
|
||||
if (area === "approval-runs" && (action === "export" || action === "export-worker")) {
|
||||
await (await import("../commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime);
|
||||
return;
|
||||
}
|
||||
|
||||
const corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp));
|
||||
|
||||
const maybePromptDivergences = async () => {
|
||||
if (area === "report" && action === "review") return;
|
||||
try {
|
||||
const { countUnreviewedDivergences, shouldPromptDivergence } = await import(
|
||||
"../../domains/seal/reports/pipeline/review-store.js"
|
||||
);
|
||||
const count = countUnreviewedDivergences(corp.id, 30);
|
||||
if (count > 0 && shouldPromptDivergence(corp.id)) {
|
||||
console.error(
|
||||
`ℹ️ [review-reminder] 检测到企业「${corp.name}」在近 30 天内有 ${count} 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。\n👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp ${corp.id} 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp ${corp.id}`
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// 容错降级,不阻断主流程
|
||||
}
|
||||
};
|
||||
|
||||
const corpCommand = CORP_COMMANDS[area];
|
||||
if (corpCommand) {
|
||||
await corpCommand(args, corp);
|
||||
await maybePromptDivergences();
|
||||
return;
|
||||
}
|
||||
|
||||
const clientCommand = CLIENT_COMMANDS[area];
|
||||
if (clientCommand) {
|
||||
const client = await (await import("../../core/http/factory.js")).createSealClient(corp);
|
||||
await clientCommand(args, corp, client);
|
||||
await maybePromptDivergences();
|
||||
return;
|
||||
}
|
||||
|
||||
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
Reference in new issue
Block a user