openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
348 lines (347 loc) • 12.8 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { r as filterStringEntries, y as sortUniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { t as formatHumanList } from "./human-list-CcomOfAw.mjs";
import { t as buildChannelApprovalNativeTargetKey } from "./approval-native-target-key-D0y5fYMe.mjs";
//#region src/infra/approval-native-route-coordinator.ts
function createApprovalNativeRouteCoordinatorState() {
return {
activeRuntimes: /* @__PURE__ */ new Map(),
pendingNotices: /* @__PURE__ */ new Map(),
selections: /* @__PURE__ */ new Map(),
runtimeSeq: 0,
closed: false
};
}
function clearApprovalRouteEntry(e, t) {
const n = e.get(t);
if (!n) return;
e.delete(t);
clearTimeout(n.cleanupTimeout);
}
async function resolveApprovalRouteSelection(e, t) {
const n = e.selections.get(t.request.id);
if (n) {
await n.ready;
return n;
}
const r = /* @__PURE__ */ new Map();
const i = Math.min(Math.max(0, t.request.expiresAtMs - Date.now()), 2147483647);
const a = setTimeout(() => {
clearApprovalRouteEntry(e.selections, t.request.id);
}, i);
a.unref?.();
const o = {
verdicts: r,
ready: Promise.resolve(),
cleanupTimeout: a
};
e.selections.set(t.request.id, o);
o.ready = (async () => {
const n = Array.from(e.activeRuntimes.values()).filter((e) => e.handledKinds.has(t.approvalKind));
const i = /* @__PURE__ */ new Map();
for (const e of n) {
const t = normalizeLowercaseStringOrEmpty(e.channel) || e.runtimeId;
i.set(t, [...i.get(t) ?? [], e]);
}
for (const n of i.values()) {
const i = [];
for (const a of n) try {
if (await a.shouldHandle(t.request) && !e.closed && e.activeRuntimes.get(a.runtimeId) === a) i.push(a);
} catch (e) {
r.set(a.runtimeId, {
kind: "selector-error",
error: e
});
}
const a = i.filter((t) => !e.closed && e.activeRuntimes.get(t.runtimeId) === t);
let o;
try {
o = await n[0]?.classifyRoute(t.request) ?? "unbound";
} catch (e) {
for (const t of n) r.set(t.runtimeId, {
kind: "selector-error",
error: e
});
continue;
}
if (o === "bound-or-explicit" && a.length === 0) {
for (const e of n) if (!r.has(e.runtimeId)) r.set(e.runtimeId, { kind: "owner-unavailable" });
} else if (o === "bound-or-explicit" || o === "unbound") {
const e = o === "bound-or-explicit" || a.length === 1 ? "selected" : "ambiguous-owner";
for (const t of a) r.set(t.runtimeId, { kind: e });
}
}
for (const e of n) if (!r.has(e.runtimeId)) r.set(e.runtimeId, { kind: "ineligible" });
})();
await o.ready;
return o;
}
const defaultCoordinatorState = createApprovalNativeRouteCoordinatorState();
const MAX_APPROVAL_ROUTE_NOTICE_TTL_MS = 3e5;
function resolvePendingApprovalRouteNotice(e, t) {
const { request: n, approvalKind: r } = t;
const i = e.pendingNotices.get(n.id);
if (i) return i;
const a = Math.min(Math.max(0, n.expiresAtMs - Date.now()), MAX_APPROVAL_ROUTE_NOTICE_TTL_MS);
const o = setTimeout(() => {
maybeFinalizeApprovalRouteNotice(e, n.id, { force: true });
}, a);
o.unref?.();
const s = {
request: n,
approvalKind: r,
reports: /* @__PURE__ */ new Map(),
cleanupTimeout: o
};
e.pendingNotices.set(n.id, s);
return s;
}
function resolveRouteNoticeTargetFromRequest(e) {
const t = e.request.turnSourceChannel?.trim();
const n = e.request.turnSourceTo?.trim();
if (!t || !n) return null;
return {
channel: t,
to: n,
accountId: e.request.turnSourceAccountId ?? void 0,
threadId: e.request.turnSourceThreadId ?? void 0
};
}
function resolveFallbackRouteNoticeTarget(e) {
const t = e.channel?.trim();
const n = e.deliveryPlan.originTarget?.to?.trim();
if (!t || !n) return null;
return {
channel: t,
to: n,
accountId: e.accountId ?? void 0,
threadId: e.deliveryPlan.originTarget?.threadId ?? void 0
};
}
function didReportDeliverToOrigin(e, t) {
const n = e.deliveryPlan.originTarget;
if (!n) return false;
const r = normalizeOptionalString(e.accountId);
if (t !== void 0 && r !== void 0 && r !== t) return false;
const i = buildChannelApprovalNativeTargetKey(n);
return e.deliveredTargets.some((e) => buildChannelApprovalNativeTargetKey(e.target) === i);
}
function readAllowedDecisionStrings(e) {
const t = "allowedDecisions" in e.request ? e.request.allowedDecisions : void 0;
if (!Array.isArray(t)) return;
return filterStringEntries(t);
}
function resolveApprovalRouteNotice(e) {
const t = resolveRouteNoticeTargetFromRequest(e.request);
const n = normalizeLowercaseStringOrEmpty(t?.channel ?? e.request.request.turnSourceChannel);
const r = e.reports.filter((e) => normalizeLowercaseStringOrEmpty(e.channel) === n || !n).map(resolveFallbackRouteNoticeTarget).find((e) => e !== null) ?? null;
const i = t ? {
...r,
...t,
accountId: t.accountId ?? r?.accountId,
threadId: t.threadId ?? r?.threadId
} : r;
if (!i) return null;
const buildNotice = (t, n = false) => {
const r = e.reports.find((t) => e.state.activeRuntimes.has(t.runtimeId))?.requestGateway ?? e.reports[0]?.requestGateway ?? (n ? Array.from(e.state.activeRuntimes.values())[0]?.requestGateway : void 0);
return r ? {
requestGateway: r,
target: i,
text: t()
} : null;
};
const a = normalizeOptionalString(i.accountId);
const o = e.reports.some((e) => e.deliveredTargets.length > 0);
const s = e.reports.some((e) => e.skipReason === "ambiguous-owner");
const c = s || e.reports.some((e) => e.skipReason === "owner-unavailable");
if (!o && (e.reports.some((e) => e.deliveryPlan.targets.length > 0) || c || e.missingSelectedRuntime)) return buildNotice(() => {
if (s) return `Approval required, but multiple channel accounts can handle this request. Open the ${e.approvalKind === "plugin" ? "Control UI or terminal UI" : "Control UI"} to approve it.`;
const t = e.approvalKind === "exec" && e.request.id.length > 8 ? e.request.id.slice(0, 8) : e.request.id;
const n = readAllowedDecisionStrings(e.request);
return [
"Approval required. I could not deliver the native approval request.",
`Reply with: /approve ${t} ${(n?.length ? n : [
"allow-once",
"allow-always",
"deny"
]).join("|")}`,
"If the short code is ambiguous, use the full id in /approve."
].join("\n");
}, true);
if (e.reports.some((e) => {
if (n && normalizeLowercaseStringOrEmpty(e.channel) !== n) return false;
return didReportDeliverToOrigin(e, a);
})) return null;
const l = e.reports.flatMap((e) => {
if (!e.channelLabel || e.deliveredTargets.length === 0) return [];
const t = normalizeLowercaseStringOrEmpty(e.channel);
if (n && t === n && !e.deliveryPlan.notifyOriginWhenDmOnly) return [];
const r = normalizeOptionalString(e.accountId);
if (n && t === n && a !== void 0 && r !== void 0 && r !== a) return [];
const i = new Set(e.deliveredTargets.map((e) => e.surface));
return [i.size === 1 && i.has("approver-dm") ? `${e.channelLabel} DMs` : e.channelLabel];
});
const u = sortUniqueStrings(l.map((e) => e.trim())).filter(Boolean);
if (u.length === 0) return null;
return buildNotice(() => `Approval required. I sent the approval request to ${formatHumanList(u)}, not this chat.`);
}
/** Returns whether a native approval runtime is active for the requested channel/account scope. */
function hasActiveApprovalNativeRouteRuntime(e) {
return hasActiveApprovalNativeRouteRuntimeForState(defaultCoordinatorState, e);
}
function hasActiveApprovalNativeRouteRuntimeForState(e, t) {
const n = normalizeLowercaseStringOrEmpty(t.channel);
const r = normalizeOptionalString(t.accountId);
const i = Array.from(e.activeRuntimes.values()).filter((e) => {
if (!e.handledKinds.has(t.approvalKind)) return false;
if (n && normalizeLowercaseStringOrEmpty(e.channel) !== n) return false;
const i = normalizeOptionalString(e.accountId);
return r === void 0 || i === void 0 || i === r;
});
return r === void 0 ? i.length === 1 : i.length > 0;
}
async function maybeFinalizeApprovalRouteNotice(e, t, n) {
const r = e.pendingNotices.get(t);
if (!r) return;
const i = e.selections.get(t);
if (!i) return;
if (!n?.force) {
for (const e of i.verdicts.keys()) if (!r.reports.has(e)) return;
}
const a = Array.from(i.verdicts).some(([e, t]) => t.kind === "selected" && !r.reports.has(e));
const o = Array.from(r.reports.values());
const s = resolveApprovalRouteNotice({
state: e,
approvalKind: r.approvalKind,
request: r.request,
reports: o,
missingSelectedRuntime: a
});
clearApprovalRouteEntry(e.pendingNotices, t);
if (!s) return;
try {
await s.requestGateway("send", {
channel: s.target.channel,
to: s.target.to,
accountId: s.target.accountId ?? void 0,
threadId: s.target.threadId ?? void 0,
message: s.text,
idempotencyKey: `approval-route-notice:${t}`
});
} catch {}
}
/** Tracks native approval deliveries and sends origin-chat notices after all observed runtimes report. */
function createApprovalNativeRouteReporter(e) {
return createApprovalNativeRouteReporterForState(defaultCoordinatorState, e);
}
function createApprovalNativeRouteReporterForState(e, t) {
const n = `native-approval-route:${++e.runtimeSeq}`;
let r = false;
const report = async (i) => {
if (e.closed || !r || !t.handledKinds.has(i.approvalKind)) return;
const a = await resolveApprovalRouteSelection(e, i);
if (e.closed || !r || e.selections.get(i.request.id) !== a || !a.verdicts.has(n)) return;
resolvePendingApprovalRouteNotice(e, i).reports.set(n, {
runtimeId: n,
channel: t.channel,
channelLabel: t.channelLabel,
accountId: t.accountId,
deliveryPlan: i.deliveryPlan,
deliveredTargets: i.deliveredTargets,
requestGateway: t.requestGateway,
skipReason: i.skipReason
});
await maybeFinalizeApprovalRouteNotice(e, i.request.id);
};
return {
async selectRequest(i) {
if (e.closed || !t.handledKinds.has(i.approvalKind)) return { kind: "ineligible" };
if (!r) try {
return await t.shouldHandle(i.request) && !e.closed ? { kind: "selected" } : { kind: "ineligible" };
} catch (e) {
return {
kind: "selector-error",
error: e
};
}
const a = await resolveApprovalRouteSelection(e, i);
if (e.closed || !r || e.selections.get(i.request.id) !== a) return { kind: "ineligible" };
resolvePendingApprovalRouteNotice(e, i);
return a.verdicts.get(n) ?? { kind: "ineligible" };
},
start() {
if (e.closed || r) return;
e.activeRuntimes.set(n, {
runtimeId: n,
handledKinds: t.handledKinds,
channel: t.channel,
channelLabel: t.channelLabel,
accountId: t.accountId,
requestGateway: t.requestGateway,
shouldHandle: t.shouldHandle,
classifyRoute: t.classifyRoute
});
r = true;
},
async reportSkipped(e) {
await report({
approvalKind: e.approvalKind,
request: e.request,
deliveryPlan: {
targets: [],
originTarget: null,
notifyOriginWhenDmOnly: false
},
deliveredTargets: [],
skipReason: e.reason
});
},
async reportDelivery(e) {
await report(e);
},
completeRequest(t) {
clearApprovalRouteEntry(e.selections, t);
clearApprovalRouteEntry(e.pendingNotices, t);
},
async stop() {
if (!r) return;
e.activeRuntimes.delete(n);
for (const t of Array.from(e.pendingNotices.values())) {
const r = e.selections.get(t.request.id);
if (r?.verdicts.has(n) && !t.reports.has(n)) await report({
request: t.request,
approvalKind: t.approvalKind,
deliveryPlan: {
targets: [],
originTarget: null,
notifyOriginWhenDmOnly: false
},
deliveredTargets: [],
skipReason: r.verdicts.get(n)?.kind === "selected" ? "owner-unavailable" : "ineligible"
});
}
r = false;
e.activeRuntimes.delete(n);
}
};
}
/** Reads native route activity from the owning Gateway coordinator, else the process default. */
function hasActiveNativeApprovalRoute(e, t) {
return e?.hasActiveRuntime(t) ?? hasActiveApprovalNativeRouteRuntime(t);
}
/** Creates an instance-local route coordinator so Gateway runtimes cannot share account state. */
function createApprovalNativeRouteCoordinator() {
const e = createApprovalNativeRouteCoordinatorState();
return {
createReporter: (t) => createApprovalNativeRouteReporterForState(e, t),
hasActiveRuntime: (t) => hasActiveApprovalNativeRouteRuntimeForState(e, t),
close: () => {
e.closed = true;
for (const t of Array.from(e.pendingNotices.keys())) clearApprovalRouteEntry(e.pendingNotices, t);
for (const t of Array.from(e.selections.keys())) clearApprovalRouteEntry(e.selections, t);
e.activeRuntimes.clear();
}
};
}
//#endregion
export { createApprovalNativeRouteReporter as n, hasActiveNativeApprovalRoute as r, createApprovalNativeRouteCoordinator as t };