UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

454 lines (453 loc) • 16.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as GATEWAY_CLIENT_IDS } from "./client-info-Cm1BcrMm.mjs"; import { _s as validateChatPendingInputsDismissParams, hs as validateChatMessageGetParams, ms as validateChatInjectParams, vs as validateChatPredictParams, xs as validateChatToolTitlesParams } from "./src-BX8OAe1J.mjs"; import { i as resolveSessionWorkStartError } from "./session-work-start-CFJs8WNp.mjs"; import { r as GatewayErrorDetailCodes, t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs"; import { o as runWithSessionActorStorage } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { r as augmentChatHistoryWithCanvasBlocks } from "./chat-display-projection.canvas-XAAIxHM8.mjs"; import { r as jsonUtf8Bytes } from "./json-utf8-bytes-DNwtq2cu.mjs"; import { R as readSessionPendingInput } from "./session-accessor-CizTbDQj.mjs"; import { t as MAX_PAYLOAD_BYTES } from "./payload-limits-ChDi8AHf.mjs"; import { r as getCliSessionBinding } from "./cli-session-binding-BEOgFSDg.mjs"; import { t as acquireSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs"; import { E as captureRpcSourceScopeMatcher } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { r as CHAT_PENDING_INPUT_MESSAGE_PREFIX } from "./chat-history-constants-BGgHv5E_.mjs"; import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs"; import { a as getRpcSourceIdentity, r as getRpcSourceForGateway } from "./session-controller.rpc-sources-CTFbRW2t.mjs"; import { t as chatRunBelongsToAgent } from "./chat-run-owner-2pVCqGmw.mjs"; import { i as projectOperatorModelRead } from "./operator-model-presentation-BAAXja2o.mjs"; import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs"; import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs"; import { s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs"; import { t as resolveCurrentUserProfileDisplay } from "./current-user-profile-display-BvqB5fqy.mjs"; import { i as resolveVisibleActiveSessionRunState } from "./session-active-runs-ENHF8ERS.mjs"; import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs"; import { t as respondError } from "./response-C7fEiIN1.mjs"; import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { o as projectChatDisplayMessage } from "./chat-display-projection.core-ApUvO4fQ.mjs"; import "./session-utils-CavYkLyd.mjs"; import "./chat-display-projection-lHBiRfmJ.mjs"; import { l as waitForChatAbortTerminalPersistence } from "./chat-abort-lifecycle-internal-ChM03p20.mjs"; import { t as injectGatewayAssistantMessage } from "./chat-inject-Dw3xs_Sq.mjs"; import { n as readChatHistoryPage, t as readChatHistoryMessageById } from "./chat-history-pages-DJbqhqAa.mjs"; import { t as prepareForwardedMessageCronJobNameResolver } from "./chat-display-projection.cron-2V2VZ-K7.mjs"; import { n as projectPendingInputMessage } from "./chat-pending-inputs-Dxwqhxeq.mjs"; import { n as dismissRetiredSessionPendingInputs } from "./session-pending-input-withdrawal-xz1ui5pv.mjs"; import { r as prepareChatHistorySessionRead, t as chatHistoryHandlers } from "./chat-history-handler-CDhnb8A5.mjs"; //#region src/gateway/server-methods/chat-message-get-handler.ts const chatMessageGetHandlers = { "chat.message.get": defineValidatedGatewayHandler("chat.message.get", validateChatMessageGetParams, async ({ params: e, respond: t, context: n, client: r, sessionMutationAuthorization: i, signal: a }) => { const { sessionKey: o, messageId: s, maxChars: c, sessionId: l } = e; const u = r?.connect.client?.id === GATEWAY_CLIENT_IDS.CONTROL_UI; const d = normalizeOptionalString(e.agentId); const f = await prepareChatHistorySessionRead({ context: n, client: r, respond: t, sessionMutationAuthorization: i, signal: a, method: "chat.message.get", sessionKey: o, agentIdOverride: d, requestedSessionId: l }); if (!f) return; try { const { selectedSession: e, entry: i, queries: o, readCurrentSharing: d, rowProjection: p } = f; const { cfg: m, agentId: h, storePath: g, canonicalKey: _ } = e; const v = l ?? i?.sessionId; const y = l && l !== i?.sessionId ? void 0 : i; const withCurrentSession = (e) => withReadySessionRows(p, o, (t) => { a?.throwIfAborted(); return d(t) ? e() : void 0; }); const respondNotFound = () => t(true, { ok: false, unavailableReason: "not_found" }); const respondMessage = (e, i = false) => { if (!e) { t(true, { ok: false, unavailableReason: "not_visible" }); return; } t(true, jsonUtf8Bytes(e) > 26214400 - 1024 ? { ok: false, unavailableReason: "oversized" } : i ? projectOperatorModelRead({ context: n, client: r, agentId: h }, { ok: true, message: e }) : { ok: true, message: e }); }; if (!v) { await withCurrentSession(respondNotFound); return; } const b = c ?? Math.min(26214400, 1e6); if (s.startsWith("pending:")) { if (v !== i?.sessionId) { await withCurrentSession(respondNotFound); return; } const e = await readSessionPendingInput({ agentId: h, sessionKey: _, sessionId: v, storePath: g }, s.slice(CHAT_PENDING_INPUT_MESSAGE_PREFIX.length)); if (!await withCurrentSession(() => true)) return; if (!e) { await withCurrentSession(respondNotFound); return; } const t = await prepareForwardedMessageCronJobNameResolver([e.message], n.cronStorePath); await withCurrentSession(() => { const n = projectPendingInputMessage(e, b, void 0, t); respondMessage(n); }); return; } const x = await readChatHistoryMessageById({ includePluginSteering: u, entry: y, provider: getCliSessionBinding(y, "claude-cli")?.sessionId ? resolveSessionModelRef(m, y, h, { allowPluginNormalization: false }).provider : void 0, sessionAgentId: h, sessionId: v, canonicalKey: _, storePath: g, messageId: s, max: 1, maxHistoryBytes: MAX_PAYLOAD_BYTES, effectiveMaxChars: b, offset: void 0 }); if (!await withCurrentSession(() => true)) return; if (!x.found) { await withCurrentSession(respondNotFound); return; } if (x.oversized) { await withCurrentSession(() => t(true, { ok: false, unavailableReason: "oversized" })); return; } const S = await prepareForwardedMessageCronJobNameResolver([x.message], n.cronStorePath); await withCurrentSession(() => { const e = x.message ? projectChatDisplayMessage(x.message, { includeCommentaryFallbacks: true, includePluginSteering: u, maxChars: b, resolveCurrentUserProfileDisplay, resolveCronJobName: S }) : void 0; const t = e ? augmentChatHistoryWithCanvasBlocks([e])[0] : void 0; respondMessage(t, true); }); } finally { f.release(); } }) }; //#endregion //#region src/gateway/server-methods/chat-pending-inputs-dismiss-handler.ts const METHOD = "chat.pendingInputs.dismiss"; const chatPendingInputsDismissHandlers = { [METHOD]: async ({ params: e, respond: t, context: n, client: r, signal: i, sessionMutationAuthorization: a, sessionAccessAuthority: o }) => { if (!assertValidParams(e, validateChatPendingInputsDismissParams, METHOD, t)) return; if (!o) { t(false, void 0, errorShape(ErrorCodes.FORBIDDEN, "Dismissing pending inputs requires session write access.")); return; } const s = o.target; const staleTarget = () => t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "The conversation changed before pending inputs were dismissed; reload and retry.")); if (e.sessionId !== s.sessionId) { staleTarget(); return; } let c; try { c = await prepareChatHistorySessionRead({ context: n, client: r, respond: t, signal: i, sessionMutationAuthorization: a, method: METHOD, sessionKey: e.sessionKey, agentIdOverride: e.agentId }); if (!c) return; const { agentId: l, canonicalKey: u, storePath: d } = c.selectedSession; if (l !== s.agentId || u !== s.sessionKey || c.entry?.sessionId !== s.sessionId) { staleTarget(); return; } const f = await dismissRetiredSessionPendingInputs({ agentId: l, sessionKey: u, sessionId: s.sessionId, storePath: d }, e.inputIds, () => { i?.throwIfAborted(); o.assertCurrent(); }); if (f.kind === "stale") { staleTarget(); return; } if (f.kind === "active") { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "Only cancelled pending inputs can be dismissed; queued and running inputs stay in place.", { details: { code: GatewayErrorDetailCodes.PENDING_INPUT_NOT_RETIRED, inputIds: f.inputIds } })); return; } if (f.inputIds.length) emitSessionsChanged(n, { sessionKey: u, sessionId: s.sessionId, agentId: l, reason: "agent.input.settled" }, { accessChanged: false }); t(true, { dismissedIds: f.inputIds, runIds: f.runIds.filter((e) => e.length <= 256), missingIds: f.missingIds }); } catch (e) { if (e instanceof SessionMutationAuthorizationChangedError) { t(false, void 0, e.error); return; } throw e; } finally { c?.release(); } } }; //#endregion //#region src/gateway/server-methods/chat-prediction-handler.ts var PredictionObsoleteError = class extends Error {}; function conversationText(e) { const t = e.flatMap((e) => { const t = asOptionalRecord(e); if (!t || t.role !== "user" && t.role !== "assistant") return []; const n = typeof t.content === "string" ? t.content : Array.isArray(t.content) ? t.content.flatMap((e) => { const t = asOptionalRecord(e); return t?.type === "text" && typeof t.text === "string" ? [t.text] : []; }).join("\n") : ""; return n.trim() ? [{ role: t.role, text: n.slice(0, 2e3) }] : []; }); if (t.at(-1)?.role !== "assistant" || !t.some((e) => e.role === "user")) return; return JSON.stringify(t.slice(-8)); } const chatPredictionHandlers = { "chat.predict": async (e) => { const { params: t, respond: n, context: r, client: i, signal: a, sessionMutationAuthorization: o, sessionAccessAuthority: s, hasCurrentClientAuthority: c } = e; if (!assertValidParams(t, validateChatPredictParams, "chat.predict", n)) return; const l = r.getRuntimeConfig().gateway?.controlUi?.experimental?.composerPredictions; if (l?.enabled !== true) { n(true, { text: null }); return; } if (!i?.connId || !s) { respondError(n, ErrorCodes.FORBIDDEN, "Composer predictions require a connected composer with session write access."); return; } const u = i.connId; let d; let f; try { const e = s.target; const p = getSessionRowProjection(r)?.sharingTarget({ agentId: e.agentId, key: e.sessionKey }); const m = r.resolveGatewayContext; const h = getRpcSourceForGateway(t.runId, m); const g = h && getRpcSourceIdentity(h); if (h && p && captureRpcSourceScopeMatcher({ storePath: p.storePath, resolveGatewayContext: m })(h) && g?.sessionId === e.sessionId && g.sessionKey === e.sessionKey && chatRunBelongsToAgent(g, e.agentId) && (h.adapter.projectSessionTerminalPending || h.adapter.projectSessionTerminalPersistence)) { await racePromiseWithAbortSignal(waitForChatAbortTerminalPersistence(h), a); s.assertCurrent(); } d = await prepareChatHistorySessionRead({ context: r, client: i, respond: n, signal: a, sessionMutationAuthorization: o, method: "chat.predict", sessionKey: t.sessionKey }); if (!d) return; const { selectedSession: _, entry: v, rowProjection: y, queries: b, readCurrentSharing: x } = d; const { cfg: S, agentId: C, canonicalKey: w, storePath: T } = _; if (!v) { n(true, { text: null }); return; } const E = v.sessionId; const D = l.model ?? "utility"; const assertCompletedAnchor = (e) => { if (!E || e?.sessionId !== E || e.lastRunId !== t.runId || e.status !== "done" || e.lifecycleRunId || resolveSessionWorkStartError(w, e) || resolveVisibleActiveSessionRunState({ storePath: T, resolveGatewayContext: m, requestedKey: t.sessionKey, canonicalKey: w, sessionId: E, agentId: C, includeTerminalPersistence: true }).active) throw new PredictionObsoleteError(); }; const assertCurrent = () => { a?.throwIfAborted(); s.assertCurrent(); if (c?.() === false || r.isConnectionActive?.(u) === false) throw new PredictionObsoleteError(); const e = r.getRuntimeConfig().gateway?.controlUi?.experimental?.composerPredictions; if (e?.enabled !== true || (e.model ?? "utility") !== D) throw new PredictionObsoleteError(); const t = y.describe({ key: w, agentId: C, storePath: T }, _.record); assertCompletedAnchor(t?.storedEntry ?? t?.entry); }; assertCompletedAnchor(v); if (!await withReadySessionRows(y, b, (e) => Boolean(x(e)))) return; assertCurrent(); const O = await readChatHistoryPage({ entry: v, provider: void 0, sessionId: E, storePath: T, sessionAgentId: C, canonicalKey: w, max: 12, maxHistoryBytes: 24e3, responseHistoryBytes: 24e3, effectiveMaxChars: 2e3, toolResultMaxChars: 0, offset: void 0, messageId: void 0, ignoreCliSessionImports: true }, a); assertCurrent(); const k = conversationText(O.messages); if (!k) { n(true, { text: null }); return; } f = await captureGatewayOperatorRunAuthority({ client: i, context: r, hasCurrentClientAuthority: c, invocationAuthority: { assertCurrent, signal: a } }); assertCurrent(); if (!f) { respondError(n, ErrorCodes.FORBIDDEN, "Composer predictions require an authenticated operator."); return; } const { completeComposerPrediction: A } = await import("./composer-prediction-completion-BMiL2Vnp.mjs"); assertCurrent(); const j = await A({ cfg: S, agentId: C, sessionKey: w, entry: v, choice: D, conversation: k, assertCurrent, operatorAuthority: f.authority, signal: a }); assertCurrent(); n(true, { text: j }); } catch (e) { if (e instanceof PredictionObsoleteError) n(true, { text: null }); else if (e instanceof SessionMutationAuthorizationChangedError) n(false, void 0, e.error); else respondError(n, ErrorCodes.UNAVAILABLE, "Composer predictions are unavailable for the selected model."); } finally { f?.release(); d?.release(); } } }; //#endregion //#region src/gateway/server-methods/chat.ts const chatHandlers = { ...chatHistoryHandlers, ...chatMessageGetHandlers, ...chatPredictionHandlers, ...chatPendingInputsDismissHandlers, "chat.toolTitles": async ({ params: e, respond: t }) => { if (!assertValidParams(e, validateChatToolTitlesParams, "chat.toolTitles", t)) return; t(true, { titles: {}, disabled: true }); }, "chat.inject": async (e) => { const { params: t, respond: n, sessionMutationCommitGuard: r } = e; if (!assertValidParams(t, validateChatInjectParams, "chat.inject", n)) return; if (!isIncognitoSessionKey(t.sessionKey)) return injectChat(e, t); const assertCurrent = () => r?.(); const i = await acquireSessionActorStorage({ sessionKey: t.sessionKey, agentId: normalizeOptionalString(t.agentId) }, { lifetime: { assertCurrent, assertReadable: assertCurrent }, authority: { assertCurrent, authorize: assertCurrent } }); if (!i) { n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "session not found")); return; } try { await runWithSessionActorStorage(i, () => injectChat(e, t)); } finally { await i.actor.release(); } } }; async function injectChat({ respond: e, context: t, sessionMutationCommitGuard: n }, r) { const i = await injectGatewayAssistantMessage(t, { sessionKey: r.sessionKey, agentId: r.agentId, message: r.message, label: r.label }, n); if (i.ok) e(true, { ok: true, messageId: i.value.messageId }); else e(false, void 0, i.error); } //#endregion export { chatHandlers };