openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,748 lines • 64.1 kB
JavaScript
import { i as isStandaloneRuntimeExecutable, s as resolveOpenClawCliInvocation } from "./cli-invocation-ZSPsKRWa.mjs";
import { h as readNonEmptyStringPreservingWhitespace } from "./string-coerce-CCIiB4H7.mjs";
import { A as resolveExpiresAtMsFromDurationMs, n as MAX_TIMER_TIMEOUT_MS, v as floorPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import "./src-H3RMXyFL.mjs";
import { n as writeStableStringify, t as stableStringify } from "./stable-stringify-vqde_3tT.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { a as isPidDefinitelyDead } from "./pid-alive-D899x-ak.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { o as payloadTextResult } from "./common-njQNtpnW.mjs";
import { w as retainBeforeToolCallForNativeHookRelay } from "./host-private-capabilities-DDumj0c_.mjs";
import { c as getGlobalHookRunnerRegistry, i as hasGlobalHooks } from "./hook-runner-global-DmYyIVDp.mjs";
import { n as getToolHookMatcherScope } from "./hooks-BiZpB_10.mjs";
import { d as hasBeforeToolCallPolicy, f as runBeforeToolCallHook, h as requestDeferredPluginToolApproval, m as cancelDeferredPluginToolApproval, y as PluginApprovalResolutions } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { n as mergePluginToolMatcherScopes } from "./tool-hook-matcher-DlUmH-ng.mjs";
import { t as runAgentHarnessAfterToolCallHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { l as createHttpRequestAbortSignal, o as readRequestBodyWithLimit } from "./http-body-B9w7rzPz.mjs";
import { i as listAgentToolResultMiddlewareRegistrations, r as getAgentToolResultMiddlewareMatcherScope } from "./agent-tool-result-middleware-C6qDSxiL.mjs";
import { a as getTrustedToolPolicyMatcherScope } from "./gateway-tool-policy-Bz1T20RP.mjs";
import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import "./agent-tools.before-tool-call-CCkSq-k3.mjs";
import { t as readByteStreamWithLimit } from "./read-byte-stream-with-limit-BjmaH2Xs.mjs";
import { t as isApprovalNotFoundError } from "./approval-errors-byE8UOsC.mjs";
import { c as prepareSystemRunMutableFileBinding, u as revalidateSystemRunMutableFileBinding } from "./system-run-approval-binding-B3btPgad.mjs";
import { i as resolveProjectedMcpCodexToolApprovalMode, t as formatMcpCodexApprovalRemedy } from "./mcp-codex-tool-approval-C6Ex4SQ6.mjs";
import { t as loadMcpToolGrants } from "./exec-approvals-mcp-CergmgTH.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { a as codexNativeHookRelayResponseCodec, o as DEFAULT_RELAY_TIMEOUT_MS, r as isNativeHookRelayBridgeStaleRegistrationError, t as NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR } from "./native-hook-relay-client-C2U5PdVd.mjs";
import { a as readNativeHookRelayProvider, c as shellQuoteArgs, i as readNativeHookRelayEvent, l as snapshotNativeHookRelayPayload, n as isJsonValue, o as readNonEmptyString, r as normalizePositiveInteger, s as readOptionalBoolean, t as isJsonObject } from "./native-hook-relay-utils-vHMzjiyc.mjs";
import { i as runAgentHarnessBeforeAgentFinalizeHook } from "./lifecycle-hook-helpers-XBA2t8zZ.mjs";
import { n as formatNativeHookRelayApprovalPresentation, r as formatPermissionApprovalDescription } from "./native-hook-relay-approval-presentation-D71fPg2_.mjs";
import { n as createAgentToolResultMiddlewareRunner } from "./tool-result-middleware-tMZkWoHr.mjs";
import { existsSync } from "node:fs";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { createServer } from "node:http";
//#region src/agents/harness/native-hook-relay-command.ts
function resolveNativeHookRelayNicePrefix(e) {
if (process.platform === "win32" || e === false || e === void 0) return [];
const t = normalizePositiveInteger(e, 0);
if (t <= 0) return [];
return [
"nice",
"-n",
String(t)
];
}
function resolveNativeHookRelayCommandTimeoutMs(e, t) {
const n = floorPositiveFiniteNumber(e);
const r = floorPositiveFiniteNumber(t);
if (n === void 0) return r;
if (r === void 0) return n;
return Math.min(n, r);
}
function buildNativeHookRelayCommand(e) {
return buildNativeHookRelayCommandWithStateDatabase(e);
}
function buildNativeHookRelayCommandWithStateDatabase(e) {
const t = normalizePositiveInteger(e.timeoutMs, DEFAULT_RELAY_TIMEOUT_MS);
const n = e.executable ? {
executable: e.executable,
kind: "cli"
} : resolveNativeHookRelayExecutable();
const r = n.executable;
const i = (n.kind === "cli" && r !== "openclaw" && isStandaloneRuntimeExecutable(path.resolve(r)) ? path.resolve(r) : void 0) ?? (r === "openclaw" ? r : void 0);
const a = n.kind === "cli" ? resolveOpenClawCliInvocation({
execPath: i ?? e.nodeExecutable ?? process.execPath,
entryPath: i ? null : r,
execArgv: [],
args: []
}) : void 0;
const o = a ? [a.command, ...a.args] : [e.nodeExecutable ?? process.execPath, r];
const s = resolveNativeHookRelayNicePrefix(e.nice);
const c = shellQuoteArgs([
...s,
...o,
"hooks",
"relay",
"--provider",
e.provider,
"--relay-id",
e.relayId,
...e.remoteCredentialPath ? ["--remote-credential", e.remoteCredentialPath] : e.stateDbPath ? ["--state-db", e.stateDbPath] : [],
...e.generation ? ["--generation", e.generation] : [],
"--event",
e.event,
...e.event === "pre_tool_use" && e.preToolUseUnavailable ? ["--pre-tool-use-unavailable", e.preToolUseUnavailable] : [],
"--timeout",
String(t)
]);
return process.platform === "win32" ? c : `exec ${c}`;
}
function resolveNativeHookRelayExecutable() {
const e = process.env.OPENCLAW_CLI_PATH?.trim();
if (e && existsSync(e)) return {
executable: e,
kind: "cli"
};
if (isStandaloneRuntimeExecutable()) return {
executable: process.execPath,
kind: "cli"
};
const t = resolveOpenClawPackageRootSync({
moduleUrl: import.meta.url,
argv1: process.argv[1],
cwd: process.cwd()
});
if (t) {
const e = path.join(t, "dist", "native-hook-relay", "entry.js");
if (existsSync(e)) return {
executable: e,
kind: "worker"
};
for (const e of [
path.join(t, "openclaw.mjs"),
path.join(t, "dist", "entry.js"),
path.join(t, "scripts", "run-node.mjs")
]) if (existsSync(e)) return {
executable: e,
kind: "cli"
};
}
const n = process.argv[1];
if (n) {
const e = path.resolve(n);
if (existsSync(e)) return {
executable: e,
kind: "cli"
};
}
throw new Error("Cannot resolve OpenClaw CLI executable path for native hook relay");
}
//#endregion
//#region src/agents/harness/native-hook-relay-codec.ts
const CODEX_NATIVE_HOOK_TOOL_NAME_ALIASES = {
exec_command: "exec",
write: "apply_patch",
edit: "apply_patch",
agent: "spawn_agent"
};
function normalizeNativeHookInvocation(e) {
const t = normalizeCodexHookMetadata(e.rawPayload);
return {
provider: e.registration.provider,
relayId: e.registration.relayId,
event: e.event,
...t,
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
runId: e.registration.runId,
rawPayload: e.rawPayload,
receivedAt: (/* @__PURE__ */ new Date()).toISOString()
};
}
function normalizeCodexHookMetadata(e) {
const t = isJsonObject(e) ? e : {};
const n = {};
for (const [e, r] of [
["nativeEventName", "hook_event_name"],
["cwd", "cwd"],
["model", "model"],
["turnId", "turn_id"],
["transcriptPath", "transcript_path"],
["permissionMode", "permission_mode"],
["stopHookActive", "stop_hook_active"],
["lastAssistantMessage", "last_assistant_message"],
["toolName", "tool_name"],
["toolUseId", "tool_use_id"]
]) if (e === "stopHookActive") {
const i = readOptionalBoolean(t[r]);
if (i !== void 0) n[e] = i;
} else {
const i = readNonEmptyStringPreservingWhitespace(t[r]);
if (i) n[e] = i;
}
return n;
}
function readCodexToolInput(e) {
const t = isJsonObject(e) ? e : {};
const n = t.tool_input;
if (isJsonObject(n)) return normalizeCodexToolInput(normalizeNativeHookToolName(readNonEmptyStringPreservingWhitespace(t.tool_name)), n);
if (n === void 0) return {};
return { value: n };
}
function normalizeCodexToolInput(e, t) {
const n = normalizeCodexCommand(t.cmd);
if (e !== "exec" || n === void 0) return t;
return {
...t,
command: n
};
}
function normalizeCodexCommand(e) {
if (typeof e === "string") return e;
if (Array.isArray(e) && e.every((e) => typeof e === "string")) return shellQuoteArgs(e);
}
function nativeHookRelayParamsWereRewritten(e, t) {
if (t === void 0) return false;
return stableStringify(t) !== e;
}
function readCodexToolResponse(e) {
return (isJsonObject(e) ? e : {}).tool_response;
}
function readNativeHookRelayApprovalMode(e) {
return (isJsonObject(e) ? e : {}).openclaw_approval_mode === "report" ? "report" : void 0;
}
function normalizeNativeHookToolName(e) {
const t = normalizeToolPolicyName(e ?? "tool");
return CODEX_NATIVE_HOOK_TOOL_NAME_ALIASES[t] ?? t;
}
//#endregion
//#region src/agents/harness/native-hook-relay-state.ts
const nativeHookRelayState = resolveGlobalSingleton(Symbol.for("openclaw.nativeHookRelay.state"), () => ({
relays: /* @__PURE__ */ new Map(),
relayBridges: /* @__PURE__ */ new Map(),
pendingOperations: /* @__PURE__ */ new Set(),
invocations: [],
pendingPermissionApprovals: /* @__PURE__ */ new Map(),
pendingPreToolUseApprovals: /* @__PURE__ */ new Map(),
permissionApprovalWindows: /* @__PURE__ */ new Map(),
permissionAllowAlwaysApprovals: /* @__PURE__ */ new Map()
}));
//#endregion
//#region src/agents/harness/native-hook-relay-permissions.ts
const DEFAULT_PERMISSION_TIMEOUT_MS = 12e4;
const PERMISSION_ALLOW_ALWAYS_TTL_MS = 18e5;
const MAX_PERMISSION_APPROVALS_PER_WINDOW = 12;
const PERMISSION_APPROVAL_WINDOW_MS = 6e4;
const MAX_PERMISSION_ALLOW_ALWAYS_ENTRIES = 512;
const log$2 = createSubsystemLogger("agents/harness/native-hook-relay");
const NATIVE_SHELL_APPROVAL_TOOLS = /* @__PURE__ */ new Set([
"bash",
"exec",
"exec_command",
"shell",
"shell_command"
]);
const { pendingPermissionApprovals, pendingPreToolUseApprovals, permissionApprovalWindows, permissionAllowAlwaysApprovals } = nativeHookRelayState;
let nativeHookRelayPermissionApprovalRequester = requestNativeHookRelayPermissionApproval;
let nativeHookRelayDeferredToolApprovalRequester = requestDeferredPluginToolApproval;
function nativeHookRelayPreToolUseApprovalKey(e) {
const t = e.toolUseId?.trim();
return t ? JSON.stringify([e.relayId, t]) : void 0;
}
function setNativeHookRelayPreToolUseApproval(e) {
const t = nativeHookRelayPreToolUseApprovalKey(e);
if (!t) return false;
const n = pendingPreToolUseApprovals.get(t);
pendingPreToolUseApprovals.set(t, {
relayId: e.relayId,
deferredApproval: e.deferredApproval,
originalParamsFingerprint: e.originalParamsFingerprint
});
let r;
if (pendingPreToolUseApprovals.size > 200) {
const e = pendingPreToolUseApprovals.keys().next().value;
if (e) {
r = pendingPreToolUseApprovals.get(e);
pendingPreToolUseApprovals.delete(e);
}
}
if (n) cancelDeferredPluginToolApproval(n.deferredApproval);
if (r) cancelDeferredPluginToolApproval(r.deferredApproval);
return true;
}
function detachNativeHookRelayApprovalState(e) {
const t = [];
for (const [n, r] of pendingPreToolUseApprovals) if (r.relayId === e) {
pendingPreToolUseApprovals.delete(n);
t.push(r);
}
const n = detachNativeHookRelayPermissionState(e);
return () => {
for (const e of t) cancelDeferredPluginToolApproval(e.deferredApproval);
for (const e of n) e.controller.abort();
};
}
async function resolveNativeHookRelayDeferredToolApproval(e) {
const t = nativeHookRelayPreToolUseApprovalKey(e);
if (!t) return;
const n = pendingPreToolUseApprovals.get(t);
if (!n) return;
n.resolutionPromise ??= resolveNativeHookRelayPreToolUseApproval(n, e.signal).finally(() => {
if (pendingPreToolUseApprovals.get(t) === n) pendingPreToolUseApprovals.delete(t);
});
return n.resolutionPromise;
}
async function resolveNativeHookRelayPreToolUseApproval(e, t) {
const n = await nativeHookRelayDeferredToolApprovalRequester({
deferredApproval: e.deferredApproval,
signal: t
});
if (n.blocked) return {
handled: true,
outcome: "denied",
reason: n.reason,
...n.kind === "failure" && n.disposition !== "blocked" ? { failureDisposition: n.disposition } : {}
};
if (nativeHookRelayParamsWereRewritten(e.originalParamsFingerprint, n.params)) return {
handled: true,
outcome: "denied",
reason: "OpenClaw tool policy rewrote Codex app-server approval params; refusing original request."
};
return {
handled: true,
outcome: "approved-once"
};
}
async function runNativeHookRelayPermissionRequest(e) {
const t = e.invocation.toolName?.startsWith("mcp__") ? e.invocation.toolName : void 0;
if (t && e.registration.deferMcpToolApprovals) return codexNativeHookRelayResponseCodec.renderNoopResponse();
const n = {
provider: e.registration.provider,
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
runId: e.registration.runId,
toolName: t ?? normalizeNativeHookToolName(e.invocation.toolName),
...e.invocation.toolUseId ? { toolCallId: e.invocation.toolUseId } : {},
...e.invocation.cwd ? { cwd: e.invocation.cwd } : {},
...e.invocation.model ? { model: e.invocation.model } : {},
toolInput: readCodexToolInput(e.invocation.rawPayload),
...e.registration.signal ? { signal: e.registration.signal } : {}
};
const r = /^mcp__(.+?)__/.exec(n.toolName)?.[1];
const i = await prepareNativeHookMutableFileBinding(n);
e.registration.assertActive?.();
if (!i.ok) return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("deny", i.message);
const a = nativeHookRelayPermissionApprovalKey({
registration: e.registration,
request: n,
binding: i.binding
});
const o = nativeHookRelayPermissionAllowAlwaysKey({
registration: e.registration,
request: n,
binding: i.binding
});
if (hasNativeHookRelayPermissionAllowAlways(o)) {
e.registration.assertActive?.();
if (i.binding) {
const t = await revalidateSystemRunMutableFileBinding({
binding: i.binding,
cwd: n.cwd
});
e.registration.assertActive?.();
if (!t.ok) return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("deny", t.message);
}
return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("allow");
}
try {
const s = await waitForNativeHookRelayPermissionApproval({
registration: e.registration,
approvalKey: a,
request: n
});
e.registration.assertActive?.();
if ((s === "allow" || s === "allow-always") && i.binding) {
const t = await revalidateSystemRunMutableFileBinding({
binding: i.binding,
cwd: n.cwd
});
e.registration.assertActive?.();
if (!t.ok) return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("deny", t.message);
}
if (s === "allow") return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("allow");
if (s === "allow-always") {
rememberNativeHookRelayPermissionAllowAlways({
key: o,
relayId: e.registration.relayId,
mcpTool: t !== void 0
});
return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("allow");
}
if (s === "deny" || s === "timed-out" && t) {
const e = s === "deny" ? "Denied by user" : "MCP tool approval timed out";
return codexNativeHookRelayResponseCodec.renderPermissionDecisionResponse("deny", t ? `${e}. ${formatMcpCodexApprovalRemedy(r)}` : e);
}
} catch (t) {
e.registration.assertActive?.();
log$2.warn(`native hook permission approval failed; deferring to provider approval path: ${String(t)}`);
}
return codexNativeHookRelayResponseCodec.renderNoopResponse();
}
async function waitForNativeHookRelayPermissionApproval(e) {
let t = pendingPermissionApprovals.get(e.approvalKey);
if (!t) {
if (!consumeNativeHookRelayPermissionBudget(e.registration.relayId)) {
log$2.warn(`native hook permission approval rate limit exceeded; deferring to provider approval path: relay=${e.registration.relayId} run=${e.registration.runId}`);
return "defer";
}
const n = new AbortController();
const r = {
relayId: e.registration.relayId,
controller: n,
waiters: 0,
cancelWhenUnobserved: e.registration.approvalHost !== void 0,
promise: racePromiseWithAbortSignal(Promise.resolve().then(() => {
n.signal.throwIfAborted();
const t = {
...e.request,
signal: n.signal
};
return e.registration.approvalHost ? requestNativeHookRelayPermissionApproval(t, e.registration.approvalHost) : nativeHookRelayPermissionApprovalRequester(t);
}), n.signal).finally(() => {
if (pendingPermissionApprovals.get(e.approvalKey) === r) pendingPermissionApprovals.delete(e.approvalKey);
})
};
pendingPermissionApprovals.set(e.approvalKey, r);
t = r;
}
t.waiters++;
try {
return await racePromiseWithAbortSignal(t.promise, e.registration.signal);
} finally {
t.waiters--;
if (t.cancelWhenUnobserved && t.waiters === 0 && pendingPermissionApprovals.get(e.approvalKey) === t) {
pendingPermissionApprovals.delete(e.approvalKey);
t.controller.abort();
}
}
}
function nativeHookRelayPermissionApprovalKey(e) {
return JSON.stringify([
e.registration.relayId,
e.registration.runId,
e.request.toolCallId,
permissionRequestContentFingerprint(e.request),
e.binding ? permissionRequestBindingFingerprint(e.binding) : "no-file-binding"
]);
}
async function prepareNativeHookMutableFileBinding(e) {
if (!NATIVE_SHELL_APPROVAL_TOOLS.has(e.toolName.trim().toLowerCase())) return { ok: true };
const t = readNonEmptyStringPreservingWhitespace(e.toolInput.command);
const n = await prepareSystemRunMutableFileBinding({
command: {
kind: "shell",
text: t ?? ""
},
cwd: e.cwd
});
if (!n.ok) return {
ok: false,
message: n.message
};
return n.binding.operands.length > 0 ? {
ok: true,
binding: n.binding
} : { ok: true };
}
function permissionRequestBindingFingerprint(e) {
const t = createHash("sha256");
for (const { argv: n, snapshot: r } of e.operands) {
t.update(JSON.stringify([
n,
r.argvIndex,
r.path,
r.sha256
]));
t.update("\0");
}
return t.digest("hex");
}
function nativeHookRelayPermissionAllowAlwaysKey(e) {
return createHash("sha256").update(JSON.stringify([
e.registration.relayId,
e.request.provider,
e.request.agentId,
e.request.sessionKey ?? e.request.sessionId,
e.request.toolName.startsWith("mcp__") ? e.request.toolName : permissionRequestContentFingerprint(e.request),
e.binding ? permissionRequestBindingFingerprint(e.binding) : void 0
])).digest("hex");
}
function permissionRequestContentFingerprint(e) {
const t = createHash("sha256");
t.update(e.toolName);
t.update("\0");
t.update(e.cwd ?? "");
t.update("\0");
writeStableStringify(e.toolInput, (e) => t.update(e));
return t.digest("hex");
}
function consumeNativeHookRelayPermissionBudget(e, t = Date.now()) {
const n = t - PERMISSION_APPROVAL_WINDOW_MS;
const r = (permissionApprovalWindows.get(e) ?? []).filter((e) => e >= n);
if (r.length >= MAX_PERMISSION_APPROVALS_PER_WINDOW) {
permissionApprovalWindows.set(e, r);
return false;
}
r.push(t);
permissionApprovalWindows.set(e, r);
return true;
}
function hasNativeHookRelayPermissionAllowAlways(e, t = Date.now()) {
const n = permissionAllowAlwaysApprovals.get(e);
if (!n) return false;
if (n.expiresAtMs !== void 0 && n.expiresAtMs <= t) {
permissionAllowAlwaysApprovals.delete(e);
return false;
}
return true;
}
function rememberNativeHookRelayPermissionAllowAlways(e, t = Date.now()) {
pruneNativeHookRelayPermissionAllowAlways(t);
const n = e.mcpTool ? void 0 : resolveExpiresAtMsFromDurationMs(PERMISSION_ALLOW_ALWAYS_TTL_MS, { nowMs: t });
if (!e.mcpTool && n === void 0) return;
permissionAllowAlwaysApprovals.set(e.key, {
relayId: e.relayId,
expiresAtMs: n
});
pruneMapToMaxSize(permissionAllowAlwaysApprovals, MAX_PERMISSION_ALLOW_ALWAYS_ENTRIES);
}
function pruneNativeHookRelayPermissionAllowAlways(e = Date.now()) {
for (const [t, n] of permissionAllowAlwaysApprovals) if (n.expiresAtMs !== void 0 && n.expiresAtMs <= e) permissionAllowAlwaysApprovals.delete(t);
}
function detachNativeHookRelayPermissionState(e) {
const t = [];
permissionApprovalWindows.delete(e);
for (const [t, n] of permissionAllowAlwaysApprovals) if (n.relayId === e) permissionAllowAlwaysApprovals.delete(t);
for (const [n, r] of pendingPermissionApprovals) if (r.relayId === e) {
pendingPermissionApprovals.delete(n);
t.push(r);
}
return t;
}
function removeNativeHookRelayPermissionState(e) {
for (const t of detachNativeHookRelayPermissionState(e)) t.controller.abort();
}
async function requestNativeHookRelayPermissionApproval(e, t) {
const n = DEFAULT_PERMISSION_TIMEOUT_MS;
const r = {
...formatNativeHookRelayApprovalPresentation(e),
severity: "warning",
toolName: e.toolName,
toolCallId: e.toolCallId,
allowedDecisions: [
PluginApprovalResolutions.ALLOW_ONCE,
PluginApprovalResolutions.ALLOW_ALWAYS,
PluginApprovalResolutions.DENY
],
timeoutMs: n
};
const i = t ? await t.requestApproval({
...r,
transportTimeoutMs: 13e4,
signal: e.signal
}) : await callGatewayTool("plugin.approval.request", { timeoutMs: 13e4 }, {
...r,
pluginId: `openclaw-native-hook-relay-${e.provider}`,
agentId: e.agentId,
sessionKey: e.sessionKey,
twoPhase: true
}, {
expectFinal: false,
signal: e.signal
});
e.signal?.throwIfAborted();
const a = i?.id;
if (!a) return "defer";
let o;
if (Object.hasOwn(i ?? {}, "decision")) o = i.decision;
else {
const r = await waitForNativeHookRelayApprovalDecision({
approvalId: a,
signal: e.signal,
timeoutMs: n,
approvalHost: t
});
if (!r || r.id !== a) return "defer";
o = r.decision;
}
if (o === PluginApprovalResolutions.ALLOW_ONCE) return "allow";
if (o === PluginApprovalResolutions.ALLOW_ALWAYS) return "allow-always";
if (o === PluginApprovalResolutions.DENY) return "deny";
return o == null ? "timed-out" : "defer";
}
async function waitForNativeHookRelayApprovalDecision(e) {
return (e.approvalHost ? e.approvalHost.waitForApproval({
approvalId: e.approvalId,
timeoutMs: e.timeoutMs,
transportTimeoutMs: e.timeoutMs + 1e4,
signal: e.signal
}).then((t) => t ? {
id: e.approvalId,
decision: t.decision
} : void 0) : callGatewayTool("plugin.approval.waitDecision", { timeoutMs: e.timeoutMs + 1e4 }, { id: e.approvalId }, { signal: e.signal })).catch((e) => {
if (isApprovalNotFoundError(e)) return;
throw e;
});
}
function setNativeHookRelayPermissionApprovalRequesterForTests(e) {
nativeHookRelayPermissionApprovalRequester = e;
}
function setNativeHookRelayDeferredToolApprovalRequesterForTests(e) {
nativeHookRelayDeferredToolApprovalRequester = e;
}
function clearNativeHookRelayPermissionsForTests() {
for (const e of pendingPermissionApprovals.values()) e.controller.abort();
pendingPermissionApprovals.clear();
for (const e of pendingPreToolUseApprovals.values()) cancelDeferredPluginToolApproval(e.deferredApproval);
pendingPreToolUseApprovals.clear();
permissionApprovalWindows.clear();
permissionAllowAlwaysApprovals.clear();
nativeHookRelayPermissionApprovalRequester = requestNativeHookRelayPermissionApproval;
nativeHookRelayDeferredToolApprovalRequester = requestDeferredPluginToolApproval;
}
//#endregion
//#region src/agents/harness/native-hook-relay-events.ts
function getGlobalToolHookMatcherScope(e) {
const t = getGlobalHookRunnerRegistry();
return t ? getToolHookMatcherScope(t, e) : void 0;
}
/** Snapshot the same canonical native tool family for planning and receipt admission. */
function snapshotNativeHookRelayExecutionAdmission(e) {
return e ? {
toolNames: [...new Set(e.toolNames.map(normalizeNativeHookToolName))],
admit: e.admit
} : void 0;
}
function nativePreToolUseMayRunLoopDetection(e) {
if (!e.preToolUseLoopDetection || !e.sessionKey) return false;
return resolveToolLoopDetectionConfig({
cfg: e.config,
agentId: e.agentId
})?.enabled === true;
}
function nativeHookRelayEventHasLocalWork(e, t) {
if (t === "pre_tool_use") return e.requirePreToolUse === true || Boolean(e.executionAdmissionToolNames?.length) || hasBeforeToolCallPolicy() || nativePreToolUseMayRunLoopDetection(e);
if (t === "post_tool_use") return Boolean(e.postToolUseToolNames?.length) || hasGlobalHooks("after_tool_call") || listAgentToolResultMiddlewareRegistrations("codex").length > 0;
if (t === "before_agent_finalize") return hasGlobalHooks("before_agent_finalize");
return true;
}
function nativeHookRelayEventToolMatcher(e, t) {
if (t === "pre_tool_use") {
if (e.requirePreToolUse || nativePreToolUseMayRunLoopDetection(e)) return;
const t = getGlobalHookRunnerRegistry();
const n = mergePluginToolMatcherScopes([
getGlobalToolHookMatcherScope("before_tool_call"),
getTrustedToolPolicyMatcherScope(t),
e.executionAdmissionToolNames?.length ? {
matchAll: false,
toolNames: e.executionAdmissionToolNames
} : void 0
]);
return n?.matchAll ? void 0 : n?.toolNames;
}
if (t === "post_tool_use") {
const t = mergePluginToolMatcherScopes([
getGlobalToolHookMatcherScope("after_tool_call"),
getAgentToolResultMiddlewareMatcherScope("codex"),
e.postToolUseToolNames?.length ? {
matchAll: false,
toolNames: e.postToolUseToolNames
} : void 0
]);
return t?.matchAll ? void 0 : t?.toolNames;
}
}
const nativeHookRelayHandlers = {
pre_tool_use: runNativeHookRelayPreToolUse,
post_tool_use: runNativeHookRelayPostToolUse,
before_agent_finalize: runNativeHookRelayBeforeAgentFinalize,
permission_request: runNativeHookRelayPermissionRequest
};
async function processNativeHookRelayInvocation(e) {
return nativeHookRelayHandlers[e.invocation.event](e);
}
async function runNativeHookRelayPreToolUse(e) {
const t = normalizeNativeHookToolName(e.invocation.toolName);
const n = readCodexToolInput(e.invocation.rawPayload);
const r = stableStringify(n);
const i = readNativeHookRelayApprovalMode(e.invocation.rawPayload);
const a = {
toolName: t,
params: n,
...e.invocation.toolUseId ? { toolCallId: e.invocation.toolUseId } : {},
signal: e.registration.signal
};
const o = e.registration.runBeforeToolCall ? await e.registration.runBeforeToolCall({
...a,
...i === "report" ? { approvalMode: "defer" } : {},
...e.invocation.cwd ? { nativeOperation: { cwd: e.invocation.cwd } } : {}
}) : await runBeforeToolCallHook({
...a,
...i === "report" ? { approvalMode: "defer" } : {},
ctx: {
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
...e.registration.config ? { config: e.registration.config } : {},
runId: e.registration.runId,
...e.registration.channelId ? { channelId: e.registration.channelId } : {},
...e.registration.requester ? { requester: e.registration.requester } : {},
...e.registration.approvalContext,
...e.invocation.cwd ? {
cwd: e.invocation.cwd,
workspaceDir: e.invocation.cwd
} : {}
}
});
try {
e.registration.signal?.throwIfAborted();
e.registration.assertActive?.();
} catch (e) {
if (!o.blocked && o.deferredApproval) cancelDeferredPluginToolApproval(o.deferredApproval);
throw e;
}
if (o.blocked) return codexNativeHookRelayResponseCodec.renderPreToolUseBlockResponse(o.reason, o.kind === "failure" && o.disposition !== "blocked" ? o.disposition : void 0);
if (!o.deferredApproval && nativeHookRelayParamsWereRewritten(r, o.params)) return codexNativeHookRelayResponseCodec.renderPreToolUseBlockResponse("OpenClaw tool policy rewrote Codex app-server approval params; refusing original request.");
try {
if (e.executionAdmission?.toolNames.includes(t)) {
const t = await e.executionAdmission.admit(e.invocation, e.assertExecutionAdmissionCurrent, {
signal: e.registration.signal,
assertCurrent: () => {
e.registration.signal?.throwIfAborted();
e.registration.assertActive?.();
}
});
e.registration.signal?.throwIfAborted();
e.registration.assertActive?.();
const n = t?.();
if (n) {
if (o.deferredApproval) cancelDeferredPluginToolApproval(o.deferredApproval);
return codexNativeHookRelayResponseCodec.renderPreToolUseBlockResponse(n);
}
}
} catch (e) {
if (o.deferredApproval) cancelDeferredPluginToolApproval(o.deferredApproval);
throw e;
}
if (o.deferredApproval) {
if (!setNativeHookRelayPreToolUseApproval({
relayId: e.registration.relayId,
toolUseId: e.invocation.toolUseId,
deferredApproval: o.deferredApproval,
originalParamsFingerprint: r
})) {
cancelDeferredPluginToolApproval(o.deferredApproval);
return codexNativeHookRelayResponseCodec.renderPreToolUseBlockResponse("Plugin approval required but Codex tool id unavailable.");
}
}
return codexNativeHookRelayResponseCodec.renderNoopResponse();
}
async function runNativeHookRelayPostToolUse(e) {
const t = normalizeNativeHookToolName(e.invocation.toolName);
const n = e.invocation.toolUseId ?? `${e.invocation.event}:${e.invocation.receivedAt}`;
const r = readCodexToolInput(e.invocation.rawPayload);
const i = readCodexToolResponse(e.invocation.rawPayload);
const a = !(listAgentToolResultMiddlewareRegistrations("codex").length > 0) ? i : await createAgentToolResultMiddlewareRunner({
runtime: "codex",
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
runId: e.registration.runId
}).applyToolResultMiddleware({
turnId: e.invocation.turnId,
toolCallId: n,
toolName: t,
args: r,
...e.invocation.cwd ? { cwd: e.invocation.cwd } : {},
result: payloadTextResult(i)
});
await runAgentHarnessAfterToolCallHook({
toolName: t,
toolCallId: n,
runId: e.registration.runId,
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
...e.registration.channelId ? { channelId: e.registration.channelId } : {},
startArgs: r,
result: a
});
return codexNativeHookRelayResponseCodec.renderNoopResponse();
}
async function runNativeHookRelayBeforeAgentFinalize(e) {
const t = await runAgentHarnessBeforeAgentFinalizeHook({
event: {
runId: e.registration.runId,
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
...e.invocation.turnId ? { turnId: e.invocation.turnId } : {},
provider: e.registration.provider,
...e.invocation.model ? { model: e.invocation.model } : {},
...e.invocation.cwd ? { cwd: e.invocation.cwd } : {},
...e.invocation.transcriptPath ? { transcriptPath: e.invocation.transcriptPath } : {},
stopHookActive: e.invocation.stopHookActive === true,
...e.invocation.lastAssistantMessage ? { lastAssistantMessage: e.invocation.lastAssistantMessage } : {}
},
ctx: {
...e.registration.agentId ? { agentId: e.registration.agentId } : {},
sessionId: e.registration.sessionId,
...e.registration.sessionKey ? { sessionKey: e.registration.sessionKey } : {},
runId: e.registration.runId,
...e.registration.channelId ? { channelId: e.registration.channelId } : {},
...e.invocation.cwd ? { workspaceDir: e.invocation.cwd } : {},
...e.invocation.model ? { modelId: e.invocation.model } : {}
}
});
if (t.action === "revise") return codexNativeHookRelayResponseCodec.renderBeforeAgentFinalizeReviseResponse(t.reason);
if (t.action === "finalize") return codexNativeHookRelayResponseCodec.renderBeforeAgentFinalizeStopResponse(t.reason);
return codexNativeHookRelayResponseCodec.renderNoopResponse();
}
//#endregion
//#region src/agents/harness/native-hook-relay-types.ts
const NATIVE_HOOK_RELAY_EVENTS = [
"pre_tool_use",
"post_tool_use",
"permission_request",
"before_agent_finalize"
];
//#endregion
//#region src/agents/harness/native-hook-relay-plan.ts
/** Snapshot static policy and commands without registering a bridge, TTL, or live callbacks. */
function buildNativeHookRelayCommandPlan(e) {
const t = resolveOpenClawStateSqlitePath();
const n = {
...e,
preToolUseLoopDetection: e.preToolUseLoopDetection !== false
};
const r = new Map(NATIVE_HOOK_RELAY_EVENTS.map((e) => [e, {
enabled: nativeHookRelayEventHasLocalWork(n, e),
matcher: nativeHookRelayEventToolMatcher(n, e)?.slice()
}]));
return {
shouldRelayEvent: (e) => r.get(e)?.enabled === true,
toolMatcherForEvent: (e) => r.get(e)?.matcher?.slice(),
commandForEvent: (n, r) => buildNativeHookRelayCommandWithStateDatabase({
provider: e.provider,
relayId: e.relayId,
generation: e.generation,
stateDbPath: t,
remoteCredentialPath: r?.remoteCredentialPath,
event: n,
nice: e.command?.nice,
timeoutMs: resolveNativeHookRelayCommandTimeoutMs(e.command?.timeoutMs, r?.timeoutMs),
executable: e.command?.executable,
nodeExecutable: e.command?.nodeExecutable
})
};
}
//#endregion
//#region src/agents/harness/native-hook-relay-store.ts
async function readNativeHookRelayBridgeRecord(e) {
const t = captureOpenClawStateWorkerContext({ path: e.stateDbPath });
const n = { relayId: e.relayId };
return runOpenClawStateWorkerOperation(t, (e) => e.execute({
type: "nativeHookRelay.read",
input: n
}), { existingOnly: true });
}
function persistNativeHookRelayBridgeRecord(e, t) {
const n = captureOpenClawStateWorkerContext({ path: t.stateDbPath });
const r = {
record: { ...t.record },
updatedAtMs: t.updatedAtMs ?? Date.now()
};
const i = t.assertCurrent;
return runOpenClawStateWorkerOperation(n, (t) => t.execute({
type: e,
input: r
}), {
assertCurrent: i,
createAdmission: () => ({
nativeLocations: [n.admission.databasePath],
admission: createSqliteWorkerOperationAdmission((e, t) => {
if (e.stage !== "transaction") throw new Error("Native hook relay persistence requires transaction admission");
n.admission.assertCurrent();
i?.();
t();
})
})
});
}
async function writeNativeHookRelayBridgeRecord(e) {
await persistNativeHookRelayBridgeRecord("nativeHookRelay.write", e);
}
async function renewOrRestoreNativeHookRelayBridgeRecord(e) {
return persistNativeHookRelayBridgeRecord("nativeHookRelay.renew", e);
}
async function deleteNativeHookRelayBridgeRecordIfOwned(e) {
const t = captureOpenClawStateWorkerContext({ path: e.stateDbPath });
const n = {
relayId: e.relayId,
pid: e.pid,
token: e.token
};
return runOpenClawStateWorkerOperation(t, (e) => e.execute({
type: "nativeHookRelay.deleteOwned",
input: n
}));
}
async function pruneNativeHookRelayBridgeRecords(e) {
const t = captureOpenClawStateWorkerContext({ path: e.stateDbPath });
const n = Date.now();
const { currentPid: r, isPidDead: i } = e;
return runOpenClawStateWorkerOperation(t, async (e) => {
const t = await e.execute({
type: "nativeHookRelay.listRecords",
input: void 0
});
const a = [];
for (const e of t) {
if (n > e.expiresAtMs) {
a.push({
record: e,
reason: "expired"
});
continue;
}
if (e.pid !== r && await i(e.pid)) a.push({
record: e,
reason: "dead-pid"
});
}
return a.length === 0 ? [] : e.execute({
type: "nativeHookRelay.prune",
input: {
candidates: a,
nowMs: n
}
});
});
}
//#endregion
//#region src/agents/harness/native-hook-relay-bridge.ts
const MAX_NATIVE_HOOK_BRIDGE_BODY_BYTES = 5e6;
const log$1 = createSubsystemLogger("agents/harness/native-hook-relay");
const { relays: relays$2, relayBridges: relayBridges$1, pendingOperations } = nativeHookRelayState;
function registerNativeHookRelayBridge(e, t, n) {
const r = randomUUID();
const i = createServer();
const a = createDeferredCore();
i.once("listening", a.resolve);
i.once("error", a.reject);
const o = {
relayId: e.relayId,
stateDbPath: t,
token: r,
server: i,
ready: a.promise,
pending: a.promise,
cancelStartup: () => a.reject(new Error(NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR)),
remoteToolUses: /* @__PURE__ */ new Set()
};
i.on("request", (t, i) => {
handleNativeHookRelayBridgeRequest(t, i, {
provider: e.provider,
relayId: e.relayId,
token: r,
registration: e,
bridge: o,
invokeRelay: n
});
});
relayBridges$1.set(e.relayId, o);
i.on("error", (t) => {
log$1.debug("native hook relay bridge server error", {
error: t,
relayId: e.relayId
});
});
o.ready = a.promise.then(async () => {
assertNativeHookRelayBridgeCurrent(e, o);
await pruneNativeHookRelayBridges(t);
assertNativeHookRelayBridgeCurrent(e, o);
const n = resolveNativeHookRelayBridgeRecord(e, o);
if (!n) throw new Error("native hook relay bridge server address unavailable");
await writeNativeHookRelayBridgeRecord({
record: n,
stateDbPath: t,
assertCurrent: () => assertNativeHookRelayBridgeCurrent(e, o)
});
});
o.pending = o.ready;
retainNativeHookRelayOperation(o.relayId, o.ready);
i.listen(0, "127.0.0.1");
i.unref();
return o;
}
function retainNativeHookRelayOperation(e, t) {
pendingOperations.add(t);
t.then(() => pendingOperations.delete(t), (n) => {
pendingOperations.delete(t);
log$1.debug("native hook relay operation failed", {
error: n,
relayId: e
});
});
}
async function drainNativeHookRelayBridge(e) {
let t;
let n;
do {
t = e.pending;
try {
await t;
} catch (e) {
n ??= { error: e };
}
} while (t !== e.pending);
if (n) throw n.error;
}
function assertNativeHookRelayBridgeCurrent(e, t) {
if (relays$2.get(e.relayId) !== e || relayBridges$1.get(e.relayId) !== t || t.closing) throw new Error(NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR);
}
async function pruneNativeHookRelayBridges(e) {
try {
await pruneNativeHookRelayBridgeRecords({
currentPid: process.pid,
isPidDead: isPidDefinitelyDead,
stateDbPath: e
});
} catch (e) {
log$1.debug("native hook relay bridge record prune skipped", { error: e });
}
}
function resolveNativeHookRelayBridgeRecord(e, t, n = e.expiresAtMs) {
const r = t.server.address();
if (!r || typeof r === "string") {
log$1.debug("native hook relay bridge server address unavailable", { relayId: e.relayId });
return;
}
return {
relayId: e.relayId,
pid: process.pid,
hostname: "127.0.0.1",
port: r.port,
token: t.token,
expiresAtMs: n
};
}
async function renewNativeHookRelayBridgeRecord(e, t, n) {
const r = t.pending.catch(() => void 0).then(async () => {
assertNativeHookRelayBridgeCurrent(e, t);
const r = resolveNativeHookRelayBridgeRecord(e, t, n);
if (!r) return "unavailable";
return await renewOrRestoreNativeHookRelayBridgeRecord({
record: r,
stateDbPath: t.stateDbPath,
assertCurrent: () => assertNativeHookRelayBridgeCurrent(e, t)
}) ? "renewed" : "ownership-changed";
});
t.pending = r.then(() => void 0);
retainNativeHookRelayOperation(t.relayId, t.pending);
return await r;
}
function unregisterNativeHookRelayBridge(e, t) {
const n = t?.expectedBridge ?? relayBridges$1.get(e);
if (!n) return;
if (n.closing) return n.closing;
if (relayBridges$1.get(e) === n) relayBridges$1.delete(e);
if (!n.server.listening) n.cancelStartup();
n.closing = n.pending.catch(() => void 0).then(async () => {
try {
await deleteNativeHookRelayBridgeRecordIfOwned({
...n,
pid: process.pid
});
} finally {
const e = normalizePositiveInteger(t?.deferListenerCloseMs, 0);
if (e > 0) await new Promise((t) => {
setTimeout(t, e).unref();
});
await new Promise((e, t) => {
n.server.close((n) => {
if (n && !hasErrnoCode(n, "ERR_SERVER_NOT_RUNNING")) t(n);
else e();
});
});
}
});
n.pending = n.closing;
retainNativeHookRelayOperation(n.relayId, n.closing);
return n.closing;
}
async function handleNativeHookRelayBridgeRequest(e, t, n) {
const r = createHttpRequestAbortSignal(e, t);
const fail = (e, n) => writeNativeHookRelayBridgeJson(t, e, {
ok: false,
error: n
});
let i;
let a;
try {
if (e.method !== "POST" || !n.remote && e.url !== "/invoke") {
fail(404, "not found");
return;
}
if (!safeEqualSecret(e.headers.authorization, `Bearer ${n.token}`)) {
fail(403, "forbidden");
return;
}
if (!isCurrentNativeHookRelayBridgeRequest(n)) {
fail(410, NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR);
return;
}
const o = n.remote ? await readRequestBodyWithLimit(e, {
maxBytes: MAX_NATIVE_HOOK_BRIDGE_BODY_BYTES,
timeoutMs: 5e3
}) : (await readByteStreamWithLimit(e[Symbol.asyncIterator](), {
maxBytes: MAX_NATIVE_HOOK_BRIDGE_BODY_BYTES,
onOverflow: () => /* @__PURE__ */ new Error("native hook relay bridge payload too large")
})).toString("utf8");
const s = readNativeHookRelayBridgePayload(JSON.parse(o));
i = s.event;
if (s.provider !== n.provider || s.relayId !== n.relayId) {
fail(403, "native hook relay bridge target mismatch");
return;
}
if (!isCurrentNativeHookRelayBridgeRequest(n) || n.remote && s.generation !== n.registration.generation) {
fail(410, NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR);
return;
}
if (n.remote && (i === "pre_tool_use" || i === "post_tool_use")) {
a = isJsonObject(s.rawPayload) ? readNonEmptyStringPreservingWhitespace(s.rawPayload.tool_use_id) : void 0;
const e = `${i}:${a}`;
if (!a || n.bridge.remoteToolUses.has(e)) {
fail(409, "Native hook callback already received");
return;
}
n.bridge.remoteToolUses.add(e);
}
writeNativeHookRelayBridgeJson(t, 200, {
ok: true,
result: await runInDetachedAsyncContext(() => n.invokeRelay({
...s,
requireGeneration: true
}, r.signal))
});
} catch (e) {
if (r.signal.aborted) return;
fail(isNativeHookRelayBridgeStaleRegistrationError(e) ? 410 : 500, n.remote ? "Native hook callback failed" : e instanceof Error ? e.message : String(e));
} finally {
r.cleanup();
if (n.remote) {
const e = {
relayId: n.relayId,
event: typeof i === "string" ? i : void 0,
toolUseId: a,
status: r.signal.aborted ? "aborted" : t.statusCode
};
if (e.status === 200) log$1.info("native hook remote callback", {
consoleMessage: false,
...e
});
else log$1.warn("native hook remote callback refused", e);
}
}
}
function isCurrentNativeHookRelayBridgeRequest(e) {
return relays$2.get(e.relayId) === e.registration && relayBridges$1.get(e.relayId) === e.bridge && !e.bridge.closing;
}
function readNativeHookRelayBridgePayload(e) {
if (!isJsonObject(e)) throw new Error("native hook relay bridge payload must be an object");
return {
provider: e.provider,
relayId: e.relayId,
generation: readNonEmptyString(e.generation, "generation"),
event: e.event,
rawPayload: e.rawPayload
};
}
function writeNativeHookRelayBridgeJson(e, t, n) {
const r = JSON.stringify(n);
e.writeHead(t, {
"content-type": "application/json",
"content-length": Buffer.byteLength(r)
});
e.end(r);
}
async function readNativeHookRelayBridgeRecordIfExists(e, t) {
try {
return await readNativeHookRelayBridgeRecord({
relayId: e,
stateDbPath: t
});
} catch (t) {
log$1.debug("failed to read native hook relay bridge record", {
error: t,
relayId: e
});
}
}
async function clearNativeHookRelayBridgesForTests() {
for (const e of relayBridges$1.keys()) unregisterNativeHookRelayBridge(e);
while (pendingOperations.size > 0) await Promise.allSettled(pendingOperations);
}
//#endregion
//#region src/agents/harness/native-hook-relay-work.ts
const { relays: relays$1 } = nativeHookRelayState;
/** Capture synchronous inputs before the relay owner admits its deferred policy read. */
function prepareNativeHookRelayMcpPolicy(e, t, n) {
const r = e.agentId;
const i = e.autoApproveMcpTools === true;
const a = Object.keys({
...e.projectedMcpServers,
...e.config?.mcp?.servers
}).some((t) => resolveProjectedMcpCodexToolApprovalMode(t, e.config?.mcp?.servers?.[t] ?? {}, e.projectedMcpServers?.[t]) !== void 0);
return Promise.resolve().then(async () => {
if (!n()) return;
return i || (r ? (await loadMcpToolGrants(r, { path: t })).length > 0 : false) || a;
});
}
/** Preserve the first failure while joining work admitted during a pending drain. */
async function drainNativeHookRelayWork(e) {
let t;
let n;
await e.policyReady.catch((e) => {
n = { error: e };
});
do {
t = e.readRenewal();
try {
await t;
} catch (e) {
n ??= { error: e };
}
const r = [...e.postToolUseWork];
const i = await Promise.allSettled(r);
for (const [t, a] of i.entries()) {
e.postToolUseWork.delete(r[t]);
if (a.status === "rejected") n ??= { error: a.reason };
}
try {
await drainNativeHookRelayBridge(e.bridge);
} catch (e) {
n ??= { error: e };
}
} while (t !== e.readRenewal() || e.postToolUseWork.size > 0);
if (n) throw n.error;
}
function assertNativeHookRelayRegistrationCurrent(e) {
if (relays$1.get(e.relayId) !== e || Date.now() > e.expiresAtMs) throw new Error("native hook relay registration is inactive");
}
function assertNativeHookRelayForegroundCurrent(e, t, n) {
assertNativeHookRelayRegistrationCurrent(e);
e.signal?.throwIfAborted();
e.assertActive?.();
if (!t.foregroundOpen || t.foregroundToken !== n) throw new Error("native hook relay foreground invocation not allowed");
}
async function resolveNativeHookRelayInvocationBinding(e, t, n, r, i) {
if (!t) throw new Error("native hook relay registration is inactive");
await racePromiseWithAbortSignal(t.policyReady, i);
i?.throwIfAborted();
assertNativeHookRelayRegistrationCurrent(e);
const a = t.retention?.readClaim(r);
if (a && n === "pre_tool_use" && t.retained && t.retention) {
const n = t.retained;
const r = t.retention;
let o;
const assertRetainedAuthority = () => {
assertNativeHookRelayRegistrationCurrent(e);
e.signal?.throwIfAborted();
n.assertActive();
if (o && !o()) throw new Error("native hook relay retained invocation not allowed");
if (!r.allowPreToolUse(a)) throw new Error("native hook relay retained invocation not allowed");
};
const assertActive = () => {
i?.throwIfAborted();
assertRetainedAuthority();
};
if (!t.foregroundOpen && !r.allowPreToolUse(a)) throw new Error("native hook relay retained invocation not allowed");
if (r.awaitForegroundAdmission) {
o = await racePromiseWithAbortSignal(r.awaitForegroundAdmission(a, i), i);
if (!o) throw new Error("native hook relay retained invocation not allowed");
assertActive();
} else if (!r.allowPreToolUse(a)) throw new Error("native hook relay retained invocation not allowed");
return {
registration: {
...e,
assertActive,
assertActiveAsync: void 0,
runBeforeToolCall: n.runBeforeToolCall,
signal: i
},
assertExecutionAdmissionCurrent: assertRetainedAuthority
};
}
if (!t.foregroundOpen) throw new Error("native hook relay foreground invocation not allowed");
const o = t.foregroundToken;
const assertExecutionAdmissionCurrent = () => assertNativeHookRelayForegroundCurrent(e, t, o);
const assertActive = () => {
i?.throwIfAborted();
assertExecutionAdmissionCurrent();
};
return {
registration: {
...e,
assertActive,
signal: i
},
assertExecutionAdmissionCurrent
};
}
//#endregion
//#region src/agents/harness/native-hook-relay.ts
/** Native harness hook event relay and public Plugin SDK facade. */
const DEFAULT_RELAY_TTL_MS = 18e5;
const log = createSubsystemLogger("agents/harness/native-hook-relay");
const { relays, relayBridges, invocations } = nativeHookRelayState;
const RELAY_LIFETIME = "__openclawNativeHookRelayLifetimeV1";
function readRelayLifetime(e) {
return e[RELAY_LIFETIME];
}
function setRelayLifetime(e, t) {
Object.defineProperty(e, RELAY_LIFETIME, {
configurable: true,
value: t
});
}
function scheduleNativeHookRelayExpiry(e, t) {
const n = readRelayLifetime(t);
if (!n) return;
if (n.expiryTimer) clearTimeout(n.expiryTimer);
const rearm = () => {
if (relays.get(e) !== t) return;
const r = (n.expiresAtMonotonicMs ?? t.expiresAtMs) - performance.now();
if (r < 0) {
unregisterNativeHookRelay(e, t);
return;
}
n.expiryTimer = setTimeout(rearm, Math.min(r + 1, MAX_TIMER_TIMEOUT_MS));
n.expiryTimer.unref();
};
rearm();
}
function resolveNativeHookRelayExpiresAtMs(e) {
return resolveExpiresAtMsFromDurationMs(normalizePositiveInteger(e, DEFAULT_RELAY_TTL_MS));
}
function resolveNativeHookRelayMonotonicExpiresAtMs(e) {
const t = normalizePositiveInteger(e, DEFAULT_RELAY_TTL_MS);
if (t === void 0) return;
return performance.now() + t;
}
function registerNativeHookRelay(e) {
return registerNativeHookRelayInternal(e);
}
/** Private-local bundled runtime entrypoint; not exported through the public SDK. */
function registerOwnedNativeHookRelay(e) {
const { retention: t, approvalHost: n, executionAdmission: r, postToolUse: i, ...a } = e;
return registerNativeHookRelayInternal(a, {
retention: t,
approvalHost: n,
executionAdmission: r,
postToolUse: i
});
}
function registerNativeHookRelayInternal(e, t) {
if (e.requirePreToolUse && !e.runBeforeToolCall) throw new Error("Required native PreToolUse relay needs a host runBeforeToolCall capability.");
const { retention: n, approvalHost: r } = t ?? {};
const i = snapshotNativeHookRelayExecutionAdmission(t?.executionAdmission);
const a = t?.postToolUse ? {
toolNames: [...new Set(t.postToolUse.toolNames.map(normalizeNativeHookToolName))],
observe: t.postToolUse.observe
} : void 0;
const o = /* @__PURE__ */ new Set();
pruneExpiredNativeHookRelays();
pruneNativeHookRelayPermissionAllowAlways();
const s = normalizeRelayKey(e.relayId, "id") ?? randomUUID();
const c = normalizeRelayKey(e.generation, "generation") ?? randomUUID();
const l = normalizePositiveInteger(e.generationMismatchGraceMs, 0);
const u = Date.now();
const d = resolveNativeHookRelayExpiresAtMs(e.ttlMs);
const f = resolveNativeHookRelayMonotonicExpiresAtMs(e.ttlMs);
if (d === void 0) throw new Error("Native hook relay expiry is outside the supported Date range");
const p = e.allowedEvents?.length ? [...new Set(e.allowedEvents)] : NATIVE_HOOK_RELAY_EVENTS;
const m = resolveOpenClawStateSqlitePath();
let h;
const g = prepareNativeHookRelayMcpPolicy(e, m, () => h !== void 0 && relays.get(s) === h);
unregisterNativeHookRelay(s, void 0, { deferListenerCloseMs: 250 });
try {
const t = e.runBeforeToolCall && n ? retainBeforeToolCallForNativeHookRelay(e.runBeforeToolCall) : void 0;
let _;
const v = {
relayId: s,
provider: e.provider,
generation: c,
...l > 0 ? { generationMismatchGraceExpiresAtMs: u + l } : {},
...e.agentId ? { agentId: e.agentId } : {},
sessionId: e.sessionId,
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.config ? { config: e.config } : {},
get deferMcpToolApprovals() {
return _;
},
runId: e.runId,
...e.channelId ? { channelId: e.channelId } : {},
...e.requester ? { requester: e.requester } : {},
...e.approvalContext ? { approvalContext: e.approvalContext } : {},
allowedEvents: p,
preToolUseLoopDetection: e.preToolUseLoopDetection !== false,
requirePreToolUse: e.requirePreToolUse,
expiresAtMs: d,
preToolUseFailureProjections: /* @__PURE__ */ new Map(),
...e.signal ? { signal: e.signal } : {},
...e.runBeforeToolCall ? { runBeforeToolCall: e.runBeforeToolCall } : {},
...r ? { approvalHost: r } : {},
...e.assertActive ? { assertActive: e.assertActive } : {},
...e.assertActiveAsync ? { assertActiveAsync: e.assertActiveAsync } : {},
...e.onPreToolUseFailure ? { onPreToolUseFailure: e.onPreToolUseFailure } : {}
};
h = v;
relays.set(s, v);
const y = g.then((e) => {
_ = e;
});
retainNativeHookRelayOperation(s, y);
setRelayLifetime(v, {
foregroundOpen: true,
foregroundToken: Symbol("native-hook-relay-foreground"),
policyReady: y,
expiresAtMonotonicMs: f,
...t ? { retained: t } : {},
...n ? { retention: n } : {},
...i ? { executionAdmission: i } : {},
...a ? { postToolUse: a } : {},
postToolUseWork: o
});
if (e.signal) {
const abort = () => unregisterNativeHookRelay(s, v);
e.signal.addEventListener("abort", abort, { once: true });
readRelayLifetime(v).removeAbortListener = () => e.signal?.removeEventListener("abort", abort);
if (e.signal.aborted) {
unregisterNativeHookRelay(s, v);
throw new Error("native hook relay registration aborted");
}
}
const b = registerNativeHookRelayBridge(v, m, invokeNativeHookRelay);
scheduleNativeHookRelayExpiry(s, v);
let x = Promise.resolve();
const S = Promise.all([b.ready, y]).then(() => void 0);
S.catch(() => void 0);
const C = {
...v,
...buildNativeHookRelayCommandPlan({
...e,
relayId: s,
generation: c,
executionAdmissionToolNames: i?.toolNames,
postToolUseToolNames: a?.toolNames
}),
get deferMcpToolApprovals() {
return _;
},
ready: S,
enableRemoteCallback: () => {
const e = readRelayLifetime(v);
if (!e) throw new Error("native hook relay registration is inactive");
assertNativeHookRelayForegroundCurrent(v, e, e.foregroundToken);
b.remoteEnabled = true;
return { token: b.token };
},
prepareInvocation: async () => {
const e = readRelayLifetime(v);
if (!e) throw new Error("native hook relay registration is inactive");
const t = e.foregroundToken;
assertNativeHookRelayForegroundCurrent(v, e, t);
await y;
await b.ready.catch(() => void 0);
assertNativeHookRelayForegroundCurrent(v, e, t);
},
drain: () => drainNativeHookRelayWork({
policyReady: y,
bridge: b,
readRenewal: () => x,
postToolUseWork: o
}),
renew: (e) => {
const t = relays.get(s);
if (t !== v) return;
const n = resolveNativeHookRelayExpiresAtMs(e);
const r = resolveNativeHookRelayMonotonicExpiresAtMs(e);
if (n === void 0 || r === void 0) return;
x = x.then(async () => {
if (relays.get(s) !== t) return;
if (b.server.listening) try {
const e = await renewNativeHookRelayBridgeRecord(t, b, n);
if (e === "unavailable") return;
if (e === "ownership-changed") {
log.debug("native hook relay bridge record ownership changed", { relayId: s });
unregisterNativeHookRelay(s, t);
return;
}
} catch (e) {
log.debug("failed to renew native hook relay bridge record", {
error: e,
relayId: s
});
return;
}
if (relays.get(s) !== t) return;
t.expiresAtMs = n;
C.expiresAtMs = n;
const e = readRelayLifetime(t);
if (e) e.expiresAtMonotonicMs = r;
scheduleNativeHookRelayExpiry(s, t);
});
},
unregister: () => deactivateNativeHookRelayForeground(s, v)
};
return C;
} catch (e) {
if (h) unregisterNativeHookRelay(s, h);
throw e;
}
}
function unregisterNativeHookRelay(e, t, n) {
if (t && relays.get(e) !== t) return;
const r = t ?? relays.get(e);
if (!r) return;
const i = readRelayLifetime(r);
const a = relayBridges.get(e);
if (relays.get(e) === r) relays.delete(e);
if (i?.expiryTimer) clearTimeout(i.expiryTimer);
i?.removeAbortListener?.();
i?.retained?.release();
delete r[RELAY_LIFETIME];
unregisterNativeHookRelayBridge(e, {
...n,
...a ? { expectedBridge: a } : {}
});
removeNativeHookRelayInvocations(e);
detachNativeHookRelayApprovalState(e)();
try {
i?.retention?.onDispose();
} catch (t) {
log.warn("native hook relay unregister callback failed", {
error: t,
relayId: e
});
}
}
function deactivateNativeHookRelayForeground(e, t) {
if (relays.get(e) !== t) return;
const n = readRelayLifetime(t);
if (!n) return;
n.foregroundOpen = false;
let r = false;
if (n.retained && n.retention) try {
r = n.retention.shouldRetainAfterForegroundClose();
} catch (t) {
try {
log.warn("native hook relay retention predicate failed", {
error: t,
relayId: e
});
} catch {}
}
if (r) {
removeNativeHookRelayPermissionState(e);
return;
}
unregisterNativeHookRelay(e, t);
}
function normalizeRelayKey(e, t) {
const n = e?.trim();
if (!n) return;
if (n.length > 160 || !/^[A-Za-z0-9._:-]+$/u.test(n)) throw new Error(`native hook relay ${t} must be non-empty, compact, and URL-safe`);
return n;
}
async function invokeNativeHookRelay(e, t) {
const n = readNativeHookRelayProvider(e.provider);
const r = readNonEmptyString(e.relayId, "relayId");
const i = readNativeHookRelayEvent(e.event);
const a = relays.get(r);
if (!a) {
pruneExpiredNativeHookRelays();
throw new Error("native hook relay not found");
}
const o = t && a.signal ? AbortSignal.any([t, a.signal]) : t ?? a.signal;
o?.throwIfAborted();
if (Date.now() > a.expiresAtMs) {
unregisterNativeHookRelay(r, a);
throw new Error("native hook relay expired");
}
if (a.provider !== n) throw new Error("native hook relay provider mismatch");
if (e.requireGeneration) {
const t = readNonEmptyString(e.generation, "generation");
if (t !== a.generation) {
if (!canAcceptNativeHookRelayGenerationMismatch(a, t)) throw new Error(NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR);
log.debug("native hook relay accepted bootstrap generation mismatch", {
relayId: r,
event: i,
runId: a.runId
});
}
}
if (!a.allowedEvents.includes(i)) throw new Error("native hook relay event not allowed");
if (!isJsonValue(e.rawPayload)) throw new Error("native hook relay payload must be JSON-compatible");
const s = normalizeNativeHookInvocation({
registration: a,
event: i,
rawPayload: e.rawPayload
});
const { registration: c, assertExecutionAdmissionCurrent: l } = await resolveNativeHookRelayInvocationBinding(a, readRelayLifetime(a), i, e.rawPayload, o);
if (i === "pre_tool_use" || i === "permission_request") c.assertActive?.();
recordNativeHookRelayInvocation(s);
const u = readRelayLifetime(a);
if (i === "post_tool_use" && u?.postToolUse?.toolNames.includes(normalizeNativeHookToolName(s.toolName))) {
l();
const e = Promise.resolve(u.postToolUse.observe(s, l));
u.postToolUseWork.add(e);
retainNativeHookRelayOperation(r, e);
await racePromiseWithAbortSignal(e, o);
}
const d = Date.now();
const f = await racePromiseWithAbortSignal(processNativeHookRelayInvocation({
registration: c,
invocation: s,
executionAdmission: readRelayLifetime(a)?.executionAdmission,
assertExecutionAdmissionCurrent: l
}), o);
if (i === "pre_tool_use" || i === "permission_request") {
await c.assertActiveAsync?.();
c.assertActive?.();
}
if (s.toolUseId && f.failureDisposition && readNativeHookRelayApprovalMode(s.rawPayload) !== "report") projectNativeHookRelayPreToolUseFailure(a, {
toolName: normalizeNativeHookToolName(s.toolName),
toolCallId: s.toolUseId,
disposition: f.failureDisposition,
durationMs: Date.now() - d
});
return f;
}
function projectNativeHookRelayPreToolUseFailure(e, t) {
const n = e.onPreToolUseFailure;
if (!n || e.preToolUseFailureProjections.has(t.toolCallId)) return;
const r = {
promise: Promise.resolve().then(() => n(t)),
settled: false
};
e.preToolUseFailureProjections.set(t.toolCallId, r);
r.promise.then(() => {
r.settled = true;
}, (n) => {
r.settled = true;
if (e.preToolUseFailureProjections.get(t.toolCallId) === r) e.preToolUseFailureProjections.delete(t.toolCallId);
log.debug("native pre-tool failure projection failed", {
error: n,
relayId: e.relayId,
toolCallId: t.toolCallId
});
});
if (e.preToolUseFailureProjections.size > 200) {
let t;
for (const [n, r] of e.preToolUseFailureProjections) {
t ??= n;
if (r.settled) {
e.preToolUseFailureProjections.delete(n);
return;
}
}
if (t) e.preToolUseFailureProjections.delete(t);
}
}
function hasNativeHookRelayInvocation(e) {
const t = e.toolUseId?.trim();
if (!t) return false;
return invocations.some((n) => n.relayId === e.relayId && n.event === e.event && n.toolUseId === t);
}
function recordNativeHookRelayInvocation(e) {
invocations.push({
...e,
rawPayload: snapshotNativeHookRelayPayload(e.rawPayload)
});
if (invocations.length > 200) invocations.splice(0, invocations.length - 200);
}
function removeNativeHookRelayInvocations(e) {
for (let t = invocations.length - 1; t >= 0; t -= 1) if (invocations[t]?.relayId === e) invocations.splice(t, 1);
}
function canAcceptNativeHookRelayGenerationMismatch(e, t) {
const n = e.generationMismatchGraceExpiresAtMs;
if (typeof n !== "number" || Date.now() > n) return false;
if (e.generationMismatchGraceAcceptedGeneration) return e.generationMismatchGraceAcceptedGeneration === t;
e.generationMismatchGraceAcceptedGeneration = t;
return true;
}
function pruneExpiredNativeHookRelays(e = Date.now()) {
for (const [t, n] of relays) if (e > n.expiresAtMs) unregisterNativeHookRelay(t, n);
}
const testing = {
async clearNativeHookRelaysForTests() {
for (const [e, t] of relays) unregisterNativeHookRelay(e, t);
await clearNativeHookRelayBridgesForTests();
invocations.length = 0;
clearNativeHookRelayPermissionsForTests();
},
getNativeHookRelayInvocationsForTests() {
return [...invocations];
},
getNativeHookRelayRegistrationForTests(e) {
return relays.get(e);
},
async getNativeHookRelayBridgeRecordForTests(e) {
const t = await readNativeHookRelayBridgeRecordIfExists(e);
return t ? { ...t } : void 0;
},
formatPermissionApprovalDescriptionForTests: formatPermissionApprovalDescription,
permissionRequestContentFingerprintForTests: permissionRequestContentFingerprint,
setNativeHookRelayPermissionApprovalRequesterForTests,
setNativeHookRelayDeferredToolApprovalRequesterForTests
};
/** Token-scoped dedicated-harness callback; never accepts Gateway operator credentials. */
async function dispatchNativeHookRelayHttpCallback(e, t) {
const n = /^\/__openclaw__\/native-hook\/([A-Za-z0-9_-]+)$/.exec(e.url ?? "");
const r = n?.[1];
const i = r ? relays.get(r) : void 0;
const a = r ? nativeHookRelayState.relayBridges.get(r) : void 0;
if (e.method !== "POST" || !n) {
t.writeHead(404).end();
return;
}
if (!i || !a?.remoteEnabled) {
log.warn("native hook remote callback refused", {
relayId: r,
status: 403
});
t.writeHead(403).end();
return;
}
await handleNativeHookRelayBridgeRequest(e, t, {
provider: i.provider,
relayId: i.relayId,
token: a.token,
registration: i,
bridge: a,
invokeRelay: invokeNativeHookRelay,
remote: true
});
}
//#endregion
export { registerOwnedNativeHookRelay as a, resolveNativeHookRelayDeferredToolApproval as c, registerNativeHookRelay as i, buildNativeHookRelayCommand as l, hasNativeHookRelayInvocation as n, testing as o, invokeNativeHookRelay as r, buildNativeHookRelayCommandPlan as s, dispatchNativeHookRelayHttpCallback as t };