From 32149762c91645e727bdff7ae908d4eb1d6f698c Mon Sep 17 00:00:00 2001 From: yunyingk Date: Fri, 7 Aug 2026 15:53:46 +0800 Subject: [PATCH] Add Webhook integration CLI management --- .agents/skills/seal-home/SKILL.md | 10 +- .agents/skills/seal-home/references/cli.md | 20 ++ package.json | 2 +- src/cli.test.ts | 3 + src/cli.ts | 128 +++++++++++ src/domains/seal/api.test.ts | 132 ++++++++++- src/domains/seal/api.ts | 254 ++++++++++++++++++++- src/domains/seal/tools.test.ts | 8 + src/domains/seal/tools.ts | 185 ++++++++++++++- src/domains/seal/types.ts | 27 ++- 10 files changed, 755 insertions(+), 14 deletions(-) diff --git a/.agents/skills/seal-home/SKILL.md b/.agents/skills/seal-home/SKILL.md index 5de8283..08c8a5a 100644 --- a/.agents/skills/seal-home/SKILL.md +++ b/.agents/skills/seal-home/SKILL.md @@ -1,13 +1,13 @@ --- name: seal-home -version: 0.4.2 -description: "v0.4.2: Use when working with Seal Home tenant operations: target-tenant Seal delegation links, Hose/合思 authorization links, approval runs, LLM config, permissions, billing, users, rules, documents, search, and Langfuse hints." +version: 0.4.3 +description: "v0.4.3: Use when working with Seal Home tenant operations: target-tenant Seal delegation links, Hose/合思 authorization links, approval runs, LLM config, permissions, billing, users, rules, documents, search, and Langfuse hints." metadata: - version: 0.4.2 - short-description: Seal tenant and Hose approval automation (v0.4.2) + version: 0.4.3 + short-description: Seal tenant and Hose approval automation (v0.4.3) --- -# Seal Home (v0.4.2) +# Seal Home (v0.4.3) Use the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. diff --git a/.agents/skills/seal-home/references/cli.md b/.agents/skills/seal-home/references/cli.md index 881db5b..86bd9ea 100644 --- a/.agents/skills/seal-home/references/cli.md +++ b/.agents/skills/seal-home/references/cli.md @@ -41,6 +41,11 @@ seal-home permissions configs [--corp ] seal-home billing status [--corp ] seal-home billing plans [--corp ] seal-home billing features [--corp ] +seal-home webhook list [--query ] [--show-secret] [--corp ] +seal-home webhook get|find [--show-secret] [--corp ] +seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] +seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] +seal-home webhook delete --yes [--corp ] seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] @@ -125,6 +130,21 @@ Style preferences: - `seal_approval_style_preferences_get` - `seal_approval_style_preferences_update` +Webhook integrations: + +- `seal-home webhook list [--query ] [--show-secret] [--corp ]` +- `seal-home webhook get|find [--show-secret] [--corp ]` +- `seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ]` +- `seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ]` +- `seal-home webhook delete --yes [--corp ]` +- `seal_webhook_list` +- `seal_webhook_get` +- `seal_webhook_add` +- `seal_webhook_update` +- `seal_webhook_delete` + +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. + Approval runs, simulations, and Langfuse bridge: - `seal_approval_runs_search` diff --git a/package.json b/package.json index 99f2d8d..fef05bc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seal-home", - "version": "0.4.2", + "version": "0.4.3", "type": "module", "module": "src/server.ts", "bin": { diff --git a/src/cli.test.ts b/src/cli.test.ts index 6c557c6..4e5448a 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -36,6 +36,9 @@ describe("CLI version & help handling", () => { expect(result.stdout).toContain("Usage:"); expect(result.stdout).toContain("seal-home users search "); expect(result.stdout).toContain("seal-home users delegation "); + expect(result.stdout).toContain("seal-home webhook get|find "); + expect(result.stdout).toContain("seal-home webhook add --name --result-url "); + expect(result.stdout).toContain("[--secret |--rotate-secret]"); }); test("invalid command displays unknown command error with help hint", () => { diff --git a/src/cli.ts b/src/cli.ts index 126dda6..b1d3a5b 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -11,6 +11,7 @@ import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; import { getMe } from "./domains/seal/api.js"; import { sealTools, type SealTool } from "./domains/seal/tools.js"; import { CorpConfig } from "./core/config/types.js"; +import type { WebhookMode } from "./domains/seal/types.js"; import { clearCorpTokenCache } from "./core/auth/token-store.js"; import { getHoseProvisionalAuthLink } from "./core/auth/hose.js"; import { VERSION } from "./version.js"; @@ -254,6 +255,96 @@ async function main() { return; } + if ((area === "webhook" || area === "webhooks") && action === "list") { + await runTool("seal_webhook_list", client, corp, { + query: stringOption(args.options.query) ?? stringOption(args.options.keyword), + includeSecret: webhookShowSecretOption(args.options) + }, outputOptions(args.options)); + return; + } + + if ((area === "webhook" || area === "webhooks") && (action === "get" || action === "find")) { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) throw new Error("Usage: seal-home webhook get [--show-secret]"); + await runTool("seal_webhook_get", client, corp, { + selector, + includeSecret: webhookShowSecretOption(args.options) + }, outputOptions(args.options)); + return; + } + + if ((area === "webhook" || area === "webhooks") && (action === "add" || action === "create")) { + const name = stringOption(args.options.name) ?? maybeName; + const outgoingResultWebhook = + stringOption(args.options.resultUrl) ?? + stringOption(args.options["result-url"]) ?? + stringOption(args.options.outgoingResultWebhook) ?? + stringOption(args.options["outgoing-result-webhook"]); + if (!name || !outgoingResultWebhook) { + throw new Error("Usage: seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic]"); + } + const autoApprovalRate = webhookRateOption(args.options); + await runTool("seal_webhook_add", client, corp, { + name, + mode: parseWebhookMode(stringOption(args.options.mode)), + outgoingResultWebhook, + autoApprovalRate, + secret: stringOption(args.options.secret) + }, outputOptions(args.options)); + return; + } + + if ((area === "webhook" || area === "webhooks") && action === "update") { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) throw new Error("Usage: seal-home webhook update [options]"); + const secret = stringOption(args.options.secret); + const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]); + if (secret !== undefined && rotateSecret) { + throw new Error("Use either --secret or --rotate-secret, not both"); + } + const name = stringOption(args.options.name); + const mode = parseWebhookMode(stringOption(args.options.mode)); + const outgoingResultWebhook = + stringOption(args.options.resultUrl) ?? + stringOption(args.options["result-url"]) ?? + stringOption(args.options.outgoingResultWebhook) ?? + stringOption(args.options["outgoing-result-webhook"]); + const autoApprovalRate = webhookRateOption(args.options); + if ( + name === undefined && + mode === undefined && + outgoingResultWebhook === undefined && + autoApprovalRate === undefined && + secret === undefined && + !rotateSecret + ) { + throw new Error("Webhook update requires at least one field option"); + } + await runTool("seal_webhook_update", client, corp, { + selector, + name, + mode, + outgoingResultWebhook, + autoApprovalRate, + secret, + rotateSecret + }, outputOptions(args.options)); + return; + } + + if ((area === "webhook" || area === "webhooks") && action === "delete") { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) throw new Error("Usage: seal-home webhook delete --yes"); + if (booleanOption(args.options.yes) !== true) { + throw new Error("Refusing to delete Webhook integration without --yes"); + } + await runTool("seal_webhook_delete", client, corp, { + selector, + confirm: true + }, outputOptions(args.options)); + return; + } + if (area === "context") { await runTool("seal_approval_context_get", client, corp, { documentLimit: numberOption(args.options.documentLimit), @@ -1190,6 +1281,38 @@ function splitOption(value: string | boolean | undefined): string[] | undefined return items.length ? items : undefined; } +function parseWebhookMode(value?: string): WebhookMode | undefined { + if (!value) return undefined; + const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); + const aliases: Record = { + assisted: "assisted", + 辅助: "assisted", + semi_automatic: "semi_automatic", + 半自动: "semi_automatic", + fully_automatic: "fully_automatic", + 全自动: "fully_automatic" + }; + const mode = aliases[normalized]; + if (!mode) { + throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic"); + } + return mode; +} + +function webhookRateOption(options: Record): number | undefined { + const value = numberOption( + options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"] + ); + if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) { + throw new Error("Webhook auto approval rate must be an integer between 0 and 100"); + } + return value; +} + +function webhookShowSecretOption(options: Record): boolean | undefined { + return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); +} + function booleanOption(value: string | boolean | undefined): boolean | undefined { if (value === undefined) return undefined; if (typeof value === "boolean") return value; @@ -1245,6 +1368,11 @@ Usage: seal-home billing status [--corp ] seal-home billing plans [--corp ] seal-home billing features [--corp ] + seal-home webhook list [--query ] [--show-secret] [--corp ] + seal-home webhook get|find [--show-secret] [--corp ] + seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] + seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] + seal-home webhook delete --yes [--corp ] seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] seal-home rules count [--corp ] diff --git a/src/domains/seal/api.test.ts b/src/domains/seal/api.test.ts index a73cb9d..82e9574 100644 --- a/src/domains/seal/api.test.ts +++ b/src/domains/seal/api.test.ts @@ -1,6 +1,14 @@ import { describe, expect, test } from "bun:test"; import type { KyInstance } from "ky"; -import { searchUsers } from "./api.js"; +import { + addWebhookIntegration, + deleteWebhookIntegration, + filterWebhookIntegrations, + findWebhookIntegration, + listWebhookIntegrations, + searchUsers, + updateWebhookIntegration +} from "./api.js"; describe("Seal contact API", () => { test("sends the contact search term as query", async () => { @@ -28,3 +36,125 @@ describe("Seal contact API", () => { expect(result.users).toEqual([{ _id: "user-1", name: "欧阳楠楠", departmentIds: [], permissions: [] }]); }); }); + +describe("Seal Webhook API", () => { + test("reads only Webhook integrations from the approval config", async () => { + let requestedUrl = ""; + const client = { + get: (url: string) => { + requestedUrl = url; + return { + json: async () => ({ data: webhookConfig() }) + }; + } + } as unknown as KyInstance; + + const result = await listWebhookIntegrations(client); + + expect(requestedUrl).toBe("api/v1/agent/ai-approval/config"); + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ + id: "integration-1", + name: "Existing webhook", + type: "webhook" + }); + }); + + test("adds a Webhook by POSTing the merged full config", async () => { + let posted: Record | undefined; + const client = { + get: () => ({ + json: async () => ({ data: webhookConfig() }) + }), + post: (_url: string, options: { json: Record }) => { + posted = options.json; + return Promise.resolve({ + ok: true, + json: async () => ({ success: true }) + }); + } + } as unknown as KyInstance; + + const result = await addWebhookIntegration(client, "https://seal.test", { + name: "New webhook", + mode: "assisted", + outgoingResultWebhook: "https://callback.test/result" + }); + + const integrations = posted?.integrations as Array>; + expect(result.name).toBe("New webhook"); + expect(result.incomingDocumentWebhook.url).toContain("/document"); + expect(result.incomingManualResultWebhook.url).toContain("/manual-result"); + expect(result.secret).toHaveLength(32); + expect(integrations).toHaveLength(3); + expect(integrations[2]).toMatchObject({ + id: result.id, + name: "New webhook" + }); + expect(integrations[1]).toMatchObject({ type: "hosecloud" }); + expect(posted?.integrationSystem).toBe("feishu"); + }); + + test("updates, deletes, and finds Webhooks without replacing other integrations", async () => { + let posted: Record | undefined; + const client = { + get: () => ({ + json: async () => ({ data: webhookConfig() }) + }), + post: (_url: string, options: { json: Record }) => { + posted = options.json; + return Promise.resolve({ + ok: true, + json: async () => ({ success: true }) + }); + } + } as unknown as KyInstance; + + const updated = await updateWebhookIntegration(client, "integration-1", { + name: "Renamed webhook", + rotateSecret: true + }); + expect(updated.name).toBe("Renamed webhook"); + expect(updated.secret).not.toBe("webhook-secret"); + expect((posted?.integrations as Array>)[1]).toMatchObject({ type: "hosecloud" }); + + const found = findWebhookIntegration([updated], "Renamed webhook"); + expect(found.id).toBe("integration-1"); + expect(filterWebhookIntegrations([updated], "renamed")).toEqual([updated]); + + const deleted = await deleteWebhookIntegration(client, "integration-1"); + expect(deleted.id).toBe("integration-1"); + expect((posted?.integrations as Array>)).toHaveLength(1); + }); +}); + +function webhookConfig() { + return { + decisionPreferences: {}, + integrationSystem: "feishu", + integrations: [ + { + type: "webhook", + id: "integration-1", + name: "Existing webhook", + mode: "assisted", + incomingDocumentWebhook: { + id: "wh_1_test", + url: "https://seal.test/api/v1/integrations/webhook/wh_1_test/document" + }, + outgoingResultWebhook: "https://callback.test/existing", + incomingManualResultWebhook: { + id: "wh_1_test", + url: "https://seal.test/api/v1/integrations/webhook/wh_1_test/manual-result" + }, + secret: "webhook-secret", + autoApprovalRate: 60 + }, + { + type: "hosecloud", + outboundName: "Other integration", + signKey: "other-secret" + } + ] + }; +} diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index 85fdf21..ad33db7 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -1,3 +1,4 @@ +import { randomBytes } from "node:crypto"; import ky, { HTTPError, KyInstance } from "ky"; import { z } from "zod"; import { CorpConfig } from "../../core/config/types.js"; @@ -44,7 +45,10 @@ import { PermissionConfigsData, PermissionConfigsDataSchema, BillingStatusData, - BillingStatusDataSchema + BillingStatusDataSchema, + WebhookIntegration, + WebhookIntegrationSchema, + WebhookMode } from "./types.js"; const SuccessResponseSchema = z.object({ success: z.boolean().optional() }).passthrough(); @@ -237,6 +241,254 @@ export async function updateApprovalStylePreferences( ); } +export async function saveApprovalStylePreferences( + client: KyInstance, + params: Record, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const response = await client.post(endpoint, { json: params }); + const json = await response.json().catch(() => ({})); + const data = SuccessResponseSchema.safeParse( + (json as { data?: unknown }).data ?? json + ); + return data.success ? data.data.success ?? response.ok : response.ok; +} + +export async function listWebhookIntegrations( + client: KyInstance, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const preferences = await getApprovalStylePreferences(client, endpoint); + return parseWebhookIntegrations(preferences.integrations); +} + +export async function addWebhookIntegration( + client: KyInstance, + baseUrl: string, + params: { + name: string; + mode?: WebhookMode; + outgoingResultWebhook: string; + autoApprovalRate?: number; + secret?: string; + }, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const preferences = await getApprovalStylePreferences(client, endpoint); + const existing = parseWebhookIntegrations(preferences.integrations); + const integration = createWebhookIntegration(baseUrl, existing, params); + const saved = await saveApprovalStylePreferences(client, { + ...preferences, + integrations: [...preferences.integrations, integration] + }, endpoint); + + if (!saved) { + throw new Error("Seal did not confirm saving the Webhook integration"); + } + + return integration; +} + +export async function updateWebhookIntegration( + client: KyInstance, + selector: string, + params: { + name?: string; + mode?: WebhookMode; + outgoingResultWebhook?: string; + autoApprovalRate?: number; + secret?: string; + rotateSecret?: boolean; + }, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + 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") } + : {}) + }); + + const saved = await saveApprovalStylePreferences(client, { + ...preferences, + integrations: preferences.integrations.map((integration, index) => + index === entry.index ? updated : integration + ) + }, endpoint); + + if (!saved) { + throw new Error("Seal did not confirm saving the Webhook integration"); + } + + return updated; +} + +export async function deleteWebhookIntegration( + client: KyInstance, + selector: string, + endpoint = "api/v1/agent/ai-approval/config" +): Promise { + const preferences = await getApprovalStylePreferences(client, endpoint); + const entries = getWebhookEntries(preferences.integrations); + const entry = findWebhookEntry(entries, selector); + const saved = await saveApprovalStylePreferences(client, { + ...preferences, + integrations: preferences.integrations.filter((_, index) => index !== entry.index) + }, endpoint); + + if (!saved) { + throw new Error("Seal did not confirm deleting the Webhook integration"); + } + + return entry.integration; +} + +export function findWebhookIntegration( + integrations: WebhookIntegration[], + selector: string +): WebhookIntegration { + const normalized = selector.trim(); + if (!normalized) throw new Error("Webhook selector must not be empty"); + + const exactId = integrations.find((integration) => integration.id === normalized); + if (exactId) return exactId; + + const byName = integrations.filter((integration) => integration.name === normalized); + if (byName.length === 1) return byName[0]!; + if (byName.length > 1) { + throw new Error(`Multiple Webhook integrations match name: ${normalized}. Use the integration ID.`); + } + + throw new Error(`Webhook integration not found: ${normalized}`); +} + +export function filterWebhookIntegrations( + integrations: WebhookIntegration[], + query?: string +): WebhookIntegration[] { + const needle = query?.trim().toLowerCase(); + if (!needle) return integrations; + + return integrations.filter((integration) => [ + integration.id, + integration.name, + integration.mode, + integration.outgoingResultWebhook, + integration.incomingDocumentWebhook.url, + integration.incomingManualResultWebhook.url + ].some((value) => value.toLowerCase().includes(needle))); +} + +function parseWebhookIntegrations( + integrations: Array<{ type: string } & Record> +): WebhookIntegration[] { + return integrations + .filter((integration) => integration.type === "webhook") + .map((integration) => WebhookIntegrationSchema.parse(integration)); +} + +function getWebhookEntries( + integrations: Array<{ type: string } & Record> +): Array<{ index: number; integration: WebhookIntegration }> { + return integrations.flatMap((integration, index) => { + if (integration.type !== "webhook") return []; + return [{ index, integration: WebhookIntegrationSchema.parse(integration) }]; + }); +} + +function findWebhookEntry( + entries: Array<{ index: number; integration: WebhookIntegration }>, + selector: string +) { + const integration = findWebhookIntegration( + entries.map((entry) => entry.integration), + selector + ); + return entries.find((entry) => entry.integration.id === integration.id)!; +} + +function createWebhookIntegration( + baseUrl: string, + existing: WebhookIntegration[], + params: { + name: string; + mode?: WebhookMode; + outgoingResultWebhook: string; + autoApprovalRate?: number; + secret?: string; + } +): WebhookIntegration { + const name = requiredText(params.name, "name"); + const mode = params.mode ?? "assisted"; + const outgoingResultWebhook = validUrl(params.outgoingResultWebhook, "outgoingResultWebhook"); + const autoApprovalRate = validApprovalRate(params.autoApprovalRate ?? 60); + const stamp = nextWebhookTimestamp(existing); + const webhookId = `wh_${stamp}_${randomBytes(8).toString("hex").slice(0, 7)}`; + const root = normalizeBaseUrl(baseUrl); + + return WebhookIntegrationSchema.parse({ + type: "webhook", + id: `integration-${stamp}`, + name, + mode, + incomingDocumentWebhook: { + id: webhookId, + url: `${root}/api/v1/integrations/webhook/${webhookId}/document` + }, + outgoingResultWebhook, + incomingManualResultWebhook: { + id: webhookId, + url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result` + }, + secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(), + autoApprovalRate + }); +} + +function nextWebhookTimestamp(existing: WebhookIntegration[]): number { + const usedIds = new Set(existing.map((integration) => integration.id)); + let stamp = Date.now(); + while (usedIds.has(`integration-${stamp}`)) stamp += 1; + return stamp; +} + +function generateWebhookSecret(): string { + return randomBytes(16).toString("hex"); +} + +function requiredText(value: string, field: string): string { + const normalized = value.trim(); + if (!normalized) throw new Error(`Webhook ${field} must not be empty`); + return normalized; +} + +function validUrl(value: string, field: string): string { + const normalized = requiredText(value, field); + try { + return new URL(normalized).toString(); + } catch { + throw new Error(`Webhook ${field} must be a valid URL`); + } +} + +function validApprovalRate(value: number): number { + if (!Number.isInteger(value) || value < 0 || value > 100) { + throw new Error("Webhook autoApprovalRate must be an integer between 0 and 100"); + } + return value; +} + export async function getApprovalContext( client: KyInstance, params: { diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index 8e0d938..f410e26 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -94,6 +94,14 @@ describe("sealTools", () => { expect(sealTools.find((item) => item.name === "seal_billing_features_list")).toBeDefined(); }); + test("includes Webhook management tools", () => { + expect(sealTools.find((item) => item.name === "seal_webhook_list")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_webhook_get")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_webhook_add")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_webhook_update")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_webhook_delete")).toBeDefined(); + }); + test("includes the approval search tool", () => { const tool = sealTools.find((item) => item.name === "seal_approval_search"); expect(tool).toBeDefined(); diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index 36cc2b8..8b8939e 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -1,11 +1,11 @@ import { z } from "zod"; import { KyInstance } from "ky"; import * as api from "./api.js"; -import { getHoseEnterpriseUrl } from "../../core/auth/hose.js"; +import { defaultSealUrl, getHoseEnterpriseUrl } from "../../core/auth/hose.js"; import { CorpConfig } from "../../core/config/types.js"; import { createSealClientForToken } from "../../core/http/factory.js"; import { searchApprovalContent } from "./search.js"; -import type { ApprovalRule, ApprovalRun, RuleSetVersion } from "./types.js"; +import type { ApprovalRule, ApprovalRun, RuleSetVersion, WebhookIntegration, WebhookMode } from "./types.js"; type ToolContext = { corp: CorpConfig; @@ -590,6 +590,156 @@ export const sealTools = [ context.corp.seal.endpoints.approvalStylePreferences ) }, + { + name: "seal_webhook_list", + description: "列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找", + parameters: z.object({ + query: z.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"), + includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩") + }), + handler: async ( + client: KyInstance, + params: { query?: string; includeSecret?: boolean }, + context: ToolContext + ) => { + const integrations = api.filterWebhookIntegrations( + await api.listWebhookIntegrations( + client, + context.corp.seal.endpoints.approvalStylePreferences + ), + params.query + ); + return { + count: integrations.length, + integrations: integrations.map((integration) => presentWebhookIntegration(integration, params.includeSecret === true)) + }; + } + }, + { + name: "seal_webhook_get", + description: "按 Webhook 集成 ID 或名称精确查找一条集成", + parameters: z.object({ + selector: z.string().min(1).describe("Webhook 集成 ID 或名称"), + includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩") + }), + handler: async ( + client: KyInstance, + params: { selector: string; includeSecret?: boolean }, + context: ToolContext + ) => { + const integration = api.findWebhookIntegration( + await api.listWebhookIntegrations( + client, + context.corp.seal.endpoints.approvalStylePreferences + ), + params.selector + ); + return presentWebhookIntegration(integration, params.includeSecret === true); + } + }, + { + name: "seal_webhook_add", + description: "新增 Webhook 集成并通过 AI 审批配置保存接口持久化", + 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") + }), + handler: async ( + client: KyInstance, + params: { + name: string; + mode?: WebhookMode; + outgoingResultWebhook: string; + autoApprovalRate?: number; + secret?: string; + }, + context: ToolContext + ) => { + const baseUrl = getConfiguredSealBaseUrl(context.corp); + const integration = await api.addWebhookIntegration( + client, + baseUrl, + params, + context.corp.seal.endpoints.approvalStylePreferences + ); + return { + saved: true, + integration: presentWebhookIntegration(integration, true) + }; + } + }, + { + name: "seal_webhook_update", + description: "更新现有 Webhook 集成并通过 AI 审批配置保存接口持久化", + parameters: z.object({ + selector: z.string().min(1).describe("Webhook 集成 ID 或名称"), + name: z.string().min(1).optional(), + mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(), + outgoingResultWebhook: z.string().url().optional(), + autoApprovalRate: z.number().int().min(0).max(100).optional(), + secret: z.string().min(1).optional(), + rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一") + }), + handler: async ( + client: KyInstance, + params: { + selector: string; + name?: string; + mode?: WebhookMode; + outgoingResultWebhook?: string; + autoApprovalRate?: number; + secret?: string; + rotateSecret?: 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( + client, + params.selector, + params, + context.corp.seal.endpoints.approvalStylePreferences + ); + return { + saved: true, + integration: presentWebhookIntegration( + integration, + params.secret !== undefined || params.rotateSecret === true + ) + }; + } + }, + { + name: "seal_webhook_delete", + description: "删除指定 Webhook 集成并通过 AI 审批配置保存接口持久化", + parameters: z.object({ + selector: z.string().min(1).describe("Webhook 集成 ID 或名称"), + confirm: z.boolean().describe("必须明确传 true 才执行删除") + }), + handler: async ( + client: KyInstance, + params: { selector: string; confirm: boolean }, + context: ToolContext + ) => { + if (!params.confirm) { + throw new Error("Refusing to delete Webhook integration without confirm=true"); + } + const integration = await api.deleteWebhookIntegration( + client, + params.selector, + context.corp.seal.endpoints.approvalStylePreferences + ); + return { + deleted: true, + integration: presentWebhookIntegration(integration, false) + }; + } + }, { name: "seal_approval_runs_search", description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段", @@ -991,6 +1141,11 @@ const sealActionNames = [ "seal_approval_document_update", "seal_approval_style_preferences_get", "seal_approval_style_preferences_update", + "seal_webhook_list", + "seal_webhook_get", + "seal_webhook_add", + "seal_webhook_update", + "seal_webhook_delete", "seal_approval_runs_summary", "seal_approval_run_get", "seal_approval_run_cited_rules_get", @@ -1020,6 +1175,11 @@ const sealActionAliases: Record = { "doc.update": "seal_approval_document_update", "style.get": "seal_approval_style_preferences_get", "style.update": "seal_approval_style_preferences_update", + "webhook.list": "seal_webhook_list", + "webhook.get": "seal_webhook_get", + "webhook.add": "seal_webhook_add", + "webhook.update": "seal_webhook_update", + "webhook.delete": "seal_webhook_delete", "runs.summary": "seal_approval_runs_summary", "runs.get": "seal_approval_run_get", "runs.citedRules": "seal_approval_run_cited_rules_get", @@ -1041,9 +1201,9 @@ export const sealMcpTools: SealToolDefinition[] = [ }, { name: "seal_action", - description: "Seal 低频管理操作统一入口。传 action=help 查看可用动作;支持 rule/doc/style/runs/batch/langfuse 等管理与诊断操作。", + description: "Seal 低频管理操作统一入口。传 action=help 查看可用动作;支持 rule/doc/style/webhook/runs/batch/langfuse 等管理与诊断操作。", parameters: z.object({ - action: z.string().describe("动作名,如 help、rule.create、doc.update、runs.summary、langfuse.bridge.get;也兼容旧 tool 名"), + action: z.string().describe("动作名,如 help、rule.create、doc.update、webhook.list、runs.summary、langfuse.bridge.get;也兼容旧 tool 名"), payload: z.record(z.string(), z.unknown()).optional().describe("动作参数对象") }), handler: async ( @@ -1103,7 +1263,7 @@ function sealActionHelp(topic: unknown) { return { usage: "seal_action({ action, payload })", - topics: ["session", "rule", "doc", "style", "runs", "batch", "langfuse"], + topics: ["session", "rule", "doc", "style", "webhook", "runs", "batch", "langfuse"], actions }; } @@ -1118,6 +1278,21 @@ function isSealActionToolName(name: string): name is (typeof sealActionNames)[nu return sealActionNames.includes(name as (typeof sealActionNames)[number]); } +function presentWebhookIntegration( + integration: WebhookIntegration, + includeSecret: boolean +) { + return includeSecret + ? integration + : { ...integration, secret: "" }; +} + +function getConfiguredSealBaseUrl(corp: CorpConfig): string { + if (corp.seal.url) return corp.seal.url; + if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source); + return corp.source.sealUrl; +} + type ApprovalRunSummary = { id: string; tenantId?: string; diff --git a/src/domains/seal/types.ts b/src/domains/seal/types.ts index 68f6f69..988f20b 100644 --- a/src/domains/seal/types.ts +++ b/src/domains/seal/types.ts @@ -159,6 +159,29 @@ export const ApprovalIntegrationSchema = z.object({ completionMessageId: z.string().optional() }).passthrough(); +export const WebhookModeSchema = z.enum([ + "assisted", + "semi_automatic", + "fully_automatic" +]); + +export const WebhookEndpointSchema = z.object({ + id: z.string(), + url: z.string().url() +}).passthrough(); + +export const WebhookIntegrationSchema = z.object({ + type: z.literal("webhook"), + id: z.string(), + name: z.string(), + mode: WebhookModeSchema, + incomingDocumentWebhook: WebhookEndpointSchema, + outgoingResultWebhook: z.string().url(), + incomingManualResultWebhook: WebhookEndpointSchema, + secret: z.string().min(1), + autoApprovalRate: z.number().int().min(0).max(100).optional() +}).passthrough(); + export const ApprovalStylePreferencesSchema = z.object({ id: z.string().optional(), tenantId: z.string().optional(), @@ -300,6 +323,9 @@ export type ApprovalDocument = z.infer; export type ApprovalDocumentListData = z.infer; export type DecisionPreferences = z.infer; export type ApprovalIntegration = z.infer; +export type WebhookMode = z.infer; +export type WebhookEndpoint = z.infer; +export type WebhookIntegration = z.infer; export type ApprovalStylePreferences = z.infer; export type ApprovalRun = z.infer; export type ApprovalRunListData = z.infer; @@ -316,4 +342,3 @@ export type PermissionConfigsData = z.infer; export type BillingStatusData = z.infer; -