UNPKG

@sellable/install

Version:

One-command installer for Sellable MCP in Claude Code, Codex, and Hermes

197 lines (188 loc) • 6.1 kB
import { createHmac, randomBytes } from "node:crypto"; export const REALTIME_WEBHOOK_HOST = "127.0.0.1"; export const REALTIME_WEBHOOK_PORT = 8644; export const REALTIME_WEBHOOK_ROUTE_NAME = "sellable_events"; export const REALTIME_WEBHOOK_EVENTS = Object.freeze([ "hot_linkedin_reply", "lead_import_finished", "low_campaign_send_supply", ]); export function createEphemeralLoopbackWebhookSecret() { return randomBytes(32).toString("hex"); } /** * Build Hermes v0.23.5's strictly loopback-only `platforms.webhook` section. * * Never binds a public interface (`host` is pinned to `127.0.0.1`) so Fly * Machine `services: []` and `runtime.publicListener: false` stay intact. * Uses Hermes' native `coalesce` (debounced per `entityId`) and * `mirror_to_session: true` so follow-up Slack replies have full context. * * @param {{ secret: string, defaultChannelId?: string | null, port?: number }} options */ export function buildLoopbackWebhookPlatformConfig({ secret, defaultChannelId = null, port = REALTIME_WEBHOOK_PORT, }) { if (typeof secret !== "string" || secret.trim().length < 16) { throw new Error("realtime_webhook_secret_rejected"); } const normalizedPort = Number(port); if ( !Number.isSafeInteger(normalizedPort) || normalizedPort < 1024 || normalizedPort > 65535 ) { throw new Error("realtime_webhook_port_rejected"); } const targetChannel = typeof defaultChannelId === "string" && defaultChannelId.trim().length > 0 ? defaultChannelId.trim() : null; return { enabled: true, extra: { host: REALTIME_WEBHOOK_HOST, port: normalizedPort, secret, rate_limit: 60, routes: { [REALTIME_WEBHOOK_ROUTE_NAME]: { events: [...REALTIME_WEBHOOK_EVENTS], secret, coalesce: { key: "entityId", window_seconds: 15, max_wait_seconds: 60, }, mirror_to_session: true, deliver: targetChannel ? "slack" : "log", ...(targetChannel ? { deliver_extra: { chat_id: targetChannel } } : {}), prompt: [ "Sellable realtime workspace event received ({eventType}).", "Entity: {entityId}", "Summary: {summary}", "Payload: {payload}", "Act promptly on this event in the workspace's Slack channel using Sellable MCP tools and report only what matters.", ].join("\n"), }, }, }, }; } /** * Compute Hermes v0.23.5 generic HMAC-V2 headers: * `X-Webhook-Signature-V2 = hex(HMAC-SHA256(secret, "<timestamp>.<body>"))` */ export function signWebhookV2Payload({ secret, body, eventType, deliveryId, timestampSec = Math.floor(Date.now() / 1000), }) { if (typeof secret !== "string" || secret.trim().length < 16) { throw new Error("realtime_webhook_secret_rejected"); } const rawBody = typeof body === "string" ? body : JSON.stringify(body); const ts = String(Math.floor(Number(timestampSec))); const signature = createHmac("sha256", secret) .update(`${ts}.${rawBody}`) .digest("hex"); return { body: rawBody, headers: { "content-type": "application/json", "x-webhook-timestamp": ts, "x-webhook-signature-v2": signature, "x-webhook-event": String(eventType || "sellable_event"), "x-webhook-delivery": String(deliveryId || `${ts}-${randomBytes(6).toString("hex")}`), }, }; } /** * Non-blocking worker pull loop that claims realtime workspace events via * `POST /api/v3/sellable-agent/worker/events-claim` and forwards them over * loopback HTTP (`127.0.0.1:8644`) with HMAC-V2 signing into Hermes. * * Acknowledges only events accepted with HTTP 2xx on the next claim pass. */ export function startRealtimeEventForwarder({ claimEvents, webhookSecret, port = REALTIME_WEBHOOK_PORT, routeName = REALTIME_WEBHOOK_ROUTE_NAME, intervalMs = 15_000, fetchImpl = globalThis.fetch, onError = () => {}, }) { const endpointUrl = `http://${REALTIME_WEBHOOK_HOST}:${port}/webhooks/${routeName}`; let stopped = false; let running = false; let pendingAckIds = []; let timer = null; async function pollOnce() { if (stopped || running) return { delivered: 0, claimed: 0 }; running = true; try { const ackBatch = pendingAckIds.slice(0, 50); const response = await claimEvents({ max: 20, ackIds: ackBatch, }); if (ackBatch.length > 0) { pendingAckIds = pendingAckIds.slice(ackBatch.length); } const events = Array.isArray(response?.events) ? response.events : []; let delivered = 0; for (const event of events) { if (stopped) break; const deliveryId = String(event?.id ?? "").trim(); const eventType = String(event?.eventType ?? "").trim(); if (!deliveryId || !eventType) continue; const signed = signWebhookV2Payload({ secret: webhookSecret, eventType, deliveryId, body: { id: deliveryId, eventType, entityId: String(event?.entityId ?? deliveryId), summary: String(event?.summary ?? eventType), payload: event?.payload ?? {}, createdAt: event?.createdAt ?? null, }, }); const res = await fetchImpl(endpointUrl, { method: "POST", headers: signed.headers, body: signed.body, signal: AbortSignal.timeout(10_000), }); if (res.ok) { delivered += 1; pendingAckIds.push(deliveryId); } } return { delivered, claimed: events.length }; } catch (error) { onError(error); return { delivered: 0, claimed: 0 }; } finally { running = false; } } timer = setInterval(() => { void pollOnce(); }, Math.max(2_000, Number(intervalMs) || 15_000)); if (typeof timer.unref === "function") timer.unref(); return { pollOnce, stop() { stopped = true; if (timer) clearInterval(timer); timer = null; }, }; }