openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
776 lines (775 loc) • 26.5 kB
JavaScript
import { c as normalizeOptionalLowercaseString, g as readStringValue, i as normalizeBoundedOptionalString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { h as resolveConfigPathCandidate } from "./paths-DAcAg5aV.mjs";
import { f as setGatewayCredentialEnvKeys } from "./host-env-security-BrTYS4pH.mjs";
import { n as normalizeAgentId, r as normalizeAgentIdStrict } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { D as tryResolveAgentOperationAgentId, z as resolvePersistedSessionStoreOwnerForKey } from "./agent-scope-config-DmXgFGKP.mjs";
import { c as getAuthoredConfigSecretRef, d as hasUnresolvedConfigPath, u as getResolvedConfigEnvSecretRef } from "./resolution-facts-xaIKuREs.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { r as listChannelPlugins } from "./registry-ByqVE5S3.mjs";
import "./plugins-BoMiRtiY.mjs";
import { a as readJsonBodyWithLimit, t as DEFAULT_WEBHOOK_MAX_BODY_BYTES } from "./http-body-B9w7rzPz.mjs";
import { _ as resolveGmailHookMaxBytes } from "./gmail-B-kIMiKm.mjs";
import { t as resolveFunctionModuleExport } from "./module-loader-C5Ij3gRJ.mjs";
import { t as resolveAllowedAgentIds } from "./hooks-policy-hjbwYLwU.mjs";
import fs from "node:fs";
import { pathToFileURL } from "node:url";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { readFile as readFile$1 } from "node:fs/promises";
//#region src/gateway/hooks-mapping.ts
const HOOK_MAPPING_FAN_OUT_MAX_ITEMS = 200;
const GMAIL_HOOK_BATCH_MAX_MESSAGES = 100;
const GMAIL_HOOK_JSON_ESCAPING_FACTOR = 3;
const GMAIL_HOOK_PER_MESSAGE_OVERHEAD_BYTES = 8192;
const GMAIL_HOOK_MAX_BODY_BYTES_CEILING = 33554432;
function resolveGmailHookMaxBodyBytes(e) {
return Math.min(GMAIL_HOOK_MAX_BODY_BYTES_CEILING, GMAIL_HOOK_BATCH_MAX_MESSAGES * (e * GMAIL_HOOK_JSON_ESCAPING_FACTOR + GMAIL_HOOK_PER_MESSAGE_OVERHEAD_BYTES));
}
const hookPresetMappings = { gmail: [{
id: "gmail",
match: { path: "gmail" },
action: "agent",
wakeMode: "now",
name: "Gmail",
forEach: "messages",
sessionKey: "hook:gmail:{{messages[0].id}}",
messageTemplate: "New email from {{messages[0].from}}\nSubject: {{messages[0].subject}}\n{{messages[0].snippet}}\n{{messages[0].body}}"
}] };
const transformCache = /* @__PURE__ */ new Map();
let transformCacheBustVersion = 0;
function commitHookTransformMappingReload() {
transformCache.clear();
transformCacheBustVersion += 1;
}
/** Resolve configured hook mappings plus preset mappings into normalized matcher entries. */
function resolveHookMappings(e) {
const t = e?.presets ?? [];
const n = e?.gmail?.allowUnsafeExternalContent;
const r = [];
if (e?.mappings) r.push(...e.mappings);
for (const e of t) {
const t = hookPresetMappings[e];
if (!t) continue;
if (e === "gmail" && typeof n === "boolean") {
r.push(...t.map((e) => ({
...e,
allowUnsafeExternalContent: n
})));
continue;
}
r.push(...t);
}
if (r.length === 0) return [];
const i = path.resolve(path.dirname(resolveConfigPathCandidate()));
const a = resolveOptionalContainedPath(path.join(i, "hooks", "transforms"), e?.transformsDir, "Hook transformsDir");
const o = resolveGmailHookMaxBodyBytes(resolveGmailHookMaxBytes(e?.gmail?.maxBytes));
return r.map((e, t) => {
const n = normalizeHookMapping(e, t, a);
if (n.matchPath === "gmail") n.maxBodyBytes = o;
return n;
});
}
async function applyHookMappings(e, t) {
if (e.length === 0) return null;
for (const n of e) {
if (!mappingMatches(n, t)) continue;
if (n.forEach) return await applyFanOutMapping(n, n.forEach, t);
const e = await applyMappingToContext(n, t);
if (!e.ok) return e;
return {
ok: true,
actions: e.action ? [e.action] : [],
fanout: false,
dropped: 0
};
}
return null;
}
async function applyMappingToContext(e, t) {
const n = buildActionFromMapping(e, t);
let r = null;
if (e.transform) {
r = await (await loadTransform(e.transform))(t);
if (r === null) return {
ok: true,
action: null
};
}
return mergeAction(n, r);
}
async function applyFanOutMapping(e, t, n) {
const r = n.payload[t];
const i = Array.isArray(r) ? r : [];
const a = i.slice(0, 200);
const o = [];
for (const r of a) {
const i = await applyMappingToContext(e, {
...n,
payload: {
...n.payload,
[t]: [r]
}
});
if (!i.ok) return i;
if (i.action) o.push(i.action);
}
return {
ok: true,
actions: o,
fanout: true,
dropped: i.length - a.length
};
}
function normalizeHookMapping(e, t, n) {
const r = normalizeOptionalString(e.id) || `mapping-${t + 1}`;
const i = normalizeHookMatchPath(e.match?.path);
const a = e.match?.source?.trim();
const o = e.action ?? "agent";
const s = e.wakeMode ?? "now";
const c = normalizeForEachKey(e.forEach);
const l = e.transform ? {
modulePath: resolveContainedPath(n, e.transform.module, "Hook transform"),
exportName: normalizeOptionalString(e.transform.export)
} : void 0;
return {
id: r,
matchPath: i,
matchSource: a,
action: o,
wakeMode: s,
forEach: c,
name: e.name,
agentId: normalizeOptionalString(e.agentId),
sessionKey: e.sessionKey,
sessionMode: e.sessionMode,
messageTemplate: e.messageTemplate,
textTemplate: e.textTemplate,
deliver: e.deliver,
allowUnsafeExternalContent: e.allowUnsafeExternalContent,
channel: e.channel,
to: e.to,
model: e.model,
thinking: e.thinking,
timeoutSeconds: e.timeoutSeconds,
transform: l
};
}
function normalizeForEachKey(e) {
const t = normalizeOptionalString(e);
if (!t) return;
if (/[.[\]]/.test(t) || isBlockedObjectKey(t)) throw new Error(`Hook mapping forEach must be a top-level payload key: ${e}`);
return t;
}
function mappingMatches(e, t) {
return (!e.matchPath || e.matchPath === normalizeHookMatchPath(t.path)) && (!e.matchSource || e.matchSource === readStringValue(t.payload.source));
}
function buildActionFromMapping(e, t) {
if (e.action === "wake") {
const n = renderTemplate(e.textTemplate ?? "", t);
return {
kind: "wake",
mappingId: e.id,
text: n,
mode: e.wakeMode ?? "now",
agentId: e.agentId,
sessionKey: renderOptional(e.sessionKey, t),
sessionKeySource: getSessionKeyTemplateSource(e.sessionKey)
};
}
const n = renderTemplate(e.messageTemplate ?? "", t);
return {
kind: "agent",
mappingId: e.id,
message: n,
name: renderOptional(e.name, t),
agentId: e.agentId,
wakeMode: e.wakeMode ?? "now",
sessionKey: renderOptional(e.sessionKey, t),
sessionKeySource: getSessionKeyTemplateSource(e.sessionKey),
sessionMode: e.sessionMode ?? "isolated",
deliver: e.deliver,
allowUnsafeExternalContent: e.allowUnsafeExternalContent,
channel: e.channel,
to: renderOptional(e.to, t),
model: renderOptional(e.model, t),
thinking: renderOptional(e.thinking, t),
timeoutSeconds: e.timeoutSeconds
};
}
function mergeAction(e, t) {
if (!t) return validateAction(e);
if ((t.kind ?? e.kind) === "wake") {
const n = e.kind === "wake" ? e : void 0;
const r = typeof t.text === "string" ? t.text : n?.text ?? "";
const i = t.mode === "now" || t.mode === "next-heartbeat" ? t.mode : n?.mode ?? "now";
return validateAction({
kind: "wake",
mappingId: e.mappingId,
text: r,
mode: i,
agentId: t.agentId ?? n?.agentId,
sessionKey: t.sessionKey ?? n?.sessionKey,
sessionKeySource: resolveMergedSessionKeySource(n, t)
});
}
const n = e.kind === "agent" ? e : void 0;
const r = typeof t.message === "string" ? t.message : n?.message ?? "";
const i = t.wakeMode === "now" || t.wakeMode === "next-heartbeat" ? t.wakeMode : n?.wakeMode ?? "now";
return validateAction({
kind: "agent",
mappingId: e.mappingId,
message: r,
wakeMode: i,
name: t.name ?? n?.name,
agentId: t.agentId ?? n?.agentId,
sessionKey: t.sessionKey ?? n?.sessionKey,
sessionKeySource: resolveMergedSessionKeySource(n, t),
sessionMode: t.sessionMode ?? n?.sessionMode ?? "isolated",
deliver: typeof t.deliver === "boolean" ? t.deliver : n?.deliver,
allowUnsafeExternalContent: typeof t.allowUnsafeExternalContent === "boolean" ? t.allowUnsafeExternalContent : n?.allowUnsafeExternalContent,
channel: t.channel ?? n?.channel,
to: t.to ?? n?.to,
model: t.model ?? n?.model,
thinking: t.thinking ?? n?.thinking,
timeoutSeconds: t.timeoutSeconds ?? n?.timeoutSeconds
});
}
function validateAction(e) {
if (e.sessionKeySource === "templated" && !e.sessionKey?.trim()) return {
ok: false,
error: "hook mapping sessionKey template rendered empty"
};
if (e.kind === "wake") {
if (!e.text?.trim()) return {
ok: false,
error: "hook mapping requires text"
};
if (e.mode === "next-heartbeat" && e.sessionKey) return {
ok: false,
error: "hook mapping sessionKey requires wakeMode=now"
};
return {
ok: true,
action: e
};
}
if (!e.message?.trim()) return {
ok: false,
error: "hook mapping requires message"
};
if (e.sessionMode !== "isolated" && e.sessionMode !== "persistent") return {
ok: false,
error: "hook mapping sessionMode must be isolated or persistent"
};
return {
ok: true,
action: e
};
}
function getSessionKeyTemplateSource(e) {
const t = normalizeOptionalString(e);
if (!t) return;
return hasHookTemplateExpressions(t) ? "templated" : "static";
}
function resolveMergedSessionKeySource(e, t) {
if (typeof t.sessionKey === "string") {
if (!normalizeOptionalString(t.sessionKey)) return;
return t.sessionKeySource === "static" ? "static" : "templated";
}
return e?.sessionKeySource;
}
function hasHookTemplateExpressions(e) {
return /\{\{\s*[^}]+\s*\}\}/.test(e);
}
async function loadTransform(e) {
const t = `${e.modulePath}::${e.exportName ?? "default"}`;
const n = transformCache.get(t);
if (n) return n;
const r = transformCacheBustVersion;
const i = createHash("sha256").update(await readFile$1(e.modulePath)).digest("hex");
const a = await import(`${pathToFileURL(e.modulePath).href}?v=${i}`);
const o = resolveFunctionModuleExport({
mod: a,
exportName: e.exportName,
fallbackExportNames: ["default", "transform"]
});
if (!o) throw new Error("hook transform module must export a function");
if (r === transformCacheBustVersion) transformCache.set(t, o);
return o;
}
function safeRealpathSync(e) {
try {
const t = fs.realpathSync.native;
return t ? t(e) : fs.realpathSync(e);
} catch {
return null;
}
}
function resolveExistingAncestor(e) {
let t = path.resolve(e);
while (true) {
if (fs.existsSync(t)) return t;
const e = path.dirname(t);
if (e === t) return null;
t = e;
}
}
function resolveContainedPath(e, t, n) {
const r = path.resolve(e);
const i = t?.trim();
if (!i) throw new Error(`${n} module path is required`);
const a = path.isAbsolute(i) ? path.resolve(i) : path.resolve(r, i);
if (!isPathInside(r, a)) throw new Error(`${n} module path must be within ${r}: ${t}`);
const o = safeRealpathSync(r);
const s = resolveExistingAncestor(a);
const c = s ? safeRealpathSync(s) : null;
if (o && c && !isPathInside(o, c)) throw new Error(`${n} module path must be within ${r}: ${t}`);
return a;
}
function resolveOptionalContainedPath(e, t, n) {
const r = t?.trim();
if (!r) return path.resolve(e);
return resolveContainedPath(e, r, n);
}
function normalizeHookMatchPath(e) {
return normalizeOptionalString(e)?.replace(/^\/+/, "").replace(/\/+$/, "");
}
function renderOptional(e, t) {
if (!e) return;
const n = renderTemplate(e, t).trim();
return n ? n : void 0;
}
function renderTemplate(e, t) {
return e.replace(/\{\{\s*([^}]+)\s*\}\}/g, (e, n) => {
const r = resolveTemplateExpr(n.trim(), t);
if (r === void 0 || r === null) return "";
if (typeof r === "string") return r;
if (typeof r === "number" || typeof r === "boolean") return String(r);
return JSON.stringify(r);
});
}
function resolveTemplateExpr(e, t) {
if (e === "path") return t.path;
if (e === "now") return (/* @__PURE__ */ new Date()).toISOString();
if (e.startsWith("headers.")) return getByPath(t.headers, e.slice(8));
if (e.startsWith("query.")) return getByPath(Object.fromEntries(t.url.searchParams.entries()), e.slice(6));
if (e.startsWith("payload.")) return getByPath(t.payload, e.slice(8));
return getByPath(t.payload, e);
}
function getByPath(e, t) {
if (!t) return;
const n = [];
for (const e of t.matchAll(/([^.[\]]+)|(\[(\d+)\])/g)) if (e[1]) n.push(e[1]);
else if (e[3]) n.push(Number(e[3]));
let r = e;
for (const e of n) {
if (r === null || r === void 0) return;
if (typeof e === "number") {
if (!Array.isArray(r)) return;
r = r[e];
continue;
}
if (isBlockedObjectKey(e)) return;
if (typeof r !== "object") return;
r = r[e];
}
return r;
}
//#endregion
//#region src/gateway/hooks.ts
const DEFAULT_HOOKS_PATH = "/hooks";
const DEFAULT_HOOKS_MAX_BODY_BYTES = DEFAULT_WEBHOOK_MAX_BODY_BYTES;
const MAX_HOOK_IDEMPOTENCY_KEY_LENGTH = 256;
var UnresolvedHooksTokenError = class extends Error {
constructor() {
super("hooks.token has an unresolved environment reference; supply the configured secret or disable hooks");
this.name = "UnresolvedHooksTokenError";
}
};
/** Keep the active hook token's env source out of host exec children. */
function publishHooksTokenEnvKey(e) {
setGatewayCredentialEnvKeys("hooks.token", e?.tokenEnvKey ? [e.tokenEnvKey] : []);
}
function resolveHooksConfig(e) {
if (e.hooks?.enabled !== true) return null;
const t = normalizeOptionalString(e.hooks?.token);
if (!t) throw new Error("hooks.enabled requires hooks.token");
if (hasUnresolvedConfigPath(e, "hooks.token") || getAuthoredConfigSecretRef(e, "hooks.token")) throw new UnresolvedHooksTokenError();
const n = normalizeOptionalString(e.hooks?.path) || DEFAULT_HOOKS_PATH;
const r = n.startsWith("/") ? n : `/${n}`;
const i = r.length > 1 ? r.replace(/\/+$/, "") : r;
if (i === "/") throw new Error("hooks.path may not be '/'");
const a = resolveHookMappings(e.hooks);
const o = tryResolveAgentOperationAgentId(e);
const s = e.session?.scope === "global" ? resolvePersistedSessionStoreOwnerForKey(e, "global") : { kind: "none" };
const c = new Set(listAgentIds(e));
if (o) c.add(o);
const l = resolveAllowedAgentIds(e.hooks?.allowedAgentIds);
const u = normalizeOptionalString(e.hooks?.defaultSessionKey);
const d = resolveAllowedSessionKeyPrefixes(e.hooks?.allowedSessionKeyPrefixes);
if (u && d && !isSessionKeyAllowedByPrefix(u, d)) throw new Error("hooks.defaultSessionKey must match hooks.allowedSessionKeyPrefixes");
if (!u && d && !isSessionKeyAllowedByPrefix("hook:example", d)) throw new Error("hooks.allowedSessionKeyPrefixes must include 'hook:' when hooks.defaultSessionKey is unset");
if (hasEffectiveTemplatedHookSessionKeyMapping(a) && !d) throw new Error("hooks.allowedSessionKeyPrefixes is required when a hook mapping sessionKey uses templates, even if hooks.allowRequestSessionKey=true");
const f = getResolvedConfigEnvSecretRef(e, "hooks.token")?.id;
return {
basePath: i,
token: t,
...f ? { tokenEnvKey: f } : {},
maxBodyBytes: DEFAULT_HOOKS_MAX_BODY_BYTES,
maxBodyBytesByPath: resolveHookBodyLimitsByPath(a),
mappings: a,
agentPolicy: {
defaultAgentId: o,
globalSessionStoreOwner: s,
knownAgentIds: c,
allowedAgentIds: l
},
sessionPolicy: {
defaultSessionKey: u,
allowRequestSessionKey: e.hooks?.allowRequestSessionKey === true,
allowedSessionKeyPrefixes: d
}
};
}
function resolveHookBodyLimitsByPath(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
if (!n.matchPath || !n.maxBodyBytes) continue;
const e = t.get(n.matchPath) ?? DEFAULT_HOOKS_MAX_BODY_BYTES;
t.set(n.matchPath, Math.max(e, n.maxBodyBytes));
}
return t;
}
/** Resolve the body byte bound for one hook sub-path (mapping-derived, floored at the default). */
function resolveHookPathBodyLimit(e, t) {
const n = normalizeHookMatchPath(t);
if (!n) return e.maxBodyBytes;
return e.maxBodyBytesByPath.get(n) ?? e.maxBodyBytes;
}
function resolveAllowedSessionKeyPrefixes(e) {
if (!Array.isArray(e)) return;
const t = [...new Set(e.map(normalizeOptionalLowercaseString).filter((e) => e !== void 0))];
return t.length > 0 ? t : void 0;
}
function isSessionKeyAllowedByPrefix(e, t) {
const n = normalizeLowercaseStringOrEmpty(e);
if (!n) return false;
return t.some((e) => n.startsWith(e));
}
/** Extract the hook bearer token from Authorization or x-openclaw-token headers. */
function extractHookToken(e) {
const t = normalizeOptionalString(e.headers.authorization) ?? "";
if (normalizeLowercaseStringOrEmpty(t).startsWith("bearer ")) {
const e = t.slice(7).trim();
if (e) return e;
}
return normalizeOptionalString(e.headers["x-openclaw-token"]);
}
async function readJsonBody(e, t, n) {
const r = await readJsonBodyWithLimit(e, {
maxBytes: t,
timeoutMs: n,
emptyObjectOnEmpty: true,
destroyOnLimit: false
});
if (r.ok) return r;
if (r.code === "PAYLOAD_TOO_LARGE") return {
ok: false,
error: "payload too large"
};
if (r.code === "REQUEST_BODY_TIMEOUT") return {
ok: false,
error: "request body timeout"
};
return {
ok: false,
error: r.error
};
}
function normalizeHookHeaders(e) {
const t = {};
for (const [n, r] of Object.entries(e.headers)) {
const e = normalizeLowercaseStringOrEmpty(n);
if (typeof r === "string") t[e] = r;
else if (Array.isArray(r) && r.length > 0) t[e] = r.join(", ");
}
return t;
}
function normalizeHookPayloadAgentId(e) {
if (e === void 0) return {
ok: true,
value: void 0
};
const t = normalizeOptionalString(e);
return t ? {
ok: true,
value: t
} : {
ok: false,
error: "agentId must be a non-empty string"
};
}
function normalizeWakePayload(e) {
const t = normalizeOptionalString(e.text) ?? "";
if (!t) return {
ok: false,
error: "text required"
};
const n = e.mode === "next-heartbeat" ? "next-heartbeat" : "now";
const r = normalizeHookPayloadAgentId(e.agentId);
if (!r.ok) return r;
const i = normalizeOptionalString(e.sessionKey);
if (e.sessionKey !== void 0 && !i) return {
ok: false,
error: "sessionKey must be a non-empty string"
};
if (n === "next-heartbeat" && i) return {
ok: false,
error: "sessionKey requires mode=now"
};
return {
ok: true,
value: {
text: t,
mode: n,
...r.value ? { agentId: r.value } : {},
...i ? { sessionKey: i } : {}
}
};
}
const listHookChannelValues = () => ["last", ...listChannelPlugins().map((e) => e.id)];
const getHookChannelError = () => `channel must be ${listHookChannelValues().join("|")}`;
/** Resolve a raw hook channel value, defaulting omitted values to `last`. */
function resolveHookChannel(e) {
if (e === void 0) return "last";
if (typeof e !== "string") return null;
const t = normalizeMessageChannel(e);
if (!t || !listHookChannelValues().includes(t)) return null;
return t;
}
function resolveHookDeliver(e) {
return e !== false;
}
/** Normalize webhook delivery intent before any isolated cron work is scheduled. */
function normalizeHookAgentDelivery(e) {
const t = resolveHookDeliver(e.deliver);
if (!t) return {
ok: true,
value: {
deliver: t,
channel: "last",
to: void 0,
accountId: void 0,
delivery: { mode: "none" }
}
};
const n = normalizeOptionalString(e.to);
const r = normalizeOptionalString(e.accountId);
const i = resolveHookChannel(e.channel);
if (!i) return {
ok: false,
error: getHookChannelError()
};
const a = e.channel !== void 0;
const o = e.to !== void 0;
const s = e.accountId !== void 0;
let c = { mode: "none" };
if (a || o || s) {
if (o && !n) return {
ok: false,
error: "to must be a non-empty string for hook delivery"
};
if (s && !r) return {
ok: false,
error: "accountId must be a non-empty string for hook delivery"
};
if (s && (!a || !n)) return {
ok: false,
error: "accountId requires channel and to for hook delivery"
};
if (!a || !n) return {
ok: false,
error: "channel and to must be set together for hook delivery"
};
if (i === "last") return {
ok: false,
error: "channel must name a concrete channel for hook delivery"
};
c = {
mode: "announce",
channel: i,
to: n,
...r ? { accountId: r } : {}
};
}
return {
ok: true,
value: {
deliver: t,
channel: i,
to: n,
accountId: r,
delivery: c
}
};
}
function resolveHookIdempotencyKey(e) {
return normalizeBoundedOptionalString(e.headers?.["idempotency-key"], MAX_HOOK_IDEMPOTENCY_KEY_LENGTH) || normalizeBoundedOptionalString(e.headers?.["x-openclaw-idempotency-key"], MAX_HOOK_IDEMPOTENCY_KEY_LENGTH) || normalizeBoundedOptionalString(e.payload.idempotencyKey, MAX_HOOK_IDEMPOTENCY_KEY_LENGTH);
}
/** Resolve request or config-mapped agent selection against durable session ownership. */
function resolveEffectiveHookTargetAgentId(e, t, n) {
const r = normalizeOptionalString(t);
let i;
if (n === "mapping" && r) {
const t = normalizeAgentId(r);
i = e.agentPolicy.knownAgentIds.has(t) ? t : e.agentPolicy.defaultAgentId;
} else if (n === "request" && r) {
const t = normalizeAgentIdStrict(r);
const n = t.ok ? t.value : r;
if (!t.ok || !e.agentPolicy.knownAgentIds.has(n)) return {
ok: false,
code: "unknown-agent",
agentId: n,
error: `unknown agentId "${n}"`
};
i = n;
}
const a = i ?? e.agentPolicy.defaultAgentId;
const o = e.agentPolicy.globalSessionStoreOwner;
if (o.kind === "retired") return {
ok: false,
code: "owner-retired",
ownerAgentId: o.agentId,
error: `global session-store owner "${o.agentId}" is no longer configured; restore that agent or update agents.defaults.sessionStore.agentId`
};
if (o.kind === "configured" && i && i !== o.agentId) return {
ok: false,
code: "owner-conflict",
agentId: i,
ownerAgentId: o.agentId,
error: `agentId "${i}" conflicts with global session-store owner "${o.agentId}"; use agentId "${o.agentId}" or update agents.defaults.sessionStore.agentId`
};
const s = o.kind === "configured" ? o.agentId : a;
if (!s) return {
ok: false,
code: "agent-required",
error: getHookAgentSelectionError()
};
return {
ok: true,
...i ? { selectedAgentId: i } : {},
effectiveAgentId: s
};
}
function isHookAgentAllowed(e, t) {
const n = e.agentPolicy.allowedAgentIds;
if (n === void 0) return true;
return n.has(t);
}
const getHookAgentPolicyError = () => "agentId is not allowed by hooks.allowedAgentIds";
const getHookAgentSelectionError = () => "agentId is required when multiple agents are configured";
const getHookSessionKeyRequestPolicyError = () => "sessionKey is disabled for externally supplied hook payload values; set hooks.allowRequestSessionKey=true to enable";
const getHookSessionKeyPrefixError = (e) => `sessionKey must start with one of: ${e.join(", ")}`;
function resolveHookSessionKey(e) {
const t = normalizeOptionalString(e.sessionKey);
if (t) {
if ((e.source === "request" || e.source === "mapping-templated") && !e.hooksConfig.sessionPolicy.allowRequestSessionKey) return {
ok: false,
error: getHookSessionKeyRequestPolicyError()
};
} else {
const t = e.hooksConfig.sessionPolicy.defaultSessionKey;
if (t) return {
ok: true,
value: t
};
}
const n = t ?? `hook:${(e.idFactory ?? randomUUID)()}`;
const r = e.hooksConfig.sessionPolicy.allowedSessionKeyPrefixes;
if (r && !isSessionKeyAllowedByPrefix(n, r)) return {
ok: false,
error: getHookSessionKeyPrefixError(r)
};
return {
ok: true,
value: n
};
}
function hasEffectiveTemplatedHookSessionKeyMapping(e) {
const t = [];
for (const n of e) {
if (t.some((e) => (!e.matchPath || e.matchPath === n.matchPath) && (!e.matchSource || e.matchSource === n.matchSource))) continue;
t.push(n);
if (typeof n.sessionKey === "string" && hasHookTemplateExpressions(n.sessionKey)) return true;
}
return false;
}
/** Re-scope agent-prefixed hook session keys to the selected target agent. */
function normalizeHookDispatchSessionKey(e) {
const t = normalizeOptionalString(e.sessionKey) ?? "";
if (!t || !e.targetAgentId) return t;
const n = parseAgentSessionKey(t);
if (!n) return t;
return `agent:${normalizeAgentId(e.targetAgentId)}:${n.rest}`;
}
function normalizeAgentPayload(e) {
const t = normalizeOptionalString(e.message) ?? "";
if (!t) return {
ok: false,
error: "message required"
};
const n = normalizeOptionalString(e.name) ?? "Hook";
const r = normalizeHookPayloadAgentId(e.agentId);
if (!r.ok) return r;
const i = normalizeBoundedOptionalString(e.idempotencyKey, MAX_HOOK_IDEMPOTENCY_KEY_LENGTH);
const a = e.wakeMode === "next-heartbeat" ? "next-heartbeat" : "now";
const o = normalizeOptionalString(e.sessionKey);
if (e.sessionKey !== void 0 && !o) return {
ok: false,
error: "sessionKey must be a non-empty string"
};
const s = e.sessionMode;
if (s !== void 0 && s !== "isolated" && s !== "persistent") return {
ok: false,
error: "sessionMode must be isolated or persistent"
};
const c = s ?? "isolated";
const l = normalizeHookAgentDelivery({
deliver: e.deliver,
channel: e.channel,
to: e.to,
accountId: e.accountId
});
if (!l.ok) return l;
const u = e.model;
const d = normalizeOptionalString(u);
if (u !== void 0 && !d) return {
ok: false,
error: "model required"
};
const f = normalizeOptionalString(e.thinking);
const p = e.timeoutSeconds;
const m = typeof p === "number" && Number.isFinite(p) && p > 0 ? Math.floor(p) : void 0;
return {
ok: true,
value: {
message: t,
name: n,
agentId: r.value,
idempotencyKey: i,
wakeMode: a,
sessionKey: o,
sessionMode: c,
...l.value,
model: d,
thinking: f,
timeoutSeconds: m
}
};
}
//#endregion
export { commitHookTransformMappingReload as S, resolveHookIdempotencyKey as _, getHookSessionKeyPrefixError as a, resolveHooksConfig as b, normalizeAgentPayload as c, normalizeWakePayload as d, publishHooksTokenEnvKey as f, resolveHookDeliver as g, resolveHookChannel as h, getHookChannelError as i, normalizeHookDispatchSessionKey as l, resolveEffectiveHookTargetAgentId as m, extractHookToken as n, isHookAgentAllowed as o, readJsonBody as p, getHookAgentPolicyError as r, isSessionKeyAllowedByPrefix as s, UnresolvedHooksTokenError as t, normalizeHookHeaders as u, resolveHookPathBodyLimit as v, applyHookMappings as x, resolveHookSessionKey as y };