openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,177 lines (1,176 loc) • 44.6 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { R as resolveTimerTimeoutMs, d as asPositiveFiniteNumber, f as asPositiveInteger, h as clampPositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { n as estimateStringChars, t as CHARS_PER_TOKEN_ESTIMATE } from "./cjk-chars-CgnWl5qA.mjs";
import { m as normalizeTrimmedStringList, r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { l as trackAsyncWork } from "./async-work-scope-BXagjUap.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs";
import { t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import { l as getPluginValueInstance, m as runPluginCleanup } from "./plugin-instance-scope-oezVdCr2.mjs";
import { n as projectModelContextMessages } from "./model-context-message-DOWMZ3wz.mjs";
import { c as normalizeDeliveryContext } from "./delivery-context.shared-CRlipPTj.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { c as normalizeToolPolicyName, i as expandToolGroups, l as readToolAllowlistIntersection, s as normalizeToolList, t as attachToolAllowlistIntersection } from "./tool-policy-shared-BHvBopvF.mjs";
import { r as createToolPolicyMatcher } from "./tool-policy-match-DzwVnbV4.mjs";
import { o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs";
import { n as isOwnedTranscriptPayload } from "./transcript-json-Cy82tIe1.mjs";
import { n as recordRuntimeActionDecision } from "./runtime-action-decision-B14EMX8j.mjs";
import { i as finalizeGroupThreadToolReply } from "./group-thread-context-DFimpu_J.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { t as isPluginReloadingError } from "./plugin-replacement-retry-cJFu4d7w.mjs";
import { r as recordReplyPayloadMediaSelectionChange, t as collectReplyMediaEntries } from "./reply-media-entries-BE-R1jqq.mjs";
import { i as isPluginHookReplyDispatchKind, t as PLUGIN_HOOK_METADATA } from "./hook-types-CLw-HaZh.mjs";
import { i as pluginToolMatcherCoversTool, t as createPluginToolMatcherScope } from "./tool-hook-matcher-DlUmH-ng.mjs";
import { createHash, randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/hooks/fire-and-forget.ts
const DEFAULT_MAX_CONCURRENT_FIRE_AND_FORGET_HOOKS = 16;
const DEFAULT_MAX_QUEUED_FIRE_AND_FORGET_HOOKS = 256;
const DEFAULT_FIRE_AND_FORGET_HOOK_TIMEOUT_MS = 2e3;
const MAX_HOOK_LOG_MESSAGE_LENGTH = 500;
const getFireAndForgetHookState = () => resolveGlobalSingleton(Symbol.for("openclaw.fireAndForgetHookState"), () => ({
active: 0,
queue: []
}));
/** Format hook errors as bounded single-line log messages with secrets redacted upstream. */
function formatHookErrorForLog(e) {
const t = formatErrorMessage(e).replace(/\p{Cc}/gu, (e) => e.charCodeAt(0) <= 127 ? " " : e).replace(/\s+/g, " ").trim();
return truncateUtf16Safe(t || "unknown error", MAX_HOOK_LOG_MESSAGE_LENGTH);
}
function fireAndForgetHook(e, t, n = logVerbose) {
e.catch((e) => {
n(`${t}: ${formatHookErrorForLog(e)}`);
});
}
function runFireAndForgetHookJob(e, { task: t, ...n }, r) {
e.active += 1;
let i = false;
const a = setTimeout(() => {
i = true;
n.logger(`${n.label}: timed out after ${n.timeoutMs}ms`);
}, n.timeoutMs);
Promise.resolve().then(t).catch((e) => {
if (!i) n.logger(`${n.label}: ${formatHookErrorForLog(e)}`);
}).finally(() => {
clearTimeout(a);
e.active -= 1;
drainFireAndForgetHookQueue(e, r);
});
}
function drainFireAndForgetHookQueue(e, t) {
while (e.active < t) {
const n = e.queue.shift();
if (!n) return;
runFireAndForgetHookJob(e, n, t);
}
}
/** Queue a fire-and-forget hook with bounded concurrency, queue depth, and timeout logs. */
function fireAndForgetBoundedHook(e, t, n = logVerbose, r = {}) {
const i = getFireAndForgetHookState();
const a = asPositiveInteger(r.maxConcurrency) ?? DEFAULT_MAX_CONCURRENT_FIRE_AND_FORGET_HOOKS;
const o = asPositiveInteger(r.maxQueue) ?? DEFAULT_MAX_QUEUED_FIRE_AND_FORGET_HOOKS;
const s = resolveTimerTimeoutMs(asPositiveInteger(r.timeoutMs) ?? DEFAULT_FIRE_AND_FORGET_HOOK_TIMEOUT_MS, DEFAULT_FIRE_AND_FORGET_HOOK_TIMEOUT_MS);
if (i.active >= a && i.queue.length >= o) {
n(`${t}: queue full; dropping hook`);
return;
}
i.queue.push({
task: e,
label: t,
logger: n,
timeoutMs: s
});
drainFireAndForgetHookQueue(i, a);
}
//#endregion
//#region src/shared/text/join-segments.ts
/** Concatenates two optional text blocks, preserving the right block's explicit empty string. */
function concatOptionalTextSegments(e) {
if (e.left && e.right) return `${e.left}\n\n${e.right}`;
return e.right ?? e.left;
}
/** Joins non-empty string segments, optionally trimming each segment before presence checks. */
function joinPresentTextSegments(e, t) {
return (t?.trim ? normalizeTrimmedStringList(e) : filterStringEntries(e).filter(Boolean)).join("\n\n") || void 0;
}
//#endregion
//#region src/plugins/hook-agent-observations.ts
function withAgentRunId(e, t) {
if (e.runId || !t.runId) return e;
return {
...e,
runId: t.runId
};
}
/** Terminal hooks release per-run state and settle work, even for private runs. */
function projectAgentEndEvent(e, t) {
return withAgentRunId(isIncognitoSessionKey(t.sessionKey) ? {
runId: e.runId,
messages: [],
success: e.success,
durationMs: e.durationMs
} : e, t);
}
/** Exclude optional prompt/response observers without changing policy hooks. */
function withoutIncognitoLlmContent(e) {
return async (t, n) => {
if (!isIncognitoSessionKey(n.sessionKey)) await e(t, n);
};
}
//#endregion
//#region src/plugins/hook-isolation.ts
var HookIsolationError = class extends Error {};
function containsSharedMemory(e, t, n = false) {
if (typeof SharedArrayBuffer !== "undefined" && e instanceof SharedArrayBuffer) return true;
if (!e || typeof e !== "object") return false;
if (ArrayBuffer.isView(e)) {
const t = e instanceof DataView ? DataView.prototype : Object.getPrototypeOf(Uint8Array.prototype);
return typeof SharedArrayBuffer !== "undefined" && Reflect.get(t, "buffer", e) instanceof SharedArrayBuffer;
}
if (e instanceof ArrayBuffer || isOwnedTranscriptPayload(e)) return false;
const r = globalThis.WebAssembly?.Memory;
if (r && e instanceof r && typeof SharedArrayBuffer !== "undefined" && Reflect.get(r.prototype, "buffer", e) instanceof SharedArrayBuffer) return true;
if (t.has(e)) return false;
t.add(e);
if (e instanceof Map) {
const r = Map.prototype.entries.call(e);
for (const [e, i] of r) if (containsSharedMemory(e, t, n) || containsSharedMemory(i, t, n)) return true;
return false;
}
if (e instanceof Set) {
const r = Set.prototype.values.call(e);
for (const e of r) if (containsSharedMemory(e, t, n)) return true;
return false;
}
if (!n && (Array.isArray(e) || Object.getPrototypeOf(e) === Object.prototype)) {
for (const n of Reflect.ownKeys(e)) if (containsSharedMemory(Reflect.get(e, n), t)) return true;
return false;
}
if (n && !(e instanceof Error) && !Array.isArray(e)) {
const t = Object.getPrototypeOf(e);
if (t !== Object.prototype && t !== null) return false;
}
for (const r of Reflect.ownKeys(e)) {
const i = Object.getOwnPropertyDescriptor(e, r);
if ((!n || (e instanceof Error ? r === "cause" : typeof r === "string" && i?.enumerable)) && i && "value" in i && containsSharedMemory(i.value, t, n)) return true;
}
return false;
}
function cloneHookIsolationValue(e, t) {
try {
if (process.versions.bun && containsSharedMemory(t, /* @__PURE__ */ new Set(), true)) throw new TypeError("shared memory cannot be isolated");
const e = structuredClone(t);
if (containsSharedMemory(e, /* @__PURE__ */ new Set())) throw new TypeError("shared memory cannot be isolated");
return e;
} catch (t) {
throw new HookIsolationError(`[hooks] ${e} mutable input isolation failed`, { cause: t });
}
}
/** Copy dispatch envelopes while retaining only payloads sealed by the transcript owner. */
function clonePromptHookEvent(e, t) {
try {
const n = [];
const r = [];
const i = /* @__PURE__ */ new Set();
const isolate = (e, t, a, o = false) => {
const s = typeof a;
if (a === null || s !== "object" && s !== "function" && s !== "symbol" || o) return;
if (typeof a === "object" && i.has(a)) {
isolateProperties(a);
return;
}
n.push(a);
r.push({
target: e,
key: t
});
};
const isolateProperties = (e, t) => {
for (const n of Reflect.ownKeys(e)) if (typeof n === "symbol") Reflect.deleteProperty(e, n);
else if (n !== t) isolate(e, n, Reflect.get(e, n));
};
const a = projectModelContextMessages(t.messages, (e) => {
i.add(e);
});
for (let e = 0; e < a.length; e++) {
const n = a[e];
if (n && typeof n === "object") {
const r = Object.getPrototypeOf(n);
if (r === Object.prototype || r === null) {
const r = t.messages[e];
const i = r && typeof r === "object" && isOwnedTranscriptPayload(r) ? r : void 0;
const o = {};
for (const e of Object.getOwnPropertyNames(n)) {
if (!Object.prototype.propertyIsEnumerable.call(n, e)) continue;
const t = Reflect.get(n, e);
if (e === "__proto__") Object.defineProperty(o, e, {
value: t,
enumerable: true,
configurable: true,
writable: true
});
else o[e] = t;
isolate(o, e, t, t !== null && typeof t === "object" && (i !== void 0 && Reflect.get(i, e) === t || isOwnedTranscriptPayload(t)));
}
a[e] = o;
continue;
}
}
isolate(a, String(e), n);
}
const o = {
...t,
messages: a
};
isolateProperties(o, "messages");
if (n.length) {
const t = cloneHookIsolationValue(e, n);
for (const [e, { target: n, key: i }] of r.entries()) Object.defineProperty(n, i, {
value: t[e],
enumerable: true,
configurable: true,
writable: true
});
}
return o;
} catch (t) {
if (t instanceof HookIsolationError) throw t;
throw new HookIsolationError(`[hooks] ${e} mutable input isolation failed`, { cause: t });
}
}
//#endregion
//#region src/plugins/hook-channel-ingress.ts
/** Pre-storage policy uses the shared hook executor and retains its exact participant authority. */
function createChannelIngressHookRunner(e) {
return async (t, n) => {
const r = e.getHooks();
if (r.length === 0) return;
const i = r.map((e) => getPluginValueInstance(e.handler)).filter((e) => e !== void 0);
const a = AbortSignal.any([n.signal, ...i.map((e) => e.lifecycle.signal)]);
const assertCurrent = () => {
if (a.aborted || i.some((e) => !e.acceptingCalls || e.owner?.revoked)) throw new Error("Channel ingress transform is no longer current");
};
assertCurrent();
const o = await e.run(t, {
...n,
signal: a
}, {
eventForHandler: (e, t) => ({ event: cloneHookIsolationValue("before_channel_ingress", t?.event === void 0 ? e.event : t.event) }),
mergeResults: (e, t) => t.event === void 0 ? e ?? {} : { event: t.event },
assertHandlerBoundaryActive: assertCurrent,
onHandlerError: () => {
throw new Error("Channel ingress transform failed");
}
});
assertCurrent();
return {
event: o?.event === void 0 ? t.event : o.event,
assertCurrent
};
};
}
//#endregion
//#region src/plugins/hook-claim-admission.ts
const CLAIM_ADMISSION = Symbol.for("openclaw.claimingHookAdmission");
function withClaimingHookAdmission(e, t) {
return t ? Object.assign(e, { [CLAIM_ADMISSION]: t }) : e;
}
function readClaimingHookAdmission(e) {
return e[CLAIM_ADMISSION];
}
//#endregion
//#region src/plugins/hook-decision-types.ts
/** Prefix for user-facing replacement messages when a `block` decision stops a request. */
const BLOCK_MESSAGE_PREFIX = "Your message could not be sent";
function resolveBlockMessage(e, t = {}) {
const n = typeof e.message === "string" ? e.message.trim() : "";
const r = t.blockedBy?.trim();
if (n) return r ? `${BLOCK_MESSAGE_PREFIX}: ${n} (blocked by ${r})` : `${BLOCK_MESSAGE_PREFIX}: ${n}`;
return r ? `${BLOCK_MESSAGE_PREFIX}: blocked by ${r}` : `${BLOCK_MESSAGE_PREFIX}: blocked`;
}
/**
* Type guard: does this object look like a HookDecision (has `outcome` field)?
*/
function isHookDecision(e) {
if (typeof e !== "object" || e === null) return false;
const t = e;
const n = Object.keys(t);
if (t.outcome === "pass") return n.length === 1;
if (t.outcome !== "block") return false;
const r = /* @__PURE__ */ new Set([
"outcome",
"reason",
"message",
"category",
"metadata"
]);
if (n.some((e) => !r.has(e))) return false;
if (typeof t.reason !== "string" || !t.reason.trim()) return false;
if ("message" in t && (typeof t.message !== "string" || !t.message.trim())) return false;
if ("category" in t && (typeof t.category !== "string" || !t.category.trim())) return false;
if ("metadata" in t && (typeof t.metadata !== "object" || t.metadata === null || Array.isArray(t.metadata))) return false;
return true;
}
//#endregion
//#region src/plugins/hook-dispatch-replacement.ts
/** Settles in place of a handler result once a reload that refused the handler finishes. */
const HOOK_REPLACED = Symbol("openclaw.hookReplaced");
/**
* Tracks which plugins one dispatch already waited out a reload for. The dispatch
* loop, not this class, invokes replacement registrations, so it reruns its own
* admission checks and per-handler context, and an expired dispatch starts no
* late plugin work.
*/
var HookDispatchSelection = class {
/** `reselect` must apply the dispatch's own eligibility and authority filters. */
constructor(e, t) {
this.dispatched = e;
this.reselect = t;
this.replaced = /* @__PURE__ */ new Set();
}
/**
* The registration to invoke for a dispatched hook: the hook itself, or, once
* this dispatch waited out its plugin's reload, the same plugin's registration
* at the same position in the current registry. Undefined when the
* replacement dropped it.
*/
current(e) {
if (!this.replaced.has(e.pluginId)) return e;
const t = this.dispatched.filter((t) => t.pluginId === e.pluginId).indexOf(e);
return this.reselect().filter((t) => t.pluginId === e.pluginId)[t];
}
/**
* Runs one handler invocation. The first reload refusal for a plugin settles
* to HOOK_REPLACED after that reload finishes; a refusal of a registration
* already reselected after a reload propagates like any handler failure.
* A synchronous result settles without extra turns, so per-handler context
* revoked on settlement closes as soon as the handler returns.
*/
invoke(e, t) {
const replace = async (t) => {
if (!isPluginReloadingError(t) || this.replaced.has(e.pluginId)) throw t;
await t.replacement;
this.replaced.add(e.pluginId);
return HOOK_REPLACED;
};
try {
const e = t();
return isPromiseLike(e) ? Promise.resolve(e).then(void 0, replace) : Promise.resolve(e);
} catch (e) {
return replace(e);
}
}
};
//#endregion
//#region src/plugins/hook-prompt-context.ts
const SYSTEM_CONTEXT_TRUNCATION_MARKER = "\n[Plugin system context truncated to fit the model budget.]";
function boundSystemContext(e, t) {
if (e === void 0 || estimateStringChars(e) <= t) return e;
const n = Math.max(0, t - 59);
let r = 0;
let i = Math.min(e.length, n);
while (r < i) {
const t = Math.ceil((r + i) / 2);
if (estimateStringChars(truncateUtf16Safe(e, t)) <= n) r = t;
else i = t - 1;
}
return truncateUtf16Safe(e, r) + truncateUtf16Safe(SYSTEM_CONTEXT_TRUNCATION_MARKER, t);
}
function createPluginSystemContextLimiter(e) {
const t = createDedupeCache({
ttlMs: 0,
maxSize: 4096
});
return (n, r, i) => {
const a = Math.floor((asPositiveFiniteNumber(i.contextTokenBudget) ?? 2e5) * 4 * .25);
const o = boundSystemContext(n.prependSystemContext, a);
const s = boundSystemContext(n.appendSystemContext, a);
if ((o !== n.prependSystemContext || s !== n.appendSystemContext) && !t.check(i.sessionId || i.sessionKey ? JSON.stringify([
i.agentId,
i.sessionKey,
i.sessionId,
r
]) : void 0)) e?.warn?.(`[hooks] before_prompt_build: plugin ${r} system context truncated (prepend: ${n.prependSystemContext?.length ?? 0} -> ${o?.length ?? 0} chars; append: ${n.appendSystemContext?.length ?? 0} -> ${s?.length ?? 0} chars)`);
return {
prependSystemContext: o,
appendSystemContext: s
};
};
}
const mergeAgentTurnPrepare = (e, t) => ({
prependContext: concatOptionalTextSegments({
left: e?.prependContext,
right: t.prependContext
}),
appendContext: concatOptionalTextSegments({
left: e?.appendContext,
right: t.appendContext
})
});
//#endregion
//#region src/plugins/hook-reply-payload.ts
const toPluginReplyPayload = (e) => {
const { trustedLocalMedia: t, ...n } = e;
return structuredClone(n);
};
const areMediaUrlArraysEqual = (e, t) => {
const n = e ?? [];
const r = t ?? [];
return n.length === r.length && n.every((e, t) => e === r[t]);
};
const preservesTrustedMediaRefs = (e, t) => {
return e.trustedLocalMedia === true && e.mediaUrl === t.mediaUrl && areMediaUrlArraysEqual(e.mediaUrls, t.mediaUrls);
};
const acceptPluginReplyPayload = (e, t) => {
const n = toPluginReplyPayload(t);
const r = preservesTrustedMediaRefs(e, n) ? {
...n,
trustedLocalMedia: true
} : n;
return recordReplyPayloadMediaSelectionChange(collectReplyMediaEntries(e).map(({ url: e }) => e), copyReplyPayloadMetadata(e, r));
};
//#endregion
//#region src/plugins/hook-timeout.ts
const withHookTimeout = async (e, t, n = {}) => {
trackAsyncWork(() => e).catch(() => {});
return await raceWithTimeout(e, t, () => {
throw new Error(`timed out after ${t}ms`);
}, { ref: !n.unref });
};
//#endregion
//#region src/plugins/runtime/subagent-requester-context.ts
const pluginSubagentRequesterScope = resolveGlobalSingleton(Symbol.for("openclaw.pluginSubagentRequesterScope"), () => new AsyncLocalStorage());
function createPluginSubagentRequesterContext(e) {
const t = normalizeOptionalString(e.sessionKey);
const n = normalizeDeliveryContext(e.origin);
if (!t || !n?.channel || !n.to) return;
return Object.freeze({
sessionKey: t,
origin: Object.freeze(n)
});
}
async function withPluginSubagentRequesterContext(e, t) {
const n = {
active: true,
requester: e
};
return await pluginSubagentRequesterScope.run(n, async () => {
try {
return await t();
} finally {
n.active = false;
}
});
}
function resolvePluginSubagentCompletionRequester(e) {
if (e !== void 0 && e !== "current-requester") throw new Error("Unsupported plugin subagent completionDelivery value.");
if (e === void 0) return;
const t = pluginSubagentRequesterScope.getStore();
const n = t?.active === true ? t.requester : void 0;
if (!n) throw new Error("completionDelivery \"current-requester\" requires an active requester-bound plugin hook invocation.");
return n;
}
//#endregion
//#region src/plugins/session-end-transcript.ts
const sessionEndTranscriptSource = Symbol("openclaw.sessionEndTranscriptSource");
function attachSessionEndTranscriptSource(e, t) {
Object.defineProperty(e, sessionEndTranscriptSource, {
configurable: false,
enumerable: false,
value: t,
writable: false
});
}
function createScopedAvailableEndedTranscript(e, t) {
let n = true;
const assertActive = () => {
if (!n || t?.aborted) throw new Error("session_end transcript reader is no longer active");
};
return {
capability: Object.freeze({
available: true,
async readTail(t) {
assertActive();
const n = await e.readTail(t);
await Promise.resolve();
assertActive();
return n;
}
}),
revoke() {
n = false;
}
};
}
function createSessionEndTranscriptSourceLease(e) {
if (!e.available) return {
source: Object.freeze({ ...e }),
revoke() {}
};
const t = createScopedAvailableEndedTranscript(e);
return {
source: t.capability,
revoke: () => t.revoke()
};
}
function projectSessionEndTranscriptContext(e, t, n) {
if (e.conversationAccessAllowed !== true) return {
context: {
...t,
endedTranscript: Object.freeze({
available: false,
reason: "conversation-access-required"
})
},
dispose() {}
};
const r = t[sessionEndTranscriptSource] ?? {
available: false,
reason: "unsupported-source"
};
if (!r.available) return {
context: {
...t,
endedTranscript: Object.freeze({ ...r })
},
dispose() {}
};
const i = createScopedAvailableEndedTranscript(r, n);
return {
context: {
...t,
endedTranscript: i.capability
},
dispose: () => i.revoke()
};
}
//#endregion
//#region src/plugins/hooks.ts
const DEFAULT_VOID_HOOK_TIMEOUT_MS_BY_HOOK = Object.fromEntries(Object.entries(PLUGIN_HOOK_METADATA).map(([e, t]) => [e, t.voidTimeoutMs]));
const DEFAULT_MODIFYING_HOOK_TIMEOUT_MS_BY_HOOK = Object.fromEntries(Object.entries(PLUGIN_HOOK_METADATA).map(([e, t]) => [e, t.modifyingTimeoutMs]));
function isHookContextEligible(e, t) {
if (e.hookName === "reply_dispatch" && e.eligibleDispatchKinds !== void 0) {
const n = typeof t === "object" && t !== null && "dispatchKind" in t ? t.dispatchKind : void 0;
return !isPluginHookReplyDispatchKind(n) || e.eligibleDispatchKinds.includes(n);
}
if (e.hookName !== "before_agent_reply" || e.eligibleTriggers === void 0) return true;
const n = typeof t === "object" && t !== null && "trigger" in t ? t.trigger : void 0;
return typeof n === "string" && e.eligibleTriggers.includes(n);
}
/** Get hooks for a specific hook name, sorted by priority (higher first). */
function getHooksForName(e, t, n, r) {
return e.typedHooks.filter((e) => e.hookName === t && isHookContextEligible(e, n)).filter((e) => r === void 0 || pluginToolMatcherCoversTool(e.matcher, r)).toSorted((e, t) => (t.priority ?? 0) - (e.priority ?? 0));
}
function getToolHookMatcherScope(e, t) {
return createPluginToolMatcherScope(getHooksForName(e, t).map((e) => e.matcher));
}
function getHooksForNameAndPlugin(e, t, n) {
return getHooksForName(e, t).filter((e) => e.pluginId === n);
}
function createHookRunner(e, t = {}) {
const n = t.logger;
const r = t.catchErrors ?? true;
const i = {
before_agent_run: "fail-closed",
before_channel_ingress: "fail-closed",
...t.failurePolicyByHook
};
const a = {
...DEFAULT_VOID_HOOK_TIMEOUT_MS_BY_HOOK,
...t.voidHookTimeoutMsByHook
};
const o = {
...DEFAULT_MODIFYING_HOOK_TIMEOUT_MS_BY_HOOK,
...t.modifyingHookTimeoutMsByHook
};
const s = randomUUID();
let c = 0;
const l = createPluginSystemContextLimiter(n);
const shouldCatchHookErrors = (e) => r && (i[e] ?? "fail-open") === "fail-open";
const recordBeforeToolCallDecision = (e) => {
if (!e.receiptAuthority) return;
try {
if (e.receiptAuthority() === false) return;
} catch {
return;
}
const t = e.failOpen !== void 0;
const n = e.result?.block === true || e.failOpen === false;
recordRuntimeActionDecision({
token: e.token,
family: "plugin",
operation: "before_tool_call",
outcome: n ? "denied" : e.failOpen ? "unknown" : "allowed",
coverageState: n || !t ? "enforced" : "unknown",
reasonCode: t ? e.failOpen ? "plugin_hook_failed_open" : "plugin_hook_failed_closed" : n ? "plugin_hook_blocked" : e.result?.requireApproval ? "plugin_hook_approval_required" : "plugin_hook_allowed",
owner: "plugin-hook",
decisionBoundary: "plugin.before-tool-call",
policyRefs: ["plugin-hook:before-tool-call"],
summary: t ? e.failOpen ? "A plugin hook failed open, so its policy outcome is unknown." : "A plugin hook failed closed before tool execution." : n ? "A registered plugin hook denied tool execution." : e.result?.requireApproval ? "A registered plugin hook required a separate owner-native approval decision." : "A registered plugin hook allowed tool execution to continue.",
missingEvidence: e.failOpen ? ["plugin.hook_decision"] : [],
remediation: e.failOpen ? [{
code: "repair_plugin_hook",
text: "Inspect the registered plugin hook failure before relying on this action."
}] : [],
discriminator: JSON.stringify([
e.hook.pluginId,
e.hook.registrationId ?? null,
e.event.toolCallId ?? null,
++c,
e.event.toolName,
s
])
});
};
const stickyTrue = (e, t) => e === true || t === true ? true : void 0;
const normalizeHookList = (e) => {
if (e === void 0) return;
return Array.isArray(e) && e.every((e) => typeof e === "string") ? e : [];
};
const readHookToolsAllowRestrictions = (e) => {
const t = normalizeHookList(e);
if (t === void 0) return [];
const n = Array.isArray(e) ? readToolAllowlistIntersection(e) : void 0;
return n ? n.map((e) => normalizeHookList(e) ?? []) : [t];
};
const intersectToolsAllow = (e, t) => {
if (e === void 0) return t;
if (e.length === 0 || t.length === 0) return [];
const n = normalizeToolList(expandToolGroups(e));
const r = normalizeToolList(expandToolGroups(t));
if (n.includes("*")) return r;
if (r.includes("*")) return n;
const i = createToolPolicyMatcher({ allow: n });
const a = createToolPolicyMatcher({ allow: r });
return [...new Set(normalizeToolList([...n, ...r]))].filter((e) => i(e) && a(e));
};
const mergeBeforePromptBuild = (e, t, n, r) => {
const { prependSystemContext: i, appendSystemContext: a } = l(t, n, r);
const o = [...readHookToolsAllowRestrictions(e?.toolsAllow), ...readHookToolsAllowRestrictions(t.toolsAllow)];
const s = o.length === 0 ? void 0 : attachToolAllowlistIntersection([...o.reduce(intersectToolsAllow, void 0) ?? []], o);
return {
systemPrompt: e?.systemPrompt ?? t.systemPrompt,
...mergeAgentTurnPrepare(e, t),
...s !== void 0 ? { toolsAllow: s } : {},
prependSystemContext: concatOptionalTextSegments({
left: e?.prependSystemContext,
right: i
}),
appendSystemContext: concatOptionalTextSegments({
left: e?.appendSystemContext,
right: a
})
};
};
const mergeBeforeAgentFinalize = (e, t) => {
const normalizeRetry = (e) => {
const t = typeof e?.instruction === "string" ? e.instruction.trim() : "";
if (!t) return;
return {
...e,
instruction: t
};
};
if (e?.action === "finalize") return e;
if (t.action === "finalize") return {
action: "finalize",
reason: t.reason
};
if (e?.action === "revise" && t.action === "revise") {
const n = normalizeRetry(t.retry);
const r = [...e.retryCandidates ?? (e.retry ? [e.retry] : []), ...n ? [n] : []];
const i = r[0];
const a = {
action: "revise",
reason: concatOptionalTextSegments({
left: e.reason,
right: t.reason
}),
...i ? { retry: i } : {}
};
if (r.length > 1) Object.defineProperty(a, "retryCandidates", {
configurable: true,
enumerable: false,
value: r
});
return a;
}
if (e?.action === "revise") return e;
if (t.action === "revise") {
const e = normalizeRetry(t.retry);
return {
action: "revise",
reason: t.reason,
...e ? { retry: e } : {}
};
}
return t.action === "continue" ? {
action: "continue",
reason: t.reason
} : e ?? t;
};
const handleHookError = (e) => {
const t = `[hooks] ${e.hookName} handler from ${e.pluginId} failed: ${formatHookErrorForLog(e.error)}`;
if (shouldCatchHookErrors(e.hookName)) {
n?.error(t);
return;
}
throw new Error(t, { cause: e.error });
};
const sanitizeHookError = (e) => {
return formatErrorMessage(e).split("\n")[0]?.trim() || "unknown error";
};
const awaitHook = (e, t, n, r) => {
const i = clampPositiveTimerTimeoutMs(e.timeoutMs) ?? clampPositiveTimerTimeoutMs(n);
return i ? withHookTimeout(t, i, r) : t;
};
const runSyncMessageHookStep = (e, t, r, i, a) => {
try {
const o = e.handler;
const s = o({
...r,
message: i
}, a);
if (isPromiseLike(s)) {
Promise.resolve(s).catch(() => void 0);
const r = `[hooks] ${t} handler from ${e.pluginId} returned a Promise; this hook is synchronous and the result was ignored.`;
if (!shouldCatchHookErrors(t)) throw new Error(r);
n?.warn?.(r);
return;
}
if (!s) return;
if (t === "before_message_write" && s.block) return { block: true };
const c = s.message;
if (!c) return;
if (typeof c !== "object" || typeof c.role !== "string") throw new Error("the replacement is not a session message; the original message was kept");
return { message: c };
} catch (r) {
const i = `[hooks] ${t} handler from ${e.pluginId} failed: ${String(r)}`;
if (shouldCatchHookErrors(t)) {
n?.error(i);
return;
}
throw new Error(i, { cause: r });
}
};
const runSyncMessageHooks = (t, n, r) => {
const i = getHooksForName(e, t);
if (i.length === 0) return;
let a = n.message;
for (const e of i) {
const i = runSyncMessageHookStep(e, t, n, a, r);
if (i?.block) return {
message: a,
block: true
};
if (i?.message) a = i.message;
}
return { message: a };
};
/**
* All handlers are executed in parallel for performance.
*/
async function runVoidHook(t, r, i, o = {}, s, c) {
const l = getHooksForName(e, t, void 0, s);
if (l.length === 0) return;
n?.debug?.(`[hooks] running ${t} (${l.length} handlers)`);
const u = new HookDispatchSelection(l, () => getHooksForName(e, t, void 0, s));
const d = l.map(async (e) => {
for (let n = u.current(e); n;) {
const s = n;
n = void 0;
const l = c?.(s, i);
try {
const invoke = () => s.handler(r, l?.context ?? i);
const c = t === "gateway_stop" ? Promise.resolve(runPluginCleanup(s.handler, invoke)) : u.invoke(s, invoke);
const d = l ? c.finally(l.dispose) : c;
if (await awaitHook(s, d, a[t], { unref: o.unrefTimeout ?? true }) === HOOK_REPLACED) n = u.current(e);
} catch (e) {
handleHookError({
hookName: t,
pluginId: s.pluginId,
error: e
});
} finally {
l?.dispose();
}
}
});
const f = (await Promise.allSettled(d)).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (f.length > 0) throw f.length === 1 ? f[0] : new AggregateError(f, f.map(formatErrorMessage).join("; "));
}
const bindVoidHook = (e) => (t, n) => runVoidHook(e, t, n);
const bindModifyingHook = (e, t = {}) => (n, r) => runModifyingHook(e, n, r, t);
const bindClaimingHook = (e, t) => runClaimingHook.bind(void 0, e, t);
/**
* Handlers are executed sequentially in priority order, and results are merged.
*/
async function runModifyingHook(t, r, i, a = {}, s) {
const c = getHooksForName(e, t, void 0, s);
const l = a.includeRegistration ? c.filter(a.includeRegistration) : c;
if (l.length === 0) return;
const u = (t === "before_prompt_build" || t === "agent_turn_prepare") && "messages" in r && Array.isArray(r.messages) ? clonePromptHookEvent(t, {
...r,
messages: r.messages
}) : r;
n?.debug?.(`[hooks] running ${t} (${l.length} handlers, sequential)`);
let d;
const f = new HookDispatchSelection(l, () => {
const n = getHooksForName(e, t, void 0, s);
return a.includeRegistration ? n.filter(a.includeRegistration) : n;
});
for (const e of l) {
let r = false;
for (let s = f.current(e); s;) {
const c = s;
s = void 0;
a.assertHandlerBoundaryActive?.();
readClaimingHookAdmission(i)?.assertCurrent?.();
try {
const l = a.eventForHandler ? a.eventForHandler(u, d) : a.isolateEventPerHandler ? cloneHookIsolationValue(t, u) : u;
const p = t === "before_prompt_build" ? { active: true } : void 0;
const m = p ? {
...i,
hookInvocation: Object.freeze({ assertActive() {
if (!p.active) throw new Error("prompt hook invocation is no longer active");
} })
} : i;
let h;
try {
const e = f.invoke(c, () => c.handler(l, m));
h = await awaitHook(c, e, o[t]);
} finally {
if (p) p.active = false;
}
if (h === HOOK_REPLACED) {
s = f.current(e);
continue;
}
const g = h;
a.onHandlerResult?.({
hook: c,
result: g
});
if (g !== void 0 && (g !== null || a.mergeNullResults)) {
if (a.mergeResults) d = a.mergeResults(d, g, c, u);
else d = g;
if (d && a.shouldStop?.(d)) {
const e = a.terminalLabel ? ` ${a.terminalLabel}` : "";
const i = c.priority ?? 0;
n?.debug?.(`[hooks] ${t}${e} decided by ${c.pluginId} (priority=${i}); skipping remaining handlers`);
r = true;
}
}
} catch (e) {
const n = !(e instanceof HookIsolationError) && shouldCatchHookErrors(t);
a.onHandlerError?.(c, n);
if (e instanceof HookIsolationError) throw e;
handleHookError({
hookName: t,
pluginId: c.pluginId,
error: e
});
}
a.assertHandlerBoundaryActive?.();
readClaimingHookAdmission(i)?.assertCurrent?.();
}
if (r) break;
}
return d;
}
/**
* Run a sequential claim hook where the first `{ handled: true }` result wins.
*/
async function runClaimingHook(t, r, i, a, o) {
const s = getHooksForName(e, t, a);
n?.debug?.(`[hooks] running ${t} (${s.length} handlers, first-claim wins)`);
const c = await runClaimingHooksList(s, t, i, a, o, r?.(a));
return c.status === "handled" ? c.result : void 0;
}
async function runClaimingHooksList(t, n, r, i, a, o = false) {
const s = readClaimingHookAdmission(i);
const c = new HookDispatchSelection(t, () => getHooksForName(e, n, i));
let l;
for (const e of t) for (let t = c.current(e); t;) {
const u = t;
t = void 0;
if (s?.prepare) await s.prepare();
s?.assertCurrent?.();
let d = void 0;
let f = false;
try {
const invokeHandler = async () => {
const e = c.invoke(u, () => u.handler(r, i));
const t = await awaitHook(u, e);
f = t === HOOK_REPLACED;
return t === HOOK_REPLACED ? void 0 : t;
};
d = a ? await a(invokeHandler) : await invokeHandler();
} catch (e) {
l ??= sanitizeHookError(e);
handleHookError({
hookName: n,
pluginId: u.pluginId,
error: e
});
if (o) throw e;
}
if (f) {
t = c.current(e);
continue;
}
s?.assertCurrent?.();
if (d?.handled) return {
status: "handled",
result: d
};
}
return l ? {
status: "error",
error: l
} : { status: "declined" };
}
async function runBeforePromptBuild(e, t) {
return runModifyingHook("before_prompt_build", e, t, {
mergeResults: (e, n, r) => mergeBeforePromptBuild(e, n, r.pluginId, t),
includeRegistration: (e) => e.requiresToolAuthority !== true
});
}
/** Runs context enrichment only after the host has finalized the turn's tool surface. */
async function runAuthorizedPromptBuild(e, t, n) {
const r = n.toolAuthorityFingerprint.trim();
if (!r) return;
const i = [...new Set(n.activeToolNames.map(normalizeToolPolicyName).filter(Boolean))].toSorted();
const a = new Set(i);
const o = { active: true };
const assertActive = () => {
if (!o.active) throw new Error("prompt tool authority is no longer active");
n.assertHostActive();
};
const s = Object.freeze({
fingerprint: createHash("sha256").update(r).update("\0").update(i.join("\0")).digest("hex"),
allows(e) {
assertActive();
return a.has(normalizeToolPolicyName(e));
},
assertActive
});
try {
const n = await runModifyingHook("before_prompt_build", e, {
...t,
toolAuthority: s
}, {
mergeResults: mergeAgentTurnPrepare,
includeRegistration: (e) => e.requiresToolAuthority === true,
assertHandlerBoundaryActive: assertActive
});
if (!n) return;
return {
...n.prependContext ? { prependContext: n.prependContext } : {},
...n.appendContext ? { appendContext: n.appendContext } : {}
};
} finally {
o.active = false;
}
}
async function runInboundClaimForPlugin(t, n, r) {
const i = await runClaimingHooksList(getHooksForNameAndPlugin(e, "inbound_claim", t), "inbound_claim", n, r);
return i.status === "handled" ? i.result : void 0;
}
async function runInboundClaimForPluginOutcome(t, r, i) {
if (!e.plugins.some((e) => e.id === t && e.status === "loaded")) return { status: "missing_plugin" };
const a = getHooksForNameAndPlugin(e, "inbound_claim", t);
if (a.length === 0) return { status: "no_handler" };
n?.debug?.(`[hooks] running inbound_claim for ${t} (${a.length} handlers, targeted outcome)`);
return runClaimingHooksList(a, "inbound_claim", r, i);
}
async function runBeforeDispatch(e, t, n) {
return runClaimingHook("before_dispatch", void 0, e, t, n ? (e) => withPluginSubagentRequesterContext(n, e) : void 0);
}
/** After session preparation, the first block wins; void handlers allow inference. */
async function runBeforeAgentRun(e, t) {
let n;
const r = await runModifyingHook("before_agent_run", e, t, {
mergeResults: (e, t, r) => {
const i = isHookDecision(t) ? t : {
outcome: "block",
reason: "before_agent_run returned an invalid decision"
};
const a = !e || i.outcome === "block" && e.outcome !== "block" ? i : e;
if (a === i) n = r.pluginId;
return a;
},
mergeNullResults: true,
shouldStop: (e) => e?.outcome === "block",
terminalLabel: "gate-decision"
});
if (!r) return;
return {
decision: r,
pluginId: n ?? "unknown"
};
}
async function runBeforeToolCall(e, t, n) {
return runModifyingHook("before_tool_call", e, t, {
isolateEventPerHandler: true,
mergeResults: (e, t, n) => {
if (e?.block === true) return e;
const r = e?.requireApproval !== void 0;
let i = t.params ?? e?.params;
if (r) i = e?.params;
else if (t.requireApproval && i !== void 0) i = cloneHookIsolationValue("before_tool_call", i);
return {
params: i,
block: stickyTrue(e?.block, t.block),
blockReason: t.blockReason ?? e?.blockReason,
requireApproval: e?.requireApproval ?? (t.requireApproval ? {
...t.requireApproval,
pluginId: n.pluginId
} : void 0)
};
},
shouldStop: (e) => e.block === true,
terminalLabel: "block=true",
onHandlerResult: ({ hook: t, result: r }) => {
n?.markOwnerDecision?.();
recordBeforeToolCallDecision({
event: e,
hook: t,
token: n?.token,
result: r,
receiptAuthority: n?.assertAuthority
});
},
onHandlerError: (t, r) => {
n?.markOwnerDecision?.();
recordBeforeToolCallDecision({
event: e,
hook: t,
token: n?.token,
failOpen: r,
receiptAuthority: n?.assertAuthority
});
}
}, e.toolName);
}
/** Transcript hooks stay synchronous and pass each replacement to the next handler. */
function runToolResultPersist(e, t) {
const n = runSyncMessageHooks("tool_result_persist", e, t);
return n ? { message: n.message } : void 0;
}
/** A blocked transcript write stops the chain; otherwise publish only a changed message. */
function runBeforeMessageWrite(e, t) {
const n = runSyncMessageHooks("before_message_write", e, t);
if (n?.block) return { block: true };
return n && n.message !== e.message ? { message: n.message } : void 0;
}
async function runResolveExecEnv(e, t) {
return await runModifyingHook("resolve_exec_env", e, t, { mergeResults: (e, t) => e ? {
...e,
...t
} : t }) ?? {};
}
return {
runBeforeModelResolve: bindModifyingHook("before_model_resolve", { mergeResults: (e, t) => ({
modelOverride: e?.modelOverride ?? t.modelOverride,
providerOverride: e?.providerOverride ?? t.providerOverride,
fallbacksOverride: e?.fallbacksOverride ?? normalizeHookList(t.fallbacksOverride)
}) }),
runAgentTurnPrepare: bindModifyingHook("agent_turn_prepare", { mergeResults: mergeAgentTurnPrepare }),
runBeforePromptBuild,
runAuthorizedPromptBuild,
hasAuthorizedPromptBuildHooks: (t) => e.typedHooks.some((e) => e.hookName === "before_prompt_build" && e.requiresToolAuthority === true && (t === void 0 || isHookContextEligible(e, t))),
runBeforeAgentReply: bindClaimingHook("before_agent_reply"),
runModelCallStarted: bindVoidHook("model_call_started"),
runModelCallEnded: bindVoidHook("model_call_ended"),
runLlmInput: withoutIncognitoLlmContent(bindVoidHook("llm_input")),
runLlmOutput: withoutIncognitoLlmContent(bindVoidHook("llm_output")),
runBeforeAgentFinalize: async (e, t) => runModifyingHook("before_agent_finalize", withAgentRunId(e, t), t, { mergeResults: mergeBeforeAgentFinalize }),
runAgentEnd: async (e, t, n) => runVoidHook("agent_end", projectAgentEndEvent(e, t), t, n),
runBeforeCompaction: bindVoidHook("before_compaction"),
runAfterCompaction: bindVoidHook("after_compaction"),
runBeforeReset: bindVoidHook("before_reset"),
runBeforeChannelIngress: createChannelIngressHookRunner({
getHooks: () => getHooksForName(e, "before_channel_ingress"),
run: (e, t, n) => runModifyingHook("before_channel_ingress", e, t, n)
}),
runBeforeAgentRun,
runInboundClaim: bindClaimingHook("inbound_claim"),
runInboundClaimForPlugin,
runInboundClaimForPluginOutcome,
runChannelPairingRequested: bindVoidHook("channel_pairing_requested"),
runMessageReceived: bindVoidHook("message_received"),
runBeforeDispatch,
runReplyDispatch: bindClaimingHook("reply_dispatch", (e) => e.dispatchKind === "acp"),
runReplyPayloadSending: bindModifyingHook("reply_payload_sending", {
eventForHandler: (e, t) => ({
...e,
payload: toPluginReplyPayload(t?.payload ?? e.payload)
}),
mergeResults: (e, t, n, r) => ({
payload: t.payload === void 0 ? e?.payload ?? r.payload : acceptPluginReplyPayload(e?.payload ?? r.payload, t.payload),
cancel: stickyTrue(e?.cancel, t.cancel),
reason: t.reason ?? e?.reason
}),
shouldStop: (e) => e.cancel === true,
terminalLabel: "cancel=true"
}),
runMessageSending: async (e, t) => {
const n = await runModifyingHook("message_sending", e, t, {
mergeResults: (e, t) => ({
content: t.content ?? e?.content,
cancel: stickyTrue(e?.cancel, t.cancel),
cancelReason: t.cancelReason ?? e?.cancelReason,
metadata: t.metadata ?? e?.metadata
}),
shouldStop: (e) => e.cancel === true,
terminalLabel: "cancel=true"
});
const r = n?.cancel ? void 0 : n?.content ?? e.content;
const i = finalizeGroupThreadToolReply(r, e, t);
return i !== r ? {
...n,
content: i
} : n;
},
runMessageSent: bindVoidHook("message_sent"),
runBeforeToolCall,
runAfterToolCall: async (e, t) => runVoidHook("after_tool_call", e, t, {}, e.toolName),
runToolResultPersist,
runBeforeMessageWrite,
runSessionStart: bindVoidHook("session_start"),
runSessionEnd: (e, t) => runVoidHook("session_end", e, t, {}, void 0, (e, t) => projectSessionEndTranscriptContext(e, t, getPluginValueInstance(e.handler)?.lifecycle.signal)),
runSubagentDeliveryTarget: bindModifyingHook("subagent_delivery_target", { mergeResults: (e, t) => e?.origin ? e : t }),
runSubagentSpawned: bindVoidHook("subagent_spawned"),
runSubagentProgress: bindVoidHook("subagent_progress"),
runSubagentEnded: bindVoidHook("subagent_ended"),
runGatewayStart: bindVoidHook("gateway_start"),
runGatewayStop: bindVoidHook("gateway_stop"),
runHeartbeatPromptContribution: bindModifyingHook("heartbeat_prompt_contribution", { mergeResults: mergeAgentTurnPrepare }),
runCronReconciled: bindVoidHook("cron_reconciled"),
runCronChanged: bindVoidHook("cron_changed"),
runSkillChanged: bindVoidHook("skill_changed"),
runBeforeInstall: bindModifyingHook("before_install", {
mergeResults: (e, t) => {
const n = [...e?.findings ?? [], ...t.findings ?? []];
return {
findings: n.length ? n : void 0,
block: stickyTrue(e?.block, t.block),
blockReason: t.blockReason ?? e?.blockReason
};
},
shouldStop: (e) => e.block === true,
terminalLabel: "block=true"
}),
runResolveExecEnv,
hasHooks: (t, n) => e.typedHooks.some((e) => e.hookName === t && (n === void 0 || isHookContextEligible(e, n))),
getHookCount: (t) => e.typedHooks.filter((e) => e.hookName === t).length
};
}
//#endregion
export { createPluginSubagentRequesterContext as a, readClaimingHookAdmission as c, joinPresentTextSegments as d, fireAndForgetBoundedHook as f, createSessionEndTranscriptSourceLease as i, withClaimingHookAdmission as l, formatHookErrorForLog as m, getToolHookMatcherScope as n, resolvePluginSubagentCompletionRequester as o, fireAndForgetHook as p, attachSessionEndTranscriptSource as r, resolveBlockMessage as s, createHookRunner as t, cloneHookIsolationValue as u };