Compare commits

...

10 Commits

10 changed files with 890 additions and 339 deletions

View File

@ -5,7 +5,11 @@ import {
type Vip98kModelPreset,
} from "@/lib/ai/vip98k-models";
import { db } from "@/lib/db";
import { getAiProviderById } from "@/lib/db/queries";
import {
deleteAiModel,
getAiModelsByProviderId,
getAiProviderById,
} from "@/lib/db/queries";
import { aiModel, type AiModel } from "@/lib/db/schema";
import { requireAdmin } from "@/lib/middleware/admin";
@ -97,8 +101,33 @@ export async function POST(request: Request) {
const addedModels: AiModel[] = [];
const updatedModels: AiModel[] = [];
const removedModels: AiModel[] = [];
const errors: Array<{ modelId: string; error: string }> = [];
const allowedCatalogModelIds = new Set(
catalogPresets.map((preset) => preset.modelId),
);
const existingModels = await getAiModelsByProviderId({ providerId });
const blockedImageModels = existingModels.filter(
(model) =>
model.supportsImageGen && !allowedCatalogModelIds.has(model.modelId),
);
for (const model of blockedImageModels) {
try {
const deleted = await deleteAiModel({ id: model.id });
removedModels.push(...deleted);
} catch (error) {
console.error(
`[VIP98K Models API] Failed to remove blocked image model ${model.modelId}:`,
error,
);
errors.push({
modelId: model.modelId,
error: error instanceof Error ? error.message : "Removal failed",
});
}
}
for (const preset of presets) {
try {
const existing = await db.query.aiModel.findFirst({
@ -161,8 +190,10 @@ export async function POST(request: Request) {
success: true,
addedCount: addedModels.length,
updatedCount: updatedModels.length,
removedCount: removedModels.length,
addedModels,
updatedModels,
removedModels,
errors: errors.length > 0 ? errors : undefined,
counts: {
requested: presets.length,

View File

@ -17,7 +17,6 @@ import {
resolveTripoProviderConfigForTaskId,
} from "@/lib/tripo/server";
import type { TripoTaskData } from "@/lib/tripo/types";
import { getConfiguredVip98kTaskStatus } from "@/lib/ai/vip98k-runtime";
export const runtime = "nodejs";
export const maxDuration = 120;
@ -320,111 +319,6 @@ export async function GET(request: Request, { params }: RouteParams) {
const { searchParams } = new URL(request.url);
const preferredProviderId = searchParams.get("providerId");
if (normalizedTaskId.startsWith("vip98k:")) {
const [, encodedProviderId, ...remoteTaskParts] = normalizedTaskId.split(":");
const remoteTaskId = remoteTaskParts.join(":");
if (!encodedProviderId || !remoteTaskId) {
return NextResponse.json(
{ success: false, error: "VIP98K 3D taskId 格式无效" },
{ status: 400 },
);
}
const result = await getConfiguredVip98kTaskStatus({
taskId: remoteTaskId,
preferredProviderId: encodedProviderId,
});
const modelUrl =
result.outputUrls.find((url) =>
/\.(?:glb|gltf|fbx|obj|stl|3mf|usdz|ply|zip)(?:[?#].*)?$/i.test(url),
) || result.outputUrls[0] || null;
const previewImageUrl =
result.outputUrls.find((url) =>
/\.(?:png|jpe?g|webp|gif)(?:[?#].*)?$/i.test(url),
) || null;
const stableModelUrl = await archiveTripoModelIfNeeded({
taskId: remoteTaskId,
cacheKey: `vip98k:${remoteTaskId}:model`,
sourceUrl: modelUrl,
filenamePrefix: `vip98k-model-${remoteTaskId}`,
fallbackExtension: "glb",
});
const stablePreviewImageUrl = await archiveTripoModelIfNeeded({
taskId: remoteTaskId,
cacheKey: `vip98k:${remoteTaskId}:preview`,
sourceUrl: previewImageUrl,
filenamePrefix: `vip98k-preview-${remoteTaskId}`,
fallbackExtension: "jpg",
});
const errorMessage = result.failed ? "VIP98K 3D 任务执行失败" : null;
const refundedPoints = result.failed
? await refundModel3DPointsForFailedTask({
userId: session.user.id,
taskId: normalizedTaskId,
errorMessage: errorMessage || "VIP98K 3D task failed",
})
: 0;
return NextResponse.json({
success: true,
data: {
taskId: normalizedTaskId,
type: "model",
status: result.failed ? "failed" : result.done ? "success" : result.status || "running",
progress: result.done ? 100 : null,
output: result.payload,
modelUrl: stableModelUrl,
previewImageUrl: stablePreviewImageUrl,
assetPayload: {
providerId: result.providerId,
providerName: result.providerName,
storageArchivedAt: stableModelUrl || stablePreviewImageUrl ? new Date().toISOString() : null,
},
errorCode: result.failed ? "VIP98K_TASK_FAILED" : null,
errorMessage,
refundedPoints,
},
});
}
if (normalizedTaskId.startsWith("vip98k-direct:")) {
const [, encodedProviderId, encodedUrls] = normalizedTaskId.split(":");
if (!encodedProviderId || !encodedUrls) {
return NextResponse.json(
{ success: false, error: "VIP98K 3D direct taskId 格式无效" },
{ status: 400 },
);
}
const outputUrls = JSON.parse(
Buffer.from(encodedUrls, "base64url").toString("utf8"),
) as string[];
const modelUrl =
outputUrls.find((url) =>
/\.(?:glb|gltf|fbx|obj|stl|3mf|usdz|ply|zip)(?:[?#].*)?$/i.test(url),
) || outputUrls[0] || null;
const previewImageUrl =
outputUrls.find((url) => /\.(?:png|jpe?g|webp|gif)(?:[?#].*)?$/i.test(url)) ||
null;
return NextResponse.json({
success: true,
data: {
taskId: normalizedTaskId,
type: "model",
status: "success",
progress: 100,
output: { urls: outputUrls },
modelUrl,
previewImageUrl,
assetPayload: {
providerId: encodedProviderId,
providerName: "VIP98K",
storageArchivedAt: null,
},
errorCode: null,
errorMessage: null,
refundedPoints: 0,
},
});
}
const config = preferredProviderId
? await getTripoProviderConfig(preferredProviderId)
: await resolveTripoProviderConfigForTaskId(normalizedTaskId);

View File

@ -14,10 +14,6 @@ import {
resolveTripoProviderConfigForTaskId,
} from "@/lib/tripo/server";
import { TripoApiError, tripoRequest } from "@/lib/tripo/client";
import {
getVip98kRuntimeProvider,
submitConfiguredVip98kTask,
} from "@/lib/ai/vip98k-runtime";
export const runtime = "nodejs";
export const maxDuration = 60;
@ -120,13 +116,6 @@ function assignMapped(
}
}
const VIP98K_TEXT_TO_3D_MODEL = "tencent/hunyuan3d-pro/text-to-3d";
const VIP98K_IMAGE_TO_3D_MODEL = "tencent/hunyuan3d-pro/image-to-3d";
function encodeVip98kDirectResult(outputUrls: string[]) {
return Buffer.from(JSON.stringify(outputUrls), "utf8").toString("base64url");
}
export async function POST(request: Request) {
try {
const session = await auth();
@ -426,73 +415,6 @@ export async function POST(request: Request) {
}
const preferredProviderId = readOptionalTrimmedText(body.providerId);
let vip98kProvider: Awaited<ReturnType<typeof getVip98kRuntimeProvider>> | null = null;
try {
vip98kProvider = await getVip98kRuntimeProvider(preferredProviderId);
} catch {
vip98kProvider = null;
}
if (vip98kProvider) {
if (taskType !== "text_to_model" && taskType !== "image_to_model") {
return NextResponse.json(
{
success: false,
error: "VIP98K 当前仅支持文生 3D 和图生 3D;细化、动画和格式转换暂不支持",
},
{ status: 400 },
);
}
const inputFile = body.file && typeof body.file === "object" ? body.file : null;
const imageUrl = String(body.imageUrl || inputFile?.url || "").trim();
if (taskType === "image_to_model" && !imageUrl) {
return NextResponse.json(
{ success: false, error: "VIP98K 图生 3D 缺少可访问的图片地址" },
{ status: 400 },
);
}
const vipModelId =
taskType === "image_to_model"
? VIP98K_IMAGE_TO_3D_MODEL
: VIP98K_TEXT_TO_3D_MODEL;
const submission = await submitConfiguredVip98kTask({
preferredProviderId: vip98kProvider.id,
modelId: vipModelId,
kind: "model-3d",
prompt: String(body.prompt || "Generate a production-ready 3D model"),
imageUrls: imageUrl ? [imageUrl] : [],
});
if (!submission.taskId && submission.outputUrls.length === 0) {
throw new Error("VIP98K 3D 任务未返回 taskId 或模型地址");
}
const taskId = submission.taskId
? `vip98k:${vip98kProvider.id}:${submission.taskId}`
: `vip98k-direct:${vip98kProvider.id}:${encodeVip98kDirectResult(submission.outputUrls)}`;
if (pointsCharge.chargeable) {
await pointsCharge.consume({
note: `3D模型任务消耗积分(${billableTaskLabel} / ${taskId})`,
}).catch((error) => {
logger.error("VIP98K points consume failed", error, {
taskId,
userId: session.user.id,
});
});
}
return NextResponse.json({
success: true,
data: {
taskId,
status: submission.outputUrls.length > 0 ? "success" : "queued",
providerId: vip98kProvider.id,
providerName: vip98kProvider.name,
raw: submission.payload,
},
});
}
const dependencyTaskId =
taskType === "refine_model"
? String(body.draftModelTaskId || "").trim()

View File

@ -2,8 +2,6 @@ import { NextResponse } from "next/server";
import { auth } from "@/app/(auth)/auth";
import { getTripoProviderConfig } from "@/lib/tripo/server";
import { TripoApiError, tripoRequest } from "@/lib/tripo/client";
import { getVip98kRuntimeProvider } from "@/lib/ai/vip98k-runtime";
import { uploadFile } from "@/lib/storage/service";
export const runtime = "nodejs";
export const maxDuration = 60;
@ -53,26 +51,7 @@ export async function POST(request: Request) {
);
}
let config: Awaited<ReturnType<typeof getTripoProviderConfig>> | null = null;
try {
config = await getTripoProviderConfig(providerId);
} catch {
const vip98k = await getVip98kRuntimeProvider(providerId);
const extension = file.type === "image/png" ? "png" : file.type === "image/webp" ? "webp" : "jpg";
const uploaded = await uploadFile(
`vip98k-3d-input-${Date.now()}-${crypto.randomUUID()}.${extension}`,
await file.arrayBuffer(),
);
return NextResponse.json({
success: true,
data: {
imageToken: null,
file: { type: extension, url: uploaded.url },
providerId: vip98k.id,
providerName: vip98k.name,
},
});
}
const config = await getTripoProviderConfig(providerId);
const uploadPaths = ["/upload/sts", "/upload"];
let lastError: unknown = null;

View File

@ -16,6 +16,9 @@ type ExtendConfig = {
yScale?: number;
};
const VIP98K_EXPANSION_FALLBACK_MODEL = "google/nano-banana-pro/edit";
const VIP98K_SOURCE_DOWNLOAD_TIMEOUT_MS = 120_000;
export interface ExecuteExtendJobParams {
userId: string;
imageUrl?: string | null;
@ -123,6 +126,97 @@ async function uploadImageToS3ForAPI(imageBase64: string): Promise<string> {
}
}
function isTemporaryVip98kExpansionError(error: unknown) {
const message = error instanceof Error ? error.message : String(error || "");
return /HTTP\s+(?:429|5\d\d)|temporar(?:y|ily)|timeout|timed out|unavailable/i.test(
message,
);
}
async function createVip98kExpansionCanvas(
imageUrl: string,
xScale: number,
yScale: number,
) {
const response = await fetch(imageUrl, {
cache: "no-store",
redirect: "follow",
signal: AbortSignal.timeout(VIP98K_SOURCE_DOWNLOAD_TIMEOUT_MS),
});
if (!response.ok) {
throw new ExtendServiceError(
"下载待拓展图片失败",
502,
`${response.status} ${response.statusText}`,
);
}
const sourceBuffer = Buffer.from(await response.arrayBuffer());
const sharp = await import("sharp");
const image = sharp.default(sourceBuffer, { failOn: "none" });
const metadata = await image.metadata();
const width = Number(metadata.width || 0);
const height = Number(metadata.height || 0);
if (!width || !height) {
throw new ExtendServiceError("无法识别待拓展图片尺寸", 422);
}
const targetWidth = Math.max(width, Math.round(width * xScale));
const targetHeight = Math.max(height, Math.round(height * yScale));
const left = Math.floor((targetWidth - width) / 2);
const top = Math.floor((targetHeight - height) / 2);
const canvas = await image
.ensureAlpha()
.extend({
left,
right: targetWidth - width - left,
top,
bottom: targetHeight - height - top,
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.png()
.toBuffer();
const arrayBuffer = canvas.buffer.slice(
canvas.byteOffset,
canvas.byteOffset + canvas.byteLength,
) as ArrayBuffer;
const uploaded = await uploadFile(
`extend-vip98k-canvas-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`,
arrayBuffer,
);
return {
imageUrl: uploaded.url,
width,
height,
targetWidth,
targetHeight,
};
}
async function extendImageWithVip98kEditFallback(
imageUrl: string,
xScale: number,
yScale: number,
) {
const canvas = await createVip98kExpansionCanvas(imageUrl, xScale, yScale);
const result = await executeConfiguredVip98kTask({
modelId: VIP98K_EXPANSION_FALLBACK_MODEL,
kind: "image",
prompt: [
"Outpaint only the transparent regions of this image.",
"Keep every original pixel, subject, scale, position, perspective, lighting and style unchanged.",
`Complete the ${canvas.targetWidth}x${canvas.targetHeight} canvas naturally from the centered ${canvas.width}x${canvas.height} source.`,
"Do not crop, zoom, move, replace or redraw the original content.",
].join(" "),
imageUrls: [canvas.imageUrl],
});
const outputUrl = result.outputUrls[0];
if (!outputUrl) {
throw new ExtendServiceError("VIP98K 生成式扩图未返回图片", 502);
}
return outputUrl;
}
async function extendImage(
imageUrl: string,
config: ExtendConfig,
@ -130,18 +224,27 @@ async function extendImage(
yScale: number,
): Promise<string> {
if (config.provider === "vip98k") {
const result = await executeConfiguredVip98kTask({
modelId: "image-expansion",
kind: "image-tool",
prompt: `Expand the image canvas naturally to ${xScale}x width and ${yScale}x height. Preserve the original subject, perspective, lighting and style.`,
imageUrls: [imageUrl],
imageParams: { xScale, yScale },
});
const outputUrl = result.outputUrls[0];
if (!outputUrl) {
throw new ExtendServiceError("VIP98K 图像拓展未返回图片", 502);
try {
const result = await executeConfiguredVip98kTask({
modelId: "image-expansion",
kind: "image-tool",
prompt: `Expand the image canvas naturally to ${xScale}x width and ${yScale}x height. Preserve the original subject, perspective, lighting and style.`,
imageUrls: [imageUrl],
imageParams: { xScale, yScale },
});
const outputUrl = result.outputUrls[0];
if (!outputUrl) {
throw new ExtendServiceError("VIP98K 图像拓展未返回图片", 502);
}
return outputUrl;
} catch (error) {
if (!isTemporaryVip98kExpansionError(error)) throw error;
console.warn(
"[Extend Service] VIP98K expansion tool is temporarily unavailable; using VIP98K generative outpainting fallback",
error instanceof Error ? error.message : String(error),
);
return extendImageWithVip98kEditFallback(imageUrl, xScale, yScale);
}
return outputUrl;
}
if (!config.apiKey) {

View File

@ -30,6 +30,16 @@ type Vip98kModelRuntimeConfig = {
imageGenConfig?: Record<string, unknown> | null;
};
type Vip98kInvocation = {
kind: string;
method: string;
path: string;
contentType: string;
requestExample: Record<string, unknown>;
resultMethod: string;
resultPath: string;
};
type UploadedImage = {
thumbnail: string;
original: string;
@ -75,6 +85,23 @@ function getVip98kMetadata(config: Vip98kModelRuntimeConfig) {
return capabilitiesVip98k || imageConfigVip98k || {};
}
function getVip98kInvocation(config: Vip98kModelRuntimeConfig): Vip98kInvocation | null {
const metadata = getVip98kMetadata(config);
const invocation = toRecord(metadata.invocation);
if (!invocation) return null;
const path = String(invocation.path || "").trim();
if (!path.startsWith("/")) return null;
return {
kind: String(invocation.kind || "task").trim().toLowerCase(),
method: String(invocation.method || "POST").trim().toUpperCase(),
path,
contentType: String(invocation.contentType || "application/json").trim(),
requestExample: { ...(toRecord(invocation.requestExample) || {}) },
resultMethod: String(invocation.resultMethod || "GET").trim().toUpperCase(),
resultPath: String(invocation.resultPath || "").trim(),
};
}
function inferKind(modelId: string, config: Vip98kModelRuntimeConfig) {
const capabilities = config.capabilities;
const metadata = getVip98kMetadata(config);
@ -108,6 +135,25 @@ function inferKind(modelId: string, config: Vip98kModelRuntimeConfig) {
return "chat";
}
const VIP98K_OPENAI_IMAGE_ALIASES = new Set([
"nano-banana-2",
"nano-banana-pro",
"gpt-image-2-vip",
]);
function resolveVip98kReferenceModelId(modelId: string) {
switch (modelId.trim().toLowerCase()) {
case "nano-banana-2":
return "google/nano-banana-2/reference-to-image";
case "nano-banana-pro":
return "google/nano-banana-pro/edit";
case "gpt-image-2-vip":
return "openai/gpt-image-2/edit";
default:
return modelId;
}
}
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@ -372,14 +418,19 @@ function getConfiguredPollSeconds(config: Vip98kModelRuntimeConfig, key: string,
async function submitTask(params: {
apiKey: string;
baseURL?: string | null;
path?: string | null;
method?: string | null;
contentType?: string | null;
body: Record<string, unknown>;
}) {
const baseURL = normalizeVip98kBaseUrl(params.baseURL);
const response = await fetch(`${baseURL}/api/external/task/generate`, {
method: "POST",
const path = String(params.path || "/api/external/task/generate").trim();
if (!path.startsWith("/")) throw new Error("VIP98K invocation path is invalid");
const response = await fetch(`${baseURL}${path}`, {
method: String(params.method || "POST").toUpperCase(),
headers: {
Authorization: `Bearer ${params.apiKey}`,
"Content-Type": "application/json",
"Content-Type": params.contentType || "application/json",
},
body: JSON.stringify(params.body),
signal: AbortSignal.timeout(120_000),
@ -440,14 +491,21 @@ export async function submitVip98kExternalTask(params: {
imageParams: params.imageParams,
modelConfig: params.modelConfig || {},
};
const invocation = getVip98kInvocation(taskParams.modelConfig);
const submitted = await submitTask({
apiKey: params.apiKey,
baseURL: params.baseURL,
body: buildTaskBody(taskParams),
path: invocation?.path,
method: invocation?.method,
contentType: invocation?.contentType,
body: buildTaskBody(taskParams, invocation),
});
const resultPath = submitted.resultPath || invocation?.resultPath || "";
return {
taskId: submitted.taskId,
resultPath: submitted.resultPath,
resultPath: submitted.taskId
? resultPath.replaceAll("{task_id}", encodeURIComponent(submitted.taskId))
: resultPath,
outputUrls: submitted.outputs,
payload: submitted.payload,
};
@ -554,15 +612,16 @@ function normalizeDuration(value: unknown) {
return Math.round(numeric);
}
function buildTaskBody(params: Vip98kTaskParams) {
function buildTaskBody(params: Vip98kTaskParams, invocation: Vip98kInvocation | null) {
const videoParams = params.videoParams || {};
const imageParams = params.imageParams || {};
const promptTitle = params.prompt.split(/\s+/).slice(0, 8).join(" ").slice(0, 80);
const body: Record<string, unknown> = {
model: params.modelId,
displayName: promptTitle || params.modelId,
prompt: params.prompt,
};
const body: Record<string, unknown> = { ...(invocation?.requestExample || {}) };
if (invocation?.kind !== "tool" || "model" in body) body.model = params.modelId;
if ("displayName" in body || invocation?.kind !== "tool") {
body.displayName = promptTitle || params.modelId;
}
if ("prompt" in body || !invocation) body.prompt = params.prompt;
const aspectRatio =
normalizeRatio(videoParams.ratio) ||
@ -573,54 +632,64 @@ function buildTaskBody(params: Vip98kTaskParams) {
const negativePrompt = String(videoParams.negativePrompt || imageParams.negativePrompt || "").trim();
if (aspectRatio) {
body.ratio = aspectRatio;
body.aspectRatio = aspectRatio;
body.aspect_ratio = aspectRatio;
if ("ratio" in body || !invocation) body.ratio = aspectRatio;
if ("aspectRatio" in body || !invocation) body.aspectRatio = aspectRatio;
if ("aspect_ratio" in body || !invocation) body.aspect_ratio = aspectRatio;
}
if (duration) body.duration = duration;
if (duration && ("duration" in body || !invocation)) body.duration = duration;
if (resolution) {
body.resolution = resolution;
body.imageSize = resolution;
body.image_size = resolution;
if ("resolution" in body || !invocation) body.resolution = resolution;
if ("imageSize" in body || !invocation) body.imageSize = resolution;
if ("image_size" in body || !invocation) body.image_size = resolution;
if ("size" in body && typeof body.size === "string") body.size = resolution;
}
if (negativePrompt) {
body.negativePrompt = negativePrompt;
body.negative_prompt = negativePrompt;
if ("negativePrompt" in body || !invocation) body.negativePrompt = negativePrompt;
if ("negative_prompt" in body || !invocation) body.negative_prompt = negativePrompt;
}
if (typeof videoParams.generateAudio === "boolean") {
body.generateAudio = videoParams.generateAudio;
body.generate_audio = videoParams.generateAudio;
if ("generateAudio" in body || !invocation) body.generateAudio = videoParams.generateAudio;
if ("generate_audio" in body || !invocation) body.generate_audio = videoParams.generateAudio;
}
if (params.imageUrls.length > 0) {
body.images = params.imageUrls;
body.imageUrls = params.imageUrls;
body.referenceImages = params.imageUrls;
body.reference_images = params.imageUrls;
body.image = params.imageUrls[0];
body.imageUrl = params.imageUrls[0];
body.image_url = params.imageUrls[0];
body.firstFrameImage = params.imageUrls[0];
body.first_frame_image = params.imageUrls[0];
body.firstFrameImageUrl = params.imageUrls[0];
body.first_frame_image_url = params.imageUrls[0];
const setImageField = (key: string, value: unknown) => {
if (key in body || !invocation) body[key] = value;
};
setImageField("images", params.imageUrls);
setImageField("imageUrls", params.imageUrls);
setImageField("referenceImages", params.imageUrls);
setImageField("reference_images", params.imageUrls);
setImageField("image", params.imageUrls[0]);
setImageField("imageUrl", params.imageUrls[0]);
setImageField("image_url", params.imageUrls[0]);
setImageField("firstFrameImage", params.imageUrls[0]);
setImageField("first_frame_image", params.imageUrls[0]);
setImageField("firstFrameImageUrl", params.imageUrls[0]);
setImageField("first_frame_image_url", params.imageUrls[0]);
if (Array.isArray(body.video_clips)) {
const template = toRecord(body.video_clips[0]) || {};
body.video_clips = params.imageUrls.map((url) => ({ ...template, url }));
}
if (params.imageUrls[1]) {
body.lastFrameImage = params.imageUrls[1];
body.last_frame_image = params.imageUrls[1];
body.endImageUrl = params.imageUrls[1];
body.end_image_url = params.imageUrls[1];
setImageField("lastFrameImage", params.imageUrls[1]);
setImageField("last_frame_image", params.imageUrls[1]);
setImageField("endImageUrl", params.imageUrls[1]);
setImageField("end_image_url", params.imageUrls[1]);
}
}
if (params.videoUrls.length > 0) {
body.videos = params.videoUrls;
body.videoUrls = params.videoUrls;
body.referenceVideos = params.videoUrls;
if ("videos" in body || !invocation) body.videos = params.videoUrls;
if ("videoUrls" in body || !invocation) body.videoUrls = params.videoUrls;
if ("referenceVideos" in body || !invocation) body.referenceVideos = params.videoUrls;
if ("video" in body) body.video = params.videoUrls[0];
if ("video_url" in body) body.video_url = params.videoUrls[0];
}
if (params.kind === "world") {
if (params.kind === "world" && ("mode" in body || !invocation)) {
body.mode = "world-generation";
} else if (params.kind === "video") {
} else if (params.kind === "video" && ("mode" in body || !invocation)) {
body.mode = params.imageUrls.length > 0 ? "image-to-video" : "text-to-video";
}
@ -746,10 +815,6 @@ export function createVip98k({ apiKey, baseURL }: Vip98kConfig) {
const modelConfig = parseRuntimeConfig(defaultModelConfig);
const kind = inferKind(modelId, modelConfig);
if (kind === "image") {
return openAIImageProvider.chat(modelId) as any;
}
if (kind === "chat") {
return openAITextProvider.chat(modelId) as any;
}
@ -774,14 +839,25 @@ export function createVip98k({ apiKey, baseURL }: Vip98kConfig) {
if (!activeModelId) throw new Error("VIP98K model ID is not configured");
const activeKind = inferKind(activeModelId, runtimeConfig);
const { prompt, imageUrls, videoUrls } = extractPromptAndMedia(options.messages);
if (
activeKind === "image" &&
imageUrls.length === 0 &&
VIP98K_OPENAI_IMAGE_ALIASES.has(activeModelId.toLowerCase())
) {
return openAIImageProvider.chat(activeModelId).doGenerate(options as any);
}
const [publicImageUrls, publicVideoUrls] = await Promise.all([
Promise.all(imageUrls.map(ensurePublicMediaUrl)),
Promise.all(videoUrls.map(ensurePublicMediaUrl)),
]);
const taskModelId =
activeKind === "image" && publicImageUrls.length > 0
? resolveVip98kReferenceModelId(activeModelId)
: activeModelId;
const text = await runTask({
apiKey,
baseURL: rootBaseURL,
modelId: activeModelId,
modelId: taskModelId,
kind: activeKind,
prompt,
imageUrls: publicImageUrls,

View File

@ -1,6 +1,5 @@
import "server-only";
export const VIP98K_BASE_URL = "https://api.vip98k.com";
export const VIP98K_MAX_IMAGE_PRICE_CNY = 0.3;
export type Vip98kCatalogModelType =
| "image"
@ -12,6 +11,16 @@ export type Vip98kCatalogModelType =
| "world"
| string;
export interface Vip98kInvocationContract {
kind?: "chat" | "task" | "tool" | string;
method?: string;
path?: string;
content_type?: string;
request_example?: Record<string, unknown>;
result_method?: string;
result_path?: string;
}
export interface Vip98kCatalogModel {
modelId?: string;
id?: string;
@ -49,6 +58,19 @@ export interface Vip98kCatalogModel {
pricing?: unknown;
price?: unknown;
status?: string;
invocation?: Vip98kInvocationContract;
taskTypes?: unknown;
task_types?: unknown;
releasedAt?: unknown;
released_at?: unknown;
releaseDate?: unknown;
release_date?: unknown;
releaseYear?: unknown;
release_year?: unknown;
publishedAt?: unknown;
published_at?: unknown;
launchDate?: unknown;
launch_date?: unknown;
[key: string]: unknown;
}
@ -94,9 +116,79 @@ const TYPE_SORT_ORDER: Record<string, number> = {
};
const IMAGE_TOOL_MODEL_IDS = new Set([
"background-generator",
"clothing-segmentation",
"colorize",
"compress",
"enhance",
"face-swap-image",
"head-cutout",
"id-photo",
"image-expansion",
"image-upscaler",
"photo-cleanup",
"remove-background",
"remove-object",
"remove-watermark",
"smart-crop",
"youchuan/v8.1/remove-background",
]);
const VIDEO_CAPABILITY_KEYS = new Set([
"audio-to-video",
"first-frame-to-video",
"image-to-video",
"reference-to-video",
"start-end-frame-to-video",
"text-to-video",
"video-extend",
"video-to-video",
]);
const IMAGE_CAPABILITY_KEYS = new Set([
"image-to-image",
"reference-to-image",
"text-to-image",
]);
const IMAGE_TOOL_OPERATION_BY_MODEL_ID: Record<string, string> = {
"background-generator": "background-generation",
"clothing-segmentation": "segmentation",
colorize: "colorize",
compress: "compress",
enhance: "enhance",
"face-swap-image": "face-swap",
"head-cutout": "remove-background",
"id-photo": "id-photo",
"image-expansion": "extend",
"image-upscaler": "enhance",
"photo-cleanup": "cleanup",
"remove-background": "remove-background",
"remove-object": "remove-object",
"remove-watermark": "remove-watermark",
"smart-crop": "smart-crop",
"youchuan/v8.1/remove-background": "remove-background",
};
// The VIP98K catalog currently has no release-date field. Unknown image models stay
// available to backend routing but remain hidden until their 2026+ release is verified.
const VERIFIED_2026_IMAGE_MODEL_PATTERNS = [
/^nano-banana-2(?:$|[-/])/,
/^gpt-image-2(?:$|[-/])/,
/^alibaba\/wan-2\.(?:6|7)(?:$|[-/])/,
/^black-forest-labs\/flux-2(?:$|[-/])/,
/^bytedance\/seedream-v5(?:$|[.\-/])/,
/^google\/nano-banana-2(?:$|[-/])/,
/^hidream-o1-1\.5(?:$|[-/])/,
/^ideogram\/v4(?:$|[-/])/,
/^krea-2(?:$|[-/])/,
/^microsoft\/mai-image-2\.5(?:$|[-/])/,
/^nvidia\/cosmos-3(?:$|[-/])/,
/^openai\/gpt-image-2(?:$|[-/])/,
/^qwen\/qwen-image-2\.0(?:$|[-/])/,
/^youchuan\/v8\.1(?:$|[-/])/,
];
function toRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
@ -137,6 +229,35 @@ function normalizeCatalogType(model: Vip98kCatalogModel): Vip98kCatalogModelType
.toLowerCase();
}
function getReleaseYear(model: Vip98kCatalogModel): number | null {
const candidates = [
model.releaseYear,
model.release_year,
model.releasedAt,
model.released_at,
model.releaseDate,
model.release_date,
model.publishedAt,
model.published_at,
model.launchDate,
model.launch_date,
];
for (const candidate of candidates) {
const match = String(candidate || "").match(/(?:19|20)\d{2}/);
if (match) return Number(match[0]);
}
const datedModelId = getModelId(model).match(/(?:^|[^\d])((?:19|20)\d{2})\d{4}(?:[^\d]|$)/);
return datedModelId?.[1] ? Number(datedModelId[1]) : null;
}
export function isVip98kImageModelVisible(model: Vip98kCatalogModel) {
const releaseYear = getReleaseYear(model);
if (releaseYear !== null) return releaseYear >= 2026;
const modelId = getModelId(model).toLowerCase();
return VERIFIED_2026_IMAGE_MODEL_PATTERNS.some((pattern) => pattern.test(modelId));
}
function resolvePresetType(model: Vip98kCatalogModel): Vip98kCatalogModelType {
const catalogType = normalizeCatalogType(model);
const modelId = getModelId(model).toLowerCase();
@ -149,10 +270,34 @@ function resolvePresetType(model: Vip98kCatalogModel): Vip98kCatalogModelType {
return "model_3d";
}
if (catalogType === "image" && IMAGE_TOOL_MODEL_IDS.has(modelId)) {
if (catalogType === "world") return "world";
if (catalogType === "image_tool" || IMAGE_TOOL_MODEL_IDS.has(modelId)) {
return "image_tool";
}
if (
catalogType === "video" ||
capabilities.some(
(capability) =>
VIDEO_CAPABILITY_KEYS.has(capability) ||
capability.endsWith("-to-video") ||
capability.startsWith("video-"),
)
) {
return "video";
}
if (
catalogType === "image" ||
capabilities.some(
(capability) =>
IMAGE_CAPABILITY_KEYS.has(capability) || capability.endsWith("-to-image"),
)
) {
return "image";
}
return catalogType;
}
@ -211,6 +356,12 @@ function getCapabilities(model: Vip98kCatalogModel) {
);
}
function getTaskTypes(model: Vip98kCatalogModel) {
return parseStringArray(model.taskTypes || model.task_types).map((item) =>
item.trim().toLowerCase().replace(/_/g, "-"),
);
}
function getInputModes(model: Vip98kCatalogModel) {
return parseStringArray(model.inputModes || model.input_modes).map((item) =>
item.trim().toLowerCase(),
@ -249,10 +400,58 @@ function getBillingMode(model: Vip98kCatalogModel) {
return String(model.billingMode || model.billing_mode || "per_request").trim();
}
export function getVip98kImageModelPolicy(model: Vip98kCatalogModel) {
const presetType = resolvePresetType(model);
const effectivePrice = getEffectivePrice(model);
if (presetType !== "image") {
return {
allowed: true,
effectivePrice,
isTextToImage: false,
reasons: [] as string[],
};
}
const modelId = getModelId(model).toLowerCase().replace(/_/g, "-");
const modes = new Set([...getCapabilities(model), ...getTaskTypes(model)]);
const isTextToImage =
modes.has("text-to-image") || modelId.includes("text-to-image");
const reasons: string[] = [];
if (isTextToImage) reasons.push("text-to-image");
if (
effectivePrice !== undefined &&
effectivePrice > VIP98K_MAX_IMAGE_PRICE_CNY
) {
reasons.push("price-over-limit");
}
return {
allowed: reasons.length === 0,
effectivePrice,
isTextToImage,
reasons,
};
}
function getVip98kMetadata(model: Vip98kCatalogModel, type: string) {
const invocation = toRecord(model.invocation);
return {
modelType: type,
taskApi: "external-task",
taskApi:
String(invocation?.kind || "").toLowerCase() === "tool"
? "external-tool"
: "external-task",
invocation: invocation
? {
kind: String(invocation.kind || ""),
method: String(invocation.method || "POST"),
path: String(invocation.path || ""),
contentType: String(invocation.content_type || "application/json"),
requestExample: toRecord(invocation.request_example) || {},
resultMethod: String(invocation.result_method || "GET"),
resultPath: String(invocation.result_path || ""),
}
: null,
supportsAsync: Boolean(model.supportsAsync ?? model.supports_async ?? true),
pollIntervalSeconds: parseNumber(
model.pollIntervalSeconds || model.poll_interval_seconds,
@ -301,7 +500,7 @@ function createImagePreset(
type: "image",
supportsVision: supportsReferenceImages,
supportsImageGen: true,
isHidden: false,
isHidden: !isVip98kImageModelVisible(model),
capabilities: {
provider: "vip98k",
kind: "image",
@ -491,7 +690,8 @@ function createThreeDPreset(
type: "model_3d",
supportsVision: supportsImageInput,
supportsImageGen: false,
isHidden: false,
// Keep the dedicated Tripo 3D integration as the only frontend 3D route.
isHidden: true,
capabilities: {
provider: "vip98k",
kind: "model-3d",
@ -570,6 +770,7 @@ function createToolPreset(
const inputModes = getInputModes(model);
const outputModes = getOutputModes(model);
const isImageTool = type === "image_tool";
const toolOperation = IMAGE_TOOL_OPERATION_BY_MODEL_ID[modelId.toLowerCase()] || type;
return {
modelId,
@ -588,12 +789,14 @@ function createToolPreset(
inputModes,
outputModes,
supportedModes: getCapabilities(model),
toolOperation,
vip98k: getVip98kMetadata(model, type),
},
defaultParams: {
provider: "vip98k",
kind: type.replace(/_/g, "-"),
endpoint: modelId,
toolOperation,
taskApi: type === "audio" ? "openai-compatible" : "external-task",
},
imageGenConfig: null,
@ -608,6 +811,7 @@ export function buildVip98kModelPresets(
.map((model, index) => {
const modelId = getModelId(model);
if (!modelId) return null;
if (!getVip98kImageModelPolicy(model).allowed) return null;
const type = resolvePresetType(model);
if (type === "image") return createImagePreset(model, index);
if (type === "video") return createVideoPreset(model, index);
@ -648,6 +852,17 @@ function extractCatalogModels(payload: unknown): Vip98kCatalogModel[] {
return [];
}
function extractPublicCatalogModels(payload: unknown): Vip98kCatalogModel[] {
const record = toRecord(payload);
const data = toRecord(record?.data);
const sections = Array.isArray(data?.sections) ? data.sections : [];
return sections.flatMap((section) => {
const sectionRecord = toRecord(section);
const models = Array.isArray(sectionRecord?.models) ? sectionRecord.models : [];
return models.filter((model): model is Vip98kCatalogModel => Boolean(toRecord(model)));
});
}
async function parseJsonResponse(response: Response) {
const text = await response.text();
if (!text.trim()) return null;
@ -678,23 +893,58 @@ export async function fetchVip98kCatalog(params: {
apiKey: string;
}): Promise<Vip98kCatalogModel[]> {
const baseURL = normalizeVip98kBaseUrl(params.baseURL);
const response = await fetch(`${baseURL}/api/external/task/models`, {
cache: "no-store",
headers: {
Authorization: `Bearer ${params.apiKey}`,
Accept: "application/json",
},
signal: AbortSignal.timeout(60_000),
});
const payload = await parseJsonResponse(response);
if (!response.ok) {
throw new Error(`${extractErrorMessage(payload)} (HTTP ${response.status})`);
const [authorizedResponse, publicResponse] = await Promise.all([
fetch(`${baseURL}/api/external/task/models`, {
cache: "no-store",
headers: {
Authorization: `Bearer ${params.apiKey}`,
Accept: "application/json",
},
signal: AbortSignal.timeout(60_000),
}),
fetch(`${baseURL}/api/v1/public/models`, {
cache: "no-store",
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(60_000),
}),
]);
const [authorizedPayload, publicPayload] = await Promise.all([
parseJsonResponse(authorizedResponse),
parseJsonResponse(publicResponse),
]);
if (!authorizedResponse.ok) {
throw new Error(
`${extractErrorMessage(authorizedPayload)} (HTTP ${authorizedResponse.status})`,
);
}
const models = extractCatalogModels(payload);
if (models.length === 0) {
if (!publicResponse.ok) {
throw new Error(
`VIP98K public invocation catalog failed (HTTP ${publicResponse.status})`,
);
}
const authorizedModels = extractCatalogModels(authorizedPayload);
const publicModels = extractPublicCatalogModels(publicPayload);
if (authorizedModels.length === 0) {
throw new Error("VIP98K model catalog is empty or has an unsupported response shape");
}
return models;
if (publicModels.length === 0) {
throw new Error("VIP98K public invocation catalog is empty");
}
const publicById = new Map(
publicModels.map((model) => [getModelId(model).toLowerCase(), model]),
);
return authorizedModels.map((model) => {
const publicModel = publicById.get(getModelId(model).toLowerCase());
if (!publicModel) return model;
return {
...publicModel,
...model,
invocation: publicModel.invocation,
taskTypes: model.taskTypes || model.task_types || publicModel.taskTypes || publicModel.task_types,
capabilities: model.capabilities || publicModel.capabilities,
};
});
}
export async function fetchVip98kModelPresets(params: {

View File

@ -12,7 +12,13 @@ import {
dotenv.config({ path: ".env.local" });
dotenv.config();
const KEEP_PROVIDER_TYPES = new Set(["vip98k", "fal-image", "fal-video"]);
const KEEP_PROVIDER_TYPES = new Set([
"vip98k",
"fal-image",
"fal-video",
"tripo-3d",
"kittycad-cad",
]);
const REQUIRED_CAPABILITY_MODELS = [
"nano-banana-2",
"remove-background",
@ -22,6 +28,9 @@ const REQUIRED_CAPABILITY_MODELS = [
"tencent/hunyuan3d-pro/text-to-3d",
"tencent/hunyuan3d-pro/image-to-3d",
] as const;
const PROTECTED_SYSTEM_SETTING_KEYS = new Set([
"realtime_canvas_config",
]);
type ProviderRow = {
id: string;
@ -39,6 +48,7 @@ type ModelRow = {
displayName: string;
supportsVision: boolean;
supportsImageGen: boolean;
isHidden: boolean;
capabilities: unknown;
imageGenConfig: unknown;
};
@ -56,6 +66,10 @@ function stableHash(value: unknown) {
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
}
function toJsonValue(value: unknown): postgres.JSONValue {
return JSON.parse(JSON.stringify(value)) as postgres.JSONValue;
}
function sortById<T extends { id: string }>(rows: T[]) {
return [...rows].sort((left, right) => left.id.localeCompare(right.id));
}
@ -218,6 +232,12 @@ async function main() {
providers: sortById(falProviders),
models: sortById(models.filter((model) => falProviderIds.has(model.providerId))),
});
const protectedSettingsBefore = await sql<{ key: string; value: unknown }[]>`
select key, value from "SystemSettings"
where key = any(${Array.from(PROTECTED_SYSTEM_SETTING_KEYS)}::text[])
order by key
`;
const protectedSettingsFingerprintBefore = stableHash(protectedSettingsBefore);
const removableProviders = providers.filter(
(provider) => !KEEP_PROVIDER_TYPES.has(provider.type),
);
@ -274,20 +294,19 @@ async function main() {
where "providerId" = ${targetProviderId}::uuid and "modelId" = ${preset.modelId}
order by "createdAt" limit 1
`;
const values = {
description: preset.description,
capabilities: JSON.stringify(preset.capabilities),
defaultParams: JSON.stringify(preset.defaultParams),
imageGenConfig: preset.imageGenConfig ? JSON.stringify(preset.imageGenConfig) : null,
};
const capabilitiesJson = tx.json(toJsonValue(preset.capabilities));
const defaultParamsJson = tx.json(toJsonValue(preset.defaultParams));
const imageGenConfigJson = preset.imageGenConfig
? tx.json(toJsonValue(preset.imageGenConfig))
: null;
if (existing[0]) {
await tx`
update "AiModel" set
"displayName" = ${preset.displayName}, description = ${values.description},
"displayName" = ${preset.displayName}, description = ${preset.description},
"supportsVision" = ${preset.supportsVision}, "supportsImageGen" = ${preset.supportsImageGen},
"isEnabled" = true, "isHidden" = ${preset.isHidden}, "sortOrder" = ${preset.sortOrder},
capabilities = ${values.capabilities}::jsonb, "defaultParams" = ${values.defaultParams}::jsonb,
"imageGenConfig" = ${values.imageGenConfig}::jsonb, "updatedAt" = now()
capabilities = ${capabilitiesJson}, "defaultParams" = ${defaultParamsJson},
"imageGenConfig" = ${imageGenConfigJson}, "updatedAt" = now()
where id = ${existing[0].id}::uuid
`;
modelDbIds.set(preset.modelId, existing[0].id);
@ -298,10 +317,10 @@ async function main() {
"supportsImageGen", "isEnabled", "isHidden", "sortOrder", capabilities,
"defaultParams", "imageGenConfig", "isDefault", "isDefaultTextEditModel"
) values (
${targetProviderId}::uuid, ${preset.modelId}, ${preset.displayName}, ${values.description},
${targetProviderId}::uuid, ${preset.modelId}, ${preset.displayName}, ${preset.description},
${preset.supportsVision}, ${preset.supportsImageGen}, true, ${preset.isHidden},
${preset.sortOrder}, ${values.capabilities}::jsonb, ${values.defaultParams}::jsonb,
${values.imageGenConfig}::jsonb, false, false
${preset.sortOrder}, ${capabilitiesJson}, ${defaultParamsJson},
${imageGenConfigJson}, false, false
) returning id
`;
if (!created) throw new Error(`Failed to create VIP98K model ${preset.modelId}`);
@ -361,6 +380,7 @@ async function main() {
select id, key, value from "SystemSettings"
`;
for (const setting of settings) {
if (PROTECTED_SYSTEM_SETTING_KEYS.has(setting.key)) continue;
let nextValue = rewriteSettingValue({
value: setting.value,
oldProviders: oldProviderMap,
@ -409,6 +429,43 @@ async function main() {
if (falFingerprintAfter !== falFingerprintBefore) {
throw new Error("FAL provider/model fingerprint changed; restore the verified database backup");
}
const protectedSettingsAfter = await sql<{ key: string; value: unknown }[]>`
select key, value from "SystemSettings"
where key = any(${Array.from(PROTECTED_SYSTEM_SETTING_KEYS)}::text[])
order by key
`;
if (stableHash(protectedSettingsAfter) !== protectedSettingsFingerprintBefore) {
throw new Error("Realtime canvas configuration changed; restore the verified database backup");
}
const vipProviderIds = new Set(
remainingProviders
.filter((provider) => provider.type === "vip98k")
.map((provider) => provider.id),
);
const invalidVipModels = remainingModels.filter((model) => {
if (!vipProviderIds.has(model.providerId)) return false;
if (
!model.capabilities ||
typeof model.capabilities !== "object" ||
Array.isArray(model.capabilities)
) {
return true;
}
const capabilities = model.capabilities as Record<string, unknown>;
const kind = String(capabilities?.kind || "").trim().toLowerCase();
if (["video", "model-3d", "world", "chat"].includes(kind)) {
if (model.supportsImageGen) return true;
}
return ["image-tool", "model-3d"].includes(kind) && !model.isHidden;
});
if (invalidVipModels.length > 0) {
throw new Error(
`VIP98K model classification invalid: ${invalidVipModels
.slice(0, 10)
.map((model) => model.modelId)
.join(", ")}`,
);
}
const invalidTypes = remainingProviders.filter(
(provider) => !KEEP_PROVIDER_TYPES.has(provider.type),
);
@ -427,6 +484,7 @@ async function main() {
),
).length,
falFingerprintUnchanged: true,
realtimeCanvasConfigUnchanged: true,
},
null,
2,

View File

@ -15,6 +15,19 @@ type Vip98kCatalogModel = {
model_id?: string;
slug?: string;
name?: string;
displayName?: string;
display_name?: string;
invocation?: Vip98kInvocation;
};
type Vip98kInvocation = {
kind?: string;
method?: string;
path?: string;
content_type?: string;
request_example?: Record<string, unknown>;
result_method?: string;
result_path?: string;
};
const CAPABILITIES = [
@ -49,7 +62,11 @@ const DEFAULT_MODEL_IDS: Record<Capability, string[]> = {
chat: ["gpt-5.4-mini", "gpt-5.4", "claude-sonnet-4-6"],
multimodal: ["gpt-5.4-mini", "gpt-5.4", "claude-sonnet-4-6"],
image: ["nano-banana-2", "nano-banana-pro", "gpt-image-2-vip"],
"multi-image-edit": ["nano-banana-2", "nano-banana-pro", "gpt-image-2-vip"],
"multi-image-edit": [
"google/nano-banana-pro/edit",
"google/nano-banana-2/edit",
"openai/gpt-image-2/edit",
],
rmbg: ["remove-background"],
enhance: ["enhance", "image-upscaler"],
extend: ["image-expansion"],
@ -89,25 +106,56 @@ function normalizeVip98kBaseUrl(baseUrl?: string | null) {
}
async function fetchVip98kCatalog(params: { baseURL: string; apiKey: string }) {
const payload = await parseResponse(
await fetch(`${normalizeVip98kBaseUrl(params.baseURL)}/api/external/task/models`, {
headers: {
Authorization: `Bearer ${params.apiKey}`,
Accept: "application/json",
},
signal: AbortSignal.timeout(60_000),
}),
);
const record = payload && typeof payload === "object" ? (payload as Record<string, any>) : {};
const baseUrl = normalizeVip98kBaseUrl(params.baseURL);
const [authorizedPayload, publicPayload] = await Promise.all([
parseResponse(
await fetch(`${baseUrl}/api/external/task/models`, {
headers: {
Authorization: `Bearer ${params.apiKey}`,
Accept: "application/json",
},
signal: AbortSignal.timeout(60_000),
}),
),
parseResponse(
await fetch(`${baseUrl}/api/v1/public/models`, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(60_000),
}),
),
]);
const record =
authorizedPayload && typeof authorizedPayload === "object"
? (authorizedPayload as Record<string, any>)
: {};
const data = record.data;
const models =
const authorized =
(Array.isArray(data?.models) && data.models) ||
(Array.isArray(data?.items) && data.items) ||
(Array.isArray(data) && data) ||
(Array.isArray(record.models) && record.models) ||
[];
if (models.length === 0) throw new Error("VIP98K model catalog is empty");
return models as Vip98kCatalogModel[];
const publicRecord =
publicPayload && typeof publicPayload === "object"
? (publicPayload as Record<string, any>)
: {};
const publicModels = (Array.isArray(publicRecord.data?.sections)
? publicRecord.data.sections
: []
).flatMap((section: any) => (Array.isArray(section?.models) ? section.models : []));
if (authorized.length === 0) throw new Error("VIP98K authorized model catalog is empty");
if (publicModels.length === 0) throw new Error("VIP98K public invocation catalog is empty");
const publicById = new Map<string, Vip98kCatalogModel>(
publicModels.map((model: Vip98kCatalogModel) => [
getModelId(model).toLowerCase(),
model,
]),
);
return authorized.map((model: Vip98kCatalogModel) => ({
...(publicById.get(getModelId(model).toLowerCase()) || {}),
...model,
invocation: publicById.get(getModelId(model).toLowerCase())?.invocation,
})) as Vip98kCatalogModel[];
}
function sanitizeError(error: unknown) {
@ -300,46 +348,79 @@ async function runExternalTask(params: {
apiKey: string;
modelId: string;
capability: Capability;
invocation: Vip98kInvocation;
}) {
const imageUrl = "https://dummyimage.com/512x512/2563eb/ffffff.png&text=VIP98K";
const body: Record<string, unknown> = {
model: params.modelId,
displayName: `provider-smoke-${params.capability}`,
prompt: "Create a minimal test result with one simple object",
};
if (["rmbg", "enhance", "extend", "image-to-3d"].includes(params.capability)) {
Object.assign(body, {
image: imageUrl,
imageUrl,
image_url: imageUrl,
images: [imageUrl],
imageUrls: [imageUrl],
});
const secondImageUrl = "https://dummyimage.com/512x512/dc2626/ffffff.png&text=REFERENCE";
const body: Record<string, unknown> = JSON.parse(
JSON.stringify(params.invocation.request_example || {}),
);
if ("model" in body) body.model = params.modelId;
if ("displayName" in body) body.displayName = `provider-smoke-${params.capability}`;
if ("prompt" in body) body.prompt = "Create a minimal test result with one simple object";
if (
["multi-image-edit", "rmbg", "enhance", "extend", "image-to-3d"].includes(
params.capability,
)
) {
const images =
params.capability === "multi-image-edit" ? [imageUrl, secondImageUrl] : [imageUrl];
if ("image" in body) body.image = imageUrl;
if ("imageUrl" in body) body.imageUrl = imageUrl;
if ("image_url" in body) body.image_url = imageUrl;
if ("images" in body) body.images = images;
if ("imageUrls" in body) body.imageUrls = images;
if ("referenceImages" in body) body.referenceImages = images;
if ("reference_images" in body) body.reference_images = images;
if (Array.isArray(body.video_clips)) {
const template =
body.video_clips[0] && typeof body.video_clips[0] === "object"
? (body.video_clips[0] as Record<string, unknown>)
: {};
body.video_clips = images.map((url) => ({ ...template, url }));
}
if (
params.capability === "multi-image-edit" &&
!Array.isArray(body.images) &&
!Array.isArray(body.referenceImages) &&
!Array.isArray(body.reference_images) &&
!Array.isArray(body.video_clips)
) {
throw new Error(`${params.modelId} official invocation does not expose multi-image input`);
}
}
if (params.capability === "extend") {
Object.assign(body, { aspectRatio: "16:9", aspect_ratio: "16:9", ratio: "16:9" });
if ("aspectRatio" in body) body.aspectRatio = "16:9";
if ("aspect_ratio" in body) body.aspect_ratio = "16:9";
if ("ratio" in body) body.ratio = "16:9";
}
if (params.capability === "video") {
Object.assign(body, { mode: "text-to-video", duration: 4, resolution: "480p", ratio: "16:9" });
}
if (params.capability === "world") body.mode = "world-generation";
if (params.capability === "world" && "mode" in body) body.mode = "world-generation";
const path = String(params.invocation.path || "").trim();
if (!path.startsWith("/")) throw new Error(`${params.modelId} has no valid invocation path`);
const submitted = await parseResponse(
await fetch(`${params.baseUrl}/api/external/task/generate`, {
method: "POST",
await fetch(`${params.baseUrl}${path}`, {
method: String(params.invocation.method || "POST").toUpperCase(),
headers: {
Authorization: `Bearer ${params.apiKey}`,
"Content-Type": "application/json",
"Content-Type": params.invocation.content_type || "application/json",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(180_000),
}),
);
const immediate = Array.from(collectUrls(submitted));
const inputUrls = new Set([imageUrl, secondImageUrl]);
const immediate = Array.from(collectUrls(submitted)).filter((url) => !inputUrls.has(url));
if (immediate.length > 0) return immediate;
const taskId = extractTaskId(submitted);
if (!taskId) throw new Error("External task returned neither output nor task ID");
const resultPath = extractResultPath(submitted);
const resultPath =
extractResultPath(submitted) ||
String(params.invocation.result_path || "").replaceAll(
"{task_id}",
encodeURIComponent(taskId),
);
const startedAt = Date.now();
while (Date.now() - startedAt < 1_200_000) {
await new Promise((resolvePromise) => setTimeout(resolvePromise, 5000));
@ -355,7 +436,7 @@ async function runExternalTask(params: {
}),
);
const status = extractStatus(payload);
const outputs = Array.from(collectUrls(payload));
const outputs = Array.from(collectUrls(payload)).filter((url) => !inputUrls.has(url));
if (["failed", "error", "timeout", "canceled", "cancelled"].includes(status)) {
throw new Error(`External task failed with status ${status}`);
}
@ -387,6 +468,13 @@ async function main() {
if (!modelId || !availableModelIds.has(modelId)) {
throw new Error(`No catalog model is available for ${capability}; pass --model=<catalog-id>`);
}
const selectedModel = catalog.find((model) => getModelId(model) === modelId);
if (
!["chat", "multimodal", "image"].includes(capability) &&
!selectedModel?.invocation?.path
) {
throw new Error(`${modelId} is missing its official invocation contract`);
}
const ledgerPath = resolve(
getArgValue("--ledger") ||
@ -424,15 +512,21 @@ async function main() {
modelId,
multimodal: capability === "multimodal",
});
} else if (capability === "image" || capability === "multi-image-edit") {
} else if (capability === "image") {
outputs = await runOpenAIImage({
baseUrl,
apiKey,
modelId,
multiImage: capability === "multi-image-edit",
multiImage: false,
});
} else {
outputs = await runExternalTask({ baseUrl, apiKey, modelId, capability });
outputs = await runExternalTask({
baseUrl,
apiKey,
modelId,
capability,
invocation: selectedModel!.invocation!,
});
}
const finishedAt = new Date();
const entry: LedgerEntry = {

View File

@ -14,6 +14,7 @@ import {
isImageGenerationModelDescriptor,
isVideoModelDescriptor,
} from "@/lib/ai/model-classification";
import { buildVip98kModelPresets } from "@/lib/ai/vip98k-models";
const atlasHunyuan3D = {
model: "tencent/hunyuan3d-pro/text-to-3d",
@ -305,4 +306,147 @@ test.describe("AI model media classification", () => {
watermark: true,
});
});
test("normalizes VIP98K media and tool types before they reach the frontend", () => {
const presets = buildVip98kModelPresets([
{
modelId: "mislabelled-video",
displayName: "Mislabelled video",
type: "image",
capabilities: ["text_to_video"],
},
{
modelId: "enhance",
displayName: "Enhance",
type: "image",
capabilities: ["image_processing"],
},
{
modelId: "image-expansion",
displayName: "Extend",
type: "image_tool",
capabilities: ["outpainting"],
},
{
modelId: "remove-background",
displayName: "Remove background",
type: "image_tool",
capabilities: ["image_processing"],
},
{
modelId: "multimodal-model",
displayName: "Multimodal model",
type: "model",
capabilities: ["multimodal"],
inputModes: ["text", "image"],
},
{
modelId: "tencent/hunyuan3d-pro/text-to-3d",
displayName: "Hunyuan 3D",
type: "image",
capabilities: ["text-to-3d"],
},
]);
expect(presets.find((item) => item.modelId === "mislabelled-video")).toMatchObject({
type: "video",
supportsImageGen: false,
});
expect(presets.find((item) => item.modelId === "enhance")).toMatchObject({
type: "image_tool",
isHidden: true,
capabilities: { toolOperation: "enhance" },
});
expect(presets.find((item) => item.modelId === "image-expansion")).toMatchObject({
type: "image_tool",
capabilities: { toolOperation: "extend" },
});
expect(presets.find((item) => item.modelId === "remove-background")).toMatchObject({
type: "image_tool",
capabilities: { toolOperation: "remove-background" },
});
expect(presets.find((item) => item.modelId === "multimodal-model")).toMatchObject({
type: "model",
supportsVision: true,
supportsImageGen: false,
});
expect(
presets.find((item) => item.modelId === "tencent/hunyuan3d-pro/text-to-3d"),
).toMatchObject({
type: "model_3d",
supportsImageGen: false,
isHidden: true,
capabilities: { kind: "model-3d" },
});
});
test("only shows VIP98K image models verified as released in 2026 or later", () => {
const presets = buildVip98kModelPresets([
{
modelId: "black-forest-labs/flux-dev",
displayName: "Flux Dev",
type: "image",
capabilities: ["image_to_image"],
},
{
modelId: "google/nano-banana-2/edit",
displayName: "Nano Banana 2",
type: "image",
capabilities: ["image_to_image"],
},
{
modelId: "future-image-with-date",
displayName: "Future image",
type: "image",
capabilities: ["image_to_image"],
releasedAt: "2027-02-01",
},
{
modelId: "old-image-with-date",
displayName: "Old image",
type: "image",
capabilities: ["image_to_image"],
releasedAt: "2025-12-15",
},
]);
expect(presets.find((item) => item.modelId === "black-forest-labs/flux-dev")?.isHidden).toBe(true);
expect(
presets.find((item) => item.modelId === "google/nano-banana-2/edit")?.isHidden,
).toBe(false);
expect(presets.find((item) => item.modelId === "future-image-with-date")?.isHidden).toBe(false);
expect(presets.find((item) => item.modelId === "old-image-with-date")?.isHidden).toBe(true);
});
test("excludes VIP98K text-to-image and image models priced over CNY 0.30", () => {
const presets = buildVip98kModelPresets([
{
modelId: "cheap-text-to-image",
type: "image",
task_types: ["text_to_image"],
pricing: { effective_price: 0.02 },
},
{
modelId: "expensive-image-edit",
type: "image",
capabilities: ["image_to_image"],
pricing: { effective_price: 0.31 },
},
{
modelId: "affordable-image-edit",
type: "image",
capabilities: ["image_to_image"],
pricing: { effective_price: 0.3 },
},
{
modelId: "remove-background",
type: "image_tool",
pricing: { effective_price: 0.9 },
},
]);
expect(presets.map((item) => item.modelId)).toEqual([
"affordable-image-edit",
"remove-background",
]);
});
});