UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

343 lines (342 loc) • 17.6 kB
import { t as asNonArrayRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as runWithAsyncStore } from "./async-store-C6naia_Y.mjs"; import { t as AsyncContext } from "./async-context-BYDAvG9A.mjs"; import { n as captureGatewayContextResolver, o as getGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs"; import { O as validateAgentRunDelegatedAuthority } from "./agent-run-registry-D7vkrqFT.mjs"; import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { i as requesterCreatorProfileId, t as captureRequesterOrigin } from "./requester-origin-DG-fk-U0.mjs"; import { a as captureAdmittedRunActiveAssertion, l as getAdmittedRunDelegatedAuthority, p as readAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import { n as intersectSessionPermissionModes } from "./session-permission-exec-mode-vqqWNPSg.mjs"; import { t as intersectSessionToolOverrides } from "./session-tool-overrides-CLYOZ-eE.mjs"; import { u as wrapAgentToolExecutionContext } from "./agent-tool-metadata-nrQgRaqv.mjs"; import { c as captureActiveEmbeddedRunPersonalToolParticipants } from "./run-state-jrY5s7TG.mjs"; import { m as readToolStringParam } from "./common-njQNtpnW.mjs"; //#region src/auto-reply/reply/session-event-policy.ts /** A delayed producer can retain restrictions, never replace current session authority. */ function narrowSessionEventSettings(e, t) { return { permissionMode: intersectSessionPermissionModes(e?.permissionMode, t?.permissionMode), toolOverrides: intersectSessionToolOverrides(e?.toolOverrides, t?.toolOverrides) }; } //#endregion //#region src/agents/tools/gateway-caller-context.ts const gatewayToolCallerStorage = new AsyncContext(Symbol("gatewayToolCaller")); const receiptAdmissionStorage = new AsyncContext(Symbol("gatewayToolReceiptAdmission")); function evaluateGatewayToolCallerReceiptAdmission(e, t) { return (receiptAdmissionStorage.getStore()?.get(e) ?? t)(); } function composeReceiptAuthority(...e) { const t = e.filter((t, n) => t !== void 0 && e.indexOf(t) === n); const n = t.map((e) => captureGatewayToolReceiptAssertion(e)); return t.length === 0 ? void 0 : Object.assign(() => { let e = true; for (const n of t) try { e = n() !== false && e; } catch { e = false; } return e; }, composeSessionSourceAssertion(n), { assertScopeCurrent: () => { for (const e of n) (e.assertScopeCurrent ?? e)(); } }); } /** Preserve boolean refusal across the receipt owner's prepared assertion. */ function captureGatewayToolReceiptAssertion(e, t = "agent tool caller authority is no longer active") { const assertAllowed = (e) => { if (e === false) throw new Error(t); }; const n = e.prepareSessionSource?.bind(e); return Object.assign(() => assertAllowed(e()), { nativeSource: e.nativeSource, opaqueCommitGuard: e.opaqueCommitGuard, assertScopeCurrent: e.assertScopeCurrent?.bind(e), prepareSessionSourceScope: e.prepareSessionSourceScope?.bind(e), ...n ? { async prepareSessionSource() { const e = await n(); const t = e.release?.bind(e); const r = e.assertPreparedCurrent?.bind(e); return { ...e, nativeSource: e.nativeSource, opaqueCommitGuard: e.opaqueCommitGuard, checks: e.checks, assertCurrent: () => assertAllowed(e.assertCurrent()), ...r ? { assertPreparedCurrent: () => assertAllowed(r()) } : {}, ...t ? { release: t } : {} }; } } : {} }); } /** Builds host-owned Gateway authority from the exact admitted execution. */ function createAdmittedGatewayToolCallerIdentity(e) { const t = e.agentId?.trim(); const n = e.sessionKey?.trim(); if (!t || !n) return; const r = getAdmittedRunDelegatedAuthority(e.admittedRunContext); const i = readAdmittedRunOperatorAuthority(e.admittedRunContext); return { agentId: t, sessionKey: n, requesterOrigin: captureRequesterOrigin({ requesterOrigin: e.requesterOrigin }), operationalRunInstance: e.admittedRunContext.operationalRunInstance, ...r ? { approvalAuthority: r } : {}, ...i ? { operatorAuthority: i } : {}, ...e.receiptAuthority ? { approvalAuthorityCheck: e.receiptAuthority } : {}, ...e.cronAuthorityCheck ? { cronAuthorityCheck: e.cronAuthorityCheck } : {}, executionIdentityToken: e.admittedRunContext.executionIdentityToken, gatewayContextResolver: captureGatewayContextResolver(getGatewayContextResolver(e.admittedRunContext)), receiptAuthority: composeReceiptAuthority((r && captureAdmittedRunActiveAssertion(e.admittedRunContext, r)) ?? (() => false), e.receiptAuthority), ...e.receiptAdmission ? { receiptAdmissions: [e.receiptAdmission] } : {}, ...e.approvalSignals?.length ? { approvalSignals: e.approvalSignals } : {}, ...e.mintCronRequesterGrant ? { mintCronRequesterGrant: e.mintCronRequesterGrant } : {}, turnSourceChannel: e.turnSourceChannel, turnSourceLocal: e.turnSourceLocal, turnSourceTo: e.turnSourceTo, turnSourceAccountId: e.turnSourceAccountId, turnSourceThreadId: e.turnSourceThreadId }; } function getGatewayToolCallerIdentity() { return gatewayToolCallerStorage.getStore(); } /** Selection is model input; only the turn's host-owned participants grant a target. */ async function withGatewayPersonalToolUser(e, t) { const n = getGatewayToolCallerIdentity(); if (!n) { if (e !== void 0) throw new Error("Selecting user requires an active personal-tool turn."); return await t(); } return await runWithAsyncStore(gatewayToolCallerStorage, { ...n, personalToolUser: e, personalToolIdentityScoped: true, personalToolSelection: void 0 }, t); } /** One prepared identity per tool call; execution, approvals and receipts stay turn-owned. */ function resolveGatewayToolOperatorSelection(e) { const t = getGatewayToolCallerIdentity(); let n = t?.personalToolSelection; if (!n) { const e = t?.personalToolUser !== void 0 ? resolveGatewayPersonalToolParticipant() : void 0; const r = e?.profileId !== t?.operatorAuthority?.profileId ? e : void 0; const i = r?.operatorAuthority ?? t?.operatorAuthority; n = Object.freeze({ operatorAuthority: i, requesterOrigin: r?.requesterOrigin ? captureRequesterOrigin({ requesterOrigin: { ...r.requesterOrigin, delegatedCreatorProfileId: requesterCreatorProfileId(t?.requesterOrigin) ?? null } }) : r ? void 0 : t?.requesterOrigin, assertCurrent: composeSessionSourceAssertion([e?.assertCurrent, i?.assertCurrent]) }); if (t?.personalToolIdentityScoped) t.personalToolSelection = n; } if (e?.requireRequesterOrigin && n.operatorAuthority && n.operatorAuthority.profileId !== t?.operatorAuthority?.profileId && n.requesterOrigin?.operatorProfileId !== n.operatorAuthority.profileId) throw new Error("Selected user's requester identity is unavailable; ask them in a new turn."); return n; } /** The accepting collector already holds this source independently of the spawning turn. */ function withGatewayToolOperatorContinuation(e, t) { const n = getGatewayToolCallerIdentity(); if (!n) return t(); const { operatorAuthority: r, requesterOrigin: i } = e; r?.assertCurrent(); return runWithAsyncStore(gatewayToolCallerStorage, { ...n, personalToolParticipants: void 0, personalToolUser: void 0, personalToolIdentityScoped: true, personalToolSelection: Object.freeze({ operatorAuthority: r, requesterOrigin: i, assertCurrent: composeSessionSourceAssertion([r?.assertCurrent]) }) }, t); } function resolveGatewayPersonalToolParticipant(e, t) { const n = getGatewayToolCallerIdentity(); if (n?.personalToolParticipants) return n.personalToolParticipants.resolve(t?.requireSingleParticipant ? void 0 : n.personalToolUser); if (n?.personalToolUser !== void 0) throw new Error("Selecting user requires an active personal-tool turn."); if (e) { const t = captureActiveEmbeddedRunPersonalToolParticipants(e); if (!t) return; const n = t.participants?.resolve(); return n && { ...n, assertCurrent: composeSessionSourceAssertion([t.assertCurrent, n.assertCurrent]) }; } } /** Capture the admitted run and worker owner, independently of optional audit collection. */ function captureGatewayToolCallerAssertion(e) { const t = getGatewayToolCallerIdentity(); if (!t?.operationalRunInstance) return; const n = t.receiptAuthority; const r = t.approvalSignals ?? []; const i = t.personalToolIdentityScoped ? resolveGatewayToolOperatorSelection() : void 0; const assertMethod = (e) => { if (e?.startsWith("cron.") && t.cronAuthorityCheck?.() === false) throw new Error("Automation caller authority is no longer active."); }; const a = composeSessionSourceAssertion([ i?.assertCurrent, i?.operatorAuthority === t.operatorAuthority ? void 0 : t.operatorAuthority?.assertCurrent, composeSessionSourceAssertion(n ? [captureGatewayToolReceiptAssertion(n)] : [], (e) => { try { if (!n || r.some((e) => e.aborted)) throw new Error("agent tool caller authority is no longer active"); e(); } catch { throw new Error("agent tool caller authority is no longer active"); } }) ], (t) => { t(); assertMethod(e); }); return Object.assign((t = e) => { a(); if (t !== e) assertMethod(t); }, a); } /** Watch admission preserves opaque lifecycle assertions while moving registered row predicates. */ async function prepareGatewayToolCallerAssertion() { const e = getGatewayToolCallerIdentity(); const t = captureGatewayToolCallerAssertion(); const n = [...new Set(e?.receiptAdmissions ?? [])]; const r = await Promise.all(n.map((e) => e.prepare())); const i = new Map(n.map((e, t) => [e, () => r[t].isCurrent()])); let a = true; const assertCurrent = () => { if (!a) throw new Error("agent tool caller admission is no longer active"); runWithAsyncStore(receiptAdmissionStorage, i, () => t?.()); }; assertCurrent(); return { assertCurrent, ...r.length ? { sessionEntriesCurrent: { sources: r.flatMap((e) => e.current.sources), assertCurrent(e) { let t = 0; for (const n of r) { n.current.assertCurrent(e.slice(t, t + n.current.sources.length)); t += n.current.sources.length; } assertCurrent(); } } } : {}, release() { a = false; i.clear(); } }; } /** Process-owned work must not retain the turn that authorized its launch. */ function withoutGatewayToolCallerIdentity(e) { return gatewayToolCallerStorage.exit(e); } async function withGatewayToolCallerIdentity(e, t) { if (!e?.agentId?.trim() || !e.sessionKey?.trim()) return await t(); const n = gatewayToolCallerStorage.getStore(); const r = e.operationalRunInstance; const i = n?.operationalRunInstance; const a = !r || i === r ? n : void 0; const inheritedValue = (t) => a?.[t] ?? e[t]; let o = a?.approvalAuthority ?? e.approvalAuthority; if (a?.approvalAuthority && e.approvalAuthority && a.approvalAuthority !== e.approvalAuthority) { if (validateAgentRunDelegatedAuthority(e.approvalAuthority, a.approvalAuthority)) o = e.approvalAuthority; else if (!validateAgentRunDelegatedAuthority(a.approvalAuthority, e.approvalAuthority)) throw new Error("agent tool caller approval scopes do not retain the same source"); } const s = [.../* @__PURE__ */ new Set([...a?.receiptAdmissions ?? [], ...e.receiptAdmissions ?? []])]; const c = [...new Set([a?.assertToolAllowed, e.assertToolAllowed].filter((e) => e !== void 0))]; const l = c.length ? (e) => { for (const t of c) t(e); } : void 0; const u = [.../* @__PURE__ */ new Set([...a?.approvalSignals ?? [], ...e.approvalSignals ?? []])]; return await runWithAsyncStore(gatewayToolCallerStorage, { agentId: a?.agentId ?? e.agentId.trim(), sessionKey: a?.sessionKey ?? e.sessionKey.trim(), watchdogAttempt: e.watchdogAttempt ?? a?.watchdogAttempt, requesterOrigin: a?.requesterOrigin ?? e.requesterOrigin, sessionEventDelivery: a?.sessionEventDelivery === false || e.sessionEventDelivery === false ? false : void 0, sessionEventSettings: e.sessionEventSettings && a?.sessionEventSettings ? narrowSessionEventSettings(a.sessionEventSettings, e.sessionEventSettings) : e.sessionEventSettings ?? a?.sessionEventSettings, sessionEventToolsAllow: e.sessionEventToolsAllow && a?.sessionEventToolsAllow ? e.sessionEventToolsAllow.filter((e) => a.sessionEventToolsAllow.includes(e)) : e.sessionEventToolsAllow ?? a?.sessionEventToolsAllow, workspaceBaseRefreshSandbox: inheritedValue("workspaceBaseRefreshSandbox"), workspacePrAdoptionSessionId: inheritedValue("workspacePrAdoptionSessionId"), workspaceEvidenceSandbox: inheritedValue("workspaceEvidenceSandbox"), personalToolParticipants: inheritedValue("personalToolParticipants"), personalToolUser: inheritedValue("personalToolUser"), personalToolIdentityScoped: inheritedValue("personalToolIdentityScoped"), personalToolSelection: inheritedValue("personalToolSelection"), fullPermission: a?.fullPermission === false || e.fullPermission === false ? false : inheritedValue("fullPermission"), assertAutoApproveChangesCurrent: a?.assertAutoApproveChangesCurrent || e.assertAutoApproveChangesCurrent ? () => { a?.assertAutoApproveChangesCurrent?.(); e.assertAutoApproveChangesCurrent?.(); } : void 0, operationalRunInstance: inheritedValue("operationalRunInstance"), embeddedRunToolAuthorityBinding: e.embeddedRunToolAuthorityBinding ?? a?.embeddedRunToolAuthorityBinding, approvalAuthority: o, operatorAuthority: inheritedValue("operatorAuthority"), approvalAuthorityCheck: inheritedValue("approvalAuthorityCheck"), approvalOwnerPluginId: e.approvalOwnerPluginId?.trim() || a?.approvalOwnerPluginId || void 0, signedAgentRuntimeIdentityToken: (a?.signedAgentRuntimeIdentityToken ?? e.signedAgentRuntimeIdentityToken?.trim()) || void 0, cronSelfManagementJobId: (e.cronSelfManagementJobId?.trim() ?? a?.cronSelfManagementJobId) || void 0, cronToolsAllowCapture: e.cronToolsAllowCapture ?? a?.cronToolsAllowCapture, cronExecToolTarget: e.cronExecToolTarget ?? a?.cronExecToolTarget, cronCreatorAuthorityGrant: e.cronCreatorAuthorityGrant ?? a?.cronCreatorAuthorityGrant, mintCronRequesterGrant: inheritedValue("mintCronRequesterGrant"), cronManagementGrant: e.cronManagementGrant ?? a?.cronManagementGrant, cronAuthorityCheck: composeReceiptAuthority(a?.cronAuthorityCheck, e.cronAuthorityCheck), executionIdentityToken: inheritedValue("executionIdentityToken"), receiptAuthority: composeReceiptAuthority(a?.receiptAuthority, e.receiptAuthority), receiptAdmissions: s.length ? s : void 0, assertToolAllowed: l, approvalSignals: u.length ? u : void 0, workerTurnClaim: inheritedValue("workerTurnClaim"), workerTurnExecutionIdentityCapability: inheritedValue("workerTurnExecutionIdentityCapability"), gatewayContextResolver: a?.gatewayContextResolver ?? captureGatewayContextResolver(e.gatewayContextResolver), gatewayUiCommandTarget: inheritedValue("gatewayUiCommandTarget"), turnSourceChannel: (a?.turnSourceChannel ?? e.turnSourceChannel?.trim()) || void 0, turnSourceLocal: inheritedValue("turnSourceLocal"), turnSourceTo: (a?.turnSourceTo ?? e.turnSourceTo?.trim()) || void 0, turnSourceAccountId: (a?.turnSourceAccountId ?? e.turnSourceAccountId?.trim()) || void 0, turnSourceThreadId: inheritedValue("turnSourceThreadId") }, t); } /** Narrows one host-owned approval call to the exact registered policy/harness owner. */ async function withGatewayToolApprovalOwner(e, t) { const n = gatewayToolCallerStorage.getStore(); const r = e?.trim(); if (!n || !r) return await t(); return await withGatewayToolCallerIdentity({ ...n, approvalOwnerPluginId: r }, t); } function wrapToolWithGatewayCallerIdentity(e, t) { if (!t?.agentId?.trim() || !t.sessionKey?.trim() || !e.execute) return e; return wrapAgentToolExecutionContext(e, (...n) => withGatewayToolCallerIdentity(t, () => e.execute?.(...n)), (e) => withGatewayToolCallerIdentity(t, e), (e) => wrapToolWithGatewayCallerIdentity(e, t)); } function createGatewayToolCallerWrapper(e, t) { const n = e && t?.agentSessionKey?.trim() ? { agentId: e, sessionKey: t.agentSessionKey.trim(), gatewayUiCommandTarget: t.gatewayUiCommandTarget, turnSourceChannel: t.agentChannel, turnSourceTo: t.currentMessagingTarget ?? t.currentChannelId ?? t.agentTo, turnSourceAccountId: t.agentAccountId, turnSourceThreadId: t.currentThreadTs ?? t.agentThreadId } : void 0; return (e) => wrapToolWithGatewayCallerIdentity(e, n); } /** Opt an identity-scoped tool into participant selection, including unnamed calls. */ function wrapGatewayPersonalToolExecution(e) { return async (...t) => await withGatewayPersonalToolUser(readToolStringParam(asNonArrayRecord(t[1]) ?? {}, "user"), async () => { const n = getGatewayToolCallerIdentity(); const r = resolveGatewayToolOperatorSelection(); r.assertCurrent(); const i = await e(...t); if (n?.personalToolParticipants) r.assertCurrent(); return i; }); } //#endregion export { narrowSessionEventSettings as _, evaluateGatewayToolCallerReceiptAdmission as a, resolveGatewayPersonalToolParticipant as c, withGatewayToolApprovalOwner as d, withGatewayToolCallerIdentity as f, wrapToolWithGatewayCallerIdentity as g, wrapGatewayPersonalToolExecution as h, createGatewayToolCallerWrapper as i, resolveGatewayToolOperatorSelection as l, withoutGatewayToolCallerIdentity as m, captureGatewayToolReceiptAssertion as n, getGatewayToolCallerIdentity as o, withGatewayToolOperatorContinuation as p, createAdmittedGatewayToolCallerIdentity as r, prepareGatewayToolCallerAssertion as s, captureGatewayToolCallerAssertion as t, withGatewayPersonalToolUser as u };