fix(commandcode): preserve images and reasoning_effort on /alpha/generate

Command Code dropped vision and ignored client effort through the router:
image blocks became "[image omitted]", HTTP image URLs were never inlined,
and reasoning_effort landed on the envelope wrapper instead of params (so the
DeepSeek family mapping remapped low -> high). The catalog also treated
deepseek/deepseek-v4.1-flash as text-only, so the vision adapter stole those
requests to another provider.

- Map OpenAI image_url / Claude image blocks (base64 or data-URI) to the
  native {type:"image", image:"data:...;base64,...", mimeType} generate block.
- Add FORMATS.COMMANDCODE to TARGETS_NEED_BASE64 so remote http(s) images are
  inlined by the existing SSRF-safe fetcher before translation.
- Write reasoning_effort inside params for targetFormat commandcode and pass
  low|medium|high|xhigh|max through unmapped; allow it in thinkingLevels.
- Provider-scoped capabilities for commandcode/cmc: vision except the CLI
  text-only denylist, thinkingFormat commandcode, so family patterns
  (deepseek-v4 -> thinkingFormat deepseek, vision false) no longer win.
- Quota Tracker: whoami + billing credits/subscriptions (credits vs plan cap,
  5h and weekly windows), labels from AI_PROVIDERS[].name.
This commit is contained in:
KhuatHieu
2026-09-16 20:16:32 +07:00
committed by decolua
parent 9300121366
commit 13b468b889
16 changed files with 529 additions and 17 deletions

View File

