UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

136 lines (135 loc) • 5.68 kB
import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs"; import { n as sanitizeTerminalText } from "../../safe-text-C80HAQ2e.mjs"; import { Fn as object, Jn as string, Nt as array, sr as unknown } from "../../schemas-Cy6abvsu.mjs"; import { t as canonicalizeBase64 } from "../../base64-CnKpkbff.mjs"; import { i as readResponseWithLimit } from "../../http-response-body-B-i_0116.mjs"; import "../../text-utility-runtime-Ds8jsG0J.mjs"; import "../../response-limit-runtime-DkiFHsEX.mjs"; import "../../text-chunking-B9FpckXY.mjs"; //#region extensions/openai/image-generation-codex-response.ts const MAX_CODEX_IMAGE_SSE_BYTES = 67108864; const MAX_CODEX_IMAGE_SSE_EVENTS = 512; const MAX_CODEX_IMAGE_BASE64_CHARS = 67108864; const OPENAI_MAX_IMAGE_RESULTS = 4; const DIAGNOSTIC_MAX_CHARS = 256; const contentSchema = object({ type: string().nullish(), text: string().nullish(), refusal: string().nullish() }); const itemSchema = contentSchema.extend({ result: string().nullish(), revised_prompt: string().nullish(), status: string().nullish(), content: array(contentSchema).nullish() }); const errorSchema = object({ code: string().nullish(), message: string().nullish() }); const eventSchema = object({ type: string().nullish(), item: itemSchema.nullish(), response: object({ error: errorSchema.nullish(), incomplete_details: object({ reason: string().nullish() }).nullish(), output: array(itemSchema).nullish(), usage: unknown().optional(), tool_usage: unknown().optional() }).nullish(), error: errorSchema.nullish(), message: string().nullish() }); function parseCodexImageGenerationEvents(e) { const t = []; for (const n of e.replace(/\r\n?/g, "\n").split("\n\n")) { const e = n.split("\n").filter((e) => e.startsWith("data:")).map((e) => e.slice(5).replace(/^ /, "")).join("\n").trim(); if (!e || e === "[DONE]") continue; let r; try { r = JSON.parse(e); } catch { continue; } const i = eventSchema.safeParse(r); if (!i.success) throw new Error("OpenAI Codex image generation returned a malformed stream event"); t.push(i.data); if (t.length > MAX_CODEX_IMAGE_SSE_EVENTS) throw new Error("OpenAI Codex image generation response exceeded event limit"); } return t; } function decodeCodexImagePayload(e) { if (e.length > MAX_CODEX_IMAGE_BASE64_CHARS) throw new Error("OpenAI Codex image generation result exceeded size limit"); const t = e.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, ""); const n = canonicalizeBase64(t); if (!n || n !== t) throw new Error("OpenAI Codex image generation returned malformed base64 image data"); return Buffer.from(n, "base64"); } function extractCodexImageDiagnostic(e, t) { for (const n of [e ?? [], t]) { let e; for (const t of n) { const n = t.type === "message" ? t.content ?? [] : [t]; for (const t of n) { const n = t.type === "refusal" ? t.refusal ?? t.text : t.type === "output_text" ? t.text : void 0; if (typeof n !== "string") continue; const r = sanitizeTerminalText(n.replace(/safety_violations=\[[^\]]*\]/gi, " ")).replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/gi, "").replace(/\s+/g, " ").trim(); if (!r) continue; const i = r.length > DIAGNOSTIC_MAX_CHARS ? `${truncateUtf16Safe(r, DIAGNOSTIC_MAX_CHARS)}...` : r; if (t.type === "refusal") return `OpenAI Codex image generation refused by provider: "${i}"`; e ??= `OpenAI Codex image generation returned text instead of an image: "${i}"`; } } if (e) return e; } } async function readCodexImageGenerationResponse(e, t) { const n = await readResponseWithLimit(e, MAX_CODEX_IMAGE_SSE_BYTES, { onOverflow: () => /* @__PURE__ */ new Error("OpenAI Codex image generation response exceeded size limit") }); const r = parseCodexImageGenerationEvents(new TextDecoder().decode(n)); const i = []; let a; for (const e of r) { if (e.type === "response.failed" || e.type === "error") { const t = e.response?.error ?? e.error; const n = t?.message ?? e.message ?? (t?.code ? `OpenAI Codex image generation failed (${t.code})` : ""); throw new Error(n || "OpenAI Codex image generation failed"); } if (e.type === "response.incomplete") { const t = e.response?.incomplete_details?.reason ?? "unknown"; throw new Error(`OpenAI Codex image generation response incomplete: ${t}`); } if (e.type === "response.completed") { a = e.response; break; } if (e.type === "response.output_item.done" && e.item) i.push(e.item); } if (!a) throw new Error("OpenAI Codex image generation stream closed before response.completed"); const o = (a.output ?? []).filter((e) => e.type === "image_generation_call"); const s = (o.length > 0 ? o : i.filter((e) => e.type === "image_generation_call")).slice(0, OPENAI_MAX_IMAGE_RESULTS); const c = []; for (const [e, n] of s.entries()) { if (n.status && n.status !== "completed") { const e = extractCodexImageDiagnostic(a.output, i); throw new Error(e ? `${e} (image call did not complete (${n.status}))` : `OpenAI Codex image generation image call did not complete (${n.status})`); } if (typeof n.result !== "string" || n.result.length === 0) continue; c.push({ buffer: decodeCodexImagePayload(n.result), mimeType: t.mimeType, fileName: `image-${e + 1}.${t.extension}`, ...n.revised_prompt ? { revisedPrompt: n.revised_prompt } : {} }); } if (c.length === 0) throw new Error(extractCodexImageDiagnostic(a.output, i) ?? "OpenAI Codex image generation completed but did not produce an image"); return { images: c, model: t.model, metadata: { usage: a.usage, toolUsage: a.tool_usage } }; } //#endregion export { readCodexImageGenerationResponse };