Fix architecture review findings and align CLI metadata

This commit is contained in:
gitea committed 2026-10-17 20:17:06 +08:00
1 parent 780a4ba9c0
commit 50e4e492b4
83 files changed
+966 -792

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
/** Execution aliases shared by dispatch, help, and the read-only gateway. */
export const AREA_ALIASES: Readonly<Record<string, string>> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference",
server: "mcp"
}
export const UPDATE_ALIASES = new Set([
"update", "upgrade", "up", "self-update", "selfupdate"
])
export function normalizeCliArea(area: string): string {
const lower = area.toLowerCase()
return UPDATE_ALIASES.has(lower) ? "update" : AREA_ALIASES[lower] ?? lower
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
@@ -31,7 +32,7 @@ export async function handleAnalyticsCommand(
if (action === "risks" || action === "risks-by-tag" || action === "tag-risks") {
const tagId = maybeName ?? stringOption(args.options.tagId) ?? stringOption(args.options["tag-id"]);
if (!tagId) {
throw new Error("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
throw usageError("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
}
await runCapability(
"sealInsightRisksByTagGet",
@@ -64,7 +65,7 @@ export async function handleAnalyticsCommand(
if (action === "analyze" || action === "reanalyze") {
const recordId = maybeName ?? stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]);
if (!recordId) {
throw new Error("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
throw usageError("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
}
await runCapability(
"sealInsightRecordAnalyze",
@@ -91,5 +92,5 @@ export async function handleAnalyticsCommand(
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+12 -15
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
@@ -151,7 +152,7 @@ export async function handleApprovalRunsCommand(
if (action === "pick") {
const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn);
if (!query) throw new Error("Usage: seal-use approval-runs pick --sn <documentSN>");
if (!query) throw usageError("Usage: seal-use approval-runs pick --sn <documentSN>");
await runCapability(
"sealApprovalRunPick",
client,
@@ -199,14 +200,14 @@ export async function handleApprovalRunsCommand(
if (action === "cited-rules") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs cited-rules <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs document-summary <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
@@ -215,7 +216,7 @@ export async function handleApprovalRunsCommand(
const recordId = args.command[2];
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw new Error("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRunDiagnose",
@@ -236,9 +237,7 @@ export async function handleApprovalRunsCommand(
if (subAction === "download") {
const recordId = args.command[3];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -259,7 +258,7 @@ export async function handleApprovalRunsCommand(
}
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (booleanOption(args.options.download)) {
const record = await api.getApprovalRun(client, recordId);
@@ -291,9 +290,7 @@ export async function handleApprovalRunsCommand(
if (action === "download") {
const recordId = args.command[2];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -315,7 +312,7 @@ export async function handleApprovalRunsCommand(
if (action === "result") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs result <recordId> [--summary]");
if (!recordId) throw usageError("Usage: seal-use approval-runs result <recordId> [--summary]");
await runCapability(
"sealApprovalRunResultGet",
client,
@@ -344,7 +341,7 @@ export async function handleApprovalRunsCommand(
const sourceDocumentId = stringOption(args.options.sourceDocumentId);
if (!recordId && !sn && !sourceDocumentId) {
throw new Error("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
}
await runCapability(
@@ -373,7 +370,7 @@ export async function handleApprovalRunsCommand(
stringOption(args.options.id) ??
stringOption(args.options.recordId);
if (!target) {
throw new Error("Usage: seal-use approval-runs hose-flow <recordId|SN>");
throw usageError("Usage: seal-use approval-runs hose-flow <recordId|SN>");
}
await runCapability(
@@ -451,5 +448,5 @@ export async function handleApprovalRunsCommand(
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+5 -7
View File
@@ -8,7 +8,7 @@ import {
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError } from "../../core/errors.js";
import { CliError, validationError, usageError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
@@ -26,9 +26,7 @@ import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]"
);
throw usageError("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");
}
const reveal =
booleanOption(args.options.reveal) === true ||
@@ -81,7 +79,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
if (!corp) {
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
throw validationError(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
}
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
@@ -99,7 +97,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
if (subAction === "revoke") {
const tokenId = args.command[3] ?? stringOption(args.options.tokenId) ?? stringOption(args.options.id);
if (!tokenId) throw new Error("Usage: seal-use auth link revoke <tokenId>");
if (!tokenId) throw usageError("Usage: seal-use auth link revoke <tokenId>");
await runCapability("sealDelegationRevoke", client, corp, { tokenId }, outputOptions(args.options));
return;
}
@@ -201,7 +199,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
async function diagnoseAuth(corp: CorpConfig) {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -25,5 +26,5 @@ export async function handleBillingCommand(
return;
}
throw new Error(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import {
getEnterprisesDirCandidates,
loadCorpConfigs,
@@ -123,5 +124,5 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -27,16 +28,16 @@ export async function handleContactsCommand(
}
if (action === "children" || action === "department-children") {
if (!maybeName) throw new Error("Usage: seal-use contacts children <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts children <departmentId>");
await runCapability("sealContactsDepartmentChildrenList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "users" || action === "department-users") {
if (!maybeName) throw new Error("Usage: seal-use contacts users <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts users <departmentId>");
await runCapability("sealContactsDepartmentUsersList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
throw new Error(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { handleCorpBindings } from "./corps/bindings.js";
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
import { handleCorpOverview } from "./corps/overview.js";
@@ -17,5 +18,5 @@ export async function handleCorpsCommand(
if (await handleCorpSync(action, maybeName, args)) return;
if (await handleCorpOnboarding(action, maybeName, args)) return;
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+4 -4
View File
@@ -14,7 +14,7 @@ import {
formatHoseKeyForOutput,
HoseKeySelectionError
} from "../../../domains/hose/keys.js";
import { CliError } from "../../errors.js";
import { CliError, usageError } from "../../../core/errors.js";
import { selectCorp } from "../../helpers.js";
import {
booleanOption,
@@ -181,7 +181,7 @@ export async function handleCorpOnboarding(
if (action === "add-link") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
throw usageError("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
}
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
const legacyAsHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true;
@@ -211,7 +211,7 @@ export async function handleCorpOnboarding(
if (action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
throw usageError("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
}
await extractKeysFromLinkAction(link, {
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true || booleanOption(args.options.plain) === true,
@@ -250,7 +250,7 @@ export async function handleCorpOnboarding(
async function addSealCorp(input: Record<string, unknown>) {
const token = requiredString(input, "token");
const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, "");
if (!sealUrl) throw new Error("Missing required JSON field: sealUrl");
if (!sealUrl) throw usageError("Missing required JSON field: sealUrl");
const result = await onboardSealBearer({
...input,
token,
+3 -3
View File
@@ -12,7 +12,7 @@ import {
} from "../../../core/stats/usage-tracker.js";
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
@@ -192,7 +192,7 @@ export async function handleCorpOverview(
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
if (!targetCorpId || !newName) {
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
throw usageError("Usage: seal-use corps rename <corpId> --name <newName>");
}
const corp = selectCorp(targetCorpId);
@@ -208,7 +208,7 @@ export async function handleCorpOverview(
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
if (!corpId) throw usageError("Usage: seal-use corps switch <corpId>");
const globalConfig = loadGlobalConfig();
if (!globalConfig.stateful) {
throw new Error(
+1 -1
View File
@@ -3,7 +3,7 @@ import type { CorpConfig } from "../../../core/config/types.js";
import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
import { selectCorp } from "../../helpers.js";
import { CliError, confirmationRequired, usageError } from "../../errors.js";
import { CliError, confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { outputOptions, printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -29,5 +30,5 @@ export async function handleDataCommand(
return;
}
throw new Error(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -8
View File
@@ -7,7 +7,7 @@ import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
import { CliError } from "../errors.js";
import { CliError, usageError, validationError } from "../../core/errors.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -18,16 +18,14 @@ export async function handleDeployCommand(
args: ParsedArgs
) {
if (!systemOrAction || systemOrAction === "help") {
throw new Error(
"Usage: seal-use deploy <system> <action> [options]\n\n" +
throw usageError("Usage: seal-use deploy <system> <action> [options]\n\n" +
"支持的审批系统与发布目标:\n" +
" • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\n" +
" • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>\n" +
" • feishu (飞书审批): 建议使用 Webhook 模式对接\n" +
" • weaver (泛微 OA): 建议使用 Webhook 模式对接\n" +
" • helios (汇联易): 建议使用 Webhook 模式对接\n" +
" • maycur (每刻报销): 建议使用 Webhook 模式对接"
);
" • maycur (每刻报销): 建议使用 Webhook 模式对接");
}
if (systemOrAction === "webhook" || systemOrAction === "webhooks") {
@@ -52,7 +50,7 @@ export async function handleDeployCommand(
const target = systemOrAction === "hosecloud" ? maybeTarget : actionOrTarget;
if (!isHosecloud) {
throw new Error(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
throw validationError(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
}
if (action === "requirements") {
@@ -108,7 +106,7 @@ export async function handleDeployCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
throw usageError("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
}
await runCapability("sealDeployHosecloudConfigure", client, corp, {
...payload,
@@ -200,6 +198,6 @@ export async function handleDeployCommand(
return;
}
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
throw usageError(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
}
+1 -1
View File
@@ -44,7 +44,7 @@ export async function handleDoctorCommand(
const { selectCorp } = await import("../helpers.js");
const { createSealClient } = await import("../../core/http/factory.js");
const { stringOption } = await import("../parser.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../core/doctor/tenant-diagnose.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../domains/seal/doctor/tenant-diagnose.js");
const corpSelector =
stringOption(args.options.corp) ??
+7 -11
View File
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import {
booleanOption,
@@ -55,7 +55,7 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents get <documentId> [--corp <corpId>]");
throw usageError("Usage: seal-use documents get <documentId> [--corp <corpId>]");
}
await runCapability(
"sealApprovalDocumentGet",
@@ -70,7 +70,7 @@ export async function handleDocumentsCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) {
throw new Error("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
throw usageError("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
}
await runCapability(
"sealApprovalSearch",
@@ -115,9 +115,7 @@ export async function handleDocumentsCommand(
(Array.isArray(payload.tags) ? (payload.tags as string[]) : undefined);
if (!title || !purpose || content === undefined) {
throw new Error(
"Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
@@ -179,9 +177,7 @@ export async function handleDocumentsCommand(
tags !== undefined;
if (!documentId || !hasChanges) {
throw new Error(
"Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
@@ -211,7 +207,7 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
@@ -230,5 +226,5 @@ export async function handleDocumentsCommand(
return;
}
throw new Error(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
throw usageError(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../errors.js";
import { CliError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
+2 -4
View File
@@ -1,4 +1,4 @@
import { validationError } from "../../core/errors.js";
import { validationError, usageError } from "../../core/errors.js";
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
import { runLangfuseCapability } from "../helpers.js";
import { outputOptions } from "../printer.js";
@@ -151,9 +151,7 @@ export async function handleLangfuseCommand(
return;
}
throw new Error(
`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`
);
throw usageError(`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
function parseMetadataOption(raw: string | undefined): Record<string, string | number | boolean> | undefined {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handleLlmCommand(
return;
}
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handlePermissionsCommand(
return;
}
throw new Error(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -5
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
@@ -27,7 +28,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
throw usageError("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
}
await runCapability("sealPreferenceDecisionUpdate", client, corp, {
...payload,
@@ -44,7 +45,7 @@ export async function handlePreferenceCommand(
stringOption(args.options.level) ??
maybeTarget;
if (defaultLevel !== "medium" && defaultLevel !== "high") {
throw new Error("Usage: seal-use preference thinking-depth set --default <medium|high>");
throw usageError("Usage: seal-use preference thinking-depth set --default <medium|high>");
}
await runCapability("sealPreferenceThinkingDepthSet", client, corp, {
defaultLevel,
@@ -65,7 +66,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || !payload.id || !payload.name) {
throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
throw usageError("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
}
await runCapability("sealPreferenceThinkingDepthPoliciesUpsert", client, corp, {
...payload,
@@ -77,7 +78,7 @@ export async function handlePreferenceCommand(
if (thirdAction === "remove" || thirdAction === "delete") {
const policyId = maybeTarget ?? stringOption(args.options.id) ?? stringOption(args.options.policyId);
if (!policyId) {
throw new Error("Usage: seal-use preference thinking-depth policies remove <policyId>");
throw usageError("Usage: seal-use preference thinking-depth policies remove <policyId>");
}
await runCapability("sealPreferenceThinkingDepthPoliciesRemove", client, corp, {
policyId,
@@ -88,5 +89,5 @@ export async function handlePreferenceCommand(
}
}
throw new Error(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
throw usageError(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
}
+11 -11
View File
@@ -9,7 +9,7 @@ import {
OFFICIAL_LINTERS_DIR
} from "../../domains/seal/linter/index.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, validationError, usageError } from "../../core/errors.js";
import {
booleanOption,
jsonObject,
@@ -58,7 +58,7 @@ export async function handleRulesCommand(
// lint, linters, and map actions can run without a network client
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
if (!client && !clientless) {
throw new Error(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
throw validationError(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
}
if (action === "count") {
@@ -145,7 +145,7 @@ export async function handleRulesCommand(
if (action === "version") {
const version = resolveVersionOption(args, maybeName);
if (!version) throw new Error("Usage: seal-use rules version <versionNumber|latest>");
if (!version) throw usageError("Usage: seal-use rules version <versionNumber|latest>");
await runCapability(
"sealApprovalRuleVersionGet",
client!,
@@ -160,7 +160,7 @@ export async function handleRulesCommand(
const from = stringOption(args.options.from) ?? maybeName;
const to = stringOption(args.options.to) ?? args.command[3];
if (!from || !to) {
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
throw usageError("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
}
const singleSelector = args.command[4];
await runCapability(
@@ -190,7 +190,7 @@ export async function handleRulesCommand(
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]);
if (!target) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleGet",
@@ -214,7 +214,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : "MUST_FOLLOW");
if (!description || !scope) {
throw new Error("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleCreate",
@@ -240,7 +240,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : undefined);
if (!ruleId || (description === undefined && scope === undefined && strictness === undefined)) {
throw new Error("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleUpdate",
@@ -259,7 +259,7 @@ export async function handleRulesCommand(
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code);
if (!ruleId) {
throw new Error("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
@@ -287,7 +287,7 @@ export async function handleRulesCommand(
stringOption(args.options.name) ??
(typeof payload.versionName === "string" ? payload.versionName : undefined);
if (!versionName) {
throw new Error("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
throw usageError("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleVersionPublish",
@@ -301,7 +301,7 @@ export async function handleRulesCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
if (!keyword) throw usageError("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
await runCapability(
"sealApprovalSearch",
client!,
@@ -465,5 +465,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
}
+9 -9
View File
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError, validationError } from "../../core/errors.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import {
booleanOption,
@@ -22,7 +22,7 @@ export async function handleSimulationCommand(
) {
if (action === "batch-records" || action === "records") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation batch-records <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation batch-records <batchId>");
await runCapability(
"sealSimulationBatchRecordsGet",
client,
@@ -142,7 +142,7 @@ export async function handleSimulationCommand(
if (action === "wait") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
if (!batchId) throw usageError("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
await runCapability(
"sealSimulationBatchWait",
client,
@@ -159,7 +159,7 @@ export async function handleSimulationCommand(
if (action === "status") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation status <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation status <batchId>");
await runCapability(
"sealSimulationBatchStatus",
client,
@@ -172,7 +172,7 @@ export async function handleSimulationCommand(
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation clean <batchId> --yes");
if (!batchId) throw usageError("Usage: seal-use simulation clean <batchId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -220,7 +220,7 @@ export async function handleSimulationCommand(
if (action === "get") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation get <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation get <batchId>");
await runCapability("sealSimulationBatchGet", client, corp, { batchId }, outputOptions(args.options));
return;
}
@@ -237,11 +237,11 @@ export async function handleSimulationCommand(
if (action === "package-upload") {
const filePath = maybeName ?? stringOption(args.options.file);
if (!filePath) throw new Error("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
await runCapability("sealSimulationMaterialPackageUpload", client, corp, { filePath }, outputOptions(args.options));
return;
}
throw new Error(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
@@ -66,5 +67,5 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
return;
}
throw new Error(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
import { printJson } from "../printer.js";
@@ -8,5 +9,5 @@ export async function handleSourceCommand(action: string | undefined, corp: Corp
return;
}
throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { CliError } from "../errors.js";
import { CliError } from "../../core/errors.js";
import { selectCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
+8 -8
View File
@@ -1,6 +1,6 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
@@ -16,7 +16,7 @@ export async function handleUsersCommand(
if (action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const phone = stringOption(args.options.phone);
if (!name || !phone) throw new Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
if (!name || !phone) throw usageError("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId);
const departmentIds = deptId ? [deptId] : undefined;
await runCapability("sealUserCreate", client, corp, { name, phone, departmentIds }, outputOptions(args.options));
@@ -25,7 +25,7 @@ export async function handleUsersCommand(
if (action === "reset-password") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users reset-password <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users reset-password <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -45,14 +45,14 @@ export async function handleUsersCommand(
if (action === "get") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users get <userId>");
if (!userId) throw usageError("Usage: seal-use users get <userId>");
await runCapability("sealUserGet", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delete") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users delete <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users delete <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -66,14 +66,14 @@ export async function handleUsersCommand(
if (action === "activate") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users activate <userId>");
if (!userId) throw usageError("Usage: seal-use users activate <userId>");
await runCapability("sealUserActivate", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delegation" || action === "impersonate") {
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
if (!userIdOrPhone) throw usageError("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
@@ -87,5 +87,5 @@ export async function handleUsersCommand(
return;
}
throw new Error(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+11 -13
View File
@@ -32,13 +32,13 @@ import {
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError, validationError } from "../errors.js";
import { CliError, confirmationRequired, usageError, validationError } from "../../core/errors.js";
export async function handleWebhookResourcePackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
printJson(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy));
}
@@ -110,9 +110,7 @@ export async function handleWebhookCommand(
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
if (!recordId && !recordIds && !sn && !sns && limit === undefined) {
throw new Error(
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
);
throw usageError("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");
}
const sourceCorpId =
@@ -317,14 +315,14 @@ export async function handleWebhookCommand(
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
printJson(await previewMaterialPack(input.fileBuffer, input.fileName), outputOptions(args.options));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (operation !== "push") throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
@@ -370,7 +368,7 @@ export async function handleWebhookCommand(
if (action === "get" || action === "find") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook get <idOrName> [--show-secret]");
if (!selector) throw usageError("Usage: seal-use webhook get <idOrName> [--show-secret]");
await runCapability(
"sealWebhookGet",
client,
@@ -392,7 +390,7 @@ export async function handleWebhookCommand(
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
if (!name || !outgoingResultWebhook) {
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
throw usageError("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
@@ -417,7 +415,7 @@ export async function handleWebhookCommand(
if (action === "update") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook update <idOrName> [options]");
if (!selector) throw usageError("Usage: seal-use webhook update <idOrName> [options]");
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
@@ -468,7 +466,7 @@ export async function handleWebhookCommand(
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (!selector) throw usageError("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (booleanOption(args.options.yes) !== true && !dryRun) {
throw confirmationRequired(
"Refusing to delete Webhook integration without --yes",
@@ -489,5 +487,5 @@ export async function handleWebhookCommand(
return;
}
throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
-106
View File
@@ -1,106 +0,0 @@
import { describe, expect, test } from "bun:test";
import {
CliError,
classifyCliError,
confirmationRequired,
PayloadTooLargeError,
safetyBlocked,
validationError
} from "./errors.js";
describe("CLI semantic errors", () => {
test("preserves explicit exit codes and next actions", () => {
const error = new CliError("missing sign key", 2, "seal-use deploy hosecloud get <sign-key>");
expect(classifyCliError(error)).toEqual({
exitCode: 2,
nextAction: "seal-use deploy hosecloud get <sign-key>"
});
});
test("classifies confirmation and output protection distinctly", () => {
expect(classifyCliError(confirmationRequired("Refusing to delete", "seal-use webhook delete <id> --yes"))).toMatchObject({
exitCode: 10,
nextAction: "seal-use webhook delete <id> --yes"
});
expect(classifyCliError(new PayloadTooLargeError("Output too large"))).toEqual({ exitCode: 12 });
});
test("classifies authentication failures from response status", () => {
expect(classifyCliError({ response: { status: 401 } })).toEqual({ exitCode: 11 });
expect(classifyCliError(new Error("bearer token expired"))).toEqual({ exitCode: 11 });
});
test("classifies unknown commands and subcommands across all domains as usage errors", () => {
expect(classifyCliError(new Error("Unknown command: not-a-command"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown contacts command: . Run 'seal-use help' for available commands."))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown data command: bad-subcommand"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown analytics command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown approval-runs command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown billing command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown webhook command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Usage: seal-use contacts children <departmentId>"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Invalid boolean: now"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown deploy hosecloud action: x"))).toEqual({ exitCode: 2 });
});
test("classifies local config and input-data failures as validation errors (13)", () => {
// Chinese-language usage wording: the message names a flag/parameter to supply.
expect(
classifyCliError(new Error("当前租户存在多个 Webhook 通道 [\"a\" (1)],请通过 --webhook <idOrName> 指定目标通道。"))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。"))).toEqual({ exitCode: 13 });
// Enterprise selection: well-formed command, incomplete local config.
expect(
classifyCliError(new Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>."))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("No enterprise config found for nope"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("rules lint requires an authenticated enterprise. Run 'seal-use corps list' to select one."))
).toEqual({ exitCode: 13 });
// Local file input the caller must fix.
expect(classifyCliError(new Error("File not found: /tmp/missing.json"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象"))
).toEqual({ exitCode: 13 });
// Structural signals that carry no message prefix.
expect(classifyCliError(new SyntaxError("JSON Parse error: Expected '}'"))).toEqual({ exitCode: 13 });
expect(classifyCliError({ issues: [{ path: ["environment"], message: "Invalid option" }] })).toEqual({ exitCode: 13 });
});
test("classifies safety-guard blocks distinctly (14)", () => {
expect(
classifyCliError(new Error("目标企业「生产目标企业」(prod) 标记为生产正式环境 (production)。"))
).toEqual({ exitCode: 14 });
expect(classifyCliError(new Error("重放目标企业「T」(t) 的环境为「production」,非测试环境!"))).toEqual({
exitCode: 14
});
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force"))).toEqual({
exitCode: 14,
nextAction: "seal-use webhook replay --force"
});
});
test("validationError helper carries exit 13 with next action", () => {
expect(classifyCliError(validationError("请选择目标通道", "seal-use webhook list"))).toEqual({
exitCode: 13,
nextAction: "seal-use webhook list"
});
});
test("keeps domain failures, post-mutation recovery errors, and quality gates at exit 1", () => {
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
exitCode: 1
});
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
expect(
classifyCliError(new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。"))
).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("上游网关响应超时,请重试或检查网络连接。"))).toEqual({ exitCode: 1 });
});
});
-12
View File
@@ -1,12 +0,0 @@
// Re-export from core — this file is the legacy entry point.
// Domain-layer code should import from "../core/errors.js" directly.
export {
type CliExitCode,
CliError,
PayloadTooLargeError,
usageError,
validationError,
safetyBlocked,
confirmationRequired,
classifyCliError
} from "../core/errors.js";
+3 -6
View File
@@ -1,5 +1,6 @@
import { normalizeCliArea } from "./area-aliases.js";
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
import { usageError } from "../core/errors.js";
export interface CommandOptionHelp {
flag: string;
@@ -1639,14 +1640,10 @@ export function renderHelp(target: string[] = []): string {
}
function normalizeArea(area: string): string {
const lower = area.toLowerCase();
if (lower === "corp") return "corps";
if (lower === "webhooks") return "webhook";
if (lower === "preferences") return "preference";
const lower = normalizeCliArea(area);
if (lower === "changelog") return "update";
if (lower === "serve") return "http";
if (lower === "mcp-config") return "mcp";
if (lower === "server") return "mcp";
return lower;
}
+22 -16
View File
@@ -1,6 +1,5 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import {
booleanOption,
BOOLEAN_FLAGS,
@@ -203,23 +202,30 @@ describe("option helpers", () => {
describe("flag registry cross-check", () => {
test("every flag documented in help.ts is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const documented = new Set(
[...help.matchAll(/flag: "--([a-z][a-z0-9-]*)"/g)].map((match) => match[1]!)
);
for (const flag of documented) {
expect(KNOWN_FLAGS.has(flag)).toBe(true);
}
const documented = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
(command.options ?? []).flatMap((option) => [...option.flag.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...documented].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
expect(documented.size).toBeGreaterThanOrEqual(20);
});
test("every flag shown in a help usage line is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const usageFlags = new Set(
[...help.matchAll(/ --([a-z][a-z0-9-]*)/g)].map((match) => match[1]!)
);
const missing = [...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag));
expect(missing).toEqual([]);
test("every flag shown in a help usage line is registered, including bracket and pipe forms", () => {
const usageFlags = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
command.usage.flatMap((usage) => [...usage.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
});
test("formerly rejected public flags retain their boolean and value arity", () => {
const parsed = parseArgs(["report", "data", "--templates", "one,two", "--latest", "record"]);
expect(parsed.options).toEqual({ templates: "one,two", latest: true });
expect(parsed.command).toEqual(["report", "data", "record"]);
expect(parseArgs(["config", "test-dir", "--clear"]).options.clear).toBe(true);
expect(parseArgs(["webhook", "get", "id", "--show-secret"]).options["show-secret"]).toBe(true);
expect(parseArgs(["webhook", "update", "id", "--min-file-size", "10", "--clear-max-file-size"]).options)
.toEqual({ "min-file-size": "10", "clear-max-file-size": true });
expect(() => parseArgs(["report", "data", "--templates"])).toThrow("requires a value");
expect(() => parseArgs(["corps", "list", "--limitt=5"])).toThrow("Unknown option: --limitt");
});
test("boolean and value sets partition the registry apart from the ambiguous three", () => {
+16 -60
View File
@@ -2,7 +2,7 @@ import type { WebhookMode } from "../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "./types.js";
import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js";
import { usageError } from "./errors.js";
import { usageError, validationError } from "../core/errors.js";
/**
* Flag metadata for argv parsing, derived from how the code reads each flag:
@@ -23,6 +23,7 @@ import { usageError } from "./errors.js";
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret",
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
@@ -40,6 +41,9 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"allowed-extensions", "allowedExtensions", "extensions", "auto-approval-rate", "autoApprovalRate", "approval-rate",
"min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes",
"max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
@@ -86,60 +90,9 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "comment", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "glossary", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-glossary", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
"startDate", "startTime", "state", "status", "strict", "strictness",
"summary", "tag", "tag-id", "tagId", "tags", "target",
"template",
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
"until", "url", "userId", "v", "version", "version-name",
"verdict",
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
...BOOLEAN_FLAGS,
...VALUE_FLAGS,
"f", "h", "version"
]);
export function parseArgs(argv: string[]): ParsedArgs {
@@ -170,6 +123,9 @@ export function parseArgs(argv: string[]): ParsedArgs {
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
if (!KNOWN_FLAGS.has(key)) {
throw usageError(`Unknown option: --${key}.${suggestFlag(key)}`);
}
options[key] = val;
continue;
}
@@ -283,7 +239,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un
export function requiredString(input: Record<string, unknown>, key: string): string {
const value = optionalString(input, key);
if (!value) throw new Error(`Missing required JSON field: ${key}`);
if (!value) throw usageError(`Missing required JSON field: ${key}`);
return value;
}
@@ -292,7 +248,7 @@ export function requiredStringAlias(input: Record<string, unknown>, keys: string
const value = optionalString(input, key);
if (value) return value;
}
throw new Error(`Missing required JSON field: ${keys.join(" or ")}`);
throw usageError(`Missing required JSON field: ${keys.join(" or ")}`);
}
export function optionalString(input: Record<string, unknown>, key: string): string | undefined {
@@ -318,7 +274,7 @@ export function parseStateMode(value: string): boolean {
const normalized = value.trim().toLowerCase();
if (["stateful", "state", "有状态"].includes(normalized)) return true;
if (["stateless", "无状态"].includes(normalized)) return false;
throw new Error("Invalid config mode. Use stateful or stateless.");
throw validationError("Invalid config mode. Use stateful or stateless.");
}
export function parseRuleVersionSelector(value: string) {
@@ -388,7 +344,7 @@ export function parseWebhookMode(value?: string): WebhookMode | undefined {
};
const mode = aliases[normalized];
if (!mode) {
throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
throw validationError("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
}
return mode;
}
@@ -398,7 +354,7 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]
);
if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) {
throw new Error("Webhook auto approval rate must be an integer between 0 and 100");
throw validationError("Webhook auto approval rate must be an integer between 0 and 100");
}
return value;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import { PayloadTooLargeError } from "./errors.js";
import { PayloadTooLargeError } from "../core/errors.js";
import { redactSensitiveText } from "../core/redact.js";
import type { OutputOptions } from "./types.js";
+2 -8
View File
@@ -1,3 +1,4 @@
import { normalizeCliArea } from "./area-aliases.js";
import { parseArgs } from "./parser.js";
/**
@@ -12,13 +13,6 @@ import { parseArgs } from "./parser.js";
* Prefix matching is boundary-safe by construction: `list-evil` does not match `list`.
*/
/** Area aliases the CLI dispatches under an alternative name; mirrors the pairs in runner.ts. */
const AREA_ALIASES: Record<string, string> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference"
};
/**
* Commands that only read tenant state, produce a local file, or inspect local configuration.
* Deliberately excluded even though they look harmless: anything that writes local config
@@ -122,7 +116,7 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
const { command } = parseArgs(argv);
const area = (command[0] ?? "").toLowerCase();
return {
area: AREA_ALIASES[area] ?? area,
area: normalizeCliArea(area),
actionTokens: command.slice(1).map((token) => token.toLowerCase())
};
}
+119 -227
View File
@@ -5,7 +5,7 @@ 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 } from "./errors.js";
import { classifyCliError, usageError } from "../core/errors.js";
import {
booleanOption,
materialPackFilePolicyOptions,
@@ -22,52 +22,70 @@ import {
printJson,
redactSensitiveText
} from "./printer.js";
import type { CliResult, CliRunOptions, CliRuntime } from "./types.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 const UPDATE_ALIASES = new Set([
"update",
"upgrade",
"up",
"self-update",
"selfupdate"
]);
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),
"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([
"config",
"update",
"corps",
"corp",
"source",
"hose-ebot",
"auth",
"users",
"contacts",
"data",
"llm",
"permissions",
"billing",
"webhook",
"webhooks",
"context",
"documents",
"rules",
"approval-runs",
"analytics",
"report",
"simulation",
"deploy",
"preference",
"preferences",
"mcp",
"server",
"mcp-config",
"skill",
"probe",
"doctor",
"langfuse",
"changelog",
"test"
...Object.keys(LOCAL_COMMANDS),
...Object.keys(CORP_COMMANDS),
...Object.keys(CLIENT_COMMANDS),
...Object.keys(AREA_ALIASES)
]);
export type { CliResult, CliRunOptions } from "./types.js";
@@ -140,12 +158,53 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
}
}
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 isUpdate = lowerArea ? UPDATE_ALIASES.has(lowerArea) : false;
const area = isUpdate ? "update" : lowerArea;
const area = lowerArea ? normalizeCliArea(lowerArea) : undefined;
if (
area === "version" ||
@@ -186,7 +245,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (!area || !KNOWN_AREAS.has(area)) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (
@@ -195,36 +254,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
maybeName === "preview"
) {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
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 === "mcp-config") {
(await import("./commands/mcp.js")).printMcpConfig();
return;
}
if (area === "skill") {
(await import("./commands/skill.js")).handleSkillCommand(action, maybeName, args);
return;
}
if (area === "mcp" || area === "server") {
await (await import("./commands/mcp.js")).handleMcpCommand(action);
return;
}
if (area === "probe") {
await (await import("./commands/probe.js")).handleProbeCommand(action, maybeName, args);
return;
}
if (area === "doctor") {
await (await import("./commands/doctor.js")).handleDoctorCommand(action, maybeName, args);
return;
}
if (
area === "report" &&
(action === "validate" ||
@@ -239,69 +273,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
// Langfuse trace inspection needs no tenant: it authenticates with the
// compile-time injected read-only key pair, so it dispatches before corp
// selection (like probe/doctor) and never touches a Seal client.
if (area === "langfuse") {
await (await import("./commands/langfuse.js")).handleLangfuseCommand(action, maybeName, args);
return;
}
if (area === "test") {
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
return;
}
if (area === "config") {
(await import("./commands/config.js")).handleConfigCommand(action, maybeName, args);
return;
}
if (isUpdate || area === "changelog") {
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;
}
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", maybeName, args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, maybeName, args);
// 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;
}
@@ -339,102 +315,18 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
if (area === "source") {
await (await import("./commands/source.js")).handleSourceCommand(action, corp);
const corpCommand = CORP_COMMANDS[area];
if (corpCommand) {
await corpCommand(args, corp);
return;
}
if (area === "auth") {
await (await import("./commands/auth.js")).handleAuthCommand(action, corp, args);
const clientCommand = CLIENT_COMMANDS[area];
if (clientCommand) {
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
await clientCommand(args, corp, client);
return;
}
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
if (area === "users") {
await (await import("./commands/users.js")).handleUsersCommand(action, maybeName, client, corp, args);
return;
}
if (area === "contacts") {
await (await import("./commands/contacts.js")).handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await (await import("./commands/data.js")).handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await (await import("./commands/llm.js")).handleLlmCommand(action, client, corp, args);
return;
}
if (area === "permissions") {
await (await import("./commands/permissions.js")).handlePermissionsCommand(action, client, corp, args);
return;
}
if (area === "billing") {
await (await import("./commands/billing.js")).handleBillingCommand(action, client, corp, args);
return;
}
if (area === "webhook" || area === "webhooks") {
await (await import("./commands/webhook.js")).handleWebhookCommand(action, maybeName, client, corp, args);
return;
}
if (area === "context") {
await (await import("./commands/context.js")).handleContextCommand(client, corp, args);
return;
}
if (area === "documents") {
await (await import("./commands/documents.js")).handleDocumentsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "rules") {
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, client, corp, args);
return;
}
if (area === "approval-runs") {
await (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "analytics") {
await (await import("./commands/analytics.js")).handleAnalyticsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "report") {
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "deploy") {
await (await import("./commands/deploy.js")).handleDeployCommand(action, maybeName, args.command[3], client, corp, args);
return;
}
if (area === "hose-ebot") {
await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
}
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
+3 -2
View File
@@ -3,6 +3,7 @@
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
* need it; importing it from the server entry would make the CLI graph circular.
*/
import { usageError } from "../core/errors.js";
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
@@ -53,8 +54,8 @@ export function tokenizeCommand(command: string): string[] {
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (escaped) throw usageError("Invalid command: trailing escape");
if (quote) throw usageError("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}