bailian-cli-core 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -20,11 +20,13 @@ interface ApiErrorContext {
20
20
  interface BailianErrorOptions {
21
21
  cause?: unknown;
22
22
  api?: ApiErrorContext;
23
+ rawResponse?: string;
23
24
  }
24
25
  declare class BailianError extends Error {
25
26
  readonly exitCode: ExitCode;
26
27
  readonly hint?: string;
27
28
  readonly api?: ApiErrorContext;
29
+ readonly rawResponse?: string;
28
30
  constructor(message: string, exitCode?: ExitCode, hint?: string, options?: BailianErrorOptions);
29
31
  toJSON(): {
30
32
  error: {
@@ -668,6 +670,8 @@ interface ConfigFile {
668
670
  access_key_id?: string;
669
671
  /** Alibaba Cloud OpenAPI AccessKey secret from `bl auth login --open-api`. */
670
672
  access_key_secret?: string;
673
+ /** Alibaba Cloud STS Security Token (optional, for temporary credentials). */
674
+ security_token?: string;
671
675
  base_url?: string;
672
676
  output?: "text" | "json";
673
677
  output_dir?: string;
@@ -683,6 +687,7 @@ interface ConfigFile {
683
687
  console_switch_agent?: number;
684
688
  telemetry?: boolean;
685
689
  }
690
+ declare const CONFIG_FILE_KEYS: readonly ["api_key", "access_token", "access_key_id", "access_key_secret", "security_token", "base_url", "output", "output_dir", "timeout", "default_text_model", "default_video_model", "default_image_model", "default_speech_model", "default_omni_model", "workspace_id", "console_site", "console_region", "console_switch_agent", "telemetry"];
686
691
  declare function parseConfigFile(raw: unknown): ConfigFile;
687
692
  /** 静态产品身份,createCli 注入一次(bl/rag 各异,故注入而非模块常量)。 */
688
693
  interface Identity {
@@ -701,6 +706,7 @@ interface Identity {
701
706
  */
702
707
  interface Settings {
703
708
  configPath?: string;
709
+ configName?: string;
704
710
  output: "text" | "json";
705
711
  /**
706
712
  * Whether `output` came from an explicit source (flag/env/file) rather than
@@ -736,9 +742,15 @@ interface ConfigStore {
736
742
  write(patch: Partial<ConfigFile>): Promise<void>;
737
743
  /** 删除指定键。 */
738
744
  unset(keys: (keyof ConfigFile)[]): Promise<void>;
745
+ /** 读取所有 Profile 与持久化激活项。 */
746
+ profiles(): ConfigProfiles;
747
+ /** 激活已存在的命名 Profile;undefined/default 激活顶层配置。 */
748
+ activate(name?: unknown): Promise<string>;
749
+ /** 校验激活目标并返回规范化展示名,不落盘。 */
750
+ validateActivation(name?: unknown): string;
739
751
  path: string;
740
752
  }
741
- declare function makeConfigStore(): ConfigStore;
753
+ declare function makeConfigStore(configName?: string): ConfigStore;
742
754
  //#endregion
743
755
  //#region src/auth/types.d.ts
744
756
  /** Where a resolved credential came from (shown by `bl auth status`). */
@@ -762,6 +774,7 @@ interface ConsoleCredential {
762
774
  interface OpenApiCredential {
763
775
  accessKeyId: string;
764
776
  accessKeySecret: string;
777
+ securityToken?: string;
765
778
  source: CredentialSource;
766
779
  }
767
780
  /** Full auth snapshot for display (`bl auth status`) — what would resolve per domain. */
@@ -773,7 +786,7 @@ interface AuthState {
773
786
  //#endregion
774
787
  //#region src/auth/store.d.ts
775
788
  /** 登录允许落盘的键:凭证本体 + 登录回调携带的连接/作用域字段。 */
776
- type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_key_id" | "access_key_secret" | "base_url" | "console_site" | "console_region" | "console_switch_agent" | "workspace_id">;
789
+ type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_key_id" | "access_key_secret" | "security_token" | "base_url" | "console_site" | "console_region" | "console_switch_agent" | "workspace_id" | "default_text_model" | "default_image_model">;
777
790
  /**
778
791
  * auth 命令族的凭证能力面(lint 限定 commands/auth/** 使用)。
779
792
  * 登录产生的全部落盘走 login,不放宽 configStore 的边界。
@@ -781,18 +794,21 @@ type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_ke
781
794
  interface AuthStore {
782
795
  /** 各域"将会解析出"的凭证快照(auth status 用)。 */
783
796
  describe(): AuthState;
784
- /** 磁盘上当前是否存有各域凭证(区别于 describe:只看 file,不含 flag/env 源)。 */
797
+ /** 磁盘上当前是否存有各域凭证及 model baseUrl(区别于 describe:只看 file,不含 flag/env 源)。 */
785
798
  stored(): {
786
799
  apiKey: boolean;
787
800
  console: boolean;
788
801
  openapi: boolean;
802
+ baseUrl?: string;
789
803
  };
790
- /** model 域 baseUrl 链(flag > env > file > 默认);验证 API key 等无凭证场景用。 */
791
- resolveBaseUrl(): string;
792
- /** 登录落盘:合并写入,undefined 键忽略。 */
804
+ /** model 域 baseUrl 链(flag > env > config file > fallback) */
805
+ resolveBaseUrl(fallback?: string): string;
806
+ /** 登录落盘:合并写入,undefined 键忽略;显式 --config 成功后同时激活目标 Profile。 */
793
807
  login(patch: AuthPersistPatch): Promise<void>;
794
808
  /** 清凭证:console/openapi 只删对应域;all 清全部登录凭证。返回是否有变更。 */
795
809
  logout(scope: "console" | "openapi" | "all"): Promise<boolean>;
810
+ /** 实际写入的 config.json 路径(不受命名配置影响,一直是同一个文件)。 */
811
+ path: string;
796
812
  }
797
813
  declare function makeAuthStore(sources: ResolutionSources): AuthStore;
798
814
  //#endregion
@@ -816,10 +832,11 @@ declare function request(deps: HttpDeps, opts: RequestOpts): Promise<Response>;
816
832
  declare function requestJson<T>(deps: HttpDeps, opts: RequestOpts): Promise<T>;
817
833
  //#endregion
818
834
  //#region src/client/acs.d.ts
819
- type AcsQueryParams = Record<string, string | string[] | undefined>;
835
+ type AcsQueryParams = Record<string, string | string[] | undefined | number>;
820
836
  interface AcsSignConfig {
821
837
  accessKeyId: string;
822
838
  accessKeySecret: string;
839
+ securityToken?: string;
823
840
  action: string;
824
841
  version: string;
825
842
  body: string;
@@ -893,6 +910,16 @@ interface ClientOpenApiQueryOpts {
893
910
  method: "GET" | "POST";
894
911
  queryParams: AcsQueryParams;
895
912
  }
913
+ interface ClientOpenApiJsonOpts {
914
+ host: string;
915
+ path: string;
916
+ action: string;
917
+ version: string;
918
+ method: "GET" | "POST";
919
+ /** JSON request body; omit for query-only calls (signed as an empty body). */
920
+ body?: unknown;
921
+ queryParams?: AcsQueryParams;
922
+ }
896
923
  interface OpenApiResponse {
897
924
  Success?: boolean;
898
925
  Code?: string;
@@ -927,6 +954,7 @@ declare class Client {
927
954
  mcp(pathOrUrl: string): McpClient;
928
955
  console<T>(api: string, data: Record<string, unknown>): Promise<T>;
929
956
  openApiQueryJson<T extends OpenApiResponse>(opts: ClientOpenApiQueryOpts): Promise<T>;
957
+ openApiJson<T extends OpenApiResponse>(opts: ClientOpenApiJsonOpts): Promise<T>;
930
958
  }
931
959
  //#endregion
932
960
  //#region src/types/command-pack-manager.d.ts
@@ -1017,6 +1045,11 @@ declare const GLOBAL_FLAGS: {
1017
1045
  type: "switch";
1018
1046
  description: string;
1019
1047
  };
1048
+ config: {
1049
+ type: "string";
1050
+ valueHint: string;
1051
+ description: string;
1052
+ };
1020
1053
  help: {
1021
1054
  type: "switch";
1022
1055
  description: string;
@@ -1089,6 +1122,11 @@ declare const OPENAPI_AUTH_FLAGS: {
1089
1122
  valueHint: string;
1090
1123
  description: string;
1091
1124
  };
1125
+ securityToken: {
1126
+ type: "string";
1127
+ valueHint: string;
1128
+ description: string;
1129
+ };
1092
1130
  };
1093
1131
  /** sources 里可能出现的全部 flag(全局 + 凭证域)。 */
1094
1132
  type SourceFlags = ParsedFlags<typeof GLOBAL_FLAGS & typeof MODEL_AUTH_FLAGS & typeof CONSOLE_AUTH_FLAGS & typeof OPENAPI_AUTH_FLAGS>;
@@ -1147,8 +1185,36 @@ type AnyCommand = Command<any>;
1147
1185
  declare function defineCommand<F extends FlagsDef>(spec: Command<F>): Command<F>;
1148
1186
  //#endregion
1149
1187
  //#region src/config/loader.d.ts
1150
- declare function readConfigFile(): ConfigFile;
1151
- declare function writeConfigFile(data: Record<string, unknown>): Promise<void>;
1188
+ /**
1189
+ * 校验并规范化 `--config <name>`:`undefined`/""/"default" 都视为未指定(等价顶层默认配置)。
1190
+ * 合法命名只允许字母、数字、`-`/`_`,且不能与 `ConfigFile` 顶层字段同名(避免写入时与默认配置字段歧义)。
1191
+ */
1192
+ declare function normalizeConfigName(name?: unknown): string | undefined;
1193
+ declare function readConfigFile(configName?: string): ConfigFile;
1194
+ /** 写入所选 Profile;登录流程可在同一次原子写入中将显式 Profile 设为激活项。 */
1195
+ declare function writeConfigFile(data: Record<string, unknown>, configName?: string, options?: {
1196
+ activate?: boolean;
1197
+ }): Promise<void>;
1198
+ /** 全量配置快照:顶层默认配置 + 各命名 profile。 */
1199
+ interface ConfigProfiles {
1200
+ /** 顶层默认配置(parseConfigFile 过滤后)。 */
1201
+ default: ConfigFile;
1202
+ /** 命名配置 name -> 配置。 */
1203
+ named: Record<string, ConfigFile>;
1204
+ /** 当前持久化激活项;default 表示顶层配置。 */
1205
+ active: string;
1206
+ }
1207
+ /**
1208
+ * 读取全部 profile:顶层默认配置与各命名 block。
1209
+ * 命名 block = raw 中不属于 `CONFIG_FILE_KEYS`、且值为普通对象的项。
1210
+ */
1211
+ declare function readConfigProfiles(): ConfigProfiles;
1212
+ /** 校验激活目标并返回规范化展示名;不写配置。 */
1213
+ declare function validateConfigProfileActivation(name?: unknown): string;
1214
+ /** 将已存在的命名 Profile(或 default)设为持久化激活项。 */
1215
+ declare function activateConfigProfile(name?: unknown): Promise<string>;
1216
+ /** 删除一个命名 profile block;存在才删并回写,返回是否有变更。 */
1217
+ declare function deleteConfigProfile(name?: unknown): Promise<boolean>;
1152
1218
  /**
1153
1219
  * 解析的三个来源,dispatch 边界一次构建。flags 收 Partial:ParsedFlags 里 switch 是
1154
1220
  * 必填 boolean,收 Partial 让 pipeline 等无 flag 场景传 {} 即可。
@@ -1157,6 +1223,10 @@ interface ResolutionSources {
1157
1223
  flags: Partial<SourceFlags>;
1158
1224
  file: ConfigFile;
1159
1225
  env: NodeJS.ProcessEnv;
1226
+ /** 当前命名配置名(`--config <name>` 解析后);未指定或 `default` 时为 undefined。 */
1227
+ configName?: string;
1228
+ /** 实际 config.json 路径(不受 configName 影响,一直是同一个文件)。 */
1229
+ configPath?: string;
1160
1230
  }
1161
1231
  declare function buildSources(flags: Partial<SourceFlags>): ResolutionSources;
1162
1232
  /**
@@ -1166,8 +1236,8 @@ declare function buildSources(flags: Partial<SourceFlags>): ResolutionSources;
1166
1236
  declare function buildSettings(s: ResolutionSources): Settings;
1167
1237
  //#endregion
1168
1238
  //#region src/auth/resolver.d.ts
1169
- /** Model-domain baseUrl(flag > env > file > cn)——无需 key 也可解析;login 验证等用。 */
1170
- declare function resolveModelBaseUrl(s: ResolutionSources): string;
1239
+ /** Model-domain baseUrl(flag > env > config file > fallback);无需 key 也可解析。 */
1240
+ declare function resolveModelBaseUrl(s: ResolutionSources, fallback?: string): string;
1171
1241
  /**
1172
1242
  * Model-domain credential from sources. Priority: `--api-key` flag >
1173
1243
  * `DASHSCOPE_API_KEY` env > config.json `api_key`. baseUrl: flag > env > file > cn.
@@ -1180,6 +1250,25 @@ declare function resolveOpenApi(s: ResolutionSources): OpenApiCredential;
1180
1250
  /** Full auth snapshot from sources — what would resolve per domain (or undefined). */
1181
1251
  declare function describeAuthState(s: ResolutionSources): AuthState;
1182
1252
  //#endregion
1253
+ //#region src/auth/refresh-token.d.ts
1254
+ declare function generateCLIAccessToken(opts: {
1255
+ identity: Identity;
1256
+ settings: Settings;
1257
+ baseUrl: string;
1258
+ accessKeyId: string;
1259
+ accessKeySecret: string;
1260
+ securityToken?: string;
1261
+ }): Promise<any>;
1262
+ /**
1263
+ * Try to refresh the console access_token using stored AK/SK.
1264
+ * Returns the new token on success, or null if AK/SK are not available.
1265
+ */
1266
+ declare function refreshAccessToken(opts: {
1267
+ identity: Identity;
1268
+ settings: Settings;
1269
+ baseUrl: string;
1270
+ }): Promise<string | null>;
1271
+ //#endregion
1183
1272
  //#region src/client/endpoints.d.ts
1184
1273
  declare function chatPath(): string;
1185
1274
  declare function imagePath(): string;
@@ -1217,6 +1306,42 @@ declare const SOURCE_CONFIG: string;
1217
1306
  /** Standard tracking headers required on every outbound request. */
1218
1307
  declare function trackingHeaders(): Record<string, string>;
1219
1308
  //#endregion
1309
+ //#region src/client/bailian-control.d.ts
1310
+ /** Shared inputs for every BailianControl OpenAPI call (AK/SK passed explicitly). */
1311
+ interface BailianControlAuth {
1312
+ identity: Identity;
1313
+ settings: Settings;
1314
+ baseUrl: string;
1315
+ regionId: string;
1316
+ accessKeyId: string;
1317
+ accessKeySecret: string;
1318
+ securityToken?: string;
1319
+ }
1320
+ interface CreateUserReqDTO {
1321
+ outerKey: string;
1322
+ nickName: string;
1323
+ userName: string;
1324
+ }
1325
+ /**
1326
+ * Create a Bailian console user via the BailianControl OpenAPI (`CreateUser`),
1327
+ * signed with Alibaba Cloud AK/SK. Mirrors {@link generateCLIAccessToken}: the
1328
+ * caller passes AK/SK explicitly, so this needs no stored credential.
1329
+ */
1330
+ declare function createBailianControlUser(opts: BailianControlAuth & {
1331
+ reqDTO: CreateUserReqDTO;
1332
+ }): Promise<OpenApiResponse>;
1333
+ /** List workspaces (used to resolve the agent id for permission changes). */
1334
+ declare function listBailianControlWorkspaces(opts: BailianControlAuth): Promise<OpenApiResponse>;
1335
+ /**
1336
+ * Authorize a user's servicer permissions via `ResetPolicies4Agent`. The single
1337
+ * `data` param carries the console payload re-encoded as a JSON string.
1338
+ */
1339
+ declare function resetBailianControlPolicies4Agent(opts: BailianControlAuth & {
1340
+ outerKey: string;
1341
+ agentId: number;
1342
+ policyIndexList?: number[];
1343
+ }): Promise<OpenApiResponse>;
1344
+ //#endregion
1220
1345
  //#region src/client/stream.d.ts
1221
1346
  interface ServerSentEvent {
1222
1347
  event?: string;
@@ -1255,7 +1380,7 @@ interface ConsoleGatewayTarget {
1255
1380
  declare function callConsoleGateway(target: ConsoleGatewayTarget, timeoutSec: number, {
1256
1381
  api,
1257
1382
  data
1258
- }: ConsoleGatewayRequest): Promise<unknown>;
1383
+ }: ConsoleGatewayRequest, settings?: Pick<Settings, "verbose">): Promise<unknown>;
1259
1384
  //#endregion
1260
1385
  //#region src/console/models.d.ts
1261
1386
  declare const MODEL_LIST_API = "zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels";
@@ -1345,6 +1470,23 @@ declare function getConfigPath(): string;
1345
1470
  declare function getCredentialsPath(): string;
1346
1471
  declare function ensureConfigDir(): Promise<void>;
1347
1472
  //#endregion
1473
+ //#region src/config/profile-presets.d.ts
1474
+ interface ModelProfilePreset {
1475
+ baseUrl: string;
1476
+ defaultTextModel: string;
1477
+ defaultImageModel: string;
1478
+ }
1479
+ /** Defaults materialized when logging into a well-known model profile. */
1480
+ declare function getModelProfilePreset(configName?: string): ModelProfilePreset | undefined;
1481
+ //#endregion
1482
+ //#region src/config/model-base-url.d.ts
1483
+ /**
1484
+ * Normalize a model-service base URL while preserving custom gateway prefixes.
1485
+ * CLI endpoints append their own API paths, so known SDK/API base suffixes must
1486
+ * not remain in the stored or resolved base URL.
1487
+ */
1488
+ declare function normalizeModelBaseUrl(input: string): string;
1489
+ //#endregion
1348
1490
  //#region src/output/formatter.d.ts
1349
1491
  type OutputFormat = "text" | "json";
1350
1492
  declare function detectOutputFormat(flagValue?: string): OutputFormat;
@@ -2555,6 +2697,9 @@ declare function maskToken(token: string): string;
2555
2697
  */
2556
2698
  declare function stripUndefined<T extends Record<string, unknown>>(obj: T): T;
2557
2699
  //#endregion
2700
+ //#region src/utils/fs.d.ts
2701
+ declare function readTextFromPathOrStdin(path: string): string;
2702
+ //#endregion
2558
2703
  //#region src/utils/boolean-flag.d.ts
2559
2704
  /** Parse true/false from CLI flags (e.g. `--watermark <bool>`). */
2560
2705
  declare function parseBooleanValue(value: unknown, label?: string): boolean;
@@ -2830,4 +2975,4 @@ interface ModelSource {
2830
2975
  load(): Promise<ModelProfile[]>;
2831
2976
  }
2832
2977
  //#endregion
2833
- export { ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BAILIAN_HOST, BILLING_METHOD, BailianError, BatchSizeGateInput, BatchSizeGateResult, BillingMethod, Budget, Budgets, CHANNEL, CHARGE_TYPE, COMMAND_PACK_API_VERSION, CONCURRENT_FLAG, CONSOLE_AUTH_FLAGS, CancelFineTuneResponse, Capabilities, Capability, ChargeType, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatResponseFormat, ChatTool, Client, ClientOpenApiQueryOpts, ClientRequestOpts, Command, CommandContext, CommandPack, CommandPackApiKeyContext, CommandPackCommand, CommandPackContext, CommandPackCredentials, CommandPackErrorOptions, CommandPackErrors, CommandPackManager, CommandPackMeta, CommandPackMutationResult, CommandPackOutput, CommandPackOutputOptions, CommandPackReport, Complexities, Complexity, ConfigFile, ConfigStore, ConsoleCredential, ConsoleGatewayRequest, ConsoleSite, ContextNeed, ContextNeeds, CreateDeploymentRequest, CreateDeploymentResponse, CreateFineTuneRequest, CreateFineTuneResponse, CreatePlanFlags, CredentialSource, DEFAULT_BILLING_METHOD, DEFAULT_DEPLOY_PLAN, DEFAULT_TRAINING_TYPE, DEPLOY_PLAN, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, DashScopeKnowledgeRetrieveRequest, DashScopeKnowledgeRetrieveResponse, DashScopeTTSRequest, DashScopeTTSResponse, DashScopeTTSStreamChunk, DashScopeTaskResponse, DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, type DataModality, DatasetDeleteResponse, DatasetFile, DatasetGetResponse, DatasetListParams, DatasetListResponse, DatasetSchema, DatasetUploadParams, DatasetUploadResponse, DeleteDeploymentResponse, DeleteFineTuneResponse, DeployModality, DeployPlan, DeployableModel, DeployableTemplate, Deployment, ExitCode, ExportCheckpointResponse, Feature, Features, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, FlagDef, FlagsDef, GLOBAL_FLAGS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, INSUFFICIENT_SAMPLES_CODE, Identity, IntentProfile, IntentSegment, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, KnowledgeChatStreamChunk, KnowledgeSearchRequest, KnowledgeSearchResponse, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, MAX_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, MODEL_AUTH_FLAGS, MODEL_LIST_API, McpClient, McpTool, McpToolResult, MemoryAddRequest, MemoryAddResponse, MemoryMessage, MemoryNode, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemorySearchRequest, MemorySearchResponse, Modalities, Modality, ModelCapability, ModelCategories, ModelCategory, ModelGroup, ModelGroupItem, ModelGroupParams, ModelGroupResult, ModelListParams, ModelListResult, ModelPreference, ModelPrice, ModelPriceInfo, ModelProfile, ModelSource, OPENAPI_AUTH_FLAGS, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, SEMANTIC_TOP_K, SOURCE_CONFIG, STRATEGIES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SourceFlags, StreamChoice, StreamChunk, TAGS, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, type TrainingProfile, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UsageError, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, analyzeIntent, appCompletionPath, bailianMcpPath, buildAcsCanonicalQuery, buildDocLink, buildSettings, buildSources, callConsoleGateway, cancelFineTune, chatPath, createDeployment, createFineTune, createTrackingEvent, credentialFlagDefs, defaultDeployPlan, defineCommand, deleteDataset, deleteDeployment, deleteFineTune, describeAuthState, detectModality, detectOutputFormat, effectiveConsoleGatewayConfig, ensureConfigDir, exportCheckpoint, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchPredictConfig, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateFilename, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getModels, getProfile, imagePath, imageSyncPath, isLocalFile, isSemanticAvailable, isTrainingTypeCli, knowledgeChatEndpoint, knowledgeRetrievePath, knowledgeSearchEndpoint, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, rankModels, readConfigFile, recallCandidates, recallSemantic, registerValidator, remoteSink, request, requestJson, resolveApiKey, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolveWatermark, scaleDeployment, signAcsRequest, speechRecognizePath, speechSynthesizePath, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unwrapResponse, updateDeployment, uploadDataset, uploadFile, userProfilePath, validateDataset, videoGeneratePath, writeConfigFile };
2978
+ export { ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BAILIAN_HOST, BILLING_METHOD, BailianControlAuth, BailianError, BatchSizeGateInput, BatchSizeGateResult, BillingMethod, Budget, Budgets, CHANNEL, CHARGE_TYPE, COMMAND_PACK_API_VERSION, CONCURRENT_FLAG, CONFIG_FILE_KEYS, CONSOLE_AUTH_FLAGS, CancelFineTuneResponse, Capabilities, Capability, ChargeType, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatResponseFormat, ChatTool, Client, ClientOpenApiJsonOpts, ClientOpenApiQueryOpts, ClientRequestOpts, Command, CommandContext, CommandPack, CommandPackApiKeyContext, CommandPackCommand, CommandPackContext, CommandPackCredentials, CommandPackErrorOptions, CommandPackErrors, CommandPackManager, CommandPackMeta, CommandPackMutationResult, CommandPackOutput, CommandPackOutputOptions, CommandPackReport, Complexities, Complexity, ConfigFile, ConfigProfiles, ConfigStore, ConsoleCredential, ConsoleGatewayRequest, ConsoleGatewayTarget, ConsoleSite, ContextNeed, ContextNeeds, CreateDeploymentRequest, CreateDeploymentResponse, CreateFineTuneRequest, CreateFineTuneResponse, CreatePlanFlags, CreateUserReqDTO, CredentialSource, DEFAULT_BILLING_METHOD, DEFAULT_DEPLOY_PLAN, DEFAULT_TRAINING_TYPE, DEPLOY_PLAN, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, DashScopeKnowledgeRetrieveRequest, DashScopeKnowledgeRetrieveResponse, DashScopeTTSRequest, DashScopeTTSResponse, DashScopeTTSStreamChunk, DashScopeTaskResponse, DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, type DataModality, DatasetDeleteResponse, DatasetFile, DatasetGetResponse, DatasetListParams, DatasetListResponse, DatasetSchema, DatasetUploadParams, DatasetUploadResponse, DeleteDeploymentResponse, DeleteFineTuneResponse, DeployModality, DeployPlan, DeployableModel, DeployableTemplate, Deployment, ExitCode, ExportCheckpointResponse, Feature, Features, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, FlagDef, FlagsDef, GLOBAL_FLAGS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, INSUFFICIENT_SAMPLES_CODE, Identity, IntentProfile, IntentSegment, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, KnowledgeChatStreamChunk, KnowledgeSearchRequest, KnowledgeSearchResponse, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, MAX_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, MODEL_AUTH_FLAGS, MODEL_LIST_API, McpClient, McpTool, McpToolResult, MemoryAddRequest, MemoryAddResponse, MemoryMessage, MemoryNode, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemorySearchRequest, MemorySearchResponse, Modalities, Modality, ModelCapability, ModelCategories, ModelCategory, ModelGroup, ModelGroupItem, ModelGroupParams, ModelGroupResult, ModelListParams, ModelListResult, ModelPreference, ModelPrice, ModelPriceInfo, ModelProfile, ModelSource, OPENAPI_AUTH_FLAGS, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, SEMANTIC_TOP_K, SOURCE_CONFIG, STRATEGIES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SourceFlags, StreamChoice, StreamChunk, TAGS, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, type TrainingProfile, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UsageError, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, activateConfigProfile, analyzeIntent, appCompletionPath, bailianMcpPath, buildAcsCanonicalQuery, buildDocLink, buildSettings, buildSources, callConsoleGateway, cancelFineTune, chatPath, createBailianControlUser, createDeployment, createFineTune, createTrackingEvent, credentialFlagDefs, defaultDeployPlan, defineCommand, deleteConfigProfile, deleteDataset, deleteDeployment, deleteFineTune, describeAuthState, detectModality, detectOutputFormat, effectiveConsoleGatewayConfig, ensureConfigDir, exportCheckpoint, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchPredictConfig, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateCLIAccessToken, generateFilename, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getModelProfilePreset, getModels, getProfile, imagePath, imageSyncPath, isLocalFile, isSemanticAvailable, isTrainingTypeCli, knowledgeChatEndpoint, knowledgeRetrievePath, knowledgeSearchEndpoint, listBailianControlWorkspaces, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, normalizeConfigName, normalizeModelBaseUrl, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, rankModels, readConfigFile, readConfigProfiles, readTextFromPathOrStdin, recallCandidates, recallSemantic, refreshAccessToken, registerValidator, remoteSink, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolveWatermark, scaleDeployment, signAcsRequest, speechRecognizePath, speechSynthesizePath, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unwrapResponse, updateDeployment, uploadDataset, uploadFile, userProfilePath, validateConfigProfileActivation, validateDataset, videoGeneratePath, writeConfigFile };
package/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{stringify as _}from"yaml";import{createHash as v,createHmac as y,randomBytes as ee,randomUUID as te}from"crypto";import{Readable as ne}from"stream";import{createInterface as b}from"readline";import{pipeline as re}from"stream/promises";import*as ie from"yauzl";import{cpSync as x,existsSync as S,mkdirSync as C,readFileSync as w,readdirSync as ae,writeFileSync as oe}from"node:fs";import{dirname as T,join as E}from"node:path";import{fileURLToPath as se}from"node:url";var ce=Object.create,D=Object.defineProperty,le=Object.getOwnPropertyDescriptor,ue=Object.getOwnPropertyNames,O=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty,fe=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ue(t),a=0,o=i.length,s;a<o;a++)s=i[a],!de.call(e,s)&&s!==n&&D(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=le(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:ce(O(e)),k(t||!e||!e.__esModule?D(n,`default`,{value:e,enumerable:!0}):n,e)),j=e(import.meta.url);const M={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var N=class extends Error{exitCode;hint;api;constructor(e,t=M.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api}toJSON(){let e=me(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},pe=class extends N{constructor(e,t){super(e,M.USAGE,t),this.name=`UsageError`}};function me(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function he(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new N(r,M.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}const ge={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},_e={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},ve=`https://bailian.cn-beijing.aliyuncs.com`,ye=new Set([`text`,`json`]),be=new Set([`domestic`,`international`]);function xe(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function Se(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};return typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.base_url==`string`&&xe(t.base_url)&&(n.base_url=t.base_url),typeof t.output==`string`&&ye.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&be.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function Ce(e){return e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||ge.cn}function we(e){let t=Ce(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new N(`No API key found.`,M.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Te(e){let t=e.file.access_token?.trim();if(!t)throw new N(`No console access token found.`,M.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function Ee(e){let t=De(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0);if(t)return t;let n=De(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Oe(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Oe(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)));if(n)return n;let r=De(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret));if(r)return r;throw new N(`No OpenAPI AK/SK credentials found.`,M.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function De(e,t,n,r){if(!r)return;let i=Oe(t),a=Oe(n);if(!i||!a)throw new N(`Incomplete OpenAPI AK/SK credentials found.`,M.AUTH,ke(e));return{accessKeyId:i,accessKeySecret:a,source:e}}function Oe(e){return e?.trim()||void 0}function ke(e){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars to use config credentials.`:"Run `bl auth login --open-api --access-key-id <id> --access-key-secret <secret>` again to save a complete pair."}function Ae(e){let t={};try{t.apiKey=we(e)}catch{}try{t.console=Te(e)}catch{}try{t.openapi=Ee(e)}catch{}return t}function P(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function F(){return g(P(),`config.json`)}function je(){return g(P(),`credentials.json`)}async function Me(){let e=P(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Ne(e){return _(e).replace(/\n$/,``)}function Pe(e){return JSON.stringify(e,null,2)}function Fe(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Ie(e){return e===`json`||e===`text`?e:`text`}function Le(e,t){switch(t){case`json`:return Pe(e);case`text`:return Ne(e)}}function I(){let e=F();if(!i(e))return{};try{return Se(JSON.parse(o(e,`utf-8`)))}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}async function L(e){await Me();let t=F(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),s(n,t)}function Re(e){return{flags:e,file:I(),env:process.env}}function ze(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=i!==void 0&&Number.isFinite(i)&&i>0?i:void 0,o=t.timeout??a??n.timeout??300;if(!Number.isFinite(o)||o<=0)throw new N(`Timeout must be a positive finite number.`,M.USAGE);return{configPath:F(),output:Ie(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const Be={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`],all:[`api_key`,`access_token`,`access_key_id`,`access_key_secret`]};function Ve(e){return{describe:()=>Ae(e),stored(){let e=I();return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret)}},resolveBaseUrl:()=>Ce(e),async login(e){let t=I();for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);await L(t)},async logout(e){let t=I(),n=Be[e];if(!n.some(e=>t[e]!==void 0))return!1;for(let e of n)delete t[e];return await L(t),!0}}}function He(){return`/compatible-mode/v1/chat/completions`}function Ue(){return`/api/v1/services/aigc/image-generation/generation`}function We(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Ge(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Ke(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function qe(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Je(){return`/api/v2/apps/memory/add`}function Ye(){return`/api/v2/apps/memory/memory_nodes/search`}function Xe(){return`/api/v2/apps/memory/memory_nodes`}function Ze(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Qe(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function $e(){return`/api/v1/services/audio/asr/transcription`}function et(){return`/api/v2/apps/memory/profile_schemas`}function tt(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function nt(){return`/api/v1/indices/rag/index/retrieve`}function rt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function it(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function at(){return`/api/v1/mcps/WebSearch/mcp`}function ot(){return`/compatible-mode/v1/files`}function st(){return`/api/v1/files`}function ct(e){return`/api/v1/files/${encodeURIComponent(e)}`}function lt(){return`/api/v1/fine-tunes`}function ut(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function dt(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function ft(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function pt(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function mt(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function ht(){return`/api/v1/deployments`}function gt(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function _t(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function vt(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function yt(){return`/api/v1/deployments/models`}const bt=`bailian-cli`,xt={t1:`public`,t2:``},St=JSON.stringify({channel:bt,tags:xt});function R(){return{"x-dashscope-source-config":St}}function Ct(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function wt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Tt(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...R(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),wt(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let e=r.Authorization;e&&console.error(`> Auth: ${Ct(e.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${St}`)}let i=Et((t.timeout??e.settings.timeout)*1e3,t.signal),a=await fetch(t.url,{method:t.method??`GET`,headers:r,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:i.signal}).finally(i.cleanup);if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!a.ok){let e={};try{e=await a.json()}catch{}throw he(a.status,e,t.url)}return a}function Et(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function Dt(e,t){let n=await Tt(e,t),r;try{r=await n.json()}catch{throw new N(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,M.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw he(200,{error:{message:r.message,type:r.code}},t.url);return r}function Ot(e){let t=[];for(let[n,r]of Object.entries(e))if(!(r===void 0||r===``))if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r]);return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${At(e)}=${At(t)}`).join(`&`)}function kt(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=te(),i=jt(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`},o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
1
+ import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{stringify as _}from"yaml";import{createHash as v,createHmac as ee,randomBytes as te,randomUUID as ne}from"crypto";import{Readable as re}from"stream";import{createInterface as y}from"readline";import{pipeline as ie}from"stream/promises";import*as ae from"yauzl";import{cpSync as b,existsSync as x,mkdirSync as S,readFileSync as C,readdirSync as oe,writeFileSync as se}from"node:fs";import{dirname as w,join as T}from"node:path";import{fileURLToPath as ce}from"node:url";var le=Object.create,ue=Object.defineProperty,de=Object.getOwnPropertyDescriptor,fe=Object.getOwnPropertyNames,E=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty,me=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),D=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=fe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!pe.call(e,s)&&s!==n&&ue(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=de(t,s))||r.enumerable});return e},O=(e,t,n)=>(n=e==null?{}:le(E(e)),D(t||!e||!e.__esModule?ue(n,`default`,{value:e,enumerable:!0}):n,e)),he=e(import.meta.url);const k={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var A=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=k.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api,this.rawResponse=r?.rawResponse}toJSON(){let e=_e(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},ge=class extends A{constructor(e,t){super(e,k.USAGE,t),this.name=`UsageError`}};function _e(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function ve(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new A(r,k.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}const ye=[`/compatible-mode/v1`,`/apps/anthropic`];function j(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw be(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw be(e);n.search=``,n.hash=``;let r=n.pathname.replace(/\/+$/,``),i=ye.find(e=>r===e||r.endsWith(e));return i&&(r=r.slice(0,-i.length).replace(/\/+$/,``)),n.pathname=r||`/`,n.toString().replace(/\/$/,``)}function be(e){return new A(`Invalid model base URL "${e}".`,k.USAGE,`Use an absolute http(s) URL.`)}const xe={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},Se={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Ce=`https://bailian.cn-beijing.aliyuncs.com`,we=[`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`default_text_model`,`default_video_model`,`default_image_model`,`default_speech_model`,`default_omni_model`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],Te=new Set([`text`,`json`]),Ee=new Set([`domestic`,`international`]);function De(e){try{return j(e)}catch{return}}function M(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=De(t.base_url);e&&(n.base_url=e)}return typeof t.output==`string`&&Te.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&Ee.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function Oe(e,t=xe.cn){return j(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function ke(e){let t=Oe(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new A(`No API key found.`,k.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Ae(e){let t=e.file.access_token?.trim();if(!t)throw new A(`No console access token found.`,k.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function je(e){let t=Me(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=Me(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(N(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||N(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=Me(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;throw new A(`No OpenAPI AK/SK credentials found.`,k.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function Me(e,t,n,r,i){if(!r)return;let a=N(t),o=N(n);if(!a||!o)throw new A(`Incomplete OpenAPI AK/SK credentials found.`,k.AUTH,Ne(e));return{accessKeyId:a,accessKeySecret:o,securityToken:N(i),source:e}}function N(e){return e?.trim()||void 0}function Ne(e){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars to use config credentials.`:"Run `bl auth login --open-api --access-key-id <id> --access-key-secret <secret>` again to save a complete pair."}function Pe(e){let t={};try{t.apiKey=ke(e)}catch{}try{t.console=Ae(e)}catch{}try{t.openapi=je(e)}catch{}return t}function P(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function F(){return g(P(),`config.json`)}function Fe(){return g(P(),`credentials.json`)}async function Ie(){let e=P(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Le(e){return _(e).replace(/\n$/,``)}function Re(e){return JSON.stringify(e,null,2)}function ze(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Be(e){return e===`json`||e===`text`?e:`text`}function Ve(e,t){switch(t){case`json`:return Re(e);case`text`:return Le(e)}}const He=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,I=`active_config`;function L(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function R(e){if(!(e===void 0||e===``||e===`default`)){if(typeof e!=`string`||!He.test(e))throw new A(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,k.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(we.includes(e)||e===I)throw new A(`Invalid config name "${e}". It conflicts with a config key.`,k.USAGE);return e}}function z(){let e=F();if(!i(e))return{};try{let t=JSON.parse(o(e,`utf-8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}function Ue(e,t){let n=R(e[I]);if(n&&t&&!L(e[n]))throw new A(`Active config "${n}" does not exist.`,k.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function We(e,t){if(!t)return e;let n=e[t];return L(n)?n:{}}function B(e){return M(We(z(),e))}async function V(e,t,n={}){let r=z();if(t)r[t]=e;else{for(let e of Object.keys(r))we.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[I]=t??`default`),await Ge(r)}async function Ge(e){await Ie();let t=F(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),s(n,t)}function Ke(){let e=z(),t={};for(let[n,r]of Object.entries(e))we.includes(n)||n===I||L(r)&&(t[n]=M(r));return{default:M(e),named:t,active:Ue(e,!0)??`default`}}function qe(e,t){let n=R(t);if(n&&!L(e[n]))throw new A(`Config "${n}" does not exist.`,k.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function Je(e){return qe(z(),e)}async function Ye(e){let t=z(),n=qe(t,e);return t[I]=n,await Ge(t),n}async function Xe(e){let t=R(e);if(!t)throw new A(`Cannot delete the default profile.`,k.USAGE);let n=z();return L(n[t])?(delete n[t],Ue(n,!1)===t&&(n[I]=`default`),await Ge(n),!0):!1}function Ze(e){let t=z(),n=e.config!==void 0,r=Ue(t,!n),i=n?R(e.config):r;return{flags:e,file:M(We(t,i)),env:process.env,configName:i,configPath:F()}}function Qe(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=i!==void 0&&Number.isFinite(i)&&i>0?i:void 0,o=t.timeout??a??n.timeout??300;if(!Number.isFinite(o)||o<=0)throw new A(`Timeout must be a positive finite number.`,k.USAGE);return{configPath:e.configPath??F(),configName:e.configName,output:Be(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const $e={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function et(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Pe(e),stored(){let e=B(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url}},resolveBaseUrl:t=>Oe(e,t),async login(e){let r=B(t);for(let[t,n]of Object.entries(e))n!==void 0&&(r[t]=t===`base_url`?j(String(n)):n);await V(r,t,{activate:n})},async logout(e){let n=B(t),r=$e[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await V(n,t),!0},get path(){return e.configPath??F()}}}function tt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const nt=`bailian-cli`,rt={t1:`public`,t2:``},it=JSON.stringify({channel:nt,tags:rt});function H(){return{"x-dashscope-source-config":it}}function at(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function ot(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...H(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),at(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let e=r.Authorization;e&&console.error(`> Auth: ${tt(e.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${it}`)}let i=st((t.timeout??e.settings.timeout)*1e3,t.signal),a=await fetch(t.url,{method:t.method??`GET`,headers:r,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:i.signal}).finally(i.cleanup);if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!a.ok){let e={};try{e=await a.json()}catch{}throw ve(a.status,e,t.url)}return a}function st(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function ct(e,t){let n=await ot(e,t),r;try{r=await n.json()}catch{throw new A(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,k.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw ve(200,{error:{message:r.message,type:r.code}},t.url);return r}function lt(e){let t=[];for(let[n,r]of Object.entries(e))if(!(r===void 0||r===``))if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r]);return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${dt(e)}=${dt(String(t))}`).join(`&`)}function ut(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=ne(),i=ft(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
3
3
  `)+`
4
4
  `,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
5
- `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${jt(u)}`,p=Mt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function At(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function jt(e){return v(`sha256`).update(e,`utf8`).digest(`hex`)}function Mt(e,t){return y(`sha256`,e).update(t,`utf8`).digest(`hex`)}const Nt=`${ge.cn}/api/v1/uploads`;async function Pt(e,t,n){let r=`${Nt}?action=getPolicy&model=${encodeURIComponent(t)}`,i=zt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...R()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new N(`Failed to get upload policy (HTTP ${a.status}): ${e}`,M.GENERAL)}return(await a.json()).data}async function Ft(e,t,n){let r=m(t),i=`${e.upload_dir}/${r}`,a=o(t),s=new FormData;s.append(`OSSAccessKeyId`,e.oss_access_key_id),s.append(`Signature`,e.signature),s.append(`policy`,e.policy),s.append(`x-oss-object-acl`,e.x_oss_object_acl),s.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),s.append(`key`,i),s.append(`success_action_status`,`200`),s.append(`file`,new Blob([a]),r);let c=zt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...R()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new N(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,M.GENERAL)}return`oss://${i}`}async function It(e){let{apiKey:t,model:n,filePath:r,signal:a}=e;if(!i(r))throw new N(`File not found: ${r}`,M.USAGE);if(!l(r).isFile())throw new N(`Not a file: ${r}`,M.USAGE);return Ft(await Pt(t,n,a),r,a)}function Lt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Rt(e,t,n,r={}){return Lt(e)?It({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function zt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}function Bt(e){return`/api/v1/mcps/${e}/mcp`}var Vt=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new N(`MCP error (${r.error.code}): ${r.error.message}`,M.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...R()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}};const Ht={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function Ut(e,t){return Ht[e]?.[t]??Ht[`cn-beijing`][t]}function Wt(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function Gt(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function Kt(e,t,{api:n,data:r}){let i=Ut(e.region,e.site),a=`https://${i.csGateway}`,o=i.action,s=Gt(n,r,e.switchAgent),c=new URLSearchParams({params:s,region:e.region}),l=t*1e3,u={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(u.Authorization=`Bearer ${e.token}`);let d=await fetch(`${a}/cli/api.json?action=${o}&product=sfm_bailian&api=${encodeURIComponent(n)}`,{method:`POST`,headers:u,body:c.toString(),signal:AbortSignal.timeout(l)});if(!d.ok){let e=await d.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${d.status} ${d.statusText}`,M.GENERAL,e.slice(0,500))}let f=await d.json(),p=f.data;if(p?.success===!1&&p.errorCode){let e=p.errorCode,t=typeof e==`string`?e:JSON.stringify(e),n=t.includes(`NotLogined`),r=typeof p.errorMsg==`string`?p.errorMsg:void 0;throw new N(n?`Console session is not logged in or has expired.`:`Console gateway error: ${t}`,n?M.AUTH:M.GENERAL,n?"Run `bl auth login --console` to sign in or refresh your console session.":r&&r!==t?r:void 0)}return f}var qt=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}url(e){return this.baseUrl+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return Tt(this.http,this.toOpts(e))}requestJson(e){return Dt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Lt(e)?Rt(e,this.requireApi().token,t,n):Promise.resolve(e)}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Vt(this.http,t,this.deps.apiCred?.token)}console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);return Kt(this.deps.consoleCred,this.deps.settings.timeout,{api:e,data:t})}async openApiQueryJson(e){let t=this.requireOpenApi(),n=Ot(e.queryParams),r=`https://${e.host}${e.path}${n?`?${n}`:``}`,i=kt({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,action:e.action,version:e.version,body:``,host:e.host,pathname:e.path,method:e.method,queryString:n});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${r}\n`),process.stderr.write(`> AK: ${Ct(t.accessKeyId)}\n`));let a=this.deps.settings.timeout*1e3,o=await fetch(r,{method:e.method,headers:{...i,...R()},signal:AbortSignal.timeout(a)});this.deps.settings.verbose&&process.stderr.write(`< ${o.status} ${o.statusText}\n`);let s=await o.json();if(!o.ok||s.Success===!1)throw new N(`${s.Code||o.status} - ${s.Message||o.statusText}`,M.GENERAL);return s}};async function*Jt(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let o=r.split(`
6
- `);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const Yt=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Xt=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Zt(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Qt(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Zt(await e(Yt,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function $t(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=Zt(await e(Yt,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function en(e,t){return(Zt(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const tn=[`name`,`key`,`default`,`tip`,`range`];function nn(e){return e.map(e=>{let t={};for(let n of tn)e[n]!==void 0&&(t[n]=e[n]);return t})}async function rn(e,t){let n=(await e(Xt,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?nn(e):null}catch{return null}return Array.isArray(n)?nn(n):null}function an(){return{read:()=>I(),async write(e){let t=I();for(let[n,r]of Object.entries(e))r===void 0?delete t[n]:t[n]=r;await L(t)},async unset(e){let t=I();for(let n of e)delete t[n];await L(t)},get path(){return F()}}}async function on(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ne.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:ot(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?new Date(f.created_at*1e3).toISOString():void 0};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new N(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,M.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new N(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,M.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function sn(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=st(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function cn(e,t,n){return e.requestJson({path:ct(t),method:`GET`,signal:n})}async function ln(e,t,n){let r=await e.request({path:ct(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const un=300*1024*1024,dn=1024*1024*1024;function fn(e,t=un){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);let n=l(e);if(!n.isFile())throw new N(`Not a regular file: ${e}`,M.USAGE);if(n.size===0)throw new N(`File is empty: ${e}`,M.USAGE);if(n.size>t)throw new N(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,M.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function pn(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,M.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function mn(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const hn=new Set([`system`,`user`,`assistant`]);function gn(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(z(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!hn.has(a))&&r.push(z(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(z(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function _n(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(z(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...gn(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(z(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(z(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const vn={name:`chatml`,detect:()=>!0,inspect:_n};function yn(e,t){let n=[];if(!(`text`in e))return n.push(z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const bn={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:yn};function xn(e,t){let n=_n(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...gn(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...gn(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Sn={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:xn};function Cn(e,t){let n=[];if(!(`wav_fn`in e))n.push(z(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(z(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(z(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(z(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(z(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const wn={name:`tts`,detect:e=>`wav_fn`in e,inspect:Cn},B=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function Tn(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function En(e){return/^[\x20-\x7E]+$/.test(e)}function Dn(e,t){let n=[];if(!(`prompt`in e))n.push(z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(z(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(z(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(z(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Tn(r);B.has(e)||n.push(z(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...B].join(`, `)}.`,{line:t,path:`img_path`})),En(r)||n.push(z(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(z(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(z(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Tn(r);B.has(e)||n.push(z(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...B].join(`, `)}.`,{line:t,path:`input_img`})),En(r)||n.push(z(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const On={name:`image`,detect:e=>`img_path`in e,inspect:Dn},kn=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),An=new Set([`.mp4`,`.mov`]);function jn(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Mn(e){return/^[\x20-\x7E]+$/.test(e)}function Nn(e,t,n,r,i,a){if(!(n in t)){r&&e.push(z(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(z(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(z(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=jn(o);i.has(s)||e.push(z(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Mn(o)||e.push(z(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Pn(e,t){let n=[];if(!(`prompt`in e))n.push(z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Nn(n,e,`first_frame_path`,!0,kn,t),Nn(n,e,`last_frame_path`,!1,kn,t),Nn(n,e,`video_path`,!1,An,t),n}const Fn=[wn,On,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Pn},Sn,bn,vn];function In(e,t){return t===void 0?Fn.find(t=>t.detect(e))??vn:Fn.find(e=>e.name===t)||vn}async function Ln(e,t){let r=b({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(z(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function Rn(e,t,r,i,a){let o=r?null:new Set(mn(t)),s=[],c=0,l=b({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...zn(n,u,i))}return{sampled:c,issues:s}}function zn(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return In(r,n).inspect(r,t)}const Bn={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Ln(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[z(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Rn(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Vn(e,t){return new Promise((n,r)=>{ie.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function Hn(e){return new Promise((t,n)=>{ie.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function Un(e,t,n){let{entry:i,zipfile:a}=await Vn(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}re(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Wn(e,t=100){let r=b({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const Gn={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Hn(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[z(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[z(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(z(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(z(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return B.has(n)});e.length<25&&r.push(z(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${ee(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await Un(e,m,_)}catch(t){return r.push(z(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await Bn.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await Wn(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(z(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Kn(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return qn(e);if(t===`.zip`)return Jn(e);throw new N(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,M.USAGE)}async function qn(e){let t=await Xn(e);if(!t)throw new N(`JSONL file is empty or contains only blank lines: ${e}`,M.USAGE);let n=Yn(t);return n===`unknown`?`text`:n}async function Jn(e){let t=await Zn(e,`data.jsonl`);if(!t)throw new N(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,M.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Yn(t);if(n===`unknown`)throw new N(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,M.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Yn(e){let t;try{t=JSON.parse(e)}catch{throw new N(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,M.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,M.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Xn(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=b({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Zn(e,t){return Vn(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new N(`Failed to read "${t}" from ZIP: ${e?.message}`,M.USAGE));return}let o=b({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const V=[Bn,Gn];function Qn(e){let t=h(e).toLowerCase(),n=V.find(e=>e.extensions.includes(t));if(!n){let e=V.flatMap(e=>e.extensions).join(`, `);throw new N(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,M.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function $n(e){V.some(t=>t.format===e.format)||V.push(e)}async function H(e,t={}){let{bytes:n}=fn(e,t.maxBytes??314572800),r=await Qn(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function er(){return V.map(e=>({format:e.format,extensions:[...e.extensions]}))}function tr(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}async function nr(e,t,n){return e.requestJson({path:lt(),method:`POST`,body:t,signal:n})}async function rr(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=lt(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ir(e,t,n){return e.requestJson({path:ut(t),method:`GET`,signal:n})}async function ar(e,t,n){return e.requestJson({path:dt(t),method:`POST`,signal:n})}async function or(e,t,n){return e.requestJson({path:ut(t),method:`DELETE`,signal:n})}async function sr(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=ft(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function cr(e,t,n){return e.requestJson({path:pt(t),method:`GET`,signal:n})}async function lr(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${mt(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const U={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},ur=Object.keys(U),dr=`sft-lora`;function fr(e){return e in U}function pr(e){let{method:t,variant:n}=U[e];return{method:t,variant:n}}function mr(e,t){if(!e)return!1;let{method:n,variant:r}=U[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function hr(e){return e?ur.filter(t=>mr(e,t)):[]}async function gr(e,t){let n=Wt(e);return(await Qt((t,r)=>Kt({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const _r=`INSUFFICIENT_SAMPLES`;function vr(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:_r,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
7
- `)}}function yr(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function br(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return H(e,{...r,schema:n})},resolveHyperParameters(e,t){return yr(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const xr=br(`sft`,`sft`,`chatml`),Sr={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},Cr={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},wr={...Cr,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Tr={n_epochs:400,learning_rate:`2e-5`,split:.9,max_split_val_dataset_sample:5,eval_epochs:50,save_total_limit:10,lora_rank:32,lora_alpha:32};function Er(e){return e===`image`||e===`image-i2i`}function Dr(e){return e===`video`||e===`video-kf2v`}function Or(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const kr=[xr,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return H(e,{...n,schema:`tts`});if(Er(t))return H(e,{...n,schema:`image`,maxBytes:dn});if(Dr(t)){let r=await H(e,{...n,schema:`video`,maxBytes:dn});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(z(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(z(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return H(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Sr};if(Er(e)){let n={...e===`image-i2i`?wr:Cr};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Dr(e)){let e=Or(t.model),n={...Tr,batch_size:4,max_pixels:e?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return yr(t)},shouldSkipGate(e,t){return!!((t===`audio`||Er(t)||Dr(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Er(e)||Dr(e)}},br(`dpo`,`dpo_full`,`dpo`),br(`dpo-lora`,`dpo_lora`,`dpo`),br(`cpt`,`cpt`,`cpt`)];function Ar(e){let t=kr.find(t=>t.clientTrainingType===e);if(!t){let t=kr.map(e=>e.clientTrainingType).join(`, `);throw new N(`Unknown training type "${e}".`,M.USAGE,`Supported training types: ${t}.`)}return t}function jr(){return kr.map(e=>e.clientTrainingType)}async function Mr(e,t,n){return e.requestJson({path:ht(),method:`POST`,body:t,signal:n})}async function Nr(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=ht(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Pr(e,t,n){return e.requestJson({path:gt(t),method:`GET`,signal:n})}async function Fr(e,t,n){return e.requestJson({path:gt(t),method:`DELETE`,signal:n})}async function Ir(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=yt(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Lr(e,t,n,r){return e.requestJson({path:_t(t),method:`PUT`,body:n,signal:r})}async function Rr(e,t,n,r){return e.requestJson({path:vt(t),method:`PUT`,body:n,signal:r})}const W={LORA:`lora`,PTU:`ptu`,MU:`mu`},zr=W.LORA;function Br(e){return e===`audio`?W.MU:zr}const Vr={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},Hr=Vr.POST_PAY,Ur={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},Wr={name:W.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},Gr={name:W.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},Kr={name:W.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||Hr,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new N(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,M.USAGE);try{let a=await Ir(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===W.MU)?.templates??[];if(o.length===0)throw i();let s=t===Vr.POST_PAY?Ur.POST_PAID:Ur.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof N?e:new N(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,M.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},qr={[W.LORA]:Wr,[W.PTU]:Gr,[W.MU]:Kr};function Jr(e){let t=qr[e];if(!t)throw new N(`Unsupported plan "${e}". Supported plans: ${Object.keys(qr).join(`, `)}.`,M.USAGE);return t}const Yr={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},Xr={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Zr={async:{type:`switch`,description:`Return async task id without waiting`}},Qr={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},$r={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},ei={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}};function ti(e){return e.auth===`apiKey`?Qr:e.auth===`console`?$r:e.auth===`openapi`?ei:{}}function ni(e){return e}const ri=1;function ii(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function ai(e,t){return`${ii(e||`image`,`image`)}_${ii((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const oi=()=>g(f(),`bailian-output`);function si(e,t){let n=t?.flagDir||e.outputDir||oi(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function ci(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function li(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new N(`Invalid ${t} value "${String(e)}". Use true or false.`,M.USAGE)}function ui(e,t=`boolean`){if(e!=null)return li(e,t)}function di(e,t,n=`boolean`){let r=ui(e,n);return r===void 0?t:r}function fi(e){return ui(e,`watermark`)??!0}function pi(e){let t={command:e.command,timestamp:new Date().toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform};return e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function mi(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function hi(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=mi(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let G;function gi(){return G||(process.env.NODE_ENV===`development`?(G=`dev`,G):(G=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,G))}var _i=fe(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=j(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=j(`dns`)},function(e,t){e.exports=j(`util`)},function(e,t){e.exports=j(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},te=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},w=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},de=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},k=new Map,A=new Map;k.set(`Baiduspider-render`,i),k.set(`Baiduspider+`,i),k.set(`Baiduspider-image+`,i),k.set(`360Spider`,a),k.set(`360Spider-Image`,a),k.set(`bingbot`,o),k.set(`Googlebot`,s),k.set(`YandexRenderResourcesBot`,c),k.set(`spider`,l),k.set(`Dataprovider.com`,u),k.set(`AhrefsBot`,d),k.set(`BitSightBot`,f),k.set(`oBot`,p),k.set(`Cincraw`,m),k.set(`DingTalkBot-LinkService`,h),k.set(`YisouSpider`,g),k.set(`Bytespider`,_),k.set(`ev-crawler`,v),k.set(`bitdiscovery`,y),k.set(`Spider`,ee),k.set(`Ai2Bot-Dolma`,te),k.set(`dianjing_ad_spider`,ne),A.set(`Baiduspider-render`,b),A.set(`Baiduspider+`,b),A.set(`Baiduspider-image+`,b),A.set(`360Spider`,re),A.set(`360Spider-Image`,re),A.set(`bingbot`,ie),A.set(`Googlebot`,x),A.set(`YandexRenderResourcesBot`,S),A.set(`spider`,C),A.set(`Dataprovider.com`,w),A.set(`AhrefsBot`,ae),A.set(`BitSightBot`,oe),A.set(`oBot`,T),A.set(`Cincraw`,E),A.set(`DingTalkBot-LinkService`,se),A.set(`YisouSpider`,ce),A.set(`Bytespider`,D),A.set(`ev-crawler`,le),A.set(`bitdiscovery`,ue),A.set(`Spider`,O),A.set(`Ai2Bot-Dolma`,de),A.set(`dianjing_ad_spider`,fe);let j={productHandlerMap:k,commentHandlerMap:A,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,j),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var ee=y,te=n(3),ne=n.n(te),b=n(4),re=n(5),ie=n.n(re);function x(e){return(x=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function S(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function C(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?S(Object(n),!0).forEach(function(t){w(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):S(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function w(e,t,n){return(t=(function(e){var t=(function(e,t){if(x(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(x(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return x(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ae(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=T(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
8
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function oe(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||T(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
9
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function T(e,t){if(e){if(typeof e==`string`)return E(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?E(e,t):void 0}}function E(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function se(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=oe(r[n],2),o=(a[0],a[1]);if(o){var s,c=ae(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var ce,D,le=(ce=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:ce,device_id:ie.a.createHash(`md5`).update(se()).digest(`hex`),platform:`node`}),ue=(0,b.promisify)(ne.a.resolve);function O(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,ee.call(this,C(C({},le),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}O.prototype=((D=function(){}).prototype=ee.prototype,new D),O.prototype.constructor=O,O.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,ue(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=O}]).default})),vi=fe(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=0)})([function(e,t,n){n.r(t);var r=[`ec`,`ea`,`el`,`et`],i=function(e,t){var n=function(e){var n=e.ec,r=e.ea,i=e.el,a=e.et,o=a===void 0?`CLK`:a,s=e.xpath;delete e.ec,delete e.ea,delete e.el,delete e.et,delete e.xpath,e.p1=n,e.p2=r,e.p3=i,e.p4=o,e.p5=s;try{t.log(`event`,e)}catch{}};return function(){var t=arguments,i={};if(t.length!==0){for(var a=0;a<t.length;a++){var o,s,c=t[a];if(a!==0&&typeof c==`object`&&a!==t.length-1)return void(e==null||(o=e.console)==null||(s=o.warn)==null||s.call(o,`Only the last argument can be object type`));if(typeof c==`string`||typeof c==`number`)i[r[a]]=c;else if(typeof c==`object`&&a===t.length-1)for(var l in c)c.hasOwnProperty(l)&&(i[l]=c[l])}n(i)}else{var u,d;(u=e.console)==null||(d=u.warn)==null||d.call(u,`At lease one augument`)}}};t.default=function(e,t){return i(global,e)}}]).default})),yi=A(_i(),1),bi=A(vi(),1);const xi=()=>g(P(),`telemetry.jsonl`);let Si;const Ci=new Set;let wi;try{let e=new yi.default({pid:`bailian-cli-node`,env:gi()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;Ci.add(e),e.finally(()=>Ci.delete(e))}return n},wi=e,Si=e.use(bi.default)}catch{}async function Ti(e=1e3){try{if(wi)try{typeof wi._sendAll==`function`&&wi._sendAll()}catch{}if(Ci.size===0)return;let t=[...Ci].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Ei(e){try{await Me();let n=xi();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
10
- `,{mode:384})}catch{}}async function Di(e){try{if(!Si)return;Si(e.command,hi(e))}catch{}}const Oi=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),ki=new Set(`page.pageSize.n.count.model.voice.language.provider.capability.temperature.topP.topK.maxTokens.seed.stream.size.resolution.ratio.duration.format.audioFormat.sampleRate.pitch.rate.volume.api.mode.download.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function Ai(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||Oi.has(n)||ki.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function ji(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof N?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=pi({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.identity.version,authMethod:e.authMethod,params:Ai(n)});Ei(l).catch(()=>{}),Di(l).catch(()=>{})}}function Mi(e){if(!e.model)return null;let t=e.inferenceMetadata;return{model:e.model,name:e.name??e.model,description:e.description??e.shortDescription??``,shortDescription:e.shortDescription,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],category:e.category,contextWindow:e.contextWindow??void 0,maxOutputTokens:e.maxOutputTokens??void 0,maxInputTokens:e.maxInputTokens??void 0,docUrl:e.docUrl,collectionTag:e.collectionTag,inferenceMetadata:t,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource}}var Ni=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=Wt(this.settings),t=(t,n)=>Kt({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await Qt(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await Qt(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(Mi).filter(e=>e!==null)}};const Pi=`models.jsonl`;function Fi(){return E(P(),`skills/bailian-docs-llm-wiki`)}function Ii(){return E(Fi(),Pi)}function Li(){return E(T(se(import.meta.url)),`../../../../../skills/bailian-docs-llm-wiki/models`)}function Ri(e){return!e.model||typeof e.model!=`string`?null:{model:e.model,name:e.name??e.model,description:e.description??``,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,docUrl:e.docUrl,inferenceMetadata:e.inferenceMetadata,shortDescription:e.shortDescription,category:e.category,collectionTag:e.collectionTag,maxInputTokens:e.maxInputTokens,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource,family:e.family,familyName:e.familyName}}function zi(e){let t=w(e,`utf-8`).split(`
11
- `).filter(Boolean),n=[];for(let e of t)try{let t=Ri(JSON.parse(e));t&&n.push(t)}catch{}return n}function Bi(){let e=Li();if(!S(E(e,Pi)))return!1;let t=Fi();try{return C(t,{recursive:!0}),x(e,t,{recursive:!0}),!0}catch{return!1}}var Vi=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return S(Ii())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!Bi())?[]:zi(Ii())}};async function Hi(e,t){let n=[new Vi({onPrepareStart:t?.onPrepareStart}),new Ni(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new N(`No model data available.`,M.GENERAL)}const Ui={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},K={Single:`single`,Pipeline:`pipeline`},Wi={Low:`low`,Medium:`medium`,High:`high`},Gi={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},q={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},J={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},Ki={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Y={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},qi=20,Ji=/-\d{4}-\d{2}-\d{2}$/,Yi=new Set([J.IG,J.VG,J.TTS,J.RealtimeTTS,J.ThreeDGeneration]),Xi=new Set([J.TG,J.Reasoning,J.ASR,J.RealtimeASR,J.RealtimeAudioTranslate,J.TR,J.ME]),Zi={standard:0,large:32e3,"extra-large":128e3},Qi=.4,$i=.6,ea=.4,ta=.2,na=.2,ra=.2;console.assert(Math.abs(Qi+$i-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(ea+ta+na+ra-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const ia=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
5
+ `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${ft(u)}`,p=pt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function dt(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function ft(e){return v(`sha256`).update(e,`utf8`).digest(`hex`)}function pt(e,t){return ee(`sha256`,e).update(t,`utf8`).digest(`hex`)}const mt=`${xe.cn}/api/v1/uploads`;async function ht(e,t,n){let r=`${mt}?action=getPolicy&model=${encodeURIComponent(t)}`,i=bt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...H()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new A(`Failed to get upload policy (HTTP ${a.status}): ${e}`,k.GENERAL)}return(await a.json()).data}async function gt(e,t,n){let r=m(t),i=`${e.upload_dir}/${r}`,a=o(t),s=new FormData;s.append(`OSSAccessKeyId`,e.oss_access_key_id),s.append(`Signature`,e.signature),s.append(`policy`,e.policy),s.append(`x-oss-object-acl`,e.x_oss_object_acl),s.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),s.append(`key`,i),s.append(`success_action_status`,`200`),s.append(`file`,new Blob([a]),r);let c=bt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...H()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new A(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,k.GENERAL)}return`oss://${i}`}async function _t(e){let{apiKey:t,model:n,filePath:r,signal:a}=e;if(!i(r))throw new A(`File not found: ${r}`,k.USAGE);if(!l(r).isFile())throw new A(`Not a file: ${r}`,k.USAGE);return gt(await ht(t,n,a),r,a)}function vt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function yt(e,t,n,r={}){return vt(e)?_t({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function bt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}function xt(e){return`/api/v1/mcps/${e}/mcp`}var St=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new A(`This command needs a model-domain API key.`,k.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new A(`MCP error (${r.error.code}): ${r.error.message}`,k.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...H()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new A(e,k.GENERAL)}return r}};const Ct={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function wt(e,t){return Ct[e]?.[t]??Ct[`cn-beijing`][t]}function Tt(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function Et(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function U(e,t,{api:n,data:r},i){let a=wt(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Et(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new A(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,k.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new A(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?k.AUTH:k.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var Dt=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new A(`This command needs a model-domain API key.`,k.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new A(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,k.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}url(e){return this.baseUrl+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return ot(this.http,this.toOpts(e))}requestJson(e){return ct(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return vt(e)?yt(e,this.requireApi().token,t,n):Promise.resolve(e)}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new St(this.http,t,this.deps.apiCred?.token)}async console(e,t){if(!this.deps.consoleCred)throw new A(`This command needs a console access token.`,k.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await U(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof A)||e.exitCode!==k.AUTH||!e.message.includes(`not logged in`))throw e;let t=await Mt({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await U({...this.deps.consoleCred,token:t},r,n,this.deps.settings)}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?lt(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=ut({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${tt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${tt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...H()},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new A(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,k.GENERAL)}if(!s.ok||l.Success===!1)throw new A(`${l.Code||s.status} - ${l.Message||s.statusText}`,k.GENERAL);return l}};const Ot={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function kt(e){for(let[t,n]of Object.entries(xe))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function At(e){return Ot[kt(e)]??Ot.cn}async function jt(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Dt({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=At(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function Mt(e){let t=e.settings.configName,n=B(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
6
+ `);let a=(await jt({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=B(t);return o.access_token=a,await V(o,t),a}function Nt(){return`/compatible-mode/v1/chat/completions`}function Pt(){return`/api/v1/services/aigc/image-generation/generation`}function Ft(){return`/api/v1/services/aigc/multimodal-generation/generation`}function It(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Lt(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Rt(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function zt(){return`/api/v2/apps/memory/add`}function Bt(){return`/api/v2/apps/memory/memory_nodes/search`}function Vt(){return`/api/v2/apps/memory/memory_nodes`}function Ht(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Ut(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Wt(){return`/api/v1/services/audio/asr/transcription`}function Gt(){return`/api/v2/apps/memory/profile_schemas`}function Kt(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function qt(){return`/api/v1/indices/rag/index/retrieve`}function Jt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Yt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Xt(){return`/api/v1/mcps/WebSearch/mcp`}function Zt(){return`/compatible-mode/v1/files`}function Qt(){return`/api/v1/files`}function $t(e){return`/api/v1/files/${encodeURIComponent(e)}`}function en(){return`/api/v1/fine-tunes`}function tn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function nn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function rn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function an(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function on(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function sn(){return`/api/v1/deployments`}function cn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function ln(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function un(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function dn(){return`/api/v1/deployments/models`}const fn=`2024-08-16`;function pn(e){return`bailiancontrol.${e}.aliyuncs.com`}function mn(e){return new Dt({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function hn(e){return mn(e).openApiJson({host:pn(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:fn,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function gn(e){return mn(e).openApiJson({host:pn(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:fn,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function _n(e){return mn(e).openApiJson({host:pn(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:fn,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}async function*vn(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new A(`SSE stream exceeded the maximum buffer size.`,k.GENERAL);let o=r.split(`
7
+ `);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new A(`SSE event exceeded the maximum buffer size.`,k.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const yn=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,bn=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function W(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function xn(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=W(await e(yn,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Sn(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=W(await e(yn,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Cn(e,t){return(W(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const wn=[`name`,`key`,`default`,`tip`,`range`];function Tn(e){return e.map(e=>{let t={};for(let n of wn)e[n]!==void 0&&(t[n]=e[n]);return t})}async function En(e,t){let n=W(await e(bn,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Tn(e):null}catch{return null}return Array.isArray(n)?Tn(n):null}function Dn(e){return{read:()=>B(e),async write(t){let n=B(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?j(String(r)):r;await V(n,e)},async unset(t){let n=B(e);for(let e of t)delete n[e];await V(n,e)},profiles:()=>Ke(),activate:e=>Ye(e),validateActivation:e=>Je(e),get path(){return F()}}}const On={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.7-max`,defaultImageModel:`qwen-image-2.0`}};function kn(e){return e?On[e]:void 0}async function An(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=re.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:Zt(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?new Date(f.created_at*1e3).toISOString():void 0};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new A(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,k.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new A(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,k.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function jn(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Qt(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Mn(e,t,n){return e.requestJson({path:$t(t),method:`GET`,signal:n})}async function Nn(e,t,n){let r=await e.request({path:$t(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Pn=300*1024*1024,Fn=1024*1024*1024;function In(e,t=Pn){if(!i(e))throw new A(`File not found: ${e}`,k.USAGE);let n=l(e);if(!n.isFile())throw new A(`Not a regular file: ${e}`,k.USAGE);if(n.size===0)throw new A(`File is empty: ${e}`,k.USAGE);if(n.size>t)throw new A(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,k.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function G(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function Ln(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new A(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,k.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function Rn(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const zn=new Set([`system`,`user`,`assistant`]);function Bn(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(G(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!zn.has(a))&&r.push(G(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(G(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function Vn(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(G(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(G(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...Bn(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(G(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(G(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(G(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(G(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const Hn={name:`chatml`,detect:()=>!0,inspect:Vn};function Un(e,t){let n=[];if(!(`text`in e))return n.push(G(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(G(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(G(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Wn={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Un};function Gn(e,t){let n=Vn(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(G(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(G(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...Bn(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(G(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...Bn(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(G(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Kn={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Gn};function qn(e,t){let n=[];if(!(`wav_fn`in e))n.push(G(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(G(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(G(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(G(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(G(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(G(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Jn={name:`tts`,detect:e=>`wav_fn`in e,inspect:qn},Yn=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function Xn(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Zn(e){return/^[\x20-\x7E]+$/.test(e)}function Qn(e,t){let n=[];if(!(`prompt`in e))n.push(G(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(G(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(G(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(G(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Xn(r);Yn.has(e)||n.push(G(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Yn].join(`, `)}.`,{line:t,path:`img_path`})),Zn(r)||n.push(G(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(G(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Xn(r);Yn.has(e)||n.push(G(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Yn].join(`, `)}.`,{line:t,path:`input_img`})),Zn(r)||n.push(G(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const $n={name:`image`,detect:e=>`img_path`in e,inspect:Qn},er=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),tr=new Set([`.mp4`,`.mov`]);function nr(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function rr(e){return/^[\x20-\x7E]+$/.test(e)}function ir(e,t,n,r,i,a){if(!(n in t)){r&&e.push(G(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(G(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(G(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=nr(o);i.has(s)||e.push(G(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),rr(o)||e.push(G(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function ar(e,t){let n=[];if(!(`prompt`in e))n.push(G(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(G(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return ir(n,e,`first_frame_path`,!0,er,t),ir(n,e,`last_frame_path`,!1,er,t),ir(n,e,`video_path`,!1,tr,t),n}const or=[Jn,$n,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:ar},Kn,Wn,Hn];function sr(e,t){return t===void 0?or.find(t=>t.detect(e))??Hn:or.find(e=>e.name===t)||Hn}async function cr(e,t){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(G(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function lr(e,t,r,i,a){let o=r?null:new Set(Rn(t)),s=[],c=0,l=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(G(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...ur(n,u,i))}return{sampled:c,issues:s}}function ur(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[G(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return sr(r,n).inspect(r,t)}const dr={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await cr(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[G(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await lr(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function fr(e,t){return new Promise((n,r)=>{ae.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function pr(e){return new Promise((t,n)=>{ae.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function mr(e,t,n){let{entry:i,zipfile:a}=await fr(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}ie(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function hr(e,t=100){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const gr={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await pr(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[G(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[G(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(G(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(G(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Yn.has(n)});e.length<25&&r.push(G(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${te(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await mr(e,m,_)}catch(t){return r.push(G(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await dr.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await hr(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(G(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function _r(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return vr(e);if(t===`.zip`)return yr(e);throw new A(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,k.USAGE)}async function vr(e){let t=await xr(e);if(!t)throw new A(`JSONL file is empty or contains only blank lines: ${e}`,k.USAGE);let n=br(t);return n===`unknown`?`text`:n}async function yr(e){let t=await Sr(e,`data.jsonl`);if(!t)throw new A(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,k.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=br(t);if(n===`unknown`)throw new A(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,k.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function br(e){let t;try{t=JSON.parse(e)}catch{throw new A(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,k.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new A(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,k.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function xr(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=y({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Sr(e,t){return fr(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new A(`Failed to read "${t}" from ZIP: ${e?.message}`,k.USAGE));return}let o=y({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Cr=[dr,gr];function wr(e){let t=h(e).toLowerCase(),n=Cr.find(e=>e.extensions.includes(t));if(!n){let e=Cr.flatMap(e=>e.extensions).join(`, `);throw new A(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,k.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Tr(e){Cr.some(t=>t.format===e.format)||Cr.push(e)}async function K(e,t={}){let{bytes:n}=In(e,t.maxBytes??314572800),r=await wr(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Er(){return Cr.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Dr(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}async function Or(e,t,n){return e.requestJson({path:en(),method:`POST`,body:t,signal:n})}async function kr(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=en(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ar(e,t,n){return e.requestJson({path:tn(t),method:`GET`,signal:n})}async function jr(e,t,n){return e.requestJson({path:nn(t),method:`POST`,signal:n})}async function Mr(e,t,n){return e.requestJson({path:tn(t),method:`DELETE`,signal:n})}async function Nr(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=rn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Pr(e,t,n){return e.requestJson({path:an(t),method:`GET`,signal:n})}async function Fr(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${on(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const Ir={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},Lr=Object.keys(Ir),Rr=`sft-lora`;function zr(e){return e in Ir}function Br(e){let{method:t,variant:n}=Ir[e];return{method:t,variant:n}}function Vr(e,t){if(!e)return!1;let{method:n,variant:r}=Ir[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Hr(e){return e?Lr.filter(t=>Vr(e,t)):[]}async function Ur(e,t){let n=Tt(e);return(await xn((t,r)=>U({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const Wr=`INSUFFICIENT_SAMPLES`;function Gr(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Wr,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
8
+ `)}}function Kr(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function qr(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return K(e,{...r,schema:n})},resolveHyperParameters(e,t){return Kr(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const Jr=qr(`sft`,`sft`,`chatml`),Yr={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},Xr={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},Zr={...Xr,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Qr={n_epochs:400,learning_rate:`2e-5`,split:.9,max_split_val_dataset_sample:5,eval_epochs:50,save_total_limit:10,lora_rank:32,lora_alpha:32};function $r(e){return e===`image`||e===`image-i2i`}function ei(e){return e===`video`||e===`video-kf2v`}function ti(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const ni=[Jr,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return K(e,{...n,schema:`tts`});if($r(t))return K(e,{...n,schema:`image`,maxBytes:Fn});if(ei(t)){let r=await K(e,{...n,schema:`video`,maxBytes:Fn});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(G(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(G(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return K(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Yr};if($r(e)){let n={...e===`image-i2i`?Zr:Xr};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(ei(e)){let e=ti(t.model),n={...Qr,batch_size:4,max_pixels:e?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return Kr(t)},shouldSkipGate(e,t){return!!((t===`audio`||$r(t)||ei(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||$r(e)||ei(e)}},qr(`dpo`,`dpo_full`,`dpo`),qr(`dpo-lora`,`dpo_lora`,`dpo`),qr(`cpt`,`cpt`,`cpt`)];function ri(e){let t=ni.find(t=>t.clientTrainingType===e);if(!t){let t=ni.map(e=>e.clientTrainingType).join(`, `);throw new A(`Unknown training type "${e}".`,k.USAGE,`Supported training types: ${t}.`)}return t}function ii(){return ni.map(e=>e.clientTrainingType)}async function ai(e,t,n){return e.requestJson({path:sn(),method:`POST`,body:t,signal:n})}async function oi(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=sn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function si(e,t,n){return e.requestJson({path:cn(t),method:`GET`,signal:n})}async function ci(e,t,n){return e.requestJson({path:cn(t),method:`DELETE`,signal:n})}async function li(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=dn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ui(e,t,n,r){return e.requestJson({path:ln(t),method:`PUT`,body:n,signal:r})}async function di(e,t,n,r){return e.requestJson({path:un(t),method:`PUT`,body:n,signal:r})}const q={LORA:`lora`,PTU:`ptu`,MU:`mu`},fi=q.LORA;function pi(e){return e===`audio`?q.MU:fi}const mi={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},hi=mi.POST_PAY,gi={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},_i={name:q.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},vi={name:q.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},yi={name:q.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||hi,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new A(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,k.USAGE);try{let a=await li(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===q.MU)?.templates??[];if(o.length===0)throw i();let s=t===mi.POST_PAY?gi.POST_PAID:gi.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof A?e:new A(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,k.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},bi={[q.LORA]:_i,[q.PTU]:vi,[q.MU]:yi};function xi(e){let t=bi[e];if(!t)throw new A(`Unsupported plan "${e}". Supported plans: ${Object.keys(bi).join(`, `)}.`,k.USAGE);return t}const Si={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},config:{type:`string`,valueHint:`<name>`,description:`Use a config profile for this command`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},Ci={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},wi={async:{type:`switch`,description:`Return async task id without waiting`}},Ti={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},Ei={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},Di={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`},securityToken:{type:`string`,valueHint:`<token>`,description:`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`}};function Oi(e){return e.auth===`apiKey`?Ti:e.auth===`console`?Ei:e.auth===`openapi`?Di:{}}function ki(e){return e}const Ai=1;function ji(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Mi(e,t){return`${ji(e||`image`,`image`)}_${ji((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Ni=()=>g(f(),`bailian-output`);function Pi(e,t){let n=t?.flagDir||e.outputDir||Ni(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Fi(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Ii(e){return o(e===`-`?0:e,`utf-8`)}function Li(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new A(`Invalid ${t} value "${String(e)}". Use true or false.`,k.USAGE)}function Ri(e,t=`boolean`){if(e!=null)return Li(e,t)}function zi(e,t,n=`boolean`){let r=Ri(e,n);return r===void 0?t:r}function Bi(e){return Ri(e,`watermark`)??!0}function Vi(e){let t={command:e.command,timestamp:new Date().toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform};return e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function Hi(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Ui(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=Hi(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let Wi;function Gi(){return Wi||(process.env.NODE_ENV===`development`?(Wi=`dev`,Wi):(Wi=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,Wi))}var Ki=me(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=he(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=he(`dns`)},function(e,t){e.exports=he(`util`)},function(e,t){e.exports=he(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ne=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},C=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},pe=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},D=new Map,O=new Map;D.set(`Baiduspider-render`,i),D.set(`Baiduspider+`,i),D.set(`Baiduspider-image+`,i),D.set(`360Spider`,a),D.set(`360Spider-Image`,a),D.set(`bingbot`,o),D.set(`Googlebot`,s),D.set(`YandexRenderResourcesBot`,c),D.set(`spider`,l),D.set(`Dataprovider.com`,u),D.set(`AhrefsBot`,d),D.set(`BitSightBot`,f),D.set(`oBot`,p),D.set(`Cincraw`,m),D.set(`DingTalkBot-LinkService`,h),D.set(`YisouSpider`,g),D.set(`Bytespider`,_),D.set(`ev-crawler`,v),D.set(`bitdiscovery`,ee),D.set(`Spider`,te),D.set(`Ai2Bot-Dolma`,ne),D.set(`dianjing_ad_spider`,re),O.set(`Baiduspider-render`,y),O.set(`Baiduspider+`,y),O.set(`Baiduspider-image+`,y),O.set(`360Spider`,ie),O.set(`360Spider-Image`,ie),O.set(`bingbot`,ae),O.set(`Googlebot`,b),O.set(`YandexRenderResourcesBot`,x),O.set(`spider`,S),O.set(`Dataprovider.com`,C),O.set(`AhrefsBot`,oe),O.set(`BitSightBot`,se),O.set(`oBot`,w),O.set(`Cincraw`,T),O.set(`DingTalkBot-LinkService`,ce),O.set(`YisouSpider`,le),O.set(`Bytespider`,ue),O.set(`ev-crawler`,de),O.set(`bitdiscovery`,fe),O.set(`Spider`,E),O.set(`Ai2Bot-Dolma`,pe),O.set(`dianjing_ad_spider`,me);let he={productHandlerMap:D,commentHandlerMap:O,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,he),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function ee(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}ee.prototype={constructor:ee,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var te=ee,ne=n(3),re=n.n(ne),y=n(4),ie=n(5),ae=n.n(ie);function b(e){return(b=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function x(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function S(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?x(Object(n),!0).forEach(function(t){C(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):x(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function C(e,t,n){return(t=(function(e){var t=(function(e,t){if(b(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(b(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return b(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oe(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=w(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
9
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function se(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||w(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
10
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function w(e,t){if(e){if(typeof e==`string`)return T(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}function T(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ce(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=se(r[n],2),o=(a[0],a[1]);if(o){var s,c=oe(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var le,ue,de=(le=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:le,device_id:ae.a.createHash(`md5`).update(ce()).digest(`hex`),platform:`node`}),fe=(0,y.promisify)(re.a.resolve);function E(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,te.call(this,S(S({},de),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}E.prototype=((ue=function(){}).prototype=te.prototype,new ue),E.prototype.constructor=E,E.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,fe(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=E}]).default})),qi=me(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=0)})([function(e,t,n){n.r(t);var r=[`ec`,`ea`,`el`,`et`],i=function(e,t){var n=function(e){var n=e.ec,r=e.ea,i=e.el,a=e.et,o=a===void 0?`CLK`:a,s=e.xpath;delete e.ec,delete e.ea,delete e.el,delete e.et,delete e.xpath,e.p1=n,e.p2=r,e.p3=i,e.p4=o,e.p5=s;try{t.log(`event`,e)}catch{}};return function(){var t=arguments,i={};if(t.length!==0){for(var a=0;a<t.length;a++){var o,s,c=t[a];if(a!==0&&typeof c==`object`&&a!==t.length-1)return void(e==null||(o=e.console)==null||(s=o.warn)==null||s.call(o,`Only the last argument can be object type`));if(typeof c==`string`||typeof c==`number`)i[r[a]]=c;else if(typeof c==`object`&&a===t.length-1)for(var l in c)c.hasOwnProperty(l)&&(i[l]=c[l])}n(i)}else{var u,d;(u=e.console)==null||(d=u.warn)==null||d.call(u,`At lease one augument`)}}};t.default=function(e,t){return i(global,e)}}]).default})),Ji=O(Ki(),1),Yi=O(qi(),1);const Xi=()=>g(P(),`telemetry.jsonl`);let Zi;const Qi=new Set;let $i;try{let e=new Ji.default({pid:`bailian-cli-node`,env:Gi()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;Qi.add(e),e.finally(()=>Qi.delete(e))}return n},$i=e,Zi=e.use(Yi.default)}catch{}async function ea(e=1e3){try{if($i)try{typeof $i._sendAll==`function`&&$i._sendAll()}catch{}if(Qi.size===0)return;let t=[...Qi].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function ta(e){try{await Ie();let n=Xi();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
11
+ `,{mode:384})}catch{}}async function na(e){try{if(!Zi)return;Zi(e.command,Ui(e))}catch{}}const ra=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),ia=new Set(`page.pageSize.n.count.model.voice.language.provider.capability.temperature.topP.topK.maxTokens.seed.stream.size.resolution.ratio.duration.format.audioFormat.sampleRate.pitch.rate.volume.api.mode.download.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function aa(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||ra.has(n)||ia.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function oa(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof A?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=Vi({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.identity.version,authMethod:e.authMethod,params:aa(n)});ta(l).catch(()=>{}),na(l).catch(()=>{})}}function sa(e){if(!e.model)return null;let t=e.inferenceMetadata;return{model:e.model,name:e.name??e.model,description:e.description??e.shortDescription??``,shortDescription:e.shortDescription,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],category:e.category,contextWindow:e.contextWindow??void 0,maxOutputTokens:e.maxOutputTokens??void 0,maxInputTokens:e.maxInputTokens??void 0,docUrl:e.docUrl,collectionTag:e.collectionTag,inferenceMetadata:t,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource}}var ca=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=Tt(this.settings),t=(t,n)=>U({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await xn(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await xn(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(sa).filter(e=>e!==null)}};const la=`models.jsonl`;function ua(){return T(P(),`skills/bailian-docs-llm-wiki`)}function da(){return T(ua(),la)}function fa(){return T(w(ce(import.meta.url)),`../../../../../skills/bailian-docs-llm-wiki/models`)}function pa(e){return!e.model||typeof e.model!=`string`?null:{model:e.model,name:e.name??e.model,description:e.description??``,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,docUrl:e.docUrl,inferenceMetadata:e.inferenceMetadata,shortDescription:e.shortDescription,category:e.category,collectionTag:e.collectionTag,maxInputTokens:e.maxInputTokens,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource,family:e.family,familyName:e.familyName}}function ma(e){let t=C(e,`utf-8`).split(`
12
+ `).filter(Boolean),n=[];for(let e of t)try{let t=pa(JSON.parse(e));t&&n.push(t)}catch{}return n}function ha(){let e=fa();if(!x(T(e,la)))return!1;let t=ua();try{return S(t,{recursive:!0}),b(e,t,{recursive:!0}),!0}catch{return!1}}var ga=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return x(da())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!ha())?[]:ma(da())}};async function _a(e,t){let n=[new ga({onPrepareStart:t?.onPrepareStart}),new ca(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new A(`No model data available.`,k.GENERAL)}const va={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},J={Single:`single`,Pipeline:`pipeline`},ya={Low:`low`,Medium:`medium`,High:`high`},ba={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Y={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},X={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},xa={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Z={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Sa=20,Ca=/-\d{4}-\d{2}-\d{2}$/,wa=new Set([X.IG,X.VG,X.TTS,X.RealtimeTTS,X.ThreeDGeneration]),Ta=new Set([X.TG,X.Reasoning,X.ASR,X.RealtimeASR,X.RealtimeAudioTranslate,X.TR,X.ME]),Ea={standard:0,large:32e3,"extra-large":128e3},Da=.4,Oa=.6,ka=.4,Aa=.2,ja=.2,Ma=.2;console.assert(Math.abs(Da+Oa-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(ka+Aa+ja+Ma-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Na=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
12
13
 
13
14
  CRITICAL: You MUST respond entirely in English. Do not use any Chinese characters anywhere in your response. Every field — reason, highlights, step, summary — must be written in English.
14
15
 
@@ -49,7 +50,7 @@ Single task:
49
50
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
50
51
 
51
52
  Pipeline (only when confident multi-model is needed):
52
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,aa=`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's need has been decomposed into multi-step pipeline. Select the best model for each step.
53
+ {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Pa=`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's need has been decomposed into multi-step pipeline. Select the best model for each step.
53
54
 
54
55
  CRITICAL: You MUST respond entirely in English. Do not use any Chinese characters anywhere in your response. Every field — reason, highlights, step, summary — must be written in English.
55
56
 
@@ -88,7 +89,7 @@ Key principles:
88
89
 
89
90
  Or (if single model suffices):
90
91
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
91
- ["key highlights"]}]}`,X={complexity:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[J.TG],requiredFeatures:[],budget:Wi.Medium,contextNeed:Gi.Standard,qualityPreference:q.Balanced,confidence:0},oa=[`unconstrained`,`scoped`,`comparison`,`alternative`];function sa(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&oa.includes(e.mode)?e.mode:`unconstrained`,n=Array.isArray(e.targets)?e.targets.filter(e=>typeof e==`string`):[],r=Array.isArray(e.excludes)?e.excludes.filter(e=>typeof e==`string`):[];return{mode:t,targets:n.length>0?n:void 0,excludes:r.length>0?r:void 0}}async function ca(e,t){let n=He(),r={model:`qwen3.6-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
92
+ ["key highlights"]}]}`,Fa={complexity:J.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[X.TG],requiredFeatures:[],budget:ya.Medium,contextNeed:ba.Standard,qualityPreference:Y.Balanced,confidence:0},Ia=[`unconstrained`,`scoped`,`comparison`,`alternative`];function La(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Ia.includes(e.mode)?e.mode:`unconstrained`,n=Array.isArray(e.targets)?e.targets.filter(e=>typeof e==`string`):[],r=Array.isArray(e.excludes)?e.excludes.filter(e=>typeof e==`string`):[];return{mode:t,targets:n.length>0?n:void 0,excludes:r.length>0?r:void 0}}async function Ra(e,t){let n=Nt(),r={model:`qwen3.6-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
92
93
 
93
94
  CRITICAL: You MUST respond entirely in English. Do not use any Chinese characters anywhere in your response. All text fields (taskSummary, scenarioHints) must be in English.
94
95
 
@@ -135,9 +136,9 @@ Analyze whether the user mentioned specific models, model families, or vendors:
135
136
  - semanticQuery: a self-contained English phrase (15-30 words) describing the need in a form optimized for semantic matching against model descriptions — fold in scenario, modalities, and key constraints; do not just copy the user's wording
136
137
  - modelPreference: { mode, targets?, excludes? }
137
138
 
138
- Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0},i;try{i=await e.requestJson({path:n,method:`POST`,body:r,timeout:30})}catch{return{...X}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...X};let o=JSON.parse(a[0]),s=o.modelPreference,c=sa(s);return{complexity:o.complexity===K.Pipeline?K.Pipeline:K.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??X.budget,contextNeed:o.contextNeed??X.contextNeed,qualityPreference:o.qualityPreference??X.qualityPreference,confidence:1,modelPreference:c}}function la(e){let t=!1,n=!1;for(let r of e)Yi.has(r)&&(t=!0),Xi.has(r)&&(n=!0);return t&&n}function ua(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Ji,``);return n===e?!0:!t.has(n)})}function da(e,t,n){let r=e.inferenceMetadata?.request_modality??[],i=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&!t.some(e=>r.includes(e))||n.length>0&&!n.some(e=>i.includes(e)))}function fa(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function pa(e,t){let{requiredCapabilities:n,requiredFeatures:r,contextNeed:i,qualityPreference:a}=t,{capabilities:o,features:s,contextWindow:c,category:l}=e,u=0;for(let e of n)o.includes(e)&&(u+=10);for(let e of r)s.includes(e)&&(u+=5);let d=Zi[i];return d>0&&(c??0)>=d&&(u+=8),a===q.Flagship&&l===Y.Flagship||a===q.CostOptimized&&l===Y.CostOptimized?u+=15:a===q.Balanced&&l===Y.Flagship&&(u+=5),u}function Z(e,t,n){return e.map(e=>({model:e,score:pa(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function ma(e){return new Set(e.map(({model:e})=>e.model))}function ha(e,t){let n=new Map,r=[],i=[];for(let a of e){let e=a.model.family;if(!e){r.push(a);continue}let o=n.get(e)??0;o<t?(r.push(a),n.set(e,o+1)):i.push(a)}return r.length>=10?r:[...r,...i.slice(0,10-r.length)]}function ga(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function _a(e,t,n){return n.size>=10?[]:Z(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function va(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:Gi.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>da(e,a,o)&&fa(e,n));return l.length<5&&(l=e.filter(e=>da(e,a,o))),l.length<5&&(l=e),Z(l,c,5)}function ya(e,t){e=ua(e);let n;if(t.complexity===K.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=ga(va(e,i,a,t.budget,t.qualityPreference),ma(r));r=[...r,...o]}let i=_a(e,t,ma(r));n=[...r,...i]}else if(la(t.requiredCapabilities))n=ba(e,t);else{let r=e.filter(e=>da(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Z(r,t,50)}return ha(n,3)}function ba(e,t){let n=t.requiredCapabilities.filter(e=>Yi.has(e)),r=t.requiredCapabilities.filter(e=>Xi.has(e)),i=[];if(n.length>0&&(i=Z(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=ma(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Z(o,a,25)]}let a=_a(e,t,ma(i));return[...i,...a]}const xa=`text-embedding-v4`;function Sa(){return E(P(),`skills/bailian-docs-llm-wiki`)}function Ca(){return E(Sa(),`models-embeddings.json`)}function wa(){let e=Ca();if(!S(e))return null;try{return JSON.parse(w(e,`utf-8`)).items}catch{return null}}async function Ta(e,t){let n={model:xa,input:[t],dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:1e4})).data[0].embedding}async function Ea(e,t){let n={model:xa,input:t,dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:3e4})).data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}const Da={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Oa={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function ka(){let e=E(Sa(),`groups`),t=new Map;if(!S(e))return t;for(let n of ae(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(w(E(e,n),`utf-8`)),i=r.description??``;if(r.items)for(let e of r.items)t.set(e.model,e.description||i)}catch{}return t}function Aa(e,t){let n=(e.capabilities??[]).map(e=>Da[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Oa[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Oa[e]??e).join(`, `);return[e.name,e.model,r,n?`Capabilities: ${n}`:``,i?`Input: ${i}`:``,a?`Output: ${a}`:``,e.features?.length?`Features: ${e.features.join(`, `)}`:``,e.familyName||``,e.category?`Category: ${e.category}`:``].filter(Boolean).join(` | `)}async function ja(e,t){let n=ka(),r=t.map(e=>Aa(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Ea(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:xa,dimensions:512,count:a.length,items:a},s=Ca();return C(T(s),{recursive:!0}),oe(s,JSON.stringify(o)),a}function Ma(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}let Q=null;function Na(){return Q===null&&(Q=wa()),Q}function Pa(){return Na()!==null}function $(e){return(e??``).toLowerCase().replace(Ji,``).replace(/[\s_-]+/g,``).trim()}function Fa(e,t){let n=$(t);if(!n)return!1;if($(e.model)===n||$(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&$(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=$(e);return t.length>0&&n.includes(t)})}function Ia(e,t){return t.some(t=>Fa(e,t))}function La(e,t){return t.length===0?[]:e.filter(e=>Ia(e,t))}function Ra(e,t){return t.length===0?e:e.filter(({model:e})=>!Ia(e,t))}function za(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&!t.some(e=>i.includes(e))||n.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function Ba(e,t){return za(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Va(e,t){let{requiredCapabilities:n,requiredFeatures:r,contextNeed:i,qualityPreference:a}=t,o=1;n.length>0&&(o=n.filter(t=>e.capabilities.includes(t)).length/n.length);let s=1;r.length>0&&(s=r.filter(t=>e.features.includes(t)).length/r.length);let c=1,l=Zi[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===q.Flagship?u=e.category===Y.Flagship?1:.5:a===q.CostOptimized&&(u=e.category===Y.CostOptimized?1:.5),ea*o+ta*s+na*c+ra*u}function Ha(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Ba(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function Ua(e,t){return za(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Wa(e,t,n,r,i,a){let o=e.filter(e=>n.has(e.id)).flatMap(e=>{let n=i.get(e.id);if(!n)return[];let r=Ma(t,e.vector),o=a?Va(n,a):0;return[{model:n,score:a?Qi*o+$i*r:r,hardScore:a?o:void 0,softScore:r}]}),s=o.filter(e=>(e.softScore??0)>=.3);return(s.length>=10?s:o).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,r))}function Ga(e){return{model:e,score:1,hardScore:1,softScore:1}}function Ka(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?La(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Ga(e));let r=new Set(l.map(({model:e})=>e.model)),s=Wa(t,n,Ha(e,o),i,a,o);for(let e of s)if(!r.has(e.model.model)&&(l.push(e),l.length>=i))break;return l}return Wa(t,n,Ha(c,o),i,a,o)}function qa(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)Ia(t,s)&&!l.has(t.model)&&(c.push(Ga(t)),l.add(t.model));return c}function Ja(e,t,n,r,i,a,o){let s=La(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Ga(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Wa(t,n,Ha(e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),o),d,a,o);for(let e of r)l.push(e)}return l}async function Ya(e,t,n,r,i){let a=Na();if(!a)a=await ja(e,t),Q=a;else{let n=new Set(a.map(e=>e.id)),r=new Set(t.map(e=>e.model)),i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}i&&(a=await ja(e,t),Q=a)}let o=await Ta(e,i?.semanticQuery?.trim()||n),s=new Map(t.map(e=>[e.model,e])),c=i?.modelPreference,l=c?.excludes??[];if(c&&c.mode!==`unconstrained`){let e;switch(c.mode){case`scoped`:e=Ka(t,a,o,c,r,s,i);break;case`comparison`:e=qa(t,a,o,c,r,s,i);break;case`alternative`:e=Ja(t,a,o,c,r,s,i);break;default:e=[]}return Ra(e,l)}if(i?.complexity===K.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>Ua(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Wa(a,o,u,c,s,i);for(let t of d)e.has(t.model.model)||(n.push(t),e.add(t.model.model))}return Ra(n,l)}let u=Ha(t,i);return Ra(Wa(a,o,u,r,s,i),l)}function Xa(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Za(e){return e.map(({model:e})=>{let t=[`ID: ${e.model}`,`Name: ${e.name}`,`Description: ${e.shortDescription||e.description}`,`Capabilities: ${e.capabilities.join(`, `)}`,`Features: ${e.features.join(`, `)}`];e.contextWindow&&t.push(`Context Window: ${e.contextWindow}`),e.maxOutputTokens&&t.push(`Max Output: ${e.maxOutputTokens}`),e.category&&t.push(`Category: ${e.category}`);let n=e.inferenceMetadata;n?.request_modality?.length&&t.push(`Input Modality: ${n.request_modality.join(`, `)}`),n?.response_modality?.length&&t.push(`Output Modality: ${n.response_modality.join(`, `)}`);let r=Xa(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
139
- `)}function Qa(e){let{taskSummary:t,scenarioHints:n,inputModality:r,outputModality:i,requiredCapabilities:a,requiredFeatures:o,budget:s,qualityPreference:c,contextNeed:l,segments:u,modelPreference:d}=e,f=[];if(t&&f.push(`Task: ${t}`),n.length&&f.push(`Scenario: ${n.join(`, `)}`),r.length&&f.push(`Input: ${r.join(`, `)}`),i.length&&f.push(`Output: ${i.join(`, `)}`),a.length&&f.push(`Capabilities: ${a.join(`, `)}`),o.length&&f.push(`Features: ${o.join(`, `)}`),f.push(`Budget: ${s}`),f.push(`Quality: ${c}`),l!==Gi.Standard&&f.push(`Context: ${l}`),d&&d.mode!==`unconstrained`&&(f.push(`Mode: ${d.mode}`),d.targets?.length&&f.push(`Targets: ${d.targets.join(`, `)}`),d.excludes?.length&&f.push(`Excludes: ${d.excludes.join(`, `)}`)),u?.length){f.push(`Pipeline Steps:`);for(let e of u){let t=e.inputModality.join(`,`)||`none`,n=e.outputModality.join(`,`)||`none`,r=e.requiredCapabilities.join(`,`)||`none`;f.push(` - ${e.step} (Input: ${t} → Output: ${n}, Capabilities: ${r})`)}}return f.join(`
140
- `)}function $a(e){if(!e)return;let t=e.match(/\/(\d+)\.html/);if(t)return`https://bailian.console.aliyun.com/cn-beijing?tab=doc#/doc/?type=model&url=${t[1]}`}function eo(e,t,n){let r=Array.isArray(e)?e:[],i=[],a=new Set;for(let e of r){let r=t.get(e.model);if(!r||r.family&&a.has(r.family))continue;r.family&&a.add(r.family);let{model:o,name:s,category:c,contextWindow:l,maxOutputTokens:u,docUrl:d}=r;if(i.push({model:o,name:s,reason:e.reason??``,highlights:e.highlights??[],category:c,contextWindow:l,maxOutputTokens:u,docUrl:d}),i.length>=n)break}return i}function to(e,t){for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n],a=new Set(r.recommendations.flatMap(e=>t.get(e.model)?.inferenceMetadata?.response_modality??[]));if(a.size===0)continue;let o=[];for(let e of i.recommendations){let n=t.get(e.model)?.inferenceMetadata?.request_modality??[];!n.some(e=>a.has(e))&&n.length>0&&o.push(`${e.name}'s input modalities [${n.join(`, `)}] may not be compatible with the previous step's output modalities [${[...a].join(`, `)}]`)}o.length>0&&(i.warnings=o)}}async function no(e,t,n,r,i,a){let o=Za(t),s=Qa(n),c=n.modelPreference?.mode,l;if(c===`comparison`)l=`You are a model comparison advisor for Alibaba Cloud Model Studio. The user wants to compare specific models — analyze them against the use case.
139
+ Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0},i;try{i=await e.requestJson({path:n,method:`POST`,body:r,timeout:30})}catch{return{...Fa}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Fa};let o=JSON.parse(a[0]),s=o.modelPreference,c=La(s);return{complexity:o.complexity===J.Pipeline?J.Pipeline:J.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Fa.budget,contextNeed:o.contextNeed??Fa.contextNeed,qualityPreference:o.qualityPreference??Fa.qualityPreference,confidence:1,modelPreference:c}}function za(e){let t=!1,n=!1;for(let r of e)wa.has(r)&&(t=!0),Ta.has(r)&&(n=!0);return t&&n}function Ba(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Ca,``);return n===e?!0:!t.has(n)})}function Va(e,t,n){let r=e.inferenceMetadata?.request_modality??[],i=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&!t.some(e=>r.includes(e))||n.length>0&&!n.some(e=>i.includes(e)))}function Ha(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Ua(e,t){let{requiredCapabilities:n,requiredFeatures:r,contextNeed:i,qualityPreference:a}=t,{capabilities:o,features:s,contextWindow:c,category:l}=e,u=0;for(let e of n)o.includes(e)&&(u+=10);for(let e of r)s.includes(e)&&(u+=5);let d=Ea[i];return d>0&&(c??0)>=d&&(u+=8),a===Y.Flagship&&l===Z.Flagship||a===Y.CostOptimized&&l===Z.CostOptimized?u+=15:a===Y.Balanced&&l===Z.Flagship&&(u+=5),u}function Q(e,t,n){return e.map(e=>({model:e,score:Ua(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Wa(e){return new Set(e.map(({model:e})=>e.model))}function Ga(e,t){let n=new Map,r=[],i=[];for(let a of e){let e=a.model.family;if(!e){r.push(a);continue}let o=n.get(e)??0;o<t?(r.push(a),n.set(e,o+1)):i.push(a)}return r.length>=10?r:[...r,...i.slice(0,10-r.length)]}function Ka(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function qa(e,t,n){return n.size>=10?[]:Q(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Ja(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:J.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:ba.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Va(e,a,o)&&Ha(e,n));return l.length<5&&(l=e.filter(e=>Va(e,a,o))),l.length<5&&(l=e),Q(l,c,5)}function Ya(e,t){e=Ba(e);let n;if(t.complexity===J.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=Ka(Ja(e,i,a,t.budget,t.qualityPreference),Wa(r));r=[...r,...o]}let i=qa(e,t,Wa(r));n=[...r,...i]}else if(za(t.requiredCapabilities))n=Xa(e,t);else{let r=e.filter(e=>Va(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Q(r,t,50)}return Ga(n,3)}function Xa(e,t){let n=t.requiredCapabilities.filter(e=>wa.has(e)),r=t.requiredCapabilities.filter(e=>Ta.has(e)),i=[];if(n.length>0&&(i=Q(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Wa(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Q(o,a,25)]}let a=qa(e,t,Wa(i));return[...i,...a]}const Za=`text-embedding-v4`;function Qa(){return T(P(),`skills/bailian-docs-llm-wiki`)}function $a(){return T(Qa(),`models-embeddings.json`)}function eo(){let e=$a();if(!x(e))return null;try{return JSON.parse(C(e,`utf-8`)).items}catch{return null}}async function to(e,t){let n={model:Za,input:[t],dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:1e4})).data[0].embedding}async function no(e,t){let n={model:Za,input:t,dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:3e4})).data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}const ro={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},io={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function ao(){let e=T(Qa(),`groups`),t=new Map;if(!x(e))return t;for(let n of oe(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(C(T(e,n),`utf-8`)),i=r.description??``;if(r.items)for(let e of r.items)t.set(e.model,e.description||i)}catch{}return t}function oo(e,t){let n=(e.capabilities??[]).map(e=>ro[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>io[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>io[e]??e).join(`, `);return[e.name,e.model,r,n?`Capabilities: ${n}`:``,i?`Input: ${i}`:``,a?`Output: ${a}`:``,e.features?.length?`Features: ${e.features.join(`, `)}`:``,e.familyName||``,e.category?`Category: ${e.category}`:``].filter(Boolean).join(` | `)}async function so(e,t){let n=ao(),r=t.map(e=>oo(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await no(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Za,dimensions:512,count:a.length,items:a},s=$a();return S(w(s),{recursive:!0}),se(s,JSON.stringify(o)),a}function co(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}let lo=null;function uo(){return lo===null&&(lo=eo()),lo}function fo(){return uo()!==null}function po(e){return(e??``).toLowerCase().replace(Ca,``).replace(/[\s_-]+/g,``).trim()}function mo(e,t){let n=po(t);if(!n)return!1;if(po(e.model)===n||po(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&po(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=po(e);return t.length>0&&n.includes(t)})}function ho(e,t){return t.some(t=>mo(e,t))}function go(e,t){return t.length===0?[]:e.filter(e=>ho(e,t))}function _o(e,t){return t.length===0?e:e.filter(({model:e})=>!ho(e,t))}function vo(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&!t.some(e=>i.includes(e))||n.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function yo(e,t){return vo(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function bo(e,t){let{requiredCapabilities:n,requiredFeatures:r,contextNeed:i,qualityPreference:a}=t,o=1;n.length>0&&(o=n.filter(t=>e.capabilities.includes(t)).length/n.length);let s=1;r.length>0&&(s=r.filter(t=>e.features.includes(t)).length/r.length);let c=1,l=Ea[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===Y.Flagship?u=e.category===Z.Flagship?1:.5:a===Y.CostOptimized&&(u=e.category===Z.CostOptimized?1:.5),ka*o+Aa*s+ja*c+Ma*u}function xo(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>yo(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function So(e,t){return vo(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function $(e,t,n,r,i,a){let o=e.filter(e=>n.has(e.id)).flatMap(e=>{let n=i.get(e.id);if(!n)return[];let r=co(t,e.vector),o=a?bo(n,a):0;return[{model:n,score:a?Da*o+Oa*r:r,hardScore:a?o:void 0,softScore:r}]}),s=o.filter(e=>(e.softScore??0)>=.3);return(s.length>=10?s:o).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,r))}function Co(e){return{model:e,score:1,hardScore:1,softScore:1}}function wo(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?go(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Co(e));let r=new Set(l.map(({model:e})=>e.model)),s=$(t,n,xo(e,o),i,a,o);for(let e of s)if(!r.has(e.model.model)&&(l.push(e),l.length>=i))break;return l}return $(t,n,xo(c,o),i,a,o)}function To(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)ho(t,s)&&!l.has(t.model)&&(c.push(Co(t)),l.add(t.model));return c}function Eo(e,t,n,r,i,a,o){let s=go(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Co(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=$(t,n,xo(e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),o),d,a,o);for(let e of r)l.push(e)}return l}async function Do(e,t,n,r,i){let a=uo();if(!a)a=await so(e,t),lo=a;else{let n=new Set(a.map(e=>e.id)),r=new Set(t.map(e=>e.model)),i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}i&&(a=await so(e,t),lo=a)}let o=await to(e,i?.semanticQuery?.trim()||n),s=new Map(t.map(e=>[e.model,e])),c=i?.modelPreference,l=c?.excludes??[];if(c&&c.mode!==`unconstrained`){let e;switch(c.mode){case`scoped`:e=wo(t,a,o,c,r,s,i);break;case`comparison`:e=To(t,a,o,c,r,s,i);break;case`alternative`:e=Eo(t,a,o,c,r,s,i);break;default:e=[]}return _o(e,l)}if(i?.complexity===J.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>So(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=$(a,o,u,c,s,i);for(let t of d)e.has(t.model.model)||(n.push(t),e.add(t.model.model))}return _o(n,l)}let u=xo(t,i);return _o($(a,o,u,r,s,i),l)}function Oo(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function ko(e){return e.map(({model:e})=>{let t=[`ID: ${e.model}`,`Name: ${e.name}`,`Description: ${e.shortDescription||e.description}`,`Capabilities: ${e.capabilities.join(`, `)}`,`Features: ${e.features.join(`, `)}`];e.contextWindow&&t.push(`Context Window: ${e.contextWindow}`),e.maxOutputTokens&&t.push(`Max Output: ${e.maxOutputTokens}`),e.category&&t.push(`Category: ${e.category}`);let n=e.inferenceMetadata;n?.request_modality?.length&&t.push(`Input Modality: ${n.request_modality.join(`, `)}`),n?.response_modality?.length&&t.push(`Output Modality: ${n.response_modality.join(`, `)}`);let r=Oo(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
140
+ `)}function Ao(e){let{taskSummary:t,scenarioHints:n,inputModality:r,outputModality:i,requiredCapabilities:a,requiredFeatures:o,budget:s,qualityPreference:c,contextNeed:l,segments:u,modelPreference:d}=e,f=[];if(t&&f.push(`Task: ${t}`),n.length&&f.push(`Scenario: ${n.join(`, `)}`),r.length&&f.push(`Input: ${r.join(`, `)}`),i.length&&f.push(`Output: ${i.join(`, `)}`),a.length&&f.push(`Capabilities: ${a.join(`, `)}`),o.length&&f.push(`Features: ${o.join(`, `)}`),f.push(`Budget: ${s}`),f.push(`Quality: ${c}`),l!==ba.Standard&&f.push(`Context: ${l}`),d&&d.mode!==`unconstrained`&&(f.push(`Mode: ${d.mode}`),d.targets?.length&&f.push(`Targets: ${d.targets.join(`, `)}`),d.excludes?.length&&f.push(`Excludes: ${d.excludes.join(`, `)}`)),u?.length){f.push(`Pipeline Steps:`);for(let e of u){let t=e.inputModality.join(`,`)||`none`,n=e.outputModality.join(`,`)||`none`,r=e.requiredCapabilities.join(`,`)||`none`;f.push(` - ${e.step} (Input: ${t} → Output: ${n}, Capabilities: ${r})`)}}return f.join(`
141
+ `)}function jo(e){if(!e)return;let t=e.match(/\/(\d+)\.html/);if(t)return`https://bailian.console.aliyun.com/cn-beijing?tab=doc#/doc/?type=model&url=${t[1]}`}function Mo(e,t,n){let r=Array.isArray(e)?e:[],i=[],a=new Set;for(let e of r){let r=t.get(e.model);if(!r||r.family&&a.has(r.family))continue;r.family&&a.add(r.family);let{model:o,name:s,category:c,contextWindow:l,maxOutputTokens:u,docUrl:d}=r;if(i.push({model:o,name:s,reason:e.reason??``,highlights:e.highlights??[],category:c,contextWindow:l,maxOutputTokens:u,docUrl:d}),i.length>=n)break}return i}function No(e,t){for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n],a=new Set(r.recommendations.flatMap(e=>t.get(e.model)?.inferenceMetadata?.response_modality??[]));if(a.size===0)continue;let o=[];for(let e of i.recommendations){let n=t.get(e.model)?.inferenceMetadata?.request_modality??[];!n.some(e=>a.has(e))&&n.length>0&&o.push(`${e.name}'s input modalities [${n.join(`, `)}] may not be compatible with the previous step's output modalities [${[...a].join(`, `)}]`)}o.length>0&&(i.warnings=o)}}async function Po(e,t,n,r,i,a){let o=ko(t),s=Ao(n),c=n.modelPreference?.mode,l;if(c===`comparison`)l=`You are a model comparison advisor for Alibaba Cloud Model Studio. The user wants to compare specific models — analyze them against the use case.
141
142
 
142
143
  CRITICAL: You MUST respond entirely in English. Do not use any Chinese characters anywhere in your response. Every field — reason, highlights — must be written in English.
143
144
 
@@ -179,4 +180,4 @@ The intent's modelPreference.targets is the reference model.
179
180
  - Output strict JSON
180
181
 
181
182
  ## Output Format
182
- {"type":"single","recommendations":[{"model":"model ID","reason":"alternative analysis","highlights":["differentiators"]}]}`;else if(c===`scoped`){let e=n.modelPreference?.targets?.length?`\n\n## Scope Restriction\nThe user explicitly requested recommendations from: ${n.modelPreference.targets.join(`, `)}. Prioritize models within this scope.`:``;l=(n.complexity===K.Pipeline?aa:ia)+e}else l=n.complexity===K.Pipeline?aa:ia;let u=a?.enableThinking??!1,d=n.complexity===K.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=He(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Jt(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await e.requestJson({path:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:K.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===K.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=eo(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return to(e,g),{type:K.Pipeline,summary:h.summary??``,steps:e}}let _=eo(h.recommendations??h??[],g,i);return{type:K.Single,recommendations:_}}export{Zr as ASYNC_FLAG,ve as BAILIAN_HOST,Vr as BILLING_METHOD,N as BailianError,Wi as Budgets,bt as CHANNEL,Ur as CHARGE_TYPE,ri as COMMAND_PACK_API_VERSION,Xr as CONCURRENT_FLAG,$r as CONSOLE_AUTH_FLAGS,J as Capabilities,qt as Client,K as Complexities,Gi as ContextNeeds,Hr as DEFAULT_BILLING_METHOD,zr as DEFAULT_DEPLOY_PLAN,dr as DEFAULT_TRAINING_TYPE,W as DEPLOY_PLAN,_e as DOCS_HOSTS,M as ExitCode,Ki as Features,Yr as GLOBAL_FLAGS,_r as INSUFFICIENT_SAMPLES_CODE,un as MAX_DATASET_BYTES,dn as MAX_MEDIA_ZIP_BYTES,Qr as MODEL_AUTH_FLAGS,Yt as MODEL_LIST_API,Vt as McpClient,Ui as Modalities,Y as ModelCategories,ei as OPENAPI_AUTH_FLAGS,Xt as PREDICT_CONFIG_API,q as QualityPreferences,ge as REGIONS,qi as SEMANTIC_TOP_K,St as SOURCE_CONFIG,qr as STRATEGIES,xt as TAGS,ur as TRAINING_TYPES_CLI,U as TRAINING_TYPE_MAP,pe as UsageError,ca as analyzeIntent,qe as appCompletionPath,Bt as bailianMcpPath,Ot as buildAcsCanonicalQuery,$a as buildDocLink,ze as buildSettings,Re as buildSources,Kt as callConsoleGateway,ar as cancelFineTune,He as chatPath,Mr as createDeployment,nr as createFineTune,pi as createTrackingEvent,ti as credentialFlagDefs,Br as defaultDeployPlan,ni as defineCommand,ln as deleteDataset,Fr as deleteDeployment,or as deleteFineTune,Ae as describeAuthState,Kn as detectModality,Ie as detectOutputFormat,Wt as effectiveConsoleGatewayConfig,Me as ensureConfigDir,lr as exportCheckpoint,gr as fetchModelCapability,en as fetchModelDetail,$t as fetchModelGroups,Qt as fetchModelList,rn as fetchPredictConfig,Ti as flushTelemetry,Fe as formatErrorJson,tr as formatIssue,Pe as formatJson,Le as formatOutput,Ne as formatText,ai as generateFilename,P as getConfigDir,F as getConfigPath,je as getCredentialsPath,cn as getDataset,Pr as getDeployment,ir as getFineTune,sr as getFineTuneLogs,Hi as getModels,Ar as getProfile,Ue as imagePath,We as imageSyncPath,Lt as isLocalFile,Pa as isSemanticAvailable,fr as isTrainingTypeCli,it as knowledgeChatEndpoint,nt as knowledgeRetrievePath,rt as knowledgeSearchEndpoint,cr as listCheckpoints,sn as listDatasets,Ir as listDeployableModels,Nr as listDeployments,rr as listFineTunes,er as listSupportedFormats,hr as listSupportedTrainingTypes,jr as listTrainingTypes,Ei as localSink,Ve as makeAuthStore,an as makeConfigStore,he as mapApiError,Ct as maskToken,at as mcpWebSearchPath,Je as memoryAddPath,Xe as memoryListPath,Ze as memoryNodePath,Ye as memorySearchPath,mr as modelSupportsTrainingType,li as parseBooleanValue,Se as parseConfigFile,pn as parseDatasetSchemaFlag,ui as parseOptionalBooleanValue,Jt as parseSSE,Jr as pickPlanStrategy,Qn as pickValidator,vr as preflightBatchSizeGate,et as profileSchemaPath,no as rankModels,I as readConfigFile,ya as recallCandidates,Ya as recallSemantic,$n as registerValidator,Di as remoteSink,Tt as request,Dt as requestJson,we as resolveApiKey,di as resolveBooleanFlag,Te as resolveConsole,Rt as resolveFileUrl,Ce as resolveModelBaseUrl,Ee as resolveOpenApi,si as resolveOutputDir,fi as resolveWatermark,Lr as scaleDeployment,kt as signAcsRequest,$e as speechRecognizePath,Qe as speechSynthesizePath,ci as stripUndefined,Ke as taskPath,ji as trackCommandExecution,R as trackingHeaders,pr as trainingTypeMethodVariant,Zt as unwrapResponse,Rr as updateDeployment,on as uploadDataset,It as uploadFile,tt as userProfilePath,H as validateDataset,Ge as videoGeneratePath,L as writeConfigFile};
183
+ {"type":"single","recommendations":[{"model":"model ID","reason":"alternative analysis","highlights":["differentiators"]}]}`;else if(c===`scoped`){let e=n.modelPreference?.targets?.length?`\n\n## Scope Restriction\nThe user explicitly requested recommendations from: ${n.modelPreference.targets.join(`, `)}. Prioritize models within this scope.`:``;l=(n.complexity===J.Pipeline?Pa:Na)+e}else l=n.complexity===J.Pipeline?Pa:Na;let u=a?.enableThinking??!1,d=n.complexity===J.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=Nt(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of vn(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await e.requestJson({path:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:J.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===J.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=Mo(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return No(e,g),{type:J.Pipeline,summary:h.summary??``,steps:e}}let _=Mo(h.recommendations??h??[],g,i);return{type:J.Single,recommendations:_}}export{wi as ASYNC_FLAG,Ce as BAILIAN_HOST,mi as BILLING_METHOD,A as BailianError,ya as Budgets,nt as CHANNEL,gi as CHARGE_TYPE,Ai as COMMAND_PACK_API_VERSION,Ci as CONCURRENT_FLAG,we as CONFIG_FILE_KEYS,Ei as CONSOLE_AUTH_FLAGS,X as Capabilities,Dt as Client,J as Complexities,ba as ContextNeeds,hi as DEFAULT_BILLING_METHOD,fi as DEFAULT_DEPLOY_PLAN,Rr as DEFAULT_TRAINING_TYPE,q as DEPLOY_PLAN,Se as DOCS_HOSTS,k as ExitCode,xa as Features,Si as GLOBAL_FLAGS,Wr as INSUFFICIENT_SAMPLES_CODE,Pn as MAX_DATASET_BYTES,Fn as MAX_MEDIA_ZIP_BYTES,Ti as MODEL_AUTH_FLAGS,yn as MODEL_LIST_API,St as McpClient,va as Modalities,Z as ModelCategories,Di as OPENAPI_AUTH_FLAGS,bn as PREDICT_CONFIG_API,Y as QualityPreferences,xe as REGIONS,Sa as SEMANTIC_TOP_K,it as SOURCE_CONFIG,bi as STRATEGIES,rt as TAGS,Lr as TRAINING_TYPES_CLI,Ir as TRAINING_TYPE_MAP,ge as UsageError,Ye as activateConfigProfile,Ra as analyzeIntent,Rt as appCompletionPath,xt as bailianMcpPath,lt as buildAcsCanonicalQuery,jo as buildDocLink,Qe as buildSettings,Ze as buildSources,U as callConsoleGateway,jr as cancelFineTune,Nt as chatPath,hn as createBailianControlUser,ai as createDeployment,Or as createFineTune,Vi as createTrackingEvent,Oi as credentialFlagDefs,pi as defaultDeployPlan,ki as defineCommand,Xe as deleteConfigProfile,Nn as deleteDataset,ci as deleteDeployment,Mr as deleteFineTune,Pe as describeAuthState,_r as detectModality,Be as detectOutputFormat,Tt as effectiveConsoleGatewayConfig,Ie as ensureConfigDir,Fr as exportCheckpoint,Ur as fetchModelCapability,Cn as fetchModelDetail,Sn as fetchModelGroups,xn as fetchModelList,En as fetchPredictConfig,ea as flushTelemetry,ze as formatErrorJson,Dr as formatIssue,Re as formatJson,Ve as formatOutput,Le as formatText,jt as generateCLIAccessToken,Mi as generateFilename,P as getConfigDir,F as getConfigPath,Fe as getCredentialsPath,Mn as getDataset,si as getDeployment,Ar as getFineTune,Nr as getFineTuneLogs,kn as getModelProfilePreset,_a as getModels,ri as getProfile,Pt as imagePath,Ft as imageSyncPath,vt as isLocalFile,fo as isSemanticAvailable,zr as isTrainingTypeCli,Yt as knowledgeChatEndpoint,qt as knowledgeRetrievePath,Jt as knowledgeSearchEndpoint,gn as listBailianControlWorkspaces,Pr as listCheckpoints,jn as listDatasets,li as listDeployableModels,oi as listDeployments,kr as listFineTunes,Er as listSupportedFormats,Hr as listSupportedTrainingTypes,ii as listTrainingTypes,ta as localSink,et as makeAuthStore,Dn as makeConfigStore,ve as mapApiError,tt as maskToken,Xt as mcpWebSearchPath,zt as memoryAddPath,Vt as memoryListPath,Ht as memoryNodePath,Bt as memorySearchPath,Vr as modelSupportsTrainingType,R as normalizeConfigName,j as normalizeModelBaseUrl,Li as parseBooleanValue,M as parseConfigFile,Ln as parseDatasetSchemaFlag,Ri as parseOptionalBooleanValue,vn as parseSSE,xi as pickPlanStrategy,wr as pickValidator,Gr as preflightBatchSizeGate,Gt as profileSchemaPath,Po as rankModels,B as readConfigFile,Ke as readConfigProfiles,Ii as readTextFromPathOrStdin,Ya as recallCandidates,Do as recallSemantic,Mt as refreshAccessToken,Tr as registerValidator,na as remoteSink,ot as request,ct as requestJson,_n as resetBailianControlPolicies4Agent,ke as resolveApiKey,zi as resolveBooleanFlag,Ae as resolveConsole,yt as resolveFileUrl,Oe as resolveModelBaseUrl,je as resolveOpenApi,Pi as resolveOutputDir,Bi as resolveWatermark,ui as scaleDeployment,ut as signAcsRequest,Wt as speechRecognizePath,Ut as speechSynthesizePath,Fi as stripUndefined,Lt as taskPath,oa as trackCommandExecution,H as trackingHeaders,Br as trainingTypeMethodVariant,W as unwrapResponse,di as updateDeployment,An as uploadDataset,_t as uploadFile,Kt as userProfilePath,Je as validateConfigProfileActivation,K as validateDataset,It as videoGeneratePath,V as writeConfigFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.",
5
5
  "homepage": "https://bailian.console.aliyun.com/cli",
6
6
  "bugs": {