diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index a94b206..6d8555f 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -39,7 +39,7 @@ seal-use corps list - Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`. - 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 repeat test-environment rule resets, prefer `rules clear --dry-run` followed by `rules clear --yes`. +- 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`. - 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`. diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 3649995..7a78b7b 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -71,21 +71,21 @@ seal-use billing plans [--corp ] seal-use billing features [--corp ] seal-use webhook list [--query ] [--show-secret] [--corp ] seal-use webhook get|find [--show-secret] [--corp ] -seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] -seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ] -seal-use webhook delete --yes [--corp ] +seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp ] +seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp ] +seal-use webhook delete [--yes|--dry-run] [--corp ] seal-use deploy hosecloud requirements [--corp ] seal-use deploy hosecloud list [--corp ] seal-use deploy hosecloud get [] [--corp ] seal-use deploy hosecloud status [--corp ] -seal-use deploy hosecloud configure --json '{...}' [--corp ] +seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp ] seal-use deploy hosecloud sync [] [--auto] [--corp ] seal-use preference get [--corp ] -seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp ] -seal-use preference thinking-depth set --default [--corp ] +seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp ] +seal-use preference thinking-depth set --default [--dry-run] [--corp ] seal-use preference thinking-depth policies list [--corp ] -seal-use preference thinking-depth policies upsert --json '{...}' [--corp ] -seal-use preference thinking-depth policies remove [--corp ] +seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp ] +seal-use preference thinking-depth policies remove [--dry-run] [--corp ] seal-use source config [--corp ] seal-use tool [--corp ] [--json '{"key":"value"}'] seal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai] @@ -168,14 +168,16 @@ Webhook integrations: - `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp ]` - `seal-use webhook list [--query ] [--show-secret] [--corp ]` - `seal-use webhook get|find [--show-secret] [--corp ]` -- `seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]` -- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ]` -- `seal-use webhook delete --yes [--corp ]` +- `seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp ]` +- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp ]` +- `seal-use webhook delete [--yes|--dry-run] [--corp ]` - `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] --corp ` - `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] --corp ` Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound. +All supported configuration writes accept `--dry-run`: rules clear/push, preference updates, thinking-depth policy changes, HoseCloud configure, and Webhook add/update/delete. Preview mode performs read-only discovery and returns JSON with `preview: true`, the exact `targetUrl`, a redacted `changesDiff` (`before`/`after`), and `impactCount`. It never sends the mutation request and does not require `--yes`; use the same command with `--yes` only after reviewing the preview. + Approval runs, simulations, and Langfuse bridge: - `seal-use approval-runs search --corp [--query ] [--limit 20]` diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index 8aaa80e..24c4aa9 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -102,7 +102,10 @@ export async function handleDeployCommand( if (!payload || Object.keys(payload).length === 0) { throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input "); } - await runTool("seal_deploy_hosecloud_configure", client, corp, payload, outputOptions(args.options)); + await runTool("seal_deploy_hosecloud_configure", client, corp, { + ...payload, + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + }, outputOptions(args.options)); return; } diff --git a/src/cli/commands/preference.ts b/src/cli/commands/preference.ts index a305a9a..980e81f 100644 --- a/src/cli/commands/preference.ts +++ b/src/cli/commands/preference.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runTool } from "../helpers.js"; -import { jsonObject, stringOption } from "../parser.js"; +import { booleanOption, jsonObject, stringOption } from "../parser.js"; import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; @@ -29,7 +29,10 @@ export async function handlePreferenceCommand( if (!payload || Object.keys(payload).length === 0) { throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'"); } - await runTool("seal_preference_decision_update", client, corp, payload, outputOptions(args.options)); + await runTool("seal_preference_decision_update", client, corp, { + ...payload, + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + }, outputOptions(args.options)); return; } } @@ -43,7 +46,10 @@ export async function handlePreferenceCommand( if (defaultLevel !== "medium" && defaultLevel !== "high") { throw new Error("Usage: seal-use preference thinking-depth set --default "); } - await runTool("seal_preference_thinking_depth_set", client, corp, { defaultLevel }, outputOptions(args.options)); + await runTool("seal_preference_thinking_depth_set", client, corp, { + defaultLevel, + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + }, outputOptions(args.options)); return; } @@ -61,7 +67,10 @@ export async function handlePreferenceCommand( if (!payload || !payload.id || !payload.name) { throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'"); } - await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, payload, outputOptions(args.options)); + await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, { + ...payload, + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + }, outputOptions(args.options)); return; } @@ -70,7 +79,10 @@ export async function handlePreferenceCommand( if (!policyId) { throw new Error("Usage: seal-use preference thinking-depth policies remove "); } - await runTool("seal_preference_thinking_depth_policies_remove", client, corp, { policyId }, outputOptions(args.options)); + await runTool("seal_preference_thinking_depth_policies_remove", client, corp, { + policyId, + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + }, outputOptions(args.options)); return; } } diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts index 391c8e1..886ba25 100644 --- a/src/cli/commands/webhook.ts +++ b/src/cli/commands/webhook.ts @@ -152,6 +152,7 @@ export async function handleWebhookCommand( } const autoApprovalRate = webhookRateOption(args.options); const materialPackFilePolicy = materialPackFilePolicyOptions(args.options); + const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); await runTool( "seal_webhook_add", client, @@ -162,7 +163,8 @@ export async function handleWebhookCommand( outgoingResultWebhook, autoApprovalRate, secret: stringOption(args.options.secret), - materialPackFilePolicy + materialPackFilePolicy, + dryRun }, outputOptions(args.options) ); @@ -186,6 +188,7 @@ export async function handleWebhookCommand( stringOption(args.options["outgoing-result-webhook"]); const autoApprovalRate = webhookRateOption(args.options); const materialPackFilePolicy = materialPackFilePolicyOptions(args.options); + const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); if ( name === undefined && mode === undefined && @@ -193,7 +196,8 @@ export async function handleWebhookCommand( autoApprovalRate === undefined && secret === undefined && !rotateSecret && - materialPackFilePolicy === undefined + materialPackFilePolicy === undefined && + !dryRun ) { throw new Error("Webhook update requires at least one field option"); } @@ -209,7 +213,8 @@ export async function handleWebhookCommand( autoApprovalRate, secret, rotateSecret, - materialPackFilePolicy + materialPackFilePolicy, + dryRun }, outputOptions(args.options) ); @@ -218,8 +223,9 @@ export async function handleWebhookCommand( if (action === "delete") { 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) { + 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"); } await runTool( @@ -228,7 +234,8 @@ export async function handleWebhookCommand( corp, { selector, - confirm: true + confirm: true, + dryRun }, outputOptions(args.options) ); diff --git a/src/cli/printer.ts b/src/cli/printer.ts index e63f59a..d9f1e54 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -122,23 +122,23 @@ Usage: seal-use webhook status [<材料包.zip>] [--corp ] seal-use webhook list [--query ] [--show-secret] [--corp ] seal-use webhook get|find [--show-secret] [--corp ] - seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size 500] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] - seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ] - seal-use webhook delete --yes [--corp ] + seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size 500] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp ] + seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp ] + seal-use webhook delete [--yes|--dry-run] [--corp ] seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] [--corp ] seal-use deploy hosecloud requirements [--corp ] seal-use deploy hosecloud list [--corp ] seal-use deploy hosecloud get [--corp ] seal-use deploy hosecloud status [--corp ] - seal-use deploy hosecloud configure --json '{...}' [--corp ] + seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp ] seal-use deploy hosecloud sync [--corp ] seal-use preference get [--corp ] - seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp ] - seal-use preference thinking-depth set --default [--corp ] + seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp ] + seal-use preference thinking-depth set --default [--dry-run] [--corp ] seal-use preference thinking-depth policies list [--corp ] - seal-use preference thinking-depth policies upsert --json '{...}' [--corp ] - seal-use preference thinking-depth policies remove [--corp ] + seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp ] + seal-use preference thinking-depth policies remove [--dry-run] [--corp ] seal-use source config [--corp ] seal-use tool [--corp ] [--json '{"key":"value"}'] seal-use rules count [--corp ] diff --git a/src/domains/seal/api.test.ts b/src/domains/seal/api.test.ts index 830314e..c827bfc 100644 --- a/src/domains/seal/api.test.ts +++ b/src/domains/seal/api.test.ts @@ -6,6 +6,9 @@ import { filterWebhookIntegrations, findWebhookIntegration, listWebhookIntegrations, + previewAddWebhookIntegration, + previewDeleteWebhookIntegration, + previewUpdateWebhookIntegration, searchUsers, updateWebhookIntegration } from "./api.js"; @@ -136,6 +139,35 @@ describe("Seal Webhook API", () => { expect(deleted.id).toBe("integration-1"); expect((posted?.integrations as Array>)).toHaveLength(1); }); + + test("previews Webhook mutations without sending a write request", async () => { + const writes: string[] = []; + const client = { + get: () => ({ + json: async () => ({ data: webhookConfig() }) + }), + post: (url: string) => { + writes.push(`post:${url}`); + throw new Error("preview must not write"); + }, + patch: (url: string) => { + writes.push(`patch:${url}`); + throw new Error("preview must not write"); + } + } as unknown as KyInstance; + + const added = await previewAddWebhookIntegration(client, "https://seal.test", { + name: "Preview webhook", + outgoingResultWebhook: "https://callback.test/preview" + }); + const updated = await previewUpdateWebhookIntegration(client, "integration-1", { name: "Preview rename" }); + const deleted = await previewDeleteWebhookIntegration(client, "integration-1"); + + expect(added.integration?.name).toBe("Preview webhook"); + expect(updated.integration?.name).toBe("Preview rename"); + expect(deleted.after.integrations).toHaveLength(1); + expect(writes).toEqual([]); + }); }); function webhookConfig() { diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index f07f985..3064db6 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -264,6 +264,12 @@ export async function updateApprovalStylePreferences( ); } +export type WebhookMutationPreview = { + before: ApprovalStylePreferences; + after: ApprovalStylePreferences; + integration?: WebhookIntegration; +}; + export async function saveApprovalStylePreferences( client: KyInstance, params: Record, @@ -313,6 +319,29 @@ export async function addWebhookIntegration( return integration; } +export async function previewAddWebhookIntegration( + client: KyInstance, + baseUrl: string, + params: { + name: string; + mode?: WebhookMode; + outgoingResultWebhook: string; + autoApprovalRate?: number; + secret?: string; + materialPackFilePolicy?: MaterialPackFilePolicyPatch; + }, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const before = await getApprovalStylePreferences(client, endpoint); + const existing = parseWebhookIntegrations(before.integrations); + const integration = createWebhookIntegration(baseUrl, existing, params); + return { + before, + after: { ...before, integrations: [...before.integrations, integration] }, + integration + }; +} + export async function updateWebhookIntegration( client: KyInstance, selector: string, @@ -330,28 +359,7 @@ export async function updateWebhookIntegration( const preferences = await getApprovalStylePreferences(client, endpoint); const entries = getWebhookEntries(preferences.integrations); const entry = findWebhookEntry(entries, selector); - const updated = WebhookIntegrationSchema.parse({ - ...entry.integration, - ...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }), - ...(params.mode === undefined ? {} : { mode: params.mode }), - ...(params.outgoingResultWebhook === undefined - ? {} - : { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }), - ...(params.autoApprovalRate === undefined - ? {} - : { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }), - ...(params.rotateSecret || params.secret !== undefined - ? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") } - : {}), - ...(params.materialPackFilePolicy === undefined - ? {} - : { - materialPackFilePolicy: mergeMaterialPackFilePolicy( - entry.integration.materialPackFilePolicy, - params.materialPackFilePolicy - ) - }) - }); + const updated = buildUpdatedWebhookIntegration(entry.integration, params); const saved = await saveApprovalStylePreferences(client, { ...preferences, @@ -367,6 +375,34 @@ export async function updateWebhookIntegration( return updated; } +export async function previewUpdateWebhookIntegration( + client: KyInstance, + selector: string, + params: { + name?: string; + mode?: WebhookMode; + outgoingResultWebhook?: string; + autoApprovalRate?: number; + secret?: string; + rotateSecret?: boolean; + materialPackFilePolicy?: MaterialPackFilePolicyPatch; + }, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const before = await getApprovalStylePreferences(client, endpoint); + const entries = getWebhookEntries(before.integrations); + const entry = findWebhookEntry(entries, selector); + const integration = buildUpdatedWebhookIntegration(entry.integration, params); + return { + before, + after: { + ...before, + integrations: before.integrations.map((item, index) => index === entry.index ? integration : item) + }, + integration + }; +} + export async function deleteWebhookIntegration( client: KyInstance, selector: string, @@ -387,6 +423,24 @@ export async function deleteWebhookIntegration( return entry.integration; } +export async function previewDeleteWebhookIntegration( + client: KyInstance, + selector: string, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const before = await getApprovalStylePreferences(client, endpoint); + const entries = getWebhookEntries(before.integrations); + const entry = findWebhookEntry(entries, selector); + return { + before, + after: { + ...before, + integrations: before.integrations.filter((_, index) => index !== entry.index) + }, + integration: entry.integration + }; +} + export function findWebhookIntegration( integrations: WebhookIntegration[], selector: string @@ -491,6 +545,42 @@ function createWebhookIntegration( }); } +function buildUpdatedWebhookIntegration( + integration: WebhookIntegration, + params: { + name?: string; + mode?: WebhookMode; + outgoingResultWebhook?: string; + autoApprovalRate?: number; + secret?: string; + rotateSecret?: boolean; + materialPackFilePolicy?: MaterialPackFilePolicyPatch; + } +): WebhookIntegration { + return WebhookIntegrationSchema.parse({ + ...integration, + ...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }), + ...(params.mode === undefined ? {} : { mode: params.mode }), + ...(params.outgoingResultWebhook === undefined + ? {} + : { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }), + ...(params.autoApprovalRate === undefined + ? {} + : { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }), + ...(params.rotateSecret || params.secret !== undefined + ? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") } + : {}), + ...(params.materialPackFilePolicy === undefined + ? {} + : { + materialPackFilePolicy: mergeMaterialPackFilePolicy( + integration.materialPackFilePolicy, + params.materialPackFilePolicy + ) + }) + }); +} + function nextWebhookTimestamp(existing: WebhookIntegration[]): number { const usedIds = new Set(existing.map((integration) => integration.id)); let stamp = Date.now(); diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index d5c4a0f..695fe93 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -223,6 +223,43 @@ describe("sealTools", () => { expect(await countFakeRules(client)).toBe(0); }); + test("preference dry run reads config without patching it", async () => { + const tool = sealTools.find((item) => item.name === "seal_preference_decision_update"); + expect(tool).toBeDefined(); + let patched = false; + const client = { + get: () => ({ + json: async () => ({ + data: { + decisionPreferences: { + explicitApprove: "old", + explicitReject: "reject", + exemptApprove: "exempt", + review: "review" + }, + integrations: [] + } + }) + }), + patch: () => { + patched = true; + throw new Error("preview must not patch"); + } + } as unknown as KyInstance; + + const handler = tool!.handler as ToolHandler; + const result = await handler(client, { explicitApprove: "new", dryRun: true }, fakeContext()) as { + preview: boolean; + targetUrl: string; + changesDiff: { after: { decisionPreferences: { explicitApprove: string } } }; + }; + + expect(result.preview).toBe(true); + expect(result.targetUrl).toBe("https://seal.test/api/v1/agent/ai-approval/config"); + expect(result.changesDiff.after.decisionPreferences.explicitApprove).toBe("new"); + expect(patched).toBe(false); + }); + 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 ee66fd1..099fd57 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -254,6 +254,7 @@ export const sealTools = [ const before = await api.listApprovalRules(client); if (params.dryRun) { return { + ...mutationPreview(context, "api/v1/rules", before.rules, [], before.rules.length), corpId: context.corp.id, corpName: context.corp.name, dryRun: true, @@ -653,6 +654,17 @@ export const sealTools = [ if (isDryRun) { return { + ...mutationPreview( + context, + "api/v1/rules", + before.rules, + local.rules.map((rule) => ({ + description: rule.description, + scope: rule.scope ?? "ALL", + strictness: rule.strictness ?? "MUST_FOLLOW" + })), + before.rules.length + local.rules.length + ), corpId: context.corp.id, dryRun: true, localFile: local.resolvedPath, @@ -949,14 +961,15 @@ export const sealTools = [ }, { name: "seal_webhook_add", - description: "新增 Webhook 集成并通过 AI 审批配置保存接口持久化", + description: "新增 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化", parameters: z.object({ name: z.string().min(1).describe("集成名称"), mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(), outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"), autoApprovalRate: z.number().int().min(0).max(100).optional(), secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"), - materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单") + materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), handler: async ( client: KyInstance, @@ -967,16 +980,29 @@ export const sealTools = [ autoApprovalRate?: number; secret?: string; materialPackFilePolicy?: Partial>; + dryRun?: boolean; }, context: ToolContext ) => { const baseUrl = getConfiguredSealBaseUrl(context.corp); - const integration = await api.addWebhookIntegration( + const preview = params.dryRun + ? await api.previewAddWebhookIntegration(client, baseUrl, params, context.corp.seal.endpoints.approvalStylePreferences) + : undefined; + const integration = preview?.integration ?? await api.addWebhookIntegration( client, baseUrl, params, context.corp.seal.endpoints.approvalStylePreferences ); + if (params.dryRun) { + return mutationPreview( + context, + context.corp.seal.endpoints.approvalStylePreferences, + preview!.before, + preview!.after, + 1 + ); + } return { saved: true, integration: presentWebhookIntegration(integration, true) @@ -985,7 +1011,7 @@ export const sealTools = [ }, { name: "seal_webhook_update", - description: "更新现有 Webhook 集成并通过 AI 审批配置保存接口持久化", + description: "更新现有 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化", parameters: z.object({ selector: z.string().min(1).describe("Webhook 集成 ID 或名称"), name: z.string().min(1).optional(), @@ -994,7 +1020,8 @@ export const sealTools = [ autoApprovalRate: z.number().int().min(0).max(100).optional(), secret: z.string().min(1).optional(), rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一"), - materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单") + materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), handler: async ( client: KyInstance, @@ -1007,18 +1034,31 @@ export const sealTools = [ secret?: string; rotateSecret?: boolean; materialPackFilePolicy?: Partial>; + dryRun?: boolean; }, context: ToolContext ) => { if (params.secret !== undefined && params.rotateSecret) { throw new Error("Webhook secret and rotateSecret cannot be used together"); } - const integration = await api.updateWebhookIntegration( + const preview = params.dryRun + ? await api.previewUpdateWebhookIntegration(client, params.selector, params, context.corp.seal.endpoints.approvalStylePreferences) + : undefined; + const integration = preview?.integration ?? await api.updateWebhookIntegration( client, params.selector, params, context.corp.seal.endpoints.approvalStylePreferences ); + if (params.dryRun) { + return mutationPreview( + context, + context.corp.seal.endpoints.approvalStylePreferences, + preview!.before, + preview!.after, + 1 + ); + } return { saved: true, integration: presentWebhookIntegration( @@ -1030,24 +1070,37 @@ export const sealTools = [ }, { name: "seal_webhook_delete", - description: "删除指定 Webhook 集成并通过 AI 审批配置保存接口持久化", + description: "删除指定 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化", parameters: z.object({ selector: z.string().min(1).describe("Webhook 集成 ID 或名称"), - confirm: z.boolean().describe("必须明确传 true 才执行删除") + confirm: z.boolean().optional().describe("执行删除时必须明确传 true;dryRun 可省略"), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行删除") }), handler: async ( client: KyInstance, - params: { selector: string; confirm: boolean }, + params: { selector: string; confirm?: boolean; dryRun?: boolean }, context: ToolContext ) => { - if (!params.confirm) { + if (!params.confirm && !params.dryRun) { throw new Error("Refusing to delete Webhook integration without confirm=true"); } - const integration = await api.deleteWebhookIntegration( + const preview = params.dryRun + ? await api.previewDeleteWebhookIntegration(client, params.selector, context.corp.seal.endpoints.approvalStylePreferences) + : undefined; + const integration = preview?.integration ?? await api.deleteWebhookIntegration( client, params.selector, context.corp.seal.endpoints.approvalStylePreferences ); + if (params.dryRun) { + return mutationPreview( + context, + context.corp.seal.endpoints.approvalStylePreferences, + preview!.before, + preview!.after, + 1 + ); + } return { deleted: true, integration: presentWebhookIntegration(integration, false) @@ -1804,15 +1857,17 @@ export const sealTools = [ rejectResubmitMethod: z.enum(["node_default", "to_ebot", "from_start"]).optional(), autoApproveNodeNames: z.array(z.string()).optional(), apiOrigin: z.string().default("production"), - customApiUrl: z.string().optional() + customApiUrl: z.string().optional(), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: ToolContext) => { - const apiKey = rawParams.apiKey ?? (rawParams as any).appKey; - const apiSecret = rawParams.apiSecret ?? (rawParams as any).appSecurity; + const { dryRun, ...inputParams } = rawParams; + const apiKey = inputParams.apiKey ?? (inputParams as any).appKey; + const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity; if (!apiKey || !apiSecret) { throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项"); } - const params = { ...rawParams, apiKey, apiSecret }; + const params = { ...inputParams, apiKey, apiSecret }; let effectiveApiOrigin = params.apiOrigin ?? "production"; let effectiveCustomApiUrl = params.customApiUrl; @@ -1858,14 +1913,24 @@ export const sealTools = [ (item: any) => item.type !== "hosecloud" || item.signKey !== signKey ); existing.push(nextIntegration); - await api.updateApprovalStylePreferences(client, { + const nextConfig = { ...config, integrationSystem: "hosecloud", integrations: existing - }); + }; + if (dryRun) { + return mutationPreview( + context, + context.corp.seal.endpoints.approvalStylePreferences, + config, + nextConfig, + 1 + ); + } + await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences); console.error(`✓ 配置已保存 (signKey: ${signKey})`); - console.error(`👉 下一步操作:运行 \`seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}\` 一键同步发布到合思审批流`); + console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`); return { integration: redactIntegrationSecrets(nextIntegration) @@ -1926,18 +1991,21 @@ export const sealTools = [ explicitApprove: z.string().optional(), explicitReject: z.string().optional(), exemptApprove: z.string().optional(), - review: z.string().optional() + review: z.string().optional(), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), - handler: async (client: KyInstance, params: Partial) => { - const config = (await api.getApprovalStylePreferences(client)) as any; + handler: async (client: KyInstance, params: Partial & { dryRun?: boolean }, context: ToolContext) => { + const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any; + const { dryRun, ...changes } = params; const updated = { ...config, decisionPreferences: { ...config.decisionPreferences, - ...params + ...changes } }; - await api.updateApprovalStylePreferences(client, updated); + if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1); + await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences); return { decisionPreferences: updated.decisionPreferences }; @@ -1947,10 +2015,11 @@ export const sealTools = [ name: "seal_preference_thinking_depth_set", description: "修改默认思考深度(medium 或 high)", parameters: z.object({ - defaultLevel: z.enum(["medium", "high"]).describe("默认思考深度") + defaultLevel: z.enum(["medium", "high"]).describe("默认思考深度"), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), - handler: async (client: KyInstance, params: { defaultLevel: "medium" | "high" }) => { - const config = (await api.getApprovalStylePreferences(client)) as any; + handler: async (client: KyInstance, params: { defaultLevel: "medium" | "high"; dryRun?: boolean }, context: ToolContext) => { + const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any; const updated = { ...config, thinkingDepthPreference: { @@ -1958,7 +2027,8 @@ export const sealTools = [ routingPolicies: config.thinkingDepthPreference?.routingPolicies ?? [] } }; - await api.updateApprovalStylePreferences(client, updated); + if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1); + await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences); return { thinkingDepthPreference: updated.thinkingDepthPreference }; @@ -1978,12 +2048,15 @@ export const sealTools = [ { name: "seal_preference_thinking_depth_policies_upsert", description: "新增或修改思考深度路由策略", - parameters: ThinkingPolicySchema, - handler: async (client: KyInstance, policy: ThinkingPolicy) => { - const config = (await api.getApprovalStylePreferences(client)) as any; + parameters: ThinkingPolicySchema.extend({ + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") + }), + handler: async (client: KyInstance, policy: ThinkingPolicy & { dryRun?: boolean }, context: ToolContext) => { + const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any; + const { dryRun, ...cleanPolicy } = policy; const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? []; - const next = existing.filter((item) => item.id !== policy.id); - next.push(policy); + const next = existing.filter((item) => item.id !== cleanPolicy.id); + next.push(cleanPolicy); const updated = { ...config, thinkingDepthPreference: { @@ -1991,9 +2064,10 @@ export const sealTools = [ routingPolicies: next } }; - await api.updateApprovalStylePreferences(client, updated); + if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1); + await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences); return { - policy, + policy: cleanPolicy, policies: next }; } @@ -2002,10 +2076,11 @@ export const sealTools = [ name: "seal_preference_thinking_depth_policies_remove", description: "删除一条思考深度路由策略", parameters: z.object({ - policyId: z.string().describe("路由策略 ID") + policyId: z.string().describe("路由策略 ID"), + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") }), - handler: async (client: KyInstance, params: { policyId: string }) => { - const config = (await api.getApprovalStylePreferences(client)) as any; + handler: async (client: KyInstance, params: { policyId: string; dryRun?: boolean }, context: ToolContext) => { + const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any; const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? []; const next = existing.filter((item) => item.id !== params.policyId); if (next.length === existing.length) { @@ -2018,7 +2093,8 @@ export const sealTools = [ routingPolicies: next } }; - await api.updateApprovalStylePreferences(client, updated); + if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1); + await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences); return { removedId: params.policyId, policies: next @@ -2244,6 +2320,38 @@ function redactIntegrationSecrets(integration: Record) { ); } +function mutationPreview( + context: ToolContext, + endpoint: string, + before: unknown, + after: unknown, + impactCount: number +) { + const baseUrl = getConfiguredSealBaseUrl(context.corp).replace(/\/+$/, ""); + return { + preview: true, + targetUrl: `${baseUrl}/${endpoint.replace(/^\/+/, "")}`, + changesDiff: { + before: redactPreviewValue(before), + after: redactPreviewValue(after) + }, + impactCount + }; +} + +function redactPreviewValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(redactPreviewValue); + if (!value || typeof value !== "object") return value; + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + ["apiKey", "apiSecret", "secret", "token", "password"].includes(key) && typeof item === "string" + ? "***" + : redactPreviewValue(item) + ]) + ); +} + export function buildSimulationBatchParams(input: SimulationBatchCreateInput): Record { const sourceSystem = input.sourceSystem ?? input.mode ?? "hosecloud"; const params: Record = { diff --git a/src/domains/seal/types.ts b/src/domains/seal/types.ts index 3f35717..dd47f7c 100644 --- a/src/domains/seal/types.ts +++ b/src/domains/seal/types.ts @@ -488,6 +488,7 @@ export const ThinkingDepthPreferenceSchema = z.object({ }).passthrough(); export const HosecloudConfigInputSchema = z.object({ + dryRun: z.boolean().optional(), signKey: z.string().min(1).optional(), outboundName: z.string().optional(), specificationId: z.string().optional(),