openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
303 lines (302 loc) • 12.9 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, u as normalizeOptionalStringifiedId } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { n as sliceUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { C as isSubagentSessionKey, l as resolveAgentIdFromSessionKey, x as isCronSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { r as emitDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { n as isGatewayMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { a as readCapturedSessionActorEntry, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs";
import { n as renderUserFacingText } from "./user-facing-text-Dqp3fcZx.mjs";
import { A as parseExecApprovalResultText, D as formatExecDeniedReasonMessage } from "./user-copy-DFvWpx47.mjs";
import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { n as getGatewayLifecycleRuntime } from "./server-lifecycle-runtime-context-B_704IYm.mjs";
import { t as resolveExternalBestEffortDeliveryTarget } from "./best-effort-delivery-BHi41M3Q.mjs";
import { t as sendMessage } from "./message-DKs6K7sM.mjs";
import { n as buildExecApprovalContinuationFallbackPrompt } from "./bash-tools.exec-approval-output-Cb90XzcX.mjs";
import { i as isExecApprovalFollowupSessionRebound, o as registerExecApprovalFollowupRuntimeHandoff, t as buildExecApprovalFollowupIdempotencyKey } from "./bash-tools.exec-approval-followup-state-CdzwahWm.mjs";
//#region src/agents/bash-tools.exec-approval-followup.ts
/**
* Delivery orchestration for async exec approval follow-ups.
* Resumes the originating agent session when possible and falls back to safe
* direct delivery only when session resume is unavailable.
*/
const log = createSubsystemLogger("agents/exec-approval-followup");
const DIRECT_FOLLOWUP_MAX_UTF16_UNITS = 4e3;
const DIRECT_FOLLOWUP_TRUNCATION_MARKER = "[... earlier command output omitted ...]";
const DIRECT_FOLLOWUP_COMPLETION_RETENTION = {
idPrefix: "exec-approval-followup:",
maxAgeMs: 864e5,
maxEntries: 2e3
};
const AGENT_FOLLOWUP_WAIT_TIMEOUT_MS = 6e4;
const AGENT_FOLLOWUP_WAIT_RETRY_DELAY_MS = 1e3;
const AGENT_FOLLOWUP_OBSERVATION_TIMEOUT_MS = 36e4;
async function callExecApprovalFollowupGateway(e, t, n) {
const r = getGatewayLifecycleRuntime();
if (r) return e === "agent" ? await r.dispatchAgent(n, t) : await r.waitForAgent(n, t);
return await callGatewayTool(e, { timeoutMs: t }, n);
}
function buildExecDeniedFollowupPrompt(e) {
return [
"An async command did not run.",
"Do not run the command again.",
"There is no new command output.",
"Do not mention, summarize, or reuse output from any earlier run in this session.",
"",
"Exact completion details:",
e.trim(),
"",
"Reply to the user in a helpful way.",
"Explain that the command did not run and why.",
"Do not claim there is new command output."
].join("\n");
}
function formatUnknownError(e) {
if (e instanceof Error) return e.message;
if (typeof e === "string") return e;
try {
return JSON.stringify(e);
} catch {
return "unknown error";
}
}
function shouldSuppressExecDeniedFollowup(e) {
return isSubagentSessionKey(e) || isCronSessionKey(e);
}
/**
* Direct/denied followups bypass the gateway agent dispatch, so the gateway
* rebind guard never sees them. Resolve the session key's current sessionId and
* report whether it was rebound away from the approval-time session by `/new`
* or `/reset` (#59349). Failure to resolve is treated as "not rebound" so a
* real result is never suppressed by accident.
*/
async function isExecApprovalFollowupDirectDeliveryStale(e) {
const t = normalizeOptionalString(e.sessionKey);
const n = normalizeOptionalString(e.expectedSessionId);
if (!t || !n) return false;
try {
if (e.source) {
const r = e.source;
const i = readCapturedSessionActorEntry(r, t);
return !i || i.sessionId !== n || i.lifecycleRevision !== e.expectedLifecycleRevision;
}
const r = resolveSessionStorePathCore(normalizeOptionalString(e.sessionStore), { agentId: e.agentId ?? resolveAgentIdFromSessionKey(t) });
const i = normalizeOptionalString((await readSessionEntryReadOnlyInWorker({
agentId: e.agentId,
storePath: r,
sessionKey: t,
clone: false
}))?.sessionId);
return isExecApprovalFollowupSessionRebound({
expectedSessionId: n,
resolvedSessionId: i
});
} catch (n) {
if (e.source) {
log.debug(`exec approval followup source retired for ${t}; suppressing delivery`);
return true;
}
log.debug(`exec approval followup session-rebind check skipped for ${t}; delivering: ${formatUnknownError(n)}`);
return false;
}
}
function formatDirectExecApprovalFollowupText(e, t = {}) {
if (e.kind === "other" && !e.raw) return null;
if (e.kind === "denied") return t.allowDenied ? formatExecDeniedReasonMessage(e.metadata) : null;
const n = e.kind === "finished" ? normalizeLowercaseStringOrEmpty(e.metadata) : "";
const r = renderUserFacingText(e.kind === "finished" || e.kind === "completed" ? e.body : e.raw, { errorContext: !n.includes("code 0") }).trim();
if (e.kind === "finished") return r || (n.includes("code 0") ? "Background command finished." : n.includes("signal") ? "Background command stopped unexpectedly." : "Background command finished with an error.");
return r || (e.kind === "completed" ? "Background command finished." : null);
}
function readGatewayString(e, t) {
return isRecord(e) ? normalizeOptionalString(e[t]) : void 0;
}
function buildFollowupWaitError(e) {
const t = typeof e.error === "string" && e.error.trim() ? `: ${e.error.trim()}` : e.status ? `: ${e.status}` : "";
return /* @__PURE__ */ new Error(`exec approval followup session resume failed${t}`);
}
function hasTerminalFollowupEvidence(e) {
if (!isRecord(e)) return false;
return typeof e.endedAt === "number" || typeof e.error === "string" || typeof e.stopReason === "string" || e.livenessState === "terminal";
}
async function waitForAgentFollowupRun(e) {
const t = Date.now() + AGENT_FOLLOWUP_OBSERVATION_TIMEOUT_MS;
let n = 0;
let r = 0;
for (;;) {
const i = t - Date.now();
if (i <= 0) return {
status: "observation_ended",
reason: "deadline",
transportErrors: r
};
const a = Math.max(1, Math.min(e.timeoutMs, i));
let o;
try {
o = await callExecApprovalFollowupGateway("agent.wait", a + 2e3, {
runId: e.runId,
timeoutMs: a
});
} catch {
n += 1;
r += 1;
const e = Math.min(AGENT_FOLLOWUP_WAIT_RETRY_DELAY_MS, t - Date.now());
if (e <= 0) return {
status: "observation_ended",
reason: "deadline",
transportErrors: r
};
if (n > 1) await sleepWithAbort(e, void 0, { ref: false });
continue;
}
n = 0;
const s = readGatewayString(o, "status");
if (s === "ok") return { status: "completed" };
if (hasTerminalFollowupEvidence(o)) throw buildFollowupWaitError({
status: s,
error: o.error
});
}
}
/** Sends an exec approval follow-up via session resume or safe direct delivery. */
async function sendExecApprovalFollowup(e) {
const t = e.sessionKey?.trim();
const n = t ? captureSessionActorStorageOwner({
agentId: e.agentId,
sessionKey: t
}, {
assertCurrent() {},
authorize() {}
}) : void 0;
const r = n && t ? readCapturedSessionActorEntry(n, t)?.lifecycleRevision : void 0;
const i = parseExecApprovalResultText(e.resultText);
if (!i.raw) return false;
const a = e.resultText;
const o = i.kind === "denied";
let s = e.internalRuntimeHandoffId;
let c = e.idempotencyKey;
if (!o && t && e.direct !== true && !s) {
const n = registerExecApprovalFollowupRuntimeHandoff({
approvalId: e.approvalId,
sessionKey: t,
resultText: a
});
s = n?.handoffId;
c = n?.idempotencyKey;
}
const l = resolveExternalBestEffortDeliveryTarget({
channel: e.turnSourceChannel,
to: e.turnSourceTo,
accountId: e.turnSourceAccountId,
threadId: e.turnSourceThreadId
});
const u = normalizeMessageChannel(e.turnSourceChannel);
const d = u && isGatewayMessageChannel(u) ? u : void 0;
let f = null;
if (o && (!t || shouldSuppressExecDeniedFollowup(t))) return false;
if (t && e.direct !== true) try {
const n = d ?? e.turnSourceChannel;
const r = {
...e.agentId ? { agentId: e.agentId } : {},
sessionKey: t,
message: o ? buildExecDeniedFollowupPrompt(a) : buildExecApprovalContinuationFallbackPrompt(a, i),
inputProvenance: {
kind: "inter_session",
sourceSessionKey: t,
sourceTool: "exec_approval_followup"
},
deliver: l.deliver,
...l.deliver ? { bestEffortDeliver: true } : {},
channel: l.deliver ? l.channel : n,
to: l.deliver ? l.to : e.turnSourceTo,
accountId: l.deliver ? l.accountId : e.turnSourceAccountId,
threadId: l.deliver ? l.threadId : normalizeOptionalStringifiedId(e.turnSourceThreadId),
idempotencyKey: c ?? buildExecApprovalFollowupIdempotencyKey({ approvalId: e.approvalId }),
...e.expectedSessionId ? { execApprovalFollowupExpectedSessionId: e.expectedSessionId } : {},
...s ? { internalRuntimeHandoffId: s } : {}
};
const u = await callExecApprovalFollowupGateway("agent", 6e4, r);
const f = readGatewayString(u, "status");
if (f === "ok") return true;
if (f === "accepted" || f === "in_flight" || f === "pending") {
const t = readGatewayString(u, "runId") ?? normalizeOptionalString(r.idempotencyKey);
if (!t) throw buildFollowupWaitError({ status: "missing-run-id" });
const n = await waitForAgentFollowupRun({
runId: t,
timeoutMs: AGENT_FOLLOWUP_WAIT_TIMEOUT_MS
});
if (n.status === "observation_ended") {
emitDiagnosticEvent({
type: "log.record",
level: "WARN",
message: "Exec approval followup observation ended",
loggerName: "agents/exec-approval-followup",
attributes: {
approvalId: e.approvalId,
runId: t,
reason: n.reason,
transportErrors: n.transportErrors,
deliveryOwner: "accepted_agent_run"
}
});
log.warn(`Stopped observing accepted exec approval followup ${e.approvalId} after its bounded wait window; run ${t} remains the sole delivery owner`);
}
return true;
}
throw buildFollowupWaitError({
status: f,
error: u.error
});
} catch (e) {
f = e;
}
if (await isExecApprovalFollowupDirectDeliveryStale({
agentId: e.agentId,
sessionKey: t,
expectedSessionId: e.expectedSessionId,
sessionStore: e.sessionStore,
source: n,
expectedLifecycleRevision: r
})) {
emitDiagnosticEvent({
type: "exec.approval.followup_suppressed",
approvalId: e.approvalId,
reason: "session_rebound",
phase: "direct_delivery"
});
log.info(o ? `Dropping stale denied exec approval followup ${e.approvalId}: session ${t ?? ""} was rebound before the approval resolved` : `Dropping stale exec approval followup ${e.approvalId} direct fallback: session ${t ?? ""} was rebound before the approval resolved`);
return false;
}
const p = formatDirectExecApprovalFollowupText(i, { allowDenied: o || f !== null });
if (l.deliver && p) {
const t = !o && f && (i.kind !== "finished" || !normalizeLowercaseStringOrEmpty(i.metadata).includes("code 0")) ? "Automatic session resume failed, so sending the status directly.\n\n" : "";
const n = DIRECT_FOLLOWUP_MAX_UTF16_UNITS - t.length - 40 - 1;
const r = `${t}${p}`.length <= DIRECT_FOLLOWUP_MAX_UTF16_UNITS ? `${t}${p}` : `${t}${DIRECT_FOLLOWUP_TRUNCATION_MARKER}\n${sliceUtf16Safe(p, Math.max(0, p.length - Math.max(1, n)))}`;
const a = `exec-approval-followup:${e.approvalId}`;
const s = await sendMessage({
channel: l.channel,
to: l.to ?? "",
accountId: l.accountId,
threadId: l.threadId,
content: r,
agentId: e.agentId,
gatewayOwnedDelivery: true,
idempotencyKey: a,
deliveryIntentId: a,
reusePendingDeliveryIntent: true,
completionRetention: DIRECT_FOLLOWUP_COMPLETION_RETENTION
});
if (s.deliveryStatus === "suppressed") throw new Error(s.suppressionReason === "adapter_returned_no_identity" ? "exec approval followup delivery could not be confirmed: adapter returned no identity" : `exec approval followup delivery was suppressed: ${s.suppressionReason ?? "unknown reason"}`);
return true;
}
if (f) throw new Error(`Session followup failed: ${formatUnknownError(f)}`);
if (o) return false;
throw new Error("Session key or deliverable origin route is required");
}
//#endregion
export { sendExecApprovalFollowup };