openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
201 lines (200 loc) • 8.04 kB
JavaScript
import { l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { _ as resolveDefaultAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as parseConfigPath, r as setConfigValueAtPath, t as getConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as REDACTED_SENTINEL } from "./redact-sentinel-Db2p5Put.mjs";
import { X as captureSessionTarget, d as getSessionControllerOperation, m as hasReplyOperationExecutionStarted } from "./session-controller.state-BApgK0mV.mjs";
import { t as appendAssistantMessageToSessionTranscript } from "./transcript-CbrBMDcL.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { i as isSessionRunActiveForKey } from "./session-controller.queries-D7T8foQX.mjs";
import { o as parseSlashCommandOrNull } from "./commands-registry.data-CoxL3Db3.mjs";
import { n as normalizeCommandBody } from "./commands-registry-normalize-dI3NYF5y.mjs";
import { t as parseConfigValue } from "./config-value-DndLgxrK.mjs";
import { r as waitForSessionRunIdle } from "./session-controller.wait-DKnNX-C5.mjs";
//#region src/auto-reply/reply/commands-setunset.ts
/** Parses a slash command whose actions include set/unset plus custom actions. */
function parseSlashCommandWithSetUnset(e) {
const t = parseSlashCommandOrNull(e.raw, e.slash);
if (!t) return null;
const error = (e) => ({
action: "error",
message: e
});
const { action: n, args: r } = t;
if (n === "unset") return r ? {
action: "unset",
path: r
} : error(`Usage: ${e.slash} unset path`);
if (n === "set") {
const t = r.indexOf("=");
const n = t > 0 ? r.slice(0, t).trim() : "";
if (!n) return error(`Usage: ${e.slash} set path=value`);
const i = parseConfigValue(r.slice(t + 1));
return i.error ? error(i.error) : {
action: "set",
path: n,
value: i.value
};
}
return e.onKnownAction(n, r) || error(e.usageMessage);
}
//#endregion
//#region src/auto-reply/reply/config-commands.ts
function parseConfigCommand(e) {
return parseSlashCommandWithSetUnset({
raw: e,
slash: "/config",
usageMessage: "Usage: /config show|set|unset",
onKnownAction: (e, t) => {
if (e === "show" || e === "get") return {
action: "show",
path: t || void 0
};
}
});
}
//#endregion
//#region src/auto-reply/reply/debug-commands.ts
function parseDebugCommand(e) {
return parseSlashCommandWithSetUnset({
raw: e,
slash: "/debug",
usageMessage: "Usage: /debug show|set|unset|reset",
onKnownAction: (e) => e === "show" || e === "reset" ? { action: e } : void 0
});
}
//#endregion
//#region src/config/sessions/command-transcript.ts
function scopeCommandTranscriptId(e, t) {
return e ? JSON.stringify([
t.channelId ?? "",
t.accountId ?? "",
t.conversationId ?? "",
e
]) : void 0;
}
async function redactConfigCommandInput(e) {
const t = parseSlashCommandOrNull(e, "/config") ? "/config" : "/debug";
if (parseSlashCommandOrNull(e, t)?.action !== "set") return e;
const n = t === "/config" ? parseConfigCommand(e) : parseDebugCommand(e);
if (n?.action !== "set") return `${t} set ${REDACTED_SENTINEL}`;
const r = parseConfigPath(n.path);
if (!r.ok) return `${t} set ${REDACTED_SENTINEL}`;
const [{ redactConfigObject: i }, { loadGatewayConfigRedactionHints: a }] = await Promise.all([import("./redact-snapshot-D48uHOIm.mjs"), import("./runtime-schema-BzOMdj_y.mjs")]);
const o = {};
setConfigValueAtPath(o, r.path, n.value);
const s = i(o, a());
return `${t} set ${n.path}=${JSON.stringify(getConfigValueAtPath(s, r.path))}`;
}
function redactCommandTranscriptText(e, t) {
const n = t.replace(/\b((?:device|pairing|verification|login|setup)\s+code|code)\s*:\s*(?:<code>)?[^\s<]+(?:<\/code>)?/gi, "$1: [login code redacted]");
return (/^\/pair(?:@\S+)?(?:\s|$)/i.test(e) ? n.replace(/\beyJ[A-Za-z0-9_-]{32,}={0,2}\b/g, "[pairing code redacted]") : n).replace(/https?:\/\/[^\s<>]+/gi, (t) => /^\/login(?:@\S+)?(?:\s|$)/i.test(e) || /[?&](?:[\w-]*token|state|code|user_code|device_code|secret|key)=/i.test(t) ? "[login URL redacted]" : t);
}
function normalizeCommandTranscriptText(e) {
return normalizeCommandBody(e, {
targetedCommandMode: "pre-identity",
preserveArguments: true
}).trim();
}
function isEphemeralCommandTranscript(e) {
return /^\/(?:btw|side)(?:@\S+)?(?:\s|$)/i.test(e);
}
/** The stored, redacted form of a command input; undefined for ephemeral commands. */
async function prepareCommandTranscriptInput(e) {
const t = normalizeCommandTranscriptText(e);
if (!t || isEphemeralCommandTranscript(t)) return;
return redactCommandTranscriptText(t, await redactConfigCommandInput(t));
}
/** Bounds how often a deferred exchange re-waits when follow-up turns keep the session busy. */
const MAX_DEFERRED_COMMAND_EXCHANGE_WAITS = 8;
/**
* A started turn owns the session's model-context fence until it commits. A context-bearing
* exchange appended inside that window invalidates the turn's prepared answer, so it waits
* until no turn is executing. Rows coordinated with a writer run
* cannot move the fence.
*/
function resolveExchangeTarget(e) {
const t = e.sessionKey.trim();
try {
const n = e.agentId?.trim() || resolveAgentIdFromSessionKey(t, e.config ? resolveDefaultAgentId(e.config) : void 0);
const r = e.storePath ?? resolveSessionStorePathCore(e.config?.session?.store, { agentId: n });
return captureSessionTarget({
storeScope: r,
sessionKey: t,
agentId: n
});
} catch {
return;
}
}
function shouldDeferUntilActiveTurnSettles(e, t) {
if (e.expectedWriterRunId) return false;
const n = e.sessionKey.trim();
try {
if (t) {
const e = getSessionControllerOperation(n, t);
return e !== void 0 && hasReplyOperationExecutionStarted(e);
}
} catch {}
return isSessionRunActiveForKey(n);
}
async function recordAfterActiveTurnSettles(e, t) {
for (let n = 0; n < MAX_DEFERRED_COMMAND_EXCHANGE_WAITS; n += 1) {
await waitForSessionRunIdle(e.sessionKey, void 0, t ? { target: t } : void 0);
if (!shouldDeferUntilActiveTurnSettles(e, t)) return await recordDeliveredCommandExchangeNow(e);
}
logVerbose("Command transcript recording skipped: session stayed busy after delivery");
return {
ok: false,
reason: "session stayed busy"
};
}
/**
* Records only settled command output; callers must first confirm delivery. During an active
* turn the exchange is recorded after that turn settles, so it still enters later model context
* without cancelling the running answer.
*/
async function recordDeliveredCommandExchange(e) {
if (isEphemeralCommandTranscript(normalizeCommandTranscriptText(e.commandText))) return {
ok: false,
reason: "ephemeral command"
};
const t = resolveExchangeTarget(e);
if (shouldDeferUntilActiveTurnSettles(e, t)) {
recordAfterActiveTurnSettles(e, t).catch(() => {
logVerbose("Command transcript recording failed after delivery");
});
return {
ok: false,
reason: "deferred until the active turn settles"
};
}
return await recordDeliveredCommandExchangeNow(e);
}
async function recordDeliveredCommandExchangeNow(e) {
const t = normalizeCommandTranscriptText(e.commandText);
if (isEphemeralCommandTranscript(t)) return {
ok: false,
reason: "ephemeral command"
};
try {
return await appendAssistantMessageToSessionTranscript({
...e,
text: redactCommandTranscriptText(t, e.replyText),
...e.commandInputCommitted ? {} : { command: {
text: redactCommandTranscriptText(t, await redactConfigCommandInput(t)),
idempotencyKey: `command-input:${e.commandId}`
} },
idempotencyKey: `command-reply:${e.commandId}:${e.replyId}`
});
} catch {
logVerbose("Command transcript recording failed after delivery");
return {
ok: false,
reason: "transcript recording failed"
};
}
}
//#endregion
export { parseConfigCommand as a, parseDebugCommand as i, recordDeliveredCommandExchange as n, parseSlashCommandWithSetUnset as o, scopeCommandTranscriptId as r, prepareCommandTranscriptInput as t };