UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

648 lines (647 loc) • 23.6 kB
import { d as normalizeOptionalThreadValue, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { t as getActivePluginGatewayNodePolicyRegistry } from "./runtime-state-DVrhXeqI.mjs"; import { n as recordRuntimeActionDecision } from "./runtime-action-decision-B14EMX8j.mjs"; import { i as sanitizeExecApprovalWarningText, n as sanitizeExecApprovalDisplayText } from "./exec-approval-text-sanitize-Xx3Q87a8.mjs"; import { t as sanitizeApprovalScope } from "./approval-scope-DOnX7GXe.mjs"; import { c as resolvePluginApprovalTimeoutMs } from "./plugin-approvals-DAqwCYQr.mjs"; import { t as resolveCanonicalPluginApprovalRequestAllowedDecisions } from "./plugin-approval-canonical-decisions-CVZjVlcb.mjs"; import { l as resolveNodeCommandAllowlist, o as isNodeCommandAllowed } from "./node-command-policy-DkH-pkTr.mjs"; import { t as NODE_INVOKE_NOT_READY } from "./node-registry.invoke-stream-pPc5-Kl3.mjs"; import { t as bindApprovalRequesterMetadata } from "./approval-shared-C8HrUVTB.mjs"; import { t as handlePendingApprovalRequestWithDelivery } from "./approval-request-delivery-2N7Slhd-.mjs"; import { t as ApprovalObserverClosedError } from "./exec-approval-lifecycle-vt4J5MXl.mjs"; import { randomUUID } from "node:crypto"; //#region src/gateway/node-invoke-placement-grant.ts function isBindingCurrentForOwner(e, t) { try { e.assertCurrent(t); return true; } catch { return false; } } async function resolveRuntimePlacementGrant(e, t) { if (e.resolveAsync) return e.resolveAsync(t); const n = e.resolveBinding(t); const r = n ? e.validate(n) : void 0; return { binding: n, ...r?.outcome === "consumed" ? { approvalId: r.grant.mintedByApprovalId } : {} }; } async function resolveNodeInvokePlacementGrant(e) { const { owner: t, runtime: n, requestedDecisions: r } = e; const i = r?.includes("allow-always") === true && t && e.approvalScope !== void 0 && e.risk?.level === "high" && e.nodeSession.pairingGeneration && n ? await resolveRuntimePlacementGrant(n, { pluginId: e.pluginId, command: e.command, approvalScope: e.approvalScope, agentId: t.agentId, sessionKey: t.sessionKey, nodeId: e.nodeSession.nodeId, pairingGeneration: e.nodeSession.pairingGeneration }) : { binding: null }; const { binding: a } = i; const o = a && t && isBindingCurrentForOwner(t, a) ? a : null; if (o && i.approvalId) return { kind: "granted", binding: o, approvalId: i.approvalId }; return { kind: "prompt", binding: o, allowedDecisions: r?.includes("allow-always") === true && !o ? r.filter((e) => e !== "allow-always") : r }; } async function retainResolvedNodeInvokePlacementGrant(e) { const { runtime: t, decision: n, owner: r, authorization: i } = e; const a = e.binding ? { ...e.binding } : null; if (n !== "allow-always" || !a) return true; const o = t?.consumeAsync ? void 0 : t?.validateAsync ? await t.validateAsync(a) : t?.validate(a); if (!r || !isBindingCurrentForOwner(r, a) || !t?.consumeAsync && o?.outcome !== "consumed") return false; i.binding = a; return true; } function consumeNodeInvokePlacementGrant(e) { if (!e.authorization.binding) return "not-required"; try { return e.runtime?.consume(e.authorization.binding).outcome === "consumed" ? "consumed" : "rejected"; } catch { return "rejected"; } } async function prepareNodeInvokePlacementGrant(e) { const t = e.authorization.binding; if (!t || !e.runtime?.consumeAsync) return true; try { return (await e.runtime.consumeAsync(t)).outcome === "consumed"; } catch { return false; } } //#endregion //#region src/gateway/node-invoke-plugin-approval.ts function sanitizeOptionalMeta(e) { const t = normalizeOptionalString(e); return t ? sanitizeExecApprovalDisplayText(t) : null; } function normalizeRouteThreadId(e) { if (typeof e === "number" && Number.isFinite(e)) return e; return normalizeOptionalString(e) ?? null; } function createPluginNodeInvokeApprovalRuntime(e) { const t = e.context.pluginApprovalManager; if (!t) return; return { async request(n) { const r = resolvePluginApprovalTimeoutMs(n.timeoutMs); const i = { turnSourceChannel: normalizeOptionalString(e.turnSource?.channel) ?? null, turnSourceTo: normalizeOptionalString(e.turnSource?.to) ?? null, turnSourceAccountId: normalizeOptionalString(e.turnSource?.accountId) ?? null, turnSourceThreadId: normalizeRouteThreadId(e.turnSource?.threadId) }; const a = e.callerIdentity; const o = e.client?.internal?.pluginRuntimeOwnerId === e.pluginId ? e.client.internal.nodeInvokeApprovalSessionKey : void 0; if (!e.isCurrent()) throw new Error("agent runtime approval authority is no longer active"); const s = n.allowedDecisions === void 0 ? void 0 : resolveCanonicalPluginApprovalRequestAllowedDecisions({ allowedDecisions: n.allowedDecisions }); const c = e.placementGrantAuthority; const l = c ? { agentId: c.agentId, sessionKey: c.sessionKey, assertCurrent: (e) => c.assertCurrent({ pluginId: e.pluginId, command: e.command, nodeId: e.nodeId, workspace: { workspaceDir: e.cwd, environmentId: e.environmentId, sessionId: e.sessionId, ownerEpoch: e.ownerEpoch, sessionKey: e.sessionKey } }) } : void 0; const u = await resolveNodeInvokePlacementGrant({ runtime: e.context.placementStandingGrants, requestedDecisions: s, owner: l, pluginId: e.pluginId, command: e.command, ...e.approvalScope ? { approvalScope: e.approvalScope } : {}, risk: e.risk, nodeSession: e.nodeSession }); if (!e.isCurrent()) throw new Error("agent runtime approval authority is no longer active"); if (u.kind === "granted") { e.standingGrantAuthorization.binding = u.binding; return { id: u.approvalId, decision: "allow-always" }; } const { allowedDecisions: d, binding: f } = u; const p = { pluginId: e.pluginId, title: truncateUtf16Safe(sanitizeExecApprovalDisplayText(normalizeOptionalString(n.title) ?? ""), 80), description: truncateUtf16Safe(sanitizeExecApprovalWarningText(normalizeOptionalString(n.description) ?? ""), 256), scope: n.scope ? sanitizeApprovalScope(n.scope) : null, severity: n.severity ?? "warning", ...d === void 0 ? {} : { allowedDecisions: d }, toolName: sanitizeOptionalMeta(n.toolName), toolCallId: normalizeOptionalString(n.toolCallId) ?? null, agentId: a?.agentId ?? c?.agentId ?? sanitizeOptionalMeta(n.agentId), sessionKey: a?.sessionKey ?? c?.sessionKey ?? o ?? normalizeOptionalString(n.sessionKey) ?? null, runId: a?.operationalRunInstance.runId ?? c?.runId ?? null, placementGrant: f, ...i }; const m = t.create(p, r, `plugin:${randomUUID()}`); if (a) { m.agentRuntimeDelegatedAuthority = a.delegatedAuthority; if (a.executionIdentity) m.executionIdentityToken = a.executionIdentity; } if (f && l) m.approvalAuthority = () => { l.assertCurrent(f); return true; }; bindApprovalRequesterMetadata({ record: m, client: e.client }); const respond = () => {}; const { decision: h } = await t.register(m, r); await handlePendingApprovalRequestWithDelivery({ approvalKind: "plugin", manager: t, record: m, respond, context: e.context, twoPhase: false, forwardRequest: e.context.forwardPluginApprovalRequest, getIosPushDelivery: () => e.context.pluginApprovalIosPushDelivery, source: "node-policy" }); let g = t.projectDecisionIfActive(m.id, await h); if (!e.isCurrent()) return { id: m.id, decision: null }; if (g === "allow-once" && !await t.consumeAllowOnce(m.id, `plugin.node.invoke:${m.id}`)) return { id: m.id, decision: null }; g = t.projectDecisionIfActive(m.id, g); if (!await retainResolvedNodeInvokePlacementGrant({ runtime: e.context.placementStandingGrants, decision: g, binding: f, owner: l, authorization: e.standingGrantAuthorization })) return { id: m.id, decision: null }; return { id: m.id, decision: e.isCurrent() ? g : null }; } }; } //#endregion //#region src/gateway/node-invoke-readiness.ts const READINESS_RETRY_DELAYS_MS = [ 100, 250, 500, 1e3 ]; /** Recover only an explicit rejection before native execution, inside the RPC's authority. */ async function invokeNodeWithReadinessRetry(e, t) { let n = t.deadlineAtMs ?? (t.timeoutMs !== void 0 && Number.isFinite(t.timeoutMs) && t.timeoutMs > 0 ? performance.now() + t.timeoutMs : void 0); const timedOut = () => ({ ok: false, error: { code: "TIMEOUT", message: "node invoke timed out" } }); for (let r = 0;; r += 1) { const i = n === void 0 ? t.timeoutMs : Math.max(0, n - performance.now()); if (n !== void 0 && i === 0) return timedOut(); const a = await e.invoke({ ...t, timeoutMs: i, deadlineAtMs: n, onDispatchReady: (e, r) => { if (r !== void 0 && (n === void 0 || r < n)) n = r; t.onDispatchReady?.(e, r); } }); const o = READINESS_RETRY_DELAYS_MS[r]; if (a.ok || a.error?.code !== "NODE_NOT_READY" || o === void 0) return a; try { await sleep(n === void 0 ? o : Math.min(o, Math.max(0, n - performance.now())), t.signal); } catch (e) { if (n !== void 0 && performance.now() >= n) return timedOut(); if (t.signal?.aborted) return { ok: false, error: { code: "ABORTED", message: "node invoke cancelled" } }; throw e; } } } //#endregion //#region src/gateway/node-invoke-plugin-policy.ts function parsePayload(e, t) { if (!e) return t; try { return JSON.parse(e); } catch { return t; } } function findDangerousPluginNodeCommand(e, t) { const n = t.trim(); if (!n) return null; return e?.nodeHostCommands?.find((e) => e.command.dangerous === true && e.command.command.trim() === n) ?? null; } function validateRiskClassification(e) { const t = normalizeOptionalString(e?.family); if (e?.level !== "ordinary" && e?.level !== "high" || !t || !/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(t)) return null; return { level: e.level, family: t }; } function resolveStandingApprovalScope(e) { const t = asOptionalRecord(e); const n = normalizeOptionalString(t?.scope); return t?.kind === "placement" && n && /^[a-z0-9][a-z0-9._-]{0,63}$/u.test(n) ? n : void 0; } /** Applies the registered plugin policy for a node.invoke command, if one exists. */ async function applyPluginNodeInvokePolicy(e) { const t = getActivePluginGatewayNodePolicyRegistry(); const n = e.agentRuntimeIdentity ?? e.client?.internal?.agentRuntimeIdentity; const r = n?.executionIdentity; const isCallerRuntimeAuthorityActive = () => !n || e.context.validateAgentRuntimeApprovalAuthority?.(n) === true; const i = randomUUID(); let a = 0; const recordNodeDecision = (t) => { a += 1; recordRuntimeActionDecision({ token: r, family: "node", operation: "invoke", outcome: t.outcome, coverageState: t.coverageState, reasonCode: t.reasonCode, owner: "node-runtime", decisionBoundary: "gateway.node-invoke-plugin-policy", policyRefs: [ "node:pairing", "node:command-capability", "plugin:node-invoke-policy" ], summary: t.summary, missingEvidence: t.missingEvidence, remediation: t.remediation ?? [], discriminator: JSON.stringify([ t.pluginId, e.nodeSession.nodeId, e.command, i, a ]) }); }; const o = n && e.turnSource ? { channel: normalizeOptionalString(e.turnSource.channel), to: normalizeOptionalString(e.turnSource.to), accountId: normalizeOptionalString(e.turnSource.accountId), threadId: normalizeOptionalThreadValue(e.turnSource.threadId) } : void 0; const s = t?.nodeInvokePolicies?.find((t) => t.policy.commands.includes(e.command)); if (!s) { const n = findDangerousPluginNodeCommand(t, e.command); if (n) { recordNodeDecision({ pluginId: n.pluginId, outcome: "denied", coverageState: "enforced", reasonCode: "node_plugin_policy_missing", summary: "A dangerous plugin-owned node command was denied because its policy was missing." }); return { ok: false, code: "PLUGIN_POLICY_MISSING", message: `node.invoke ${e.command} is registered as dangerous by plugin ${n.pluginId} but has no plugin node.invoke policy`, details: { nodeCommandDispatched: false } }; } return null; } let c; if (s.policy.classifyRisk) { try { c = validateRiskClassification(s.policy.classifyRisk({ command: e.command, params: e.params })) ?? void 0; } catch {} if (!c) { recordNodeDecision({ pluginId: s.pluginId, outcome: "denied", coverageState: "enforced", reasonCode: "node_risk_classification_failed", summary: "A plugin-owned node command was denied before transport after risk classification failed." }); return { ok: false, code: "PLUGIN_POLICY_RISK_CLASSIFICATION_FAILED", message: `node.invoke ${e.command} arguments could not be classified by plugin ${s.pluginId}`, details: { nodeCommandDispatched: false } }; } } const l = resolveStandingApprovalScope(s.policy.standingApproval); let u = false; let d = false; const f = {}; const p = t?.plugins.find((e) => e.id === s.pluginId); const m = s.policy; const isPluginCurrent = () => getActivePluginGatewayNodePolicyRegistry() === t && s.policy === m && t?.nodeInvokePolicies.includes(s) === true && (!p || t.plugins.includes(p) && p.enabled && p.status === "loaded"); const dispatchNode = async (t = {}, n) => { const deny = (e, t) => { d = true; recordNodeDecision({ pluginId: s.pluginId, outcome: "denied", coverageState: "enforced", reasonCode: e, summary: "A plugin-owned node command was denied at the Gateway dispatch gate." }); return { ok: false, ...t }; }; n?.assertCurrent(); if (!isCallerRuntimeAuthorityActive()) return deny("node_runtime_authority_closed", { code: "APPROVAL_AUTHORITY_CLOSED", message: "agent runtime approval authority closed before node dispatch" }); if (e.isInvocationCurrent && !await e.isInvocationCurrent()) return deny("node_pairing_changed", { code: "PAIRING_CHANGED", message: "node pairing changed before dispatch" }); const r = e.nodeSession.pairingGeneration ? e.context.nodeRegistry.getForPairingGeneration(e.nodeSession.nodeId, e.nodeSession.pairingGeneration) : e.context.nodeRegistry.get(e.nodeSession.nodeId); if (!r || r.connId !== e.nodeSession.connId) return deny("node_route_changed", { code: "ROUTE_CHANGED", message: "node connection changed before dispatch" }); if (r.client.invalidated === true) return deny("node_pairing_changed", { code: "PAIRING_CHANGED", message: "node pairing changed before dispatch" }); const resolveCommandAuthorization = () => { const t = e.privateTransport?.commands ? [...e.privateTransport.commands] : r.commands; return isNodeCommandAllowed({ command: e.command, declaredCommands: t, allowlist: resolveNodeCommandAllowlist(e.context.getRuntimeConfig(), { ...r, approvedCommands: t }) }); }; const i = resolveCommandAuthorization(); if (!i.ok) return deny("node_command_revoked", { code: "NODE_COMMAND_REVOKED", message: `node command not allowed at dispatch: ${i.reason}`, details: { command: e.command, reason: i.reason } }); const a = e.resolveRemainingTimeoutMs?.(); if (a === 0 && e.timeoutMs !== 0) return deny("node_dispatch_timeout", { code: "TIMEOUT", message: "node invoke timed out" }); const c = t.timeoutMs ?? e.timeoutMs; const l = typeof a === "number" && a > 0 ? typeof c === "number" && c > 0 ? Math.min(c, a) : a : c; const p = e.deadlineAtMs === void 0 ? void 0 : typeof c === "number" && c > 0 ? Math.min(e.deadlineAtMs, performance.now() + c) : e.deadlineAtMs; n?.assertCurrent(); if (e.privateTransport?.isCurrent() === false) return deny("node_private_owner_closed", { code: "PRIVATE_OWNER_CLOSED", message: "private node invocation owner closed before dispatch" }); if (!isPluginCurrent()) return deny("node_plugin_replaced", { code: "PLUGIN_POLICY_CHANGED", message: "node plugin policy changed before dispatch" }); if (!isCallerRuntimeAuthorityActive()) return deny("node_runtime_authority_closed", { code: "APPROVAL_AUTHORITY_CLOSED", message: "agent runtime approval authority closed before node dispatch" }); if (e.isApprovalAuthorityActive?.() === false) return deny("node_approval_authority_closed", { code: "APPROVAL_AUTHORITY_CLOSED", message: "approved runtime authority closed before node dispatch" }); recordNodeDecision({ pluginId: s.pluginId, outcome: "allowed", coverageState: "enforced", reasonCode: "node_dispatch_gate_allowed", summary: "Gateway node pairing, capability, and plugin policy gates allowed transport dispatch." }); d = true; const m = { nodeId: e.nodeSession.nodeId, expectedConnId: e.nodeSession.connId, ...e.nodeSession.pairingGeneration ? { expectedPairingGeneration: e.nodeSession.pairingGeneration } : {}, command: e.command, params: t.params ?? e.params, ...o ? { turnSource: o } : {}, timeoutMs: l, ...n ? { signal: e.signal ? AbortSignal.any([e.signal, n.signal]) : n.signal } : e.signal ? { signal: e.signal } : {}, ...e.sessionKey ? { sessionKey: e.sessionKey } : {}, idempotencyKey: t.idempotencyKey ?? e.idempotencyKey, ...e.nodeInvokeStream && { onProgress: e.nodeInvokeStream.onProgress, idleTimeoutMs: e.nodeInvokeStream.idleTimeoutMs }, ...f.binding ? { authorizeDispatch: () => prepareNodeInvokePlacementGrant({ runtime: e.context.placementStandingGrants, authorization: f }) } : {}, isDispatchAuthorized: () => { try { n?.assertCurrent(); } catch { return false; } if (!(isPluginCurrent() && e.privateTransport?.isCurrent() !== false && (e.nodeInvokeStream?.isRuntimeCurrent() ?? true) && isCallerRuntimeAuthorityActive() && e.isApprovalAuthorityActive?.() !== false && resolveCommandAuthorization().ok)) return false; const t = consumeNodeInvokePlacementGrant({ runtime: e.context.placementStandingGrants, authorization: f }); if (t === "rejected") return false; if (t === "consumed") recordNodeDecision({ pluginId: s.pluginId, outcome: "allowed", coverageState: "enforced", reasonCode: "node_placement_standing_grant_consumed", summary: "A placement-scoped standing grant authorized the node transport dispatch." }); return true; }, onDispatchReady: (t) => { u = true; e.onNodeCommandDispatched?.(); e.nodeInvokeStream?.onDispatchReady(t); } }; const h = e.privateTransport ? await e.privateTransport.invoke(m) : await invokeNodeWithReadinessRetry(e.context.nodeRegistry, { ...m, deadlineAtMs: p }); if (!h.ok) { if (u) recordNodeDecision({ pluginId: s.pluginId, outcome: "unknown", coverageState: "unknown", reasonCode: "node_action_completion_unknown", summary: "The node transport accepted the action but did not report a successful outcome.", missingEvidence: ["node.action_completion"], remediation: [{ code: "inspect_node_action", text: "Inspect the paired node before retrying an action whose completion is unknown." }] }); return { ok: false, code: h.error?.code, message: h.error?.message ?? "node command failed", details: { nodeError: h.error ?? null } }; } recordNodeDecision({ pluginId: s.pluginId, outcome: "allowed", coverageState: "attribution-only", reasonCode: "node_action_completed", summary: "The paired node reported successful completion; this is attribution, not authorization." }); return { ok: true, payload: parsePayload(h.payloadJSON, h.payload), payloadJSON: h.payloadJSON ?? null }; }; const h = getPluginRuntimeGatewayRequestScope(); const g = e.nodeInvokeStream && e.client?.internal?.pluginRuntimeOwnerId === s.pluginId ? h?.invokeWithSessionNodeAuthority : void 0; const invokeOwned = (t, n, r) => g && n.workspace ? g({ pluginId: s.pluginId, command: e.command, nodeId: e.nodeSession.nodeId, workspace: n.workspace, source: t }, async (t, i) => { if (e.sessionKey !== n.workspace?.sessionKey) throw new Error("Node launch requires its authenticated outer session"); return await dispatchNode(r ? { ...n, params: r() } : n, { assertCurrent: t, signal: i }); }) : void 0; const invokeNode = async (e = {}) => { if (!g || !e.workspace) return await dispatchNode(e); const t = await invokeOwned("human-approved", e); if (!t) throw new Error("Node launch lost its admitted owner"); return t; }; let _; try { _ = await s.policy.handle({ nodeId: e.nodeSession.nodeId, command: e.command, params: e.params, timeoutMs: e.timeoutMs, idempotencyKey: e.idempotencyKey, config: e.context.getRuntimeConfig(), pluginConfig: s.pluginConfig, node: { nodeId: e.nodeSession.nodeId, displayName: e.nodeSession.displayName, platform: e.nodeSession.platform, deviceFamily: e.nodeSession.deviceFamily, caps: e.nodeSession.caps, commands: e.nodeSession.commands }, client: e.client ? { connId: e.client.connId, scopes: filterStringEntries(e.client.connect?.scopes) } : null, ...c ? { risk: c } : {}, approvals: createPluginNodeInvokeApprovalRuntime({ context: e.context, client: e.client, callerIdentity: n, pluginId: s.pluginId, command: e.command, ...l ? { approvalScope: l } : {}, nodeSession: e.nodeSession, risk: c, standingGrantAuthorization: f, ...h?.nodePlacementGrantAuthority ? { placementGrantAuthority: h.nodePlacementGrantAuthority } : {}, turnSource: o, isCurrent: () => isPluginCurrent() && isCallerRuntimeAuthorityActive() && e.privateTransport?.isCurrent() !== false && e.isApprovalAuthorityActive?.() !== false }), invokeNode, ...g ? { invokeNodeWithSessionFull: async ({ workspace: e, createParams: t }) => await invokeOwned("session-full", { workspace: e }, t) } : {} }); } catch (e) { if (!(e instanceof ApprovalObserverClosedError) && !u && isCallerRuntimeAuthorityActive()) recordNodeDecision({ pluginId: s.pluginId, outcome: "denied", coverageState: "enforced", reasonCode: "node_plugin_policy_failed", summary: "The registered plugin policy failed closed before node transport dispatch." }); throw e; } if (!u && !d && isCallerRuntimeAuthorityActive()) recordNodeDecision({ pluginId: s.pluginId, outcome: _.ok ? "unknown" : "denied", coverageState: _.ok ? "unknown" : "enforced", reasonCode: _.ok ? "node_action_callback_missing" : "node_plugin_policy_denied", summary: _.ok ? "The plugin policy returned without invoking the expected OpenClaw node callback." : "The registered plugin policy denied node transport dispatch.", missingEvidence: _.ok ? ["node.action_callback"] : [], remediation: _.ok ? [{ code: "add_node_action_callback", text: "Route the native action through the provided OpenClaw node callback." }] : [] }); return _.ok ? _ : { ..._, details: { ..._.details, nodeCommandDispatched: u } }; } //#endregion export { invokeNodeWithReadinessRetry as n, applyPluginNodeInvokePolicy as t };