UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

502 lines (501 loc) • 18.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { P as resolveIntegerOption } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { c as normalizeOptionalTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs"; import "./gateway-request-scope-BvvDhs5D.mjs"; import { t as bindGatewayContextResolver } from "./gateway-context-binding-BdXZoMU9.mjs"; import { d as normalizeUsage, o as hasNonzeroUsage } from "./usage-CHLnzpJG.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { a as emitAgentEvent, h as onAgentEventForRun } from "./agent-events-BdfWYmot.mjs"; import "./io-4QsrsWTJ.mjs"; import { _ as retainGatewayRootWorkAdmissionContinuation } from "./gateway-work-admission-79pid1hQ.mjs"; import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs"; import { d as isSignalTimeoutReason, u as isFailoverError } from "./error-BCRqSFIY.mjs"; import { f as resolveGatewayOperatorRoleActor } from "./operator-role-policy-DhcqVpmG.mjs"; import { t as ToolAuthorizationError } from "./tool-input-error-B1hgavSw.mjs"; import { o as buildHistoryContext } from "./history-B0kihfTi.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { t as createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client-DE2ydcEw.mjs"; import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs"; import { t as createDefaultDeps } from "./deps-CeXkTZma.mjs"; import { r as resolveAssistantResultText, t as createAssistantTextStream } from "./agent-event-assistant-text-BJ77EXnU.mjs"; import { t as sendJson } from "./http-json-ddGJz5CA.mjs"; import { a as parseGatewayJsonRequest, c as retainGatewayHttpResponseWork, f as sendMissingScopeForbidden, v as watchClientDisconnect, y as writeDone } from "./http-common-FfhIIwOW.mjs"; import { n as readAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-BQoZ_25h.mjs"; import { c as normalizeMimeList, l as resolveInputFileLimits, n as DEFAULT_INPUT_IMAGE_MIMES, r as DEFAULT_INPUT_TIMEOUT_MS, t as DEFAULT_INPUT_IMAGE_MAX_BYTES } from "./input-files-DKoRlBjP.mjs"; import { i as isClientToolNameConflictError } from "./agent-tool-definition-adapter-CAIOgFtX.mjs"; import { i as authorizeOpenAiCompatibleHttpModelOverride, l as resolveOpenAiCompatibleHttpSenderIsOwner } from "./http-auth-utils-B0FI4CE4.mjs"; import "./http-utils-B5V9Okzh.mjs"; import { n as agentCommandFromGatewayIngress } from "./agent-command-FXkX3hj5.mjs"; import "./agent-WNO-h9tH.mjs"; import { n as GATEWAY_UPLOADS_DISABLED_MESSAGE, r as areGatewayUploadsEnabled, t as GATEWAY_UPLOADS_DISABLED_CODE } from "./upload-policy-Dp8z9OKP.mjs"; import { o as handleGatewayPostJsonEndpoint, t as resolveOpenAiCompatError } from "./openai-compat-errors-DSFdRblo.mjs"; import { STREAM_ERROR_FALLBACK_TEXT } from "@openclaw/ai/internal/shared"; //#region src/gateway/agent-prompt.ts function renderConversationToolCall(e) { return `tool_call id=${e.id ?? ""} name=${e.name} arguments=${e.arguments}`; } const IMAGE_ONLY_USER_MESSAGE = "User sent image(s) with no text."; /** Normalize content-array bodies and omit provenance-marked stream-error placeholders. */ function toPromptBody(e) { const t = e.entry.body; const n = typeof t === "string" ? t : extractTextFromChatContent(t) ?? ""; return e.role === "assistant" && e.internalStreamError === true && n.trim() === STREAM_ERROR_FALLBACK_TEXT ? null : n; } function buildAgentMessageFromConversationEntries(e) { let t = e.findLastIndex((e) => e?.role === "user" || e?.role === "tool"); if (t < 0) t = e.length - 1; const n = e[t]; const r = n?.entry; if (!n || !r) return ""; const i = []; for (let n = 0; n < t; n += 1) { const t = e[n]; const r = toPromptBody(t); if (r !== null) i.push(`${t.entry.sender}: ${r}`); } const a = toPromptBody(n); if (a === null) return ""; if (i.length === 0 && n.role !== "tool") return a; return buildHistoryContext({ historyText: i.join("\n"), currentMessage: `${r.sender}: ${a}` }); } //#endregion //#region src/gateway/http-upload-policy.ts /** Recheck the current client-upload policy before HTTP media preparation and dispatch. */ function rejectDisabledGatewayUpload(e, t) { if (!t || areGatewayUploadsEnabled(readRuntimeConfig())) return false; sendJson(e, 403, { error: { message: GATEWAY_UPLOADS_DISABLED_MESSAGE, type: "forbidden", code: GATEWAY_UPLOADS_DISABLED_CODE } }); return true; } //#endregion //#region src/gateway/openai-agent-run-usage.ts /** An explicit aggregate report owns completeness; legacy counters may use the last call. */ function resolveAgentRunUsage(e) { const t = e?.meta?.agentMeta; const n = normalizeUsage(t?.usage); if (n?.usageReport || hasNonzeroUsage(n)) return n; const r = normalizeUsage(t?.lastCallUsage); if (hasNonzeroUsage(r)) return r; return n ?? r; } //#endregion //#region src/gateway/openai-compatible-agent-run.ts function isGatewayRunCancellation(e) { if (!e || typeof e !== "object" || isFailoverError(e) || !isAbortError(e)) return false; return !isSignalTimeoutReason("cause" in e ? e.cause : void 0); } function resolveOpenAiCompatibleAgentError(e, t) { if (isClientToolNameConflictError(e)) return { status: 400, error: { message: "invalid tool configuration", type: "invalid_request_error" } }; if (isGatewayRunCancellation(e)) return { status: 500, error: { message: "agent run was cancelled", type: "api_error" } }; return resolveOpenAiCompatError(e) ?? { status: 500, error: t ?? { message: "internal error", type: "api_error" } }; } function readOpenAiHttpRunTerminal(e) { const t = asOptionalRecord(asOptionalRecord(e)?.meta); const n = t?.stopReason; const r = typeof n === "string" ? n : void 0; const i = readAgentRunTerminalOutcome(e) === "failed"; const a = i && r === "length" && asOptionalRecord(t?.error)?.kind === "incomplete_turn" ? resolveAssistantResultText(e) : void 0; const o = t?.pendingToolCalls; const s = Array.isArray(o) ? o.flatMap((e) => { const t = asOptionalRecord(e); const n = typeof t?.id === "string" ? t.id.trim() : ""; const r = typeof t?.name === "string" ? t.name.trim() : ""; const i = t?.arguments; const a = typeof i === "string" ? i : i == null ? "" : JSON.stringify(i); return n && r ? [{ id: n, name: r, arguments: a }] : []; }) : void 0; return { runFailed: i, ...a ? { incompleteTurnText: a } : {}, stopReason: r, pendingToolCalls: s }; } async function runOpenAiCompatibleAgentCommand(e) { e.abortSignal?.throwIfAborted(); let t = false; const assertSourceCurrent = () => { if (!t && e.hasClientUploads && !areGatewayUploadsEnabled(readRuntimeConfig())) throw new ToolAuthorizationError(GATEWAY_UPLOADS_DISABLED_MESSAGE); if (!t && e.hasCurrentClientAuthority?.() === false) throw new ToolAuthorizationError("Gateway requester authority changed"); }; assertSourceCurrent(); const n = createSyntheticPluginRuntimeClient({ authenticatedUserProfile: e.requestAuth.authenticatedUserProfile, operatorRoleActor: e.requestAuth.operatorRoleActor, scopes: [...e.operatorScopes] }); const r = resolveGatewayOperatorRoleActor(n)?.kind === "operator"; const i = r ? e.resolveGatewayContext?.() : void 0; if (r && !i) throw new Error("OpenAI-compatible operator execution requires a current Gateway context."); const a = i ? await captureGatewayOperatorRunAuthority({ client: n, context: { getRuntimeConfig: i.getRuntimeConfig, getCommittedRuntimeConfig: i.getCommittedRuntimeConfig, resolveGatewayContext: e.resolveGatewayContext }, sourceAuthority: e.requestAuth.operatorAccessAuthority }) : void 0; try { assertSourceCurrent(); a?.authority.assertCurrent(); const n = a?.authority.signal; const r = e.abortSignal && n ? AbortSignal.any([e.abortSignal, n]) : e.abortSignal ?? n; r?.throwIfAborted(); const i = await agentCommandFromGatewayIngress({ message: e.message, images: e.images?.length ? e.images : void 0, clientTools: e.clientTools?.length ? e.clientTools : void 0, extraSystemPrompt: e.extraSystemPrompt || void 0, model: e.modelOverride, streamParams: e.streamParams, sessionKey: e.sessionKey, runId: e.runId, deliver: false, messageChannel: e.messageChannel, senderIsOwner: e.senderIsOwner, bestEffortDeliver: false, allowModelOverride: e.modelOverride !== void 0, abortSignal: r, operatorAuthority: a?.authority, assertSourceCurrent, onAdmittedRunContext: (n) => { assertSourceCurrent(); bindGatewayContextResolver(n, e.resolveGatewayContext); t = true; } }, defaultRuntime, createDefaultDeps()); a?.authority.assertCurrent(); return i; } finally { a?.release(); } } //#endregion //#region src/gateway/openai-tool-choice.ts function resolveChatToolChoice(e) { if (e == null || e === "auto") return; if (e === "none") return "none"; if (e === "required") return { type: "required" }; const t = asOptionalRecord(e); if (!t) throw new Error("tool_choice must be a string or object"); const n = t.type; if (n === "function") { const e = normalizeOptionalString(asOptionalRecord(t.function)?.name); if (!e) throw new Error("tool_choice.function.name is required"); return { type: "function", name: e }; } if (typeof n !== "string") throw new Error("unsupported tool_choice type"); throw new Error(`tool_choice ${n} is not supported`); } function resolveResponsesToolChoice(e) { if (!e) return; if (e === "none") return "none"; if (e === "required") return { type: "required" }; if (typeof e === "object" && e.type === "function") { const t = ("name" in e ? e.name : e.function.name).trim(); if (!t) throw new Error("tool_choice.name is required"); return { type: "function", name: t }; } } function applyToolChoice(e, t) { if (!t) return { tools: e }; if (t === "none") return { tools: [] }; const n = t.type === "function" ? e.filter((e) => e.function.name === t.name) : e; if (n.length === 0) throw new Error(t.type === "function" ? `tool_choice requested unknown tool: ${t.name}` : "tool_choice=required but no tools were provided"); return { tools: n, extraSystemPrompt: t.type === "function" ? `You must call the ${t.name} tool before responding.` : "You must call one of the available tools before responding.", constraint: t }; } function resolveToolChoiceConstraintError(e, t) { if (!e || t?.length && (e.type === "required" || t.some((t) => t.name === e.name))) return; return e.type === "function" ? `tool_choice required a ${e.name} tool call, but the agent did not produce one` : "tool_choice=required was not satisfied by the agent response"; } //#endregion //#region src/gateway/openai-compatible-http.ts const REPLACEMENT_ERROR = "Assistant output cannot be represented as an append-only response stream."; function incompleteTurnError(e) { return { message: e, type: "api_error", code: "incomplete_turn" }; } async function prepareOpenAiCompatibleHttpRequest(e, t, n) { const r = await handleGatewayPostJsonEndpoint(e, t, { ...n, requiredOperatorMethod: "chat.send" }); if (!r) return r; const i = { abortController: new AbortController() }; watchClientDisconnect(e, t, i.abortController); const a = authorizeOpenAiCompatibleHttpModelOverride(e, r.requestAuth); if (!a.allowed) { sendMissingScopeForbidden(t, a.missingScope); return; } const o = resolveOpenAiCompatibleHttpSenderIsOwner(e, r.requestAuth); const s = parseGatewayJsonRequest(t, r.body, n.schema); return s ? Object.assign(i, r, { payload: s, senderIsOwner: o }) : void 0; } async function sendOpenAiCompatibleJsonResponse(e) { const t = e.fail ?? ((t) => sendJson(e.res, t.status, { error: t.error })); try { const n = await e.run(); if (e.signal.aborted) return true; const { runFailed: r, stopReason: i, pendingToolCalls: a, incompleteTurnText: o } = readOpenAiHttpRunTerminal(n); if (r) { if (o !== void 0) { t({ status: 500, error: incompleteTurnError(o) }, n, o); return true; } throw new Error("agent run failed"); } e.complete({ result: n, stopReason: i, toolCalls: i === "tool_calls" && a?.length ? a : void 0, text: resolveAssistantResultText(n) ?? "", toolChoiceError: resolveToolChoiceConstraintError(e.constraint, a) }); } catch (n) { if (!e.signal.aborted) { logWarn(`${e.failureLabel}: ${String(n)}`); t(resolveOpenAiCompatibleAgentError(n)); } } return true; } /** Own run settlement and text delivery; adapters only encode their wire protocol. */ function startOpenAiCompatibleStream(e) { if (e.signal.aborted) return; const { res: t, runId: n } = e; const r = e.protocol === "chat"; const i = createAssistantTextStream(Boolean(e.constraint)); let a = false; let o = false; let s = false; let c = "end"; let l; let u; let d = false; let f; const close = () => { a = true; p(); e.signal.removeEventListener("abort", onAbort); }; const finish = () => { writeDone(t); t.end(); }; const fail = (t, n, r) => { if (a) return; close(); e.fail(t, n, r); finish(); }; const requestFinalize = () => { if (a || o || !f || !r && !l) return; o = true; (r ? queueMicrotask : setImmediate)(() => { if (a || !f) return; if (u || d) { fail(u ?? { message: REPLACEMENT_ERROR, type: "server_error" }, f.result); return; } const t = i.complete(resolveAssistantResultText(f.result), f.toolCalls ? "" : "No response from OpenClaw."); if (!t.startsWith(i.streamedText)) { fail({ message: REPLACEMENT_ERROR, type: r ? "api_error" : "server_error" }, f.result); return; } close(); e.complete({ ...f, text: t, delta: t.slice(i.streamedText.length), lifecycleError: l?.phase === "error" ? l.error || "Agent run failed" : void 0 }); finish(); }); }; const p = onAgentEventForRun(n, (t) => { if (a) return; if (t.stream === "assistant") { const { delta: n, replacement: a } = i.update(t.data, t.assistantProjection?.rawDelta); if (r && a === "unrepresentable") { u ??= { message: REPLACEMENT_ERROR, type: "api_error" }; return; } if (!r && a) d = a === "unrepresentable"; if (n) e.writeDelta(n); } else if (t.stream === "lifecycle") { const e = t.data?.phase; if (r && e === "start") s = false; if (e === "end" || e === "error") { s = true; l ??= { phase: e, error: normalizeOptionalString(t.data?.error) }; if (r && e === "error" && c !== "error") u ??= { message: normalizeOptionalString(t.data?.error) ?? "Agent run failed", type: "api_error" }; requestFinalize(); } } }); const m = retainGatewayRootWorkAdmissionContinuation(); const h = retainGatewayHttpResponseWork(t); const onAbort = () => { close(); h(); }; e.signal.addEventListener("abort", onAbort, { once: true }); (async () => { try { const t = await e.run(); if (a) return; const { runFailed: n, stopReason: o, pendingToolCalls: s, incompleteTurnText: l } = readOpenAiHttpRunTerminal(t); if (n) { c = "error"; if (l !== void 0) { const n = l.startsWith(i.streamedText) ? l.slice(i.streamedText.length) : ""; if (n && !e.constraint) e.writeDelta(n); fail(incompleteTurnError(l), t, l); return; } fail({ message: "internal error", type: "api_error" }, t); return; } if (r && u) { fail(u); return; } const d = resolveToolChoiceConstraintError(e.constraint, s); if (d) { fail({ message: d, type: "api_error" }, t); return; } f = { result: t, stopReason: o, toolCalls: o === "tool_calls" && s?.length ? s : void 0 }; requestFinalize(); } catch (e) { if (a) return; c = "error"; logWarn(`${r ? "openai-compat: streaming chat completion" : "openresponses: streaming response"} failed: ${String(e)}`); fail(resolveOpenAiCompatibleAgentError(e, r ? u : void 0).error); } finally { m?.(); if (!s && (c === "error" || !a)) emitAgentEvent({ runId: n, stream: "lifecycle", data: { phase: c } }); } })(); } //#endregion //#region src/gateway/openai-compatible-input-limits.ts const DEFAULT_OPENAI_CHAT_COMPLETIONS_BODY_BYTES = 20971520; const DEFAULT_OPENAI_MAX_IMAGE_PARTS = 8; const DEFAULT_OPENAI_MAX_TOTAL_IMAGE_BYTES = 20971520; function resolveImageLimits(e, t) { return { allowUrl: e?.allowUrl ?? t, urlAllowlist: normalizeOptionalTrimmedStringList(e?.urlAllowlist), allowedMimes: normalizeMimeList(e?.allowedMimes, DEFAULT_INPUT_IMAGE_MIMES), maxBytes: e?.maxBytes ?? 10485760, maxRedirects: e?.maxRedirects ?? 3, timeoutMs: e?.timeoutMs ?? 1e4 }; } function resolveOpenAiChatCompletionsLimits(e) { return { maxBodyBytes: DEFAULT_OPENAI_CHAT_COMPLETIONS_BODY_BYTES, maxImageParts: DEFAULT_OPENAI_MAX_IMAGE_PARTS, maxTotalImageBytes: DEFAULT_OPENAI_MAX_TOTAL_IMAGE_BYTES, images: resolveImageLimits(e?.images, false) }; } const DEFAULT_BODY_BYTES = 20971520; const DEFAULT_MAX_URL_PARTS = 8; function resolveResponsesLimits(e) { const t = e?.files; const n = resolveInputFileLimits(t); return { maxBodyBytes: DEFAULT_BODY_BYTES, maxUrlParts: resolveIntegerOption(e?.maxUrlParts, DEFAULT_MAX_URL_PARTS, { min: 0 }), files: { ...n, urlAllowlist: normalizeOptionalTrimmedStringList(t?.urlAllowlist) }, images: resolveImageLimits(e?.images, true) }; } //#endregion export { startOpenAiCompatibleStream as a, resolveResponsesToolChoice as c, resolveAgentRunUsage as d, rejectDisabledGatewayUpload as f, renderConversationToolCall as h, sendOpenAiCompatibleJsonResponse as i, readOpenAiHttpRunTerminal as l, buildAgentMessageFromConversationEntries as m, resolveResponsesLimits as n, applyToolChoice as o, IMAGE_ONLY_USER_MESSAGE as p, prepareOpenAiCompatibleHttpRequest as r, resolveChatToolChoice as s, resolveOpenAiChatCompletionsLimits as t, runOpenAiCompatibleAgentCommand as u };