Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/src/api.ts

Raw
export const ORIGIN = "https://api.minimax.io";
export const MAX_JSON: number = 32 * 1024 * 1024;

export function object(value: unknown): Record<string, unknown> {
	if (!value || typeof value !== "object" || Array.isArray(value)) return {};
	return value as Record<string, unknown>;
}

export async function boundedBody(
	response: Response,
	limit: number,
): Promise<Buffer> {
	const declared = response.headers.get("content-length");
	if (declared && Number(declared) > limit) {
		await response.body?.cancel();
		throw new Error("MiniMax response exceeds byte limit.");
	}
	if (!response.body) throw new Error("MiniMax response body missing.");
	const reader = response.body.getReader();
	const chunks: Uint8Array[] = [];
	let bytes = 0;
	try {
		for (;;) {
			const part = await reader.read();
			if (part.done) break;
			bytes += part.value.byteLength;
			if (bytes > limit)
				throw new Error("MiniMax response exceeds byte limit.");
			chunks.push(part.value);
		}
		return Buffer.concat(chunks, bytes);
	} finally {
		await reader.cancel().catch(() => {});
		reader.releaseLock();
	}
}

export class ApiError extends Error {
	constructor(
		readonly kind: string,
		message: string,
	) {
		super(message);
	}
}

export async function request(
	key: string,
	path: string,
	body: unknown,
	signal?: AbortSignal,
	method = "POST",
	fetcher: typeof globalThis.fetch = globalThis.fetch,
	timeoutMs = 120_000,
): Promise<Record<string, unknown>> {
	const deadline = AbortSignal.timeout(timeoutMs);
	const combined = AbortSignal.any([deadline, ...(signal ? [signal] : [])]);
	let response: Response;
	try {
		response = await fetcher(ORIGIN + path, {
			method,
			headers: {
				Authorization: `Bearer ${key}`,
				"Content-Type": "application/json",
			},
			...(body === undefined ? {} : { body: JSON.stringify(body) }),
			signal: combined,
			redirect: "error",
		});
	} catch {
		throw new ApiError(
			deadline.aborted
				? "timeout"
				: combined.aborted
					? "local-cancellation"
					: "unknown-completion",
			"MiniMax request interrupted; completion unknown. No automatic retry. H3: inspect owned job; never blindly resubmit.",
		);
	}
	if (!response.ok) {
		await response.body?.cancel();
		const kind =
			response.status === 401
				? "authentication"
				: response.status === 402
					? "allowance-exhausted"
					: response.status === 403
						? "entitlement"
						: response.status === 429
							? "rate-limit"
							: "upstream";
		throw new ApiError(
			kind,
			`MiniMax ${kind} failure (HTTP ${response.status}); no fallback or retry.`,
		);
	}
	let result: Record<string, unknown>;
	try {
		result = object(
			JSON.parse((await boundedBody(response, MAX_JSON)).toString("utf8")),
		);
	} catch {
		throw new ApiError(
			"incompatible",
			"MiniMax malformed/oversized response; completion unknown. Do not resubmit automatically.",
		);
	}
	const base = object(result["base_resp"]);
	const code = base["status_code"];
	if (code !== undefined && code !== 0) {
		const kind =
			code === 1002
				? "rate-limit"
				: code === 1008
					? "allowance-exhausted"
					: code === 1004
						? "authentication"
						: "upstream";
		throw new ApiError(
			kind,
			`MiniMax ${kind}: provider status ${typeof code === "number" ? code : "invalid"}; no fallback or retry.`,
		);
	}
	return result;
}