diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index 52c0fc96..02fb4553 100644 --- a/packages/bailian-kb-dsh/package.json +++ b/packages/bailian-kb-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-kb-dsh", - "version": "2.10.4", + "version": "2.10.5", "description": "Bailian knowledge-base tools for DeepSeek Harness: kb_search and kb_chat over the DashScope RAG API, plus the bl CLI management skill.", "keywords": [ "alibaba-cloud", diff --git a/packages/bailian-memo-dsh/package.json b/packages/bailian-memo-dsh/package.json index a0fdae44..adb3472c 100644 --- a/packages/bailian-memo-dsh/package.json +++ b/packages/bailian-memo-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-memo-dsh", - "version": "2.10.4", + "version": "2.10.5", "description": "Bailian personal memory for DeepSeek Harness: automatic recall, silent curation, and user-controlled remember/forget.", "keywords": [ "alibaba-cloud", diff --git a/packages/cli/package.json b/packages/cli/package.json index 9c1ac9f5..13d5125c 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.10.4", + "version": "2.10.5", "description": "CLI for Aliyun Model Studio (DashScope) AI Platform.", "keywords": [ "agent", diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 91214219..92793ba8 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -234,6 +234,8 @@ import { deployCapacityCreate, deployCapacityScale, deployCapacityRenew, + deployCapacityAutoRenewEnable, + deployCapacityAutoRenewDisable, deployCapacityDelete, deployCapacityUnsubscribe, deployOverflow, @@ -245,6 +247,12 @@ import { deployDelete, deployPause, deployResume, + deployRouterVersions, + deployRouterCreate, + deployRouterList, + deployRouterGet, + deployRouterUpdate, + deployRouterDelete, tokenPlanListSeats, tokenPlanCreateKey, tokenPlanAssignSeats, @@ -613,6 +621,8 @@ export const commands: Record = { "deploy capacity create": deployCapacityCreate, "deploy capacity scale": deployCapacityScale, "deploy capacity renew": deployCapacityRenew, + "deploy capacity auto-renew enable": deployCapacityAutoRenewEnable, + "deploy capacity auto-renew disable": deployCapacityAutoRenewDisable, "deploy capacity delete": deployCapacityDelete, "deploy capacity unsubscribe": deployCapacityUnsubscribe, "deploy overflow": deployOverflow, @@ -624,6 +634,12 @@ export const commands: Record = { "deploy delete": deployDelete, "deploy pause": deployPause, "deploy resume": deployResume, + "deploy router versions": deployRouterVersions, + "deploy router create": deployRouterCreate, + "deploy router list": deployRouterList, + "deploy router get": deployRouterGet, + "deploy router update": deployRouterUpdate, + "deploy router delete": deployRouterDelete, "token-plan list-seats": tokenPlanListSeats, "token-plan create-key": tokenPlanCreateKey, "token-plan assign-seats": tokenPlanAssignSeats, diff --git a/packages/commands/package.json b/packages/commands/package.json index f5ff5306..91b165a5 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.10.4", + "version": "2.10.5", "description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/commands/src/commands/deploy/capacity-write.ts b/packages/commands/src/commands/deploy/capacity-write.ts index b10bae0b..447a1cfc 100644 --- a/packages/commands/src/commands/deploy/capacity-write.ts +++ b/packages/commands/src/commands/deploy/capacity-write.ts @@ -6,6 +6,7 @@ import { createCapacityInstance, scaleCapacityInstance, renewCapacityInstance, + updateCapacityInstanceAutoRenew, deleteCapacityInstance, buildReservationCapacity, buildPrepaidInfo, @@ -61,10 +62,11 @@ export const deployCapacityCreate = defineCommand({ }, flags: CREATE_FLAGS, usageArgs: - "--deployed-model --billing-method --input-tpm --output-tpm [--duration ] [--auto-renewal ] [--wait]", + "--deployed-model --billing-method --input-tpm --output-tpm [--pricing-cycle ] [--duration ] [--auto-renewal ] [--wait]", exampleArgs: [ "--deployed-model example-code --billing-method POST_PAY --input-tpm 10000 --output-tpm 1000 --dry-run", "--deployed-model example-code --billing-method PRE_PAY --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run", + "--deployed-model example-code --billing-method PRE_PAY --pricing-cycle Hour --duration 8 --auto-renewal false --input-tpm 10000 --output-tpm 1000 --dry-run", ], notes: [ ...MUTATION_NOTES, @@ -74,6 +76,12 @@ export const deployCapacityCreate = defineCommand({ "zh-CN": "沿用原 ModelCode、模型和性能档位。同一 ModelCode 只允许一个未释放的后付费实例;购买资格和实例数量限制由服务端校验。", }, + { + "en-US": + "The 8-hour off-peak window is an additional prepaid purchase: --pricing-cycle Hour with --duration 8, --auto-renewal false and no automatic-renewal duration. The selling window (22:00–24:00 Beijing time) and model support are validated by the server; created instances cannot be scaled, renewed, auto-renewed, released or unsubscribed and expire automatically.", + "zh-CN": + "8 小时闲时窗口按预付费叠加购买:--pricing-cycle Hour 配 --duration 8、--auto-renewal false,不传自动续费时长。售卖时段(北京时间 22:00–24:00)与模型支持由服务端校验;所建实例不可变配、续订、自动续费、释放或退订,到期自动失效。", + }, ], validate(flags) { const error = @@ -242,7 +250,7 @@ export const deployCapacityRenew = defineCommand({ }, flags: RENEW_FLAGS, usageArgs: - "--deployed-model --instance-id --duration --auto-renewal [--is-change ] [--input-tpm ] [--output-tpm ] [--wait]", + "--deployed-model --instance-id --duration --auto-renewal [--is-change ] [--input-tpm ] [--output-tpm ] [--wait]", exampleArgs: [ "--deployed-model example-code --instance-id example-instance --duration 30 --auto-renewal false --dry-run", "--deployed-model example-code --instance-id example-instance --duration 30 --auto-renewal true --auto-renewal-duration 30 --dry-run", @@ -410,3 +418,133 @@ export const deployCapacityDelete = defineCommand({ ); }, }); + +const AUTO_RENEW_FLAGS = { + ...DEPLOYED_MODEL_FLAG, + ...CAPACITY_INSTANCE_FLAG, + ...WRITE_OPTIONS, + cycle: { + type: "string", + valueHint: "", + required: true, + choices: ["Day"] as const, + description: { + "en-US": "Automatic renewal cycle; the service currently accepts only Day (case-sensitive)", + "zh-CN": "自动续费周期单位;当前服务仅接受 Day(区分大小写)", + }, + }, + autoRenewalDuration: { + type: "number", + valueHint: "", + required: true, + description: { + "en-US": "Days renewed at each automatic renewal, positive integer", + "zh-CN": "每次自动续费的天数,正整数", + }, + }, +} satisfies FlagsDef; + +function defineCapacityAutoRenewCommand(autoRenewal: boolean) { + return defineCommand({ + defaultOutput: "json", + description: autoRenewal + ? { + "en-US": "Enable automatic renewal for one prepaid capacity instance", + "zh-CN": "开启单个预付费容量实例的自动续费", + } + : { + "en-US": "Disable automatic renewal for one prepaid capacity instance", + "zh-CN": "关闭单个预付费容量实例的自动续费", + }, + auth: "apiKey", + risk: { + level: "high", + ...(autoRenewal ? { reason: "billing" as const } : {}), + message: autoRenewal + ? { + "en-US": + "Enabling automatic renewal starts recurring charges until it is disabled again.", + "zh-CN": "开启自动续费后将按周期持续扣费,直到再次关闭。", + } + : { + "en-US": "Disabling automatic renewal stops recurring charges at expiry.", + "zh-CN": "关闭自动续费后,到期不再自动续费扣款。", + }, + }, + flags: AUTO_RENEW_FLAGS, + usageArgs: + "--deployed-model --instance-id --cycle --auto-renewal-duration [--wait]", + exampleArgs: [ + "--deployed-model example-code --instance-id example-instance --cycle Day --auto-renewal-duration 30 --dry-run", + ], + notes: [ + ...MUTATION_NOTES, + { + "en-US": + "Prepaid instances only; refreshes can_enable_auto_renew / can_disable_auto_renew before writing. 8-hour off-peak instances do not support automatic renewal. The operation usually completes synchronously and returns SUCCEEDED.", + "zh-CN": + "仅预付费实例;写入前刷新 can_enable_auto_renew / can_disable_auto_renew。8 小时闲时实例不支持自动续费。该操作通常同步完成并返回 SUCCEEDED。", + }, + ], + validate: (flags) => { + const optionError = validateQueryIds(flags) ?? validateWriteOptions(flags); + if (optionError) return optionError; + if ( + flags.autoRenewalDuration === undefined || + !Number.isSafeInteger(flags.autoRenewalDuration) || + flags.autoRenewalDuration <= 0 + ) + return "--auto-renewal-duration must be a positive safe integer in days.\n--auto-renewal-duration 必须是正安全整数(天)。"; + return undefined; + }, + async run(ctx) { + const { flags, settings } = ctx; + const body = { + auto_renewal: autoRenewal, + auto_renewal_cycle: flags.cycle, + auto_renewal_duration: flags.autoRenewalDuration, + }; + if (settings.dryRun) { + const resultData5 = { + action: autoRenewal + ? "deploy.capacity.auto-renew.enable" + : "deploy.capacity.auto-renew.disable", + deployed_model: flags.deployedModel, + instance_id: flags.instanceId, + body, + client_request_id: flags.requestId ?? "", + precheck: autoRenewal ? "can_enable_auto_renew" : "can_disable_auto_renew", + wait: flags.wait, + }; + ctx.output.result( + resultData5, + ctx.settings.output === "text" + ? { text: JSON.stringify(resultData5, null, 2) } + : undefined, + ); + return; + } + const instance = await requireCapacityInstance( + ctx.client, + flags.deployedModel, + flags.instanceId, + autoRenewal ? "enable_auto_renew" : "disable_auto_renew", + ); + if (instance.charge_type !== "pre_paid") + throw new BailianError( + "Only prepaid instances support automatic renewal. / 仅预付费实例支持自动续费。", + ExitCode.USAGE, + ); + const requestId = flags.requestId ?? randomUUID(); + const response = await submitCapacityWrite(requestId, () => + updateCapacityInstanceAutoRenew(ctx.client, flags.deployedModel, flags.instanceId, body, { + requestId, + }), + ); + await finishMutation(ctx, flags.deployedModel, response, flags, requestId, true); + }, + }); +} + +export const deployCapacityAutoRenewEnable = defineCapacityAutoRenewCommand(true); +export const deployCapacityAutoRenewDisable = defineCapacityAutoRenewCommand(false); diff --git a/packages/commands/src/commands/deploy/create.ts b/packages/commands/src/commands/deploy/create.ts index f078cb6f..9001d1b7 100644 --- a/packages/commands/src/commands/deploy/create.ts +++ b/packages/commands/src/commands/deploy/create.ts @@ -77,8 +77,9 @@ const CREATE_FLAGS = { type: "number", valueHint: "", description: { - "en-US": "Legacy thinking-output capacity flag; not supported for PTU", - "zh-CN": "旧版思考输出容量参数;PTU 不支持此参数", + "en-US": + "Thinking-output capacity in kTPM (plan=ptu); only some models support it, validated server-side", + "zh-CN": "思考输出容量,单位 kTPM(plan=ptu);仅部分模型支持,由服务端校验", }, }, chargeType: { @@ -112,7 +113,7 @@ const CREATE_FLAGS = { } satisfies FlagsDef; const CREATE_USAGE = - "--model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--input-tpm --output-tpm ] [flags]"; + "--model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--pricing-cycle ] [--input-tpm --output-tpm ] [flags]"; const CREATE_RISK: CommandRisk = { level: "high", @@ -131,9 +132,15 @@ const CREATE_NOTES = [ }, { "en-US": - "For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity is unsupported. Prepaid requires --duration and explicit --auto-renewal true|false.", + "For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity (--thinking-output-tpm) is only supported by some models and is validated server-side. Prepaid requires --duration and explicit --auto-renewal true|false.", "zh-CN": - "plan=ptu 时,--charge-type、--input-tpm 和 --output-tpm 必填。容量单位为 kTPM(1 kTPM = 1000 Token/分钟),不支持单独的思考输出容量。预付费须提供 --duration 和显式 --auto-renewal true|false。", + "plan=ptu 时,--charge-type、--input-tpm 和 --output-tpm 必填。容量单位为 kTPM(1 kTPM = 1000 Token/分钟);单独的思考输出容量(--thinking-output-tpm)仅部分模型支持,由服务端校验。预付费须提供 --duration 和显式 --auto-renewal true|false。", + }, + { + "en-US": + "The 8-hour off-peak window is prepaid ptu_default only: --pricing-cycle Hour with --duration 8, --auto-renewal false and an explicit --service-tier ptu_default. Service hours must fall within 22:00–08:00, so orders are accepted only between 22:00 and 24:00 Beijing time; model support is validated by the server.", + "zh-CN": + "8 小时闲时窗口仅限预付费 ptu_default:--pricing-cycle Hour 配 --duration 8、--auto-renewal false,且必须显式指定 --service-tier ptu_default。服务时段须完整落在 22:00–08:00,因此仅在北京时间 22:00–24:00 之间下单;模型支持由服务端校验。", }, { "en-US": @@ -194,8 +201,6 @@ function validateCreate( if (!flags.displayName?.trim()) { return "--display-name is required for non-PTU plans. / 非 PTU 方案必须提供 --display-name。"; } - } else if (flags.thinkingOutputTpm !== undefined) { - return "--thinking-output-tpm is not supported for PTU. / PTU 不支持 --thinking-output-tpm。"; } return validateWriteOptions(flags) ?? strategy.validateFlags(flags); } @@ -259,6 +264,7 @@ export const deployTextCreate = defineCommand({ "--model-name my-qwen-sft --display-name my-sft-test", "--model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type post_paid --input-tpm 10000 --output-tpm 1000 --dry-run", "--model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type pre_paid --service-tier ptu_default --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run", + "--model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type pre_paid --service-tier ptu_default --pricing-cycle Hour --duration 8 --auto-renewal false --input-tpm 10000 --output-tpm 1000 --dry-run", "--model-name qwen3-8b --display-name my-qwen3-mu --plan mu", "--model-name qwen3-8b --display-name my-qwen3 --plan mu --deploy-spec MU1 --capacity 2", ], diff --git a/packages/commands/src/commands/deploy/delete.ts b/packages/commands/src/commands/deploy/delete.ts index 76a4940a..dc3f516d 100644 --- a/packages/commands/src/commands/deploy/delete.ts +++ b/packages/commands/src/commands/deploy/delete.ts @@ -85,6 +85,7 @@ export default defineCommand({ const status = (deployment?.status ?? "").toUpperCase(); const plan = typeof deployment?.plan === "string" ? deployment.plan.trim().toLowerCase() : ""; const knownPtuPlan = plan === "ptu" || plan === "ptu_v2"; + const knownModelRouterPlan = plan === "mr"; const knownNonPtuPlan = plan === "mu" || plan === "cu" || plan === "lora"; const hasMeaningfulPtuTier = typeof deployment?.ptu_service_tier === "string" && @@ -95,7 +96,7 @@ export default defineCommand({ !Array.isArray(deployment.ptu_capacity) && Object.keys(deployment.ptu_capacity).length > 0; const isPtu = knownPtuPlan || (!plan && (hasMeaningfulPtuTier || hasMeaningfulPtuCapacity)); - if (!isPtu && !knownNonPtuPlan) { + if (!isPtu && !knownModelRouterPlan && !knownNonPtuPlan) { throw new BailianError( "Cannot determine deployment plan safely; deletion was not submitted. / 无法可靠判断部署计划类型;未提交删除请求。", ExitCode.USAGE, @@ -161,7 +162,7 @@ export default defineCommand({ ); } } - } else if (status !== "STOPPED" && status !== "FAILED") { + } else if (!knownModelRouterPlan && status !== "STOPPED" && status !== "FAILED") { throw new BailianError( `Deployment ${deployedModel} must be STOPPED or FAILED before deletion (current: ${status || "unknown"}). / 部署 ${deployedModel} 删除前必须为 STOPPED 或 FAILED(当前:${status || "未知"})。`, ExitCode.USAGE, diff --git a/packages/commands/src/commands/deploy/mutation-shared.ts b/packages/commands/src/commands/deploy/mutation-shared.ts index 3d9c64c0..dc14b3b6 100644 --- a/packages/commands/src/commands/deploy/mutation-shared.ts +++ b/packages/commands/src/commands/deploy/mutation-shared.ts @@ -33,12 +33,22 @@ export const CAPACITY_FLAGS = { } satisfies FlagsDef; export const PREPAID_FLAGS = { + pricingCycle: { + type: "string", + valueHint: "", + choices: ["Day", "Hour"] as const, + description: { + "en-US": + "Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window", + "zh-CN": "预付费计费周期(区分大小写):Day(默认)或 Hour(8 小时闲时窗口)", + }, + }, duration: { type: "number", - valueHint: "", + valueHint: "", description: { - "en-US": "Prepaid purchase/renewal duration, positive integer days", - "zh-CN": "预付费购买或续订天数,正整数", + "en-US": "Prepaid duration: positive integer days for Day, exactly 8 hours for Hour", + "zh-CN": "预付费时长:Day 使用正整数天数,Hour 固定为 8 小时", }, }, autoRenewal: { @@ -127,9 +137,9 @@ export const MUTATION_NOTES: LocalizedText[] = [ }, { "en-US": - "Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change.", + "Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`.", "zh-CN": - "容量是单个实例的绝对 kTPM,不是增量或 ModelCode 总量;容量归零不等于释放。模型步长、上下限及购买时长限制由服务端校验。自动续费配置属于购买、变配或续订流程,不是独立免费设置操作。", + "容量是单个实例的绝对 kTPM,不是增量或 ModelCode 总量;容量归零不等于释放。模型步长、上下限及购买时长限制由服务端校验。自动续费在购买或续订时配置,变更请使用 `deploy capacity auto-renew enable` / `disable`。", }, ]; @@ -169,10 +179,22 @@ export async function requireCapacityInstance( client: Client, code: string, id: string, - action: "scale" | "renew" | "delete", + action: "scale" | "renew" | "delete" | "enable_auto_renew" | "disable_auto_renew", ): Promise { const response = await getCapacityInstance(client, code, id); const instance = response.output ?? response.data; + if ( + action === "delete" && + instance?.pre_paid_info?.pricing_cycle === "Hour" && + instance.deleted !== true + ) { + throw new BailianError( + "8-hour off-peak instances cannot be released or unsubscribed; they expire automatically at gmt_expired. / 8 小时闲时实例不能释放或退订,到期后自动失效。", + ExitCode.USAGE, + undefined, + { cause: response }, + ); + } if (!instance || instance.deleted === true || instance[`can_${action}`] !== true) { throw new BailianError( `Capacity instance does not currently allow ${action}; refresh its details. / 容量实例当前不允许 ${action},请刷新详情。`, diff --git a/packages/commands/src/commands/deploy/operation-wait.ts b/packages/commands/src/commands/deploy/operation-wait.ts index 03361f84..c217e577 100644 --- a/packages/commands/src/commands/deploy/operation-wait.ts +++ b/packages/commands/src/commands/deploy/operation-wait.ts @@ -101,11 +101,12 @@ export async function waitForCapacityOperation( } if (operation?.operation_status === "SUCCEEDED") { const instanceId = operation.instance_id ?? options.fallbackInstanceId; - const instance = instanceId - ? await getCapacityInstance(client, deployedModel, instanceId, controller.signal) - : undefined; - checkDeadline(); - const deployment = await getDeployment(client, deployedModel, controller.signal); + const [instance, deployment] = await Promise.all([ + instanceId + ? getCapacityInstance(client, deployedModel, instanceId, controller.signal) + : undefined, + getDeployment(client, deployedModel, controller.signal), + ]); checkDeadline(); return { ...response, instance, deployment }; } diff --git a/packages/commands/src/commands/deploy/router-create.ts b/packages/commands/src/commands/deploy/router-create.ts new file mode 100644 index 00000000..18c765fc --- /dev/null +++ b/packages/commands/src/commands/deploy/router-create.ts @@ -0,0 +1,70 @@ +import { createDeployment, defineCommand, type FlagsDef } from "bailian-cli-core"; + +import { + ROUTER_CONFIG_FLAGS, + buildCreateModelRouterRequest, + validateRouterConfig, + validateRouterName, +} from "./router-shared.ts"; + +const FLAGS = { + name: { + type: "string", + valueHint: "", + required: true, + description: { + "en-US": "Router name (1–64 letters, digits or hyphens)", + "zh-CN": "路由名称(1–64 个字母、数字或连字符)", + }, + }, + ...ROUTER_CONFIG_FLAGS, +} satisfies FlagsDef; + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": "Create a postpaid model router", + "zh-CN": "创建后付费模型路由", + }, + auth: "apiKey", + risk: { + level: "high", + reason: "billing", + message: { + "en-US": + "Creating the model router starts it in RUNNING state immediately; postpaid routing may incur charges.", + "zh-CN": "创建模型路由后会立即进入 RUNNING 状态;后付费路由可能产生费用。", + }, + }, + usageArgs: + "--name --route-version --strategy --candidates ", + flags: FLAGS, + exampleArgs: [ + "--name my-router --route-version v1 --strategy EFFECT_FIRST --candidates qwen-plus,qwen-turbo --dry-run", + ], + notes: [ + { + "en-US": + "Creation uses plan=mr and charge_type=post_paid. The router becomes RUNNING immediately and may incur postpaid charges; preview with --dry-run before confirming.", + "zh-CN": + "创建固定使用 plan=mr 和 charge_type=post_paid。路由会立即进入 RUNNING 状态并可能产生后付费费用;确认前请先使用 --dry-run 预览。", + }, + ], + validate: (flags) => validateRouterName(flags.name) ?? validateRouterConfig(flags), + async run(ctx) { + const body = buildCreateModelRouterRequest(ctx.flags); + if (ctx.settings.dryRun) { + const result = { action: "deploy.router.create", body }; + ctx.output.result( + result, + ctx.settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + return; + } + const response = await createDeployment(ctx.client, body); + ctx.output.result( + response, + ctx.settings.output === "text" ? { text: JSON.stringify(response, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/deploy/router-delete.ts b/packages/commands/src/commands/deploy/router-delete.ts new file mode 100644 index 00000000..483e7ce3 --- /dev/null +++ b/packages/commands/src/commands/deploy/router-delete.ts @@ -0,0 +1,56 @@ +import { defineCommand, deleteDeployment, getDeployment } from "bailian-cli-core"; + +import { + ROUTER_RESOURCE_FLAGS, + assertModelRouter, + validateRouterResource, +} from "./router-shared.ts"; + +export default defineCommand({ + defaultOutput: "json", + description: { "en-US": "Delete a model router", "zh-CN": "删除模型路由" }, + auth: "apiKey", + risk: { + level: "high", + reason: "destructive", + message: { + "en-US": "This permanently deletes the specified model router and cannot be undone.", + "zh-CN": "该操作会永久删除指定的模型路由,且无法撤销。", + }, + }, + usageArgs: "--deployed-model ", + flags: ROUTER_RESOURCE_FLAGS, + exampleArgs: [ + "--deployed-model router-example --dry-run", + { + "en-US": "--deployed-model router-example --yes # Execute only after confirmation", + "zh-CN": "--deployed-model router-example --yes # 仅在确认后执行", + }, + ], + notes: [ + { + "en-US": + "Deletion is irreversible. The command verifies plan=mr first; a RUNNING model router does not need to be stopped before deletion.", + "zh-CN": "删除不可撤销。本命令会先验证 plan=mr;RUNNING 状态的模型路由无需停机即可删除。", + }, + ], + validate: validateRouterResource, + async run(ctx) { + const { flags, settings } = ctx; + if (settings.dryRun) { + const result = { action: "deploy.router.delete", deployed_model: flags.deployedModel }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + return; + } + const getResponse = await getDeployment(ctx.client, flags.deployedModel); + assertModelRouter(getResponse.output ?? getResponse.data); + const response = await deleteDeployment(ctx.client, flags.deployedModel); + ctx.output.result( + response, + settings.output === "text" ? { text: JSON.stringify(response, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/deploy/router-get.ts b/packages/commands/src/commands/deploy/router-get.ts new file mode 100644 index 00000000..0049ba8c --- /dev/null +++ b/packages/commands/src/commands/deploy/router-get.ts @@ -0,0 +1,42 @@ +import { defineCommand, getDeployment } from "bailian-cli-core"; + +import { + ROUTER_RESOURCE_FLAGS, + assertModelRouter, + validateRouterResource, +} from "./router-shared.ts"; + +export default defineCommand({ + defaultOutput: "json", + description: { "en-US": "Get model router details", "zh-CN": "获取模型路由详情" }, + auth: "apiKey", + usageArgs: "--deployed-model ", + flags: ROUTER_RESOURCE_FLAGS, + exampleArgs: ["--deployed-model router-example", "--deployed-model router-example --output json"], + notes: [ + { + "en-US": "The deployment is verified as plan=mr before its details are returned.", + "zh-CN": "返回详情前会验证该部署为 plan=mr。", + }, + ], + validate: validateRouterResource, + async run(ctx) { + const { flags, settings } = ctx; + if (settings.dryRun) { + const result = { action: "deploy.router.get", deployed_model: flags.deployedModel }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + return; + } + const response = await getDeployment(ctx.client, flags.deployedModel); + const deployment = response.output ?? response.data; + assertModelRouter(deployment); + const result = { ...deployment, request_id: response.request_id }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/deploy/router-list.ts b/packages/commands/src/commands/deploy/router-list.ts new file mode 100644 index 00000000..4d3999f0 --- /dev/null +++ b/packages/commands/src/commands/deploy/router-list.ts @@ -0,0 +1,61 @@ +import { defineCommand, listDeployments, type FlagsDef } from "bailian-cli-core"; + +import { validateRouterListPagination } from "./router-shared.ts"; + +const FLAGS = { + page: { + type: "number", + valueHint: "", + description: { "en-US": "Page number (default: 1)", "zh-CN": "页码(默认:1)" }, + }, + pageSize: { + type: "number", + valueHint: "", + description: { + "en-US": "Results per page (1–100, default: 10)", + "zh-CN": "每页结果数(1–100,默认:10)", + }, + }, +} satisfies FlagsDef; + +export default defineCommand({ + defaultOutput: "json", + description: { "en-US": "List model routers", "zh-CN": "列出模型路由" }, + auth: "apiKey", + usageArgs: "[--page ] [--page-size ]", + flags: FLAGS, + exampleArgs: ["", "--page 2 --page-size 20"], + notes: [ + { + "en-US": "This command always requests plan=mr and does not expose a plan override.", + "zh-CN": "本命令固定请求 plan=mr,不提供方案覆盖选项。", + }, + ], + validate: validateRouterListPagination, + async run(ctx) { + const { flags, settings } = ctx; + const page = flags.page ?? 1; + const pageSize = flags.pageSize ?? 10; + if (settings.dryRun) { + const result = { action: "deploy.router.list", page, page_size: pageSize, plan: "mr" }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + return; + } + const response = await listDeployments(ctx.client, { pageNo: page, pageSize, plan: "mr" }); + const payload = response.output ?? response.data; + const result = { + items: payload?.deployments ?? [], + total: payload?.total, + page_no: payload?.page_no ?? page, + page_size: payload?.page_size ?? pageSize, + request_id: response.request_id, + }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/deploy/router-shared.ts b/packages/commands/src/commands/deploy/router-shared.ts new file mode 100644 index 00000000..dd9e7232 --- /dev/null +++ b/packages/commands/src/commands/deploy/router-shared.ts @@ -0,0 +1,250 @@ +import { + BailianError, + ExitCode, + type CreateModelRouterRequest, + type Deployment, + type FlagsDef, + type ModelRoutingConfig, + type UpdateModelRouterRequest, +} from "bailian-cli-core"; + +import { DEPLOYED_MODEL_FLAG, validatePagination } from "./query-shared.ts"; + +const ROUTER_CONFIG_FLAG_DEFINITIONS = { + routeVersion: { + type: "string", + valueHint: "", + description: { + "en-US": "Model-routing version returned by the versions command", + "zh-CN": "版本命令返回的模型路由版本", + }, + }, + strategy: { + type: "string", + valueHint: "", + choices: ["EFFECT_FIRST", "COST_FIRST"] as const, + description: { + "en-US": "Routing optimization strategy", + "zh-CN": "路由优化策略", + }, + }, + candidates: { + type: "string", + valueHint: "", + description: { + "en-US": "Candidate model IDs, comma-separated", + "zh-CN": "候选模型 ID,逗号分隔", + }, + }, +} satisfies FlagsDef; + +export const ROUTER_CONFIG_FLAGS = { + routeVersion: { ...ROUTER_CONFIG_FLAG_DEFINITIONS.routeVersion, required: true }, + strategy: { ...ROUTER_CONFIG_FLAG_DEFINITIONS.strategy, required: true }, + candidates: { ...ROUTER_CONFIG_FLAG_DEFINITIONS.candidates, required: true }, +} satisfies FlagsDef; + +export const ROUTER_RESOURCE_FLAGS = { + ...DEPLOYED_MODEL_FLAG, +} satisfies FlagsDef; + +export const ROUTER_UPDATE_FLAGS = { + ...DEPLOYED_MODEL_FLAG, + ...ROUTER_CONFIG_FLAG_DEFINITIONS, +} satisfies FlagsDef; + +export function validateRouterResource(flags: { deployedModel?: string }): string | undefined { + if (flags.deployedModel !== undefined && !flags.deployedModel.trim()) { + return "--deployed-model must not be empty. / --deployed-model 不能为空。"; + } + return undefined; +} + +export function validateRouterConfig(flags: { + deployedModel?: string; + routeVersion: string; + candidates: string; +}): string | undefined { + const resourceError = validateRouterResource(flags); + if (resourceError) return resourceError; + if (!flags.routeVersion.trim()) { + return "--route-version must not be empty. / --route-version 不能为空。"; + } + if (splitCandidates(flags.candidates).some((candidate) => !candidate)) { + return "--candidates must not contain empty values. / --candidates 不能包含空值。"; + } + return undefined; +} + +export function validateRouterUpdate(flags: { + deployedModel?: string; + routeVersion?: string; + strategy?: "EFFECT_FIRST" | "COST_FIRST"; + candidates?: string; +}): string | undefined { + const resourceError = validateRouterResource(flags); + if (resourceError) return resourceError; + if ( + flags.routeVersion === undefined && + flags.strategy === undefined && + flags.candidates === undefined + ) { + return "Provide at least one of --route-version, --strategy or --candidates. / 请至少提供 --route-version、--strategy 或 --candidates 之一。"; + } + if (flags.routeVersion !== undefined && !flags.routeVersion.trim()) { + return "--route-version must not be empty. / --route-version 不能为空。"; + } + if ( + flags.candidates !== undefined && + splitCandidates(flags.candidates).some((candidate) => !candidate) + ) { + return "--candidates must not contain empty values. / --candidates 不能包含空值。"; + } + return undefined; +} + +export function hasCompleteRouterUpdate(flags: { + routeVersion?: string; + strategy?: "EFFECT_FIRST" | "COST_FIRST"; + candidates?: string; +}): flags is { + routeVersion: string; + strategy: "EFFECT_FIRST" | "COST_FIRST"; + candidates: string; +} { + return ( + flags.routeVersion !== undefined && + flags.strategy !== undefined && + flags.candidates !== undefined + ); +} + +function splitCandidates(candidates: string): string[] { + return candidates.split(",").map((candidate) => candidate.trim()); +} + +export function validateRouterName(name: string): string | undefined { + const trimmedName = name.trim(); + if (trimmedName.length < 1 || trimmedName.length > 64) { + return "--name must contain 1–64 characters. / --name 长度必须为 1–64 个字符。"; + } + if (!/^[A-Za-z0-9-]+$/.test(trimmedName)) { + return "--name may contain only letters, digits and hyphens. / --name 只能包含字母、数字和连字符。"; + } + return undefined; +} + +export function validateRouterVersionsPagination(flags: { + page?: number; + pageSize?: number; +}): string | undefined { + if (flags.page !== undefined && (!Number.isSafeInteger(flags.page) || flags.page < 1)) { + return "--page must be a positive integer. / --page 必须是正整数。"; + } + if ( + flags.pageSize !== undefined && + (!Number.isSafeInteger(flags.pageSize) || flags.pageSize < 1 || flags.pageSize > 1000) + ) { + return "--page-size must be an integer from 1 to 1000. / --page-size 必须是 1–1000 的整数。"; + } + return undefined; +} + +export function validateRouterListPagination(flags: { + page?: number; + pageSize?: number; +}): string | undefined { + return validatePagination(flags); +} + +export function buildRoutingConfig(flags: { + routeVersion: string; + strategy: "EFFECT_FIRST" | "COST_FIRST"; + candidates: string; +}): ModelRoutingConfig { + const candidateModelIds = [...new Set(splitCandidates(flags.candidates))]; + return { + route_model_version: flags.routeVersion.trim(), + strategy: flags.strategy, + candidate_model_ids: candidateModelIds, + }; +} + +export function buildCreateModelRouterRequest(flags: { + name: string; + routeVersion: string; + strategy: "EFFECT_FIRST" | "COST_FIRST"; + candidates: string; +}): CreateModelRouterRequest { + return { + name: flags.name.trim(), + plan: "mr", + charge_type: "post_paid", + routing_config: buildRoutingConfig(flags), + }; +} + +export function buildUpdateModelRouterRequest( + flags: { + routeVersion?: string; + strategy?: "EFFECT_FIRST" | "COST_FIRST"; + candidates?: string; + }, + currentConfig?: ModelRoutingConfig, +): UpdateModelRouterRequest { + const mergedConfig: Record = { ...currentConfig }; + if (flags.routeVersion !== undefined) { + mergedConfig.route_model_version = flags.routeVersion.trim(); + } + if (flags.strategy !== undefined) { + mergedConfig.strategy = flags.strategy; + } + if (flags.candidates !== undefined) { + mergedConfig.candidate_model_ids = [...new Set(splitCandidates(flags.candidates))]; + } + + const routeModelVersion = mergedConfig.route_model_version; + const strategy = mergedConfig.strategy; + const candidateModelIds = mergedConfig.candidate_model_ids; + if ( + typeof routeModelVersion !== "string" || + !routeModelVersion.trim() || + (strategy !== "EFFECT_FIRST" && strategy !== "COST_FIRST") || + !Array.isArray(candidateModelIds) || + candidateModelIds.some((candidate) => typeof candidate !== "string" || !candidate.trim()) + ) { + throw new BailianError( + "The current router response does not contain a complete routing_config, so the update cannot be merged safely. / 当前路由响应未包含完整的 routing_config,无法安全合并更新。", + ExitCode.GENERAL, + ); + } + + return { + routing_config: { + ...mergedConfig, + route_model_version: routeModelVersion.trim(), + strategy, + candidate_model_ids: candidateModelIds, + }, + }; +} + +export function assertModelRouter( + deployment: Deployment | undefined, +): asserts deployment is Deployment { + if (deployment?.plan?.trim().toLowerCase() !== "mr") { + throw new BailianError( + "The specified deployment is not a model router (plan=mr). / 指定的部署不是模型路由(plan=mr)。", + ExitCode.USAGE, + ); + } +} + +export function assertRouterRunning(deployment: Deployment): void { + if (deployment.status?.trim().toUpperCase() !== "RUNNING") { + throw new BailianError( + `The model router must be RUNNING for this operation (current: ${deployment.status || "unknown"}). / 执行此操作时模型路由必须为 RUNNING(当前:${deployment.status || "未知"})。`, + ExitCode.USAGE, + ); + } +} diff --git a/packages/commands/src/commands/deploy/router-update.ts b/packages/commands/src/commands/deploy/router-update.ts new file mode 100644 index 00000000..29b51c7f --- /dev/null +++ b/packages/commands/src/commands/deploy/router-update.ts @@ -0,0 +1,87 @@ +import { + BailianError, + ExitCode, + defineCommand, + getDeployment, + updateDeployment, + type UpdateModelRouterRequest, +} from "bailian-cli-core"; + +import { + ROUTER_UPDATE_FLAGS, + assertModelRouter, + assertRouterRunning, + buildUpdateModelRouterRequest, + hasCompleteRouterUpdate, + validateRouterUpdate, +} from "./router-shared.ts"; + +interface RouterUpdatePrepared { + body: UpdateModelRouterRequest; +} + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": "Update selected fields of a running model router configuration", + "zh-CN": "更新运行中模型路由的指定配置项", + }, + auth: "apiKey", + usageArgs: + "--deployed-model [--route-version ] [--strategy ] [--candidates ]", + flags: ROUTER_UPDATE_FLAGS, + exampleArgs: [ + "--deployed-model router-example --strategy COST_FIRST --dry-run", + "--deployed-model router-example --route-version v1 --strategy COST_FIRST --candidates qwen-plus,qwen-turbo --dry-run", + ], + notes: [ + { + "en-US": + "Provide at least one routing field. The CLI reads the current router and preserves fields you do not provide; --candidates replaces the entire candidate list. Only RUNNING model routers can be updated.", + "zh-CN": + "请至少提供一个路由配置项。CLI 会读取当前路由并保留未提供的字段;--candidates 会替换整个候选模型列表。仅 RUNNING 状态的模型路由可更新。", + }, + { + "en-US": + "A dry-run with all three routing fields stays offline. A partial dry-run requires credentials and reads the current router, but never submits an update.", + "zh-CN": + "同时提供三个路由配置项时,预览不会联网。部分参数预览需要凭证并读取当前路由,但不会提交更新。", + }, + ], + validate: validateRouterUpdate, + async prepare(ctx) { + let body: UpdateModelRouterRequest; + if (ctx.settings.dryRun && hasCompleteRouterUpdate(ctx.flags)) { + body = buildUpdateModelRouterRequest(ctx.flags); + } else { + const getResponse = await getDeployment(ctx.client, ctx.flags.deployedModel); + const deployment = getResponse.output ?? getResponse.data; + assertModelRouter(deployment); + assertRouterRunning(deployment); + body = buildUpdateModelRouterRequest(ctx.flags, deployment.routing_config); + } + return { + data: { body }, + preview: { + action: "deploy.router.update", + deployed_model: ctx.flags.deployedModel, + body, + }, + risk: null, + notices: [], + }; + }, + async run(ctx) { + if (!ctx.prepared) { + throw new BailianError( + "The model router update requires a prepared request. / 模型路由更新需要先完成请求预检。", + ExitCode.GENERAL, + ); + } + const response = await updateDeployment(ctx.client, ctx.flags.deployedModel, ctx.prepared.body); + ctx.output.result( + response, + ctx.settings.output === "text" ? { text: JSON.stringify(response, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/deploy/router-versions.ts b/packages/commands/src/commands/deploy/router-versions.ts new file mode 100644 index 00000000..61c987c1 --- /dev/null +++ b/packages/commands/src/commands/deploy/router-versions.ts @@ -0,0 +1,67 @@ +import { defineCommand, listModelRoutingVersions, type FlagsDef } from "bailian-cli-core"; + +import { validateRouterVersionsPagination } from "./router-shared.ts"; + +const FLAGS = { + page: { + type: "number", + valueHint: "", + description: { "en-US": "Page number (default: 1)", "zh-CN": "页码(默认:1)" }, + }, + pageSize: { + type: "number", + valueHint: "", + description: { + "en-US": "Results per page (1–1000, default: 50)", + "zh-CN": "每页结果数(1–1000,默认:50)", + }, + }, +} satisfies FlagsDef; + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": "List available model-routing versions and candidates", + "zh-CN": "列出可用的模型路由版本和候选模型", + }, + auth: "apiKey", + usageArgs: "[--page ] [--page-size ]", + flags: FLAGS, + exampleArgs: ["", "--page 1 --page-size 100"], + notes: [ + { + "en-US": + "Use the returned route_model_version, supported_strategies and supported_candidate_model_ids when creating or fully replacing a router configuration.", + "zh-CN": + "创建路由或完整替换路由配置时,请使用返回的 route_model_version、supported_strategies 和 supported_candidate_model_ids。", + }, + ], + validate: validateRouterVersionsPagination, + async run(ctx) { + const { flags, settings } = ctx; + const page = flags.page ?? 1; + const pageSize = flags.pageSize ?? 50; + if (settings.dryRun) { + const result = { action: "deploy.router.versions", page, page_size: pageSize }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + return; + } + const response = await listModelRoutingVersions(ctx.client, { pageNo: page, pageSize }); + const payload = response.output ?? response.data; + const result = { + items: payload?.route_model_versions ?? [], + total: payload?.total, + total_page: payload?.total_page, + page_no: payload?.page_no ?? page, + page_size: payload?.page_size ?? pageSize, + request_id: response.request_id, + }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index 90d12cf7..9c295f44 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -239,6 +239,8 @@ export { deployCapacityCreate, deployCapacityScale, deployCapacityRenew, + deployCapacityAutoRenewEnable, + deployCapacityAutoRenewDisable, deployCapacityDelete, } from "./commands/deploy/capacity-write.ts"; export { default as deployCapacityUnsubscribe } from "./commands/deploy/capacity-unsubscribe.ts"; @@ -251,6 +253,12 @@ export { default as deployUpdate } from "./commands/deploy/update.ts"; export { default as deployDelete } from "./commands/deploy/delete.ts"; export { default as deployPause } from "./commands/deploy/pause.ts"; export { default as deployResume } from "./commands/deploy/resume.ts"; +export { default as deployRouterVersions } from "./commands/deploy/router-versions.ts"; +export { default as deployRouterCreate } from "./commands/deploy/router-create.ts"; +export { default as deployRouterList } from "./commands/deploy/router-list.ts"; +export { default as deployRouterGet } from "./commands/deploy/router-get.ts"; +export { default as deployRouterUpdate } from "./commands/deploy/router-update.ts"; +export { default as deployRouterDelete } from "./commands/deploy/router-delete.ts"; export { default as tokenPlanListSeats } from "./commands/token-plan/list-seats.ts"; export { default as tokenPlanCreateKey } from "./commands/token-plan/create-key.ts"; export { default as tokenPlanAssignSeats } from "./commands/token-plan/assign-seats.ts"; diff --git a/packages/commands/tests/deploy-capacity-write.test.ts b/packages/commands/tests/deploy-capacity-write.test.ts index 1b0903ae..b2a581df 100644 --- a/packages/commands/tests/deploy-capacity-write.test.ts +++ b/packages/commands/tests/deploy-capacity-write.test.ts @@ -12,6 +12,8 @@ import { deployCapacityCreate, deployCapacityScale, deployCapacityRenew, + deployCapacityAutoRenewEnable, + deployCapacityAutoRenewDisable, deployCapacityDelete, } from "../src/commands/deploy/capacity-write.ts"; import deployOverflow from "../src/commands/deploy/overflow.ts"; @@ -46,6 +48,8 @@ const INSTANCE = { can_scale: true, can_renew: true, can_delete: true, + can_enable_auto_renew: true, + can_disable_auto_renew: true, configured_capacity: { input_tpm: 100, output_tpm: 10 }, }; const OPERATION = { @@ -61,6 +65,8 @@ interface MutationCase { path: string; body?: object; precheck?: string; + /** can_* key consulted before the write; defaults to `can_${name}`. */ + capability?: string; instance: typeof INSTANCE; } const MUTATIONS: MutationCase[] = [ @@ -93,6 +99,28 @@ const MUTATIONS: MutationCase[] = [ precheck: "can_renew/pre_paid/configured_capacity", instance: { ...INSTANCE, charge_type: "pre_paid" }, }, + { + name: "auto-renew.enable", + command: deployCapacityAutoRenewEnable, + flags: { ...IDS, cycle: "Day", autoRenewalDuration: 30 }, + method: "PUT", + path: `${INSTANCE_PATH}/auto-renew`, + body: { auto_renewal: true, auto_renewal_cycle: "Day", auto_renewal_duration: 30 }, + precheck: "can_enable_auto_renew", + capability: "can_enable_auto_renew", + instance: { ...INSTANCE, charge_type: "pre_paid" }, + }, + { + name: "auto-renew.disable", + command: deployCapacityAutoRenewDisable, + flags: { ...IDS, cycle: "Day", autoRenewalDuration: 30 }, + method: "PUT", + path: `${INSTANCE_PATH}/auto-renew`, + body: { auto_renewal: false, auto_renewal_cycle: "Day", auto_renewal_duration: 30 }, + precheck: "can_disable_auto_renew", + capability: "can_disable_auto_renew", + instance: { ...INSTANCE, charge_type: "pre_paid" }, + }, { name: "delete", command: deployCapacityDelete, @@ -285,6 +313,14 @@ describe("capacity mutation metadata and offline previews", () => { }); expect(deployCapacityRenew.flags).not.toHaveProperty("orderType"); expect(deployCapacityScale.flags?.orderType.choices).toEqual(["UPGRADE", "DOWNGRADE"]); + expect(deployCapacityAutoRenewEnable.flags?.cycle).toMatchObject({ + required: true, + choices: ["Day"], + }); + expect(deployCapacityAutoRenewEnable.risk).toMatchObject({ reason: "billing" }); + expect(deployCapacityAutoRenewDisable.risk).not.toHaveProperty("reason"); + expect(deployCapacityAutoRenewEnable.flags).not.toHaveProperty("autoRenewal"); + expect(deployCapacityAutoRenewEnable.flags).not.toHaveProperty("pricingCycle"); }); test.each(MUTATIONS)( @@ -503,7 +539,7 @@ describe.each(MUTATIONS)("$name capacity write contract", (mutation) => { }); describe("capacity/prepaid validation and purchase mapping", () => { - test.each(MUTATIONS.filter(({ name }) => name !== "delete"))( + test.each(MUTATIONS.filter((mutation) => "inputTpm" in mutation.flags))( "$name rejects unpaired, negative, fractional or unsafe capacity locally", async (mutation) => { for (const capacity of [ @@ -542,6 +578,12 @@ describe("capacity/prepaid validation and purchase mapping", () => { { duration: 31, autoRenewal: true }, { ...PREPAID, autoRenewalDuration: 0 }, { ...PREPAID, autoRenewalCycle: " " }, + { pricingCycle: "Hour" }, + { pricingCycle: "Hour", duration: 30, autoRenewal: false }, + { pricingCycle: "Hour", duration: 8, autoRenewal: true }, + { pricingCycle: "Hour", duration: 8, autoRenewal: false, autoRenewalDuration: 31 }, + { pricingCycle: "Hour", duration: 8, autoRenewal: false, autoRenewalCycle: "Day" }, + { pricingCycle: "MONTH", duration: 31, autoRenewal: false }, ])("PRE_PAY purchase rejects incomplete prepaid block %j", async (flags) => { const mock = mockClient(); await expect( @@ -565,6 +607,8 @@ describe("capacity/prepaid validation and purchase mapping", () => { PREPAID, { autoRenewalDuration: 31 }, { autoRenewalCycle: "Day" }, + { pricingCycle: "Day" }, + { pricingCycle: "Hour" }, ])("POST_PAY rejects prepaid fields %j", async (prepaid) => { const mock = mockClient(); await expect( @@ -615,6 +659,29 @@ describe("capacity/prepaid validation and purchase mapping", () => { }, ); + test("PRE_PAY Hour off-peak purchase maps the exact 8-hour block", async () => { + const mock = mockClient({ output: OPERATION }); + await run( + deployCapacityCreate, + { + deployedModel: MODEL_CODE, + billingMethod: "PRE_PAY", + inputTpm: 0, + outputTpm: 7, + pricingCycle: "Hour", + duration: 8, + autoRenewal: false, + }, + mock.client, + ); + expect(writes(mock)[0].body).toEqual({ + billing_method: "PRE_PAY", + ptu_capacity: { input_tpm: 0, output_tpm: 7 }, + pre_paid_info: { pricing_cycle: "Hour", duration: 8, auto_renewal: false }, + }); + expect(requests(mock)).toHaveLength(1); + }); + test.each([undefined, "UPGRADE", "DOWNGRADE"])( "prepaid scale maps orderType=%s and never invents absent prepaid settings", async (orderType) => { @@ -656,7 +723,7 @@ describe.each(MUTATIONS.filter(({ precheck }) => precheck))("$name precheck safe test.each(["false", "missing", "deleted", "missing payload"])( "%s capability/instance prevents all writes", async (scenario) => { - const capability = `can_${mutation.name}`; + const capability = mutation.capability ?? `can_${mutation.name}`; const response = scenario === "missing payload" ? {} @@ -770,6 +837,25 @@ describe("renewal and release business constraints", () => { }, ); + test.each(["RUNNING", "FAILED"])( + "8-hour off-peak status=%s instance is never released or unsubscribed", + async (status) => { + const mock = mockClient({ + output: { + ...INSTANCE, + charge_type: "pre_paid", + status, + pre_paid_info: { pricing_cycle: "Hour", duration: 8, auto_renewal: false }, + }, + }); + await expect(run(deployCapacityDelete, IDS, mock.client)).rejects.toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringMatching(/8-hour|8 小时/), + }); + expect(writes(mock)).toHaveLength(0); + }, + ); + test.each(["accepted", "rejected"])( "FAILED prepaid release is %s by the server, not decided from status alone", async (outcome) => { diff --git a/packages/commands/tests/deploy-legacy-write.test.ts b/packages/commands/tests/deploy-legacy-write.test.ts index f50341d5..8905fa61 100644 --- a/packages/commands/tests/deploy-legacy-write.test.ts +++ b/packages/commands/tests/deploy-legacy-write.test.ts @@ -243,10 +243,13 @@ describe.each(CREATE_COMMANDS)("$name create", ({ command }) => { expect(requests(mock)).toHaveLength(1); }); - test("PTU rejects thinking-output rather than ignoring it", async () => { - expect(await validate(command, { ...PTU_CREATE, thinkingOutputTpm: 0 })).toMatch( - /thinking-output-tpm/, - ); + test("PTU forwards thinking-output capacity without dropping zero", async () => { + const mock = mockClient({ output: { deployed_model: MODEL_CODE } }); + await run(command, { ...PTU_CREATE, thinkingOutputTpm: 0 }, mock.client); + expect(requests(mock)).toHaveLength(1); + expect(requests(mock)[0].body).toMatchObject({ + ptu_capacity: { input_tpm: 10, output_tpm: 1, thinking_output_tpm: 0 }, + }); }); test.each(["lora", "mu"])("%s requires display-name", async (plan) => { @@ -778,4 +781,41 @@ describe("delete safety", () => { expect(requests(mock).every(({ method }) => method === "GET")).toBe(true); }, ); + + test.each(["output", "data"] as const)( + "deletes a RUNNING model router without requiring STOPPED via %s envelope", + async (envelope) => { + const response = { [envelope]: { deployed_model: MODEL_CODE, deleted: true } }; + const mock = mockClient({ [envelope]: { plan: "mr", status: "RUNNING" } }, response); + await run(deployDelete, { deployedModel: MODEL_CODE }, mock.client); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + expect(JSON.parse(stdout)).toEqual(response); + }, + ); + + test("model router skips PTU capacity and operation prechecks", async () => { + const mock = mockClient( + { output: { plan: "mr", status: "RUNNING" } }, + { output: { deployed_model: MODEL_CODE, deleted: true } }, + ); + await run(deployDelete, { deployedModel: MODEL_CODE }, mock.client); + // Only GET deployment + DELETE, no capacity-instances or operation GET + expect(requests(mock)).toHaveLength(2); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + }); + + test.each(["STOPPED", "FAILED"])( + "model router %s status also deletes without extra checks", + async (status) => { + const mock = mockClient({ output: { plan: "mr", status } }, { output: { deleted: true } }); + await run(deployDelete, { deployedModel: MODEL_CODE }, mock.client); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + }, + ); + + test("skip-precheck for model router skips the GET entirely", async () => { + const mock = mockClient({ output: { deleted: true } }); + await run(deployDelete, { deployedModel: MODEL_CODE, skipPrecheck: true }, mock.client); + expect(requests(mock).map(({ method }) => method)).toEqual(["DELETE"]); + }); }); diff --git a/packages/commands/tests/deploy-query.test.ts b/packages/commands/tests/deploy-query.test.ts index 843eb84a..c847f164 100644 --- a/packages/commands/tests/deploy-query.test.ts +++ b/packages/commands/tests/deploy-query.test.ts @@ -583,7 +583,7 @@ describe("waitForCapacityOperation read-only polling", () => { beforeEach(() => vi.useFakeTimers()); test.each(["output", "data"] as const)( - "backs off PROCESSING, then preserves %s and refreshes instance followed by deployment", + "backs off PROCESSING, then preserves %s and refreshes instance and deployment", async (envelope) => { const mock = createMockClient(); const response = { @@ -668,6 +668,32 @@ describe("waitForCapacityOperation read-only polling", () => { }, ); + test("starts both refreshes before either completes and preserves both responses", async () => { + const response = { + output: { operation_status: "SUCCEEDED", instance_id: INSTANCE_ID }, + }; + const instance = { output: { instance_id: INSTANCE_ID } }; + const deployment = { data: { deployed_model: MODEL_CODE } }; + const mock = createMockClient(); + mock.requestJson.mockImplementation(async (request) => { + if (request.path === OPERATION_PATH) return response; + return new Promise((resolve) => { + setTimeout( + () => resolve(request.path === INSTANCE_PATH ? instance : deployment), + request.path === INSTANCE_PATH ? 100 : 200, + ); + }); + }); + const result = wait(mock.client); + await vi.advanceTimersByTimeAsync(0); + const startedPaths = requestPaths(mock); + await vi.advanceTimersByTimeAsync(300); + expect(await result).toEqual({ ...response, instance, deployment }); + expect(startedPaths).toEqual([OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH]); + const signal = mock.requestJson.mock.calls[0][0].signal; + for (const [request] of mock.requestJson.mock.calls) expect(request.signal).toBe(signal); + }); + test.each([undefined, ""])( "SUCCEEDED without instance_id=%s refreshes only the deployment", async (instanceId) => { @@ -756,9 +782,15 @@ describe("waitForCapacityOperation read-only polling", () => { mock.requestJson.mockResolvedValueOnce({ output: { operation_status: "SUCCEEDED", instance_id: INSTANCE_ID }, }); - if (phase === "deployment") - mock.requestJson.mockResolvedValueOnce({ output: { instance_id: INSTANCE_ID } }); - mock.requestJson.mockImplementation(pendingRequestUntilAbort); + mock.requestJson.mockImplementation((request) => { + if ( + phase === "poll" || + (phase === "instance" && request.path === INSTANCE_PATH) || + (phase === "deployment" && request.path === DEPLOYMENT_PATH) + ) + return pendingRequestUntilAbort(request); + return Promise.resolve({ output: {} }); + }); const result = wait(mock.client, { pollTimeout: 3 }); const rejection = expect(result).rejects.toMatchObject({ exitCode: ExitCode.TIMEOUT }); await vi.advanceTimersByTimeAsync(0); @@ -769,11 +801,7 @@ describe("waitForCapacityOperation read-only polling", () => { expect(request.signal?.aborted).toBe(true); expect(await result.catch((error: unknown) => error)).toBe(request.signal?.reason); expect(requestPaths(mock)).toEqual( - phase === "poll" - ? [OPERATION_PATH] - : phase === "instance" - ? [OPERATION_PATH, INSTANCE_PATH] - : [OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH], + phase === "poll" ? [OPERATION_PATH] : [OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH], ); }, ); @@ -826,6 +854,28 @@ describe("waitForCapacityOperation read-only polling", () => { }, ); + test("parent cancellation aborts both in-flight refreshes and clears the deadline", async () => { + const controller = new AbortController(); + const reason = new Error("cancel refreshes"); + const mock = createMockClient(); + mock.requestJson + .mockResolvedValueOnce({ + output: { operation_status: "SUCCEEDED", instance_id: INSTANCE_ID }, + }) + .mockImplementation(pendingRequestUntilAbort); + const result = wait(mock.client, { signal: controller.signal }); + const rejection = expect(result).rejects.toBe(reason); + await vi.advanceTimersByTimeAsync(0); + expect(requestPaths(mock)).toEqual([OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH]); + controller.abort(reason); + await rejection; + for (const [request] of mock.requestJson.mock.calls) { + expect(request.signal?.aborted).toBe(true); + expect(request.signal?.reason).toBe(reason); + } + expect(vi.getTimerCount()).toBe(0); + }); + test("successful wait detaches the parent signal and deadline without later aborting requests", async () => { const controller = new AbortController(); const addListener = vi.spyOn(controller.signal, "addEventListener"); @@ -842,7 +892,7 @@ describe("waitForCapacityOperation read-only polling", () => { }); test.each(["poll", "instance", "deployment"] as const)( - "passes an HTTP failure during %s through unchanged without additional requests", + "passes an HTTP failure during %s through unchanged without retries", async (phase) => { const failure = new BailianError( "Server original message", @@ -859,16 +909,18 @@ describe("waitForCapacityOperation read-only polling", () => { mock.requestJson.mockResolvedValueOnce({ data: { operation_status: "SUCCEEDED", instance_id: INSTANCE_ID }, }); - if (phase === "deployment") - mock.requestJson.mockResolvedValueOnce({ data: { instance_id: INSTANCE_ID } }); - mock.requestJson.mockRejectedValue(failure); + mock.requestJson.mockImplementation((request) => { + if ( + phase === "poll" || + (phase === "instance" && request.path === INSTANCE_PATH) || + (phase === "deployment" && request.path === DEPLOYMENT_PATH) + ) + return Promise.reject(failure); + return Promise.resolve({ data: {} }); + }); await expect(wait(mock.client)).rejects.toBe(failure); expect(requestPaths(mock)).toEqual( - phase === "poll" - ? [OPERATION_PATH] - : phase === "instance" - ? [OPERATION_PATH, INSTANCE_PATH] - : [OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH], + phase === "poll" ? [OPERATION_PATH] : [OPERATION_PATH, INSTANCE_PATH, DEPLOYMENT_PATH], ); }, ); diff --git a/packages/commands/tests/deploy-router.test.ts b/packages/commands/tests/deploy-router.test.ts new file mode 100644 index 00000000..f22f5a65 --- /dev/null +++ b/packages/commands/tests/deploy-router.test.ts @@ -0,0 +1,791 @@ +import { withCommandOutput } from "./output/command-context.ts"; +import { httpTransport } from "bailian-cli-core"; +import { + BailianError, + ExitCode, + type AnyCommand, + type Client, + type Settings, +} from "bailian-cli-core"; +import { afterEach, beforeEach, describe, expect, test, vi, type Mock } from "vite-plus/test"; +import deployRouterVersions from "../src/commands/deploy/router-versions.ts"; +import deployRouterCreate from "../src/commands/deploy/router-create.ts"; +import deployRouterList from "../src/commands/deploy/router-list.ts"; +import deployRouterGet from "../src/commands/deploy/router-get.ts"; +import deployRouterUpdate from "../src/commands/deploy/router-update.ts"; +import deployRouterDelete from "../src/commands/deploy/router-delete.ts"; + +const SETTINGS: Settings = { + output: "json", + outputExplicit: true, + timeout: 30, + watermark: true, + verbose: false, + quiet: true, + dryRun: false, + telemetry: false, +}; + +const DEPLOYED_MODEL = "router-test-id"; +const REQUEST_ID = "fc9c0b75-7327-4a86-88e1-a3b7d093da89"; +const VALID_CREATE_FLAGS = { + name: "my-router", + routeVersion: "v1", + strategy: "EFFECT_FIRST" as const, + candidates: "qwen-plus,qwen-turbo", +}; +const VALID_UPDATE_FLAGS = { + deployedModel: DEPLOYED_MODEL, + routeVersion: "v1", + strategy: "COST_FIRST" as const, + candidates: "qwen-plus,qwen-turbo", +}; + +let stdout = ""; +let stderr = ""; +const mocks: ReturnType[] = []; + +function mockClient(...responses: unknown[]): { + client: Client; + requestJson: Mock; + request: Mock; +} { + const requestJson = vi + .fn() + .mockRejectedValue(new Error("Unexpected request")); + for (const response of responses) { + if (response instanceof Error) requestJson.mockRejectedValueOnce(response); + else requestJson.mockResolvedValueOnce(response); + } + const request = vi.fn().mockRejectedValue(new Error("Unexpected raw request")); + const mock = { client: { requestJson, request } as unknown as Client, requestJson, request }; + mocks.push(mock); + return mock; +} + +type CommandFlags = Parameters>[0]; + +function validate(command: AnyCommand, flags: CommandFlags) { + return command.validate?.(flags); +} + +async function run( + command: AnyCommand, + flags: CommandFlags, + client: Client, + settings: Partial = {}, +) { + const validation = await command.validate?.(flags); + if (validation) + throw new BailianError( + typeof validation === "string" ? validation : validation["en-US"], + ExitCode.USAGE, + ); + const context = withCommandOutput({ + identity: { + binName: "test-cli", + version: "test", + npmPackage: "test-cli", + clientName: "test-cli", + }, + settings: { ...SETTINGS, ...settings }, + flags, + client, + }) as Parameters[0]; + const preparation = await command.prepare?.(context); + if (preparation && context.settings.dryRun) { + context.output.result({ + plan: preparation.preview, + risk: preparation.risk, + notices: preparation.notices.map((notice) => ({ + ...notice, + message: context.localize(notice.message), + })), + }); + return; + } + await command.run({ ...context, prepared: preparation?.data }); +} + +function requests(mock: ReturnType) { + return mock.requestJson.mock.calls.map(([request]) => request); +} + +beforeEach(() => { + vi.useFakeTimers(); + stdout = ""; + stderr = ""; + mocks.length = 0; + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout += String(chunk); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { + stderr += String(chunk); + return true; + }); + vi.spyOn(httpTransport, "fetch").mockImplementation( + vi.fn().mockRejectedValue(new Error("Real network is forbidden")), + ); +}); + +afterEach(() => { + try { + expect(httpTransport.fetch).not.toHaveBeenCalled(); + for (const mock of mocks) expect(mock.request).not.toHaveBeenCalled(); + if (vi.isFakeTimers()) expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + } +}); + +// --------------------------------------------------------------------------- +// 1. Metadata +// --------------------------------------------------------------------------- + +describe("router command metadata", () => { + const ALL_COMMANDS = [ + { name: "versions", command: deployRouterVersions }, + { name: "create", command: deployRouterCreate }, + { name: "list", command: deployRouterList }, + { name: "get", command: deployRouterGet }, + { name: "update", command: deployRouterUpdate }, + { name: "delete", command: deployRouterDelete }, + ]; + + test.each(ALL_COMMANDS)("$name uses auth apiKey and defaultOutput json", ({ command }) => { + expect(command.auth).toBe("apiKey"); + expect(command.defaultOutput).toBe("json"); + }); + + test.each(ALL_COMMANDS)("$name has bilingual descriptions", ({ command }) => { + expect(command.description).toMatchObject({ + "en-US": expect.any(String), + "zh-CN": expect.any(String), + }); + }); + + test("create declares high risk with billing reason", () => { + expect(deployRouterCreate.risk).toMatchObject({ + level: "high", + reason: "billing", + }); + }); + + test("delete declares high risk with destructive reason", () => { + expect(deployRouterDelete.risk).toMatchObject({ + level: "high", + reason: "destructive", + }); + }); + + test.each([ + { name: "versions", command: deployRouterVersions }, + { name: "list", command: deployRouterList }, + { name: "get", command: deployRouterGet }, + { name: "update", command: deployRouterUpdate }, + ])("$name has no risk declaration", ({ command }) => { + expect(command.risk).toBeUndefined(); + }); + + test.each(ALL_COMMANDS)( + "$name does not declare a --yes flag (runtime injects it)", + ({ command }) => { + expect(command.flags).not.toHaveProperty("yes"); + }, + ); +}); + +// --------------------------------------------------------------------------- +// 2. Validation +// --------------------------------------------------------------------------- + +describe("router validation", () => { + describe("validateRouterName", () => { + test("accepts a valid name", async () => { + expect(await validate(deployRouterCreate, VALID_CREATE_FLAGS)).toBeUndefined(); + }); + + test("rejects empty name", async () => { + expect(await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, name: "" })).toMatch( + /--name/, + ); + }); + + test("rejects name longer than 64 characters", async () => { + const longName = "a".repeat(65); + expect(await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, name: longName })).toMatch( + /--name/, + ); + }); + + test("rejects name with underscore", async () => { + expect( + await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, name: "my_router" }), + ).toMatch(/--name/); + }); + + test("rejects name with space", async () => { + expect( + await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, name: "my router" }), + ).toMatch(/--name/); + }); + }); + + describe("validateRouterConfig", () => { + test("rejects empty --route-version", async () => { + expect( + await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, routeVersion: " " }), + ).toMatch(/--route-version/); + }); + + test.each(["qwen-plus, ", "qwen-plus,,qwen-turbo", " ", ""])( + "rejects empty candidate in %j", + async (candidates) => { + expect(await validate(deployRouterCreate, { ...VALID_CREATE_FLAGS, candidates })).toMatch( + /--candidates/, + ); + }, + ); + + test("accepts valid config", async () => { + expect(await validate(deployRouterCreate, VALID_CREATE_FLAGS)).toBeUndefined(); + }); + }); + + describe("validateRouterUpdate", () => { + test("requires at least one configuration field", async () => { + expect(await validate(deployRouterUpdate, { deployedModel: DEPLOYED_MODEL })).toMatch( + /--route-version.*--strategy.*--candidates/, + ); + }); + + test.each([ + { routeVersion: "v2" }, + { strategy: "COST_FIRST" as const }, + { candidates: "qwen-plus,qwen-turbo" }, + ])("accepts one provided configuration field: %j", async (update) => { + expect( + await validate(deployRouterUpdate, { deployedModel: DEPLOYED_MODEL, ...update }), + ).toBeUndefined(); + }); + + test("rejects an explicitly empty route version", async () => { + expect( + await validate(deployRouterUpdate, { + deployedModel: DEPLOYED_MODEL, + routeVersion: " ", + }), + ).toMatch(/--route-version/); + }); + + test.each(["", " ", "qwen-plus,", ",qwen-plus", "qwen-plus,,qwen-turbo"])( + "rejects invalid explicit candidates %j", + async (candidates) => { + expect( + await validate(deployRouterUpdate, { deployedModel: DEPLOYED_MODEL, candidates }), + ).toMatch(/--candidates/); + }, + ); + }); + + describe("validateRouterVersionsPagination", () => { + test("rejects page=0", async () => { + expect(await validate(deployRouterVersions, { page: 0 })).toMatch(/--page/); + }); + + test("rejects page-size=0", async () => { + expect(await validate(deployRouterVersions, { pageSize: 0 })).toMatch(/--page-size/); + }); + + test("rejects page-size=1001", async () => { + expect(await validate(deployRouterVersions, { pageSize: 1001 })).toMatch(/--page-size/); + }); + + test("accepts page-size=1000", async () => { + expect(await validate(deployRouterVersions, { pageSize: 1000 })).toBeUndefined(); + }); + }); + + describe("validateRouterListPagination", () => { + test("rejects page-size > 100", async () => { + expect(await validate(deployRouterList, { pageSize: 101 })).toMatch(/--page-size/); + }); + + test("accepts page-size=100", async () => { + expect(await validate(deployRouterList, { pageSize: 100 })).toBeUndefined(); + }); + }); + + describe("validateRouterResource", () => { + test("rejects empty --deployed-model", async () => { + expect(await validate(deployRouterGet, { deployedModel: " " })).toMatch(/--deployed-model/); + }); + + test("accepts valid deployed-model", async () => { + expect(await validate(deployRouterGet, { deployedModel: DEPLOYED_MODEL })).toBeUndefined(); + }); + }); +}); + +// --------------------------------------------------------------------------- +// 3. Dry-run (zero network) +// --------------------------------------------------------------------------- + +describe("router dry-run (zero network)", () => { + test("router-create dry-run outputs action, body with plan=mr and charge_type=post_paid", async () => { + const mock = mockClient(); + await run(deployRouterCreate, VALID_CREATE_FLAGS, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toMatchObject({ + action: "deploy.router.create", + body: { + name: "my-router", + plan: "mr", + charge_type: "post_paid", + routing_config: { + route_model_version: "v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-turbo"], + }, + }, + }); + }); + + test("router-update complete dry-run stays offline and previews the full request", async () => { + const mock = mockClient(); + await run(deployRouterUpdate, VALID_UPDATE_FLAGS, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toEqual({ + plan: { + action: "deploy.router.update", + deployed_model: DEPLOYED_MODEL, + body: { + routing_config: { + route_model_version: "v1", + strategy: "COST_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-turbo"], + }, + }, + }, + risk: null, + notices: [], + }); + }); + + test("router-update partial dry-run only reads and previews the merged request", async () => { + const mock = mockClient({ + data: { + plan: "mr", + status: "RUNNING", + routing_config: { + route_model_version: "v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-turbo"], + offline_model_ids: ["qwen-offline"], + future_field: { enabled: true }, + }, + }, + }); + await run( + deployRouterUpdate, + { deployedModel: DEPLOYED_MODEL, strategy: "COST_FIRST" }, + mock.client, + { dryRun: true }, + ); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET"]); + expect(JSON.parse(stdout)).toMatchObject({ + plan: { + action: "deploy.router.update", + deployed_model: DEPLOYED_MODEL, + body: { + routing_config: { + route_model_version: "v1", + strategy: "COST_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-turbo"], + offline_model_ids: ["qwen-offline"], + future_field: { enabled: true }, + }, + }, + }, + risk: null, + notices: [], + }); + }); + + test("router-delete dry-run outputs action and deployed_model", async () => { + const mock = mockClient(); + await run(deployRouterDelete, { deployedModel: DEPLOYED_MODEL }, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toEqual({ + action: "deploy.router.delete", + deployed_model: DEPLOYED_MODEL, + }); + }); + + test("router-versions dry-run outputs action with pagination defaults", async () => { + const mock = mockClient(); + await run(deployRouterVersions, {}, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toEqual({ + action: "deploy.router.versions", + page: 1, + page_size: 50, + }); + }); + + test("router-list dry-run outputs action with pagination and fixed plan=mr", async () => { + const mock = mockClient(); + await run(deployRouterList, {}, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toEqual({ + action: "deploy.router.list", + page: 1, + page_size: 10, + plan: "mr", + }); + }); + + test("router-get dry-run outputs action and deployed_model", async () => { + const mock = mockClient(); + await run(deployRouterGet, { deployedModel: DEPLOYED_MODEL }, mock.client, { dryRun: true }); + expect(mock.requestJson).not.toHaveBeenCalled(); + const result = JSON.parse(stdout); + expect(result).toEqual({ + action: "deploy.router.get", + deployed_model: DEPLOYED_MODEL, + }); + }); +}); + +// --------------------------------------------------------------------------- +// 4. Runtime behavior +// --------------------------------------------------------------------------- + +describe("router-create runtime", () => { + test("successful create returns server response", async () => { + const response = { + request_id: REQUEST_ID, + output: { deployed_model: DEPLOYED_MODEL, status: "RUNNING" }, + }; + const mock = mockClient(response); + await run(deployRouterCreate, VALID_CREATE_FLAGS, mock.client); + expect(requests(mock)).toHaveLength(1); + expect(JSON.parse(stdout)).toEqual(response); + }); + + test("POST body has fixed plan=mr and charge_type=post_paid", async () => { + const response = { output: { deployed_model: DEPLOYED_MODEL } }; + const mock = mockClient(response); + await run(deployRouterCreate, VALID_CREATE_FLAGS, mock.client); + expect(requests(mock)[0]).toMatchObject({ + method: "POST", + body: { + plan: "mr", + charge_type: "post_paid", + }, + }); + }); + + test("comma-separated candidates are trimmed and deduplicated", async () => { + const response = { output: { deployed_model: DEPLOYED_MODEL } }; + const mock = mockClient(response); + await run( + deployRouterCreate, + { ...VALID_CREATE_FLAGS, candidates: " qwen-plus , qwen-plus,qwen-turbo " }, + mock.client, + ); + const body = requests(mock)[0].body as { + routing_config: { candidate_model_ids: string[] }; + }; + expect(body.routing_config.candidate_model_ids).toEqual(["qwen-plus", "qwen-turbo"]); + }); +}); + +describe("router-get runtime", () => { + test.each(["output", "data"] as const)( + "successful get via %s envelope returns deployment with request_id", + async (envelope) => { + const deployment = { plan: "mr", status: "RUNNING", deployed_model: DEPLOYED_MODEL }; + const response = { request_id: REQUEST_ID, [envelope]: deployment }; + const mock = mockClient(response); + await run(deployRouterGet, { deployedModel: DEPLOYED_MODEL }, mock.client); + expect(requests(mock)).toHaveLength(1); + const result = JSON.parse(stdout); + expect(result).toMatchObject({ plan: "mr", request_id: REQUEST_ID }); + }, + ); + + test("rejects non-mr deployment", async () => { + const response = { request_id: REQUEST_ID, output: { plan: "lora" } }; + const mock = mockClient(response); + await expect( + run(deployRouterGet, { deployedModel: DEPLOYED_MODEL }, mock.client), + ).rejects.toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("not a model router"), + }); + expect(requests(mock)).toHaveLength(1); + }); +}); + +describe("router-update runtime", () => { + test("successful update: GET confirms plan=mr + RUNNING then PUT", async () => { + const getResponse = { + output: { plan: "mr", status: "RUNNING", deployed_model: DEPLOYED_MODEL }, + }; + const putResponse = { request_id: REQUEST_ID, output: { deployed_model: DEPLOYED_MODEL } }; + const mock = mockClient(getResponse, putResponse); + await run(deployRouterUpdate, VALID_UPDATE_FLAGS, mock.client); + expect(requests(mock)).toHaveLength(2); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "PUT"]); + expect(JSON.parse(stdout)).toEqual(putResponse); + }); + + test("rejects non-RUNNING router", async () => { + const getResponse = { output: { plan: "mr", status: "STOPPED" } }; + const mock = mockClient(getResponse); + await expect(run(deployRouterUpdate, VALID_UPDATE_FLAGS, mock.client)).rejects.toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("RUNNING"), + }); + expect(requests(mock)).toHaveLength(1); + }); + + test("rejects non-mr deployment", async () => { + const getResponse = { output: { plan: "lora", status: "RUNNING" } }; + const mock = mockClient(getResponse); + await expect(run(deployRouterUpdate, VALID_UPDATE_FLAGS, mock.client)).rejects.toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("not a model router"), + }); + expect(requests(mock)).toHaveLength(1); + }); + + test.each(["output", "data"] as const)( + "partial update merges the %s envelope and preserves unmodified fields", + async (envelope) => { + const currentConfig = { + route_model_version: "v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-turbo"], + offline_model_ids: ["qwen-offline"], + future_field: { enabled: true }, + }; + const mock = mockClient( + { [envelope]: { plan: "mr", status: "RUNNING", routing_config: currentConfig } }, + { output: { deployed_model: DEPLOYED_MODEL } }, + ); + await run( + deployRouterUpdate, + { deployedModel: DEPLOYED_MODEL, routeVersion: "v2" }, + mock.client, + ); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "PUT"]); + expect(requests(mock)[1].body).toEqual({ + routing_config: { + ...currentConfig, + route_model_version: "v2", + }, + }); + }, + ); + + test("provided candidates replace the full existing list", async () => { + const mock = mockClient( + { + output: { + plan: "mr", + status: "RUNNING", + routing_config: { + route_model_version: "v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["old-a", "old-b"], + }, + }, + }, + { output: { deployed_model: DEPLOYED_MODEL } }, + ); + await run( + deployRouterUpdate, + { deployedModel: DEPLOYED_MODEL, candidates: " new-a, new-a,new-b " }, + mock.client, + ); + expect(requests(mock)[1].body).toMatchObject({ + routing_config: { candidate_model_ids: ["new-a", "new-b"] }, + }); + }); + + test("does not PUT when the current routing config is incomplete", async () => { + const mock = mockClient({ + output: { + plan: "mr", + status: "RUNNING", + routing_config: { strategy: "EFFECT_FIRST", candidate_model_ids: ["a", "b"] }, + }, + }); + await expect( + run( + deployRouterUpdate, + { deployedModel: DEPLOYED_MODEL, strategy: "COST_FIRST" }, + mock.client, + ), + ).rejects.toMatchObject({ + exitCode: ExitCode.GENERAL, + message: expect.stringContaining("routing_config"), + }); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET"]); + }); + + test("GET and PUT failures are propagated as-is without retry", async () => { + const getFailure = new BailianError("GET rejected", ExitCode.GENERAL); + const getMock = mockClient(getFailure); + await expect( + run( + deployRouterUpdate, + { deployedModel: DEPLOYED_MODEL, strategy: "COST_FIRST" }, + getMock.client, + ), + ).rejects.toBe(getFailure); + expect(requests(getMock).map(({ method }) => method)).toEqual(["GET"]); + + const putFailure = new BailianError("PUT rejected", ExitCode.GENERAL); + const putMock = mockClient({ output: { plan: "mr", status: "RUNNING" } }, putFailure); + await expect(run(deployRouterUpdate, VALID_UPDATE_FLAGS, putMock.client)).rejects.toBe( + putFailure, + ); + expect(requests(putMock).map(({ method }) => method)).toEqual(["GET", "PUT"]); + }); +}); + +describe("router-delete runtime", () => { + test("successful delete: GET confirms plan=mr then DELETE", async () => { + const deleteResponse = { output: { deployed_model: DEPLOYED_MODEL, deleted: true } }; + const mock = mockClient({ output: { plan: "mr", status: "STOPPED" } }, deleteResponse); + await run(deployRouterDelete, { deployedModel: DEPLOYED_MODEL }, mock.client); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + expect(JSON.parse(stdout)).toEqual(deleteResponse); + }); + + test("RUNNING state is allowed for model router deletion", async () => { + const deleteResponse = { output: { deployed_model: DEPLOYED_MODEL, deleted: true } }; + const mock = mockClient({ output: { plan: "mr", status: "RUNNING" } }, deleteResponse); + await run(deployRouterDelete, { deployedModel: DEPLOYED_MODEL }, mock.client); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + expect(JSON.parse(stdout)).toEqual(deleteResponse); + }); + + test("rejects non-mr deployment", async () => { + const mock = mockClient({ output: { plan: "ptu" } }); + await expect( + run(deployRouterDelete, { deployedModel: DEPLOYED_MODEL }, mock.client), + ).rejects.toMatchObject({ + exitCode: ExitCode.USAGE, + message: expect.stringContaining("not a model router"), + }); + expect(requests(mock)).toHaveLength(1); + }); + + test("server error on DELETE is propagated as-is", async () => { + const failure = new BailianError("Server rejection", ExitCode.GENERAL); + const mock = mockClient({ output: { plan: "mr", status: "RUNNING" } }, failure); + await expect( + run(deployRouterDelete, { deployedModel: DEPLOYED_MODEL }, mock.client), + ).rejects.toBe(failure); + expect(requests(mock).map(({ method }) => method)).toEqual(["GET", "DELETE"]); + }); +}); + +describe("router-list runtime", () => { + test("passes plan=mr as query parameter with default pagination", async () => { + const response = { + request_id: REQUEST_ID, + output: { + deployments: [{ deployed_model: DEPLOYED_MODEL }], + total: 1, + page_no: 1, + page_size: 10, + }, + }; + const mock = mockClient(response); + await run(deployRouterList, {}, mock.client); + expect(requests(mock)).toHaveLength(1); + expect(requests(mock)[0]).toMatchObject({ + method: "GET", + }); + const result = JSON.parse(stdout); + expect(result).toMatchObject({ + items: [{ deployed_model: DEPLOYED_MODEL }], + total: 1, + page_no: 1, + page_size: 10, + request_id: REQUEST_ID, + }); + }); + + test("custom pagination is forwarded", async () => { + const response = { + request_id: REQUEST_ID, + output: { deployments: [], total: 0, page_no: 3, page_size: 20 }, + }; + const mock = mockClient(response); + await run(deployRouterList, { page: 3, pageSize: 20 }, mock.client); + expect(requests(mock)).toHaveLength(1); + const result = JSON.parse(stdout); + expect(result.page_no).toBe(3); + expect(result.page_size).toBe(20); + }); +}); + +describe("router-versions runtime", () => { + test("default pagination is page=1, pageSize=50", async () => { + const response = { + request_id: REQUEST_ID, + output: { + route_model_versions: [{ version: "v1" }], + total: 1, + total_page: 1, + page_no: 1, + page_size: 50, + }, + }; + const mock = mockClient(response); + await run(deployRouterVersions, {}, mock.client); + expect(requests(mock)).toHaveLength(1); + const result = JSON.parse(stdout); + expect(result).toMatchObject({ + items: [{ version: "v1" }], + total: 1, + total_page: 1, + page_no: 1, + page_size: 50, + request_id: REQUEST_ID, + }); + }); + + test("custom pagination is forwarded to API", async () => { + const response = { + request_id: REQUEST_ID, + output: { + route_model_versions: [], + total: 0, + total_page: 0, + page_no: 2, + page_size: 100, + }, + }; + const mock = mockClient(response); + await run(deployRouterVersions, { page: 2, pageSize: 100 }, mock.client); + expect(requests(mock)).toHaveLength(1); + const result = JSON.parse(stdout); + expect(result.page_no).toBe(2); + expect(result.page_size).toBe(100); + }); +}); diff --git a/packages/commands/tests/e2e/deploy.e2e.test.ts b/packages/commands/tests/e2e/deploy.e2e.test.ts index a4a4cd11..1836d964 100644 --- a/packages/commands/tests/e2e/deploy.e2e.test.ts +++ b/packages/commands/tests/e2e/deploy.e2e.test.ts @@ -1,3 +1,5 @@ +import { createServer, type RequestListener } from "node:http"; +import type { Socket } from "node:net"; import { fileURLToPath } from "node:url"; import { httpTransport } from "bailian-cli-core"; import { describe, expect, test, vi } from "vite-plus/test"; @@ -8,7 +10,7 @@ import { runCommandE2e, runCommandInProcess, } from "./helpers.ts"; -import { DEPLOY_ROUTES } from "./topic-routes.ts"; +import { DEPLOY_ROUTES, DEPLOY_ROUTER_ROUTES } from "./topic-routes.ts"; // No files are created: isolate user config and block fetch in the child process, // including the runtime's background npm version check. Never load an env file. @@ -76,6 +78,88 @@ function runReadOnlyDeploy(args: string[]) { ]); } +async function runOfflineRouter(args: string[]) { + const transportFetch = vi + .spyOn(httpTransport, "fetch") + .mockRejectedValue(new Error("Network disabled for deploy router E2E")); + const nativeFetch = vi + .spyOn(globalThis, "fetch") + .mockRejectedValue(new Error("Network disabled for deploy router E2E")); + try { + const result = await runCommandInProcess(DEPLOY_ROUTER_ROUTES, args, IN_PROCESS_ENV); + expect(transportFetch).not.toHaveBeenCalled(); + expect(nativeFetch).not.toHaveBeenCalled(); + return result; + } finally { + transportFetch.mockRestore(); + nativeFetch.mockRestore(); + } +} + +function runReadOnlyRouter(args: string[]) { + return runOfflineRouter([ + "deploy", + "router", + ...args, + "--api-key", + "e2e-dummy-key", + "--dry-run", + "--output", + "json", + "--quiet", + ]); +} + +interface RouterRequest { + method: string | undefined; + url: string | undefined; + authorization: string | undefined; + body: string; +} + +async function withRouterServer( + handler: RequestListener, + run: (url: string, requests: RouterRequest[]) => Promise, +): Promise { + const requests: RouterRequest[] = []; + const sockets = new Set(); + const server = createServer((incoming, response) => { + const request: RouterRequest = { + method: incoming.method, + url: incoming.url, + authorization: incoming.headers.authorization, + body: "", + }; + requests.push(request); + incoming.setEncoding("utf8"); + incoming.on("data", (chunk: string) => { + request.body += chunk; + }); + incoming.once("end", () => handler(incoming, response)); + }); + server.on("connection", (socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + }); + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected a local TCP server"); + await run(`http://127.0.0.1:${address.port}`, requests); + } finally { + const closed = server.listening + ? new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }) + : Promise.resolve(); + for (const socket of sockets) socket.destroy(); + await closed; + } +} + test.each([ { label: "read-only query preview", @@ -630,6 +714,16 @@ describe("e2e: deploy capacity writes (offline, no credentials)", () => { flags: ["--deployed-model", "--instance-id", "--duration", "--auto-renewal", "--is-change"], note: "prepaid", }, + { + path: ["capacity", "auto-renew", "enable"], + flags: ["--deployed-model", "--instance-id", "--cycle", "--auto-renewal-duration"], + note: "prepaid", + }, + { + path: ["capacity", "auto-renew", "disable"], + flags: ["--deployed-model", "--instance-id", "--cycle", "--auto-renewal-duration"], + note: "prepaid", + }, { path: ["capacity", "delete"], flags: ["--deployed-model", "--instance-id", "--reason"], @@ -729,6 +823,50 @@ describe("e2e: deploy capacity writes (offline, no credentials)", () => { wait: false, }, }, + { + path: ["capacity", "auto-renew", "enable"], + args: [ + "--deployed-model", + "dep-test", + "--instance-id", + "instance-test", + "--cycle", + "Day", + "--auto-renewal-duration", + "30", + ], + expected: { + action: "deploy.capacity.auto-renew.enable", + deployed_model: "dep-test", + instance_id: "instance-test", + body: { auto_renewal: true, auto_renewal_cycle: "Day", auto_renewal_duration: 30 }, + client_request_id: "", + precheck: "can_enable_auto_renew", + wait: false, + }, + }, + { + path: ["capacity", "auto-renew", "disable"], + args: [ + "--deployed-model", + "dep-test", + "--instance-id", + "instance-test", + "--cycle", + "Day", + "--auto-renewal-duration", + "30", + ], + expected: { + action: "deploy.capacity.auto-renew.disable", + deployed_model: "dep-test", + instance_id: "instance-test", + body: { auto_renewal: false, auto_renewal_cycle: "Day", auto_renewal_duration: 30 }, + client_request_id: "", + precheck: "can_disable_auto_renew", + wait: false, + }, + }, { path: ["capacity", "delete"], args: [ @@ -787,6 +925,13 @@ describe("e2e: deploy capacity writes (offline, no credentials)", () => { args: ["--deployed-model", "dep-test", "--instance-id", "instance-test"], missing: "--duration", }, + { path: ["capacity", "auto-renew", "enable"], args: [], missing: "--deployed-model" }, + { + path: ["capacity", "auto-renew", "enable"], + args: ["--deployed-model", "dep-test", "--instance-id", "instance-test"], + missing: "--cycle", + }, + { path: ["capacity", "auto-renew", "disable"], args: [], missing: "--deployed-model" }, { path: ["capacity", "delete"], args: [], missing: "--deployed-model" }, { path: ["capacity", "delete"], @@ -838,6 +983,62 @@ describe("e2e: deploy capacity writes (offline, no credentials)", () => { expect(stderr).toMatch(/POST_PAY/); }); + test("capacity create previews the exact 8-hour off-peak purchase during dry-run", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyDeploy([ + "capacity", + "create", + "--deployed-model", + "dep-test", + "--billing-method", + "PRE_PAY", + "--pricing-cycle", + "Hour", + "--duration", + "8", + "--auto-renewal", + "false", + "--input-tpm", + "10000", + "--output-tpm", + "1000", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toEqual({ + action: "deploy.capacity.create", + deployed_model: "dep-test", + body: { + billing_method: "PRE_PAY", + ptu_capacity: { input_tpm: 10000, output_tpm: 1000 }, + pre_paid_info: { pricing_cycle: "Hour", duration: 8, auto_renewal: false }, + }, + client_request_id: "", + wait: false, + }); + expect(stderr).not.toContain("Network disabled"); + }); + + test("capacity create rejects Hour off-peak violations during dry-run", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyDeploy([ + "capacity", + "create", + "--deployed-model", + "dep-test", + "--billing-method", + "PRE_PAY", + "--pricing-cycle", + "Hour", + "--duration", + "30", + "--input-tpm", + "10000", + "--output-tpm", + "1000", + ]); + expect(exitCode, stderr).toBe(2); + expect(stdout.trim()).toBe(""); + expect(stderr).toMatch(/Hour/); + }); + test("capacity scale rejects --interval without --wait during dry-run", async () => { const { stdout, stderr, exitCode } = await runReadOnlyDeploy([ "capacity", @@ -921,6 +1122,431 @@ describe("e2e: deploy capacity writes (offline, no credentials)", () => { }); }); +describe("e2e: deploy router help (offline, no credentials)", () => { + test.each([ + { path: ["versions"], flags: ["--page", "--page-size"], note: "model-routing" }, + { + path: ["create"], + flags: ["--name", "--route-version", "--strategy", "--candidates"], + note: "postpaid", + }, + { path: ["list"], flags: ["--page", "--page-size"], note: "model router" }, + { path: ["get"], flags: ["--deployed-model"], note: "model router" }, + { + path: ["update"], + flags: ["--deployed-model", "--route-version", "--strategy", "--candidates"], + note: "replace", + }, + { path: ["delete"], flags: ["--deployed-model"], note: "Delete" }, + ])("deploy router $path --help exposes flags and semantics", async ({ path, flags, note }) => { + const { stdout, stderr, exitCode } = await runCommandHelp(DEPLOY_ROUTER_ROUTES, [ + "deploy", + "router", + ...path, + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stdout).toBe(""); + for (const flag of flags) expect(stderr).toContain(flag); + expect(stderr.toLowerCase()).toContain(note.toLowerCase()); + expect(stderr).toContain("--api-key"); + }); + + test("deploy router create --help shows --yes (high-risk billing)", async () => { + const { stderr, exitCode } = await runCommandHelp(DEPLOY_ROUTER_ROUTES, [ + "deploy", + "router", + "create", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toContain("--yes"); + }); + + test("deploy router delete --help shows --yes (high-risk destructive)", async () => { + const { stderr, exitCode } = await runCommandHelp(DEPLOY_ROUTER_ROUTES, [ + "deploy", + "router", + "delete", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toContain("--yes"); + }); + + test("deploy router update --help does NOT show --yes (no risk)", async () => { + const { stderr, exitCode } = await runCommandHelp(DEPLOY_ROUTER_ROUTES, [ + "deploy", + "router", + "update", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).not.toContain("--yes"); + }); +}); + +describe("e2e: deploy router dry-run (offline, no credentials)", () => { + test("router create --dry-run previews with fixed plan=mr and charge_type=post_paid", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + "create", + "--name", + "test-router", + "--route-version", + "v1", + "--strategy", + "EFFECT_FIRST", + "--candidates", + "qwen-plus,qwen-turbo", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + body: { + name: string; + plan: string; + charge_type: string; + routing_config: { candidate_model_ids: string[] }; + }; + }>(stdout); + expect(data.action).toBe("deploy.router.create"); + expect(data.body.plan).toBe("mr"); + expect(data.body.charge_type).toBe("post_paid"); + expect(data.body.name).toBe("test-router"); + expect(data.body.routing_config.candidate_model_ids).toEqual(["qwen-plus", "qwen-turbo"]); + }); + + test("router update --dry-run previews complete routing_config", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + "update", + "--deployed-model", + "router-test", + "--route-version", + "v2", + "--strategy", + "COST_FIRST", + "--candidates", + "qwen-max", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + plan: { + action: string; + deployed_model: string; + body: { routing_config: { route_model_version: string; strategy: string } }; + }; + risk: null; + notices: unknown[]; + }>(stdout); + expect(data.plan.action).toBe("deploy.router.update"); + expect(data.plan.deployed_model).toBe("router-test"); + expect(data.plan.body.routing_config.route_model_version).toBe("v2"); + expect(data.plan.body.routing_config.strategy).toBe("COST_FIRST"); + expect(data.risk).toBeNull(); + expect(data.notices).toEqual([]); + }); + + test("router delete --dry-run sends zero requests", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + "delete", + "--deployed-model", + "router-test", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toEqual({ + action: "deploy.router.delete", + deployed_model: "router-test", + }); + }); + + test("router versions --dry-run previews with default pagination", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter(["versions"]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; page: number; page_size: number }>(stdout); + expect(data.action).toBe("deploy.router.versions"); + expect(data.page).toBe(1); + expect(data.page_size).toBe(50); + }); + + test("router list --dry-run previews with fixed plan=mr", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter(["list"]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; plan: string }>(stdout); + expect(data.action).toBe("deploy.router.list"); + expect(data.plan).toBe("mr"); + }); + + test("router get --dry-run previews the deployed-model", async () => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + "get", + "--deployed-model", + "router-test", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toEqual({ + action: "deploy.router.get", + deployed_model: "router-test", + }); + }); +}); + +test("router partial update uses the real Client for GET-only preview and GET then PUT execution", async () => { + const currentConfig = { + route_model_version: "v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["old-a", "old-b"], + offline_model_ids: ["offline-a"], + future_field: { enabled: true }, + }; + await withRouterServer( + (incoming, response) => { + if (incoming.method === "GET" && incoming.url === "/api/v1/deployments/router%2Flocal") { + response.writeHead(200, { "content-type": "application/json" }).end( + JSON.stringify({ + request_id: "request-get", + output: { plan: "mr", status: "RUNNING", routing_config: currentConfig }, + }), + ); + return; + } + if ( + incoming.method === "PUT" && + incoming.url === "/api/v1/deployments/router%2Flocal/update" + ) { + response + .writeHead(200, { "content-type": "application/json" }) + .end(JSON.stringify({ request_id: "request-put", output: { updated: true } })); + return; + } + response.writeHead(404).end(); + }, + async (baseUrl, requests) => { + const commonArgs = [ + "deploy", + "router", + "update", + "--deployed-model", + "router/local", + "--api-key", + "e2e-dummy-key", + "--base-url", + baseUrl, + "--output", + "json", + "--quiet", + ]; + const preview = await runCommandInProcess( + DEPLOY_ROUTER_ROUTES, + [...commonArgs, "--strategy", "COST_FIRST", "--dry-run"], + IN_PROCESS_ENV, + ); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(requests.map(({ method }) => method)).toEqual(["GET"]); + expect( + parseStdoutJson<{ + plan: { body: { routing_config: Record } }; + }>(preview.stdout).plan.body.routing_config, + ).toEqual({ + ...currentConfig, + strategy: "COST_FIRST", + }); + + const update = await runCommandInProcess( + DEPLOY_ROUTER_ROUTES, + [...commonArgs, "--candidates", "new-a,new-b"], + IN_PROCESS_ENV, + ); + expect(update.exitCode, update.stderr).toBe(0); + expect(parseStdoutJson(update.stdout)).toEqual({ + request_id: "request-put", + output: { updated: true }, + }); + expect(requests.map(({ method }) => method)).toEqual(["GET", "GET", "PUT"]); + expect(requests.map(({ url }) => url)).toEqual([ + "/api/v1/deployments/router%2Flocal", + "/api/v1/deployments/router%2Flocal", + "/api/v1/deployments/router%2Flocal/update", + ]); + expect(requests.every(({ authorization }) => authorization === "Bearer e2e-dummy-key")).toBe( + true, + ); + expect(JSON.parse(requests[2].body)).toEqual({ + routing_config: { + ...currentConfig, + candidate_model_ids: ["new-a", "new-b"], + }, + }); + }, + ); +}); + +describe.each([ + { command: "create", resourceArgs: ["--name", "test-router"] }, + { command: "update", resourceArgs: ["--deployed-model", "router-test"] }, +])("e2e: router $command candidate lists (offline)", ({ command, resourceArgs }) => { + test.each([ + { candidates: "qwen-plus", expected: ["qwen-plus"] }, + { candidates: "qwen-plus,qwen-turbo", expected: ["qwen-plus", "qwen-turbo"] }, + { candidates: " qwen-plus , qwen-turbo ", expected: ["qwen-plus", "qwen-turbo"] }, + { candidates: "qwen-plus,qwen-plus,qwen-turbo", expected: ["qwen-plus", "qwen-turbo"] }, + ])("parses --candidates $candidates", async ({ candidates, expected }) => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + command, + ...resourceArgs, + "--route-version", + "v1", + "--strategy", + "EFFECT_FIRST", + "--candidates", + candidates, + ]); + expect(exitCode, stderr).toBe(0); + const result = parseStdoutJson<{ + body?: { routing_config: { candidate_model_ids: string[] } }; + plan?: { body: { routing_config: { candidate_model_ids: string[] } } }; + }>(stdout); + expect((result.body ?? result.plan?.body)?.routing_config.candidate_model_ids).toEqual( + expected, + ); + }); + + test.each(["", " ", ",qwen-plus", "qwen-plus,", "qwen-plus,,qwen-turbo"])( + "rejects empty entries in --candidates %j", + async (candidates) => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([ + command, + ...resourceArgs, + "--route-version", + "v1", + "--strategy", + "EFFECT_FIRST", + "--candidates", + candidates, + ]); + expect(exitCode, stderr).toBe(2); + expect(stdout.trim()).toBe(""); + expect(stderr).toContain("--candidates"); + }, + ); +}); + +test("router CSV dry-run matches the network-blocked subprocess", async () => { + const args = [ + "deploy", + "router", + "create", + "--name", + "test-router", + "--route-version", + "v1", + "--strategy", + "EFFECT_FIRST", + "--candidates", + " qwen-plus ,qwen-turbo,qwen-plus ", + "--api-key", + "e2e-dummy-key", + "--dry-run", + "--output", + "json", + "--quiet", + ]; + const inProcess = await runOfflineRouter(args); + const subprocess = await runCommandE2e(DEPLOY_ROUTER_ROUTES, args, { + ...IN_PROCESS_ENV, + NODE_OPTIONS: READ_ONLY_ENV.NODE_OPTIONS, + }); + expect(subprocess.exitCode, subprocess.stderr).toBe(0); + expect(inProcess).toEqual(subprocess); +}); + +describe("e2e: deploy router missing required flags (offline)", () => { + test.each([ + { + path: ["create"], + args: ["--route-version", "v1", "--strategy", "EFFECT_FIRST", "--candidates", "qwen"], + missing: "--name", + }, + { + path: ["create"], + args: ["--name", "r", "--strategy", "EFFECT_FIRST", "--candidates", "qwen"], + missing: "--route-version", + }, + { + path: ["create"], + args: ["--name", "r", "--route-version", "v1", "--candidates", "qwen"], + missing: "--strategy", + }, + { + path: ["create"], + args: ["--name", "r", "--route-version", "v1", "--strategy", "EFFECT_FIRST"], + missing: "--candidates", + }, + { + path: ["update"], + args: ["--route-version", "v1", "--strategy", "COST_FIRST", "--candidates", "qwen"], + missing: "--deployed-model", + }, + { + path: ["update"], + args: ["--deployed-model", "router-test"], + missing: "--route-version", + }, + { path: ["delete"], args: [], missing: "--deployed-model" }, + { path: ["get"], args: [], missing: "--deployed-model" }, + ])("deploy router $path requires $missing", async ({ path, args, missing }) => { + const { stdout, stderr, exitCode } = await runReadOnlyRouter([...path, ...args]); + expect(exitCode, stderr).toBe(2); + expect(stdout.trim()).toBe(""); + expect(stderr).toContain(missing); + }); +}); + +describe("e2e: deploy router high-risk confirmation", () => { + test("router create without --yes requires confirmation (7)", async () => { + const { stdout, stderr, exitCode } = await runOfflineRouter([ + "deploy", + "router", + "create", + "--name", + "test-router", + "--route-version", + "v1", + "--strategy", + "EFFECT_FIRST", + "--candidates", + "qwen-plus", + "--api-key", + "e2e-dummy-key", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(7); + expect(stdout.trim()).toBe(""); + expect(JSON.parse(stderr)).toMatchObject({ + error: { code: 7, type: "requires_confirmation" }, + }); + }); + + test("router delete without --yes requires confirmation (7)", async () => { + const { stdout, stderr, exitCode } = await runOfflineRouter([ + "deploy", + "router", + "delete", + "--deployed-model", + "router-test", + "--api-key", + "e2e-dummy-key", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(7); + expect(stdout.trim()).toBe(""); + expect(JSON.parse(stderr)).toMatchObject({ + error: { code: 7, type: "requires_confirmation" }, + }); + }); +}); + describe.skipIf(!isDashScopeE2EReady())("e2e: deploy (DashScope)", () => { /** * 不同开发者的 key 状态不一:可能鉴权失败、可能账号下没有任何部署记录、 diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index d7ce3a3e..fb02e049 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -296,6 +296,8 @@ export const DEPLOY_ROUTES: E2eRouteExports = { "deploy capacity create": "deployCapacityCreate", "deploy capacity scale": "deployCapacityScale", "deploy capacity renew": "deployCapacityRenew", + "deploy capacity auto-renew enable": "deployCapacityAutoRenewEnable", + "deploy capacity auto-renew disable": "deployCapacityAutoRenewDisable", "deploy capacity delete": "deployCapacityDelete", "deploy capacity unsubscribe": "deployCapacityUnsubscribe", "deploy overflow": "deployOverflow", @@ -307,6 +309,15 @@ export const DEPLOY_ROUTES: E2eRouteExports = { "deploy delete": "deployDelete", }; +export const DEPLOY_ROUTER_ROUTES: E2eRouteExports = { + "deploy router versions": "deployRouterVersions", + "deploy router create": "deployRouterCreate", + "deploy router list": "deployRouterList", + "deploy router get": "deployRouterGet", + "deploy router update": "deployRouterUpdate", + "deploy router delete": "deployRouterDelete", +}; + export const DATASET_ROUTES: E2eRouteExports = { "dataset upload": "datasetUpload", "dataset list": "datasetList", diff --git a/packages/core/package.json b/packages/core/package.json index b95e45fe..205c9419 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.10.4", + "version": "2.10.5", "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/core/src/client/endpoints.ts b/packages/core/src/client/endpoints.ts index aa684611..e3f9f3c2 100644 --- a/packages/core/src/client/endpoints.ts +++ b/packages/core/src/client/endpoints.ts @@ -417,6 +417,11 @@ export function deploymentCapacityInstanceRenewPath(code: string, id: string): s return `${deploymentCapacityInstancePath(code, id)}/renew`; } +/** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/auto-renew */ +export function deploymentCapacityInstanceAutoRenewPath(code: string, id: string): string { + return `${deploymentCapacityInstancePath(code, id)}/auto-renew`; +} + /** PUT /api/v1/deployments/{deployed_model}/update-overflowstrategy */ export function deploymentOverflowPath(code: string): string { return `${deploymentPath(code)}/update-overflowstrategy`; @@ -445,6 +450,11 @@ export function deploymentsModelsPath(): string { return "/api/v1/deployments/models"; } +/** GET /api/v1/deployments/model-routing/versions — model-routing version catalog. */ +export function modelRoutingVersionsPath(): string { + return "/api/v1/deployments/model-routing/versions"; +} + // ---- RAG admin plane (knowledge base / data center / service management, workspace-based host) ---- // All admin endpoints go through this factory; path constants are centralized in // RAG_PATHS to avoid per-endpoint boilerplate. diff --git a/packages/core/src/deploy/api.ts b/packages/core/src/deploy/api.ts index 21d5443f..a1ed99d4 100644 --- a/packages/core/src/deploy/api.ts +++ b/packages/core/src/deploy/api.ts @@ -15,19 +15,24 @@ import { deploymentCapacityOperationPath, deploymentCapacityInstanceScalePath, deploymentCapacityInstanceRenewPath, + deploymentCapacityInstanceAutoRenewPath, deploymentOverflowPath, + modelRoutingVersionsPath, } from "../client/endpoints.ts"; import type { Client } from "../client/client.ts"; import type { CreateDeploymentRequest, + CreateModelRouterRequest, CreateDeploymentResponse, ListDeploymentsResponse, + ListModelRoutingVersionsResponse, GetDeploymentResponse, DeleteDeploymentResponse, ListDeployableModelsResponse, ScaleDeploymentRequest, ScaleDeploymentResponse, UpdateDeploymentRequest, + UpdateModelRouterRequest, UpdateDeploymentResponse, ListCapacityInstancesResponse, GetCapacityInstanceResponse, @@ -35,6 +40,7 @@ import type { CreateCapacityInstanceRequest, ScaleCapacityInstanceRequest, RenewCapacityInstanceRequest, + UpdateCapacityAutoRenewRequest, CapacityOperationResponse, UpdateDeploymentOverflowResponse, } from "./types.ts"; @@ -54,7 +60,7 @@ function capacityWriteHeaders(requestId?: string): Record | unde /** POST /api/v1/deployments; initial ModelCode creation has no instance-idempotency guarantee. */ export async function createDeployment( client: Client, - body: CreateDeploymentRequest, + body: CreateDeploymentRequest | CreateModelRouterRequest, signal?: AbortSignal, ): Promise { return client.requestJson({ @@ -72,6 +78,29 @@ export interface ListDeploymentsParams { signal?: AbortSignal; } +export interface ListModelRoutingVersionsParams { + pageNo?: number; + pageSize?: number; + signal?: AbortSignal; +} + +/** GET /api/v1/deployments/model-routing/versions */ +export async function listModelRoutingVersions( + client: Client, + params: ListModelRoutingVersionsParams = {}, +): Promise { + const query = new URLSearchParams(); + if (params.pageNo !== undefined) query.set("page_no", String(params.pageNo)); + if (params.pageSize !== undefined) query.set("page_size", String(params.pageSize)); + const base = modelRoutingVersionsPath(); + const path = query.toString() ? `${base}?${query.toString()}` : base; + return client.requestJson({ + path, + method: "GET", + signal: params.signal, + }); +} + /** GET /api/v1/deployments */ export async function listDeployments( client: Client, @@ -216,6 +245,23 @@ export async function renewCapacityInstance( }); } +/** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/auto-renew */ +export async function updateCapacityInstanceAutoRenew( + client: Client, + code: string, + id: string, + body: UpdateCapacityAutoRenewRequest, + options: CapacityWriteOptions = {}, +): Promise { + return client.requestJson({ + path: deploymentCapacityInstanceAutoRenewPath(code, id), + method: "PUT", + body, + headers: capacityWriteHeaders(options.requestId), + signal: options.signal, + }); +} + /** DELETE /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}; no JSON body. */ export async function deleteCapacityInstance( client: Client, @@ -316,7 +362,7 @@ export async function scaleDeployment( export async function updateDeployment( client: Client, deployedModel: string, - body: UpdateDeploymentRequest, + body: UpdateDeploymentRequest | UpdateModelRouterRequest, signal?: AbortSignal, ): Promise { return client.requestJson({ diff --git a/packages/core/src/deploy/index.ts b/packages/core/src/deploy/index.ts index 63486242..f023af32 100644 --- a/packages/core/src/deploy/index.ts +++ b/packages/core/src/deploy/index.ts @@ -11,5 +11,7 @@ export { deploymentCapacityOperationPath, deploymentCapacityInstanceScalePath, deploymentCapacityInstanceRenewPath, + deploymentCapacityInstanceAutoRenewPath, deploymentOverflowPath, + modelRoutingVersionsPath, } from "../client/endpoints.ts"; diff --git a/packages/core/src/deploy/plans.ts b/packages/core/src/deploy/plans.ts index afce76bf..f219435a 100644 --- a/packages/core/src/deploy/plans.ts +++ b/packages/core/src/deploy/plans.ts @@ -100,9 +100,6 @@ const ptuStrategy: PlanStrategy = { ) { return "--capacity, --deploy-spec and --billing-method are not supported for plan=ptu; use reservation capacity and --charge-type.\nplan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。"; } - if (flags.thinkingOutputTpm !== undefined) { - return "--thinking-output-tpm is not supported by current reservation models.\n当前吞吐预留模型不支持 --thinking-output-tpm。"; - } if (flags.chargeType !== CHARGE_TYPE.PRE_PAID && flags.chargeType !== CHARGE_TYPE.POST_PAID) { return "--charge-type is required for plan=ptu and must be pre_paid or post_paid.\nplan=ptu 必须提供 --charge-type,且只能为 pre_paid 或 post_paid。"; } @@ -116,6 +113,9 @@ const ptuStrategy: PlanStrategy = { if (flags.serviceTier === "ptu_default" && flags.chargeType === CHARGE_TYPE.POST_PAID) { return "ptu_default only supports pre_paid.\nptu_default 仅支持 pre_paid。"; } + if (flags.pricingCycle === "Hour" && flags.serviceTier !== "ptu_default") { + return "--pricing-cycle Hour requires --service-tier ptu_default; without it the service assumes the fast tier and rejects the request.\n--pricing-cycle Hour 必须显式指定 --service-tier ptu_default;否则服务按默认高速档处理并拒绝请求。"; + } if (flags.chargeType === CHARGE_TYPE.POST_PAID && hasPrepaidFlags(flags)) { return "Prepaid flags are not allowed with --charge-type post_paid.\n--charge-type post_paid 不允许提供预付费参数。"; } diff --git a/packages/core/src/deploy/reservation.ts b/packages/core/src/deploy/reservation.ts index c4b5b58c..2b24c57a 100644 --- a/packages/core/src/deploy/reservation.ts +++ b/packages/core/src/deploy/reservation.ts @@ -4,6 +4,10 @@ import type { PrePaidInfo, ReservationCapacity } from "./types.ts"; export interface ReservationFlags { inputTpm?: number; outputTpm?: number; + /** Thinking-output capacity; only some models support it, validated server-side. */ + thinkingOutputTpm?: number; + /** Day (default) | Hour; Hour is the 8-hour off-peak window. */ + pricingCycle?: string; duration?: number; autoRenewal?: boolean; autoRenewalDuration?: number; @@ -33,11 +37,13 @@ export function buildReservationCapacity(flags: ReservationFlags): ReservationCa const capacity: ReservationCapacity = {}; if (flags.inputTpm !== undefined) capacity.input_tpm = flags.inputTpm; if (flags.outputTpm !== undefined) capacity.output_tpm = flags.outputTpm; + if (flags.thinkingOutputTpm !== undefined) capacity.thinking_output_tpm = flags.thinkingOutputTpm; return capacity; } export function hasPrepaidFlags(flags: ReservationFlags): boolean { return ( + flags.pricingCycle !== undefined || flags.duration !== undefined || flags.autoRenewal !== undefined || flags.autoRenewalDuration !== undefined || @@ -45,12 +51,42 @@ export function hasPrepaidFlags(flags: ReservationFlags): boolean { ); } +/** + * The 8-hour off-peak window: prepaid ptu_default only, exactly 8 hours per + * purchase, never auto-renewed. Selling windows (22:00–24:00) stay server-side. + */ +function validateHourCycle(flags: ReservationFlags): string | undefined { + if (flags.pricingCycle !== "Hour") return undefined; + if (flags.duration !== 8) { + return "--pricing-cycle Hour requires --duration 8.\n--pricing-cycle Hour 要求 --duration 为 8。"; + } + if (flags.autoRenewal !== false) { + return "--pricing-cycle Hour requires --auto-renewal false.\n--pricing-cycle Hour 要求 --auto-renewal 为 false。"; + } + if (flags.autoRenewalDuration !== undefined) { + return "--pricing-cycle Hour does not accept --auto-renewal-duration.\n--pricing-cycle Hour 不接受 --auto-renewal-duration。"; + } + if (flags.autoRenewalCycle !== undefined) { + return "--pricing-cycle Hour does not accept --auto-renewal-cycle.\n--pricing-cycle Hour 不接受 --auto-renewal-cycle。"; + } + return undefined; +} + /** Validate a complete prepaid block whenever any prepaid field is supplied. */ export function validatePrepaidFlags( flags: ReservationFlags, required: boolean, ): string | undefined { if (!required && !hasPrepaidFlags(flags)) return undefined; + if ( + flags.pricingCycle !== undefined && + flags.pricingCycle !== "Day" && + flags.pricingCycle !== "Hour" + ) { + return "--pricing-cycle must be Day or Hour (case-sensitive).\n--pricing-cycle 只能为 Day 或 Hour(区分大小写)。"; + } + const hourError = validateHourCycle(flags); + if (hourError) return hourError; if ( flags.duration === undefined || !Number.isSafeInteger(flags.duration) || @@ -82,6 +118,8 @@ export function validatePrepaidFlags( export function buildPrepaidInfo(flags: ReservationFlags): PrePaidInfo | undefined { if (!hasPrepaidFlags(flags)) return undefined; const prepaid: PrePaidInfo = {}; + if (flags.pricingCycle !== undefined) + prepaid.pricing_cycle = flags.pricingCycle as "Day" | "Hour"; if (flags.duration !== undefined) prepaid.duration = flags.duration; if (flags.autoRenewal !== undefined) prepaid.auto_renewal = flags.autoRenewal; if (flags.autoRenewalDuration !== undefined) diff --git a/packages/core/src/deploy/types.ts b/packages/core/src/deploy/types.ts index c8677ea7..19392d1d 100644 --- a/packages/core/src/deploy/types.ts +++ b/packages/core/src/deploy/types.ts @@ -5,6 +5,44 @@ * preserved verbatim — callers decide how to surface fields). */ +/** Model-routing optimization strategy. */ +export type ModelRoutingStrategy = "EFFECT_FIRST" | "COST_FIRST"; + +/** Model-routing configuration used by create, update and deployment responses. */ +export interface ModelRoutingConfig { + route_model_version: string; + strategy: ModelRoutingStrategy; + candidate_model_ids: string[]; + offline_model_ids?: string[]; + [key: string]: unknown; +} + +/** A model-routing version record returned by the platform. */ +export interface ModelRoutingVersion { + route_model_version?: string; + supported_strategies?: ModelRoutingStrategy[]; + supported_candidate_model_ids?: string[]; + offline_model_ids?: string[]; + [key: string]: unknown; +} + +/** GET /api/v1/deployments/model-routing/versions response. */ +export interface ModelRoutingVersionsPage { + route_model_versions?: ModelRoutingVersion[]; + total?: number; + total_page?: number; + page_no?: number; + page_size?: number; + [key: string]: unknown; +} + +export interface ListModelRoutingVersionsResponse { + request_id?: string; + output?: ModelRoutingVersionsPage; + data?: ModelRoutingVersionsPage; + [key: string]: unknown; +} + /** A single deployment record as returned by the platform. */ export interface Deployment { /** Unique deployed-model identifier — used as the `model` parameter when invoking the deployed model. */ @@ -17,8 +55,10 @@ export interface Deployment { base_model?: string; /** PENDING | RUNNING | STOPPED | FAILED */ status?: string; - /** Billing plan: mu | cu | ptu | lora (Token-billed). */ + /** Billing plan: mu | cu | ptu | lora | mr (model routing). */ plan?: string; + /** Model-routing configuration for plan=mr. */ + routing_config?: ModelRoutingConfig; /** Spec descriptor for MU plan, e.g. "MU1". */ model_unit_spec?: string; /** Charge type, e.g. "post_paid". */ @@ -62,17 +102,21 @@ export interface ReservationCapacity { input_tpm?: number; /** Output capacity in kTPM; zero is valid. */ output_tpm?: number; + /** Thinking-output capacity in kTPM; only some models support it, validated server-side. */ + thinking_output_tpm?: number; [key: string]: unknown; } /** Prepaid purchase and renewal configuration returned by queries. */ export interface PrePaidInfo { - /** Purchase / renewal duration in days. */ + /** Day (default) | Hour; Hour is the 8-hour off-peak window, prepaid ptu_default only. */ + pricing_cycle?: "Day" | "Hour"; + /** Purchase / renewal duration in days (Day), or exactly 8 (Hour). */ duration?: number; auto_renewal?: boolean; - /** Automatic renewal duration in days. */ + /** Automatic renewal duration in days; not sent for Hour. */ auto_renewal_duration?: number; - /** Renewal cycle unit, e.g. Day. */ + /** Renewal cycle unit, e.g. Day; not sent for Hour. */ auto_renewal_cycle?: string; [key: string]: unknown; } @@ -94,9 +138,12 @@ export interface CapacityInstance { /** Pending target, not effective capacity; may be absent or null in a stable state. */ target_capacity?: ReservationCapacity | null; pre_paid_info?: PrePaidInfo; + gmt_effective?: string; gmt_expired?: string; can_scale?: boolean; can_renew?: boolean; + can_enable_auto_renew?: boolean; + can_disable_auto_renew?: boolean; can_delete?: boolean; fail_reason?: string; gmt_created?: string; @@ -110,7 +157,7 @@ export interface CapacityOperation { operation_id?: string; /** Original operation request ID, distinct from the query response's request_id. */ request_id?: string; - /** CREATE | SCALE | RENEW | DELETE | STOP | REFUND | future operation types. */ + /** CREATE | SCALE | RENEW | AUTO_RENEW | DELETE | STOP | REFUND | future operation types. */ operation_type?: string; /** PROCESSING | SUCCEEDED | FAILED | future operation states. */ operation_status?: string; @@ -196,7 +243,7 @@ export interface CreateDeploymentRequest { model_name: string; /** Optional display name; PTU creation generates one when omitted. */ name?: string; - /** Required. Billing plan: mu | cu | ptu | lora. CLI defaults to "lora". */ + /** Required. Billing plan: mu | cu | ptu | lora | mr. CLI defaults to "lora". */ plan: string; /** Required for PTU creation; distinct from instance billing_method. */ charge_type?: "pre_paid" | "post_paid"; @@ -221,6 +268,19 @@ export interface CreateDeploymentRequest { [k: string]: unknown; } +/** POST /api/v1/deployments request body for a model router. */ +export interface CreateModelRouterRequest { + name: string; + plan: "mr"; + charge_type: "post_paid"; + routing_config: ModelRoutingConfig; +} + +/** PUT /api/v1/deployments/{deployed_model}/update request body for a model router. */ +export interface UpdateModelRouterRequest { + routing_config: ModelRoutingConfig; +} + /** * AIGC generation config — used when deploying fine-tuned Wan video (i2v/kf2v) * LoRA models. Controls how prompts are applied at inference time: @@ -241,7 +301,7 @@ export interface PtuCapacity { input_tpm?: number; /** Output capacity in kTPM. */ output_tpm?: number; - /** @deprecated Current reservation models do not support separate thinking-output capacity. */ + /** Thinking-output capacity in kTPM; only some models support it, validated server-side. */ thinking_output_tpm?: number; } @@ -338,6 +398,16 @@ export interface RenewCapacityInstanceRequest { ptu_capacity?: ReservationCapacity; } +/** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/auto-renew body. */ +export interface UpdateCapacityAutoRenewRequest { + /** true enables automatic renewal; false disables it. */ + auto_renewal: boolean; + /** The service currently accepts only "Day" (case-sensitive). */ + auto_renewal_cycle: string; + /** Days renewed per automatic cycle, positive integer. */ + auto_renewal_duration: number; +} + /** PUT /api/v1/deployments/{deployed_model}/update-overflowstrategy response. */ export type UpdateDeploymentOverflowResponse = GetDeploymentResponse; diff --git a/packages/core/tests/deploy-router-api.test.ts b/packages/core/tests/deploy-router-api.test.ts new file mode 100644 index 00000000..cbc6be52 --- /dev/null +++ b/packages/core/tests/deploy-router-api.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, test, vi } from "vite-plus/test"; +import type { Client } from "../src/client/client.ts"; +import { + createDeployment, + deleteDeployment, + listModelRoutingVersions, + modelRoutingVersionsPath, + updateDeployment, + type CreateModelRouterRequest, + type ListModelRoutingVersionsResponse, + type ModelRoutingConfig, + type UpdateModelRouterRequest, +} from "../src/deploy/index.ts"; + +function mockClient(response: unknown = {}) { + const requestJson = vi.fn().mockResolvedValue(response); + return { client: { requestJson } as unknown as Client, requestJson }; +} + +const routingConfig: ModelRoutingConfig = { + route_model_version: "router-v1", + strategy: "EFFECT_FIRST", + candidate_model_ids: ["qwen-plus", "qwen-max"], + offline_model_ids: ["qwen-offline"], + future_config: { enabled: false }, +}; + +const createBody: CreateModelRouterRequest = { + name: "production-router", + plan: "mr", + charge_type: "post_paid", + routing_config: routingConfig, +}; + +const updateBody: UpdateModelRouterRequest = { + routing_config: { + ...routingConfig, + strategy: "COST_FIRST", + }, +}; + +const deployedModel = "router /?#%&+"; +const encodedDeployment = "/api/v1/deployments/router%20%2F%3F%23%25%26%2B"; + +describe("model-routing versions", () => { + test("uses the fixed endpoint with no query when params are omitted", async () => { + const { client, requestJson } = mockClient(); + await listModelRoutingVersions(client); + expect(modelRoutingVersionsPath()).toBe("/api/v1/deployments/model-routing/versions"); + expect(requestJson).toHaveBeenCalledExactlyOnceWith({ + path: "/api/v1/deployments/model-routing/versions", + method: "GET", + signal: undefined, + }); + }); + + test("maps explicit pagination and forwards the signal", async () => { + const { client, requestJson } = mockClient(); + const signal = new AbortController().signal; + await listModelRoutingVersions(client, { pageNo: 2, pageSize: 50, signal }); + expect(requestJson).toHaveBeenCalledExactlyOnceWith({ + path: "/api/v1/deployments/model-routing/versions?page_no=2&page_size=50", + method: "GET", + signal, + }); + }); + + test("preserves pagination records and unknown fields verbatim", async () => { + const response: ListModelRoutingVersionsResponse = { + request_id: "request-1", + output: { + route_model_versions: [ + { + route_model_version: "router-v1", + supported_strategies: ["EFFECT_FIRST", "COST_FIRST"], + supported_candidate_model_ids: ["qwen-plus", "qwen-max"], + offline_model_ids: [], + future_version_field: { enabled: false }, + }, + ], + total: 1, + total_page: 1, + page_no: 1, + page_size: 20, + future_page_field: 0, + }, + future_response_field: false, + }; + const { client } = mockClient(response); + const result = await listModelRoutingVersions(client); + expect(result).toBe(response); + expect(result).toStrictEqual(response); + }); +}); + +describe("model-router deployment writes", () => { + test("creates with the exact POST body", async () => { + const response = { output: { deployed_model: deployedModel, routing_config: routingConfig } }; + const { client, requestJson } = mockClient(response); + const signal = new AbortController().signal; + expect(await createDeployment(client, createBody, signal)).toBe(response); + expect(requestJson).toHaveBeenCalledExactlyOnceWith({ + path: "/api/v1/deployments", + method: "POST", + body: createBody, + signal, + }); + expect(requestJson.mock.calls[0][0].body).toBe(createBody); + }); + + test("updates an encoded deployment ID with the complete PUT body", async () => { + const response = { + output: { deployed_model: deployedModel, routing_config: updateBody.routing_config }, + }; + const { client, requestJson } = mockClient(response); + const signal = new AbortController().signal; + expect(await updateDeployment(client, deployedModel, updateBody, signal)).toBe(response); + expect(requestJson).toHaveBeenCalledExactlyOnceWith({ + path: `${encodedDeployment}/update`, + method: "PUT", + body: updateBody, + signal, + }); + expect(requestJson.mock.calls[0][0].body).toBe(updateBody); + }); + + test("deletes an encoded deployment ID without a body", async () => { + const response = { output: { deployed_model: deployedModel, deleted: true } }; + const { client, requestJson } = mockClient(response); + expect(await deleteDeployment(client, deployedModel)).toBe(response); + expect(requestJson).toHaveBeenCalledExactlyOnceWith({ + path: encodedDeployment, + method: "DELETE", + signal: undefined, + }); + expect(requestJson.mock.calls[0][0]).not.toHaveProperty("body"); + }); + + test.each([ + ["versions", (client: Client) => listModelRoutingVersions(client)], + ["create", (client: Client) => createDeployment(client, createBody)], + ["update", (client: Client) => updateDeployment(client, deployedModel, updateBody)], + ["delete", (client: Client) => deleteDeployment(client, deployedModel)], + ])("does not retry the same %s failure", async (_name, run) => { + const error = new Error("original client failure"); + const { client, requestJson } = mockClient(); + requestJson.mockRejectedValue(error); + await expect(run(client)).rejects.toBe(error); + expect(requestJson).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/core/tests/deploy-write-api.test.ts b/packages/core/tests/deploy-write-api.test.ts index 76fad8ee..320c473e 100644 --- a/packages/core/tests/deploy-write-api.test.ts +++ b/packages/core/tests/deploy-write-api.test.ts @@ -8,6 +8,7 @@ import { createDeployment, deleteCapacityInstance, deleteDeployment, + deploymentCapacityInstanceAutoRenewPath, deploymentCapacityInstanceRenewPath, deploymentCapacityInstanceScalePath, deploymentOverflowPath, @@ -16,6 +17,7 @@ import { renewCapacityInstance, scaleCapacityInstance, scaleDeployment, + updateCapacityInstanceAutoRenew, updateDeploymentOverflow, validatePrepaidFlags, validateReservationCapacity, @@ -33,6 +35,7 @@ import { type ReservationFlags, type ScaleCapacityInstanceRequest, type ScaleDeploymentRequest, + type UpdateCapacityAutoRenewRequest, } from "../src/deploy/index.ts"; beforeEach(() => { @@ -96,6 +99,11 @@ const renewBody: RenewCapacityInstanceRequest = { pre_paid_info: prepaid, is_change: false, }; +const autoRenewBody: UpdateCapacityAutoRenewRequest = { + auto_renewal: true, + auto_renewal_cycle: "Day", + auto_renewal_duration: 30, +}; const writes = [ { name: "createCapacityInstance", @@ -121,6 +129,14 @@ const writes = [ run: (client: Client, options?: CapacityWriteOptions) => renewCapacityInstance(client, code, instanceId, renewBody, options), }, + { + name: "updateCapacityInstanceAutoRenew", + path: `${encodedInstance}/auto-renew`, + method: "PUT", + body: autoRenewBody, + run: (client: Client, options?: CapacityWriteOptions) => + updateCapacityInstanceAutoRenew(client, code, instanceId, autoRenewBody, options), + }, { name: "deleteCapacityInstance", path: encodedInstance, @@ -145,6 +161,9 @@ describe("reservation write paths", () => { test("encodes opaque path segments and appends exact action suffixes", () => { expect(deploymentCapacityInstanceScalePath(code, instanceId)).toBe(`${encodedInstance}/scale`); expect(deploymentCapacityInstanceRenewPath(code, instanceId)).toBe(`${encodedInstance}/renew`); + expect(deploymentCapacityInstanceAutoRenewPath(code, instanceId)).toBe( + `${encodedInstance}/auto-renew`, + ); expect(deploymentOverflowPath(code)).toBe(`${encodedDeployment}/update-overflowstrategy`); }); }); @@ -429,6 +448,16 @@ describe("shared reservation capacity", () => { }); }, ); + + test("forwards thinking-output capacity unchanged for server-side validation", () => { + const flags = { inputTpm: 0, outputTpm: 7, thinkingOutputTpm: 5 }; + expect(validateReservationCapacity(flags, true)).toBeUndefined(); + expect(buildReservationCapacity(flags)).toStrictEqual({ + input_tpm: 0, + output_tpm: 7, + thinking_output_tpm: 5, + }); + }); }); describe("shared prepaid information", () => { @@ -498,6 +527,29 @@ describe("shared prepaid information", () => { "--auto-renewal-duration", ); }); + + test("the 8-hour off-peak block is exact and other cycles are rejected", () => { + const hour: ReservationFlags = { pricingCycle: "Hour", duration: 8, autoRenewal: false }; + expect(hasPrepaidFlags({ pricingCycle: "Day" })).toBe(true); + expect(validatePrepaidFlags(hour, true)).toBeUndefined(); + expect(buildPrepaidInfo(hour)).toStrictEqual({ + pricing_cycle: "Hour", + duration: 8, + auto_renewal: false, + }); + for (const overrides of [ + { duration: 30 }, + { autoRenewal: true }, + { autoRenewalDuration: 30 }, + { autoRenewalCycle: "Day" }, + ] satisfies ReservationFlags[]) { + expectBilingual(validatePrepaidFlags({ ...hour, ...overrides }, true)); + } + expectBilingual( + validatePrepaidFlags({ pricingCycle: "WEEK", duration: 1, autoRenewal: false }, true), + "--pricing-cycle", + ); + }); }); function planContext(client: Client, flags: CreatePlanFlags = {}, dryRun = false): PlanContext { @@ -522,7 +574,6 @@ describe("PTU creation strategy", () => { { serviceTier: "ptu_v2" }, { serviceTier: "" }, { serviceTier: "ptu_default" }, - { thinkingOutputTpm: 0 }, { capacity: 0 }, { deploySpec: "MU1" }, { billingMethod: "POST_PAY" }, @@ -535,6 +586,32 @@ describe("PTU creation strategy", () => { { chargeType: "pre_paid" }, { chargeType: "pre_paid", duration: 30 }, { chargeType: "pre_paid", duration: 30, autoRenewal: true }, + { pricingCycle: "Hour" }, + { chargeType: "pre_paid", pricingCycle: "Hour", duration: 8, autoRenewal: false }, + { chargeType: "pre_paid", serviceTier: "ptu_default", pricingCycle: "Hour", duration: 30 }, + { + chargeType: "pre_paid", + serviceTier: "ptu_default", + pricingCycle: "Hour", + duration: 8, + autoRenewal: true, + }, + { + chargeType: "pre_paid", + serviceTier: "ptu_default", + pricingCycle: "Hour", + duration: 8, + autoRenewal: false, + autoRenewalDuration: 30, + }, + { + chargeType: "pre_paid", + serviceTier: "ptu_default", + pricingCycle: "Hour", + duration: 8, + autoRenewal: false, + autoRenewalCycle: "Day", + }, ] satisfies CreatePlanFlags[])( "rejects invalid combinations with bilingual errors: %j", (overrides) => { @@ -584,6 +661,29 @@ describe("PTU creation strategy", () => { expect(requestJson).not.toHaveBeenCalled(); }, ); + + test("builds the exact 8-hour off-peak purchase and forwards thinking capacity", async () => { + const flags: CreatePlanFlags = { + ...validFlags, + chargeType: "pre_paid", + serviceTier: "ptu_default", + pricingCycle: "Hour", + duration: 8, + autoRenewal: false, + thinkingOutputTpm: 5, + }; + const { client, requestJson } = mockClient(); + expect(strategy.validateFlags(flags)).toBeUndefined(); + expect(await strategy.resolve(planContext(client, flags))).toStrictEqual({ + body: { + charge_type: "pre_paid", + service_tier: "ptu_default", + ptu_capacity: { input_tpm: 0, output_tpm: 7, thinking_output_tpm: 5 }, + pre_paid_info: { pricing_cycle: "Hour", duration: 8, auto_renewal: false }, + }, + }); + expect(requestJson).not.toHaveBeenCalled(); + }); }); describe("MU and LoRA regressions", () => { diff --git a/packages/kscli/package.json b/packages/kscli/package.json index ae682ca1..aebbb523 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.10.4", + "version": "2.10.5", "description": "Lightweight RAG CLI for Aliyun Model Studio — focused on knowledge-base retrieval.", "keywords": [ "alibaba-cloud", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 6e35ce37..e2c2a4f2 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.10.4", + "version": "2.10.5", "description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index d8629466..3879aa44 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-cli metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- @@ -12,6 +12,7 @@ description: >- 用户点名百炼 / DashScope / `bl`,或继续既有 `bl` 工作流时直接使用。 共享协议(consent / 版本预检 / 鉴权 / 错误上报)在 bailian-protocol;官方安装 `bl skill init`。 家族路由:生图/生视频/配音/语音合成/转写 → bailian-gen;精调/微调/训练/训练数据集 → bailian-finetune; + 百炼模型智能路由(智能选模、smart routing / model routing)、吞吐预留(PTU)、ModelCode 容量购买与扩缩容 → bailian-finetune; agents.yaml 托管 Agent → bailian-managed-agent;Sandbox 实例与模版 → bailian-sandbox; 个人长期记忆与应用记忆资源 → bailian-memory;个人历史资料辅助任务、资料接入与知识库管理 → bailian-knowledge; 联网搜索路由(默认模型搜索 vs 显式 `--mode mcp` + 兜底)→ bailian-web-search。 @@ -102,6 +103,8 @@ Use this table only after the decision table in [`bailian-protocol`](../bailian- | Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | | Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | | Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | +| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | +| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | | Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | | agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | | Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index 47cde633..f9f9c7f1 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-finetune metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- @@ -10,6 +10,8 @@ description: >- 把专属模型部署成服务时使用 `bl dataset` / `bl finetune` / `bl deploy`。链路是 validate 校验数据 → upload 拿 file-id → finetune create 建任务 → watch 看进度 → export 导出 → 可选 compress 量化压缩 → deploy 上线,需要 API key; Console 版本状态与独立部署服务查询使用 Console 鉴权。 + 百炼模型智能路由(智能选模、smart routing / model routing)的路由版本查询、服务创建、配置更新与服务删除也由本 skill 承接,不要求先精调。 + 百炼吞吐预留(PTU)、ModelCode 容量购买、扩缩容、续费、释放、退订与溢出策略也由本 skill 承接,不要求先精调。 强化学习(RL)训练走 `bl finetune rl`,在隔离沙箱内执行,需先 `bl finetune runtime prepare` 准备运行时(沙箱仅支持 macOS / Linux); OPD 蒸馏训练走 `bl finetune opd`,宿主直连 fine-tunes OpenAPI,无需沙箱运行时; 授权检查与开通走 `bl finetune rl authorize` / `bl finetune opd authorize`(Console 鉴权)。 @@ -28,6 +30,8 @@ description: >- BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-finetune BAILIAN_SKILL_VERSION= bl dataset validate --file train.jsonl ``` +模型智能路由是独立的服务管理流程,不需要先准备训练数据或创建精调任务。命令组 `bl deploy router` 覆盖版本查询、创建、列表、详情、配置更新和删除。`router update` 的 `--route-version`、`--strategy`、`--candidates` 至少提供一项;CLI 先读取当前配置,保留未提供的字段,再向服务端提交完整 `routing_config`。`--candidates` 使用逗号分隔并替换整个候选列表。三个配置项齐全时 `--dry-run` 不联网;部分参数预览会读取当前路由,但不会提交更新。普通部署的限流、扩缩容、启停命令不适用于智能路由。创建/删除遇到确认错误时遵循共享协议,不自动补 `--yes`。详见 `reference/deploy.md` 或 `bl deploy router --help`。 + ## End-to-end workflow (follow in order) ``` @@ -75,12 +79,19 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-f | Query capacity instances | `bl deploy capacity list` / `get` | | Query / wait for a capacity operation | `bl deploy operation get` / `wait` | | Buy / scale / renew / release capacity | `bl deploy capacity create` / `scale` / `renew` / `delete` | +| Enable / disable automatic renewal | `bl deploy capacity auto-renew enable` / `disable` | | Unsubscribe a prepaid instance | `bl deploy capacity unsubscribe` (builds the billing console refund link) | | Configure ModelCode overflow strategy | `bl deploy overflow` | +| List model-routing versions | `bl deploy router versions` | +| Create a model router | `bl deploy router create --name --route-version --strategy --candidates ` | +| List model routers | `bl deploy router list` | +| Get model router detail | `bl deploy router get --deployed-model ` | +| Update selected model router fields | `bl deploy router update --deployed-model [--route-version ] [--strategy ] [--candidates ]` | +| Delete a model router | `bl deploy router delete --deployed-model ` | The `capacity list` / `get`, `operation get` / `wait` and `deploy list` / `get` queries are read-only. Capacity values are kTPM; effective, configured and target capacities are distinct. `deploy list --status` filters only the fetched page locally, with the server total left unfiltered. `operation get` reports status as data; `operation wait` exits non-zero on failure or timeout and refreshes capacity after success. Use IDs returned by the API; waiting never retries a write. -The `capacity create` / `scale` / `renew` / `delete` and `overflow` commands are high-risk writes: preview with `--dry-run`, then confirm with the runtime-injected `--yes`. Each write is submitted once and never auto-retried; HTTP 200 is not success, so pass `--wait` or check `operation_status`. Scale values are one instance's absolute kTPM, not deltas or ModelCode totals, and zero is not release. `capacity delete` releases an instance but keeps the ModelCode; active prepaid instances cannot be DELETEd — run `capacity unsubscribe --instance-id ` to get the billing console refund link and finish there (no API exists for refunds). Release is confirmed by `deleted=true`. `overflow` applies to the whole ModelCode, not one instance. There is no estimator or standalone auto-renewal endpoint — renewal settings ride along purchase/scale/renew. +The `capacity create` / `scale` / `renew` / `auto-renew enable` / `auto-renew disable` / `delete` and `overflow` commands are high-risk writes: preview with `--dry-run`, then confirm with the runtime-injected `--yes`. Each write is submitted once and never auto-retried; HTTP 200 is not success, so pass `--wait` or check `operation_status`. Scale values are one instance's absolute kTPM, not deltas or ModelCode totals, and zero is not release. `capacity delete` releases an instance but keeps the ModelCode; active prepaid instances cannot be DELETEd — run `capacity unsubscribe --instance-id ` to get the billing console refund link and finish there (no API exists for refunds). Release is confirmed by `deleted=true`. `overflow` applies to the whole ModelCode, not one instance. There is no estimator. Change automatic renewal through `capacity auto-renew enable` / `disable`; enabling it starts recurring charges until disabled. Console reads are separate from API-key file/deployment queries; the API Key / `file_id` semantics of `dataset list` are unchanged. Discover `records[].datasetGroupId` with `dataset groups`, then pass it to `dataset version --dataset-group-id ` to get `{result:[...]}` with `result[].datasetId` and an optional `fileId`. Use `dataset version --dataset-id ` for details; exactly one of `--dataset-group-id` and `--dataset-id` is required, and they cannot be combined. `fileId` is not `datasetId`; never pass a file ID from `dataset list` as a Console version ID. Groups are paginated and contain only one nested version preview; `version --dataset-group-id` normalizes array responses to `result` without promising exhaustive results or exposing pagination. Keep the same workspace throughout this chain. `--include-status` is available only in detail mode (`dataset version --dataset-id --include-status`) and preserves raw version and task state; missing/unknown state never means validation success or training readiness, and the returned task is not guaranteed to be the latest. A failed follow-up query retains metadata and exits nonzero. `deploy instances` returns one page (`records` is the list, `items` the total); reading does not establish inference or pause permission. With `--workspace-id`, these commands resolve that workspace's Console identity before business requests and stop on resolution failure. For an error-report file key, hand off to `bailian-cli` (`file url`); an existing report URL can be used directly. diff --git a/skills/bailian-finetune/reference/deploy.md b/skills/bailian-finetune/reference/deploy.md index 3be79d37..c357f154 100644 --- a/skills/bailian-finetune/reference/deploy.md +++ b/skills/bailian-finetune/reference/deploy.md @@ -7,77 +7,87 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| -------------------------------- | -------------- | --------------------------------------------------------------------------------- | -| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | -| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | -| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | -| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | -| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | -| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | -| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | -| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | -| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | -| `bl deploy get` | API Key | Get details of a single model deployment | -| `bl deploy image create` | API Key | Create an image generation model deployment | -| `bl deploy instances` | Console | List Console independent deployment services | -| `bl deploy list` | API Key | List model deployments and throughput reservations | -| `bl deploy models` | API Key | List models available for deployment | -| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | -| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | -| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | -| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | -| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | -| `bl deploy scale` | API Key | Scale a deployment's capacity | -| `bl deploy text create` | API Key | Create a text model deployment | -| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | +| Command | Authentication | Description | +| --------------------------------------- | -------------- | --------------------------------------------------------------------------------- | +| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | +| `bl deploy capacity auto-renew disable` | API Key | Disable automatic renewal for one prepaid capacity instance | +| `bl deploy capacity auto-renew enable` | API Key | Enable automatic renewal for one prepaid capacity instance | +| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | +| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | +| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | +| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | +| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | +| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | +| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | +| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | +| `bl deploy get` | API Key | Get details of a single model deployment | +| `bl deploy image create` | API Key | Create an image generation model deployment | +| `bl deploy instances` | Console | List Console independent deployment services | +| `bl deploy list` | API Key | List model deployments and throughput reservations | +| `bl deploy models` | API Key | List models available for deployment | +| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | +| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | +| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | +| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | +| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | +| `bl deploy router create` | API Key | Create a postpaid model router | +| `bl deploy router delete` | API Key | Delete a model router | +| `bl deploy router get` | API Key | Get model router details | +| `bl deploy router list` | API Key | List model routers | +| `bl deploy router update` | API Key | Update selected fields of a running model router configuration | +| `bl deploy router versions` | API Key | List available model-routing versions and candidates | +| `bl deploy scale` | API Key | Scale a deployment's capacity | +| `bl deploy text create` | API Key | Create a text model deployment | +| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | ## Command details ### `bl deploy audio create` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy audio create` | -| **Description** | Create an audio (TTS) model deployment | -| **Authentication** | API Key | -| **Usage** | `bl deploy audio create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--input-tpm --output-tpm ] [flags]` | -| **Risk** | `high` | -| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy audio create` | +| **Description** | Create an audio (TTS) model deployment | +| **Authentication** | API Key | +| **Usage** | `bl deploy audio create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--pricing-cycle ] [--input-tpm --output-tpm ] [flags]` | +| **Risk** | `high` | +| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | > **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. #### Flags -| Flag | Type | Required | Description | -| ---------------------------------------- | ------- | -------- | -------------------------------------------------------------------------------- | -| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | -| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | -| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | -| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | -| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | -| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | -| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | -| `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--thinking-output-tpm ` | number | no | Legacy thinking-output capacity flag; not supported for PTU | -| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | -| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | -| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | -| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | -| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | -| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | -| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | -| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | -| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | -| `--yes` | switch | no | Confirm this high-risk operation | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ---------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- | +| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | +| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | +| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | +| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | +| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | +| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | +| `--output-tpm ` | number | no | Absolute output capacity in kTPM | +| `--thinking-output-tpm ` | number | no | Thinking-output capacity in kTPM (plan=ptu); only some models support it, validated server-side | +| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | +| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | +| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | +| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | +| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | +| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | +| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | +| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | +| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes - Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit-billed) for audio (CosyVoice TTS). Pass --plan to override. -- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity is unsupported. Prepaid requires --duration and explicit --auto-renewal true|false. +- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity (--thinking-output-tpm) is only supported by some models and is validated server-side. Prepaid requires --duration and explicit --auto-renewal true|false. +- The 8-hour off-peak window is prepaid ptu_default only: --pricing-cycle Hour with --duration 8, --auto-renewal false and an explicit --service-tier ptu_default. Service hours must fall within 22:00–08:00, so orders are accepted only between 22:00 and 24:00 Beijing time; model support is validated by the server. - For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. billing_method defaults to POST_PAY (only supported value); deploy_spec and capacity are auto-picked from GET /deployments/models when omitted. - Use `deploy models --source base` to inspect available templates. - PTU creation preserves the original JSON and operation_id even with --quiet. --wait only queries the returned operation; pending capacity is not effective capacity. Check the actual status before invoking the model. @@ -99,16 +109,98 @@ bl deploy audio create --model-name my-cosyvoice-ft --display-name my-tts --depl bl deploy audio create --model-name my-cosyvoice-ft --display-name my-tts --dry-run ``` +### `bl deploy capacity auto-renew disable` + +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy capacity auto-renew disable` | +| **Description** | Disable automatic renewal for one prepaid capacity instance | +| **Authentication** | API Key | +| **Usage** | `bl deploy capacity auto-renew disable --deployed-model --instance-id --cycle --auto-renewal-duration [--wait]` | +| **Risk** | `high` | +| **Risk message** | Disabling automatic renewal stops recurring charges at expiry. | + +> **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. + +#### Flags + +| Flag | Type | Required | Description | +| -------------------------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------- | +| `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | +| `--instance-id ` | string | yes | Capacity instance ID returned by the API | +| `--request-id ` | string | no | Request identifier; generated if omitted. Reuse with identical parameters only for the same capacity operation | +| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | +| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | +| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | +| `--cycle ` | string | yes | Automatic renewal cycle; the service currently accepts only Day (case-sensitive) | +| `--auto-renewal-duration ` | number | yes | Days renewed at each automatic renewal, positive integer | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. +- Prepaid instances only; refreshes can_enable_auto_renew / can_disable_auto_renew before writing. 8-hour off-peak instances do not support automatic renewal. The operation usually completes synchronously and returns SUCCEEDED. + +#### Examples + +```bash +bl deploy capacity auto-renew disable --deployed-model example-code --instance-id example-instance --cycle Day --auto-renewal-duration 30 --dry-run +``` + +### `bl deploy capacity auto-renew enable` + +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy capacity auto-renew enable` | +| **Description** | Enable automatic renewal for one prepaid capacity instance | +| **Authentication** | API Key | +| **Usage** | `bl deploy capacity auto-renew enable --deployed-model --instance-id --cycle --auto-renewal-duration [--wait]` | +| **Risk** | `high` | +| **Risk message** | Enabling automatic renewal starts recurring charges until it is disabled again. | + +> **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. + +#### Flags + +| Flag | Type | Required | Description | +| -------------------------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------- | +| `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | +| `--instance-id ` | string | yes | Capacity instance ID returned by the API | +| `--request-id ` | string | no | Request identifier; generated if omitted. Reuse with identical parameters only for the same capacity operation | +| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | +| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | +| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | +| `--cycle ` | string | yes | Automatic renewal cycle; the service currently accepts only Day (case-sensitive) | +| `--auto-renewal-duration ` | number | yes | Days renewed at each automatic renewal, positive integer | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. +- Prepaid instances only; refreshes can_enable_auto_renew / can_disable_auto_renew before writing. 8-hour off-peak instances do not support automatic renewal. The operation usually completes synchronously and returns SUCCEEDED. + +#### Examples + +```bash +bl deploy capacity auto-renew enable --deployed-model example-code --instance-id example-instance --cycle Day --auto-renewal-duration 30 --dry-run +``` + ### `bl deploy capacity create` -| Field | Value | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy capacity create` | -| **Description** | Purchase an additional capacity instance for a ModelCode | -| **Authentication** | API Key | -| **Usage** | `bl deploy capacity create --deployed-model --billing-method --input-tpm --output-tpm [--duration ] [--auto-renewal ] [--wait]` | -| **Risk** | `high` | -| **Risk message** | Purchases additional throughput capacity and may enable recurring charges. | +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy capacity create` | +| **Description** | Purchase an additional capacity instance for a ModelCode | +| **Authentication** | API Key | +| **Usage** | `bl deploy capacity create --deployed-model --billing-method --input-tpm --output-tpm [--pricing-cycle ] [--duration ] [--auto-renewal ] [--wait]` | +| **Risk** | `high` | +| **Risk message** | Purchases additional throughput capacity and may enable recurring charges. | > **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. @@ -119,7 +211,8 @@ bl deploy audio create --model-name my-cosyvoice-ft --display-name my-tts --dry- | `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | | `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | | `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | | `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | | `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | | `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | @@ -135,8 +228,9 @@ bl deploy audio create --model-name my-cosyvoice-ft --display-name my-tts --dry- #### Notes - Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. -- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. - Keeps the ModelCode, model and performance tier. Only one unreleased postpaid instance is allowed per ModelCode; the server validates purchase eligibility and slot limits. +- The 8-hour off-peak window is an additional prepaid purchase: --pricing-cycle Hour with --duration 8, --auto-renewal false and no automatic-renewal duration. The selling window (22:00–24:00 Beijing time) and model support are validated by the server; created instances cannot be scaled, renewed, auto-renewed, released or unsubscribed and expire automatically. #### Examples @@ -148,6 +242,10 @@ bl deploy capacity create --deployed-model example-code --billing-method POST_PA bl deploy capacity create --deployed-model example-code --billing-method PRE_PAY --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run ``` +```bash +bl deploy capacity create --deployed-model example-code --billing-method PRE_PAY --pricing-cycle Hour --duration 8 --auto-renewal false --input-tpm 10000 --output-tpm 1000 --dry-run +``` + ### `bl deploy capacity delete` | Field | Value | @@ -179,7 +277,7 @@ bl deploy capacity create --deployed-model example-code --billing-method PRE_PAY #### Notes - Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. -- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. - Active prepaid instances must be unsubscribed via `deploy capacity unsubscribe` (billing console link), even when can_delete=true. Failed prepaid instances may have no associated order; only the server can decide whether direct release is supported. Release is asynchronous; verify deleted=true, not merely STOPPED or zero capacity. #### Examples @@ -254,14 +352,14 @@ bl deploy capacity list --deployed-model example-model-code --include-deleted fa ### `bl deploy capacity renew` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy capacity renew` | -| **Description** | Renew a prepaid capacity instance, optionally changing capacity | -| **Authentication** | API Key | -| **Usage** | `bl deploy capacity renew --deployed-model --instance-id --duration --auto-renewal [--is-change ] [--input-tpm ] [--output-tpm ] [--wait]` | -| **Risk** | `high` | -| **Risk message** | Renews a paid capacity instance and may enable automatic recurring renewal. | +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy capacity renew` | +| **Description** | Renew a prepaid capacity instance, optionally changing capacity | +| **Authentication** | API Key | +| **Usage** | `bl deploy capacity renew --deployed-model --instance-id --duration --auto-renewal [--is-change ] [--input-tpm ] [--output-tpm ] [--wait]` | +| **Risk** | `high` | +| **Risk message** | Renews a paid capacity instance and may enable automatic recurring renewal. | > **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. @@ -273,7 +371,8 @@ bl deploy capacity list --deployed-model example-model-code --include-deleted fa | `--instance-id ` | string | yes | Capacity instance ID returned by the API | | `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | | `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | | `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | | `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | | `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | @@ -289,7 +388,7 @@ bl deploy capacity list --deployed-model example-model-code --include-deleted fa #### Notes - Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. -- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. - Prepaid only; refreshes can_renew. Different capacity requires --is-change true; an unchanged capacity may be sent with false. No order_type is accepted by this endpoint. #### Examples @@ -323,7 +422,8 @@ bl deploy capacity renew --deployed-model example-code --instance-id example-ins | `--instance-id ` | string | yes | Capacity instance ID returned by the API | | `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | | `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | | `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | | `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | | `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | @@ -339,7 +439,7 @@ bl deploy capacity renew --deployed-model example-code --instance-id example-ins #### Notes - Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. -- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. - Refreshes can_scale before writing. Omitted prepaid settings remain omitted, so the server can reuse saved information. Postpaid instances cannot receive prepaid settings. #### Examples @@ -450,48 +550,50 @@ bl deploy get --deployed-model qwen-plus-2025-12-01-b6d61c71 --output json ### `bl deploy image create` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy image create` | -| **Description** | Create an image generation model deployment | -| **Authentication** | API Key | -| **Usage** | `bl deploy image create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--input-tpm --output-tpm ] [flags]` | -| **Risk** | `high` | -| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy image create` | +| **Description** | Create an image generation model deployment | +| **Authentication** | API Key | +| **Usage** | `bl deploy image create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--pricing-cycle ] [--input-tpm --output-tpm ] [flags]` | +| **Risk** | `high` | +| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | > **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. #### Flags -| Flag | Type | Required | Description | -| ---------------------------------------- | ------- | -------- | -------------------------------------------------------------------------------- | -| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | -| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | -| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | -| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | -| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | -| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | -| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | -| `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--thinking-output-tpm ` | number | no | Legacy thinking-output capacity flag; not supported for PTU | -| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | -| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | -| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | -| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | -| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | -| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | -| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | -| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | -| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | -| `--yes` | switch | no | Confirm this high-risk operation | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ---------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- | +| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | +| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | +| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | +| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | +| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | +| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | +| `--output-tpm ` | number | no | Absolute output capacity in kTPM | +| `--thinking-output-tpm ` | number | no | Thinking-output capacity in kTPM (plan=ptu); only some models support it, validated server-side | +| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | +| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | +| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | +| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | +| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | +| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | +| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | +| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | +| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes - Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit-billed) for audio (CosyVoice TTS). Pass --plan to override. -- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity is unsupported. Prepaid requires --duration and explicit --auto-renewal true|false. +- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity (--thinking-output-tpm) is only supported by some models and is validated server-side. Prepaid requires --duration and explicit --auto-renewal true|false. +- The 8-hour off-peak window is prepaid ptu_default only: --pricing-cycle Hour with --duration 8, --auto-renewal false and an explicit --service-tier ptu_default. Service hours must fall within 22:00–08:00, so orders are accepted only between 22:00 and 24:00 Beijing time; model support is validated by the server. - For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. billing_method defaults to POST_PAY (only supported value); deploy_spec and capacity are auto-picked from GET /deployments/models when omitted. - Use `deploy models --source base` to inspect available templates. - PTU creation preserves the original JSON and operation_id even with --quiet. --wait only queries the returned operation; pending capacity is not effective capacity. Check the actual status before invoking the model. @@ -813,6 +915,208 @@ bl deploy resume --deployed-model dep-... --skip-precheck bl deploy resume --deployed-model dep-... --dry-run ``` +### `bl deploy router create` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy router create` | +| **Description** | Create a postpaid model router | +| **Authentication** | API Key | +| **Usage** | `bl deploy router create --name --route-version --strategy --candidates ` | +| **Risk** | `high` | +| **Risk message** | Creating the model router starts it in RUNNING state immediately; postpaid routing may incur charges. | + +> **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------------------- | ------ | -------- | ------------------------------------------------------ | +| `--name ` | string | yes | Router name (1–64 letters, digits or hyphens) | +| `--route-version ` | string | yes | Model-routing version returned by the versions command | +| `--strategy ` | string | yes | Routing optimization strategy | +| `--candidates ` | string | yes | Candidate model IDs, comma-separated | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Creation uses plan=mr and charge_type=post_paid. The router becomes RUNNING immediately and may incur postpaid charges; preview with --dry-run before confirming. + +#### Examples + +```bash +bl deploy router create --name my-router --route-version v1 --strategy EFFECT_FIRST --candidates qwen-plus,qwen-turbo --dry-run +``` + +### `bl deploy router delete` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------- | +| **Name** | `deploy router delete` | +| **Description** | Delete a model router | +| **Authentication** | API Key | +| **Usage** | `bl deploy router delete --deployed-model ` | +| **Risk** | `high` | +| **Risk message** | This permanently deletes the specified model router and cannot be undone. | + +> **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------- | ------ | -------- | ------------------------------------- | +| `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Deletion is irreversible. The command verifies plan=mr first; a RUNNING model router does not need to be stopped before deletion. + +#### Examples + +```bash +bl deploy router delete --deployed-model router-example --dry-run +``` + +```bash +# Only after explicit user confirmation: +bl deploy router delete --deployed-model router-example --yes # Execute only after confirmation +``` + +### `bl deploy router get` + +| Field | Value | +| ------------------ | -------------------------------------------- | +| **Name** | `deploy router get` | +| **Description** | Get model router details | +| **Authentication** | API Key | +| **Usage** | `bl deploy router get --deployed-model ` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------- | ------ | -------- | ------------------------------------- | +| `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- The deployment is verified as plan=mr before its details are returned. + +#### Examples + +```bash +bl deploy router get --deployed-model router-example +``` + +```bash +bl deploy router get --deployed-model router-example --output json +``` + +### `bl deploy router list` + +| Field | Value | +| ------------------ | ------------------------------------------------------ | +| **Name** | `deploy router list` | +| **Description** | List model routers | +| **Authentication** | API Key | +| **Usage** | `bl deploy router list [--page ] [--page-size ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------ | ------ | -------- | ------------------------------------- | +| `--page ` | number | no | Page number (default: 1) | +| `--page-size ` | number | no | Results per page (1–100, default: 10) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- This command always requests plan=mr and does not expose a plan override. + +#### Examples + +```bash +bl deploy router list +``` + +```bash +bl deploy router list --page 2 --page-size 20 +``` + +### `bl deploy router update` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy router update` | +| **Description** | Update selected fields of a running model router configuration | +| **Authentication** | API Key | +| **Usage** | `bl deploy router update --deployed-model [--route-version ] [--strategy ] [--candidates ]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------------------- | ------ | -------- | ------------------------------------------------------ | +| `--deployed-model ` | string | yes | Deployed model identifier (ModelCode) | +| `--route-version ` | string | no | Model-routing version returned by the versions command | +| `--strategy ` | string | no | Routing optimization strategy | +| `--candidates ` | string | no | Candidate model IDs, comma-separated | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Provide at least one routing field. The CLI reads the current router and preserves fields you do not provide; --candidates replaces the entire candidate list. Only RUNNING model routers can be updated. +- A dry-run with all three routing fields stays offline. A partial dry-run requires credentials and reads the current router, but never submits an update. + +#### Examples + +```bash +bl deploy router update --deployed-model router-example --strategy COST_FIRST --dry-run +``` + +```bash +bl deploy router update --deployed-model router-example --route-version v1 --strategy COST_FIRST --candidates qwen-plus,qwen-turbo --dry-run +``` + +### `bl deploy router versions` + +| Field | Value | +| ------------------ | ---------------------------------------------------------- | +| **Name** | `deploy router versions` | +| **Description** | List available model-routing versions and candidates | +| **Authentication** | API Key | +| **Usage** | `bl deploy router versions [--page ] [--page-size ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------ | ------ | -------- | -------------------------------------- | +| `--page ` | number | no | Page number (default: 1) | +| `--page-size ` | number | no | Results per page (1–1000, default: 50) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Use the returned route_model_version, supported_strategies and supported_candidate_model_ids when creating or fully replacing a router configuration. + +#### Examples + +```bash +bl deploy router versions +``` + +```bash +bl deploy router versions --page 1 --page-size 100 +``` + ### `bl deploy scale` | Field | Value | @@ -835,7 +1139,8 @@ bl deploy resume --deployed-model dep-... --dry-run | `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | | `--output-tpm ` | number | no | Absolute output capacity in kTPM | | `--instance-id ` | string | no | PTU capacity instance ID; required when multiple unreleased instances exist | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | | `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | | `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | | `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | @@ -851,7 +1156,7 @@ bl deploy resume --deployed-model dep-... --dry-run #### Notes - Use --dry-run before confirming with --yes. A write is submitted once, never automatically retried. HTTP 200 is not operation success: inspect operation_status or pass --wait. After interruption or timeout, query the saved ModelCode/operation ID before considering another write. -- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal configuration is part of purchase/scale/renew, not a standalone free setting change. +- Capacities are absolute kTPM for one instance, not increments or ModelCode totals. Zero capacity is not release. Model-specific steps, limits and purchase periods are validated by the server. Automatic renewal is configured at purchase/renewal and changed via `deploy capacity auto-renew enable` / `disable`. - PTU input/output values are the selected instance's absolute target capacity in kTPM (1 kTPM = 1000 tokens/minute), not deltas or deployment totals. Both zero is valid and does not release the instance. PTU options cannot be combined with --capacity. - Without --instance-id, execution must confirm exactly one unreleased instance and recheck can_scale. Dry-run does not resolve an instance or validate its billing type. Pass --yes only after confirming the costs and target. @@ -867,48 +1172,50 @@ bl deploy scale --deployed-model dep-... --instance-id instance-... --input-tpm ### `bl deploy text create` -| Field | Value | -| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy text create` | -| **Description** | Create a text model deployment | -| **Authentication** | API Key | -| **Usage** | `bl deploy text create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--input-tpm --output-tpm ] [flags]` | -| **Risk** | `high` | -| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy text create` | +| **Description** | Create a text model deployment | +| **Authentication** | API Key | +| **Usage** | `bl deploy text create --model-name [--display-name ] [--plan ] [--charge-type ] [--service-tier ] [--suffix ] [--pricing-cycle ] [--input-tpm --output-tpm ] [flags]` | +| **Risk** | `high` | +| **Risk message** | Creating a deployment purchases or provisions resources and may incur charges. | > **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. #### Flags -| Flag | Type | Required | Description | -| ---------------------------------------- | ------- | -------- | -------------------------------------------------------------------------------- | -| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | -| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | -| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | -| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | -| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | -| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | -| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | -| `--output-tpm ` | number | no | Absolute output capacity in kTPM | -| `--thinking-output-tpm ` | number | no | Legacy thinking-output capacity flag; not supported for PTU | -| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | -| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | -| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | -| `--duration ` | number | no | Prepaid purchase/renewal duration, positive integer days | -| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | -| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | -| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | -| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | -| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | -| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | -| `--yes` | switch | no | Confirm this high-risk operation | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ---------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- | +| `--model-name ` | string | yes | Model to deploy — fine-tuned output name or catalog model (required) | +| `--display-name ` | string | no | Console display name (optional for PTU; required for other plans) | +| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (throughput reservation) \| mu | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | +| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | +| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | +| `--input-tpm ` | number | no | Absolute input capacity in kTPM (1 kTPM = 1000 tokens/minute) | +| `--output-tpm ` | number | no | Absolute output capacity in kTPM | +| `--thinking-output-tpm ` | number | no | Thinking-output capacity in kTPM (plan=ptu); only some models support it, validated server-side | +| `--charge-type ` | string | no | PTU payment type (required for plan=ptu): pre_paid or post_paid | +| `--service-tier ` | string | no | PTU service tier: ptu_fast (default) or ptu_default (prepaid only) | +| `--suffix ` | string | no | Optional PTU ModelCode suffix; generated by the service when omitted | +| `--pricing-cycle ` | string | no | Prepaid pricing cycle (case-sensitive): Day (default) or Hour for the 8-hour off-peak window | +| `--duration ` | number | no | Prepaid duration: positive integer days for Day, exactly 8 hours for Hour | +| `--auto-renewal ` | boolean | no | Explicitly enable or disable automatic renewal for prepaid purchases | +| `--auto-renewal-duration ` | number | no | Automatic renewal duration; required when enabled | +| `--auto-renewal-cycle ` | string | no | Optional supported renewal cycle, e.g. Day | +| `--wait` | switch | no | Wait for the returned capacity operation and refresh capacity | +| `--interval ` | number | no | Initial wait poll interval (1–3600, default: 2 seconds) | +| `--poll-timeout ` | number | no | Wait budget after submission (default: 600 seconds) | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes - Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit-billed) for audio (CosyVoice TTS). Pass --plan to override. -- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity is unsupported. Prepaid requires --duration and explicit --auto-renewal true|false. +- For plan=ptu, --charge-type, --input-tpm and --output-tpm are required. Capacity is in kTPM (1 kTPM = 1000 tokens/minute). Separate thinking-output capacity (--thinking-output-tpm) is only supported by some models and is validated server-side. Prepaid requires --duration and explicit --auto-renewal true|false. +- The 8-hour off-peak window is prepaid ptu_default only: --pricing-cycle Hour with --duration 8, --auto-renewal false and an explicit --service-tier ptu_default. Service hours must fall within 22:00–08:00, so orders are accepted only between 22:00 and 24:00 Beijing time; model support is validated by the server. - For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. billing_method defaults to POST_PAY (only supported value); deploy_spec and capacity are auto-picked from GET /deployments/models when omitted. - Use `deploy models --source base` to inspect available templates. - PTU creation preserves the original JSON and operation_id even with --quiet. --wait only queries the returned operation; pending capacity is not effective capacity. Check the actual status before invoking the model. @@ -930,6 +1237,10 @@ bl deploy text create --model-name qwen3.6-flash-2026-04-16 --plan ptu --charge- bl deploy text create --model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type pre_paid --service-tier ptu_default --input-tpm 10000 --output-tpm 1000 --duration 30 --auto-renewal false --dry-run ``` +```bash +bl deploy text create --model-name qwen3.6-flash-2026-04-16 --plan ptu --charge-type pre_paid --service-tier ptu_default --pricing-cycle Hour --duration 8 --auto-renewal false --input-tpm 10000 --output-tpm 1000 --dry-run +``` + ```bash bl deploy text create --model-name qwen3-8b --display-name my-qwen3-mu --plan mu ``` diff --git a/skills/bailian-finetune/reference/index.md b/skills/bailian-finetune/reference/index.md index 0d4351ed..279376a4 100644 --- a/skills/bailian-finetune/reference/index.md +++ b/skills/bailian-finetune/reference/index.md @@ -9,87 +9,95 @@ Use this index for the skill-scoped quick index and global flags. ## Quick index -| Command | Authentication | Description | Detail | -| -------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| `bl dataset delete` | API Key | Delete a dataset file by ID | [dataset.md](dataset.md) | -| `bl dataset get` | API Key | Get details of a single dataset file | [dataset.md](dataset.md) | -| `bl dataset groups` | Console | List Console dataset groups | [dataset.md](dataset.md) | -| `bl dataset list` | API Key | List uploaded dataset files | [dataset.md](dataset.md) | -| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | [dataset.md](dataset.md) | -| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | [dataset.md](dataset.md) | -| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | [dataset.md](dataset.md) | -| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | [deploy.md](deploy.md) | -| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | [deploy.md](deploy.md) | -| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | [deploy.md](deploy.md) | -| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | [deploy.md](deploy.md) | -| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | [deploy.md](deploy.md) | -| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | [deploy.md](deploy.md) | -| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | [deploy.md](deploy.md) | -| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | [deploy.md](deploy.md) | -| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | [deploy.md](deploy.md) | -| `bl deploy get` | API Key | Get details of a single model deployment | [deploy.md](deploy.md) | -| `bl deploy image create` | API Key | Create an image generation model deployment | [deploy.md](deploy.md) | -| `bl deploy instances` | Console | List Console independent deployment services | [deploy.md](deploy.md) | -| `bl deploy list` | API Key | List model deployments and throughput reservations | [deploy.md](deploy.md) | -| `bl deploy models` | API Key | List models available for deployment | [deploy.md](deploy.md) | -| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | [deploy.md](deploy.md) | -| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | [deploy.md](deploy.md) | -| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | [deploy.md](deploy.md) | -| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | [deploy.md](deploy.md) | -| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | [deploy.md](deploy.md) | -| `bl deploy scale` | API Key | Scale a deployment's capacity | [deploy.md](deploy.md) | -| `bl deploy text create` | API Key | Create a text model deployment | [deploy.md](deploy.md) | -| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | [deploy.md](deploy.md) | -| `bl finetune audio create` | API Key | Create an audio TTS model fine-tune job (sft-lora) | [finetune.md](finetune.md) | -| `bl finetune cancel` | API Key | Cancel a running fine-tune job | [finetune.md](finetune.md) | -| `bl finetune capability` | No Auth | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | [finetune.md](finetune.md) | -| `bl finetune checkpoints` | API Key | List checkpoints produced by a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune compress cancel` | API Key | Cancel a compression job | [finetune.md](finetune.md) | -| `bl finetune compress create` | API Key | Create a model compression job | [finetune.md](finetune.md) | -| `bl finetune compress delete` | API Key | Delete a compression job record | [finetune.md](finetune.md) | -| `bl finetune compress get` | API Key | Get a compression job | [finetune.md](finetune.md) | -| `bl finetune compress list` | API Key | List model compression jobs | [finetune.md](finetune.md) | -| `bl finetune compress logs` | API Key | Get compression job logs | [finetune.md](finetune.md) | -| `bl finetune compress templates` | API Key | List quantizable models and their compression templates | [finetune.md](finetune.md) | -| `bl finetune compress watch` | API Key | Probe or follow a compression job's status | [finetune.md](finetune.md) | -| `bl finetune delete` | API Key | Delete a fine-tune job record | [finetune.md](finetune.md) | -| `bl finetune export` | API Key | Publish a checkpoint as a deployable model | [finetune.md](finetune.md) | -| `bl finetune get` | API Key | Get details of a single fine-tune job | [finetune.md](finetune.md) | -| `bl finetune image create` | API Key | Create an image generation model fine-tune job (sft-lora) | [finetune.md](finetune.md) | -| `bl finetune list` | API Key | List fine-tune jobs | [finetune.md](finetune.md) | -| `bl finetune logs` | API Key | Fetch training logs for a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune metrics` | API Key | Query the training metrics of a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune opd authorize` | Console | Check and authorize OPD distillation access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | -| `bl finetune opd cancel` | API Key | Cancel a running OPD job | [finetune.md](finetune.md) | -| `bl finetune opd delete` | API Key | Delete an OPD job record | [finetune.md](finetune.md) | -| `bl finetune opd get` | API Key | Get an OPD job | [finetune.md](finetune.md) | -| `bl finetune opd logs` | API Key | Fetch OPD job logs | [finetune.md](finetune.md) | -| `bl finetune opd params` | API Key | Query OPD (pg_opd) training / resource parameter configuration for a student model | [finetune.md](finetune.md) | -| `bl finetune opd run` | API Key | Submit a pure Model OPD distillation job (pg_opd) via the fine-tunes OpenAPI | [finetune.md](finetune.md) | -| `bl finetune opd watch` | API Key | Probe an OPD job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | -| `bl finetune params` | API Key | Query the training hyper-parameter configuration for a base model | [finetune.md](finetune.md) | -| `bl finetune price` | Console | Estimate the training cost for a fine-tune job (token billing) | [finetune.md](finetune.md) | -| `bl finetune rl authorize` | Console | Check and authorize reinforcement-learning access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | -| `bl finetune rl cancel` | API Key | Cancel a running RL job | [finetune.md](finetune.md) | -| `bl finetune rl delete` | API Key | Delete an RL job record | [finetune.md](finetune.md) | -| `bl finetune rl get` | API Key | Get an RL job | [finetune.md](finetune.md) | -| `bl finetune rl list` | API Key | List RL jobs | [finetune.md](finetune.md) | -| `bl finetune rl logs` | API Key | Fetch RL job logs | [finetune.md](finetune.md) | -| `bl finetune rl run` | API Key | Submit a reinforcement-learning training job | [finetune.md](finetune.md) | -| `bl finetune rl watch` | API Key | Probe an RL job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | -| `bl finetune runtime clean` | No Auth | Reclaim orphaned sandbox run directories and superseded runtime versions | [finetune.md](finetune.md) | -| `bl finetune runtime doctor` | No Auth | Check the RL runtime and sandbox isolation (credential deny, home redirect, SDK import) | [finetune.md](finetune.md) | -| `bl finetune runtime prepare` | No Auth | Prepare the managed Python/SDK runtime used by RL and OPD jobs | [finetune.md](finetune.md) | -| `bl finetune text create` | API Key | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | -| `bl finetune video create` | API Key | Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft) | [finetune.md](finetune.md) | -| `bl finetune watch` | API Key | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | +| Command | Authentication | Description | Detail | +| --------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| `bl dataset delete` | API Key | Delete a dataset file by ID | [dataset.md](dataset.md) | +| `bl dataset get` | API Key | Get details of a single dataset file | [dataset.md](dataset.md) | +| `bl dataset groups` | Console | List Console dataset groups | [dataset.md](dataset.md) | +| `bl dataset list` | API Key | List uploaded dataset files | [dataset.md](dataset.md) | +| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | [dataset.md](dataset.md) | +| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | [dataset.md](dataset.md) | +| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | [dataset.md](dataset.md) | +| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | [deploy.md](deploy.md) | +| `bl deploy capacity auto-renew disable` | API Key | Disable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity auto-renew enable` | API Key | Enable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | [deploy.md](deploy.md) | +| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | [deploy.md](deploy.md) | +| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | [deploy.md](deploy.md) | +| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | [deploy.md](deploy.md) | +| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | [deploy.md](deploy.md) | +| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | [deploy.md](deploy.md) | +| `bl deploy get` | API Key | Get details of a single model deployment | [deploy.md](deploy.md) | +| `bl deploy image create` | API Key | Create an image generation model deployment | [deploy.md](deploy.md) | +| `bl deploy instances` | Console | List Console independent deployment services | [deploy.md](deploy.md) | +| `bl deploy list` | API Key | List model deployments and throughput reservations | [deploy.md](deploy.md) | +| `bl deploy models` | API Key | List models available for deployment | [deploy.md](deploy.md) | +| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | [deploy.md](deploy.md) | +| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | [deploy.md](deploy.md) | +| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | [deploy.md](deploy.md) | +| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | [deploy.md](deploy.md) | +| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | [deploy.md](deploy.md) | +| `bl deploy router create` | API Key | Create a postpaid model router | [deploy.md](deploy.md) | +| `bl deploy router delete` | API Key | Delete a model router | [deploy.md](deploy.md) | +| `bl deploy router get` | API Key | Get model router details | [deploy.md](deploy.md) | +| `bl deploy router list` | API Key | List model routers | [deploy.md](deploy.md) | +| `bl deploy router update` | API Key | Update selected fields of a running model router configuration | [deploy.md](deploy.md) | +| `bl deploy router versions` | API Key | List available model-routing versions and candidates | [deploy.md](deploy.md) | +| `bl deploy scale` | API Key | Scale a deployment's capacity | [deploy.md](deploy.md) | +| `bl deploy text create` | API Key | Create a text model deployment | [deploy.md](deploy.md) | +| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | [deploy.md](deploy.md) | +| `bl finetune audio create` | API Key | Create an audio TTS model fine-tune job (sft-lora) | [finetune.md](finetune.md) | +| `bl finetune cancel` | API Key | Cancel a running fine-tune job | [finetune.md](finetune.md) | +| `bl finetune capability` | No Auth | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | [finetune.md](finetune.md) | +| `bl finetune checkpoints` | API Key | List checkpoints produced by a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune compress cancel` | API Key | Cancel a compression job | [finetune.md](finetune.md) | +| `bl finetune compress create` | API Key | Create a model compression job | [finetune.md](finetune.md) | +| `bl finetune compress delete` | API Key | Delete a compression job record | [finetune.md](finetune.md) | +| `bl finetune compress get` | API Key | Get a compression job | [finetune.md](finetune.md) | +| `bl finetune compress list` | API Key | List model compression jobs | [finetune.md](finetune.md) | +| `bl finetune compress logs` | API Key | Get compression job logs | [finetune.md](finetune.md) | +| `bl finetune compress templates` | API Key | List quantizable models and their compression templates | [finetune.md](finetune.md) | +| `bl finetune compress watch` | API Key | Probe or follow a compression job's status | [finetune.md](finetune.md) | +| `bl finetune delete` | API Key | Delete a fine-tune job record | [finetune.md](finetune.md) | +| `bl finetune export` | API Key | Publish a checkpoint as a deployable model | [finetune.md](finetune.md) | +| `bl finetune get` | API Key | Get details of a single fine-tune job | [finetune.md](finetune.md) | +| `bl finetune image create` | API Key | Create an image generation model fine-tune job (sft-lora) | [finetune.md](finetune.md) | +| `bl finetune list` | API Key | List fine-tune jobs | [finetune.md](finetune.md) | +| `bl finetune logs` | API Key | Fetch training logs for a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune metrics` | API Key | Query the training metrics of a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune opd authorize` | Console | Check and authorize OPD distillation access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | +| `bl finetune opd cancel` | API Key | Cancel a running OPD job | [finetune.md](finetune.md) | +| `bl finetune opd delete` | API Key | Delete an OPD job record | [finetune.md](finetune.md) | +| `bl finetune opd get` | API Key | Get an OPD job | [finetune.md](finetune.md) | +| `bl finetune opd logs` | API Key | Fetch OPD job logs | [finetune.md](finetune.md) | +| `bl finetune opd params` | API Key | Query OPD (pg_opd) training / resource parameter configuration for a student model | [finetune.md](finetune.md) | +| `bl finetune opd run` | API Key | Submit a pure Model OPD distillation job (pg_opd) via the fine-tunes OpenAPI | [finetune.md](finetune.md) | +| `bl finetune opd watch` | API Key | Probe an OPD job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | +| `bl finetune params` | API Key | Query the training hyper-parameter configuration for a base model | [finetune.md](finetune.md) | +| `bl finetune price` | Console | Estimate the training cost for a fine-tune job (token billing) | [finetune.md](finetune.md) | +| `bl finetune rl authorize` | Console | Check and authorize reinforcement-learning access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | +| `bl finetune rl cancel` | API Key | Cancel a running RL job | [finetune.md](finetune.md) | +| `bl finetune rl delete` | API Key | Delete an RL job record | [finetune.md](finetune.md) | +| `bl finetune rl get` | API Key | Get an RL job | [finetune.md](finetune.md) | +| `bl finetune rl list` | API Key | List RL jobs | [finetune.md](finetune.md) | +| `bl finetune rl logs` | API Key | Fetch RL job logs | [finetune.md](finetune.md) | +| `bl finetune rl run` | API Key | Submit a reinforcement-learning training job | [finetune.md](finetune.md) | +| `bl finetune rl watch` | API Key | Probe an RL job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | +| `bl finetune runtime clean` | No Auth | Reclaim orphaned sandbox run directories and superseded runtime versions | [finetune.md](finetune.md) | +| `bl finetune runtime doctor` | No Auth | Check the RL runtime and sandbox isolation (credential deny, home redirect, SDK import) | [finetune.md](finetune.md) | +| `bl finetune runtime prepare` | No Auth | Prepare the managed Python/SDK runtime used by RL and OPD jobs | [finetune.md](finetune.md) | +| `bl finetune text create` | API Key | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | +| `bl finetune video create` | API Key | Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft) | [finetune.md](finetune.md) | +| `bl finetune watch` | API Key | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | ## By group | Group | Commands | Reference | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | `dataset` | `delete`, `get`, `groups`, `list`, `upload`, `validate`, `version` | [dataset.md](dataset.md) | -| `deploy` | `audio create`, `capacity create`, `capacity delete`, `capacity get`, `capacity list`, `capacity renew`, `capacity scale`, `capacity unsubscribe`, `delete`, `get`, `image create`, `instances`, `list`, `models`, `operation get`, `operation wait`, `overflow`, `pause`, `resume`, `scale`, `text create`, `update` | [deploy.md](deploy.md) | +| `deploy` | `audio create`, `capacity auto-renew disable`, `capacity auto-renew enable`, `capacity create`, `capacity delete`, `capacity get`, `capacity list`, `capacity renew`, `capacity scale`, `capacity unsubscribe`, `delete`, `get`, `image create`, `instances`, `list`, `models`, `operation get`, `operation wait`, `overflow`, `pause`, `resume`, `router create`, `router delete`, `router get`, `router list`, `router update`, `router versions`, `scale`, `text create`, `update` | [deploy.md](deploy.md) | | `finetune` | `audio create`, `cancel`, `capability`, `checkpoints`, `compress cancel`, `compress create`, `compress delete`, `compress get`, `compress list`, `compress logs`, `compress templates`, `compress watch`, `delete`, `export`, `get`, `image create`, `list`, `logs`, `metrics`, `opd authorize`, `opd cancel`, `opd delete`, `opd get`, `opd logs`, `opd params`, `opd run`, `opd watch`, `params`, `price`, `rl authorize`, `rl cancel`, `rl delete`, `rl get`, `rl list`, `rl logs`, `rl run`, `rl watch`, `runtime clean`, `runtime doctor`, `runtime prepare`, `text create`, `video create`, `watch` | [finetune.md](finetune.md) | ## Global flags diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index f431e81b..0f3b2e23 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index 295a023f..e490006a 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index 6da883e8..f14037cd 100644 --- a/skills/bailian-managed-agent/SKILL.md +++ b/skills/bailian-managed-agent/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-managed-agent metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index 8ac2fb8d..84e9a649 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index ecf6264a..81e2a072 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 58b521c6..3c66f14d 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index a08c6373..1d5bc5cd 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index b5a461fb..654c81a5 100644 --- a/skills/bailian-web-search/SKILL.md +++ b/skills/bailian-web-search/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-web-search metadata: - version: "2.10.4" + version: "2.10.5" requires: bins: ["bl"] description: >-