openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
510 lines (509 loc) • 16.9 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as avoidTrailingHighSurrogateBreak } from "./utf16-slice-CuDyEXgS.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { p as toOpenAiChatCompletionsUsage } from "./usage-CHLnzpJG.mjs";
import { Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, or as union, sr as unknown } from "./schemas-Cy6abvsu.mjs";
import { n as estimateBase64DecodedBytes } from "./base64-CnKpkbff.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import "./io-4QsrsWTJ.mjs";
import { r as authorizeGatewaySessionCreation } from "./operator-role-policy-DhcqVpmG.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { t as sendJson } from "./http-json-ddGJz5CA.mjs";
import { _ as setSseHeaders, h as sendUnauthorized, u as sendInvalidRequest } from "./http-common-FfhIIwOW.mjs";
import { n as assertGatewayHttpRequestCurrent } from "./http-request-authority-CYXIvBHo.mjs";
import { o as extractImageContentFromSource } from "./input-files-DKoRlBjP.mjs";
import { d as resolveGatewayRequestContext, f as resolveOpenAiCompatModelOverride, r as authorizeOpenAiCompatibleHttpSession, s as isGatewayRequestContextError } from "./http-utils-B5V9Okzh.mjs";
import { n as GATEWAY_UPLOADS_DISABLED_MESSAGE, r as areGatewayUploadsEnabled } from "./upload-policy-Dp8z9OKP.mjs";
import { a as validateOpenAiSamplingParams, i as resolveStopSequences, n as resolveOpenAiStreamParams, r as resolveResponseFormat } from "./openai-compat-errors-DSFdRblo.mjs";
import { a as startOpenAiCompatibleStream, d as resolveAgentRunUsage, f as rejectDisabledGatewayUpload, h as renderConversationToolCall, i as sendOpenAiCompatibleJsonResponse, m as buildAgentMessageFromConversationEntries, o as applyToolChoice, p as IMAGE_ONLY_USER_MESSAGE, r as prepareOpenAiCompatibleHttpRequest, s as resolveChatToolChoice, t as resolveOpenAiChatCompletionsLimits, u as runOpenAiCompatibleAgentCommand } from "./openai-compatible-input-limits-BzRh2lX4.mjs";
import { randomUUID } from "node:crypto";
import { STREAM_ERROR_FALLBACK_TEXT } from "@openclaw/ai/internal/shared";
//#region src/gateway/openai-http-images.ts
function resolveImageUrlPart(e) {
const t = asOptionalObjectRecord(e)?.image_url;
return normalizeOptionalString(typeof t === "string" ? t : asOptionalObjectRecord(t)?.url);
}
function extractImageUrls(e) {
const t = [];
if (!Array.isArray(e)) return {
kind: "valid",
urls: t
};
for (const n of e) {
if (asOptionalObjectRecord(n)?.type !== "image_url") continue;
const e = resolveImageUrlPart(n);
if (!e) return { kind: "invalid" };
t.push(e);
}
return {
kind: "valid",
urls: t
};
}
function parseImageUrlToSource(e) {
const t = /^data:([^,]*?),(.*)$/is.exec(e);
if (t) {
const e = normalizeOptionalString(t[1]) ?? "";
const n = t[2] ?? "";
const r = e.split(";").map((e) => normalizeOptionalString(e) ?? "").filter(Boolean);
if (!r.some((e) => normalizeLowercaseStringOrEmpty(e) === "base64")) throw new Error("image_url data URI must be base64 encoded");
if (!(normalizeOptionalString(n) ?? "")) throw new Error("image_url data URI is missing payload data");
return {
type: "base64",
mediaType: r.find((e) => e.includes("/")),
data: n
};
}
return {
type: "url",
url: e
};
}
async function resolveImagesForRequest(e, t, n, r) {
n.throwIfAborted();
if (e.imageUrls.kind === "invalid") throw new Error("image_url part is missing a valid URL");
const i = e.imageUrls.urls;
if (i.length === 0) return [];
if (i.length > t.maxImageParts) throw new Error(`Too many image_url parts (${i.length}; limit ${t.maxImageParts})`);
const a = [];
let o = 0;
for (const e of i) {
r();
const i = parseImageUrlToSource(e);
if (i.type === "base64") {
const e = estimateBase64DecodedBytes(i.data);
if (o + e > t.maxTotalImageBytes) throw new Error(`Total image payload too large (${o + e}; limit ${t.maxTotalImageBytes})`);
}
const s = await extractImageContentFromSource(i, t.images, n);
o += estimateBase64DecodedBytes(s.data);
if (o > t.maxTotalImageBytes) throw new Error(`Total image payload too large (${o}; limit ${t.maxTotalImageBytes})`);
a.push(s);
}
return a;
}
//#endregion
//#region src/gateway/openai-http.ts
const OpenAiChatCompletionRequestSchema = object({
model: string().optional(),
stream: boolean().nullish(),
stream_options: object({ include_usage: boolean().optional() }).passthrough().nullish(),
tools: array(unknown()).optional(),
tool_choice: unknown().optional(),
messages: array(unknown()).optional(),
user: string().optional(),
max_tokens: number().int().positive().nullish(),
max_completion_tokens: number().int().positive().nullish(),
temperature: number().nullish(),
top_p: number().nullish(),
response_format: unknown().optional(),
frequency_penalty: number().nullish(),
presence_penalty: number().nullish(),
seed: number().nullish(),
stop: union([string(), array(string())]).nullish()
});
function writeSse(e, t) {
e.write(`data: ${JSON.stringify(t)}\n\n`);
}
function extractClientToolsFromChatRequest(e) {
const t = [];
for (const n of e ?? []) {
const e = asOptionalRecord(n);
if (!e) throw new Error("each tool must be an object");
if (e.type !== "function") throw new Error("only function tools are supported");
const r = asOptionalRecord(e.function);
if (!r) throw new Error("tool.function is required");
const i = normalizeOptionalString(r.name);
if (!i) throw new Error("tool.function.name is required");
const { description: a, strict: o } = r;
const s = asOptionalRecord(r.parameters);
t.push({
type: "function",
function: {
name: i,
...typeof a === "string" ? { description: a } : {},
...s ? { parameters: s } : {},
...typeof o === "boolean" ? { strict: o } : {}
}
});
}
return t;
}
function writeChatCompletionChunk(e, t, n) {
writeSse(e, {
id: t.runId,
object: "chat.completion.chunk",
created: t.created,
model: t.model,
...n
});
}
function writeChatCompletionChoice(e, t, n, r = null) {
writeChatCompletionChunk(e, t, { choices: [{
index: 0,
delta: n,
finish_reason: r
}] });
}
function writeAssistantToolCallsIncrementalChunks(e, t) {
for (const [n, r] of t.toolCalls.entries()) {
writeChatCompletionChoice(e, t, { tool_calls: [{
index: n,
id: r.id,
type: "function",
function: {
name: r.name,
arguments: ""
}
}] });
let i = 0;
do {
const a = avoidTrailingHighSurrogateBreak(r.arguments, i, Math.min(i + 256, r.arguments.length));
writeChatCompletionChoice(e, t, { tool_calls: [{
index: n,
function: { arguments: r.arguments.slice(i, a) }
}] });
i = a;
} while (i < r.arguments.length);
}
}
function extractTextContent(e) {
if (typeof e === "string") return e;
if (Array.isArray(e)) {
const t = e.map((e) => {
const t = asOptionalObjectRecord(e);
if (!t) return;
const { type: n, text: r, input_text: i } = t;
if ((n === "text" || n === "input_text") && typeof r === "string") return r;
return typeof i === "string" ? i : void 0;
});
const n = t.filter(Boolean).join("\n");
return n.trim() || t.every((e) => e !== void 0) ? n : void 0;
}
}
function stringifyToolCallArguments(e) {
if (typeof e === "string") return e;
if (e == null) return "";
try {
const t = JSON.stringify(e);
return typeof t === "string" ? t : "";
} catch {
return "";
}
}
function extractAssistantToolCalls(e) {
if (!Array.isArray(e)) return [];
const t = [];
for (const n of e) {
const e = asOptionalRecord(n);
if (!e) continue;
const r = normalizeOptionalString(e.id);
const i = asOptionalRecord(e.function);
const a = normalizeOptionalString(i?.name);
if (!r || !a) continue;
const o = stringifyToolCallArguments(i?.arguments);
t.push({
id: r,
name: a,
arguments: o
});
}
return t;
}
function resolveActiveTurnContext(e = []) {
for (let t = e.length - 1; t >= 0; t -= 1) {
const n = asOptionalObjectRecord(e[t]);
if (!n) continue;
const r = normalizeOptionalString(n.role) ?? "";
const i = r === "function" ? "tool" : r;
if (i !== "user" && i !== "tool") continue;
const a = i === "user" ? extractImageUrls(n.content) : {
kind: "valid",
urls: []
};
return {
activeUserMessageIndex: i === "user" ? t : -1,
imageUrls: a
};
}
return {
activeUserMessageIndex: -1,
imageUrls: {
kind: "valid",
urls: []
}
};
}
function buildAgentPrompt(e, t) {
const n = t.imageUrls.kind === "valid" && t.imageUrls.urls.length > 0;
const r = [];
const i = [];
for (const [a, o] of (e ?? []).entries()) {
const e = asOptionalObjectRecord(o);
if (!e) continue;
const s = normalizeOptionalString(e.role) ?? "";
const c = (s === "function" && e.content === null ? "" : extractTextContent(e.content))?.trim();
if (!s) continue;
if (s === "system" || s === "developer") {
if (c) r.push(c);
continue;
}
const l = s === "function" ? "tool" : s;
if (l !== "user" && l !== "assistant" && l !== "tool") continue;
const u = (l === "assistant" ? extractAssistantToolCalls(e.tool_calls) : []).map(renderConversationToolCall).join("\n");
const d = [l === "user" && !c && n && a === t.activeUserMessageIndex ? IMAGE_ONLY_USER_MESSAGE : c, u].filter((e) => Boolean(e)).join("\n");
const f = normalizeOptionalString(e.name) ?? "";
const p = normalizeOptionalString(e.tool_call_id) ?? "";
const m = l === "tool" && Boolean(s === "function" ? f : p) && c !== void 0 && (s !== "function" || typeof e.content === "string" || e.content === null);
if (!d && !m) continue;
const h = l === "assistant" ? "Assistant" : l === "user" ? "User" : p ? `Tool:${p}` : f ? `Tool:${f}` : "Tool";
i.push({
role: l,
entry: {
sender: h,
body: d
},
internalStreamError: l === "assistant" && normalizeOptionalString(e.stopReason) === "error" && d.trim() === STREAM_ERROR_FALLBACK_TEXT
});
}
return {
message: buildAgentMessageFromConversationEntries(i),
extraSystemPrompt: r.length > 0 ? r.join("\n\n") : void 0
};
}
async function handleOpenAiHttpRequest(e, t, n) {
const r = resolveOpenAiChatCompletionsLimits(n.config);
const i = await prepareOpenAiCompatibleHttpRequest(e, t, {
...n,
pathname: "/v1/chat/completions",
maxBodyBytes: n.maxBodyBytes ?? r.maxBodyBytes,
schema: OpenAiChatCompletionRequestSchema
});
if (!i) return i !== false;
const { payload: a, abortController: o, senderIsOwner: s } = i;
const c = (a.messages ?? []).some((e) => {
const t = asOptionalObjectRecord(e)?.content;
return Array.isArray(t) && t.some((e) => {
const t = asOptionalObjectRecord(e)?.type;
return t === "image_url" || t === "file";
});
});
if (rejectDisabledGatewayUpload(t, c)) return true;
const l = a.stream === true;
const u = l && a.stream_options?.include_usage === true;
const d = a.model ?? "openclaw";
const f = a.user;
let p;
try {
p = resolveResponseFormat(a.response_format);
} catch (e) {
sendInvalidRequest(t, `Invalid response_format: ${formatErrorMessage(e).trim()}`);
return true;
}
let m;
try {
m = resolveStopSequences(a.stop);
} catch (e) {
sendInvalidRequest(t, `Invalid stop: ${formatErrorMessage(e).trim()}`);
return true;
}
const h = validateOpenAiSamplingParams({
temperature: a.temperature,
topP: a.top_p,
frequencyPenalty: a.frequency_penalty,
presencePenalty: a.presence_penalty,
seed: a.seed
});
if (h) {
sendInvalidRequest(t, h);
return true;
}
const g = resolveOpenAiStreamParams({
maxTokens: a.max_completion_tokens ?? a.max_tokens ?? void 0,
temperature: a.temperature ?? void 0,
topP: a.top_p ?? void 0,
responseFormat: p,
frequencyPenalty: a.frequency_penalty ?? void 0,
presencePenalty: a.presence_penalty ?? void 0,
seed: a.seed ?? void 0,
stop: m
});
let _;
let v;
let y;
try {
({agentId: _, sessionKey: v, messageChannel: y} = await resolveGatewayRequestContext({
req: e,
model: d,
user: f,
sessionPrefix: "openai"
}));
} catch (e) {
if (isGatewayRequestContextError(e)) {
sendInvalidRequest(t, e.message);
return true;
}
throw e;
}
const b = authorizeGatewaySessionCreation({
cfg: readRuntimeConfig(),
...i.requestAuth.operatorRoleActor ? { actor: i.requestAuth.operatorRoleActor } : { profileId: i.requestAuth.authenticatedUserProfile?.profileId },
agentId: _
});
if (b) {
sendJson(t, 403, { error: {
message: b.message,
type: "forbidden"
} });
return true;
}
const x = await authorizeOpenAiCompatibleHttpSession({
agentId: _,
sessionKey: v,
requestAuth: i.requestAuth,
senderIsOwner: s
});
if (!x.allowed) {
sendJson(t, 403, { error: {
message: x.message,
type: "forbidden"
} });
return true;
}
const { modelOverride: S, errorMessage: C } = await resolveOpenAiCompatModelOverride({
req: e,
agentId: _,
model: d
});
if (C) {
sendInvalidRequest(t, C);
return true;
}
const w = resolveActiveTurnContext(a.messages);
const T = buildAgentPrompt(a.messages, w);
let E;
try {
const e = extractClientToolsFromChatRequest(a.tools);
E = applyToolChoice(e, resolveChatToolChoice(a.tool_choice));
} catch (e) {
sendInvalidRequest(t, `Invalid tools/tool_choice: ${formatErrorMessage(e).trim()}`);
return true;
}
let D;
try {
assertGatewayHttpRequestCurrent(i.requestAuth);
D = await resolveImagesForRequest(w, r, o.signal, () => {
assertGatewayHttpRequestCurrent(i.requestAuth);
if (c && !areGatewayUploadsEnabled(readRuntimeConfig())) throw new Error(GATEWAY_UPLOADS_DISABLED_MESSAGE);
});
} catch (e) {
if (o.signal.aborted) return true;
if (i.requestAuth.hasCurrentClientAuthority?.() === false) {
sendUnauthorized(t);
return true;
}
if (rejectDisabledGatewayUpload(t, c)) return true;
logWarn(`openai-compat: invalid image_url content: ${String(e)}`);
sendInvalidRequest(t, "Invalid image_url content in `messages`.");
return true;
}
if (rejectDisabledGatewayUpload(t, c)) return true;
if (!T.message && D.length === 0) {
sendInvalidRequest(t, "Missing user message in `messages`.");
return true;
}
const O = `chatcmpl_${randomUUID()}`;
const k = Math.floor(Date.now() / 1e3);
const A = {
runId: O,
model: d,
created: k
};
const j = [T.extraSystemPrompt, E.extraSystemPrompt].filter((e) => Boolean(e)).join("\n\n");
const runAgentCommand = () => runOpenAiCompatibleAgentCommand({
message: T.message,
extraSystemPrompt: j,
images: D,
clientTools: E.tools,
modelOverride: S,
sessionKey: v,
runId: O,
messageChannel: y,
senderIsOwner: s,
requestAuth: i.requestAuth,
operatorScopes: i.operatorScopes,
abortSignal: o.signal,
hasCurrentClientAuthority: i.requestAuth.hasCurrentClientAuthority,
hasClientUploads: c,
streamParams: g,
resolveGatewayContext: n.resolveGatewayContext
});
if (!l) return sendOpenAiCompatibleJsonResponse({
res: t,
signal: o.signal,
constraint: E.constraint,
run: runAgentCommand,
failureLabel: "openai-compat: chat completion failed",
complete: ({ result: e, stopReason: n, toolCalls: r, text: i, toolChoiceError: a }) => {
const o = toOpenAiChatCompletionsUsage(resolveAgentRunUsage(e));
if (a) {
sendJson(t, 502, { error: {
message: a,
type: "api_error"
} });
return;
}
sendJson(t, 200, {
id: O,
object: "chat.completion",
created: k,
model: d,
choices: [{
index: 0,
message: {
role: "assistant",
content: i || (r ? "" : "No response from OpenClaw."),
...r ? { tool_calls: r.map((e) => ({
id: e.id,
type: "function",
function: {
name: e.name,
arguments: e.arguments
}
})) } : {}
},
finish_reason: r ? "tool_calls" : n === "length" ? "length" : "stop"
}],
usage: o
});
}
});
setSseHeaders(t);
writeChatCompletionChoice(t, A, { role: "assistant" });
startOpenAiCompatibleStream({
protocol: "chat",
res: t,
runId: O,
signal: o.signal,
constraint: E.constraint,
run: runAgentCommand,
writeDelta: (e) => writeChatCompletionChoice(t, A, { content: e }),
complete: ({ result: e, delta: n, toolCalls: r, stopReason: i }) => {
if (n) writeChatCompletionChoice(t, A, { content: n });
if (r) writeAssistantToolCallsIncrementalChunks(t, {
...A,
toolCalls: r
});
writeChatCompletionChoice(t, A, {}, r ? "tool_calls" : i === "length" ? "length" : "stop");
const a = toOpenAiChatCompletionsUsage(resolveAgentRunUsage(e));
if (u && a) writeChatCompletionChunk(t, A, {
choices: [],
usage: a
});
},
fail: (e) => writeSse(t, { error: e })
});
return true;
}
//#endregion
export { handleOpenAiHttpRequest };