openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
486 lines (485 loc) • 14.8 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { i as isApprovalMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { u as readConnectErrorDetailCode } from "./connect-error-details-BdhXf496.mjs";
import { t as startGatewayClientWhenEventLoopReady } from "./readiness-tJvtmnC1.mjs";
import { n as isGatewayNativeApprovalMethod } from "./approval-gateway-runtime-methods-DlYB_jEJ.mjs";
import { t as getGatewayNativeApprovalRuntime } from "./approval-gateway-runtime-context-B9yxaZi6.mjs";
import { t as buildChannelApprovalNativeTargetKey } from "./approval-native-target-key-D0y5fYMe.mjs";
import { n as createApprovalNativeRouteReporter } from "./approval-native-route-coordinator-Dm94seHh.mjs";
import { h as normalizeApprovalRequest, t as classifyApprovalRequestChannelRouteAsync } from "./approval-request-account-binding-DOCAr58L.mjs";
import { t as createOperatorApprovalsGatewayClient } from "./operator-approvals-client-CqzKpK3v.mjs";
import { t as createPendingApprovalRegistry } from "./pending-approval-registry-DDiENhk3.mjs";
//#region src/infra/approval-native-delivery.ts
/** Resolves the origin and approver-DM targets a channel should use for native approvals. */
async function resolveChannelNativeApprovalDeliveryPlan(e) {
const t = e.adapter;
const n = {
targets: [],
originTarget: null,
notifyOriginWhenDmOnly: false
};
if (!t) return n;
const deliveryContext = () => ({
cfg: e.cfg,
accountId: e.accountId,
approvalKind: e.approvalKind,
request: e.request
});
const r = await t.describeDeliveryCapabilities(deliveryContext());
if (!r.enabled) return n;
const i = r.supportsOriginSurface && t.resolveOriginTarget ? await t.resolveOriginTarget(deliveryContext()) ?? null : null;
const a = r.supportsApproverDmSurface && t.resolveApproverDmTargets ? await t.resolveApproverDmTargets(deliveryContext()) : [];
const o = [];
const s = r.preferredSurface === "origin" || r.preferredSurface === "both";
const c = r.preferredSurface === "approver-dm" || r.preferredSurface === "both";
if (s && i) o.push({
surface: "origin",
target: i,
reason: "preferred"
});
if (c || !i) for (const e of a) o.push({
surface: "approver-dm",
target: e,
reason: c ? "preferred" : "fallback"
});
return {
targets: dedupeByKey(o, (e) => buildChannelApprovalNativeTargetKey(e.target)),
originTarget: i,
notifyOriginWhenDmOnly: r.preferredSurface === "approver-dm" && r.notifyOriginWhenDmOnly === true && i !== null
};
}
//#endregion
//#region src/infra/exec-approval-channel-runtime.ts
/** Error raised when the gateway pauses approval reconnects after a terminal startup failure. */
var ExecApprovalChannelRuntimeTerminalStartError = class extends Error {
constructor(e, t) {
super(`native approval gateway client paused reconnect after startup auth failure (${e.detailCode ?? "unknown"}): gateway closed (${e.code}): ${e.reason}`, t === void 0 ? void 0 : { cause: t });
this.name = "ExecApprovalChannelRuntimeTerminalStartError";
this.detailCode = e.detailCode;
}
};
/** Narrows terminal approval runtime startup failures for bootstrap retry policy. */
function isExecApprovalChannelRuntimeTerminalStartError(e) {
return e instanceof ExecApprovalChannelRuntimeTerminalStartError;
}
const APPROVAL_EVENT_PREFIXES = [
["exec", "exec"],
["plugin", "plugin"],
["system-agent", "openclaw"]
];
function readGatewayConnectErrorDetailCode(e) {
if (!e || typeof e !== "object") return null;
return readConnectErrorDetailCode(e.details);
}
/** Creates the gateway-backed approval runtime that tracks pending requests and finalization. */
function createExecApprovalChannelRuntime(e) {
const t = createSubsystemLogger(e.label);
const n = e.nowMs ?? Date.now;
const r = new Set(e.eventKinds ?? ["exec"]);
const i = getGatewayNativeApprovalRuntime();
const a = createPendingApprovalRegistry();
let o = null;
let s;
let c = null;
let l = false;
let u = false;
let d = null;
let f = null;
const spawn = (e, n) => {
n.catch((n) => {
const r = formatErrorMessage(n);
t.error(`${e}: ${r}`);
});
};
const stopClientIfInactive = (e) => {
if (u) return false;
o = null;
e.stop();
return true;
};
const finalizeExpiredEntry = async (n) => {
t.debug(`expired ${n.id}`);
await e.finalizeExpired?.(n.value);
};
const handleExpired = async (e) => {
const t = a.remove(e);
if (!t) return;
await finalizeExpiredEntry(t);
};
const handleRequested = async (r, i) => {
if (i?.ignoreIfInactive && !u) return;
const o = normalizeApprovalRequest(r);
if (a.has(o.id)) {
t.debug(`ignored duplicate request ${o.id}`);
return;
}
const s = a.begin(o.id, {
request: o,
entries: []
});
let c;
try {
const n = i?.alreadyAccepted === true ? true : e.shouldHandle(o);
if (!(typeof n === "boolean" ? n : await n) || i?.ignoreIfInactive && !u || !a.isCurrent(s) || s.queued) {
a.remove(o.id, s);
return;
}
t.debug(`received request ${o.id}`);
c = await e.deliverRequested(o);
} catch (e) {
a.remove(o.id, s);
throw e;
}
if (!c.length) {
a.remove(o.id, s);
return;
}
await a.completeDelivery(s, {
request: o,
entries: c
});
const l = Math.max(0, o.expiresAtMs - n());
a.scheduleExpiry(s, l, (e) => {
spawn("error handling approval expiration", finalizeExpiredEntry(e));
});
};
const handleResolved = async (n) => {
if ("terminalStatus" in n && n.terminalStatus === "expired") {
await handleExpired(n.id);
return;
}
const r = a.settle(n.id, async (r) => {
t.debug(`resolved ${n.id} with ${n.decision}`);
await e.finalizeResolved({
request: r.value.request,
resolved: n,
entries: r.value.entries
});
});
if (r.status === "taken") await r.terminal(r.entry);
};
const handleGatewayEvent = (e) => {
if (APPROVAL_EVENT_PREFIXES.some(([t, n]) => e.event === `${n}.approval.requested` && r.has(t))) {
spawn("error handling approval request", handleRequested(e.payload, { ignoreIfInactive: true }));
return;
}
if (APPROVAL_EVENT_PREFIXES.some(([t, n]) => e.event === `${n}.approval.resolved` && r.has(t))) spawn("error handling approval resolved", handleResolved(e.payload));
};
const replayPendingApprovals = async (e, t) => {
try {
for (const n of APPROVAL_EVENT_PREFIXES.flatMap(([e, t]) => r.has(e) ? [`${t}.approval.list`] : [])) {
if (t && stopClientIfInactive(t)) return;
const r = await e.request(n, {});
if (t && stopClientIfInactive(t)) return;
for (const e of r) {
if (t && stopClientIfInactive(t)) return;
await handleRequested(e, { ignoreIfInactive: true });
}
}
} catch (e) {
if (!u) return;
throw e;
}
};
const startPendingApprovalReplay = (e, n) => {
const r = replayPendingApprovals(e, n).catch((e) => {
const n = formatErrorMessage(e);
t.error(`error replaying pending approvals: ${n}`);
}).finally(() => {
if (f === r) f = null;
});
f = r;
};
return {
async start() {
if (l) return;
if (d) {
await d;
return;
}
u = true;
d = (async () => {
if (!await e.isConfigured()) {
t.debug("disabled");
return;
}
if (!u) return;
if (i) {
await e.beforeGatewayClientStart?.();
s = i;
c = s.subscribe({
eventKinds: r,
shouldHandle: (t) => {
if (!u) return false;
const n = e.shouldHandle(t);
return typeof n === "boolean" ? n && u : n.then((e) => e && u);
},
onRequested: (e) => {
spawn("error handling approval request", handleRequested(e, {
ignoreIfInactive: true,
alreadyAccepted: true
}));
},
onResolved: (e) => {
spawn("error handling approval resolved", handleResolved(e));
}
});
if (!u) {
c();
c = null;
s = void 0;
return;
}
l = true;
startPendingApprovalReplay({ request: s.request });
return;
}
const n = createDeferredCore();
let a = null;
const d = await createOperatorApprovalsGatewayClient({
config: e.cfg,
gatewayUrl: e.gatewayUrl,
clientDisplayName: e.clientDisplayName,
onEvent: handleGatewayEvent,
onHelloOk: () => {
t.debug("connected to gateway");
n.resolve();
},
onConnectError: (e) => {
t.error(`connect error: ${e.message}`);
a = e;
if (readGatewayConnectErrorDetailCode(e)) return;
n.reject(e);
},
onReconnectPaused: (e) => {
n.reject(new ExecApprovalChannelRuntimeTerminalStartError(e, a));
},
onClose: (e, r) => {
t.debug(`gateway closed: ${e} ${r}`);
n.reject(a ?? /* @__PURE__ */ new Error(`gateway closed: ${e} ${r}`));
}
});
if (!u) {
d.stop();
return;
}
await e.beforeGatewayClientStart?.();
o = d;
try {
const e = await startGatewayClientWhenEventLoopReady(d, { clientOptions: {} });
if (!e.ready) throw new Error(e.aborted ? "gateway approval runtime start aborted before readiness" : "gateway readiness unavailable before exec approval runtime start");
await n.promise;
if (stopClientIfInactive(d)) return;
l = true;
startPendingApprovalReplay(d, d);
} catch (e) {
o = null;
l = false;
d.stop();
throw e;
}
})().finally(() => {
d = null;
});
await d;
},
async stop() {
u = false;
if (d) await d.catch(() => {});
const n = l || o !== null || f !== null;
l = false;
c?.();
c = null;
s = void 0;
o?.stop();
o = null;
await f?.catch(() => {});
a.clear();
await e.onStopped?.();
if (n) t.debug("stopped");
},
handleRequested,
handleResolved,
handleExpired,
async request(t, n) {
if (!isApprovalMethod(t)) throw new Error(`${e.label}: operator approvals runtime cannot dispatch ${t}; use a write-capable gateway client`);
if (s) {
if (!isGatewayNativeApprovalMethod(t)) throw new Error(`${e.label}: Gateway-owned approval runtime cannot dispatch ${t}`);
return await s.request(t, n, { clientDisplayName: e.clientDisplayName });
}
if (!o) throw new Error(`${e.label}: gateway client not connected`);
return await o.request(t, n);
}
};
}
//#endregion
//#region src/infra/approval-native-runtime.ts
/** Creates a channel-native approval runtime with synchronous availability callbacks. */
function createChannelNativeApprovalRuntime(e) {
return createChannelNativeApprovalRuntimeAsync(e);
}
/** Creates the shared gateway approval runtime backed by channel-native delivery hooks. */
function createChannelNativeApprovalRuntimeAsync(e) {
const t = e.nowMs ?? Date.now;
const n = new Set(e.eventKinds ?? ["exec"]);
const r = getGatewayNativeApprovalRuntime();
const i = (r?.routeCoordinator.createReporter ?? createApprovalNativeRouteReporter)({
handledKinds: n,
channel: e.channel,
channelLabel: e.channelLabel,
accountId: e.accountId,
shouldHandle: (t) => e.shouldHandle(t),
classifyRoute: (t) => classifyApprovalRequestChannelRouteAsync({
cfg: e.getRequestConfig?.(t) ?? e.cfg,
request: t,
channel: e.channel ?? ""
}),
requestGateway: async (t, n) => {
if (r) {
if (t !== "send") throw new Error(`native approval route cannot dispatch ${t}`);
return await r.requestRoute(t, n);
}
const { callGatewayLeastPrivilege: i } = await import("./call-CT5jlfNe.mjs");
return await i({
config: e.cfg,
...e.gatewayUrl ? { url: e.gatewayUrl } : {},
method: t,
params: n,
clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
mode: GATEWAY_CLIENT_MODES.BACKEND
});
}
});
const finalize = (e) => async (t) => {
try {
await e(t);
} finally {
i.completeRequest(t.request.id);
}
};
const a = createExecApprovalChannelRuntime({
label: e.label,
clientDisplayName: e.clientDisplayName,
cfg: e.cfg,
gatewayUrl: e.gatewayUrl,
eventKinds: e.eventKinds,
isConfigured: e.isConfigured,
shouldHandle: async (t) => {
const n = e.resolveApprovalKind?.(t) ?? t.approvalKind;
const r = await i.selectRequest({
approvalKind: n,
request: t
});
if (r.kind === "selected") return true;
i.reportSkipped({
approvalKind: n,
request: t,
reason: r.kind === "selector-error" ? "ineligible" : r.kind
});
if (r.kind === "selector-error") throw r.error;
return false;
},
finalizeResolved: finalize((t) => e.finalizeResolved(t)),
finalizeExpired: e.finalizeExpired ? finalize((t) => e.finalizeExpired?.(t)) : void 0,
onStopped: e.onStopped,
beforeGatewayClientStart: () => {
i.start();
},
nowMs: t,
deliverRequested: async (n) => {
const r = e.resolveApprovalKind?.(n) ?? n.approvalKind;
let a = {
targets: [],
originTarget: null,
notifyOriginWhenDmOnly: false
};
let o = [];
try {
const i = await e.buildPendingContent({
request: n,
approvalKind: r,
nowMs: t()
});
const s = await resolveChannelNativeApprovalDeliveryPlan({
cfg: e.getRequestConfig?.(n) ?? e.cfg,
accountId: e.accountId,
approvalKind: r,
request: n,
adapter: e.nativeAdapter
});
const c = /* @__PURE__ */ new Set();
const l = [];
const u = [];
for (const t of s.targets) {
const a = {
plannedTarget: t,
request: n,
approvalKind: r,
pendingContent: i
};
try {
const n = await e.prepareTarget({ ...a });
if (!n) continue;
if (c.has(n.dedupeKey)) {
e.onDuplicateSkipped?.({
...a,
preparedTarget: n
});
continue;
}
const r = await e.deliverTarget({
...a,
preparedTarget: n.target
});
if (!r) continue;
c.add(n.dedupeKey);
l.push(r);
u.push(t);
e.onDelivered?.({
...a,
preparedTarget: n,
entry: r
});
} catch (t) {
e.onDeliveryError?.({
...a,
error: t
});
}
}
a = s;
o = u;
return l;
} finally {
await i.reportDelivery({
approvalKind: r,
request: n,
deliveryPlan: a,
deliveredTargets: o
});
}
}
});
return {
...a,
async start() {
try {
await a.start();
} catch (e) {
await i.stop();
throw e;
}
},
async stop() {
await a.stop();
await i.stop();
}
};
}
//#endregion
export { createChannelNativeApprovalRuntimeAsync as n, isExecApprovalChannelRuntimeTerminalStartError as r, createChannelNativeApprovalRuntime as t };