Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/src/access.ts

Raw
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import {
	defineChoiceSetting,
	resolveSetting,
	type SettingDeclaration,
	type SettingResult,
} from "./pi-ext-settings.ts";

export const VIDEO_APPROVAL: SettingDeclaration<"ask" | "always"> =
	defineChoiceSetting({
		key: "minimax.videoApproval",
		label: "H3 video approval",
		description:
			"USER or env only: ask confirms each H3 submit in the UI (or allows it for the session); always submits without a dialog, including noninteractive use. Project settings never authorize.",
		env: "PI_MINIMAX_VIDEO_APPROVAL",
		choices: ["ask", "always"] as const,
		default: "ask",
	});
export const REGION: SettingDeclaration<"global" | "cn"> = defineChoiceSetting({
	key: "minimax.region",
	label: "Service region",
	description:
		"Only global M Plan routes are established; cn reports unavailable.",
	env: "PI_MINIMAX_REGION",
	choices: ["global", "cn"] as const,
	default: "global",
});

export function region(pi: ExtensionAPI, ctx: ExtensionContext): void {
	const value = resolveSetting(pi, ctx, REGION);
	if (!value.ok) throw new Error(value.error);
	if (value.value !== "global")
		throw new Error(
			"MiniMax CN M Plan media routes unavailable: not established. No cross-region fallback.",
		);
}

async function abortable<T>(
	promise: Promise<T>,
	signal?: AbortSignal,
): Promise<T> {
	if (!signal) return promise;
	signal.throwIfAborted();
	return new Promise<T>((resolve, reject) => {
		const cancelled = () =>
			reject(new Error("MiniMax operation cancelled before submission."));
		signal.addEventListener("abort", cancelled, { once: true });
		void promise.then(resolve, reject).finally(() => {
			signal.removeEventListener("abort", cancelled);
		});
		if (signal.aborted) cancelled();
	});
}

export async function credentials(
	ctx: ExtensionContext,
	signal?: AbortSignal,
): Promise<string> {
	signal?.throwIfAborted();
	const provider = ctx.modelRegistry.getProvider("minimax");
	if (
		provider?.baseUrl &&
		new URL(provider.baseUrl).origin !== "https://api.minimax.io"
	)
		throw new Error(
			"MiniMax provider endpoint/region mismatch: global api.minimax.io required.",
		);
	let result: Awaited<
		ReturnType<ExtensionContext["modelRegistry"]["getProviderAuth"]>
	>;
	try {
		result = await abortable(
			ctx.modelRegistry.getProviderAuth("minimax"),
			signal,
		);
	} catch {
		signal?.throwIfAborted();
		throw new Error(
			"Pi MiniMax credential resolution failed; inspect existing Pi minimax configuration. No fallback.",
		);
	}
	signal?.throwIfAborted();
	const key = result?.auth.apiKey;
	if (!key)
		throw new Error(
			"Missing MiniMax M Plan key: configure existing Pi minimax credentials.",
		);
	if (key.startsWith("sk-api-"))
		throw new Error(
			"PAYG MiniMax key rejected: use M Plan key from Plan Details.",
		);
	if (!key.startsWith("sk-cp-"))
		throw new Error(
			"Ambiguous MiniMax credential: M Plan key required; access remains unverified.",
		);
	if (
		result?.auth.baseUrl &&
		new URL(result.auth.baseUrl).origin !== "https://api.minimax.io"
	)
		throw new Error(
			"MiniMax credential endpoint/region mismatch: global api.minimax.io required.",
		);
	return key;
}

/** Even trusted project files are not human spending authority. */
export function videoApproval(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
): SettingResult<"ask" | "always"> {
	return resolveSetting(
		pi,
		{ ...ctx, isProjectTrusted: () => false },
		VIDEO_APPROVAL,
	);
}

const SUBMIT_ONCE = "Submit once";
const ALLOW_SESSION = "Allow H3 for this session";
const CANCEL = "Cancel";

/**
 * Only H3 is gated: it is the one costly, weekly-only operation. Session
 * allowance is keyed by session id so forks and new sessions ask again.
 */
export async function approveVideo(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	request: { duration: number; resolution: "768P" | "2K" },
	allowed: Set<string>,
	signal?: AbortSignal,
): Promise<void> {
	signal?.throwIfAborted();
	const setting = videoApproval(pi, ctx);
	if (!setting.ok) throw new Error(setting.error);
	if (setting.value === "always") return;
	const session = ctx.sessionManager.getSessionId();
	if (allowed.has(session)) return;
	if (!ctx.hasUI)
		throw new Error(
			'MiniMax H3 submit needs approval but no interactive UI is available; no request sent. To allow noninteractive H3 submits, set USER setting minimax.videoApproval to "always" or env PI_MINIMAX_VIDEO_APPROVAL=always.',
		);
	const rate = request.resolution === "768P" ? 0.08 : 0.13;
	const choice = await abortable(
		ctx.ui.select(
			[
				`Submit MiniMax-H3 video: ${request.duration}s at ${request.resolution}?`,
				`Catalog estimate ≈ $${Number((request.duration * rate).toPrecision(3))} (0.08 USD/s at 768P, 0.13 USD/s at 2K).`,
				"Uses the weekly-only H3 allowance; Go plan lacks H3. Purchased Credits, if ever bought, could be consumed.",
			].join("\n"),
			[SUBMIT_ONCE, ALLOW_SESSION, CANCEL],
			...(signal ? [{ signal }] : []),
		),
		signal,
	);
	signal?.throwIfAborted();
	if (choice === ALLOW_SESSION) allowed.add(session);
	else if (choice !== SUBMIT_ONCE)
		throw new Error("MiniMax H3 submission declined; no request submitted.");
}