Add Webhook integration CLI management
This commit is contained in:
1 parent
48d20a788f
commit
32149762c9
10 files changed
+755
-14
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
@@ -41,6 +41,11 @@ seal-home permissions configs [--corp <corpId>]
|
||||
seal-home billing status [--corp <corpId>]
|
||||
seal-home billing plans [--corp <corpId>]
|
||||
seal-home billing features [--corp <corpId>]
|
||||
seal-home webhook list [--query <text>] [--show-secret] [--corp <corpId>]
|
||||
seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
|
||||
seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
|
||||
seal-home webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
|
||||
seal-home webhook delete <idOrName> --yes [--corp <corpId>]
|
||||
seal-home source config [--corp <corpId>]
|
||||
seal-home tool <toolName> [--corp <corpId>] [--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 <text>] [--show-secret] [--corp <corpId>]`
|
||||
- `seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
|
||||
- `seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]`
|
||||
- `seal-home webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]`
|
||||
- `seal-home webhook delete <idOrName> --yes [--corp <corpId>]`
|
||||
- `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`
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-home",
|
||||
"version": "0.4.2",
|
||||
"version": "0.4.3",
|
||||
"type": "module",
|
||||
"module": "src/server.ts",
|
||||
"bin": {
|
||||
|
||||
@@ -36,6 +36,9 @@ describe("CLI version & help handling", () => {
|
||||
expect(result.stdout).toContain("Usage:");
|
||||
expect(result.stdout).toContain("seal-home users search <keyword>");
|
||||
expect(result.stdout).toContain("seal-home users delegation <userIdOrPhone|name>");
|
||||
expect(result.stdout).toContain("seal-home webhook get|find <idOrName>");
|
||||
expect(result.stdout).toContain("seal-home webhook add --name <name> --result-url <url>");
|
||||
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
|
||||
});
|
||||
|
||||
test("invalid command displays unknown command error with help hint", () => {
|
||||
|
||||
+128
@@ -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 <idOrName> [--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 <name> --result-url <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 <idOrName> [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 <idOrName> --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<string, WebhookMode> = {
|
||||
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<string, string | boolean>): 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<string, string | boolean>): 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 <corpId>]
|
||||
seal-home billing plans [--corp <corpId>]
|
||||
seal-home billing features [--corp <corpId>]
|
||||
seal-home webhook list [--query <text>] [--show-secret] [--corp <corpId>]
|
||||
seal-home webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
|
||||
seal-home webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
|
||||
seal-home webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
|
||||
seal-home webhook delete <idOrName> --yes [--corp <corpId>]
|
||||
seal-home source config [--corp <corpId>]
|
||||
seal-home tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
|
||||
seal-home rules count [--corp <corpId>]
|
||||
|
||||
@@ -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<string, unknown> | undefined;
|
||||
const client = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: webhookConfig() })
|
||||
}),
|
||||
post: (_url: string, options: { json: Record<string, unknown> }) => {
|
||||
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<Record<string, unknown>>;
|
||||
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<string, unknown> | undefined;
|
||||
const client = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: webhookConfig() })
|
||||
}),
|
||||
post: (_url: string, options: { json: Record<string, unknown> }) => {
|
||||
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<Record<string, unknown>>)[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<Record<string, unknown>>)).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"
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
+253
-1
@@ -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<string, unknown>,
|
||||
endpoint = "api/v1/agent/ai-approval/config"
|
||||
): Promise<boolean> {
|
||||
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<WebhookIntegration[]> {
|
||||
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<WebhookIntegration> {
|
||||
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<WebhookIntegration> {
|
||||
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<WebhookIntegration> {
|
||||
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<string, unknown>>
|
||||
): WebhookIntegration[] {
|
||||
return integrations
|
||||
.filter((integration) => integration.type === "webhook")
|
||||
.map((integration) => WebhookIntegrationSchema.parse(integration));
|
||||
}
|
||||
|
||||
function getWebhookEntries(
|
||||
integrations: Array<{ type: string } & Record<string, unknown>>
|
||||
): 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: {
|
||||
|
||||
@@ -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();
|
||||
|
||||
+180
-5
@@ -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<string, (typeof sealActionNames)[number]> = {
|
||||
"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: "<redacted>" };
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -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<typeof ApprovalDocumentSchema>;
|
||||
export type ApprovalDocumentListData = z.infer<typeof ApprovalDocumentListDataSchema>;
|
||||
export type DecisionPreferences = z.infer<typeof DecisionPreferencesSchema>;
|
||||
export type ApprovalIntegration = z.infer<typeof ApprovalIntegrationSchema>;
|
||||
export type WebhookMode = z.infer<typeof WebhookModeSchema>;
|
||||
export type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;
|
||||
export type WebhookIntegration = z.infer<typeof WebhookIntegrationSchema>;
|
||||
export type ApprovalStylePreferences = z.infer<typeof ApprovalStylePreferencesSchema>;
|
||||
export type ApprovalRun = z.infer<typeof ApprovalRunSchema>;
|
||||
export type ApprovalRunListData = z.infer<typeof ApprovalRunListDataSchema>;
|
||||
@@ -316,4 +342,3 @@ export type PermissionConfigsData = z.infer<typeof PermissionConfigsDataSchema>;
|
||||
export type BillingStatusData = z.infer<typeof BillingStatusDataSchema>;
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user