openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
479 lines (478 loc) β’ 19.1 kB
JavaScript
import { l as isRecord } from "../record-coerce-CVPuDqcc.mjs";
import { t as pruneMapToMaxSize } from "../map-size-BBr20tbc.mjs";
import { t as formatFencedCodeBlock } from "../markdown-code-C5it6V4Q.mjs";
import { n as summarizeApprovalScope } from "../approval-scope-DOnX7GXe.mjs";
import { t as isApprovalNotFoundError } from "../approval-errors-byE8UOsC.mjs";
import "../error-runtime-BM740gJj.mjs";
import { r as sanitizeForPromptLiteral } from "../sanitize-for-prompt-CAahLekM.mjs";
import { t as formatApprovalDisplayPath } from "../approval-display-paths-C-0hBZZ4.mjs";
import { i as buildExecApprovalPendingReplyPayload, u as formatExecApprovalExpiresIn } from "../exec-approval-reply-CfpNUvnC.mjs";
import { h as normalizeApprovalRequest } from "../approval-request-account-binding-DOCAr58L.mjs";
import { s as shouldSuppressLocalNativeExecApprovalPrompt } from "../approval-native-helpers-BnPamoUJ.mjs";
import { n as buildPendingApprovalView } from "../approval-view-model-D_4llAVF.mjs";
import { r as buildPluginApprovalPendingReplyPayload, t as buildApprovalPendingReplyPayload } from "../approval-renderers-BFs8Orkr.mjs";
//#region src/plugin-sdk/approval-reaction-binding.ts
/** Build the private marker revalidated after channel delivery. */
function buildApprovalReactionDeliveredBindingMarker(e) {
return {
version: 1,
...e
};
}
/** Read a nonempty, duplicate-free list without accepting unrecognized decisions. */
function readApprovalReactionDecisionList(e) {
if (!Array.isArray(e) || e.length === 0) return null;
const t = [];
for (const n of e) {
if (n !== "allow-once" && n !== "allow-always" && n !== "deny" || t.includes(n)) return null;
t.push(n);
}
return t;
}
/** Normalize the shipped approval command spelling without accepting other decisions. */
function normalizeApprovalReactionDecision(e) {
const t = e.trim().toLowerCase();
if (t === "always") return "allow-always";
return t === "allow-once" || t === "allow-always" || t === "deny" ? t : null;
}
/** Compare approved decision sets independently of presentation order. */
function approvalReactionDecisionSetsMatch(e, t) {
return e.length === t.length && e.every((e) => t.includes(e));
}
/** Validate canonical approval metadata without inferring its owner from text. */
function readApprovalReactionDeliveryMetadata(e, t = {}) {
const n = e.channelData?.execApproval;
if (!n || typeof n !== "object" || Array.isArray(n)) return null;
const r = n;
if (typeof r.approvalId !== "string") return null;
const i = t.trimApprovalId ? r.approvalId.trim() : r.approvalId;
const a = typeof r.approvalSlug === "string" ? r.approvalSlug.trim() : "";
const o = readApprovalReactionDecisionList(r.allowedDecisions);
if (!i || !t.trimApprovalId && i !== i.trim() || t.requireApprovalSlug && !a || r.approvalKind !== "exec" && r.approvalKind !== "plugin" && r.approvalKind !== "system-agent" || !o) return null;
return {
approvalId: i,
approvalKind: r.approvalKind,
allowedDecisions: o,
...a ? { approvalSlug: a } : {}
};
}
/** Verify that typed presentation controls exactly match authoritative approval metadata. */
function readApprovalReactionPresentationBinding(e) {
const t = readApprovalReactionDeliveryMetadata(e.payload, e);
if (!t) return null;
const n = (e.presentation ?? e.payload.presentation)?.blocks.flatMap((e) => e.type === "buttons" ? e.buttons.flatMap((e) => e.action?.type === "approval" ? [e.action] : []) : []);
if (!n?.length || n.some((e) => e.approvalId !== t.approvalId || e.approvalKind !== t.approvalKind)) return null;
const r = readApprovalReactionDecisionList(n.map((e) => e.decision));
return r && approvalReactionDecisionSetsMatch(t.allowedDecisions, r) ? t : null;
}
/** Revalidate the private delivery marker against canonical typed approval metadata. */
function readApprovalReactionDeliveredBinding(e) {
const t = readApprovalReactionDeliveryMetadata(e.payload, e);
const n = e.payload.channelData?.[e.channelDataKey];
if (!t || !n || typeof n !== "object" || Array.isArray(n)) return null;
const r = n;
const i = typeof r.approvalId === "string" && e.trimApprovalId ? r.approvalId.trim() : r.approvalId;
const a = typeof r.approvalSlug === "string" ? r.approvalSlug.trim() : "";
const o = readApprovalReactionDecisionList(r.allowedDecisions);
return r.version === 1 && i === t.approvalId && r.approvalKind === t.approvalKind && (!e.requireApprovalSlug || a === t.approvalSlug) && o && approvalReactionDecisionSetsMatch(t.allowedDecisions, o) ? t : null;
}
//#endregion
//#region src/plugin-sdk/approval-reaction-runtime.ts
/** Validate the shared persisted fields without changing transport-owned metadata. */
function readApprovalReactionTargetRecord(e) {
if (!isRecord(e) || typeof e.approvalId !== "string" || e.approvalKind !== "exec" && e.approvalKind !== "plugin" && e.approvalKind !== "system-agent") return null;
const t = readApprovalReactionDecisionList(e.allowedDecisions);
return t ? {
approvalId: e.approvalId,
approvalKind: e.approvalKind,
allowedDecisions: t
} : null;
}
/** Admit an explicit approver and retire transport bindings only on terminal resolution. */
async function settleApprovalReaction(e) {
const { request: t, logVerboseMessage: n } = e;
const { channel: r, approvalId: i, senderId: a } = t;
if (e.approvers.length === 0) {
n?.(`${r}: approval reaction denied id=${i}; reactions require explicit approvers`);
return "denied";
}
if (!e.authorizeActorAction({
...t,
action: "approve"
}).authorized) {
n?.(`${r}: approval reaction denied id=${i} sender=${a}`);
return "denied";
}
const o = await e.loadResolver();
let s;
try {
s = await o(t);
} catch (t) {
if (isApprovalNotFoundError(t)) {
await e.clearTarget();
n?.(`${r}: approval reaction ignored for expired approval id=${i} sender=${a}`);
return "not-found";
}
e.onError?.(t);
n?.(`${r}: approval reaction failed id=${i} sender=${a}: ${String(t)}`);
throw t;
}
await e.clearTarget();
e.onResolved(s);
return "resolved";
}
/** Canonical reaction controls shown for approval prompts, in product display order. */
const APPROVAL_REACTION_BINDINGS = [
{
decision: "allow-once",
emoji: "π",
label: "Allow Once"
},
{
decision: "allow-always",
emoji: "βΎοΈ",
label: "Allow Always"
},
{
decision: "deny",
emoji: "π",
label: "Deny"
}
];
const APPROVAL_REACTION_ORDER = APPROVAL_REACTION_BINDINGS.map((e) => e.decision);
const VARIATION_SELECTOR_RE = /[\uFE0E\uFE0F]/gu;
const FITZPATRICK_MODIFIER_RE = /[\u{1F3FB}-\u{1F3FF}]/gu;
/** List the canonical reaction bindings allowed for a specific approval request. */
function listApprovalReactionBindings(e) {
const t = new Set(e.allowedDecisions);
return APPROVAL_REACTION_BINDINGS.filter((e) => t.has(e.decision)).map((e) => ({
decision: e.decision,
emoji: e.emoji,
label: e.label
}));
}
/** Build user-facing reaction instructions, or null when no reaction decisions are allowed. */
function buildApprovalReactionHint(e) {
const t = listApprovalReactionBindings(e);
if (t.length === 0) return null;
return `React with:\n\n${t.map((e) => `${e.emoji} ${e.label}`).join("\n")}`;
}
const APPROVAL_REACTION_HINT_PRESENT_RE = /(^|\n)React with:\s*(\n|$)/i;
/** True when approval prompt text already carries a reaction hint block. */
function hasApprovalReactionHintText(e) {
return APPROVAL_REACTION_HINT_PRESENT_RE.test(e ?? "");
}
/** Adds the canonical reaction hint to approval prompt text unless one is present. */
function addApprovalReactionHintToText(e) {
if (hasApprovalReactionHintText(e.text)) return e.text;
const t = buildApprovalReactionHint({ allowedDecisions: e.allowedDecisions });
if (!t) return e.text;
const n = e.text.split(/\r?\n/);
const r = n.findIndex((e) => /^ID:\s*\S+/.test(e.trim()));
if (r >= 0) {
const e = n.slice(0, r + 1).join("\n");
const i = n.slice(r + 1).join("\n").replace(/^\n+/, "");
return i ? `${e}\n\n${t}\n\n${i}` : `${e}\n\n${t}`;
}
return `${t}\n\n${e.text}`;
}
/** Normalize reaction emoji so skin-tone and text/presentation variants match canonical bindings. */
function normalizeApprovalReactionEmoji(e) {
const t = e.trim().replace(VARIATION_SELECTOR_RE, "").replace(FITZPATRICK_MODIFIER_RE, "");
if (t === "βΎ") return "βΎοΈ";
return t;
}
/** Resolve a reaction key to an allowed approval decision. */
function resolveApprovalReactionDecision(e) {
const t = normalizeApprovalReactionEmoji(e.reactionKey);
if (!t) return null;
for (const n of listApprovalReactionBindings(e)) if (n.emoji === t) return {
decision: n.decision,
normalizedEmoji: t
};
return null;
}
/** Resolve an explicitly typed target without deriving ownership from its id. */
function resolveTypedApprovalReactionTarget(e) {
const t = e.target;
if (!t) return null;
const n = resolveApprovalReactionDecision({
reactionKey: e.reactionKey,
allowedDecisions: t.allowedDecisions
});
if (!n) return null;
const r = t.approvalId;
const i = t.approvalKind;
if (!r) return null;
if (i !== "exec" && i !== "plugin" && i !== "system-agent") return null;
return {
approvalId: r,
approvalKind: i,
decision: n.decision,
normalizedEmoji: n.normalizedEmoji,
...t.route === void 0 ? {} : { route: t.route }
};
}
function formatSeverity(e) {
return e === "critical" ? "Critical" : e === "info" ? "Info" : "Warning";
}
function buildManualInstructionSection(e) {
const t = [];
if (!e.allowedDecisions.includes("allow-always")) t.push(e.approvalKind === "exec" ? "Allow Always is unavailable for this command." : "Allow Always is unavailable because the effective policy requires approval every time.");
if (e.allowedDecisions.length > 0) t.push(`Reply with: /approve ${e.approvalId} ${e.allowedDecisions.join("|")}`);
return t;
}
function listDecisionActions(e) {
const t = new Set(e.flatMap((e) => "decision" in e && e.decision ? [e.decision] : []));
return APPROVAL_REACTION_ORDER.filter((e) => t.has(e));
}
function buildApprovalReactionPromptText(e) {
const { view: t } = e;
const n = t.scope ? summarizeApprovalScope(t.scope) : void 0;
const r = listDecisionActions(t.actions);
const i = [];
if (t.approvalKind === "exec") {
const r = ["**Exec approval required**", `**ID:** ${t.approvalId}`];
i.push(r.join("\n"));
const a = t.warningText?.trim();
if (a) i.push(`**${a}**`);
const o = t.commandAnalysis?.warningLines?.map((e) => e.trim()).filter(Boolean).slice(0, 5);
if (o?.length) i.push(["**Command analysis:**", ...o.map((e) => `- ${e}`)].join("\n"));
i.push(["**Pending command:**", formatFencedCodeBlock(t.commandText, "sh")].join("\n"));
const s = [];
if (t.cwd) s.push(`**CWD:** ${formatApprovalDisplayPath(sanitizeForPromptLiteral(t.cwd))}`);
if (t.host) s.push(`**Host:** ${t.host}`);
if (t.nodeId) s.push(`**Node:** ${t.nodeId}`);
if (n) s.push(`**Scope:** ${n}`);
if (t.agentId) s.push(`**Agent:** ${t.agentId}`);
if (t.ask) s.push(`**Ask:** ${t.ask}`);
s.push(`**Expires in:** ${formatExecApprovalExpiresIn(t.expiresAtMs, e.nowMs)}`);
s.push(`**Full id:** \`${t.approvalId}\``);
i.push(s.join("\n"));
} else if (t.approvalKind === "system-agent") {
const n = ["**OpenClaw change requires approval**", `**Change:** ${t.operationSummary}`];
if (t.agentId) n.push(`**Agent:** ${t.agentId}`);
n.push(`**Expires in:** ${formatExecApprovalExpiresIn(t.expiresAtMs, e.nowMs)}`);
i.push(n.join("\n"));
} else {
const r = ["**Plugin approval required**", `**ID:** ${t.approvalId}`];
i.push(r.join("\n"));
const a = [`**Title:** ${t.title}`];
if (t.description) a.push(`**Description:** ${t.description}`);
if (n) a.push(`**Scope:** ${n}`);
a.push(`**Severity:** ${formatSeverity(t.severity)}`);
if (t.toolName) a.push(`**Tool:** ${t.toolName}`);
if (t.pluginId) a.push(`**Plugin:** ${t.pluginId}`);
if (t.agentId) a.push(`**Agent:** ${t.agentId}`);
a.push(`**Expires in:** ${formatExecApprovalExpiresIn(t.expiresAtMs, e.nowMs)}`);
a.push(`**Full id:** \`${t.approvalId}\``);
i.push(a.join("\n"));
}
if (e.reactionHint) i.push(e.reactionHint);
const a = t.actions.flatMap((e) => e.command.trim() ? [`${e.label}: ${e.command}`] : []);
if (a.length > 0) i.push(a.join("\n"));
const o = buildManualInstructionSection({
approvalKind: t.approvalKind,
approvalId: t.approvalId,
allowedDecisions: r
});
if (o.length > 0) i.push(o.join("\n"));
return i.filter(Boolean).join("\n\n");
}
function withoutPresentation(e) {
const { presentation: t, interactive: n, ...r } = e;
return r;
}
/** Build an approval prompt payload with reaction bindings for a prepared view. */
function buildApprovalPendingPromptPayload(e) {
const t = listDecisionActions(e.view.actions);
const n = listApprovalReactionBindings({ allowedDecisions: t });
const r = buildApprovalReactionPromptText({
view: e.view,
nowMs: e.nowMs,
reactionHint: buildApprovalReactionHint({ allowedDecisions: t })
});
return {
...withoutPresentation(buildApprovalPendingReplyPayload({
approvalKind: e.view.approvalKind,
approvalId: e.view.approvalId,
approvalSlug: e.view.approvalId.slice(0, 8),
text: r,
agentId: e.view.agentId ?? null,
allowedDecisions: t,
sessionKey: e.request.request.sessionKey ?? null
})),
allowedDecisions: t,
reactionBindings: n
};
}
/** Build an approval prompt payload with reaction bindings directly from a request. */
function buildApprovalReactionPromptPayloadForRequest(e) {
return buildApprovalPendingPromptPayload({
request: e.request,
view: buildPendingApprovalView(e.request),
nowMs: e.nowMs
});
}
function replaceApprovalIdPlaceholder(e, t) {
return (e ?? "").replace(/\/approve\s+<id>/g, `/approve ${t}`);
}
/** Build reaction and manual-fallback pending approval content for a prepared view. */
function buildApprovalReactionPendingContent(e) {
const t = buildApprovalPendingPromptPayload(e);
const n = normalizeApprovalRequest(e.request);
if (e.view.approvalKind === "plugin") {
if (n.approvalKind !== "plugin") throw new Error("approval request and view kinds do not match");
const r = buildPluginApprovalPendingReplyPayload({
request: n,
nowMs: e.nowMs,
allowedDecisions: t.allowedDecisions
});
return {
reactionPayload: t,
manualFallbackPayload: withoutPresentation({
...r,
text: replaceApprovalIdPlaceholder(r.text, n.id)
})
};
}
if (e.view.approvalKind === "system-agent") {
if (n.approvalKind !== "system-agent") throw new Error("approval request and view kinds do not match");
return {
reactionPayload: t,
manualFallbackPayload: withoutPresentation(buildApprovalPendingReplyPayload({
approvalKind: "system-agent",
approvalId: n.id,
approvalSlug: n.id.slice(0, 8),
text: t.text ?? "",
agentId: e.view.agentId ?? null,
allowedDecisions: t.allowedDecisions,
sessionKey: n.request.sessionKey ?? null
}))
};
}
if (n.approvalKind !== "exec") throw new Error("approval request and view kinds do not match");
return {
reactionPayload: t,
manualFallbackPayload: withoutPresentation(buildExecApprovalPendingReplyPayload({
approvalId: n.id,
approvalSlug: n.id.slice(0, 8),
approvalCommandId: n.id,
warningText: e.view.warningText ?? void 0,
ask: e.view.ask ?? null,
agentId: e.view.agentId ?? null,
allowedDecisions: t.allowedDecisions,
command: e.view.commandText,
cwd: e.view.cwd ?? void 0,
host: e.view.host === "node" ? "node" : "gateway",
nodeId: e.view.nodeId ?? void 0,
scope: e.view.scope ?? void 0,
sessionKey: e.view.sessionKey ?? null,
expiresAtMs: n.expiresAtMs,
nowMs: e.nowMs
}))
};
}
/**
* Prompt copy for channels whose native controls (Apple Messages polls, inline
* buttons) own the decision surface. Same bold headers and labels as the
* reaction prompt (#85954) minus the tapback hint, which would advertise a
* second, redundant control path next to the native one.
*/
function buildApprovalNativeControlsPromptText(e) {
return buildApprovalReactionPromptText({
view: e.view,
nowMs: e.nowMs,
reactionHint: null
});
}
/** Build reaction and manual-fallback pending approval content directly from a request. */
function buildApprovalReactionPendingContentForRequest(e) {
return buildApprovalReactionPendingContent({
request: e.request,
view: buildPendingApprovalView(e.request),
nowMs: e.nowMs
});
}
/** Create an approval target store backed by memory with optional persistent storage. */
function createApprovalReactionTargetStore(e) {
const t = e.nowMs ?? (() => Date.now());
const n = /* @__PURE__ */ new Map();
let r;
let i = false;
const disablePersistentStore = (t) => {
i = true;
r = void 0;
e.logPersistentError?.(t);
};
const getPersistentStore = () => {
if (i || !e.openStore) return;
if (r) return r;
try {
r = e.openStore({
namespace: e.namespace,
maxEntries: e.maxEntries,
defaultTtlMs: e.defaultTtlMs
});
return r;
} catch (e) {
disablePersistentStore(e);
return;
}
};
const pruneMemory = () => {
const r = t();
for (const [e, t] of n) if (t.expiresAtMs <= r) n.delete(e);
pruneMapToMaxSize(n, e.maxEntries);
};
return {
async register(r, i, a) {
const o = r.trim();
if (!o) return;
const s = Math.max(1, a?.ttlMs ?? e.defaultTtlMs);
n.set(o, {
target: i,
expiresAtMs: t() + s
});
pruneMemory();
const c = getPersistentStore();
if (!c) return;
await c.register(o, {
version: 1,
target: i
}, { ttlMs: s }).catch(disablePersistentStore);
},
async lookup(t) {
const r = t.trim();
if (!r) return null;
pruneMemory();
const i = n.get(r);
if (i) return i.target;
const a = getPersistentStore();
if (!a) return null;
try {
const t = await a.lookup(r);
if (t?.version !== 1) return null;
return e.readPersistedTarget ? e.readPersistedTarget(t.target) : t.target;
} catch (e) {
disablePersistentStore(e);
return null;
}
},
async delete(e) {
const t = e.trim();
if (!t) return;
n.delete(t);
const r = getPersistentStore();
if (!r) return;
await r.delete(t).catch(disablePersistentStore);
},
clearForTest() {
n.clear();
r = void 0;
i = false;
}
};
}
//#endregion
export { APPROVAL_REACTION_BINDINGS, addApprovalReactionHintToText, approvalReactionDecisionSetsMatch, buildApprovalNativeControlsPromptText, buildApprovalPendingPromptPayload, buildApprovalReactionDeliveredBindingMarker, buildApprovalReactionHint, buildApprovalReactionPendingContent, buildApprovalReactionPendingContentForRequest, buildApprovalReactionPromptPayloadForRequest, createApprovalReactionTargetStore, hasApprovalReactionHintText, listApprovalReactionBindings, normalizeApprovalReactionDecision, normalizeApprovalReactionEmoji, readApprovalReactionDecisionList, readApprovalReactionDeliveredBinding, readApprovalReactionDeliveryMetadata, readApprovalReactionPresentationBinding, readApprovalReactionTargetRecord, resolveApprovalReactionDecision, resolveTypedApprovalReactionTarget, settleApprovalReaction, shouldSuppressLocalNativeExecApprovalPrompt };