diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 6d8555f..84be11d 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -40,6 +40,7 @@ seal-use corps list - Parse JSON stdout. Do not scrape human text. - Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`. - Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`. +- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate `contentType` and `scenarios` before creating, and use `enabled: false` when the document should be withdrawn. - For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise. - Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing. - For date questions, use explicit dates and `--timezone Asia/Shanghai`. @@ -55,7 +56,7 @@ seal-use corps list - First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically. - User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp --note ''`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version. -- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp ` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system `, `simulation wait ` 轮询等待完成, `simulation clean ` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。 +- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp ` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system `, `simulation status ` 单次查询状态, `simulation wait ` 轮询等待完成, `simulation clean ` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。 - Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud --corp `; read `references/hose-enterprise-deploy.md`. - 审核决策偏好与思考深度: `seal-use preference get --corp `, `preference decision update --json '...' --corp `, `preference thinking-depth set --default --corp `, `preference thinking-depth policies --corp `. - 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp `, `seal-use approval-runs count --corp `. diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 7a78b7b..b956b50 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, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation. +- **`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 @@ -102,9 +102,10 @@ seal-use approval-runs url --corp seal-use approval-runs url --sourceDocumentSN --corp seal-use approval-runs bridge --corp [--sourceDocumentSN ] seal-use simulation batch-records --corp -seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp +seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp seal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp +seal-use simulation status --corp seal-use simulation wait [--timeout 10m] [--poll-interval 2s] --corp seal-use simulation clean --corp seal-use simulation specifications [--integration ] --corp @@ -142,9 +143,16 @@ Approval rule maintenance: - `seal-use rules list --summary [--corp ]` - `seal-use rules pull [--corp ] [--version ] [--out ]` - `seal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]` -- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]` +- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred. - `seal-use rules clear [--corp ] [--dry-run|--yes]` +Rule identity and versioning: + +- `rules list` and `rules pull` read the current **draft** rule set. Their `code` values belong to the draft code space. +- A published version has its own snapshot and code space. Publishing can recode rules, so a published `code` may differ from the draft `code`, and codes can shift again after later edits and publishes. +- Do not use a draft `#NN` as a cross-version identifier. For current draft work, prefer the stable rule `id`; for historical behavior, select the published `version` and locate the rule by its text/context or runtime rule ID from the approval run. +- `rules get --version ... --code ...` interprets `code` inside that selected published version, while `rules get --record-id ... --runtime-id ...` resolves the version recorded on the run. + Approval run lightweight queries: - `seal-use approval-runs get --corp --fields metadata` @@ -183,7 +191,8 @@ Approval runs, simulations, and Langfuse bridge: - `seal-use approval-runs search --corp [--query ] [--limit 20]` - `seal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]` - `seal-use approval-runs bridge --corp [--sourceDocumentSN ]` -- `seal-use simulation create --mode hosecloud --flow-ids ... --corp ` +- `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp ` returns immediately with an `asyncTicket` (creation is non-blocking by default for compatibility). +- `seal-use simulation status --corp ` performs one non-blocking status check and returns `QUEUED`/`RUNNING`/`COMPLETED`/`FAILED`-style state plus counters. - `seal-use simulation wait --corp ` - `seal-use simulation clean --corp ` - `seal-use simulation list --corp ` @@ -313,13 +322,17 @@ Create a document: "title": "标题", "purpose": "用途", "content": "Markdown 内容", - "contentType": "text/markdown", - "status": "可选", - "scenarios": ["场景"], + "contentType": "policy", + "status": "published", + "scenarios": ["audit"], "tags": ["标签"] } ``` +`contentType` 必须是 `document`、`video`、`pdf`、`feishu_doc` 或 `policy` 之一;`scenarios` 必填且至少包含一个 `fill`(智能填单)或 `audit`(智能审核)。这里的 `scenarios` 是产品能力开关,不是费用类别或业务场景名。 + +知识文档创建后当前 API 没有删除接口,创建操作不可逆;请在写入前确认标题、正文、内容类型和能力场景。需要撤下内容时,优先使用更新操作并设置 `enabled: false`(如果上游支持该字段),不要通过试探性创建来验证参数。规则支持删除,但知识文档与规则的生命周期能力并不对称。 + Update a document: ```json diff --git a/skills/seal-use/references/customer-feedback-rule-remediation.md b/skills/seal-use/references/customer-feedback-rule-remediation.md index d76d823..d7630a3 100644 --- a/skills/seal-use/references/customer-feedback-rule-remediation.md +++ b/skills/seal-use/references/customer-feedback-rule-remediation.md @@ -133,6 +133,8 @@ seal-use tool seal_approval_rule_update --corp \ Do not send `scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing. +For a complete local rule-set sync, `rules push` is incremental: it matches pulled rules by stable `id`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with `rules push --dry-run` before applying. + ## 9. Publish and verify Publish only when explicitly authorized: diff --git a/skills/seal-use/references/rule-lightweight.md b/skills/seal-use/references/rule-lightweight.md index babf45a..0b42305 100644 --- a/skills/seal-use/references/rule-lightweight.md +++ b/skills/seal-use/references/rule-lightweight.md @@ -2,6 +2,12 @@ Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions. +## Draft and Published Rule Codes + +`rules list` and `rules pull` operate on the current draft and therefore return draft `code` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as `#0038` is only meaningful together with its version context. + +Use the draft `id` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version. + ## Count Rules Use count when only scale or existence matters. 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 24c4aa9..facc6e6 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; @@ -146,7 +153,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/simulation.ts b/src/cli/commands/simulation.ts index c553d07..beb6bd0 100644 --- a/src/cli/commands/simulation.ts +++ b/src/cli/commands/simulation.ts @@ -62,6 +62,7 @@ export async function handleSimulationCommand( stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]) ?? stringOption(args.options.integration); + const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]); await runTool( "seal_simulation_batch_create", @@ -91,6 +92,7 @@ export async function handleSimulationCommand( endTime: numberOption(args.options.endTime) ?? numberOption(args.options["end-time"]), status: splitOption(args.options.status), limit: numberOption(args.options.limit), + noWait, rawParams: inputPayload }, outputOptions(args.options) @@ -115,6 +117,19 @@ export async function handleSimulationCommand( return; } + 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 "); + await runTool( + "seal_simulation_batch_status", + client, + corp, + { batchId }, + outputOptions(args.options) + ); + return; + } + 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 "); diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 886ba25..6d0c762 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, @@ -226,7 +231,10 @@ export async function handleWebhookCommand( const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); if (!selector) throw new Error("Usage: seal-use webhook delete [--yes|--dry-run]"); if (booleanOption(args.options.yes) !== true && !dryRun) { - 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 d9f1e54..2757168 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" ); } } @@ -167,9 +169,10 @@ Usage: seal-use approval-runs url --sourceDocumentSN B26022501 [--corp ] seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp ] seal-use simulation batch-records [--corp ] - seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp ] + seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp ] seal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp ] seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp ] + seal-use simulation status [--corp ] seal-use simulation wait [--timeout 10m] [--poll-interval 2s] [--corp ] seal-use simulation clean [--corp ] seal-use simulation specifications [--integration ] [--corp ] 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> = []; + +afterEach(() => { + for (const server of servers.splice(0)) server.stop(true); +}); + +describe("Seal HTTP client errors", () => { + test("includes ky's parsed response body after the response stream is consumed", async () => { + const server = Bun.serve({ + port: 0, + fetch: () => new Response(JSON.stringify({ + error: { + code: "error:common:invalid-parameter", + message: "contentType 取值非法" + } + }), { + status: 400, + headers: { "content-type": "application/json" } + }) + }); + servers.push(server); + + await expect( + createSealClientForUrl(`http://127.0.0.1:${server.port}`, "dummy-token").get("/") + ).rejects.toThrow( + 'Request failed with status code 400 Bad Request: GET http://127.0.0.1:' + + `${server.port}/: {"error":{"code":"error:common:invalid-parameter","message":"contentType 取值非法"}}` + ); + }); +}); diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index a0d2889..10a9aa8 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -3,6 +3,32 @@ import { CorpConfig } from "../config/types.js"; import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js"; import { resolveSealCustomHeaders } from "./request-headers.js"; +function formatErrorData(data: unknown): string { + if (data === undefined || data === null || data === "") return ""; + if (typeof data === "string") return data; + try { + return JSON.stringify(data); + } catch { + return String(data); + } +} + +function withResponseBody(error: unknown): Error { + if (!(error instanceof HTTPError)) return error as Error; + const body = formatErrorData(error.data); + if (body) error.message = `${error.message}: ${body}`; + return error; +} + +function createBeforeErrorHook(corpId?: string) { + return async ({ error }: { error: unknown }) => { + if (corpId && error instanceof HTTPError && error.response.status === 401) { + clearSealToken(corpId); + } + return withResponseBody(error); + }; +} + export async function createSealClient(corp: CorpConfig): Promise { const session = await getSealSessionForCorp(corp); @@ -14,19 +40,7 @@ export async function createSealClient(corp: CorpConfig): Promise { Authorization: `Bearer ${session.token}` }, hooks: { - beforeError: [ - async ({ error }) => { - if (error instanceof HTTPError && error.response.status === 401) { - clearSealToken(corp.id); - } - const body = - error instanceof HTTPError - ? await error.response.text().catch(() => "") - : ""; - error.message = `${error.message}${body ? `: ${body}` : ""}`; - return error; - } - ] + beforeError: [createBeforeErrorHook(corp.id)] } }); } @@ -50,16 +64,7 @@ export function createSealClientForUrl( Authorization: `Bearer ${token}` }, hooks: { - beforeError: [ - async ({ error }) => { - const body = - error instanceof HTTPError - ? await error.response.text().catch(() => "") - : ""; - error.message = `${error.message}${body ? `: ${body}` : ""}`; - return error; - } - ] + beforeError: [createBeforeErrorHook()] } }); } diff --git a/src/domains/seal/simulation.test.ts b/src/domains/seal/simulation.test.ts index 893d93f..c09b648 100644 --- a/src/domains/seal/simulation.test.ts +++ b/src/domains/seal/simulation.test.ts @@ -501,7 +501,12 @@ describe("simulation tool handlers", () => { sourceSystem: "hosecloud" }); expect(postedBody).not.toHaveProperty("limit"); - expect(result).toMatchObject({ batchId: "batch-1", created: true }); + expect(result).toMatchObject({ + batchId: "batch-1", + created: true, + noWait: true, + asyncTicket: "batch-1" + }); }); test("create tool surface exposes mode, flowIds, and rawParams", () => { @@ -509,18 +514,44 @@ describe("simulation tool handlers", () => { const { z } = require("zod") as typeof import("zod"); const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record }; expect(Object.keys(schema.properties ?? {})).toEqual( - expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds"]) + expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds", "noWait"]) ); }); test("includes the simulation management tool set", () => { expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_simulation_batch_status")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined(); }); + + test("status tool performs one non-blocking check and exposes the next action", async () => { + const tool = sealTools.find((item) => item.name === "seal_simulation_batch_status"); + expect(tool).toBeDefined(); + + const client = { + get: (url: string) => { + expect(url).toBe("api/v1/simulation/batch/batch-1"); + return { json: async () => ({ data: { ...hosecloudBatchFixture, id: "batch-1" } }) }; + } + } as unknown as KyInstance; + + const handler = tool!.handler as ToolHandler; + const result = await handler(client, { batchId: "batch-1" }, fakeContext()) as Record; + + expect(result).toMatchObject({ + batchId: "batch-1", + status: "SYNCING", + terminal: false, + next: { + status: "seal-use simulation status batch-1", + wait: "seal-use simulation wait batch-1" + } + }); + }); }); describe("simulation response schemas", () => { diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index 695fe93..fcfa8b7 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -5,7 +5,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CorpConfig } from "../../core/config/types.js"; -import { findSealTool, sealTools } from "./tools.js"; +import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js"; type ToolHandler = ( client: KyInstance, @@ -260,6 +260,87 @@ describe("sealTools", () => { expect(patched).toBe(false); }); + test("plans incremental rule updates without rebuilding matched rules", () => { + const plan = buildRulePushPlan( + [ + { + id: "rule-1", + code: 1, + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }, + { + id: "rule-2", + code: 2, + description: "Keep attendee names", + scope: "meal", + strictness: "SHOULD_FOLLOW" + } + ], + [ + { + id: "rule-1", + description: "Keep complete receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }, + { + description: "Require cost center", + scope: "all", + strictness: "SUGGESTION" + } + ] + ); + + expect(plan.updated).toMatchObject([ + { id: "rule-1", changedFields: ["description"] } + ]); + expect(plan.created).toMatchObject([ + { description: "Require cost center" } + ]); + expect(plan.deleted).toMatchObject([{ id: "rule-2", code: 2 }]); + expect(plan.unchanged).toEqual([]); + }); + + test("matches legacy local rules by unique content when no id is present", () => { + const plan = buildRulePushPlan( + [{ + id: "rule-1", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }], + [{ + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + ); + + expect(plan.created).toEqual([]); + expect(plan.updated).toEqual([]); + expect(plan.deleted).toEqual([]); + expect(plan.unchanged).toEqual([{ id: "rule-1" }]); + }); + + test("rejects local rule ids that are absent from the current draft", () => { + expect(() => buildRulePushPlan( + [{ + id: "rule-1", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }], + [{ + id: "stale-rule", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + )).toThrow("stale-rule"); + }); + test("includes approval run Langfuse bridge tools", () => { expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined(); diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index 099fd57..d2c7ffa 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -209,7 +209,7 @@ export const sealTools = [ }, { name: "seal_approval_rules_list", - description: "列出 Seal 当前草稿审批规则;支持 countOnly、fields、limit 以避免返回规则正文", + description: "列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文", parameters: z.object({ countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"), fields: z.array(z.enum([ @@ -424,7 +424,7 @@ export const sealTools = [ }, { name: "seal_approval_rule_get", - description: "按版本号/code/runtime-id/record-id 定位单条规则,避免拉取整版规则快照", + description: "按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照", parameters: z.object({ versionId: z.string().optional().describe("规则版本 ID"), versionNumber: z.number().int().positive().optional().describe("规则版本号"), @@ -626,7 +626,7 @@ export const sealTools = [ }, { name: "seal_approval_rules_push", - description: "将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)", + description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本", parameters: z.object({ file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"), dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"), @@ -651,6 +651,7 @@ export const sealTools = [ const isDryRun = params.dryRun ?? !isConfirmed; const before = await api.listApprovalRules(client); + const plan = buildRulePushPlan(before.rules, local.rules); if (isDryRun) { return { @@ -670,39 +671,42 @@ export const sealTools = [ localFile: local.resolvedPath, localRulesCount: local.rules.length, remoteDraftCount: before.rules.length, + changes: plan, + impactCount: plan.created.length + plan.updated.length + plan.deleted.length, + preservedRuleIds: [ + ...plan.updated.map((change) => change.id), + ...plan.unchanged.map((rule) => rule.id) + ], + warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.", willPublish: Boolean(params.publish), - message: "Preview mode. Use --yes or confirm=true to apply local rules to remote draft." + message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft." }; } - // Step 1: Clear existing draft rules - let deleted = 0; - for (const rule of before.rules) { + for (const rule of plan.deleted) { await api.deleteApprovalRule(client, rule.id); - deleted += 1; } - // Step 2: Create new rules from local const created: Array<{ id: string; description: string; code?: number }> = []; - for (const rule of local.rules) { - const strictness = rule.strictness?.toUpperCase()?.includes("SHOULD") - ? "SHOULD_FOLLOW" - : rule.strictness?.toUpperCase()?.includes("SUGGEST") - ? "SUGGESTION" - : "MUST_FOLLOW"; - + for (const rule of plan.created) { const newRule = await api.createApprovalRule(client, { description: rule.description, scope: rule.scope ?? "ALL", - strictness + strictness: normalizeRuleStrictness(rule.strictness) }); created.push({ id: newRule.id, description: newRule.description, code: newRule.code }); } - // Step 3: Recode - await api.recodeApprovalRules(client); + const updated: string[] = []; + for (const change of plan.updated) { + await api.updateApprovalRule(client, change.id, { + description: change.rule.description, + scope: change.rule.scope ?? "ALL", + strictness: normalizeRuleStrictness(change.rule.strictness) + }); + updated.push(change.id); + } - // Step 4: Optional publish let publishedVersion: unknown = undefined; if (params.publish) { const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); @@ -714,8 +718,15 @@ export const sealTools = [ corpId: context.corp.id, dryRun: false, localFile: local.resolvedPath, - clearedDraftRules: deleted, + deletedRules: plan.deleted.length, createdRules: created.length, + updatedRules: updated.length, + unchangedRules: plan.unchanged.length, + preservedRuleIds: [ + ...updated, + ...plan.unchanged.map((rule) => rule.id) + ], + recoded: false, published: publishedVersion ?? false }; } @@ -1476,6 +1487,7 @@ export const sealTools = [ packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"), templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"), schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"), + noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"), rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果") }), handler: async ( @@ -1492,6 +1504,7 @@ export const sealTools = [ packageIds?: string[]; templateId?: string; schemaConfig?: Record; + noWait?: boolean; rawParams?: Record; } ) => { @@ -1527,7 +1540,11 @@ export const sealTools = [ return { ...result, created: true, + noWait: params.noWait ?? true, + asyncTicket: result.batchId, next: { + status: `seal-use simulation status ${result.batchId}`, + wait: `seal-use simulation wait ${result.batchId}`, getBatch: "seal-home simulation get ", getRecords: "seal-home simulation batch-records ", listBatches: "seal-home simulation list" @@ -1569,6 +1586,32 @@ export const sealTools = [ }; } }, + { + name: "seal_simulation_batch_status", + description: "单次读取 Seal 模拟批次状态,不阻塞等待;适合根据异步票据轮询", + parameters: z.object({ + batchId: z.string().describe("simulation batch ID") + }), + handler: async (client: KyInstance, params: { batchId: string }) => { + const batch = await api.getSimulationBatch(client, params.batchId); + const status = String(batch.status ?? "UNKNOWN").toUpperCase(); + const terminal = ["COMPLETED", "FAILED", "CANCELLED", "CANCELED"].includes(status); + return { + batchId: params.batchId, + status, + terminal, + totalCount: batch.totalCount, + processedCount: batch.processedCount, + successCount: batch.successCount, + failedCount: batch.failedCount, + createdAt: batch.createdAt, + updatedAt: batch.updatedAt, + next: terminal + ? { getRecords: `seal-use simulation batch-records ${params.batchId}` } + : { status: `seal-use simulation status ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` } + }; + } + }, { name: "seal_simulation_templates_get", description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)", @@ -2260,6 +2303,90 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) { return output; } +type RulePushPlan = { + created: LocalRuleItem[]; + updated: Array<{ id: string; rule: LocalRuleItem; changedFields: string[] }>; + deleted: ApprovalRule[]; + unchanged: Array>; +}; + +export function buildRulePushPlan( + remoteRules: ApprovalRule[], + localRules: LocalRuleItem[] +): RulePushPlan { + const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule])); + const usedRemoteIds = new Set(); + const created: LocalRuleItem[] = []; + const updated: RulePushPlan["updated"] = []; + const unchanged: RulePushPlan["unchanged"] = []; + + for (const localRule of localRules) { + let remoteRule: ApprovalRule | undefined; + if (localRule.id) { + remoteRule = remoteById.get(localRule.id); + if (!remoteRule) { + throw new Error( + `本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。` + ); + } + if (usedRemoteIds.has(localRule.id)) { + throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`); + } + } else { + const matches = remoteRules.filter( + (candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule) + ); + if (matches.length > 1) { + throw new Error( + `本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。` + ); + } + remoteRule = matches[0]; + } + + if (!remoteRule) { + created.push(localRule); + continue; + } + + usedRemoteIds.add(remoteRule.id); + const changedFields = ruleChangedFields(remoteRule, localRule); + if (changedFields.length) { + updated.push({ id: remoteRule.id, rule: localRule, changedFields }); + } else { + unchanged.push({ id: remoteRule.id }); + } + } + + return { + created, + updated, + deleted: remoteRules.filter((rule) => !usedRemoteIds.has(rule.id)), + unchanged + }; +} + +function rulesHaveSameContent(remoteRule: ApprovalRule, localRule: LocalRuleItem): boolean { + return remoteRule.description === localRule.description.trim() && + remoteRule.scope === (localRule.scope ?? "ALL") && + remoteRule.strictness === normalizeRuleStrictness(localRule.strictness); +} + +function ruleChangedFields(remoteRule: ApprovalRule, localRule: LocalRuleItem): string[] { + const changed: string[] = []; + if (remoteRule.description !== localRule.description.trim()) changed.push("description"); + if (remoteRule.scope !== (localRule.scope ?? "ALL")) changed.push("scope"); + if (remoteRule.strictness !== normalizeRuleStrictness(localRule.strictness)) changed.push("strictness"); + return changed; +} + +function normalizeRuleStrictness(value?: string): string { + const normalized = value?.toUpperCase() ?? "MUST_FOLLOW"; + if (normalized.includes("SHOULD")) return "SHOULD_FOLLOW"; + if (normalized.includes("SUGGEST")) return "SUGGESTION"; + return "MUST_FOLLOW"; +} + export type SimulationBatchCreateInput = { mode?: string; sourceSystem?: string; diff --git a/src/server.ts b/src/server.ts index cc476a8..c1bc74a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -7,6 +7,7 @@ import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import { runCli } from "./cli/runner.js"; +import { classifyCliError } from "./cli/errors.js"; import { VERSION } from "./version.js"; const serverEntryFile = fileURLToPath(import.meta.url); @@ -69,7 +70,7 @@ export function createServer(options: { enableCli?: boolean } = {}) { stdout: "", stderr: "seal_cli requires a non-empty command string", isError: true, - exitCode: 1 + exitCode: 2 }); } @@ -89,11 +90,12 @@ export function createServer(options: { enableCli?: boolean } = {}) { } })); } catch (error) { + const classification = classifyCliError(error); return cliResult({ stdout: "", stderr: error instanceof Error ? error.message : String(error), isError: true, - exitCode: 1 + exitCode: classification.exitCode }); } });