openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
242 lines (241 loc) • 13.8 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { c as withPluginRuntimeGatewayContextResolver, o as getPluginRuntimeGatewayRequestScope, r as getInProcessGatewayRequestContext } from "./gateway-request-scope-BvvDhs5D.mjs";
import { a as captureExternalSessionCommitGuard, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { i as requesterCreatorProfileId } from "./requester-origin-DG-fk-U0.mjs";
import { s as resolveLeastPrivilegeOperatorScopesForMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import { l as resolveGatewayToolOperatorSelection, m as withoutGatewayToolCallerIdentity, o as getGatewayToolCallerIdentity, t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs";
import { m as readQuestionDispatchCapability } from "./host-private-capabilities-DDumj0c_.mjs";
import { a as bindInProcessSubagentResume, o as readInProcessSubagentResume } from "./server-plugin-runtime-client-DE2ydcEw.mjs";
import { l as runWithGatewaySessionSpawnContext, t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { r as createCronMutationCompletion } from "./mutation-completion-Dxq3k_3J.mjs";
import { a as runWithOperatorToolGatewayContinuationContext, i as runWithOperatorToolGatewayCleanupContext, s as withInProcessAgentRuntimeIdentity, t as captureOperatorToolGatewayContinuationContext } from "./server-plugin-in-process-authority-6ufuLah5.mjs";
import { n as readInProcessSessionDeliveryGeneration } from "./in-process-session-delivery-BHvKFyYB.mjs";
import { u as retainInternalApprovalCommitGuard } from "./session-mutation-guards-Bjnk_O0z.mjs";
import { i as isHostPluginApprovalMethod, r as isGatewayWorkerApprovalMethod } from "./approval-gateway-runtime-methods-DlYB_jEJ.mjs";
import { t as dispatchGatewayMethodInProcess } from "./server-plugin-in-process-dispatch-B-bx4bU2.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/gateway/session-send-delivery.ts
const admission = resolveGlobalSingleton(Symbol.for("openclaw.sessionSendDeliveryAdmission"), () => new AsyncLocalStorage());
/** Only the in-process communication owner may attach live delivery facts. */
function withSessionSendDelivery(e, t) {
return admission.run(e, t);
}
/** Carry invocation-time delivery facts through a previously captured caller context. */
function bindSessionSendDeliveryContext(e) {
const t = admission.getStore();
return () => admission.run(t, e);
}
function readSessionSendDeliveryAdmission(e) {
const t = admission.getStore();
return t?.delivery.runId === e.runId && t.delivery.target.sessionKey === e.sessionKey && t.delivery.target.sessionId === e.sessionId && t.delivery.target.agentId === e.agentId ? t : void 0;
}
//#endregion
//#region src/agents/tools/in-process-gateway.ts
const agentToolGatewayRuntimeIdentities = /* @__PURE__ */ new WeakMap();
/** Carry trusted runtime identity without making it enumerable or transportable. */
function withAgentToolGatewayRuntimeIdentity(e, t) {
if (!t) return e;
const n = { ...e };
agentToolGatewayRuntimeIdentities.set(n, t);
return bindInProcessSubagentResume(n, readInProcessSubagentResume(e));
}
const DEFAULT_IN_PROCESS_GATEWAY_REQUEST_TIMEOUT_MS = 1e4;
function callerGatewayContextResolver(e) {
return e ?? getGatewayToolCallerIdentity()?.gatewayContextResolver;
}
/** Transfer already-owned cleanup to its Gateway, without retaining the finished turn. */
function runWithGatewayToolCleanupContext(e, t) {
const n = callerGatewayContextResolver(t);
return withoutGatewayToolCallerIdentity(() => runWithOperatorToolGatewayCleanupContext(() => n ? withPluginRuntimeGatewayContextResolver(n, e) : e()));
}
/** Transfers accepted reply work to a bounded source-authority hold, not the tool lifetime. */
async function runWithGatewayToolContinuationContext(e, t) {
const n = callerGatewayContextResolver();
if (t?.retainRequester) {
const t = captureOperatorToolGatewayContinuationContext(void 0, { retainRequester: true });
if (t) {
const n = await t;
try {
return await n.runWithRequester(e);
} finally {
n.release();
}
}
}
return runWithOperatorToolGatewayContinuationContext(() => withoutGatewayToolCallerIdentity(() => n ? withPluginRuntimeGatewayContextResolver(n, e) : e()));
}
function bindInProcessGatewayContext(e, t) {
const n = t();
if (!n) throw new Error(`Gateway instance unavailable for ${e}`);
const assertCurrent = () => {
if (t() !== n) throw new Error(`Gateway instance unavailable for ${e}`);
};
return {
assertCurrent,
resolve: () => {
assertCurrent();
return n;
}
};
}
async function runBoundInProcessGatewayCall(e, t, n, r = true, i) {
const assertCurrent = (t = false) => {
e?.assertCurrent();
if (!t || (i ? !i.isCommitted() : r)) n?.();
};
try {
assertCurrent();
const n = i ? await i.run(() => t(e?.resolve)) : await t(e?.resolve);
assertCurrent(true);
return n;
} catch (e) {
assertCurrent(true);
throw e;
}
}
function hasInProcessGatewayToolContext() {
return Boolean(getInProcessGatewayRequestContext(callerGatewayContextResolver()));
}
/** Whether Gateway routing belongs to this caller or the hosting process. */
function hasGatewayToolRoutingContext() {
const e = callerGatewayContextResolver() ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
const t = getInProcessGatewayRequestContext(e);
return t?.localEmbedded !== true && Boolean(e || t);
}
function getInProcessGatewayToolContext(e) {
return getInProcessGatewayRequestContext(callerGatewayContextResolver(e));
}
/**
* Dispatches a request-shaped built-in tool call through the local Gateway
* router without opening a loopback transport. Outside a Gateway process, the
* same request falls back to the ordinary Gateway client.
*/
async function callAgentToolGatewayRequestBound(e, t, n, r, i = false, a = true, o) {
const s = e.method;
const c = e.sessionCreation ?? o?.sessionCreation;
const l = e.assertDispatchCurrent;
const u = o ? void 0 : createCronMutationCompletion(s);
const d = r && Object.assign(() => r(s), r);
const f = r || l || (!a || u) && e.signal ? composeSessionSourceAssertion([d, l], (t) => {
t();
if (!a || u) e.signal?.throwIfAborted();
}) : void 0;
f?.();
const p = t ? bindInProcessGatewayContext(s, t) : void 0;
const m = e.scopes ?? resolveLeastPrivilegeOperatorScopesForMethod(s, e.params);
if (i || !getInProcessGatewayRequestContext(p?.resolve)) {
if (e.agentToolCaller?.requesterOrigin) throw new Error("Requester provenance requires trusted in-process Gateway dispatch.");
if (p && !i) throw new Error(`Gateway instance unavailable for ${s}`);
if (getGatewayToolCallerIdentity()?.operatorAuthority) throw new Error("operator run authority requires its admitted Gateway");
if (e.sessionCreation) throw new Error("Trusted session creation requires its admitted in-process Gateway.");
if (o) return await runBoundInProcessGatewayCall(p, () => o.fallback(m), f);
if (e.sessionMutationCommitGuard) throw new Error("Guarded session control requires its admitted in-process Gateway.");
if (readInProcessSessionDeliveryGeneration(e.params)) throw new Error("Session-bound delivery requires its admitted in-process Gateway.");
if (readInProcessSubagentResume(e)) throw new Error("Task resume requires trusted in-process Gateway dispatch.");
if (n) throw new Error("trusted agent runtime identity requires in-process Gateway dispatch");
const { callGateway: t } = await import("./call-CT5jlfNe.mjs");
const { agentRunTracking: r, agentToolCaller: c, sessionCreation: l, sessionMutationCommitGuard: u, replyExpectation: d, ...h } = e;
return await runBoundInProcessGatewayCall(p, () => t({
...h,
method: s,
assertDispatchCurrent: readQuestionDispatchCapability(e.assertDispatchCurrent)?.assertCompatibilityCurrent ?? e.assertDispatchCurrent
}), f, a);
}
const h = e.scopes === void 0 ? "minimum" : "exact";
const g = e.timeoutMs === null ? void 0 : e.timeoutMs ?? DEFAULT_IN_PROCESS_GATEWAY_REQUEST_TIMEOUT_MS;
const _ = s === "sessions.create" && (c?.via === "spawn" || c?.via === "operator" && c.requesterSessionKey === e.agentToolCaller?.sessionKey) && e.agentToolCaller !== void 0;
let v = f && !_ ? composeSessionSourceAssertion([f, captureExternalSessionCommitGuard(e.sessionMutationCommitGuard)]) : captureExternalSessionCommitGuard(e.sessionMutationCommitGuard);
if (isGatewayWorkerApprovalMethod(s) && !e.sessionMutationCommitGuard && !l) v = retainInternalApprovalCommitGuard(composeSessionSourceAssertion([v]));
const y = {
prepareDispatchCurrent: e.prepareDispatchCurrent,
...e.replyExpectation ? { replyExpectation: e.replyExpectation } : {},
forceSyntheticClient: true,
operatorRoleActor: { kind: "system" },
...isHostPluginApprovalMethod(s) && n?.approvalOwnerPluginId ? { allowHostPluginApprovalRequest: true } : {},
...e.agentRunTracking ? { agentRunTracking: e.agentRunTracking } : {},
...e.agentToolCaller ? { agentToolCaller: e.agentToolCaller } : {},
...c ? { sessionCreation: c } : {},
...o?.onExecution ? { onExecution: o.onExecution } : {},
syntheticScopes: m,
syntheticScopeMode: h,
...e.expectFinal !== void 0 ? { expectFinal: e.expectFinal } : {},
...e.onAccepted ? { onAccepted: e.onAccepted } : {},
...e.onSignalAbort ? { onSignalAbort: () => runWithGatewayToolCleanupContext(() => e.onSignalAbort?.((e, n, r) => callAgentToolGatewayRequestBound({
method: e,
params: n,
...r
}, p?.resolve ?? t, void 0, void 0)), p?.resolve ?? t) } : {},
...e.signal && a && !u ? { signal: e.signal } : {},
...g !== void 0 ? { timeoutMs: g } : {},
...p ? { resolveGatewayContext: p.resolve } : {},
...v ? { sessionMutationCommitGuard: v } : {}
};
return await runBoundInProcessGatewayCall(p, async () => await dispatchGatewayMethodInProcess(s, e.params ?? {}, bindInProcessSubagentResume(withInProcessAgentRuntimeIdentity(y, n), readInProcessSubagentResume(e))), f, a, u);
}
/** Capture one Gateway and caller for a multi-request operation. */
function bindAgentToolGatewayRequest(e) {
const t = getPluginRuntimeGatewayRequestScope();
const n = callerGatewayContextResolver(e?.resolveGatewayContext) ?? t?.resolveGatewayContext;
const r = getInProcessGatewayRequestContext(n);
const i = n ? () => n() === r ? r : void 0 : r ? () => r : void 0;
const a = captureGatewayToolCallerAssertion();
const o = AsyncLocalStorage.snapshot();
return async (t) => await o(bindSessionSendDeliveryContext(() => callAgentToolGatewayRequestBound(t, i, agentToolGatewayRuntimeIdentities.get(t), a, !n && !r || e?.hostedOnly === true && r?.localEmbedded === true, e?.revalidateOnCompletion)));
}
const callAgentToolGatewayRequest = async (e) => await bindAgentToolGatewayRequest()(e);
async function callInProcessGatewayToolBound(e, t, n) {
const r = captureGatewayToolCallerAssertion();
const i = getGatewayToolCallerIdentity();
return await callAgentToolGatewayRequestBound({
method: e,
params: t,
agentToolCaller: n.sessionCreation?.via === "spawn" && i && r ? {
agentId: i.agentId,
sessionKey: i.sessionKey,
executionIdentityToken: i.executionIdentityToken,
requesterOrigin: resolveGatewayToolOperatorSelection({ requireRequesterOrigin: true }).requesterOrigin,
assertCurrent: r
} : void 0,
sessionMutationCommitGuard: n.sessionMutationCommitGuard,
signal: n.signal,
timeoutMs: n.timeoutMs ?? null
}, callerGatewayContextResolver(n.resolveGatewayContext), void 0, r, false, true, {
sessionCreation: n.sessionCreation,
onExecution: n.onExecution,
fallback: async (r) => {
const i = n.sessionCreation;
if (i?.childSessionPublication) throw new Error("Automatic public work sessions require the live in-process Gateway.");
const a = n.timeoutMs == null ? {} : { timeoutMs: n.timeoutMs };
const dispatch = (i) => callGatewayTool(e, a, t, {
scopes: r,
...i ? { requireAgentRuntimeIdentity: i } : {},
...n.signal ? { signal: n.signal } : {}
});
if (i?.via !== "spawn" || !i.inheritedToolPolicy) return await dispatch();
return await runWithGatewaySessionSpawnContext({
...i.requesterProfileId ? { requesterProfileId: i.requesterProfileId } : {},
...i.gitContributorProfileId ? { gitContributorProfileId: i.gitContributorProfileId } : {},
...i.completionOwnerSessionKey ? { completionOwnerSessionKey: i.completionOwnerSessionKey } : {},
requesterSenderIsOwner: i.requesterSenderIsOwner,
inheritedToolPolicy: i.inheritedToolPolicy,
...i.inheritedPermissionMode ? { inheritedPermissionMode: i.inheritedPermissionMode } : {},
...i.resolvedModel ? { resolvedModel: i.resolvedModel } : {},
...i.spawnModelAutoSelection ? { spawnModelAutoSelection: i.spawnModelAutoSelection } : {}
}, () => dispatch(true));
}
});
}
const callInProcessGatewayTool = async (e, t, n = {}) => await callInProcessGatewayToolBound(e, t, n);
async function callInProcessGatewayToolWithCreation(e, t, n, r = {}) {
const i = resolveGatewayToolOperatorSelection().operatorAuthority?.profileId ?? n.requesterProfileId ?? requesterCreatorProfileId(getGatewayToolCallerIdentity()?.requesterOrigin);
const a = n.via === "spawn" && i ? {
...n,
requesterProfileId: i
} : n;
return await callInProcessGatewayToolBound(e, t, {
...r,
sessionCreation: a
});
}
//#endregion
export { getInProcessGatewayToolContext as a, runWithGatewayToolCleanupContext as c, readSessionSendDeliveryAdmission as d, withSessionSendDelivery as f, callInProcessGatewayToolWithCreation as i, runWithGatewayToolContinuationContext as l, callAgentToolGatewayRequest as n, hasGatewayToolRoutingContext as o, callInProcessGatewayTool as r, hasInProcessGatewayToolContext as s, bindAgentToolGatewayRequest as t, withAgentToolGatewayRuntimeIdentity as u };