@gguf/claw
Version:
WhatsApp gateway CLI (Baileys web) with Pi RPC agent
1,433 lines (1,417 loc) • 115 kB
JavaScript
import { Et as resolveNodeManagerOptions, pt as detectBinary, xr as loadModelCatalog, xt as openUrl } from "./reply-B8pOiUNN.js";
import { f as resolveConfigDir, h as resolveUserPath, s as ensureDir, t as CONFIG_DIR } from "./utils-CKSrBNwq.js";
import { t as runCommandWithTimeout } from "./exec-HEWTMJ7j.js";
import { a as resolveAgentModelPrimary, c as resolveDefaultAgentId, r as resolveAgentDir, s as resolveAgentWorkspaceDir, w as resolveDefaultAgentWorkspaceDir } from "./agent-scope-CMs5Y7l-.js";
import { I as resolveEnvApiKey, J as resolveAuthProfileOrder, M as getCustomProviderApiKey, O as SYNTHETIC_DEFAULT_MODEL_REF, W as CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF, at as listProfilesForProvider, bt as DEFAULT_PROVIDER, ct as upsertAuthProfile, d as resolveConfiguredModelRef, et as CHUTES_AUTHORIZE_ENDPOINT, lt as ensureAuthProfileStore, mt as resolveOpenClawAgentDir, nt as generateChutesPkce, o as modelKey, r as buildModelAliasIndex, rt as parseOAuthCallbackInput, s as normalizeProviderId, t as buildAllowedModelSet, tt as exchangeChutesCodeForTokens, u as resolveAllowlistModelKey, w as VENICE_DEFAULT_MODEL_REF, yt as DEFAULT_MODEL } from "./model-selection-DMUrNhQP.js";
import { t as formatCliCommand } from "./command-format-ChfKqObn.js";
import { _ as resolveSkillKey, d as hasBinary, i as loadWorkspaceSkillEntries, t as resolveSkillsInstallPreferences } from "./skills-D5JDj3TR.js";
import { Y as fetchWithSsrFGuard } from "./deliver-C3bnXkg5.js";
import { t as resolveBrewExecutable } from "./brew-CAcErcKz.js";
import { $ as setVeniceApiKey, A as applySyntheticProviderConfig, B as OPENROUTER_DEFAULT_MODEL_REF, C as applyMoonshotConfig, D as applyOpenrouterConfig, E as applyMoonshotProviderConfigCn, F as applyXaiConfig, G as setCloudflareAiGatewayConfig, H as XIAOMI_DEFAULT_MODEL_REF, I as applyXaiProviderConfig, J as setMinimaxApiKey, K as setGeminiApiKey, L as applyXiaomiConfig, M as applyVeniceProviderConfig, N as applyVercelAiGatewayConfig, O as applyOpenrouterProviderConfig, P as applyVercelAiGatewayProviderConfig, Q as setSyntheticApiKey, R as applyXiaomiProviderConfig, S as applyKimiCodeProviderConfig, T as applyMoonshotProviderConfig, U as ZAI_DEFAULT_MODEL_REF, V as VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF, W as setAnthropicApiKey, X as setOpencodeZenApiKey, Y as setMoonshotApiKey, Z as setOpenrouterApiKey, _ as applyMinimaxProviderConfig, at as KIMI_CODING_MODEL_REF, b as applyCloudflareAiGatewayProviderConfig, ct as buildTokenProfileId, d as resolvePluginProviders, et as setVercelAiGatewayApiKey, f as applyOpencodeZenConfig, g as applyMinimaxConfig, h as applyMinimaxApiProviderConfig, i as formatTokenK, it as writeOAuthCredentials, j as applyVeniceConfig, k as applySyntheticConfig, l as createVpsAwareOAuthHandlers, lt as validateAnthropicSetupToken, m as applyMinimaxApiConfig, nt as setXiaomiApiKey, ot as MOONSHOT_DEFAULT_MODEL_REF, p as applyOpencodeZenProviderConfig, q as setKimiCodingApiKey, rt as setZaiApiKey, st as XAI_DEFAULT_MODEL_REF, t as githubCopilotLoginCommand, tt as setXaiApiKey, u as isRemoteEnvironment, v as applyAuthProfileConfig, w as applyMoonshotConfigCn, x as applyKimiCodeConfig, y as applyCloudflareAiGatewayConfig, z as applyZaiConfig } from "./github-copilot-auth-C8Uf0Q03.js";
import { a as enablePluginInConfig } from "./onboard-channels-DKT27PdN.js";
import { t as scanDirectoryWithSummary } from "./skill-scanner-BoGjHXUZ.js";
import { t as buildWorkspaceSkillStatus } from "./skills-status-CEvVUD3U.js";
import { n as resolveWideAreaDiscoveryDomain } from "./widearea-dns-D9Al4QRv.js";
import path from "node:path";
import fs from "node:fs";
import { randomBytes } from "node:crypto";
import { loginOpenAICodex } from "@mariozechner/pi-ai";
import { createServer } from "node:http";
import { pipeline } from "node:stream/promises";
import { Readable } from "node:stream";
//#region src/commands/auth-choice-options.ts
const AUTH_CHOICE_GROUP_DEFS = [
{
value: "xai",
label: "xAI (Grok)",
hint: "API key",
choices: ["xai-api-key"]
},
{
value: "openai",
label: "OpenAI",
hint: "Codex OAuth + API key",
choices: ["openai-codex", "openai-api-key"]
},
{
value: "anthropic",
label: "Anthropic",
hint: "setup-token + API key",
choices: ["token", "apiKey"]
},
{
value: "minimax",
label: "MiniMax",
hint: "M2.1 (recommended)",
choices: [
"minimax-portal",
"minimax-api",
"minimax-api-lightning"
]
},
{
value: "moonshot",
label: "Moonshot AI (Kimi K2.5)",
hint: "Kimi K2.5 + Kimi Coding",
choices: [
"moonshot-api-key",
"moonshot-api-key-cn",
"kimi-code-api-key"
]
},
{
value: "google",
label: "Google",
hint: "Gemini API key + OAuth",
choices: [
"gemini-api-key",
"google-antigravity",
"google-gemini-cli"
]
},
{
value: "openrouter",
label: "OpenRouter",
hint: "API key",
choices: ["openrouter-api-key"]
},
{
value: "qwen",
label: "Qwen",
hint: "OAuth",
choices: ["qwen-portal"]
},
{
value: "zai",
label: "Z.AI (GLM 4.7)",
hint: "API key",
choices: ["zai-api-key"]
},
{
value: "copilot",
label: "Copilot",
hint: "GitHub + local proxy",
choices: ["github-copilot", "copilot-proxy"]
},
{
value: "ai-gateway",
label: "Vercel AI Gateway",
hint: "API key",
choices: ["ai-gateway-api-key"]
},
{
value: "opencode-zen",
label: "OpenCode Zen",
hint: "API key",
choices: ["opencode-zen"]
},
{
value: "xiaomi",
label: "Xiaomi",
hint: "API key",
choices: ["xiaomi-api-key"]
},
{
value: "synthetic",
label: "Synthetic",
hint: "Anthropic-compatible (multi-model)",
choices: ["synthetic-api-key"]
},
{
value: "venice",
label: "Venice AI",
hint: "Privacy-focused (uncensored models)",
choices: ["venice-api-key"]
},
{
value: "cloudflare-ai-gateway",
label: "Cloudflare AI Gateway",
hint: "Account ID + Gateway ID + API key",
choices: ["cloudflare-ai-gateway-api-key"]
}
];
function buildAuthChoiceOptions(params) {
params.store;
const options = [];
options.push({
value: "token",
label: "Anthropic token (paste setup-token)",
hint: "run `claude setup-token` elsewhere, then paste the token here"
});
options.push({
value: "openai-codex",
label: "OpenAI Codex (ChatGPT OAuth)"
});
options.push({
value: "chutes",
label: "Chutes (OAuth)"
});
options.push({
value: "openai-api-key",
label: "OpenAI API key"
});
options.push({
value: "openrouter-api-key",
label: "OpenRouter API key"
});
options.push({
value: "xai-api-key",
label: "xAI (Grok) API key"
});
options.push({
value: "ai-gateway-api-key",
label: "Vercel AI Gateway API key"
});
options.push({
value: "cloudflare-ai-gateway-api-key",
label: "Cloudflare AI Gateway",
hint: "Account ID + Gateway ID + API key"
});
options.push({
value: "moonshot-api-key",
label: "Kimi API key (.ai)"
});
options.push({
value: "moonshot-api-key-cn",
label: "Kimi API key (.cn)"
});
options.push({
value: "kimi-code-api-key",
label: "Kimi Code API key (subscription)"
});
options.push({
value: "synthetic-api-key",
label: "Synthetic API key"
});
options.push({
value: "venice-api-key",
label: "Venice AI API key",
hint: "Privacy-focused inference (uncensored models)"
});
options.push({
value: "github-copilot",
label: "GitHub Copilot (GitHub device login)",
hint: "Uses GitHub device flow"
});
options.push({
value: "gemini-api-key",
label: "Google Gemini API key"
});
options.push({
value: "google-antigravity",
label: "Google Antigravity OAuth",
hint: "Uses the bundled Antigravity auth plugin"
});
options.push({
value: "google-gemini-cli",
label: "Google Gemini CLI OAuth",
hint: "Uses the bundled Gemini CLI auth plugin"
});
options.push({
value: "zai-api-key",
label: "Z.AI (GLM 4.7) API key"
});
options.push({
value: "xiaomi-api-key",
label: "Xiaomi API key"
});
options.push({
value: "minimax-portal",
label: "MiniMax OAuth",
hint: "Oauth plugin for MiniMax"
});
options.push({
value: "qwen-portal",
label: "Qwen OAuth"
});
options.push({
value: "copilot-proxy",
label: "Copilot Proxy (local)",
hint: "Local proxy for VS Code Copilot models"
});
options.push({
value: "apiKey",
label: "Anthropic API key"
});
options.push({
value: "opencode-zen",
label: "OpenCode Zen (multi-model proxy)",
hint: "Claude, GPT, Gemini via opencode.ai/zen"
});
options.push({
value: "minimax-api",
label: "MiniMax M2.1"
});
options.push({
value: "minimax-api-lightning",
label: "MiniMax M2.1 Lightning",
hint: "Faster, higher output cost"
});
if (params.includeSkip) options.push({
value: "skip",
label: "Skip for now"
});
return options;
}
function buildAuthChoiceGroups(params) {
const options = buildAuthChoiceOptions({
...params,
includeSkip: false
});
const optionByValue = new Map(options.map((opt) => [opt.value, opt]));
return {
groups: AUTH_CHOICE_GROUP_DEFS.map((group) => ({
...group,
options: group.choices.map((choice) => optionByValue.get(choice)).filter((opt) => Boolean(opt))
})),
skipOption: params.includeSkip ? {
value: "skip",
label: "Skip for now"
} : void 0
};
}
//#endregion
//#region src/commands/auth-choice-prompt.ts
const BACK_VALUE = "__back";
async function promptAuthChoiceGrouped(params) {
const { groups, skipOption } = buildAuthChoiceGroups(params);
const availableGroups = groups.filter((group) => group.options.length > 0);
while (true) {
const providerOptions = [...availableGroups.map((group) => ({
value: group.value,
label: group.label,
hint: group.hint
})), ...skipOption ? [skipOption] : []];
const providerSelection = await params.prompter.select({
message: "Model/auth provider",
options: providerOptions
});
if (providerSelection === "skip") return "skip";
const group = availableGroups.find((candidate) => candidate.value === providerSelection);
if (!group || group.options.length === 0) {
await params.prompter.note("No auth methods available for that provider.", "Model/auth choice");
continue;
}
const methodSelection = await params.prompter.select({
message: `${group.label} auth method`,
options: [...group.options, {
value: BACK_VALUE,
label: "Back"
}]
});
if (methodSelection === BACK_VALUE) continue;
return methodSelection;
}
}
//#endregion
//#region src/commands/auth-choice.api-key.ts
const DEFAULT_KEY_PREVIEW = {
head: 4,
tail: 4
};
function normalizeApiKeyInput(raw) {
const trimmed = String(raw ?? "").trim();
if (!trimmed) return "";
const assignmentMatch = trimmed.match(/^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/);
const valuePart = assignmentMatch ? assignmentMatch[1].trim() : trimmed;
const unquoted = valuePart.length >= 2 && (valuePart.startsWith("\"") && valuePart.endsWith("\"") || valuePart.startsWith("'") && valuePart.endsWith("'") || valuePart.startsWith("`") && valuePart.endsWith("`")) ? valuePart.slice(1, -1) : valuePart;
return (unquoted.endsWith(";") ? unquoted.slice(0, -1) : unquoted).trim();
}
const validateApiKeyInput = (value) => normalizeApiKeyInput(value).length > 0 ? void 0 : "Required";
function formatApiKeyPreview(raw, opts = {}) {
const trimmed = raw.trim();
if (!trimmed) return "…";
const head = opts.head ?? DEFAULT_KEY_PREVIEW.head;
const tail = opts.tail ?? DEFAULT_KEY_PREVIEW.tail;
if (trimmed.length <= head + tail) {
const shortHead = Math.min(2, trimmed.length);
const shortTail = Math.min(2, trimmed.length - shortHead);
if (shortTail <= 0) return `${trimmed.slice(0, shortHead)}…`;
return `${trimmed.slice(0, shortHead)}…${trimmed.slice(-shortTail)}`;
}
return `${trimmed.slice(0, head)}…${trimmed.slice(-tail)}`;
}
//#endregion
//#region src/commands/auth-choice.apply.anthropic.ts
async function applyAuthChoiceAnthropic(params) {
if (params.authChoice === "setup-token" || params.authChoice === "oauth" || params.authChoice === "token") {
let nextConfig = params.config;
await params.prompter.note(["Run `claude setup-token` in your terminal.", "Then paste the generated token below."].join("\n"), "Anthropic setup-token");
const tokenRaw = await params.prompter.text({
message: "Paste Anthropic setup-token",
validate: (value) => validateAnthropicSetupToken(String(value ?? ""))
});
const token = String(tokenRaw).trim();
const profileNameRaw = await params.prompter.text({
message: "Token name (blank = default)",
placeholder: "default"
});
const provider = "anthropic";
const namedProfileId = buildTokenProfileId({
provider,
name: String(profileNameRaw ?? "")
});
upsertAuthProfile({
profileId: namedProfileId,
agentDir: params.agentDir,
credential: {
type: "token",
provider,
token
}
});
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: namedProfileId,
provider,
mode: "token"
});
return { config: nextConfig };
}
if (params.authChoice === "apiKey") {
if (params.opts?.tokenProvider && params.opts.tokenProvider !== "anthropic") return null;
let nextConfig = params.config;
let hasCredential = false;
const envKey = process.env.ANTHROPIC_API_KEY?.trim();
if (params.opts?.token) {
await setAnthropicApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential && envKey) {
if (await params.prompter.confirm({
message: `Use existing ANTHROPIC_API_KEY (env, ${formatApiKeyPreview(envKey)})?`,
initialValue: true
})) {
await setAnthropicApiKey(envKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Anthropic API key",
validate: validateApiKeyInput
});
await setAnthropicApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "anthropic:default",
provider: "anthropic",
mode: "api_key"
});
return { config: nextConfig };
}
return null;
}
//#endregion
//#region src/commands/model-allowlist.ts
function ensureModelAllowlistEntry(params) {
const rawModelRef = params.modelRef.trim();
if (!rawModelRef) return params.cfg;
const models = { ...params.cfg.agents?.defaults?.models };
const keySet = new Set([rawModelRef]);
const canonicalKey = resolveAllowlistModelKey(rawModelRef, params.defaultProvider ?? DEFAULT_PROVIDER);
if (canonicalKey) keySet.add(canonicalKey);
for (const key of keySet) models[key] = { ...models[key] };
return {
...params.cfg,
agents: {
...params.cfg.agents,
defaults: {
...params.cfg.agents?.defaults,
models
}
}
};
}
//#endregion
//#region src/commands/auth-choice.default-model.ts
async function applyDefaultModelChoice(params) {
if (params.setDefaultModel) {
const next = params.applyDefaultConfig(params.config);
if (params.noteDefault) await params.prompter.note(`Default model set to ${params.noteDefault}`, "Model configured");
return { config: next };
}
const nextWithModel = ensureModelAllowlistEntry({
cfg: params.applyProviderConfig(params.config),
modelRef: params.defaultModel
});
await params.noteAgentModel(params.defaultModel);
return {
config: nextWithModel,
agentModelOverride: params.defaultModel
};
}
//#endregion
//#region src/commands/google-gemini-model-default.ts
const GOOGLE_GEMINI_DEFAULT_MODEL = "google/gemini-3-pro-preview";
function resolvePrimaryModel$1(model) {
if (typeof model === "string") return model;
if (model && typeof model === "object" && typeof model.primary === "string") return model.primary;
}
function applyGoogleGeminiModelDefault(cfg) {
if (resolvePrimaryModel$1(cfg.agents?.defaults?.model)?.trim() === GOOGLE_GEMINI_DEFAULT_MODEL) return {
next: cfg,
changed: false
};
return {
next: {
...cfg,
agents: {
...cfg.agents,
defaults: {
...cfg.agents?.defaults,
model: cfg.agents?.defaults?.model && typeof cfg.agents.defaults.model === "object" ? {
...cfg.agents.defaults.model,
primary: GOOGLE_GEMINI_DEFAULT_MODEL
} : { primary: GOOGLE_GEMINI_DEFAULT_MODEL }
}
}
},
changed: true
};
}
//#endregion
//#region src/commands/opencode-zen-model-default.ts
const OPENCODE_ZEN_DEFAULT_MODEL = "opencode/claude-opus-4-6";
//#endregion
//#region src/commands/auth-choice.apply.api-providers.ts
async function applyAuthChoiceApiProviders(params) {
let nextConfig = params.config;
let agentModelOverride;
const noteAgentModel = async (model) => {
if (!params.agentId) return;
await params.prompter.note(`Default model set to ${model} for agent "${params.agentId}".`, "Model configured");
};
let authChoice = params.authChoice;
if (authChoice === "apiKey" && params.opts?.tokenProvider && params.opts.tokenProvider !== "anthropic" && params.opts.tokenProvider !== "openai") {
if (params.opts.tokenProvider === "openrouter") authChoice = "openrouter-api-key";
else if (params.opts.tokenProvider === "vercel-ai-gateway") authChoice = "ai-gateway-api-key";
else if (params.opts.tokenProvider === "cloudflare-ai-gateway") authChoice = "cloudflare-ai-gateway-api-key";
else if (params.opts.tokenProvider === "moonshot") authChoice = "moonshot-api-key";
else if (params.opts.tokenProvider === "kimi-code" || params.opts.tokenProvider === "kimi-coding") authChoice = "kimi-code-api-key";
else if (params.opts.tokenProvider === "google") authChoice = "gemini-api-key";
else if (params.opts.tokenProvider === "zai") authChoice = "zai-api-key";
else if (params.opts.tokenProvider === "xiaomi") authChoice = "xiaomi-api-key";
else if (params.opts.tokenProvider === "synthetic") authChoice = "synthetic-api-key";
else if (params.opts.tokenProvider === "venice") authChoice = "venice-api-key";
else if (params.opts.tokenProvider === "opencode") authChoice = "opencode-zen";
}
if (authChoice === "openrouter-api-key") {
const store = ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false });
const existingProfileId = resolveAuthProfileOrder({
cfg: nextConfig,
store,
provider: "openrouter"
}).find((profileId) => Boolean(store.profiles[profileId]));
const existingCred = existingProfileId ? store.profiles[existingProfileId] : void 0;
let profileId = "openrouter:default";
let mode = "api_key";
let hasCredential = false;
if (existingProfileId && existingCred?.type) {
profileId = existingProfileId;
mode = existingCred.type === "oauth" ? "oauth" : existingCred.type === "token" ? "token" : "api_key";
hasCredential = true;
}
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "openrouter") {
await setOpenrouterApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential) {
const envKey = resolveEnvApiKey("openrouter");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing OPENROUTER_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setOpenrouterApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter OpenRouter API key",
validate: validateApiKeyInput
});
await setOpenrouterApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
hasCredential = true;
}
if (hasCredential) nextConfig = applyAuthProfileConfig(nextConfig, {
profileId,
provider: "openrouter",
mode
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: OPENROUTER_DEFAULT_MODEL_REF,
applyDefaultConfig: applyOpenrouterConfig,
applyProviderConfig: applyOpenrouterProviderConfig,
noteDefault: OPENROUTER_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "ai-gateway-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "vercel-ai-gateway") {
await setVercelAiGatewayApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("vercel-ai-gateway");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing AI_GATEWAY_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setVercelAiGatewayApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Vercel AI Gateway API key",
validate: validateApiKeyInput
});
await setVercelAiGatewayApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "vercel-ai-gateway:default",
provider: "vercel-ai-gateway",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF,
applyDefaultConfig: applyVercelAiGatewayConfig,
applyProviderConfig: applyVercelAiGatewayProviderConfig,
noteDefault: VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "cloudflare-ai-gateway-api-key") {
let hasCredential = false;
let accountId = params.opts?.cloudflareAiGatewayAccountId?.trim() ?? "";
let gatewayId = params.opts?.cloudflareAiGatewayGatewayId?.trim() ?? "";
const ensureAccountGateway = async () => {
if (!accountId) {
const value = await params.prompter.text({
message: "Enter Cloudflare Account ID",
validate: (val) => String(val).trim() ? void 0 : "Account ID is required"
});
accountId = String(value).trim();
}
if (!gatewayId) {
const value = await params.prompter.text({
message: "Enter Cloudflare AI Gateway ID",
validate: (val) => String(val).trim() ? void 0 : "Gateway ID is required"
});
gatewayId = String(value).trim();
}
};
const optsApiKey = normalizeApiKeyInput(params.opts?.cloudflareAiGatewayApiKey ?? "");
if (!hasCredential && accountId && gatewayId && optsApiKey) {
await setCloudflareAiGatewayConfig(accountId, gatewayId, optsApiKey, params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("cloudflare-ai-gateway");
if (!hasCredential && envKey) {
if (await params.prompter.confirm({
message: `Use existing CLOUDFLARE_AI_GATEWAY_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await ensureAccountGateway();
await setCloudflareAiGatewayConfig(accountId, gatewayId, normalizeApiKeyInput(envKey.apiKey), params.agentDir);
hasCredential = true;
}
}
if (!hasCredential && optsApiKey) {
await ensureAccountGateway();
await setCloudflareAiGatewayConfig(accountId, gatewayId, optsApiKey, params.agentDir);
hasCredential = true;
}
if (!hasCredential) {
await ensureAccountGateway();
const key = await params.prompter.text({
message: "Enter Cloudflare AI Gateway API key",
validate: validateApiKeyInput
});
await setCloudflareAiGatewayConfig(accountId, gatewayId, normalizeApiKeyInput(String(key)), params.agentDir);
hasCredential = true;
}
if (hasCredential) nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "cloudflare-ai-gateway:default",
provider: "cloudflare-ai-gateway",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
applyDefaultConfig: (cfg) => applyCloudflareAiGatewayConfig(cfg, {
accountId: accountId || params.opts?.cloudflareAiGatewayAccountId,
gatewayId: gatewayId || params.opts?.cloudflareAiGatewayGatewayId
}),
applyProviderConfig: (cfg) => applyCloudflareAiGatewayProviderConfig(cfg, {
accountId: accountId || params.opts?.cloudflareAiGatewayAccountId,
gatewayId: gatewayId || params.opts?.cloudflareAiGatewayGatewayId
}),
noteDefault: CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "moonshot-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "moonshot") {
await setMoonshotApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("moonshot");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing MOONSHOT_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setMoonshotApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Moonshot API key",
validate: validateApiKeyInput
});
await setMoonshotApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "moonshot:default",
provider: "moonshot",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: MOONSHOT_DEFAULT_MODEL_REF,
applyDefaultConfig: applyMoonshotConfig,
applyProviderConfig: applyMoonshotProviderConfig,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "moonshot-api-key-cn") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "moonshot") {
await setMoonshotApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("moonshot");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing MOONSHOT_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setMoonshotApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Moonshot API key (.cn)",
validate: validateApiKeyInput
});
await setMoonshotApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "moonshot:default",
provider: "moonshot",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: MOONSHOT_DEFAULT_MODEL_REF,
applyDefaultConfig: applyMoonshotConfigCn,
applyProviderConfig: applyMoonshotProviderConfigCn,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "kimi-code-api-key") {
let hasCredential = false;
const tokenProvider = params.opts?.tokenProvider?.trim().toLowerCase();
if (!hasCredential && params.opts?.token && (tokenProvider === "kimi-code" || tokenProvider === "kimi-coding")) {
await setKimiCodingApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential) await params.prompter.note(["Kimi Coding uses a dedicated endpoint and API key.", "Get your API key at: https://www.kimi.com/code/en"].join("\n"), "Kimi Coding");
const envKey = resolveEnvApiKey("kimi-coding");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing KIMI_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setKimiCodingApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Kimi Coding API key",
validate: validateApiKeyInput
});
await setKimiCodingApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "kimi-coding:default",
provider: "kimi-coding",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: KIMI_CODING_MODEL_REF,
applyDefaultConfig: applyKimiCodeConfig,
applyProviderConfig: applyKimiCodeProviderConfig,
noteDefault: KIMI_CODING_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "gemini-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "google") {
await setGeminiApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("google");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing GEMINI_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setGeminiApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Gemini API key",
validate: validateApiKeyInput
});
await setGeminiApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "google:default",
provider: "google",
mode: "api_key"
});
if (params.setDefaultModel) {
const applied = applyGoogleGeminiModelDefault(nextConfig);
nextConfig = applied.next;
if (applied.changed) await params.prompter.note(`Default model set to ${GOOGLE_GEMINI_DEFAULT_MODEL}`, "Model configured");
} else {
agentModelOverride = GOOGLE_GEMINI_DEFAULT_MODEL;
await noteAgentModel(GOOGLE_GEMINI_DEFAULT_MODEL);
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "zai-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "zai") {
await setZaiApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("zai");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing ZAI_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setZaiApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Z.AI API key",
validate: validateApiKeyInput
});
await setZaiApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "zai:default",
provider: "zai",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: ZAI_DEFAULT_MODEL_REF,
applyDefaultConfig: applyZaiConfig,
applyProviderConfig: (config) => ({
...config,
agents: {
...config.agents,
defaults: {
...config.agents?.defaults,
models: {
...config.agents?.defaults?.models,
[ZAI_DEFAULT_MODEL_REF]: {
...config.agents?.defaults?.models?.[ZAI_DEFAULT_MODEL_REF],
alias: config.agents?.defaults?.models?.[ZAI_DEFAULT_MODEL_REF]?.alias ?? "GLM"
}
}
}
}
}),
noteDefault: ZAI_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "xiaomi-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "xiaomi") {
await setXiaomiApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
const envKey = resolveEnvApiKey("xiaomi");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing XIAOMI_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setXiaomiApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Xiaomi API key",
validate: validateApiKeyInput
});
await setXiaomiApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "xiaomi:default",
provider: "xiaomi",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: XIAOMI_DEFAULT_MODEL_REF,
applyDefaultConfig: applyXiaomiConfig,
applyProviderConfig: applyXiaomiProviderConfig,
noteDefault: XIAOMI_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "synthetic-api-key") {
if (params.opts?.token && params.opts?.tokenProvider === "synthetic") await setSyntheticApiKey(String(params.opts.token).trim(), params.agentDir);
else {
const key = await params.prompter.text({
message: "Enter Synthetic API key",
validate: (value) => value?.trim() ? void 0 : "Required"
});
await setSyntheticApiKey(String(key).trim(), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "synthetic:default",
provider: "synthetic",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: SYNTHETIC_DEFAULT_MODEL_REF,
applyDefaultConfig: applySyntheticConfig,
applyProviderConfig: applySyntheticProviderConfig,
noteDefault: SYNTHETIC_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "venice-api-key") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "venice") {
await setVeniceApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential) await params.prompter.note([
"Venice AI provides privacy-focused inference with uncensored models.",
"Get your API key at: https://venice.ai/settings/api",
"Supports 'private' (fully private) and 'anonymized' (proxy) modes."
].join("\n"), "Venice AI");
const envKey = resolveEnvApiKey("venice");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing VENICE_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setVeniceApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Venice AI API key",
validate: validateApiKeyInput
});
await setVeniceApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "venice:default",
provider: "venice",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: VENICE_DEFAULT_MODEL_REF,
applyDefaultConfig: applyVeniceConfig,
applyProviderConfig: applyVeniceProviderConfig,
noteDefault: VENICE_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (authChoice === "opencode-zen") {
let hasCredential = false;
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "opencode") {
await setOpencodeZenApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential) await params.prompter.note([
"OpenCode Zen provides access to Claude, GPT, Gemini, and more models.",
"Get your API key at: https://opencode.ai/auth",
"OpenCode Zen bills per request. Check your OpenCode dashboard for details."
].join("\n"), "OpenCode Zen");
const envKey = resolveEnvApiKey("opencode");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing OPENCODE_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setOpencodeZenApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter OpenCode Zen API key",
validate: validateApiKeyInput
});
await setOpencodeZenApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "opencode:default",
provider: "opencode",
mode: "api_key"
});
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: OPENCODE_ZEN_DEFAULT_MODEL,
applyDefaultConfig: applyOpencodeZenConfig,
applyProviderConfig: applyOpencodeZenProviderConfig,
noteDefault: OPENCODE_ZEN_DEFAULT_MODEL,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
return null;
}
//#endregion
//#region src/commands/auth-choice.apply.plugin-provider.ts
function resolveProviderMatch(providers, rawProvider) {
const normalized = normalizeProviderId(rawProvider);
return providers.find((provider) => normalizeProviderId(provider.id) === normalized) ?? providers.find((provider) => provider.aliases?.some((alias) => normalizeProviderId(alias) === normalized) ?? false) ?? null;
}
function pickAuthMethod(provider, rawMethod) {
const raw = rawMethod?.trim();
if (!raw) return null;
const normalized = raw.toLowerCase();
return provider.auth.find((method) => method.id.toLowerCase() === normalized) ?? provider.auth.find((method) => method.label.toLowerCase() === normalized) ?? null;
}
function isPlainRecord(value) {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function mergeConfigPatch(base, patch) {
if (!isPlainRecord(base) || !isPlainRecord(patch)) return patch;
const next = { ...base };
for (const [key, value] of Object.entries(patch)) {
const existing = next[key];
if (isPlainRecord(existing) && isPlainRecord(value)) next[key] = mergeConfigPatch(existing, value);
else next[key] = value;
}
return next;
}
function applyDefaultModel(cfg, model) {
const models = { ...cfg.agents?.defaults?.models };
models[model] = models[model] ?? {};
const existingModel = cfg.agents?.defaults?.model;
return {
...cfg,
agents: {
...cfg.agents,
defaults: {
...cfg.agents?.defaults,
models,
model: {
...existingModel && typeof existingModel === "object" && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
primary: model
}
}
}
};
}
async function applyAuthChoicePluginProvider(params, options) {
if (params.authChoice !== options.authChoice) return null;
const enableResult = enablePluginInConfig(params.config, options.pluginId);
let nextConfig = enableResult.config;
if (!enableResult.enabled) {
await params.prompter.note(`${options.label} plugin is disabled (${enableResult.reason ?? "blocked"}).`, options.label);
return { config: nextConfig };
}
const agentId = params.agentId ?? resolveDefaultAgentId(nextConfig);
const defaultAgentId = resolveDefaultAgentId(nextConfig);
const agentDir = params.agentDir ?? (agentId === defaultAgentId ? resolveOpenClawAgentDir() : resolveAgentDir(nextConfig, agentId));
const workspaceDir = resolveAgentWorkspaceDir(nextConfig, agentId) ?? resolveDefaultAgentWorkspaceDir();
const provider = resolveProviderMatch(resolvePluginProviders({
config: nextConfig,
workspaceDir
}), options.providerId);
if (!provider) {
await params.prompter.note(`${options.label} auth plugin is not available. Enable it and re-run the wizard.`, options.label);
return { config: nextConfig };
}
const method = pickAuthMethod(provider, options.methodId) ?? provider.auth[0];
if (!method) {
await params.prompter.note(`${options.label} auth method missing.`, options.label);
return { config: nextConfig };
}
const isRemote = isRemoteEnvironment();
const result = await method.run({
config: nextConfig,
agentDir,
workspaceDir,
prompter: params.prompter,
runtime: params.runtime,
isRemote,
openUrl: async (url) => {
await openUrl(url);
},
oauth: { createVpsAwareHandlers: (opts) => createVpsAwareOAuthHandlers(opts) }
});
if (result.configPatch) nextConfig = mergeConfigPatch(nextConfig, result.configPatch);
for (const profile of result.profiles) {
upsertAuthProfile({
profileId: profile.profileId,
credential: profile.credential,
agentDir
});
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: profile.profileId,
provider: profile.credential.provider,
mode: profile.credential.type === "token" ? "token" : profile.credential.type,
..."email" in profile.credential && profile.credential.email ? { email: profile.credential.email } : {}
});
}
let agentModelOverride;
if (result.defaultModel) {
if (params.setDefaultModel) {
nextConfig = applyDefaultModel(nextConfig, result.defaultModel);
await params.prompter.note(`Default model set to ${result.defaultModel}`, "Model configured");
} else if (params.agentId) {
agentModelOverride = result.defaultModel;
await params.prompter.note(`Default model set to ${result.defaultModel} for agent "${params.agentId}".`, "Model configured");
}
}
if (result.notes && result.notes.length > 0) await params.prompter.note(result.notes.join("\n"), "Provider notes");
return {
config: nextConfig,
agentModelOverride
};
}
//#endregion
//#region src/commands/auth-choice.apply.copilot-proxy.ts
async function applyAuthChoiceCopilotProxy(params) {
return await applyAuthChoicePluginProvider(params, {
authChoice: "copilot-proxy",
pluginId: "copilot-proxy",
providerId: "copilot-proxy",
methodId: "local",
label: "Copilot Proxy"
});
}
//#endregion
//#region src/commands/auth-choice.apply.github-copilot.ts
async function applyAuthChoiceGitHubCopilot(params) {
if (params.authChoice !== "github-copilot") return null;
let nextConfig = params.config;
await params.prompter.note(["This will open a GitHub device login to authorize Copilot.", "Requires an active GitHub Copilot subscription."].join("\n"), "GitHub Copilot");
if (!process.stdin.isTTY) {
await params.prompter.note("GitHub Copilot login requires an interactive TTY.", "GitHub Copilot");
return { config: nextConfig };
}
try {
await githubCopilotLoginCommand({ yes: true }, params.runtime);
} catch (err) {
await params.prompter.note(`GitHub Copilot login failed: ${String(err)}`, "GitHub Copilot");
return { config: nextConfig };
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "github-copilot:github",
provider: "github-copilot",
mode: "token"
});
if (params.setDefaultModel) {
const model = "github-copilot/gpt-4o";
nextConfig = {
...nextConfig,
agents: {
...nextConfig.agents,
defaults: {
...nextConfig.agents?.defaults,
model: {
...typeof nextConfig.agents?.defaults?.model === "object" ? nextConfig.agents.defaults.model : void 0,
primary: model
}
}
}
};
await params.prompter.note(`Default model set to ${model}`, "Model configured");
}
return { config: nextConfig };
}
//#endregion
//#region src/commands/auth-choice.apply.google-antigravity.ts
async function applyAuthChoiceGoogleAntigravity(params) {
return await applyAuthChoicePluginProvider(params, {
authChoice: "google-antigravity",
pluginId: "google-antigravity-auth",
providerId: "google-antigravity",
methodId: "oauth",
label: "Google Antigravity"
});
}
//#endregion
//#region src/commands/auth-choice.apply.google-gemini-cli.ts
async function applyAuthChoiceGoogleGeminiCli(params) {
return await applyAuthChoicePluginProvider(params, {
authChoice: "google-gemini-cli",
pluginId: "google-gemini-cli-auth",
providerId: "google-gemini-cli",
methodId: "oauth",
label: "Google Gemini CLI"
});
}
//#endregion
//#region src/commands/auth-choice.apply.minimax.ts
async function applyAuthChoiceMiniMax(params) {
let nextConfig = params.config;
let agentModelOverride;
const noteAgentModel = async (model) => {
if (!params.agentId) return;
await params.prompter.note(`Default model set to ${model} for agent "${params.agentId}".`, "Model configured");
};
if (params.authChoice === "minimax-portal") return await applyAuthChoicePluginProvider(params, {
authChoice: "minimax-portal",
pluginId: "minimax-portal-auth",
providerId: "minimax-portal",
methodId: await params.prompter.select({
message: "Select MiniMax endpoint",
options: [{
value: "oauth",
label: "Global",
hint: "OAuth for international users"
}, {
value: "oauth-cn",
label: "CN",
hint: "OAuth for users in China"
}]
}),
label: "MiniMax"
});
if (params.authChoice === "minimax-cloud" || params.authChoice === "minimax-api" || params.authChoice === "minimax-api-lightning") {
const modelId = params.authChoice === "minimax-api-lightning" ? "MiniMax-M2.1-lightning" : "MiniMax-M2.1";
let hasCredential = false;
const envKey = resolveEnvApiKey("minimax");
if (envKey) {
if (await params.prompter.confirm({
message: `Use existing MINIMAX_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true
})) {
await setMinimaxApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter MiniMax API key",
validate: validateApiKeyInput
});
await setMinimaxApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "minimax:default",
provider: "minimax",
mode: "api_key"
});
{
const modelRef = `minimax/${modelId}`;
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: modelRef,
applyDefaultConfig: (config) => applyMinimaxApiConfig(config, modelId),
applyProviderConfig: (config) => applyMinimaxApiProviderConfig(config, modelId),
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return {
config: nextConfig,
agentModelOverride
};
}
if (params.authChoice === "minimax") {
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: "lmstudio/minimax-m2.1-gs32",
applyDefaultConfig: applyMinimaxConfig,
applyProviderConfig: applyMinimaxProviderConfig,
noteAgentModel,
prompter: params.prompter
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
return {
config: nextConfig,
agentModelOverride
};
}
return null;
}
//#endregion
//#region src/commands/chutes-oauth.ts
function buildAuthorizeUrl(params) {
return `${CHUTES_AUTHORIZE_ENDPOINT}?${new URLSearchParams({
client_id: params.clientId,
redirect_uri: params.redirectUri,
response_type: "code",
scope: params.scopes.join(" "),
state: params.state,
code_challenge: params.challenge,
code_challenge_method: "S256"
}).toString()}`;
}
async function waitForLocalCallback(params) {
const redirectUrl = new URL(params.redirectUri);
if (redirectUrl.protocol !== "http:") throw new Error(`Chutes OAuth redirect URI must be http:// (got ${params.redirectUri})`);
const hostname = redirectUrl.hostname || "127.0.0.1";
const port = redirectUrl.port ? Number.parseInt(redirectUrl.port, 10) : 80;
const expectedPath = redirectUrl.pathname || "/";
return await new Promise((resolve, reject) => {
let timeout = null;
const server = createServer((req, res) => {
try {
const