UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

236 lines (235 loc) • 10 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { d as getActivePluginRegistryWorkspaceDirFromStateCore } from "./model-ref-shared-DqE2RqZv.mjs"; import { n as normalizeAgentId, t as isValidAgentId } from "./agent-id-CQjtp2ft.mjs"; import { n as buildAgentMainSessionKey } from "./session-key-DW1jcHbM.mjs"; import { C as isSubagentSessionKey, x as isCronSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { _ as resolveDefaultAgentId, t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs"; import { i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs"; import { n as parseModelRef } from "./model-selection-normalize-DIZCRGVF.mjs"; import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs"; import "./method-scopes-Dpyb0Ck-.mjs"; import { r as getHeader } from "./http-header-value-BTQlMYRm.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { t as canonicalizeSessionKeyForAgent } from "./session-store-key-CEwU3noi.mjs"; import { n as readResolvedSessionEntryInWorker } from "./session-accessor.entry-read-runtime-y5p3nnUX.mjs"; import "./session-accessor.entry-f0bkn7cv.mjs"; import { a as isAgentHarnessSessionKey, s as isAgentHarnessSessionStoreEntryProtected } from "./agent-harness-session-key-BRYGtzM6.mjs"; import { f as isResolvedIncognitoSession, i as authorizePreparedSessionMutation, x as withSessionSharingTarget } from "./session-sharing-policy-3TAaxC-R.mjs"; import { t as createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client-DE2ydcEw.mjs"; import { c as prepareSessionSharingProfiles, o as prepareProjectedSessionSharing } from "./session-sharing-read-BqjuH16A.mjs"; import "./session-sharing-BIP3raq1.mjs"; import { n as createModelVisibilityPolicy } from "./model-visibility-policy-CH4gPfvH.mjs"; import "./model-selection-C2A4Wyix.mjs"; import "./http-auth-utils-B0FI4CE4.mjs"; import { t as loadGatewayModelCatalog } from "./server-model-catalog-DpggHr2T.mjs"; import { randomUUID } from "node:crypto"; //#region src/gateway/http-utils.ts const OPENCLAW_MODEL_ID = "openclaw"; /** Default OpenAI-compatible model alias that targets the default OpenClaw agent. */ const OPENCLAW_DEFAULT_MODEL_ID = "openclaw/default"; const AGENT_MODEL_PATTERN = /^(?:openclaw[:/]|agent:)(?<agentId>[a-z0-9][a-z0-9_-]{0,63})$/i; var UnknownGatewayAgentError = class extends Error { constructor(e) { super(`Unknown agent '${e}'.`); this.agentId = e; this.name = "UnknownGatewayAgentError"; } }; var GatewaySessionKeyOverrideError = class extends Error { constructor() { super("`x-openclaw-session-key` cannot use reserved internal session namespaces."); this.name = "GatewaySessionKeyOverrideError"; } }; var InvalidGatewayModelError = class extends Error { constructor() { super("Invalid `model`. Use `openclaw` or `openclaw/<agentId>`."); this.name = "InvalidGatewayModelError"; } }; function isUnknownGatewayAgentError(e) { return e instanceof UnknownGatewayAgentError; } function isAgentSelectionRequiredError(e) { return e instanceof AgentSelectionRequiredError; } function isGatewayAgentRequestError(e) { return isAgentSelectionRequiredError(e) || e instanceof InvalidGatewayModelError || isUnknownGatewayAgentError(e); } function isGatewayRequestContextError(e) { return isGatewayAgentRequestError(e) || e instanceof GatewaySessionKeyOverrideError; } function assertKnownAgentId(e, t = readRuntimeConfig()) { if (!listAgentIds(t).includes(e)) throw new UnknownGatewayAgentError(e); } function resolveAgentIdFromModel(e, t = readRuntimeConfig()) { const n = e?.trim(); if (!n) return; const r = normalizeLowercaseStringOrEmpty(n); if (r === "openclaw" || r === "openclaw/default") return resolveDefaultAgentId(t); const i = n.match(AGENT_MODEL_PATTERN)?.groups?.agentId; if (!i) return; return normalizeAgentId(i); } /** Maps accepted OpenClaw routing-model spellings to the canonical id listed by `/v1/models`. */ function canonicalizeOpenClawAgentModelId(e) { const t = e?.trim(); if (!t) return; const n = normalizeLowercaseStringOrEmpty(t); if (n === "openclaw" || n === "openclaw/default") return n; const r = t.match(AGENT_MODEL_PATTERN)?.groups?.agentId; return r ? `openclaw/${normalizeAgentId(r)}` : void 0; } /** Checks OpenClaw routing-model syntax without resolving fleet ownership. */ function isOpenClawAgentModelId(e) { return canonicalizeOpenClawAgentModelId(e) !== void 0; } /** Validates and resolves the `x-openclaw-model` override for OpenAI-compatible requests. */ async function resolveOpenAiCompatModelOverride(e) { const t = e.model?.trim(); if (t && !isOpenClawAgentModelId(t)) return { errorMessage: "Invalid `model`. Use `openclaw` or `openclaw/<agentId>`." }; const n = getHeader(e.req, "x-openclaw-model")?.trim(); if (!n) return {}; const r = readRuntimeConfig(); const i = resolveDefaultModelForAgent({ cfg: r, agentId: e.agentId }).provider; const a = getActivePluginRegistryWorkspaceDirFromStateCore(); const o = { manifestPlugins: getCurrentPluginMetadataSnapshot({ config: r, env: process.env, ...a ? { workspaceDir: a } : {} }) }; const s = parseModelRef(n, i, { allowManifestNormalization: true, allowPluginNormalization: true, ...o }); if (!s) return { errorMessage: "Invalid `x-openclaw-model`." }; const c = await loadGatewayModelCatalog({ agentId: e.agentId }); const l = createModelVisibilityPolicy({ cfg: r, catalog: c, defaultProvider: i, agentId: e.agentId, allowManifestNormalization: true, allowPluginNormalization: true, ...o }); const u = modelKey(s.provider, s.model); if (!l.allows(s)) return { errorMessage: `Model '${u}' is not allowed for agent '${e.agentId}'.` }; return { modelOverride: n }; } /** Resolves the request agent from headers, model alias, or the configured default. */ function resolveAgentIdForRequest(e) { const t = readRuntimeConfig(); if (e.model?.trim() && !isOpenClawAgentModelId(e.model)) throw new InvalidGatewayModelError(); const n = normalizeOptionalString(getHeader(e.req, "x-openclaw-agent-id")) || normalizeOptionalString(getHeader(e.req, "x-openclaw-agent")); if (n) { if (!isValidAgentId(n)) throw new UnknownGatewayAgentError(n); const e = normalizeAgentId(n); assertKnownAgentId(e, t); return e; } const r = resolveAgentIdFromModel(e.model, t); if (r) { assertKnownAgentId(r, t); return r; } return resolveDefaultAgentId(t); } async function isReservedSessionKeyOverride(e, t) { const n = normalizeLowercaseStringOrEmpty(e); const r = e.startsWith("agent:") ? e : canonicalizeSessionKeyForAgent(t, e); const i = isAgentHarnessSessionKey(e) ? await readResolvedSessionEntryInWorker({ cfg: readRuntimeConfig(), sessionKey: r }) : void 0; const a = isAgentHarnessSessionKey(e) && (!i || isAgentHarnessSessionStoreEntryProtected(e, i)); return n.startsWith("subagent:") || n.startsWith("cron:") || n.startsWith("acp:") || a || isSubagentSessionKey(e) || isCronSessionKey(e) || isAcpSessionKey(e); } async function resolveGatewayRequestContext(e) { const t = resolveAgentIdForRequest({ req: e.req, model: e.model }); const n = getHeader(e.req, "x-openclaw-session-key")?.trim(); let r; if (n) { if (await isReservedSessionKeyOverride(n, t)) throw new GatewaySessionKeyOverrideError(); r = n; } else { const n = e.user?.trim(); const i = n ? `${e.sessionPrefix}-user:${n}` : `${e.sessionPrefix}:${randomUUID()}`; r = buildAgentMainSessionKey({ agentId: t, mainKey: i }); } const i = normalizeMessageChannel(getHeader(e.req, "x-openclaw-message-channel")) ?? "webchat"; return { agentId: t, sessionKey: r, messageChannel: i }; } async function authorizeOpenAiCompatibleHttpSession(e) { const t = e.requestAuth.authenticatedUserProfile; const n = createSyntheticPluginRuntimeClient({ ...t ? { authenticatedUserProfile: t } : {}, operatorRoleActor: e.requestAuth.operatorRoleActor, operatorAccessAuthority: e.requestAuth.operatorAccessAuthority, scopes: e.senderIsOwner ? [ADMIN_SCOPE] : [] }); const r = await prepareSessionSharingProfiles(n); return withSessionSharingTarget({ cfg: readRuntimeConfig(), sessionKey: e.sessionKey, agentId: e.agentId }, (i) => { i.assertCurrent(); const a = readRuntimeConfig(); const o = new Set(i.members.map((e) => e.identityId)); const s = prepareProjectedSessionSharing({ cfg: a, client: n, profiles: r, isMember: (e, t) => o.has(t) }); const c = authorizePreparedSessionMutation({ cfg: a, client: n, sessionKey: e.sessionKey, agentId: e.agentId }, { target: i.target, membership: o }, { policy: s.policy, aliases: r.readCurrent().profile?.aliases ?? /* @__PURE__ */ new Set() }); if (c) return { allowed: false, message: c.message }; if (!e.senderIsOwner && !t && isResolvedIncognitoSession({ cfg: a, sessionKey: e.sessionKey, agentId: e.agentId }, i.target)) return { allowed: false, message: `missing scope: ${ADMIN_SCOPE}` }; return { allowed: true }; }); } //#endregion export { isAgentSelectionRequiredError as a, isOpenClawAgentModelId as c, resolveGatewayRequestContext as d, resolveOpenAiCompatModelOverride as f, canonicalizeOpenClawAgentModelId as i, isUnknownGatewayAgentError as l, OPENCLAW_MODEL_ID as n, isGatewayAgentRequestError as o, authorizeOpenAiCompatibleHttpSession as r, isGatewayRequestContextError as s, OPENCLAW_DEFAULT_MODEL_ID as t, resolveAgentIdForRequest as u };