openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
469 lines (468 loc) • 16.5 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs";
import { o as closeAdmittedRunDelegatedAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs";
import { X as captureSessionTarget } from "./session-controller.state-BApgK0mV.mjs";
import "./plugins-BoMiRtiY.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { i as runSessionMutation } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { c as updateSessionEntry } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { c as readChannelContextAdmissionEvidence, l as readChannelContextGatewayContextResolver } from "./admission-evidence-q4_t-NFq.mjs";
import { r as getGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { i as captureSessionControllerStop, r as stopSession } from "./session-controller.stop-BqKrTY7V.mjs";
import { i as resolveAcpThreadSessionDetailLines, n as resolveAcpSessionCwd } from "./session-identifiers-dCLUDxk0.mjs";
import { n as resolveSessionStorePathForAcp } from "./session-meta-store-X3_cjz74.mjs";
import { u as resolveAcpSessionResolutionError } from "./manager.utils-CiSXdCbv.mjs";
import { a as resolveAcpDispatchPolicyMessage, i as resolveAcpDispatchPolicyError, n as isAcpEnabledByPolicy, r as resolveAcpAgentPolicyError } from "./policy-De5rDLTI.mjs";
import { n as getAcpSessionManager } from "./manager-CDGCO__f.mjs";
import "./session-meta-CupK_5Fp.mjs";
import { T as expectedCurrentSessionBinding, k as resolveChannelDefaultBindingPlacement, t as getSessionBindingService } from "./session-binding-service-Bn-zGfS9.mjs";
import { r as normalizeConversationRef } from "./session-binding-normalization-c5CMRfx2.mjs";
import { t as prepareChannelRunAdmission } from "./channel-run-admission-V419E9U5.mjs";
import { n as commandReply } from "./command-gates-BZ-IYgiD.mjs";
import { i as resolveSpawnedWorkspaceInheritance } from "./spawned-context-wZ6NGSBl.mjs";
import { i as resolveThreadBindingThreadName, r as resolveThreadBindingIntroText } from "./thread-bindings-messages-Bd-PuMza.mjs";
import { a as resolveThreadBindingIdleTimeoutMsForChannel, c as resolveThreadBindingSpawnPolicy, n as formatThreadBindingSpawnDisabledError, s as resolveThreadBindingMaxAgeMsForChannel, t as formatThreadBindingDisabledError } from "./thread-bindings-policy-Ty7ueYar.mjs";
import { n as resolveAcpSpawnRuntimePolicyError } from "./acp-spawn-policy-BQ2YsISr.mjs";
import { a as cleanupFailedAcpSpawn, i as resolveRuntimeCwdForAcpSpawn } from "./acp-spawn-runtime-C_Pjeq3C.mjs";
import { i as stopSubagentsForRequester } from "./abort-operation-ClQrZLCq.mjs";
import { t as formatAbortReplyText } from "./abort-DOr-mahZ.mjs";
import { r as resolveAcpCommandBindingContext, t as resolveAcpTargetSessionKey } from "./targets-BmjrxBCj.mjs";
import { _ as parseSpawnInput, b as resolveCommandRequestId, f as acpCommandErrorReply, v as parseSteerInput, x as withAcpCommandErrorBoundary } from "./shared-BqXu2vMv.mjs";
import { randomUUID } from "node:crypto";
//#region src/auto-reply/reply/commands-acp/bindings.ts
async function resolveBoundReplyPayload(e) {
const t = normalizeAnyChannelId(e.binding.conversation.channel);
if (!t) return;
const n = getChannelPlugin(t)?.conversationBindings?.buildBoundReplyPayload;
if (!n) return;
return await n({
operation: "acp-spawn",
placement: e.placement,
conversation: e.binding.conversation
}) ?? void 0;
}
async function bindSpawnedAcpSession(e) {
const { commandParams: t } = e;
const n = e.mode === "conversation";
const r = resolveAcpCommandBindingContext(t);
const { channel: i, accountId: a, conversationId: o, threadId: s } = r;
if (!i) return {
ok: false,
error: `ACP ${n ? "current-conversation" : "thread"} binding requires a channel context.`
};
const c = resolveThreadBindingSpawnPolicy({
cfg: t.cfg,
channel: i,
accountId: a,
kind: "acp"
});
if (!c.enabled) return {
ok: false,
error: formatThreadBindingDisabledError({
...c,
kind: "acp"
})
};
if (!n && !c.spawnEnabled) return {
ok: false,
error: formatThreadBindingSpawnDisabledError({
...c,
kind: "acp"
})
};
const l = getSessionBindingService();
const u = l.getCapabilities({
channel: c.channel,
accountId: c.accountId
});
const d = n ? "Conversation" : "Thread";
if (!u.adapterAvailable || !u.bindSupported) return {
ok: false,
error: `${d} bindings are unavailable for ${i}.`
};
const f = n ? "current" : resolveChannelDefaultBindingPlacement(i) ?? "current";
if (e.mode === "thread-here") {
if (!(f === "child" ? s : o)) return {
ok: false,
error: `--thread here requires running /acp spawn inside an active ${i} thread/conversation.`
};
}
const p = n || s ? "current" : f;
if (!u.placements.includes(p)) return {
ok: false,
error: `${d} bindings do not support ${p} placement for ${i}.`
};
if (!o) return {
ok: false,
error: n ? `--bind here requires running /acp spawn inside an active ${i} conversation.` : `Could not resolve a ${i} conversation for ACP thread spawn.`
};
const m = normalizeOptionalString(t.command.senderId) ?? "";
const h = normalizeConversationRef({
channel: c.channel,
accountId: c.accountId,
conversationId: o,
parentConversationId: r.parentConversationId
});
const g = p === "child" || s && o === s ? "thread" : "conversation";
let _;
if (p === "current") {
_ = await l.resolveByConversationAsync(h);
const e = normalizeOptionalString(_?.metadata?.boundBy) ?? "";
if (_ && e && e !== "system" && m && m !== e) return {
ok: false,
error: `Only ${e} can rebind this ${g}.`
};
}
try {
t.command.assertOwnerCurrent?.();
const n = e.label || e.agentId;
const r = {
cfg: t.cfg,
channel: c.channel,
accountId: c.accountId
};
const i = {
[expectedCurrentSessionBinding]: _,
targetSessionKey: e.sessionKey,
targetKind: "session",
conversation: h,
placement: p,
assertCurrent: t.command.assertOwnerCurrent,
metadata: {
threadName: resolveThreadBindingThreadName({
agentId: e.agentId,
label: n
}),
agentId: e.agentId,
label: n,
boundBy: m || "unknown",
introText: resolveThreadBindingIntroText({
agentId: e.agentId,
label: n,
idleTimeoutMs: resolveThreadBindingIdleTimeoutMsForChannel(r),
maxAgeMs: resolveThreadBindingMaxAgeMsForChannel(r),
sessionCwd: resolveAcpSessionCwd(e.sessionMeta),
sessionDetails: resolveAcpThreadSessionDetailLines(e.sessionMeta)
})
}
};
return {
ok: true,
bound: {
binding: await l.bind(i),
placement: p,
labelNoun: g
}
};
} catch (e) {
return {
ok: false,
error: formatErrorMessage(e) || (n ? `Failed to bind the current ${i} conversation to the new ACP session.` : `Failed to bind a ${i} thread/conversation to the new ACP session.`)
};
}
}
//#endregion
//#region src/auto-reply/reply/commands-acp/lifecycle.ts
async function persistSpawnedSessionLabel(e) {
const t = normalizeOptionalString(e.label);
if (!t) return;
const n = Date.now();
const { storePath: r, agentId: i } = resolveSessionStorePathForAcp({
cfg: e.commandParams.cfg,
sessionKey: e.sessionKey,
agentId: e.agentId
});
e.commandParams.command.assertOwnerCurrent?.();
if (e.commandParams.sessionStore && e.commandParams.storePath === r) {
const r = e.commandParams.sessionStore[e.sessionKey];
if (r) e.commandParams.sessionStore[e.sessionKey] = {
...r,
label: t,
updatedAt: n
};
}
await updateSessionEntry({
storePath: r,
agentId: i,
sessionKey: e.sessionKey
}, () => {
e.commandParams.command.assertOwnerCurrent?.();
return {
label: t,
updatedAt: n
};
});
}
async function handleAcpSpawnAction(e, t) {
if (!isAcpEnabledByPolicy(e.cfg)) return commandReply("ACP is disabled by policy (`acp.enabled=false`).");
const n = parseSpawnInput(e, t);
if (!n.ok) return commandReply(`⚠️ ${n.error}`);
const r = n.value;
const i = await resolveAcpSpawnRuntimePolicyError({
cfg: e.cfg,
requesterAgentId: e.agentId,
requesterSessionKey: e.sessionKey
});
if (i) return commandReply(`⚠️ ${i}`);
const a = resolveAcpAgentPolicyError(e.cfg, r.agentId);
if (a) return acpCommandErrorReply(a, "ACP target agent is not allowed by policy.", "ACP_SESSION_INIT_FAILED");
const o = getAcpSessionManager();
const s = listAgentIds(e.cfg).includes(r.agentId) ? r.agentId : e.agentId;
const c = `agent:${s}:acp:${randomUUID()}`;
const l = resolveSpawnedWorkspaceInheritance({
config: e.cfg,
targetAgentId: s,
requesterSessionKey: e.sessionKey,
explicitWorkspaceDir: r.cwd
});
let u;
try {
u = await resolveRuntimeCwdForAcpSpawn({
resolvedCwd: l,
explicitCwd: r.cwd
});
} catch (e) {
return acpCommandErrorReply(e, "Could not resolve ACP session workspace.", "ACP_SESSION_INIT_FAILED");
}
let d;
try {
d = await o.initializeSession({
assertActive: e.command.assertOwnerCurrent,
cfg: e.cfg,
sessionKey: c,
agentId: s,
agent: r.agentId,
mode: r.mode,
cwd: u
});
} catch (e) {
return acpCommandErrorReply(e, "Could not initialize ACP session runtime.", "ACP_SESSION_INIT_FAILED");
}
const { sessionEntry: f, closeRuntimeOnFailure: p, meta: m } = d;
const h = d.handle.backend || m.backend;
const cleanupSpawn = () => cleanupFailedAcpSpawn({
cfg: e.cfg,
sessionKey: c,
agentId: s,
sessionEntry: f,
deleteTranscript: false,
closeRuntimeOnFailure: p
});
let g;
if (r.bind !== "off" || r.thread !== "off") {
const t = await bindSpawnedAcpSession({
commandParams: e,
sessionKey: c,
agentId: s,
label: r.label ?? r.agentId,
mode: r.bind !== "off" ? "conversation" : r.thread === "here" ? "thread-here" : "thread-auto",
sessionMeta: m
});
if (!t.ok) {
await cleanupSpawn();
return commandReply(`⚠️ ${t.error}`);
}
g = t.bound;
}
try {
await persistSpawnedSessionLabel({
commandParams: e,
sessionKey: c,
agentId: s,
label: r.label
});
} catch (e) {
await cleanupSpawn();
const t = formatErrorMessage(e);
return commandReply(`⚠️ ACP spawn failed: ${t}`);
}
const _ = [`✅ Spawned ACP session ${c} (${r.mode}, backend ${h}).`];
if (g) {
const { binding: e, placement: t, labelNoun: n } = g;
const r = e.conversation.conversationId.trim();
if (t === "current") _.push(`Bound this ${n} to ${c}.`);
else _.push(`Created ${n} ${r} and bound it to ${c}.`);
const i = await resolveBoundReplyPayload({
binding: e,
placement: t
});
if (i) return commandReply({
text: _.join(" "),
...i
});
} else _.push("Session is unbound (use /acp spawn ... --bind here to create a session bound to this conversation).");
const v = resolveAcpDispatchPolicyMessage(e.cfg);
if (v) _.push(`ℹ️ ${v}`);
return commandReply(_.join(" "));
}
async function withResolvedAcpSessionTarget(e) {
const t = getAcpSessionManager();
const n = await resolveAcpTargetSessionKey({
commandParams: e.commandParams,
token: e.token
});
if (!n.ok) return commandReply(`⚠️ ${n.error}`);
const r = await t.resolveSessionAsync({
cfg: e.commandParams.cfg,
...n,
assertCurrent: e.commandParams.command.assertOwnerCurrent
});
e.commandParams.command.assertOwnerCurrent?.();
const i = resolveAcpSessionResolutionError(r);
if (i) return acpCommandErrorReply(i, i.message, "ACP_SESSION_INIT_FAILED");
return await e.run({
acpManager: t,
...n
});
}
/**
* Stops the target's controller turns with source `client-session`. When Stop finds no
* turn or waiting input, it sends ACP cancel to a backend that may still be running.
*/
async function handleAcpCancelAction(e, t) {
return await withResolvedAcpSessionTarget({
commandParams: e,
token: normalizeOptionalString(t.join(" ")),
run: async ({ acpManager: t, sessionKey: n, agentId: r }) => await withAcpCommandErrorBoundary({
run: async () => {
const i = e.command.assertOwnerCurrent;
const { storePath: a } = resolveSessionStorePathForAcp({
cfg: e.cfg,
sessionKey: n,
agentId: r
});
const o = captureSessionTarget({
storeScope: a,
sessionKey: n,
agentId: r
});
return await runSessionMutation({
target: o,
policy: "allow-live",
assertCurrent: i,
run: async () => {
const a = await stopSession({
source: "client-session",
capture: captureSessionControllerStop({
targets: [o],
resolveGatewayContext: readChannelContextGatewayContextResolver(e.rootCtx ?? e.ctx) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext
}),
assertCurrent: i,
hookContext: {
sessionKey: n,
commandSource: e.command.surface,
senderId: e.command.senderId
},
stopChildren: (t) => stopSubagentsForRequester({
cfg: e.cfg,
requesterSessionKey: n,
requesterAgentId: r,
assertCurrent: i,
beforeKill: async (e) => {
e();
return await t();
}
})
}).completed;
if (a.alreadyFinalizing && !a.aborted) return commandReply(formatAbortReplyText(a.childrenStopped, "finalizing"));
if (!a.aborted && a.queuedCancelled === 0) await t.cancelSession({
assertActive: i,
cfg: e.cfg,
sessionKey: n,
agentId: r,
reason: "manual-cancel"
});
return commandReply(`✅ Cancel requested for ACP session ${n}.`);
}
});
},
fallbackMessage: "ACP cancel failed before completion."
})
});
}
async function handleAcpSteerAction(e, t, n) {
const r = resolveAcpDispatchPolicyError(e.cfg);
if (r) return acpCommandErrorReply(r, r.message, "ACP_DISPATCH_DISABLED");
const i = parseSteerInput(n);
if (!i.ok) return commandReply(`⚠️ ${i.error}`);
return await withResolvedAcpSessionTarget({
commandParams: e,
token: i.value.sessionToken,
run: async ({ sessionKey: t, agentId: n }) => withAcpCommandErrorBoundary({
run: async () => {
const r = `${resolveCommandRequestId(e)}:steer`;
const a = getAcpSessionManager();
let o = "";
const s = await prepareChannelRunAdmission({
assertSourceCurrent: e.command.assertOwnerCurrent,
cfg: e.cfg,
runId: r,
agentId: n,
ingressKind: "acp",
boundary: "acp.command.steer",
evidence: readChannelContextAdmissionEvidence(e.rootCtx ?? e.ctx),
gatewayLocalUserIngress: getGatewayLocalUserIngress(e.rootCtx ?? e.ctx)
}).admit("acp");
try {
await a.runTurn({
admittedRunContext: s,
cfg: e.cfg,
sessionKey: t,
agentId: n,
provenance: "agent",
text: i.value.instruction,
mode: "steer",
requestId: r,
onEvent: (e) => {
if (e.type !== "text_delta" || e.stream && e.stream !== "output") return;
if (e.text) {
o += e.text;
if (o.length > 800) o = `${truncateUtf16Safe(o, 800)}…`;
}
}
});
} finally {
closeAdmittedRunDelegatedAuthority(s);
}
const c = o.trim();
return commandReply(`✅ ACP steer sent to ${t}.${c ? `\n${c}` : ""}`);
},
fallbackMessage: "ACP steer failed before completion."
})
});
}
async function handleAcpCloseAction(e, t) {
return await withResolvedAcpSessionTarget({
commandParams: e,
token: normalizeOptionalString(t.join(" ")),
run: async ({ acpManager: t, sessionKey: n, agentId: r }) => {
let i;
try {
const a = await t.closeSession({
assertActive: e.command.assertOwnerCurrent,
cfg: e.cfg,
sessionKey: n,
agentId: r,
reason: "manual-close",
allowBackendUnavailable: true,
clearMeta: true
});
i = a.runtimeNotice ? ` (${a.runtimeNotice})` : "";
} catch (e) {
return acpCommandErrorReply(e, "ACP close failed before completion.");
}
const a = await getSessionBindingService().unbind({
targetSessionKey: n,
reason: "manual"
});
return commandReply(`✅ Closed ACP session ${n}${i}. Removed ${a.length} binding${a.length === 1 ? "" : "s"}.`);
}
});
}
//#endregion
export { handleAcpCancelAction, handleAcpCloseAction, handleAcpSpawnAction, handleAcpSteerAction };