Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); add token plan by heimanba · Pull Request #37 · modelstudioai/cli · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/commands/app/call.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -102,11 +102,11 @@ export default defineCommand({
}

if (config.dryRun) {
emitResult({ endpoint: appCompletionEndpoint(config.baseUrl, appId), request: body }, format);
emitResult({ endpoint: appCompletionEndpoint(config, appId), request: body }, format);
return;
}

const url = appCompletionEndpoint(config.baseUrl, appId);
const url = appCompletionEndpoint(config, appId);

if (shouldStream) {
const headers: Record<string, string> = { "X-DashScope-SSE": "enable" };
Expand Down
169 changes: 153 additions & 16 deletions packages/cli/src/commands/auth/login.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import {
AUTH_MODES,
BailianError,
CODING_PLAN_REGIONS,
ExitCode,
TOKEN_PLAN_REGIONS,
chatEndpoint,
defineCommand,
getConfigPath,
Expand All@@ -9,12 +12,16 @@ import {
readConfigFile,
requestJson,
writeConfigFile,
type AuthMode,
type CodingPlanRegion,
type Config,
type GlobalFlags,
type TokenPlanRegion,
} from "bailian-cli-core";
import { printQuickStart } from "../../output/banner.ts";
import { emitBare } from "../../output/output.ts";
import { promptConfirm } from "../../output/prompt.ts";
import { interactiveAuthSetup } from "../../utils/auth-wizard.ts";
import { printCurrentCommandHelp } from "../../utils/command-help.ts";
import { resolveConsoleOrigin, runConsoleLogin } from "./login-console.ts";

Expand All@@ -39,11 +46,26 @@ function canRetry(err: unknown): boolean {
return false;
}

async function validateKeyAndPersist(config: Config, key: string): Promise<void> {
async function validateKeyAndPersist(
config: Config,
key: string,
mode: AuthMode,
codingPlanRegion: CodingPlanRegion,
tokenPlanRegion: TokenPlanRegion,
): Promise<void> {
process.stderr.write("Testing key... ");
const testConfig = { ...config, apiKey: key };
const testConfig: Config = {
...config,
activeAuthMode: mode,
apiKey: undefined,
fileApiKey: mode === "standard-api-key" ? key : undefined,
codingPlanApiKey: mode === "coding-plan" ? key : config.codingPlanApiKey,
codingPlanRegion,
tokenPlanApiKey: mode === "token-plan" ? key : config.tokenPlanApiKey,
tokenPlanRegion,
};
const requestOpts = {
url: chatEndpoint(testConfig.baseUrl),
url: chatEndpoint(testConfig),
method: "POST",
timeout: Math.min(config.timeout, 30),
body: {
Expand All@@ -64,7 +86,6 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
cause: err,
});
}
// retry delay: 500ms, 1000ms, 2000ms
const delayMs = RETRY_DELAY_BASE_MS * 2 ** (attempt - 1);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
Expand All@@ -73,25 +94,49 @@ async function validateKeyAndPersist(config: Config, key: string): Promise<void>
process.stderr.write("Valid\n");

const existing = readConfigFile() as Record<string, unknown>;
existing.api_key = key;
existing.active_auth_mode = mode;
if (mode === "standard-api-key") existing.api_key = key;
if (mode === "coding-plan") {
existing.coding_plan_api_key = key;
existing.coding_plan_region = codingPlanRegion;
}
if (mode === "token-plan") {
existing.token_plan_api_key = key;
existing.token_plan_region = tokenPlanRegion;
}
await writeConfigFile(existing);
process.stderr.write(`Active auth mode set to ${mode}\n`);
process.stderr.write(`Saved to ${getConfigPath()}\n`);
}

export default defineCommand({
name: "auth login",
description: "Authenticate with API key or console browser login (credentials can coexist)",
usage: "bl auth login --api-key <key> | bl auth login --console",
description: "Authenticate with API key, console browser login, or interactive wizard",
usage: "bl auth login --mode <mode> --api-key <key> | bl auth login --console",
options: [
{ flag: "--api-key <key>", description: "DashScope API key to store" },
{
flag: "--mode <mode>",
description: "Auth mode: standard-api-key, coding-plan, token-plan",
},
{ flag: "--api-key <key>", description: "API key for the selected auth mode" },
{ flag: "--coding-plan-api-key <key>", description: "Coding Plan API key (sets mode)" },
{ flag: "--coding-plan-region <region>", description: "Coding Plan region: cn, intl" },
{ flag: "--token-plan-api-key <key>", description: "Token Plan API key (sets mode)" },
{ flag: "--token-plan-region <region>", description: "Token Plan region: cn, intl" },
{
flag: "--console",
description: "Sign in via browser; opens the console login URL in your default browser",
type: "boolean",
},
],
examples: ["bl auth login --api-key sk-xxxxx", "bl auth login --console"],
examples: [
"bl auth login --api-key sk-xxxxx",
"bl auth login --mode coding-plan --api-key sk-sp-xxxxx",
"bl auth login --token-plan-api-key sk-xxxxx --token-plan-region intl",
"bl auth login --console",
],
async run(config: Config, flags: GlobalFlags) {
// Console login branch (cli-specific)
if (flags.console) {
if (config.dryRun) {
emitBare(
Expand All@@ -102,11 +147,32 @@ export default defineCommand({
const hasApiKey = !!(config.apiKey || config.fileApiKey);
await runConsoleLogin(resolveConsoleOrigin(), {
needApiKey: !hasApiKey,
onApiKey: (key) => validateKeyAndPersist(config, key),
onApiKey: (key) =>
validateKeyAndPersist(
config,
key,
"standard-api-key",
config.codingPlanRegion,
config.tokenPlanRegion,
),
});
return;
}

const hasFlags = !!(
flags.mode ||
flags.apiKey ||
flags.codingPlanApiKey ||
flags.tokenPlanApiKey ||
flags.codingPlanRegion ||
flags.tokenPlanRegion
);

let mode: AuthMode;
let key: string | undefined;
let codingPlanRegion: CodingPlanRegion;
let tokenPlanRegion: TokenPlanRegion;

const envKey = process.env.DASHSCOPE_API_KEY;
if (envKey && !flags.apiKey) {
const maskedEnvKey = maskToken(envKey);
Expand All@@ -119,22 +185,93 @@ export default defineCommand({
process.stdout.write("Login skipped. Using environment variables.\n");
process.exit(0);
}
} else {
} else if (hasFlags) {
process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.\n`);
}
}

const key = (flags.apiKey as string) || config.apiKey;
if (!hasFlags && isInteractive({ nonInteractive: config.nonInteractive })) {
const result = await interactiveAuthSetup(config);
mode = result.mode;
key = result.key;
codingPlanRegion = result.codingPlanRegion ?? config.codingPlanRegion;
tokenPlanRegion = result.tokenPlanRegion ?? config.tokenPlanRegion;
} else {
const explicitMode = flags.mode as string | undefined;
mode = resolveLoginMode(explicitMode, flags);
key =
(flags.apiKey as string | undefined) ||
(flags.codingPlanApiKey as string | undefined) ||
(flags.tokenPlanApiKey as string | undefined) ||
(mode === "standard-api-key" ? config.apiKey : undefined);
codingPlanRegion = resolveCodingPlanRegion(flags, config);
tokenPlanRegion = resolveTokenPlanRegion(flags, config);
}

if (!key) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
if (!hasFlags) {
printCurrentCommandHelp(process.stderr);
process.exit(0);
}
throw new BailianError(
"--api-key is required.",
ExitCode.USAGE,
"bl auth login --mode <mode> --api-key <key>",
);
}

if (mode === "coding-plan" && !key.startsWith("sk-sp-")) {
throw new BailianError(
'Invalid API key. Coding Plan API keys start with "sk-sp-".',
ExitCode.USAGE,
);
}

if (!config.dryRun) {
await validateKeyAndPersist(config, key);
await validateKeyAndPersist(config, key, mode, codingPlanRegion, tokenPlanRegion);
printQuickStart();
} else {
emitBare("Would validate and save API key.");
emitBare(`Would validate and save ${mode} API key.`);
}
},
});

function resolveLoginMode(explicitMode: string | undefined, flags: GlobalFlags): AuthMode {
if (explicitMode) {
if (!AUTH_MODES.has(explicitMode)) {
throw new BailianError(
`Invalid auth mode "${explicitMode}".`,
ExitCode.USAGE,
"Valid modes: standard-api-key, coding-plan, token-plan",
);
}
return explicitMode as AuthMode;
}
if (flags.codingPlanApiKey) return "coding-plan";
if (flags.tokenPlanApiKey) return "token-plan";
return "standard-api-key";
}

function resolveCodingPlanRegion(flags: GlobalFlags, config: Config): CodingPlanRegion {
const region = (flags.codingPlanRegion as string | undefined) || config.codingPlanRegion;
if (!CODING_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Coding Plan region "${region}".`,
ExitCode.USAGE,
"Valid Coding Plan regions: cn, intl",
);
}
return region as CodingPlanRegion;
}

function resolveTokenPlanRegion(flags: GlobalFlags, config: Config): TokenPlanRegion {
const region = (flags.tokenPlanRegion as string | undefined) || config.tokenPlanRegion;
if (!TOKEN_PLAN_REGIONS.has(region)) {
throw new BailianError(
`Invalid Token Plan region "${region}".`,
ExitCode.USAGE,
"Valid Token Plan regions: cn, intl",
);
}
return region as TokenPlanRegion;
}
51 changes: 34 additions & 17 deletions packages/cli/src/commands/auth/logout.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import {
defineCommand,
clearApiKey,
readConfigFile,
writeConfigFile,
getConfigPath,
Expand All@@ -9,34 +8,27 @@ import {
} from "bailian-cli-core";
import { emitBare } from "../../output/output.ts";

async function clearConsoleToken(): Promise<boolean> {
const file = readConfigFile() as Record<string, unknown>;
if (!file.access_token) return false;
delete file.access_token;
await writeConfigFile(file);
return true;
}

export default defineCommand({
name: "auth logout",
description: "Clear stored credentials",
usage: "bl auth logout [--console] [--yes] [--dry-run]",
usage: "bl auth logout [--console] [--all] [--yes] [--dry-run]",
options: [
{
flag: "--console",
description: "Only clear the console access_token, keep api_key intact",
type: "boolean",
},
{ flag: "--all", description: "Clear all stored auth credentials", type: "boolean" },
{ flag: "--yes", description: "Skip confirmation prompt" },
],
examples: [
"bl auth logout",
"bl auth logout --console",
"bl auth logout --all",
"bl auth logout --dry-run",
"bl auth logout --yes",
],
async run(config: Config, flags: GlobalFlags) {
const file = readConfigFile();
const file = readConfigFile() as Record<string, unknown>;

if (flags.console) {
const hasToken = !!file.access_token;
Expand All@@ -47,7 +39,8 @@ export default defineCommand({
return;
}
if (hasToken) {
await clearConsoleToken();
delete file.access_token;
await writeConfigFile(file);
process.stderr.write(`Cleared access_token from ${getConfigPath()}\n`);
if (file.api_key) {
process.stderr.write(
Expand All@@ -60,20 +53,44 @@ export default defineCommand({
return;
}

const hasKey = !!(file.api_key || file.access_token);
const keys = keysToClear(config, !!flags.all);
const hasKey = keys.some(
(key) => typeof file[key] === "string" && (file[key] as string).length,
);

if (config.dryRun) {
if (hasKey) emitBare("Would clear api_key / access_token from ~/.bailian/config.json");
if (hasKey) emitBare(`Would clear ${keys.join(", ")} from ~/.bailian/config.json`);
else emitBare("No credentials to clear.");
emitBare("No changes made.");
return;
}

if (hasKey) {
await clearApiKey();
process.stderr.write("Cleared api_key / access_token from ~/.bailian/config.json\n");
for (const key of keys) delete file[key];
if (config.activeAuthMode !== "standard-api-key") {
file.active_auth_mode = "standard-api-key";
}
await writeConfigFile(file);
process.stderr.write(`Cleared ${keys.join(", ")} from ${getConfigPath()}\n`);
if (config.activeAuthMode !== "standard-api-key") {
process.stderr.write("Active auth mode reset to standard-api-key.\n");
}
} else {
process.stderr.write("No credentials to clear.\n");
}
},
});

function keysToClear(config: Config, all: boolean): string[] {
if (all)
return [
"api_key",
"coding_plan_api_key",
"token_plan_api_key",
"active_auth_mode",
"access_token",
];
if (config.activeAuthMode === "coding-plan") return ["coding_plan_api_key"];
if (config.activeAuthMode === "token-plan") return ["token_plan_api_key"];
return ["api_key", "access_token"];
}
Loading