openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
109 lines (108 loc) • 4.67 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { a as openRootFile } from "./boundary-file-read-BfaFLDqt.mjs";
import { s as safeRealpathSync } from "./boundary-path-C2gXEiXe.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { l as unregisterInternalHook, o as registerInternalHook, s as setInternalHooksEnabled } from "./internal-hooks-D6nf-Q3g.mjs";
import { t as resolveFunctionModuleExport } from "./module-loader-C5Ij3gRJ.mjs";
import { t as isKnownInternalHookEventKey } from "./internal-hook-types-B0QGfnTY.mjs";
import { n as isHookNameSelected, r as resolveInternalHookSelection, t as isHookLoadable } from "./configured-hsNkp5Xq.mjs";
import fs from "node:fs";
import { pathToFileURL } from "node:url";
//#region src/hooks/loader.ts
function buildImportUrl(e, t) {
const n = pathToFileURL(e).href;
if (t === "openclaw-bundled") return n;
try {
const { ctimeMs: t, mtimeMs: r, size: i } = fs.statSync(e);
return `${n}?t=${r}&c=${t}&s=${i}`;
} catch {
return `${n}?t=${Date.now()}`;
}
}
const log = createSubsystemLogger("hooks:loader");
const hookOwner = resolveGlobalSingleton(Symbol.for("openclaw.loadedInternalHookRegistrations"), () => ({ generation: { registrations: [] } }), () => resetLoadedInternalHooks());
function resetLoadedInternalHooks() {
for (const { event: e, handler: t } of hookOwner.generation.registrations) unregisterInternalHook(e, t);
hookOwner.generation = { registrations: [] };
}
/** Imports candidate handlers without publishing registrations or changing the dispatch gate. */
async function prepareInternalHooks(e, t, n) {
const r = e.hooks?.internal?.enabled !== false;
const i = hookOwner.generation;
const a = [];
let o = 0;
const s = n?.selection ?? await resolveInternalHookSelection(e);
const shouldLoadHook = (t) => isHookLoadable({
entry: t,
config: e,
names: s.names
});
const c = s.configured ? (await import("./workspace-DiuLRmfJ.mjs")).prepareWorkspaceHookEntries(t, {
config: e,
...n?.failureMode !== "best-effort" ? {
requireValidHook: shouldLoadHook,
previousSources: i.discovery?.sources.filter((e) => !isHookNameSelected(i.discovery?.declaredNames, e) || isHookNameSelected(s.declaredNames, e))
} : {}
}) : {
entries: [],
sources: []
};
for (const e of c.entries) {
if (!shouldLoadHook(e)) continue;
try {
const t = safeRealpathSync(e.hook.baseDir);
if (!t) throw new Error(`Hook base directory is no longer readable: ${e.hook.baseDir}`);
const n = await openRootFile({
absolutePath: e.hook.handlerPath,
rootPath: t,
boundaryLabel: "hook directory"
});
if (!n.ok) throw new Error(`Handler path fails boundary checks: ${e.hook.handlerPath}`);
const r = n.path;
fs.closeSync(n.fd);
if (e.hook.source === "openclaw-workspace" || e.hook.source === "openclaw-managed") log.warn(`Loading ${e.hook.source.slice(9)} hook code into the gateway process. Hooks are trusted local code.`);
const i = await import(buildImportUrl(r, e.hook.source));
const s = e.metadata?.export ?? "default";
const c = resolveFunctionModuleExport({
mod: i,
exportName: s
});
if (!c) throw new Error(`Handler '${s}' is not a function`);
const l = e.metadata?.events ?? [];
if (l.length === 0) throw new Error("Hook has no events defined in metadata");
const u = l.filter((e) => !isKnownInternalHookEventKey(e));
if (u.length > 0) log.warn(`Hook '${sanitizeForLog(e.hook.name)}' subscribes to event${u.length === 1 ? "" : "s"} ${u.map((e) => sanitizeForLog(e)).join(", ")} not emitted by OpenClaw core — likely a typo; unless a plugin emits it, the hook never fires. Known events: https://docs.openclaw.ai/automation/hooks`);
a.push(...l.map((e) => ({
event: e,
handler: c
})));
o++;
} catch (t) {
const r = `Failed to load hook ${sanitizeForLog(e.hook.name)}: ${sanitizeForLog(formatErrorMessage(t))}`;
if (n?.failureMode !== "best-effort") throw new Error(r, { cause: t });
log.error(r);
}
}
return {
loadedCount: o,
commit({ initial: e = false } = {}) {
if (e && (i !== hookOwner.generation || i.committed)) return false;
resetLoadedInternalHooks();
for (const { event: e, handler: t } of a) registerInternalHook(e, t);
hookOwner.generation = {
registrations: a,
discovery: {
sources: c.sources,
declaredNames: s.declaredNames
},
committed: true
};
setInternalHooksEnabled(r);
return true;
}
};
}
//#endregion
export { prepareInternalHooks };