UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,217 lines (1,216 loc) • 38.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { k as resolveDateTimestampMs, z as resolveTimestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs"; import { o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { g as toAgentStoreSessionKey, s as isUnscopedSessionKeySentinel } from "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import "./io-4QsrsWTJ.mjs"; import { C as runWithGatewayDetachedWorkContinuation } from "./gateway-work-admission-79pid1hQ.mjs"; import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs"; import { x as resolveRequestClientIpFromHeaders } from "./net-BgRayX-P.mjs"; import { l as withSystemEventOwner } from "./system-event-ownership-zDxyv2EM.mjs"; import { n as channelRouteDedupeKey } from "./channel-route-E3mkfWI_.mjs"; import { _ as peekSystemEventEntries, c as enqueueRequiredSystemEventEntry, i as consumeSelectedSystemEventEntries, m as isSystemEventTurnOwned, t as SystemEventQueueFullError } from "./system-events-BFJiZPP0.mjs"; import { t as enqueueSessionEventForHost } from "./session-event-handoff-CC7Ui3SA.mjs"; import { n as canonicalizeMainSessionAlias, r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs"; import { r as captureSessionEventTargetForHost } from "./session-event-target-BPiQeS30.mjs"; import "./sessions-D5Vvu3AE.mjs"; import { a as AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH, h as normalizeRateLimitClientIp, p as createGatewayAuthRateLimiter } from "./auth-rate-limit-DGfPTrXr.mjs"; import { u as readPreparedGatewayIngressAttribution } from "./ingress-attribution-DAAQgd6y.mjs"; import { n as DEDUPE_TTL_MS, t as DEDUPE_MAX } from "./server-constants-CYohpfLc.mjs"; import { f as sendHttpRequestRejection } from "./http-body-B9w7rzPz.mjs"; import { t as resolveCronAgentSessionKey } from "./session-key-BQPSZVRH.mjs"; import { _ as resolveHookIdempotencyKey, a as getHookSessionKeyPrefixError, c as normalizeAgentPayload, d as normalizeWakePayload, g as resolveHookDeliver, h as resolveHookChannel, i as getHookChannelError, l as normalizeHookDispatchSessionKey, m as resolveEffectiveHookTargetAgentId, n as extractHookToken, o as isHookAgentAllowed, p as readJsonBody, r as getHookAgentPolicyError, s as isSessionKeyAllowedByPrefix, u as normalizeHookHeaders, v as resolveHookPathBodyLimit, x as applyHookMappings, y as resolveHookSessionKey } from "./hooks-CCWUVSIu.mjs"; import { t as sendJson } from "./http-json-ddGJz5CA.mjs"; import "./http-common-FfhIIwOW.mjs"; import { r as resolveHookExternalContentSource } from "./external-content-source-BOt3r-v5.mjs"; import "./external-content-CGL7l-3s.mjs"; import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs"; import { r as resolveOutboundChannelPlugin } from "./channel-resolution-DjtSMYUG.mjs"; import { r as validateExplicitMessageAccountSelection } from "./message-account-selection-DxhPXlSt.mjs"; import { t as admitEventOccurrence } from "./event-occurrence-admission-CGIoTVyH.mjs"; import { n as fenceScheduledGatewayContextResolver, t as createScheduledGatewayRunner } from "./scheduled-run-gateway-context-0pdhso3i.mjs"; import { randomUUID } from "node:crypto"; //#region src/gateway/server/hooks-request-handler-response.ts const HOOK_FAN_OUT_RESPONSE_DEADLINE_MS = 8e3; var HookWakeUnavailableError = class extends Error {}; const FAN_OUT_PENDING = Symbol("hook-fanout-pending"); async function settleFanOutDispatches(e) { const t = e.map((e) => e.catch((e) => ({ ok: false, statusCode: 502, error: String(e) }))); let n; const r = new Promise((e) => { n = setTimeout(() => e(FAN_OUT_PENDING), HOOK_FAN_OUT_RESPONSE_DEADLINE_MS).unref(); }); try { return await Promise.all(t.map((e) => Promise.race([e, r]))); } finally { clearTimeout(n); } } function sendAgentResult(e, t, n, r = false) { if (!t.ok) { const { statusCode: r, ...i } = t; sendJson(e, r, { ...i, ...n }); return; } const send = (r) => sendJson(e, 200, { ok: true, runId: t.runId, ...n, ...r ? { completion: r } : {} }); return r ? t.completion.then(send) : send(); } function sendFanOutResult(e, t, n) { const r = t[0]; if (t.length === 1 && r !== void 0 && r !== FAN_OUT_PENDING) { sendAgentResult(e, r, n); return; } const i = []; const a = []; let o = 0; for (const e of t) if (e === FAN_OUT_PENDING) o += 1; else if (e.ok) i.push(e.runId); else a.push(e); if (a.length === 0 && o === 0) { const t = { ok: true, runId: i[0], runIds: i, dispatched: i.length }; sendJson(e, 200, { ...t, ...n }); return; } const s = a[0]; sendJson(e, s ? s.statusCode : 503, { ok: false, error: `hook fan-out incomplete: ${i.length}/${t.length} dispatched, ${a.length} failed, ${o} pending`, runIds: i, ...a.length > 0 ? { errors: a.slice(0, 5).map((e) => e.error) } : {}, ...n }); } //#endregion //#region src/gateway/server/hooks-event-dispatch.ts function resolveHookEventTarget(e) { if (e.cfg.session?.scope === "global") return { eventSessionKey: "global", agentId: e.resolvedAgentId }; return { eventSessionKey: e.sessionKey ? canonicalizeMainSessionAlias({ cfg: e.cfg, agentId: e.resolvedAgentId, sessionKey: toAgentStoreSessionKey({ agentId: e.resolvedAgentId, requestKey: e.sessionKey, mainKey: e.cfg.session?.mainKey }) }) : resolveAgentMainSessionKey({ cfg: e.cfg, agentId: e.resolvedAgentId }), agentId: e.resolvedAgentId }; } async function deferHookEvent(e, t) { if (!e) throw new HookWakeUnavailableError("Scheduled Hook wake admission is unavailable; restart the Gateway"); const n = await e(t); if (!n.ok) throw new HookWakeUnavailableError(n.reason ?? "No scheduled target can receive this Hook notice"); return { eventOutcome: n.eventOutcome }; } /** Owns capture, queue custody, and acceptance for immediate or deferred hook wakes. */ function createHookWakeDispatcher(e, t) { const n = /* @__PURE__ */ new Map(); return async (r, i, a) => { const o = resolveHookEventTarget({ cfg: readRuntimeConfig(), resolvedAgentId: i, sessionKey: r.sessionKey }); const s = /* @__PURE__ */ new Error("Hook configuration changed during wake admission"); let c = false; const assertAcceptanceCurrent = () => { if (c || a?.() === false) { c = true; throw s; } }; let l; try { assertAcceptanceCurrent(); l = await captureSessionEventTargetForHost(o.agentId, o.eventSessionKey, { assertCaptureCurrent: assertAcceptanceCurrent }); assertAcceptanceCurrent(); if (r.mode === "next-heartbeat") return await deferHookEvent(t, { text: r.text, agentId: o.agentId, expectedTarget: l, createIfMissing: true, commitGuard: assertAcceptanceCurrent }); } catch (e) { if (e === s) return null; throw new HookWakeUnavailableError(formatErrorMessage(e)); } const u = withSystemEventOwner({ sessionKey: o.eventSessionKey, deliveryContext: l.deliveryContext }, o.agentId); let d = enqueueRequiredSystemEventEntry(r.text, u); const f = d ? "queued" : "coalesced"; let p; if (!d) { const e = peekSystemEventEntries(u.sessionKey).at(-1); if (!e || e.text !== r.text.trim() || e.contextKey != null || channelRouteDedupeKey(e.deliveryContext) !== channelRouteDedupeKey(u.deliveryContext)) throw new HookWakeUnavailableError("Hook wake has no pending occurrence to accept"); if (isSystemEventTurnOwned(u.sessionKey, e)) { p = e.id ? n.get(e.id) : void 0; if (!p) throw new HookWakeUnavailableError("Hook wake acceptance is owned by another dispatcher"); } d = e; } let m = false; try { if (!p) { const t = enqueueSessionEventForHost(r.text, { agentId: o.agentId, sessionKey: o.eventSessionKey, source: "hook", occurrences: [d], ...f === "coalesced" ? { preserveOccurrenceOnRejection: true } : {}, expectedTarget: l, createIfMissing: true, assertAcceptanceCurrent }); p = t; m = true; n.set(t.id, t); t.settled.then((r) => { if (n.get(t.id) === t) n.delete(t.id); if (r.status !== "completed") e(r); }); } const t = await p.accepted; if (!t.ok) { assertAcceptanceCurrent(); throw new HookWakeUnavailableError(t.error); } assertAcceptanceCurrent(); } catch (e) { if (m) p?.cancel(); if (f === "queued") consumeSelectedSystemEventEntries(u.sessionKey, [d]); if (e === s) return null; throw e; } return { eventOutcome: f }; }; } //#endregion //#region src/gateway/server/hooks-request-handler.ts const HOOK_AUTH_FAILURE_LIMIT = 20; const HOOK_AUTH_FAILURE_WINDOW_MS = 6e4; const HOOK_FAN_OUT_DERIVED_IDEMPOTENCY = "hook-fanout-item"; const HOOK_CONFIG_CHANGED_ERROR = "hook configuration changed; retry request"; function createHooksRequestHandler(e) { const { getHooksConfig: t, logHooks: n, dispatchAgentHook: r, dispatchWakeHook: i, getClientIpConfig: a } = e; const o = /* @__PURE__ */ new Map(); const s = createGatewayAuthRateLimiter({ maxAttempts: HOOK_AUTH_FAILURE_LIMIT, windowMs: HOOK_AUTH_FAILURE_WINDOW_MS, lockoutMs: HOOK_AUTH_FAILURE_WINDOW_MS, exemptLoopback: false, pruneIntervalMs: 0 }, { scheduler: e.scheduler }); const resolveHookClientKey = (e) => { const t = readPreparedGatewayIngressAttribution(e); if (t && t.kind !== "unattributable-proxy") return normalizeRateLimitClientIp(t.rateLimit.subject.key); const n = a?.(); const r = resolveRequestClientIpFromHeaders(e, n?.trustedProxies, n?.allowRealIpFallback === true) ?? e.socket?.remoteAddress; return normalizeRateLimitClientIp(r); }; const pruneHookReplayCache = (e) => { for (const [t, n] of o) if (n.state === "terminal" && n.ts < e - 3e5) o.delete(t); const t = [...o].filter(([, e]) => e.state === "terminal"); for (const [e] of t.slice(0, Math.max(0, t.length - DEDUPE_MAX))) o.delete(e); }; const buildHookReplayCacheKey = (e) => { const t = e.idempotencyKey?.trim(); if (!t) return; const n = JSON.stringify({ pathKey: e.pathKey, dispatchScope: e.dispatchScope }); return `${sha256Hex(e.token ?? "")}:${sha256Hex(n)}:${sha256Hex(t)}`; }; const resolveHookReplay = (e) => { if (!e) return; pruneHookReplayCache(Date.now()); const t = o.get(e); if (!t) return; if (t.state === "terminal") { o.delete(e); o.set(e, t); } return t.dispatch; }; const dispatchAgentHookWithReplay = (e, t) => { if (!e) return t(); const n = resolveHookReplay(e); if (n) return n; const r = Promise.resolve().then(t).then((t) => { if (t.ok) { o.set(e, { state: "active", dispatch: t }); const settle = () => { const n = { state: "terminal", ts: Date.now(), dispatch: t }; o.delete(e); o.set(e, n); pruneHookReplayCache(n.ts); }; t.completion.then(settle, settle); } else o.delete(e); return t; }).catch((t) => { o.delete(e); throw t; }); o.set(e, { state: "pending", dispatch: r }); return r; }; return async (e, a) => { const o = t(); if (!o) return false; const c = new URL(e.url ?? "/", "http://localhost"); const l = o.basePath; if (c.pathname !== l && !c.pathname.startsWith(`${l}/`)) return false; if (c.searchParams.has("token")) { a.statusCode = 400; a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Hook token must be provided via Authorization: Bearer <token> or X-OpenClaw-Token header (query parameters are not allowed)."); return true; } if (e.method !== "POST") { a.statusCode = 405; a.setHeader("Allow", "POST"); a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Method Not Allowed"); return true; } const u = extractHookToken(e); const d = resolveHookClientKey(e); if (!safeEqualSecret(u, o.token)) { const e = s.check(d, AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH); if (!e.allowed) { const t = e.retryAfterMs > 0 ? Math.ceil(e.retryAfterMs / 1e3) : 1; a.statusCode = 429; a.setHeader("Retry-After", String(t)); a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Too Many Requests"); n.warn(`hook auth throttled for ${d}; retry-after=${t}s`); return true; } s.recordFailure(d, AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH); a.statusCode = 401; a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Unauthorized"); return true; } s.reset(d, AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH); const isHooksConfigCurrent = () => t() === o; const rejectChangedHooksConfig = () => { if (isHooksConfigCurrent()) return false; sendJson(a, 409, { ok: false, error: HOOK_CONFIG_CHANGED_ERROR }); return true; }; const changedHooksConfigDispatchResult = () => ({ ok: false, statusCode: 409, error: HOOK_CONFIG_CHANGED_ERROR }); const f = c.pathname.slice(l.length).replace(/^\/+/, ""); if (!f) { a.statusCode = 404; a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Not Found"); return true; } const p = resolveHookPathBodyLimit(o, f); const m = await readJsonBody(e, p); if (!m.ok) { const t = { ok: false, error: m.error }; const r = m.error === "payload too large" ? 413 : m.error === "request body timeout" ? 408 : 400; n.warn(`hook request rejected for ${l}/${f}: status=${r} bodyLimitBytes=${p}`); if (r === 400) sendJson(a, 400, t); else await sendHttpRequestRejection(e, a, r, JSON.stringify(t), "application/json; charset=utf-8"); return true; } if (rejectChangedHooksConfig()) return true; const h = asRecord(m.value); const g = normalizeHookHeaders(e); const _ = resolveHookIdempotencyKey({ payload: h, headers: g }); let v; const sendHookError = (e) => sendJson(a, 400, { ok: false, error: e, ...v }); const resolveDispatchSessionKeyOrRespond = (e, t) => { const n = normalizeHookDispatchSessionKey({ sessionKey: e, targetAgentId: t }); const r = o.sessionPolicy.allowedSessionKeyPrefixes; if (r && !isSessionKeyAllowedByPrefix(n, r)) { sendHookError(getHookSessionKeyPrefixError(r)); return null; } return n; }; const resolveTargetAgentOrRespond = (e, t) => { const n = resolveEffectiveHookTargetAgentId(o, e, t); if (!n.ok) { sendHookError(n.error); return null; } if (!isHookAgentAllowed(o, n.effectiveAgentId)) { sendHookError(getHookAgentPolicyError()); return null; } return n; }; const dispatchWake = async (e, t, n) => { let r; if (e.sessionKey) { const i = resolveHookSessionKey({ hooksConfig: o, source: n, sessionKey: e.sessionKey }); if (!i.ok) { sendHookError(i.error); return null; } const a = resolveDispatchSessionKeyOrRespond(i.value, t); if (a === null) return null; r = a; } const s = { ...e, sessionKey: r }; if (rejectChangedHooksConfig()) return null; try { return await i(s, t, () => !rejectChangedHooksConfig()); } catch (e) { if (!(e instanceof SystemEventQueueFullError || e instanceof HookWakeUnavailableError)) throw e; sendJson(a, 503, { ok: false, error: e.message, ...v }); return null; } }; if (f === "wake") { const e = normalizeWakePayload(h); if (!e.ok) { sendJson(a, 400, { ok: false, error: e.error }); return true; } const t = resolveTargetAgentOrRespond(e.value.agentId, "request"); if (!t) return true; const n = await dispatchWake(e.value, t.effectiveAgentId, "request"); if (!n) return true; sendJson(a, 200, { ok: true, mode: e.value.mode, ...n }); return true; } if (f === "agent") { const e = h.waitForCompletion; if (e !== void 0 && typeof e !== "boolean") { sendJson(a, 400, { ok: false, error: "waitForCompletion must be boolean" }); return true; } const t = normalizeAgentPayload(h); if (!t.ok) { sendJson(a, 400, { ok: false, error: t.error }); return true; } const n = resolveTargetAgentOrRespond(t.value.agentId, "request"); if (!n) return true; if (t.value.sessionMode === "persistent" && !t.value.sessionKey) { sendJson(a, 400, { ok: false, error: "sessionKey is required when sessionMode is persistent" }); return true; } const i = resolveHookSessionKey({ hooksConfig: o, source: "request", sessionKey: t.value.sessionKey }); if (!i.ok) { sendJson(a, 400, { ok: false, error: i.error }); return true; } if (t.value.sessionMode === "persistent" && !o.sessionPolicy.allowedSessionKeyPrefixes?.length) { sendJson(a, 400, { ok: false, error: "hooks.allowedSessionKeyPrefixes is required when direct hook sessionMode is persistent" }); return true; } const s = buildHookReplayCacheKey({ pathKey: "agent", token: u, idempotencyKey: _, dispatchScope: { agentId: n.effectiveAgentId, sessionKey: t.value.sessionKey ?? o.sessionPolicy.defaultSessionKey ?? null, message: t.value.message, name: t.value.name, wakeMode: t.value.wakeMode, sessionMode: t.value.sessionMode, deliver: t.value.deliver, channel: t.value.channel, to: t.value.to ?? null, accountId: t.value.accountId ?? null, model: t.value.model ?? null, thinking: t.value.thinking ?? null, timeoutSeconds: t.value.timeoutSeconds ?? null } }); const c = resolveHookReplay(s); if (c) { await sendAgentResult(a, await c, void 0, e === true); return true; } const d = resolveDispatchSessionKeyOrRespond(i.value, n.effectiveAgentId); if (d === null) return true; const f = await dispatchAgentHookWithReplay(s, () => { if (!isHooksConfigCurrent()) return changedHooksConfigDispatchResult(); return r({ ...t.value, effectiveAgentId: n.effectiveAgentId, idempotencyKey: _, sessionKey: d, sourcePath: `${l}/agent`, agentId: n.selectedAgentId, externalContentSource: "webhook", replayKey: s }); }); await sendAgentResult(a, f, void 0, e === true); return true; } if (o.mappings.length > 0) try { const e = await applyHookMappings(o.mappings, { payload: h, headers: g, url: c, path: f }); if (rejectChangedHooksConfig()) return true; if (e) { if (!e.ok) { sendJson(a, 400, { ok: false, error: e.error }); return true; } if (e.dropped > 0) n.warn(`hook mapping ${f} fan-out dropped ${e.dropped} items beyond the ${200}-item cap`); if (e.actions.length === 0) { if (e.fanout) n.info(`hook mapping ${f} matched with no items to dispatch`); a.statusCode = 204; a.end(); return true; } const t = /* @__PURE__ */ new Map(); const prepareMappedAgentDispatchOrRespond = (n) => { const i = resolveHookChannel(n.channel); if (!i) { sendHookError(getHookChannelError()); return null; } const a = resolveHookDeliver(n.deliver); const s = a ? { mode: "announce", channel: i, to: n.to } : { mode: "none" }; const c = resolveTargetAgentOrRespond(n.agentId, "mapping"); if (!c) return null; if (n.sessionMode === "persistent" && !n.sessionKey && !o.sessionPolicy.defaultSessionKey) { sendHookError("sessionKey or hooks.defaultSessionKey is required when mapped hook sessionMode is persistent"); return null; } const d = resolveHookSessionKey({ hooksConfig: o, source: n.sessionKeySource === "static" ? "mapping-static" : "mapping-templated", sessionKey: n.sessionKey }); if (!d.ok) { sendHookError(d.error); return null; } const p = resolveDispatchSessionKeyOrRespond(d.value, c.effectiveAgentId); if (p === null) return null; const m = { agentId: c.effectiveAgentId, sessionKey: n.sessionKey ?? o.sessionPolicy.defaultSessionKey ?? null, message: n.message, name: n.name ?? "Hook", wakeMode: n.wakeMode, sessionMode: n.sessionMode, deliver: a, channel: i, to: n.to ?? null, model: n.model ?? null, thinking: n.thinking ?? null, timeoutSeconds: n.timeoutSeconds ?? null }; if (e.fanout) { const e = JSON.stringify(m); const n = t.get(e) ?? 0; t.set(e, n + 1); m.occurrence = n; } const h = buildHookReplayCacheKey({ pathKey: f, token: u, idempotencyKey: e.fanout ? _ ?? HOOK_FAN_OUT_DERIVED_IDEMPOTENCY : _, dispatchScope: m }); return () => dispatchAgentHookWithReplay(h, () => { if (!isHooksConfigCurrent()) return changedHooksConfigDispatchResult(); return r({ message: n.message, name: n.name ?? "Hook", idempotencyKey: _, agentId: c.selectedAgentId, effectiveAgentId: c.effectiveAgentId, wakeMode: n.wakeMode, sessionKey: p, sessionMode: n.sessionMode, sourcePath: `${l}/${f}`, deliver: a, channel: i, to: n.to, delivery: s, model: n.model, thinking: n.thinking, timeoutSeconds: n.timeoutSeconds, mappingId: n.mappingId, allowUnsafeExternalContent: n.allowUnsafeExternalContent, ...e.fanout ? { admissionMode: "background" } : {}, replayKey: h, externalContentSource: f === "gmail" ? "gmail" : resolveHookExternalContentSource(d.value) ?? "webhook" }); }); }; const i = []; let s; for (const t of e.actions) { if (t.kind === "wake") { const e = resolveTargetAgentOrRespond(t.agentId, "mapping"); if (!e) return true; const n = await dispatchWake({ text: t.text, mode: t.mode, sessionKey: t.sessionKey }, e.effectiveAgentId, t.sessionKeySource === "static" ? "mapping-static" : "mapping-templated"); if (!n) return true; if (!v || n.eventOutcome === "queued") v = n; s = t.mode; continue; } const e = prepareMappedAgentDispatchOrRespond(t); if (!e) return true; i.push(e); } if (i.length === 0) { sendJson(a, 200, { ok: true, mode: s ?? "now", ...v }); return true; } if (!e.fanout) { const e = await i[0](); sendAgentResult(a, e, v); return true; } const c = await settleFanOutDispatches(i.map((e) => Promise.resolve(e()))); sendFanOutResult(a, c, v); return true; } } catch (e) { n.warn(`hook mapping failed: ${String(e)}`); sendJson(a, 500, { ok: false, error: "hook mapping failed" }); return true; } a.statusCode = 404; a.setHeader("Content-Type", "text/plain; charset=utf-8"); a.end("Not Found"); return true; }; } //#endregion //#region src/gateway/server/hooks.ts const HOOK_AGENT_START_ADMISSION_TIMEOUT_MS = 15e3; const HOOK_AGENT_START_ADMISSION_TIMEOUT_ERROR = "hook agent run did not start before admission timeout"; const HOOK_AGENT_SESSION_CONFLICT_ERROR = "hook agent run was rejected because the target session changed"; const HOOK_AGENT_PREPARATION_ERROR = "hook agent run failed before entering the agent runner"; function resolveHookRunSummary(e) { return (e.status !== "ok" ? normalizeOptionalString(e.diagnostics?.summary) : void 0) || normalizeOptionalString(e.summary) || normalizeOptionalString(e.error) || e.status; } function sanitizeHookConsoleValue(e) { const t = normalizeOptionalString(e); if (!t) return; const n = Array.from(t, (e) => { const t = e.charCodeAt(0); return t < 32 || t === 127 ? " " : e; }).join(""); return truncateUtf16Safe(n.replace(/\s+/gu, " ").trim(), 500); } function sanitizeHookLogMetadata(e) { return Object.fromEntries(Object.entries(e).filter(([, e]) => e !== void 0).map(([e, t]) => [e, typeof t === "string" ? sanitizeHookConsoleValue(redactToolPayloadText(t).replace(/\p{Cc}/gu, " ")) : t])); } function createHookAdmissionFailure(e) { const t = e.statusCode ?? (e.disposition === "session-conflict" ? 409 : 502); return { ok: false, statusCode: t, error: t === 409 ? HOOK_AGENT_SESSION_CONFLICT_ERROR : t === 503 ? HOOK_AGENT_START_ADMISSION_TIMEOUT_ERROR : HOOK_AGENT_PREPARATION_ERROR, runId: e.runId }; } function createSessionKeyedHookDispatchQueue() { const e = /* @__PURE__ */ new Map(); return (t, n) => { const r = e.get(t); const i = r ? r.catch(() => void 0).then(n) : n(); const a = i.then(() => void 0, () => void 0); e.set(t, a); a.finally(() => { if (e.get(t) === a) e.delete(t); }); return i; }; } async function validateHookAgentDeliveryAccount(e) { if (e.value.delivery.mode !== "announce" || e.value.delivery.channel === "last" || !e.value.delivery.to) return e.value; const t = e.value.delivery.accountId ? await validateExplicitMessageAccountSelection({ cfg: e.cfg, channel: e.value.delivery.channel, accountId: e.value.delivery.accountId }) : (() => { const t = resolveOutboundChannelPlugin({ channel: e.value.delivery.channel, cfg: e.cfg }); if (!t) throw new Error(`Channel ${e.value.delivery.channel} is unavailable.`); return resolveChannelDefaultAccountId({ plugin: t, cfg: e.cfg }); })(); if (!t) throw new Error(`Channel ${e.value.delivery.channel} did not resolve an account.`); return { ...e.value, accountId: t, delivery: { ...e.value.delivery, accountId: t } }; } /** Creates one lifecycle-owned dispatcher shared by HTTP hooks and trusted plugins. */ function createGatewayHookDispatcher(e) { const { deps: t, logHooks: n, resolveGatewayContext: r, agentStartAdmissionTimeoutMs: i = HOOK_AGENT_START_ADMISSION_TIMEOUT_MS } = e; const a = fenceScheduledGatewayContextResolver(r); const o = createScheduledGatewayRunner(a); const s = createSessionKeyedHookDispatchQueue(); const c = /* @__PURE__ */ new Map(); const claimFailureNotice = (e) => { if (!e) return true; const t = Date.now(); for (const [e, n] of c) if (n < t - 3e5) c.delete(e); if (c.has(e)) return false; c.set(e, t); pruneMapToMaxSize(c, DEDUPE_MAX); return true; }; let l; const loadIsolatedAgentModule = () => l ??= import("./isolated-agent-bzYpyUzf.mjs"); const u = createHookWakeDispatcher((e) => { n.warn("hook wake failed", sanitizeHookLogMetadata({ status: e.status, error: e.error })); }, e.deferHookWake); const dispatchAgentHook = async (r, a) => { const l = r.sessionKey; const u = sanitizeHookConsoleValue(r.name) ?? "Hook"; const d = randomUUID(); const f = randomUUID(); const p = createDeferredCore(); const m = sanitizeHookLogMetadata({ runId: f, jobId: d, sourcePath: r.sourcePath, name: r.name, agentId: r.effectiveAgentId, logicalSessionKey: l }); const logHookRunTerminal = (e) => { const t = { ...m, ...sanitizeHookLogMetadata({ status: e.status, sessionId: e.sessionId, sessionKey: e.sessionKey, deliver: r.deliver, delivered: e.delivered, deliveryAttempted: e.deliveryAttempted, deliveryError: e.deliveryError, deliverySuppressionReason: e.deliverySuppressionReason, model: e.model ?? r.model, summary: e.status !== "ok" ? resolveHookRunSummary(e) : void 0 }) }; const i = [ "runId", "status", "deliveryError", "summary", "model" ].flatMap((e) => t[e] === void 0 ? [] : [`${e}=${String(t[e])}`]); const a = truncateUtf16Safe(["hook agent run completed", ...i].join(" "), 500); const o = e.status !== "ok" || e.deliveryError ? "warn" : "info"; n[o](a, t); return { status: e.status, replyDisposition: e.replyDisposition ?? "empty", ...e.delivered !== void 0 ? { delivered: e.delivered } : {}, ...e.deliveryAttempted !== void 0 ? { deliveryAttempted: e.deliveryAttempted } : {}, ...e.deliveryError ? { deliveryError: "delivery-failed" } : {}, ...e.deliverySuppressionReason ? { deliverySuppressionReason: e.deliverySuppressionReason } : {} }; }; const h = resolveDateTimestampMs(Date.now()); const g = { id: d, agentId: r.effectiveAgentId, name: u, enabled: true, createdAtMs: h, updatedAtMs: h, schedule: { kind: "at", at: resolveTimestampMsToIsoString(h) }, sessionTarget: r.sessionMode === "persistent" ? `session:${l}` : "isolated", wakeMode: "now", payload: { kind: "agentTurn", message: r.message, model: r.model, thinking: r.thinking, timeoutSeconds: r.timeoutSeconds, allowUnsafeExternalContent: r.allowUnsafeExternalContent, externalContentSource: r.externalContentSource }, delivery: r.delivery, state: { nextRunAtMs: h } }; let _; const resolveGlobalTerminalAgentId = (e) => { const t = _?.agentId; if (t && listAgentIds(readRuntimeConfig()).includes(t)) return t; n.warn("hook agent terminal event suppressed", { ...m, ...sanitizeHookLogMetadata({ acceptedAgentId: t, status: e }), reason: "accepted-agent-removed" }); }; const announceHookEvent = async (t, i, a) => { if (a !== "ok" && !claimFailureNotice(r.replayKey)) return; try { const o = t.eventSessionKey; const s = isUnscopedSessionKeySentinel(o); let c = t.agentId; if (s && _) { const e = resolveGlobalTerminalAgentId(a); if (!e) return; c = e; } const l = t.expectedTarget ?? (_ ? void 0 : await captureSessionEventTargetForHost(c, o)); if (!l) throw new Error("Hook terminal target could not be captured before the run"); if (r.wakeMode === "next-heartbeat") { await deferHookEvent(e.deferHookWake, { text: i, agentId: c, expectedTarget: l, createIfMissing: true, commitGuard: () => { if (!listAgentIds(readRuntimeConfig()).includes(c)) throw new Error("Hook terminal agent was removed before event admission"); } }); return; } enqueueSessionEventForHost(i, { agentId: c, sessionKey: o, source: "hook", expectedTarget: l, createIfMissing: true }).settled.then((e) => { if (e.status !== "completed") n.warn("hook terminal event not delivered", { ...m, ...sanitizeHookLogMetadata({ status: e.status, error: e.error }) }); }); } catch (e) { n.warn("hook terminal event not delivered", { ...m, ...sanitizeHookLogMetadata({ error: formatErrorMessage(e) }) }); } }; const reportHookFailure = async (e) => { p.resolve(logHookRunTerminal({ status: "error", error: String(e) })); try { await announceHookEvent(_ ?? resolveHookEventTarget({ cfg: readRuntimeConfig(), resolvedAgentId: r.effectiveAgentId }), `Hook ${u} (error): ${String(e)}`, "error"); } catch (e) { n.warn("hook terminal event not delivered", { ...m, ...sanitizeHookLogMetadata({ error: formatErrorMessage(e) }) }); } }; let v; try { v = readRuntimeConfig(); } catch (e) { runWithGatewayDetachedWorkContinuation(async () => reportHookFailure(e), "hooks:failure-report"); return createHookAdmissionFailure({ runId: f }); } let y; try { y = await validateHookAgentDeliveryAccount({ cfg: v, value: r }); g.delivery = y.delivery; } catch (e) { return { ok: false, statusCode: 400, error: formatErrorMessage(e), runId: f }; } const b = y.effectiveAgentId; const x = resolveCronAgentSessionKey({ sessionKey: l, agentId: b, mainKey: v.session?.mainKey, cfg: v }); const S = createDeferredCore(); let C = false; let w = false; let T; const settleAdmission = (e) => { if (C) return; C = true; if (T) { clearTimeout(T); T = void 0; } if (e.ok && r.replayKey) c.delete(r.replayKey); S.resolve(e); }; const failAdmission = async (e) => { if (w) return; settleAdmission(createHookAdmissionFailure({ runId: f })); await reportHookFailure(e); }; const E = /* @__PURE__ */ new Error(HOOK_AGENT_START_ADMISSION_TIMEOUT_ERROR); const D = new AbortController(); const settleSuccessfulAdmission = () => { D.signal.throwIfAborted(); settleAdmission({ ok: true, runId: f, completion: p.promise }); }; if (r.admissionMode !== "background") { T = setTimeout(() => { w = true; D.abort(E); settleAdmission(createHookAdmissionFailure({ runId: f, statusCode: 503 })); }, i); T.unref?.(); } runWithGatewayDetachedWorkContinuation(() => s(x, async () => { if (D.signal.aborted) return; try { const e = readRuntimeConfig(); try { await validateHookAgentDeliveryAccount({ cfg: e, value: y }); } catch (e) { settleAdmission({ ok: false, statusCode: 400, error: formatErrorMessage(e), runId: f }); return; } if (D.signal.aborted) return; const n = resolveHookEventTarget({ cfg: e, resolvedAgentId: b }); _ = n; n.expectedTarget = await captureSessionEventTargetForHost(n.agentId, n.eventSessionKey); const { runCronIsolatedAgentTurn: i } = await loadIsolatedAgentModule(); if (D.signal.aborted) return; const s = a ? "gateway.hooks.plugin" : "gateway.hooks.agent"; const runHookIsolatedTurn = async () => await i({ occurrence: await admitEventOccurrence({ cfg: e, job: g, agentId: b, ingressBoundary: s }), cfg: e, deps: t, job: g, trigger: "event", deliveryAttemptFence: null, message: y.message, sessionKey: l, agentId: b, lane: a ? "cron-nested" : "hook-dispatch", executionIdentity: { ingress: a ? { kind: "webhook", boundary: s, state: "present", rawSourceRef: `${a}:${u}` } : { kind: "webhook", boundary: s, state: "present", ...y.mappingId ? { rawSourceRef: y.mappingId } : {} } }, abortSignal: D.signal, onLaneWait: (e) => { if (e?.waiting === false && e.stage === void 0) settleSuccessfulAdmission(); }, onExecutionStarted: settleSuccessfulAdmission }); const c = await o(runHookIsolatedTurn); if (w) return; const d = resolveHookRunSummary(c); if (!C) settleAdmission(c.status === "ok" || c.executionStarted === true ? { ok: true, runId: f, completion: p.promise } : createHookAdmissionFailure({ runId: f, disposition: c.admissionDisposition })); const m = c.status === "ok" ? `Hook ${u}` : `Hook ${u} (${c.status})`; const h = c.status !== "ok" || r.deliver && c.delivered !== true && c.deliveryAttempted !== true; p.resolve(logHookRunTerminal(c)); if (h) await announceHookEvent(n, `${m}: ${d}`.trim(), c.status); } catch (e) { await failAdmission(e); } }), "hooks:agent-dispatch").catch(failAdmission); return await S.promise; }; const d = /* @__PURE__ */ new Map(); const dispatchHookAgentTurn = async (e, t) => { const n = normalizeOptionalString(e.agentId); if (!n) return { ok: false, reason: "agentId is required" }; const r = normalizeHookDispatchSessionKey({ sessionKey: e.sessionKey, targetAgentId: n }); if (r !== e.sessionKey || !r.startsWith("hook:") || r.length <= 5 || /[\s\p{Cc}]/u.test(r)) return { ok: false, reason: "sessionKey must start with hook: and contain no whitespace or control characters" }; if (e.externalContentSource !== "email") return { ok: false, reason: "externalContentSource must be email" }; const run = async () => { const i = await dispatchAgentHook({ name: e.name, agentId: n, effectiveAgentId: n, sessionKey: r, message: e.message, deliver: e.deliver, model: e.model, thinking: e.thinking, timeoutSeconds: e.timeoutSeconds, idempotencyKey: e.idempotencyKey, sessionMode: "isolated", sourcePath: `plugin:${t}`, wakeMode: "now", channel: "last", delivery: e.deliver ? { mode: "announce", channel: "last" } : { mode: "none" }, externalContentSource: "email" }, t); return i.ok ? { ok: true, runId: i.runId } : { ok: false, reason: i.error }; }; const i = normalizeOptionalString(e.idempotencyKey); if (!i) return await run(); const a = Date.now(); for (const [e, t] of d) if (t.createdAt < a - 3e5) d.delete(e); const o = JSON.stringify({ pluginId: t, idempotencyKey: i, name: e.name, agentId: n, sessionKey: r, message: e.message, externalContentSource: e.externalContentSource, deliver: e.deliver, model: e.model, thinking: e.thinking, timeoutSeconds: e.timeoutSeconds }); const s = d.get(o); if (s) return await s.result; const c = run().then((e) => { if (!e.ok) d.delete(o); return e; }, (e) => { d.delete(o); throw e; }); d.set(o, { createdAt: a, result: c }); pruneMapToMaxSize(d, DEDUPE_MAX); return await c; }; return { dispatchWakeHook: u, dispatchAgentHook, dispatchHookAgentTurn }; } /** Creates the HTTP handler used by gateway hook endpoints. */ function createGatewayHooksRequestHandler(e) { const { getHooksConfig: t, bindHost: n, port: r, logHooks: i, getClientIpConfig: a } = e; const { dispatchAgentHook: o, dispatchWakeHook: s } = e.dispatcher ?? createGatewayHookDispatcher(e); return createHooksRequestHandler({ scheduler: e.scheduler, getHooksConfig: t, bindHost: n, port: r, logHooks: i, getClientIpConfig: a, dispatchAgentHook: o, dispatchWakeHook: s }); } //#endregion export { createGatewayHookDispatcher, createGatewayHooksRequestHandler };