import { r as truncateUtf16Safe } from "./utf16-slice-lH-m0h6-.js";
import { A as resolvePositiveTimerTimeoutMs } from "./number-coercion-CJQ8TR--.js";
import { o as isRecord } from "./record-coerce-DHZ4bFlT.js";
import { t as decodeTextPrefix } from "./src-Bl7G9qvi.js";
import { r as formatErrorMessage } from "./errors-DMsu67n4.js";
import "./number-coercion-EqFmHmOw.js";
import "./utils-d4Gq0rDX.js";
import { c as readResponseTextPrefix } from "./http-body-BtJOYB8-.js";
import { t as createSubsystemLogger } from "./subsystem-X_t1gG1U.js";
import { m as readProviderJsonResponse } from "./provider-http-errors-Bh4de1Nm.js";
import { n as normalizeSecretInput } from "./normalize-secret-input-Df_qhWv_.js";
import { r as resolveProviderTransportSsrFPolicy } from "./provider-transport-fetch-ZyBJez8p.js";
import { c as postJsonRequest, m as resolveProviderHttpRequestConfigWithOriginTrust } from "./shared-mcx3jCpt.js";
//#region src/infra/http-error-body.ts
const errorBodyLog = createSubsystemLogger("http-error-body");
async function readResponseBodySnippet(response, limits) {
	try {
		const body = response.body;
		if (!body || typeof body.getReader !== "function") {
			const text = await response.text();
			const encoded = new TextEncoder().encode(text);
			if (encoded.byteLength > limits.maxBytes) return truncateUtf16Safe(decodeTextPrefix(encoded.subarray(0, limits.maxBytes), { truncated: true }), limits.maxChars);
			return truncateUtf16Safe(text, limits.maxChars);
		}
		return truncateUtf16Safe((await readResponseTextPrefix(response, limits.maxBytes)).text, limits.maxChars);
	} catch (err) {
		errorBodyLog.warn(`Failed to read response body snippet: ${formatErrorMessage(err)}`);
		return "";
	}
}
//#endregion
//#region src/agents/minimax-vlm.ts
/**
* Adapts MiniMax VLM image-understanding requests for agent image inputs.
*/
const MINIMAX_VLM_ERROR_BODY_MAX_BYTES = 8 * 1024;
const MINIMAX_VLM_ERROR_BODY_MAX_CHARS = 400;
const DEFAULT_MINIMAX_VLM_TIMEOUT_MS = 6e4;
function isMinimaxVlmProvider(provider) {
	const normalized = provider.trim().toLowerCase();
	return normalized === "minimax" || normalized === "minimax-cn" || normalized === "minimax-portal" || normalized === "minimax-portal-cn";
}
function isMinimaxVlmModel(provider, modelId) {
	return isMinimaxVlmProvider(provider) && modelId.trim() === "MiniMax-VL-01";
}
function isMinimaxCnProvider(provider) {
	const normalized = provider?.trim().toLowerCase();
	return normalized === "minimax-cn" || normalized === "minimax-portal-cn";
}
function resolveDefaultApiHost(provider) {
	return isMinimaxCnProvider(provider) ? "https://api.minimaxi.com" : "https://api.minimax.io";
}
function coerceApiHost(params) {
	const env = params.env ?? process.env;
	const defaultHost = resolveDefaultApiHost(params.provider);
	const raw = params.apiHost?.trim() || env.MINIMAX_API_HOST?.trim() || params.modelBaseUrl?.trim() || defaultHost;
	try {
		return new URL(raw).origin;
	} catch {}
	if (/^[a-z][a-z\d+.-]*:\/\//i.test(raw)) return defaultHost;
	try {
		return new URL(`https://${raw}`).origin;
	} catch {
		return defaultHost;
	}
}
function pickString(rec, key) {
	const v = rec[key];
	return typeof v === "string" ? v : "";
}
async function minimaxUnderstandImage(params) {
	const apiKey = normalizeSecretInput(params.apiKey);
	if (!apiKey) throw new Error("MiniMax VLM: apiKey required");
	const prompt = params.prompt.trim();
	if (!prompt) throw new Error("MiniMax VLM: prompt required");
	const imageDataUrl = params.imageDataUrl.trim();
	if (!imageDataUrl) throw new Error("MiniMax VLM: imageDataUrl required");
	if (!/^data:image\/(png|jpeg|webp);base64,/i.test(imageDataUrl)) throw new Error("MiniMax VLM: imageDataUrl must be a base64 data:image/(png|jpeg|webp) URL");
	const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy, trustConfiguredBaseUrlOrigin } = resolveProviderHttpRequestConfigWithOriginTrust({
		baseUrl: coerceApiHost({
			apiHost: params.apiHost,
			modelBaseUrl: params.modelBaseUrl,
			provider: params.provider
		}),
		defaultBaseUrl: resolveDefaultApiHost(params.provider),
		allowPrivateNetwork: params.allowPrivateNetwork,
		defaultHeaders: {
			Authorization: `Bearer ${apiKey}`,
			"Content-Type": "application/json",
			"MM-API-Source": "OpenClaw"
		},
		request: params.request,
		provider: params.provider ?? "minimax",
		capability: "image",
		transport: "media-understanding"
	});
	const url = new URL("/v1/coding_plan/vlm", baseUrl).toString();
	const timeoutMs = resolvePositiveTimerTimeoutMs(params.timeoutMs, DEFAULT_MINIMAX_VLM_TIMEOUT_MS);
	const ssrfPolicy = resolveProviderTransportSsrFPolicy({
		baseUrl,
		url,
		allowPrivateNetwork,
		trustConfiguredBaseUrlOrigin
	});
	const guarded = await postJsonRequest({
		url,
		headers,
		body: {
			prompt,
			image_url: imageDataUrl
		},
		timeoutMs,
		fetchFn: fetch,
		allowPrivateNetwork,
		ssrfPolicy,
		dispatcherPolicy,
		auditContext: "minimax-vlm"
	});
	const res = guarded.response;
	try {
		const traceId = res.headers.get("Trace-Id") ?? "";
		if (!res.ok) {
			const body = await readResponseBodySnippet(res, {
				maxBytes: MINIMAX_VLM_ERROR_BODY_MAX_BYTES,
				maxChars: MINIMAX_VLM_ERROR_BODY_MAX_CHARS
			});
			const trace = traceId ? ` Trace-Id: ${traceId}` : "";
			throw new Error(`MiniMax VLM request failed (${res.status} ${res.statusText}).${trace}${body ? ` Body: ${body}` : ""}`);
		}
		const json = await readProviderJsonResponse(res, traceId ? `MiniMax VLM response [Trace-Id=${traceId}]` : "MiniMax VLM response");
		if (!isRecord(json)) {
			const trace = traceId ? ` Trace-Id: ${traceId}` : "";
			throw new Error(`MiniMax VLM response was not JSON.${trace}`);
		}
		const baseResp = isRecord(json.base_resp) ? json.base_resp : {};
		const code = typeof baseResp.status_code === "number" ? baseResp.status_code : -1;
		if (code !== 0) {
			const msg = (baseResp.status_msg ?? "").trim();
			const trace = traceId ? ` Trace-Id: ${traceId}` : "";
			throw new Error(`MiniMax VLM API error (${code})${msg ? `: ${msg}` : ""}.${trace}`);
		}
		const content = pickString(json, "content").trim();
		if (!content) {
			const trace = traceId ? ` Trace-Id: ${traceId}` : "";
			throw new Error(`MiniMax VLM returned no content.${trace}`);
		}
		return content;
	} finally {
		await guarded.release();
	}
}
//#endregion
export { readResponseBodySnippet as i, isMinimaxVlmProvider as n, minimaxUnderstandImage as r, isMinimaxVlmModel as t };