@@ -467,12 +467,66 @@ function refine(base, provider, model) {
return result;
}
// Mirrors Command Code CLI `isKnownTextOnlyModel` (no image input). New models
// default to vision; only this denylist stays text-only.
const COMMANDCODE_TEXT_ONLY = new Set([
"deepseek/deepseek-v4-pro",
"deepseek/deepseek-v4-flash",
"deepseek/deepseek-v4-flash-fast",
"zai-org/glm-5.3",
"zai-org/glm-5.2",
"zai-org/glm-5.2-fast",
"zai-org/glm-5.1",
"zai-org/glm-5",
"minimaxai/minimax-m2.7",
"minimax/minimax-m2.7-free",
"minimaxai/minimax-m2.5",
"xiaomi/mimo-v2.5-pro",
"qwen/qwen3.6-max-preview",
"qwen/qwen3.7-max",
"meituan/longcat-2.0:free",
"stepfun/step-3.5-flash",
"tencent/hy4-preview",
"tencent/hy3",
"tencent/hy3-paid",
"nvidia/nemotron-3-ultra-550b-a55b",
"poolside/laguna-s-2.1-free",
"inclusionai/ling-3.0-flash-free",
"inclusionai/ling-3.0-flash-sante:free",
]);
function isCommandCodeTextOnly(model) {
const key = String(model || "").toLowerCase();
if (COMMANDCODE_TEXT_ONLY.has(key)) return true;
for (const id of COMMANDCODE_TEXT_ONLY) {
const base = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
if (key === base || key.endsWith("/" + base)) return true;
}
return false;
}
export function getCapabilitiesForModel(provider, model) {
if (!model) return { ...DEFAULT_CAPABILITIES };
// Canonical exact lookup strips vendor prefix: "anthropic/claude-opus-4.7" -> "claude-opus-4.7".
const baseModel = model.includes("/") ? model.split("/").pop() : model;
// CommandCode wire is /alpha/generate for every model. Family patterns
// (deepseek-v4 → thinkingFormat:deepseek, vision:false) must not win here.
if (provider === "commandcode" || provider === "cmc") {
const providerCaps = PROVIDER_CAPABILITIES.commandcode;
if (providerCaps?.[model]) return { ...DEFAULT_CAPABILITIES, ...providerCaps[model] };
if (providerCaps?.[baseModel]) return { ...DEFAULT_CAPABILITIES, ...providerCaps[baseModel] };
return {
...DEFAULT_CAPABILITIES,
reasoning: true,
thinkingFormat: "commandcode",
thinkingEffortSupported: true,
vision: !isCommandCodeTextOnly(model),
contextWindow: 1000000,
maxOutput: 384000,
};
}
// 1. Provider-specific override
if (provider) {
const providerCaps = PROVIDER_CAPABILITIES[provider];

View File

@@ -40,4 +40,8 @@ export default {
{ id: "Qwen/Qwen3.6-Plus", name: "Qwen 3.6 Plus" },
{ id: "stepfun/Step-3.5-Flash", name: "Step 3.5 Flash" },
],
features: {
usage: true,
usageApikey: true,
},
};

View File

@@ -26,6 +26,7 @@ const FORMAT_LEVELS = {
qwen: L.base,
kimi: L.levelMax,
deepseek: L.hiMax,
commandcode: ["none", "low", "medium", "high", "xhigh", "max"],
minimax: L.onOff,
hunyuan: L.base,
step: L.base,

View File

@@ -20,6 +20,7 @@ import { getZedUsage } from "./usage/zed.js";
import { getXiaomiMimoUsage } from "./usage/xiaomi-mimo.js";
import { resolveQoderCredentials } from "./qoderModels.js";
import { getGlmUsage } from "./usage/glm.js";
import { getCommandCodeUsage } from "./usage/commandcode.js";
import {
getIflowUsage,
getOllamaUsage,
@@ -62,6 +63,7 @@ const USAGE_HANDLERS = {
groq: (c) => getGroqUsage(c.apiKey, c.proxyOptions),
zed: (c) => getZedUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
"xiaomi-mimo": (c) => getXiaomiMimoUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
commandcode: (c) => getCommandCodeUsage(c.apiKey, c.proxyOptions),
};
export async function getUsageForProvider(connection, proxyOptions = null, options = {}) {

View File

@@ -0,0 +1,134 @@
/**
* Command Code usage — billing credits + 5h/weekly rate windows.
* Mirrors ~/cc-usage.mjs: whoami → credits + subscriptions.
*/
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
import { parseResetTime, toFiniteNumber } from "./shared.js";
const BASE = (process.env.COMMAND_CODE_API_BASE_URL || "https://api.commandcode.ai").replace(/\/$/, "");
const PLAN_NAMES = {
"individual-go": "Go",
"individual-goat": "GOAT",
"individual-pro": "Pro",
"individual-pro-v1": "Pro",
"individual-provider": "Provider",
"individual-max": "Max",
"individual-ultra": "Ultra",
"teams-pro": "Teams Pro",
};
const PLAN_CAPS = {
"individual-go": 10,
"individual-goat": 70,
"individual-pro": 30,
"individual-pro-v1": 80,
"individual-provider": 15,
"individual-max": 150,
"individual-ultra": 300,
"teams-pro": 40,
};
function qs(route, params) {
const s = new URLSearchParams(
Object.entries(params || {}).filter(([, v]) => v != null),
).toString();
return s ? `${route}?${s}` : route;
}
function windowQuota(win) {
if (!win || typeof win !== "object") return null;
const used = toFiniteNumber(win.used, 0);
const total = toFiniteNumber(win.cap, 0);
if (total <= 0 && used <= 0) return null;
return {
used,
total,
remaining: Math.max(0, total - used),
unlimited: false,
resetAt: parseResetTime(win.resetAt),
};
}
/**
* @param {string|null|undefined} apiKey
* @param {object|null} proxyOptions
*/
export async function getCommandCodeUsage(apiKey, proxyOptions = null) {
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
return { message: "Command Code API key not available. Add a key to view usage." };
}
const headers = {
Authorization: `Bearer ${apiKey.trim()}`,
Accept: "application/json",
};
const get = async (route) => {
const response = await proxyAwareFetch(
BASE + route,
{ method: "GET", headers },
proxyOptions,
);
return response;
};
try {
const whoamiRes = await get(qs("/alpha/whoami", { limits: "1" }));
if (whoamiRes.status === 401 || whoamiRes.status === 403) {
return { plan: "Command Code", message: "Command Code authentication failed. Check the API key." };
}
if (!whoamiRes.ok) {
return { plan: "Command Code", message: `Command Code usage API error (${whoamiRes.status})` };
}
const whoami = await whoamiRes.json().catch(() => ({}));
const orgId = whoami?.org?.id ?? null;
const [creditsRes, subsRes] = await Promise.all([
get(qs("/alpha/billing/credits", { orgId })),
get(qs("/alpha/billing/subscriptions", { orgId })),
]);
if (creditsRes.status === 401 || creditsRes.status === 403 || subsRes.status === 401 || subsRes.status === 403) {
return { plan: "Command Code", message: "Command Code authentication failed. Check the API key." };
}
if (!creditsRes.ok) {
return { plan: "Command Code", message: `Command Code credits API error (${creditsRes.status})` };
}
if (!subsRes.ok) {
return { plan: "Command Code", message: `Command Code subscriptions API error (${subsRes.status})` };
}
const creditsBody = await creditsRes.json().catch(() => ({}));
const subsBody = await subsRes.json().catch(() => ({}));
const planId = subsBody?.data?.planId ?? null;
const plan = (planId && PLAN_NAMES[planId]) || planId || "Command Code";
const cap = planId ? (PLAN_CAPS[planId] || 0) : 0;
const c = creditsBody?.credits || {};
const remaining =
toFiniteNumber(c.monthlyCredits, 0) +
toFiniteNumber(c.purchasedCredits, 0) +
toFiniteNumber(c.freeCredits, 0);
const used = cap > 0 ? Math.max(0, cap - remaining) : 0;
const total = cap > 0 ? cap : remaining;
const quotas = {};
quotas.Credits = {
used,
total,
remaining,
unlimited: cap <= 0,
resetAt: parseResetTime(subsBody?.data?.currentPeriodEnd),
};
const fiveHour = windowQuota(creditsBody?.windowLimits?.fiveHour);
if (fiveHour) quotas["Session (5h)"] = fiveHour;
const weekly = windowQuota(creditsBody?.windowLimits?.weekly);
if (weekly) quotas.Weekly = weekly;
return { plan, quotas };
} catch (error) {
return { message: `Command Code error: ${error.message}` };
}
}

View File

@@ -8,6 +8,7 @@ import { fetchImageAsBase64, parseDataUri } from "./image.js";
const TARGETS_NEED_BASE64 = new Set([
FORMATS.GEMINI, FORMATS.GEMINI_CLI, FORMATS.VERTEX,
FORMATS.ANTIGRAVITY, FORMATS.OLLAMA, FORMATS.KIRO,
FORMATS.COMMANDCODE,
]);
function isRemoteUrl(url) {

View File

@@ -19,6 +19,7 @@ const FORMAT_TO_NATIVE = {
vertex: "gemini-budget",
antigravity: "gemini-budget",
kiro: "kiro",
commandcode: "commandcode",
};
// Strip a trailing thinking suffix "model(value)" → "model" (no-op when absent).
@@ -108,6 +109,7 @@ export const captureThinking = extractThinking;
const NATIVE_ONLY_FORMATS = new Set(["gemini-level", "gemini-budget", "claude-budget", "claude-adaptive", "kiro"]);
function resolveFormat(targetFormat, model, provider) {
if (targetFormat === "commandcode") return "commandcode";
const providerFmt = provider ? PROVIDERS[provider]?.thinkingFormat : null;
if (providerFmt) return providerFmt;
const caps = getCapabilitiesForModel(provider, model);
@@ -223,6 +225,10 @@ function stripAll(body) {
delete body.output_config;
if (body.generationConfig) delete body.generationConfig.thinkingConfig;
if (body.request?.generationConfig) delete body.request.generationConfig.thinkingConfig;
if (body.params && typeof body.params === "object") {
delete body.params.reasoning_effort;
delete body.params.thinking;
}
}
// Apply unified thinking config to body in the resolved provider-native format.
@@ -336,6 +342,17 @@ function applyFormat(fmt, body, cfg, caps, supportedLevels) {
case "kiro":
// Kiro thinking handled via system-tag injection in openai-to-kiro.js; no body field here.
break;
case "commandcode": {
// Native CLI sends reasoning_effort inside params of the /alpha/generate envelope.
if (!body.params || typeof body.params !== "object") body.params = {};
if (none && canDisable) {
delete body.params.reasoning_effort;
break;
}
const level = toLevel(eff);
if (level) body.params.reasoning_effort = level;
break;
}
default:
break;
}

View File

@@ -5,6 +5,7 @@
* - params.system: STRING at top level (Anthropic-style; system messages NOT allowed in messages[])
* - params.messages[*].role ∈ {"user","assistant","tool"}
* - params.messages[*].content: Array of content blocks (NEVER a string)
* - image_url / image source → {type:"image", image:"data:...;base64,...", mimeType}
* - tool_use blocks (assistant): {type:"tool-call", toolCallId, toolName, input}
* - tool_result blocks (role=user): {type:"tool-result", toolCallId, toolName, output}
* - tools[*]: Anthropic plain {name, description, input_schema}
@@ -12,8 +13,9 @@
import { register } from "../index.js";
import { FORMATS } from "../formats.js";
import { randomUUID } from "crypto";
import { ROLE, OPENAI_BLOCK } from "../schema/index.js";
import { ROLE, OPENAI_BLOCK, CLAUDE_BLOCK } from "../schema/index.js";
import { DEFAULT_MAX_TOKENS } from "../../config/runtimeConfig.js";
import { parseDataUri, encodeDataUri } from "../concerns/image.js";
function flattenText(content) {
if (content == null) return "";
@@ -29,6 +31,43 @@ function flattenText(content) {
return String(content);
}
function toNativeImageBlock(part) {
if (!part || typeof part !== "object") return null;
if (part.type === OPENAI_BLOCK.IMAGE_URL) {
const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url;
const parsed = parseDataUri(url);
if (!parsed) return null;
return {
type: OPENAI_BLOCK.IMAGE,
image: encodeDataUri(parsed.mimeType, parsed.base64),
mimeType: parsed.mimeType,
};
}
if (part.type === OPENAI_BLOCK.IMAGE || part.type === CLAUDE_BLOCK.IMAGE) {
if (typeof part.image === "string" && part.image.startsWith("data:")) {
const parsed = parseDataUri(part.image);
return {
type: OPENAI_BLOCK.IMAGE,
image: part.image,
mimeType: part.mimeType || parsed?.mimeType || "image/png",
};
}
const source = part.source;
if (source?.type === "base64" && typeof source.data === "string") {
const mime = source.media_type || "image/png";
return {
type: OPENAI_BLOCK.IMAGE,
image: encodeDataUri(mime, source.data),
mimeType: mime,
};
}
}
return null;
}
function toContentBlocks(content) {
if (content == null) return [{ type: OPENAI_BLOCK.TEXT, text: "" }];
if (typeof content === "string") return [{ type: OPENAI_BLOCK.TEXT, text: content }];
@@ -40,10 +79,12 @@ function toContentBlocks(content) {
} else if (part && typeof part === "object") {
if (part.type === OPENAI_BLOCK.TEXT && typeof part.text === "string") {
blocks.push({ type: OPENAI_BLOCK.TEXT, text: part.text });
} else if (part.type === OPENAI_BLOCK.IMAGE_URL || part.type === OPENAI_BLOCK.IMAGE) {
blocks.push({ type: OPENAI_BLOCK.TEXT, text: "[image omitted]" });
} else if (typeof part.text === "string") {
blocks.push({ type: OPENAI_BLOCK.TEXT, text: part.text });
} else {
const image = toNativeImageBlock(part);
if (image) blocks.push(image);
else if (typeof part.text === "string") {
blocks.push({ type: OPENAI_BLOCK.TEXT, text: part.text });
}
}
}
}