diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 670946c..8f28033 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -27,8 +27,8 @@ override that path. The legacy `current-corp` file is not read. ## Stream & Exit Code Contract - **`stdout`**: Pure, deterministic JSON for machine/Agent parsing. -- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`). -- **`Exit Code`**: `0` on success; `1` for runtime/upstream failures, `2` for usage or argument errors, `10` when an explicit destructive-operation confirmation is required, `11` for missing/invalid authentication, and `12` when output protection requires a compact or file-based query. +- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** with the stable prefix `👉 Next action: seal-use ...`. +- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative. ## Top-Level Commands diff --git a/src/cli.test.ts b/src/cli.test.ts index d88a581..c4fbd18 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -57,7 +57,7 @@ describe("CLI version & help handling", () => { test("invalid command displays unknown command error with help hint", () => { const result = runCli(["invalid-command"]); - expect(result.status).toBe(1); + expect(result.status).toBe(2); expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-use help' for available commands."); }); diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index 8aaa80e..c3c090d 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -6,6 +6,7 @@ import { booleanOption, jsonObject, stringOption } from "../parser.js"; import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import * as api from "../../domains/seal/api.js"; +import { CliError } from "../errors.js"; export async function handleDeployCommand( systemOrAction: string | undefined, @@ -83,7 +84,13 @@ export async function handleDeployCommand( console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`); console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`); } - throw new Error("缺少必需参数 。请从上述候选列表中选择并指定 signKey。"); + throw new CliError( + "缺少必需参数 。请从上述候选列表中选择并指定 signKey。", + 2, + hoseConfigs.length === 1 + ? `seal-use deploy hosecloud get ${hoseConfigs[0]!.signKey} --corp ${corp.id}` + : undefined + ); } await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options)); return; @@ -143,7 +150,13 @@ export async function handleDeployCommand( console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`); } - throw new Error("缺少必需参数 。请从上述候选列表中选择并指定 signKey 执行同步。"); + throw new CliError( + "缺少必需参数 。请从上述候选列表中选择并指定 signKey 执行同步。", + 2, + hoseConfigs.length === 1 + ? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}` + : undefined + ); } await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options)); diff --git a/src/cli/commands/rules.ts b/src/cli/commands/rules.ts index db73028..936f7f7 100644 --- a/src/cli/commands/rules.ts +++ b/src/cli/commands/rules.ts @@ -1,6 +1,7 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runTool, runToolResult } from "../helpers.js"; +import { confirmationRequired } from "../errors.js"; import { booleanOption, numberOption, @@ -63,7 +64,10 @@ export async function handleRulesCommand( const confirmed = booleanOption(args.options.yes) === true; const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed; if (!confirmed && !dryRun) { - throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview."); + throw confirmationRequired( + "Refusing to clear rules without --yes. Use --dry-run to preview.", + `seal-use rules clear --corp ${corp.id} --dry-run` + ); } const result = await runToolResult("seal_approval_rules_clear", client, corp, { dryRun, diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 391c8e1..c3e84a6 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -22,6 +22,7 @@ import { import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js"; +import { CliError, confirmationRequired } from "../errors.js"; export async function handleWebhookMaterialPackPreview( filePath: string, @@ -100,7 +101,11 @@ export async function handleWebhookCommand( const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", "); throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook 指定目标通道。`); } else { - throw new Error("当前租户未配置任何 Webhook 集成通道。请先运行 'seal-use webhook add --name ... --result-url ...' 创建通道。"); + throw new CliError( + "当前租户未配置任何 Webhook 集成通道。", + 1, + `seal-use webhook add --name --result-url --corp ${corp.id}` + ); } const result = await pushMaterialPack(input.fileBuffer, input.fileName, { webhookUrl: integration.incomingDocumentWebhook.url, @@ -220,7 +225,10 @@ export async function handleWebhookCommand( const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); if (!selector) throw new Error("Usage: seal-use webhook delete --yes"); if (booleanOption(args.options.yes) !== true) { - throw new Error("Refusing to delete Webhook integration without --yes"); + throw confirmationRequired( + "Refusing to delete Webhook integration without --yes", + `seal-use webhook delete ${selector} --corp ${corp.id} --yes` + ); } await runTool( "seal_webhook_delete", diff --git a/src/cli/errors.test.ts b/src/cli/errors.test.ts new file mode 100644 index 0000000..af929a8 --- /dev/null +++ b/src/cli/errors.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from "bun:test"; +import { CliError, classifyCliError, confirmationRequired, PayloadTooLargeError } 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 "); + + expect(classifyCliError(error)).toEqual({ + exitCode: 2, + nextAction: "seal-use deploy hosecloud get " + }); + }); + + test("classifies confirmation and output protection distinctly", () => { + expect(classifyCliError(confirmationRequired("Refusing to delete", "seal-use webhook delete --yes"))).toMatchObject({ + exitCode: 10, + nextAction: "seal-use webhook delete --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 }); + }); +}); diff --git a/src/cli/errors.ts b/src/cli/errors.ts new file mode 100644 index 0000000..57709b8 --- /dev/null +++ b/src/cli/errors.ts @@ -0,0 +1,58 @@ +export type CliExitCode = 1 | 2 | 10 | 11 | 12; + +export class CliError extends Error { + readonly exitCode: CliExitCode; + readonly nextAction?: string; + + constructor(message: string, exitCode: CliExitCode, nextAction?: string) { + super(message); + this.name = "CliError"; + this.exitCode = exitCode; + this.nextAction = nextAction; + } +} + +export class PayloadTooLargeError extends CliError { + constructor(message: string, nextAction?: string) { + super(message, 12, nextAction); + this.name = "PayloadTooLargeError"; + } +} + +export function usageError(message: string, nextAction?: string): CliError { + return new CliError(message, 2, nextAction); +} + +export function confirmationRequired(message: string, nextAction: string): CliError { + return new CliError(message, 10, nextAction); +} + +export function classifyCliError(error: unknown): { + exitCode: CliExitCode; + nextAction?: string; +} { + if (error instanceof CliError) { + return { exitCode: error.exitCode, nextAction: error.nextAction }; + } + + const value = error instanceof Error ? error.message : String(error); + const status = responseStatus(error); + if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) { + return { exitCode: 11 }; + } + if (/^(?:Usage:|Unknown (?:command|auth|config|corps|delegation|deploy|llm|permissions|preference|rules|simulation|users|webhook)|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/.test(value)) { + return { exitCode: 2 }; + } + if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) { + return { exitCode: 10 }; + } + return { exitCode: 1 }; +} + +function responseStatus(error: unknown): number | undefined { + if (!error || typeof error !== "object") return undefined; + const response = (error as { response?: unknown }).response; + if (!response || typeof response !== "object") return undefined; + const status = (response as { status?: unknown }).status; + return typeof status === "number" ? status : undefined; +} diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 1b43524..1404846 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -1,6 +1,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 { usageError } from "./errors.js"; export function parseArgs(argv: string[]): ParsedArgs { const command: string[] = []; @@ -13,8 +14,12 @@ export function parseArgs(argv: string[]): ParsedArgs { if (arg === "--json") { const raw = argv[index + 1]; - if (!raw) throw new Error("--json requires a JSON object argument"); - json = JSON.parse(raw); + if (!raw) throw usageError("--json requires a JSON object argument"); + try { + json = JSON.parse(raw); + } catch (error) { + throw usageError(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`); + } index += 1; continue; } @@ -47,7 +52,7 @@ export function parseArgs(argv: string[]): ParsedArgs { export function jsonObject(value: unknown): Record { if (value === undefined) return {}; if (!value || typeof value !== "object" || Array.isArray(value)) { - throw new Error("--json must be an object"); + throw usageError("--json must be an object"); } return value as Record; } @@ -59,7 +64,7 @@ export function stringOption(value: string | boolean | undefined): string | unde export function numberOption(value: string | boolean | undefined): number | undefined { if (typeof value !== "string") return undefined; const number = Number(value); - if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`); + if (!Number.isFinite(number)) throw usageError(`Invalid number: ${value}`); return number; } @@ -74,7 +79,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un if (typeof value === "boolean") return value; if (value === "true") return true; if (value === "false") return false; - throw new Error(`Invalid boolean: ${value}`); + throw usageError(`Invalid boolean: ${value}`); } export function requiredString(input: Record, key: string): string { diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 50f39a6..c23effc 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -1,5 +1,6 @@ import { writeFileSync } from "node:fs"; import { booleanOption, stringOption } from "./parser.js"; +import { PayloadTooLargeError } from "./errors.js"; import type { OutputOptions } from "./types.js"; const RULE_LIST_FULL_COUNT_LIMIT = 100; @@ -37,7 +38,7 @@ function protectLargeOutput(result: unknown, options: OutputOptions = {}) { if (options.allowFull || options.outputFile) return; const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { - throw new Error( + throw new PayloadTooLargeError( `Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.` ); } @@ -56,8 +57,9 @@ export function protectLargeRuleListOutput(result: unknown, allowFull: boolean) const effectiveCount = count ?? rulesCount ?? 0; if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) { - throw new Error( - `Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.` + throw new PayloadTooLargeError( + `Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`, + "seal-use rules list --summary" ); } } diff --git a/src/cli/runner.test.ts b/src/cli/runner.test.ts index cb784d7..03a108c 100644 --- a/src/cli/runner.test.ts +++ b/src/cli/runner.test.ts @@ -17,7 +17,15 @@ describe("CLI runner", () => { const result = await runCli(["not-a-command"]); expect(result.isError).toBe(true); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); expect(result.stderr).toContain("Unknown command: not-a-command"); }); + + test("returns a semantic usage exit code for invalid JSON", async () => { + const result = await runCli(["version", "--json", "not-json"]); + + expect(result.isError).toBe(true); + expect(result.exitCode).toBe(2); + expect(result.stderr).toContain("Invalid JSON:"); + }); }); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index dabd7de..9105dcf 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -30,6 +30,7 @@ import { handleToolsListCommand } from "./commands/tools.js"; import { handleUpdateCommand } from "./commands/update.js"; import { handleUsersCommand } from "./commands/users.js"; import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js"; +import { classifyCliError } from "./errors.js"; import { selectCorp } from "./helpers.js"; import { booleanOption, @@ -137,12 +138,17 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise