Skip to content
Merged
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
20 changes: 18 additions & 2 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,12 @@ import {
modelList,
workspaceList,
quotaList,
quotaRequest,
quotaUpdate,
quotaHistory,
quotaCheck,
permissionList,
permissionGrant,
permissionRevoke,
datasetUpload,
datasetList,
datasetGet,
Expand Down Expand Up @@ -174,9 +177,12 @@ export const commands: Record<string, AnyCommand> = {
"model list": modelList,
"workspace list": workspaceList,
"quota list": quotaList,
"quota request": quotaRequest,
"quota update": quotaUpdate,
"quota history": quotaHistory,
"quota check": quotaCheck,
"permission list": permissionList,
"permission grant": permissionGrant,
"permission revoke": permissionRevoke,
"dataset upload": datasetUpload,
"dataset list": datasetList,
"dataset get": datasetGet,
Expand Down Expand Up @@ -235,3 +241,13 @@ export const commands: Record<string, AnyCommand> = {
"managed-agent session events": managedAgentSessionEvents,
"managed-agent skill-list": managedAgentSkillList,
};

/**
* Runtime-only aliases for renamed commands: dispatched by the CLI (merged in
* main.ts) but kept out of the canonical map so generate-reference.ts only
* documents the canonical path.
*/
export const commandAliases: Record<string, AnyCommand> = {
// Pre-migration name of "quota update".
"quota request": quotaUpdate,
};
21 changes: 12 additions & 9 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createCli } from "bailian-cli-runtime";
import { commands } from "./commands.ts";
import { commandAliases, commands } from "./commands.ts";
import { commandPackPolicy } from "./command-pack-policy.ts";
import pkg from "../package.json" with { type: "json" };

Expand All @@ -10,11 +10,14 @@ const quickStartTasks = [
"Help me analyze this video and write a Xiaohongshu-style post",
] as const;

void createCli(commands, {
binName: "bl",
version: pkg.version,
clientName: "bailian-cli",
npmPackage: "bailian-cli",
quickStartTasks,
commandPacks: commandPackPolicy,
}).run();
void createCli(
{ ...commands, ...commandAliases },
{
binName: "bl",
version: pkg.version,
clientName: "bailian-cli",
npmPackage: "bailian-cli",
quickStartTasks,
commandPacks: commandPackPolicy,
},
).run();
22 changes: 3 additions & 19 deletions packages/commands/src/commands/finetune/capability.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,29 @@
import {
defineCommand,
detectOutputFormat,
fetchModelList,
fetchModelListAll,
fetchModelCapability,
listSupportedTrainingTypes,
modelSupportsTrainingType,
isTrainingTypeCli,
trainingTypeMethodVariant,
TRAINING_TYPES_CLI,
callConsoleGateway,
effectiveConsoleGatewayConfig,
anonymousConsoleCall,
UsageError,
type Settings,
type ModelCapability,
type FlagsDef,
} from "bailian-cli-core";
import { emitResult, emitBare } from "bailian-cli-runtime";

const PAGE_SIZE = 50;

/**
* Page through every foundation-model page (listFoundationModels, public — no
* console login needed, so the gateway is called anonymously). Returns raw
* records so capability fields (`supports` / `trainingTypes`) are preserved
* for filtering.
*/
async function fetchAllFoundationModels(settings: Settings): Promise<ModelCapability[]> {
const eff = effectiveConsoleGatewayConfig(settings);
const call = (api: string, data: Record<string, unknown>) =>
callConsoleGateway(
{ region: eff.consoleRegion, site: eff.consoleSite, switchAgent: eff.consoleSwitchAgent },
settings.timeout,
{ api, data },
);
const first = await fetchModelList(call, { pageNo: 1, pageSize: PAGE_SIZE });
const all = [...first.models];
const totalPages = Math.ceil(first.total / PAGE_SIZE);
for (let pageNo = 2; pageNo <= totalPages; pageNo++) {
const result = await fetchModelList(call, { pageNo, pageSize: PAGE_SIZE });
all.push(...result.models);
}
const all = await fetchModelListAll(anonymousConsoleCall(settings));
return all as ModelCapability[];
}

Expand Down
16 changes: 9 additions & 7 deletions packages/commands/src/commands/model/list.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
anonymousConsoleCall,
defineCommand,
detectOutputFormat,
fetchModelDetail,
Expand Down Expand Up @@ -290,7 +291,7 @@ function printPredictConfigTable(entries: PredictConfigEntry[]): void {

export default defineCommand({
description: "Browse model families or show detailed model info in the Bailian model marketplace",
auth: "console",
auth: "none",
usageArgs:
"[--model <model>] [--page <n>] [--page-size <n>] [--provider <p>] [--capability <c>] [--feature <f>] [--enrich]",
flags: LIST_FLAGS,
Expand All @@ -302,10 +303,14 @@ export default defineCommand({
"--model qwen-max --enrich --output json",
"--feature function-calling --output json",
],
notes: [
"Both the catalog and --enrich parameter-schema endpoints are public — no console login needed.",
],
async run(ctx) {
const { settings, flags } = ctx;
const format = settings.outputExplicit ? detectOutputFormat(settings.output) : "json";
const modelKey = flags.model;
const call = anonymousConsoleCall(settings);

// ── Detail mode ──
if (modelKey) {
Expand All @@ -316,7 +321,7 @@ export default defineCommand({
return;
}

const detail = await fetchModelDetail(ctx.client.console.bind(ctx.client), modelKey);
const detail = await fetchModelDetail(call, modelKey);

if (!detail) {
emitBare(`Model "${modelKey}" not found.`);
Expand All @@ -328,10 +333,7 @@ export default defineCommand({
await Promise.all(
trunkItems.map(async (item) => {
if (!item.model) return;
const config = await fetchPredictConfig(
ctx.client.console.bind(ctx.client),
item.model,
);
const config = await fetchPredictConfig(call, item.model);
if (config) item.predictConfig = config;
}),
);
Expand Down Expand Up @@ -361,7 +363,7 @@ export default defineCommand({
return;
}

const { total, groups } = await fetchModelGroups(ctx.client.console.bind(ctx.client), params);
const { total, groups } = await fetchModelGroups(call, params);

if (format === "json") {
emitResult(formatBrowseJson(groups, total), format);
Expand Down
41 changes: 41 additions & 0 deletions packages/commands/src/commands/permission/grant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { defineCommand } from "bailian-cli-core";
import { runPermissionChange, validatePermissionChange } from "./shared.ts";

export default defineCommand({
description: "Grant model permissions (inference / finetune / deploy)",
auth: "apiKey",
usageArgs: "--model <models> [--action <actions>] | --all",
flags: {
model: {
type: "string",
valueHint: "<models>",
description: "Model ID(s), comma-separated (max 20)",
},
action: {
type: "string",
valueHint: "<actions>",
description:
"Permission action(s), comma-separated: inference, finetune, deploy (default: inference)",
},
all: {
type: "switch",
description:
"One-key grant inference for all models in the workspace (including future ones)",
},
},
exampleArgs: [
"--model qwen-plus",
"--model qwen-plus,qwen3-max --action inference,finetune",
"--all",
"--model qwen-plus --dry-run --output json",
],
notes: [
"Grants apply to the business workspace your API key belongs to.",
"--all maps to the server one-key switch (access_all_entities: OPEN) and only covers inference.",
"Actions you omit keep their current grants (server-side tri-state patch).",
],
validate: (flags) => validatePermissionChange(flags),
async run(ctx) {
await runPermissionChange(ctx, ctx.flags, true);
},
});
145 changes: 145 additions & 0 deletions packages/commands/src/commands/permission/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { defineCommand, detectOutputFormat, modelsPermissionsPath } from "bailian-cli-core";
import { emitResult, renderBoxTable } from "bailian-cli-runtime";
import { buildQuery } from "../shared/params.ts";

// ---------------------------------------------------------------------------
// Types — mirror GET /api/v1/models/permissions
// ---------------------------------------------------------------------------

interface PermissionDetail {
inference?: boolean | null;
fine_tune?: boolean | null;
deploy?: boolean | null;
}

interface ModelPermission {
model: string;
name?: string;
permissions?: PermissionDetail;
}

interface PermissionsResponse {
output?: {
total?: number;
page_no?: number;
page_size?: number;
permissions?: ModelPermission[];
};
request_id?: string;
}

// ---------------------------------------------------------------------------
// Formatters
// ---------------------------------------------------------------------------

/** Tri-state permission cell: true → yes, false → no, null/undefined → "-". */
function formatGrant(granted: boolean | null | undefined): string {
if (granted == null) return "-";
return granted ? "yes" : "no";
}

function printTable(permissions: ModelPermission[], total: number, emptyHint: string): void {
if (permissions.length === 0) {
process.stdout.write(`No model permissions found.\n${emptyHint}\n`);
return;
}
const headers = ["Model", "Name", "Inference", "Fine-tune", "Deploy"];
const rows = permissions.map((entry) => [
entry.model,
entry.name ?? "-",
formatGrant(entry.permissions?.inference),
formatGrant(entry.permissions?.fine_tune),
formatGrant(entry.permissions?.deploy),
]);
const lines = renderBoxTable({
headers,
rows,
align: ["left", "left", "right", "right", "right"],
});
for (const line of lines) process.stdout.write(line + "\n");
process.stdout.write(`\nTotal: ${total}\n`);
}

// ---------------------------------------------------------------------------
// Command
// ---------------------------------------------------------------------------

export default defineCommand({
description: "List model permissions (inference / fine-tune / deploy) in the workspace",
auth: "apiKey",
usageArgs: "[--scope <scope>] [--model <model>] [--name <name>] [--page <n>] [--page-size <n>]",
flags: {
scope: {
type: "string",
valueHint: "<scope>",
choices: ["authorized", "authorizable"] as const,
description: "Authorization scope: authorizable (default, full catalog), authorized",
},
model: {
type: "string",
valueHint: "<model>",
description: "Model ID (exact match)",
},
name: {
type: "string",
valueHint: "<name>",
description: "Fuzzy search by model name or ID",
},
page: { type: "number", valueHint: "<n>", description: "Page number (default: 1)" },
pageSize: { type: "number", valueHint: "<n>", description: "Results per page (default: 20)" },
},
exampleArgs: [
"",
"--model qwen-plus",
"--scope authorized",
"--name qwen --page-size 50",
"--output text",
],
notes: [
"Default scope is `authorizable` (the full grantable catalog); use `--scope authorized` to see only models already granted.",
"Output defaults to JSON; pass `--output text` for a table. Permission values are tri-state: true / false / null (never set).",
"Values mirror the server's grant records as-is for the workspace bound to your API key. A model reporting false/null can still be callable (access may come from other channels); see the Model Studio authorization docs for the exact semantics.",
],
async run(ctx) {
const { settings, flags } = ctx;
const format = settings.outputExplicit ? detectOutputFormat(settings.output) : "json";
const scope = flags.scope ?? "authorizable";

const query = {
authorization_scope: scope.toUpperCase(),
model: flags.model || undefined,
name: flags.name || undefined,
page_no: flags.page || 1,
page_size: flags.pageSize || 20,
};

if (settings.dryRun) {
emitResult(
{ endpoint: ctx.client.url(modelsPermissionsPath()), method: "GET", query },
format,
);
return;
}

const resp = await ctx.client.requestJson<PermissionsResponse>({
path: modelsPermissionsPath() + buildQuery(query),
});
const permissions = resp.output?.permissions ?? [];
const total = resp.output?.total ?? permissions.length;

if (format === "json") {
emitResult({ items: permissions, total }, format);
return;
}

// The default authorized view is empty until something is granted — point
// at the authorizable catalog instead of ending with a bare "nothing".
const binName = ctx.identity.binName;
const emptyHint =
scope === "authorized"
? `Nothing granted yet in this workspace. Browse grantable models with \`${binName} permission list --scope authorizable\`, then grant with \`${binName} permission grant --model <model>\`.`
: `Adjust --name/--model filters, or check pagination with --page/--page-size.`;

printTable(permissions, total, emptyHint);
},
});
Loading