335 lines
14 KiB
TypeScript
Executable File
335 lines
14 KiB
TypeScript
Executable File
#!/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-cache.js";
|
|
import { classifyCliError, usageError } from "../core/errors.js";
|
|
import {
|
|
booleanOption,
|
|
materialPackFilePolicyOptions,
|
|
numberOption,
|
|
parseArgs,
|
|
stringOption
|
|
} from "./parser.js";
|
|
import { extractHelpRequest } from "./help.js";
|
|
import { isNewerVersion } from "../core/semver.js";
|
|
import {
|
|
formatConsoleOutput,
|
|
joinOutput,
|
|
printHelp,
|
|
printJson,
|
|
redactSensitiveText
|
|
} from "./printer.js";
|
|
import type { KyInstance } from "ky";
|
|
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
|
|
|
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
export { UPDATE_ALIASES } from "./area-aliases.js";
|
|
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "./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];
|
|
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/data.js")).handleDataCommand("expenses", 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[]) => {
|
|
stderr.push(formatConsoleOutput(values));
|
|
};
|
|
|
|
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);
|
|
stderr.push(message);
|
|
if (classification.nextAction && !message.includes("Next action:")) {
|
|
stderr.push(`👉 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 targetVersion =
|
|
stringOption(args.options.version) ??
|
|
stringOption(args.options.tag) ??
|
|
(!isChangelog && !isCheck && !isBgSave && 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
|
|
});
|
|
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,
|
|
...(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`);
|
|
}
|
|
|
|
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 {
|
|
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;
|
|
}
|
|
|
|
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
|
|
|
|
const corpCommand = CORP_COMMANDS[area];
|
|
if (corpCommand) {
|
|
await corpCommand(args, corp);
|
|
return;
|
|
}
|
|
|
|
const clientCommand = CLIENT_COMMANDS[area];
|
|
if (clientCommand) {
|
|
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
|
|
await clientCommand(args, corp, client);
|
|
return;
|
|
}
|
|
|
|
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
|
|
}
|