Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/index.ts

Raw
import { createProvider } from "@earendil-works/pi-ai";
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { credentials, region } from "./src/access.ts";
import { ORIGIN } from "./src/api.ts";
import { registerCapabilities } from "./src/capabilities.ts";
import { closeDebug, dbg } from "./src/debug.ts";
import { generateImages, IMAGE_API, IMAGE_PROVIDER } from "./src/images.ts";
import { registerSpeech } from "./src/speech.ts";
import { registerUnderstanding } from "./src/tools.ts";
import { registerVideo } from "./src/video.ts";

export default function minimax(pi: ExtensionAPI): void {
	let active: ExtensionContext | undefined;
	let lifetime = new AbortController();
	registerUnderstanding(pi, () => lifetime.signal);
	registerSpeech(pi, () => lifetime.signal);
	registerVideo(pi, () => lifetime.signal);
	registerCapabilities(pi);
	pi.registerProvider(
		createProvider({
			id: IMAGE_PROVIDER,
			name: "MiniMax M Plan media",
			baseUrl: ORIGIN,
			auth: {
				apiKey: {
					name: "Existing Pi minimax M Plan credentials",
					async check({ signal }) {
						if (!active) return undefined;
						try {
							region(pi, active);
							await credentials(active, signal);
							return {
								type: "api_key" as const,
								source: "Pi minimax M Plan key",
							};
						} catch {
							signal.throwIfAborted();
							return undefined;
						}
					},
					async resolve({ signal }) {
						if (!active) return undefined;
						return { auth: { apiKey: await credentials(active, signal) } };
					},
				},
			},
			models: [
				{
					type: "image",
					provider: IMAGE_PROVIDER,
					id: "image-01",
					name: "MiniMax image-01 (M Plan, access unverified)",
					api: IMAGE_API,
					baseUrl: ORIGIN,
					input: ["text"],
					output: ["image"],
					cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
				},
			],
			images: {
				[IMAGE_API]: {
					async generateImages(model, context, options) {
						if (!active)
							return {
								api: IMAGE_API,
								provider: IMAGE_PROVIDER,
								model: model.id,
								output: [],
								stopReason: "error",
								errorMessage: "MiniMax session unavailable.",
								timestamp: Date.now(),
							};
						return generateImages(pi, active, model, context, {
							...options,
							signal: AbortSignal.any([
								lifetime.signal,
								...(options?.signal ? [options.signal] : []),
							]),
						});
					},
				},
			},
		}),
	);
	pi.on("session_start", (_event, ctx) => {
		active = ctx;
		lifetime = new AbortController();
		dbg?.("session.start");
	});
	pi.on("session_shutdown", () => {
		lifetime.abort();
		active = undefined;
		dbg?.("session.shutdown");
		closeDebug();
	});
}