bailian-cli-core 1.13.1 → 1.14.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
@@ -1745,7 +1745,9 @@ interface DatasetUploadParams {
1745
1745
  * `Response`'s helper to avoid the buffer doubling. Fall back to readFileSync
1746
1746
  * for small files where streaming overhead isn't worth it.
1747
1747
  */
1748
- declare function uploadDataset(client: Client, params: DatasetUploadParams): Promise<DatasetFile>;
1748
+ declare function uploadDataset(client: Client, params: DatasetUploadParams): Promise<DatasetFile & {
1749
+ request_id?: string;
1750
+ }>;
1749
1751
  interface DatasetListParams {
1750
1752
  pageNo?: number;
1751
1753
  pageSize?: number;
@@ -2810,6 +2812,13 @@ declare function stripUndefined<T extends Record<string, unknown>>(obj: T): T;
2810
2812
  //#region src/utils/fs.d.ts
2811
2813
  declare function readTextFromPathOrStdin(path: string): string;
2812
2814
  //#endregion
2815
+ //#region src/utils/concurrency.d.ts
2816
+ /**
2817
+ * Run async task factories with a bounded concurrency pool.
2818
+ * Returns results in the same order as the input tasks array.
2819
+ */
2820
+ declare function runWithConcurrency<T>(tasks: Array<() => Promise<T>>, limit: number): Promise<T[]>;
2821
+ //#endregion
2813
2822
  //#region src/utils/boolean-flag.d.ts
2814
2823
  /** Parse true/false from CLI flags (e.g. `--watermark <bool>`). */
2815
2824
  declare function parseBooleanValue(value: unknown, label?: string): boolean;
@@ -3078,6 +3087,13 @@ interface RecommendOptions {
3078
3087
  declare function buildDocLink(docUrl?: string): string | undefined;
3079
3088
  declare function rankModels(client: Client, candidates: ScoredCandidate[], intent: IntentProfile, userInput: string, top: number, options?: RecommendOptions): Promise<RecommendResult>;
3080
3089
  //#endregion
3090
+ //#region src/advisor/sync.d.ts
3091
+ /**
3092
+ * Check and sync Wiki data. Runs silently; never throws.
3093
+ * @returns Whether data was actually updated (for testing/debugging)
3094
+ */
3095
+ declare function maybeSyncWikiData(): Promise<boolean>;
3096
+ //#endregion
3081
3097
  //#region src/advisor/sources/types.d.ts
3082
3098
  interface ModelSource {
3083
3099
  name: string;
@@ -3085,4 +3101,347 @@ interface ModelSource {
3085
3101
  load(): Promise<ModelProfile[]>;
3086
3102
  }
3087
3103
  //#endregion
3088
- 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, FetchImplementation, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, FlagDef, FlagsDef, GLOBAL_FLAGS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, HttpDeps, INSUFFICIENT_SAMPLES_CODE, Identity, ImageApiKind, ImageApiRoute, ImageInputStyle, ImageSizeProfile, 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, createInstrumentedFetch, 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, image2ImagePath, imageFileToDataUri, imagePath, imageSyncPath, imageText2ImagePath, isLegacyImage2ImageModel, isLegacyText2ImageModel, isLocalFile, isSemanticAvailable, isSyncMultimodalImageModel, isTrainingTypeCli, isWanxFunctionImageEditModel, 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, redactDataUri, refreshAccessToken, registerValidator, remoteSink, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveImageEditApi, resolveImageGenerateApi, resolveImageSizeProfile, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolvePromptExtendDefault, resolveWatermark, scaleDeployment, signAcsRequest, speechRecognizePath, speechSynthesizePath, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unwrapResponse, updateDeployment, uploadDataset, uploadFile, userProfilePath, validateConfigProfileActivation, validateDataset, videoGeneratePath, writeConfigFile };
3104
+ //#region src/install/method.d.ts
3105
+ /** How the CLI was installed on this machine. */
3106
+ type InstallMethod = "binary" | "npm" | "brew" | "winget" | "unknown";
3107
+ /** Product that currently ships standalone binary artifacts (`bl` / `bailian`). */
3108
+ declare const BINARY_PRODUCT_CLIENT_NAME = "bailian-cli";
3109
+ type InstallMethodIdentity = {
3110
+ clientName: string;
3111
+ };
3112
+ /**
3113
+ * True when running a Bun-compiled standalone executable
3114
+ * rather than via the Node/npm entry shim.
3115
+ *
3116
+ * Binary entrypoints set `BAILIAN_COMPILED=1` before other code runs.
3117
+ */
3118
+ declare function isCompiledBinary(): boolean;
3119
+ /** Infer install method when no marker file / env override is present. */
3120
+ declare function detectInstallMethod(): InstallMethod;
3121
+ /**
3122
+ * Read the persisted install method, falling back to detection.
3123
+ *
3124
+ * When `identity` is provided, prefer `install-method.<clientName>`.
3125
+ * Legacy `~/.bailian/install-method` is only consulted for `bailian-cli`
3126
+ * so other products (e.g. kscli) are not polluted by a shared binary marker.
3127
+ */
3128
+ declare function getInstallMethod(identity?: InstallMethodIdentity): InstallMethod;
3129
+ /**
3130
+ * Install method for update / auto-update routing.
3131
+ * Only `bailian-cli` may follow the binary channel; other products always use npm
3132
+ * even if env or a mistaken marker claims `binary`.
3133
+ */
3134
+ declare function getUpdateInstallMethod(identity: {
3135
+ clientName: string;
3136
+ npmPackage: string;
3137
+ }): InstallMethod;
3138
+ /**
3139
+ * Persist install method under `~/.bailian/install-method.<clientName>` (best-effort).
3140
+ * For `bailian-cli`, also write the legacy `install-method` file for older readers.
3141
+ */
3142
+ declare function writeInstallMethodSync(method: InstallMethod, identity?: InstallMethodIdentity): void;
3143
+ //#endregion
3144
+ //#region src/install/cdn.d.ts
3145
+ /**
3146
+ * End-user binary download base (OSS). CI publishes release assets and rolling
3147
+ * channel manifests here directly (tools/release/lib/oss-direct-upload.mjs);
3148
+ * no external FC is involved.
3149
+ *
3150
+ * Layout under the base:
3151
+ * v<version>/<asset>.zip —— immutable per-version binaries + SHA256SUMS
3152
+ * manifest.json —— stable install/update pointer (rolling-manifest shape)
3153
+ * latest.json —— stable alias; same body as manifest.json
3154
+ * sync-release.json —— official channel/verify rolling pointer (all bailian-cli
3155
+ * channel publishes overwrite this; npm dist-tag is separate)
3156
+ *
3157
+ * Legacy `{name}.json` files may still exist on CDN; install may resolve them, but
3158
+ * release tooling no longer creates per-dist-tag manifests.
3159
+ *
3160
+ * Override with `BAILIAN_CLI_CDN`.
3161
+ */
3162
+ declare const DEFAULT_CLI_CDN_BASE = "https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release";
3163
+ /** GitHub Releases base — used when writing manifests attached to gh release assets. */
3164
+ declare const GITHUB_RELEASES_BASE = "https://github.com/modelstudioai/cli/releases";
3165
+ /** User-facing install entry (docs / update hints); asset downloads still use getCliCdnBase(). */
3166
+ declare const DEFAULT_INSTALL_SCRIPT_URL = "https://bailian.aliyun.com/cli/install.sh";
3167
+ declare const DEFAULT_INSTALL_PS1_URL = "https://bailian.aliyun.com/cli/install.ps1";
3168
+ declare function getCliCdnBase(): string;
3169
+ /**
3170
+ * Rolling manifest URL at the CDN base root.
3171
+ * Stable (`latest` / `stable` / empty) → `manifest.json`.
3172
+ * Official verify line → `sync-release.json` (`channel=sync-release`).
3173
+ * Other names still map to `{channel}.json` for backward compatibility only.
3174
+ * All share the same rolling-manifest shape from binary-build.
3175
+ */
3176
+ declare function channelManifestUrl(channel?: string): string;
3177
+ /** Immutable per-version asset: `{base}/v{version}/{fileName}`. */
3178
+ declare function releaseAssetUrl(version: string, fileName: string): string;
3179
+ /** Platform triple used in asset names: `bl-<ver>-<os>-<arch>[.exe]`. */
3180
+ declare function detectBinaryPlatform(): {
3181
+ os: string;
3182
+ arch: string;
3183
+ fileSuffix: string;
3184
+ };
3185
+ /** Release download asset: `bl-<ver>-<os>-<arch>.zip`. */
3186
+ declare function binaryAssetFileName(version: string, os: string, arch: string, _exe?: boolean): string;
3187
+ /** Uncompressed binary name inside the zip. */
3188
+ declare function binaryInnerFileName(version: string, os: string, arch: string, exe?: boolean): string;
3189
+ //#endregion
3190
+ //#region src/install/unzip-asset.d.ts
3191
+ /**
3192
+ * Extract `entryName` (or the first non-directory entry) from `zipPath` to `destPath`.
3193
+ * Returns the archive entry basename that was extracted.
3194
+ */
3195
+ declare function extractZipEntryToFile(zipPath: string, destPath: string, entryName?: string): Promise<string>;
3196
+ //#endregion
3197
+ //#region src/skills/types.d.ts
3198
+ /**
3199
+ * Data structures for the unified skill publishing protocol (symmetric with FC publisher skills-publish.mjs).
3200
+ *
3201
+ * Remote layout (public-read OSS, the sole data source for `bl skill`):
3202
+ * <registry>/index.json — skill catalog (SkillsIndex)
3203
+ * <registry>/<name>/sha256-<hex>.tar.br — content-addressed skill object (tar + brotli);
3204
+ * entry.object names the exact file, so index.json is the single atomic commit point.
3205
+ * Legacy fallback: <registry>/<name>/skill.tar.br (entries without object)
3206
+ *
3207
+ * Local layout:
3208
+ * ~/.bailian/skills/<name>/ — canonical install directory
3209
+ * ~/.bailian/skills/skill-lock.json — installation fact records (SkillLockFile)
3210
+ */
3211
+ /** A single skill entry in index.json */
3212
+ interface SkillIndexEntry {
3213
+ /** Reserved for the skill's own semantic version (x.y.z); not yet populated by the publisher */
3214
+ version?: string;
3215
+ /** Beijing-time publish timestamp; refreshed whenever content changes — the human-facing release marker */
3216
+ publishedAt?: string;
3217
+ /** Extracted by the publisher from README.md first paragraph or SKILL.md frontmatter */
3218
+ description?: string;
3219
+ /** Deterministic content fingerprint; the CLI uses this as the change-detection token (install/outdated) */
3220
+ contentHash?: string;
3221
+ /** Compression format identifier, currently always "tar.br" */
3222
+ compression?: string;
3223
+ /**
3224
+ * Content-addressed object file name under <registry>/<name>/, e.g. "sha256-<hex>.tar.br".
3225
+ * Absent on legacy entries — client falls back to the fixed key "skill.tar.br".
3226
+ */
3227
+ object?: string;
3228
+ }
3229
+ interface SkillsIndex {
3230
+ updatedAt?: string;
3231
+ /** key = skill name (i.e. OSS directory name, download path, local install dir name) */
3232
+ skills: Record<string, SkillIndexEntry>;
3233
+ }
3234
+ /** Installation facts for a single skill in skill-lock.json */
3235
+ interface SkillLockEntry {
3236
+ /** Content fingerprint at install time; compared against the remote index to detect updates */
3237
+ contentHash?: string;
3238
+ /** Publish timestamp of the installed revision (for display) */
3239
+ publishedAt?: string;
3240
+ installedAt: string;
3241
+ /** Reserved: future support for github/gitlab and other sources */
3242
+ sourceType: "oss";
3243
+ description?: string;
3244
+ /** Fan-out link/copy paths to each agent; used for precise reclamation on remove */
3245
+ links?: string[];
3246
+ }
3247
+ interface SkillLockFile {
3248
+ version: 1;
3249
+ skills: Record<string, SkillLockEntry>;
3250
+ }
3251
+ /**
3252
+ * Skill statuses for list:
3253
+ * installed — lock record exists, dir on disk, content fingerprint matches remote
3254
+ * outdated — lock record exists, dir on disk, remote content fingerprint differs
3255
+ * not-installed — present in remote, absent locally
3256
+ * missing — lock record exists but dir was deleted (reinstall can fix)
3257
+ * untracked — dir on disk but no install record (manually placed or synced by other channels)
3258
+ */
3259
+ type SkillStatus = "installed" | "outdated" | "not-installed" | "missing" | "untracked";
3260
+ interface SkillStatusRow {
3261
+ name: string;
3262
+ status: SkillStatus;
3263
+ /** Publish timestamp of the remote revision (or local, for delisted skills) */
3264
+ publishedAt?: string;
3265
+ description?: string;
3266
+ }
3267
+ //#endregion
3268
+ //#region src/skills/registry.d.ts
3269
+ declare function getSkillRegistryBaseUrl(): string;
3270
+ /**
3271
+ * Fetch the remote skill index. No local caching — the diff comparison is always
3272
+ * "live remote index vs local skill-lock.json".
3273
+ * Silent background channels (advisor sync) may pass a tighter timeout than the interactive default.
3274
+ */
3275
+ declare function fetchSkillsIndex(timeoutMs?: number): Promise<SkillsIndex>;
3276
+ /** Resolve which file to download for a skill: content-addressed object, else legacy fixed key */
3277
+ declare function resolveAssetFileName(entry?: SkillIndexEntry): string;
3278
+ /** Download the tar.br archive for a single skill (one skill = one GET) */
3279
+ declare function downloadSkillAsset(name: string, entry?: SkillIndexEntry): Promise<Buffer>;
3280
+ //#endregion
3281
+ //#region src/skills/lock.d.ts
3282
+ /**
3283
+ * Local skill state: canonical directory + skill-lock.json.
3284
+ *
3285
+ * The lock only records "installation facts" (version, timestamp, fan-out links) and never
3286
+ * caches the remote index — list/update diffs are always "live remote index vs lock".
3287
+ * Paths follow the config.json directory logic (BAILIAN_CONFIG_DIR can redirect everything).
3288
+ */
3289
+ declare function getSkillsDir(): string;
3290
+ declare function getSkillLockPath(): string;
3291
+ declare function emptySkillLock(): SkillLockFile;
3292
+ /**
3293
+ * Read installation records. Returns an empty lock when the file is absent (first install),
3294
+ * corrupted, or has an unrecognized version — an empty lock is a valid initial state, not an
3295
+ * error; subsequent install actions will rebuild correct records.
3296
+ */
3297
+ declare function readSkillLock(): SkillLockFile;
3298
+ declare function writeSkillLock(lock: SkillLockFile): void;
3299
+ /**
3300
+ * Merge-update a single skill's installation record (read-modify-write).
3301
+ * Shallow-merges with the existing entry: fields not provided in patch (typically links —
3302
+ * agent fan-out records) are preserved, preventing "install-only, no fan-out" sync channels
3303
+ * like postinstall/advisor from overwriting link records established by bl skill add.
3304
+ */
3305
+ declare function upsertSkillLockEntry(name: string, patch: SkillLockEntry): void;
3306
+ //#endregion
3307
+ //#region src/skills/sanitize.d.ts
3308
+ /**
3309
+ * Sanitize a skill name into a safe directory name (semantics aligned with vercel-labs/skills sanitizeName):
3310
+ * skill names come from the remote index (untrusted input) and are interpolated into file paths, so they
3311
+ * must be disinfected first — path separators/drive letters/whitespace/Windows-illegal chars are collapsed
3312
+ * to hyphens, `..` is destroyed, leading/trailing `.-` are stripped.
3313
+ *
3314
+ * `bl skill` uses this as an "equivalence check": if the sanitized name differs from the original,
3315
+ * installation is rejected outright (the publisher already has an isomorphic allowlist; this is client-side defense-in-depth).
3316
+ */
3317
+ declare function sanitizeSkillName(name: string): string;
3318
+ /** Whether the skill name is already a safe directory name (unchanged after sanitization) */
3319
+ declare function isSafeSkillName(name: string): boolean;
3320
+ //#endregion
3321
+ //#region src/skills/names.d.ts
3322
+ /**
3323
+ * Parse --name: `all` or a comma-separated list of skill names (deduplicated, trimmed).
3324
+ * `all` cannot be mixed with specific names.
3325
+ */
3326
+ declare function parseSkillNames(raw: string | undefined, defaultAll: boolean): string[] | "all";
3327
+ //#endregion
3328
+ //#region src/skills/validate.d.ts
3329
+ /**
3330
+ * Skill validity check (aligned with vercel-labs/skills parseSkillMd semantics):
3331
+ * 1. SKILL.md exists as a regular file at the directory root
3332
+ * 2. frontmatter is valid YAML delimited by `---`
3333
+ * 3. name / description fields exist and are non-empty strings
3334
+ *
3335
+ * Validation happens in the temp dir before writing to canonical — any failure rolls back the entire install.
3336
+ */
3337
+ interface SkillMeta {
3338
+ name: string;
3339
+ description: string;
3340
+ }
3341
+ declare function validateSkillDir(dir: string, skillName: string): SkillMeta;
3342
+ //#endregion
3343
+ //#region src/skills/extract.d.ts
3344
+ /** tar 条目路径必须是相对路径且不含 ..,防止 tar-slip 逃逸解包目录 */
3345
+ declare function isSafeEntryName(name: string): boolean;
3346
+ /** Brotli decompress + tar-stream extract into destDir (per-entry path safety check). */
3347
+ declare function extractTarBr(tarBrBuffer: Buffer, destDir: string): Promise<void>;
3348
+ /**
3349
+ * Recompute the publisher's deterministic content hash over an extracted directory:
3350
+ * regular files sorted by "/"-separated relative path (code-unit order, same as the
3351
+ * publisher's byte-order sort for ASCII paths), sha256 accumulating relPath + bytes.
3352
+ * Symmetric with computeContentHash in FC skills-publish.mjs.
3353
+ */
3354
+ declare function computeDirContentHash(dir: string): string;
3355
+ /**
3356
+ * Atomic swap: replace destDir with the extracted content from tmpDir.
3357
+ * tmpDir must be on the same volume as destDir (same parent) for renameSync to be atomic.
3358
+ */
3359
+ declare function atomicSwap(tmpDir: string, destDir: string): void;
3360
+ //#endregion
3361
+ //#region src/skills/agents.d.ts
3362
+ /**
3363
+ * Agent fan-out: after a skill lands in the canonical dir (~/.bailian/skills/<name>),
3364
+ * symlink it into each detected AI agent's global skills directory so that a single
3365
+ * install becomes visible across all agents.
3366
+ *
3367
+ * Detection semantics: if the agent's config dir exists → agent is installed → create link;
3368
+ * otherwise skip (never create ~/.xxx dirs that pollute home). When a new agent is installed
3369
+ * later, any subsequent `bl skill add/update` will fill in missing links (self-healing).
3370
+ */
3371
+ interface AgentTarget {
3372
+ id: string;
3373
+ displayName: string;
3374
+ /** Global directory where this agent reads skills from */
3375
+ skillsDir: string;
3376
+ /** 任一存在即判定"本机装了该 agent" */
3377
+ detectDirs: string[];
3378
+ }
3379
+ /** Computed on each call (depends on homedir / XDG_CONFIG_HOME; easy to override in tests) */
3380
+ declare function getAgentTargets(): AgentTarget[];
3381
+ declare function detectInstalledAgents(): AgentTarget[];
3382
+ interface LinkResult {
3383
+ agent: string;
3384
+ path: string;
3385
+ mode: "symlink" | "copy" | "skipped";
3386
+ reason?: string;
3387
+ }
3388
+ /**
3389
+ * Fan out a skill from canonical to each agent's skills dir.
3390
+ * Stale links created by this tool are rebuilt; existing files/dirs NOT managed by this tool
3391
+ * are always skipped (never delete user content). Falls back to copy when symlink fails
3392
+ * (e.g. Windows without Developer Mode).
3393
+ */
3394
+ declare function linkSkillToAgents(name: string, agents?: AgentTarget[]): LinkResult[];
3395
+ /**
3396
+ * Reclaim fan-out artifacts for a skill across all agent dirs.
3397
+ * Symlinks pointing to canonical are removed (including historical links not in lock,
3398
+ * via defensive scan of the full registry); real directories are only removed if recorded
3399
+ * in lock (copy-fallback artifacts). A single failure does not block the rest.
3400
+ */
3401
+ declare function unlinkSkillFromAgents(name: string, recordedLinks?: string[]): string[];
3402
+ //#endregion
3403
+ //#region src/skills/installer.d.ts
3404
+ /**
3405
+ * Skill installer: download → extract to tmpdir (with tar-slip check) → validate SKILL.md →
3406
+ * atomic swap into canonical. Canonical is only touched after all validations pass; on any failure
3407
+ * the current installation is preserved and temp artifacts are cleaned up in finally.
3408
+ */
3409
+ interface InstalledSkill {
3410
+ name: string;
3411
+ path: string;
3412
+ meta: SkillMeta;
3413
+ }
3414
+ /** Install from an in-memory tar.br archive (the download-and-onwards half of installSkill; test-friendly) */
3415
+ declare function installSkillFromBuffer(name: string, tarBrBuffer: Buffer, expectedContentHash?: string): Promise<InstalledSkill>;
3416
+ /** Install a single skill by index entry (download + validate + write to disk) */
3417
+ declare function installSkill(name: string, entry: SkillIndexEntry): Promise<InstalledSkill>;
3418
+ /** Remove the skill directory under canonical; returns whether it was actually deleted (dir absent → false) */
3419
+ declare function removeSkillDir(name: string): boolean;
3420
+ /**
3421
+ * Build a skill-lock entry from an index entry + effective fan-out link paths.
3422
+ * Single source of truth for the "installation fact" shape shared by bl skill add/update,
3423
+ * advisor wiki sync, and any future install channel.
3424
+ */
3425
+ declare function buildSkillLockEntry(entry: SkillIndexEntry, links: string[]): SkillLockEntry;
3426
+ interface SkillInstallRecord {
3427
+ /** Ready-to-persist lock entry (links = effective fan-out paths) */
3428
+ lockEntry: SkillLockEntry;
3429
+ /** Ids of agents that actually received a link/copy (skipped ones excluded) */
3430
+ linkedAgents: string[];
3431
+ }
3432
+ /**
3433
+ * Full install workflow for one skill: install into canonical, fan out to agents, and build
3434
+ * the lock entry recording effective links. Callers decide how to persist the lock entry
3435
+ * (batch writeSkillLock for commands, best-effort upsertSkillLockEntry for silent channels).
3436
+ */
3437
+ declare function installSkillWithFanout(name: string, entry: SkillIndexEntry, agents?: AgentTarget[]): Promise<SkillInstallRecord>;
3438
+ //#endregion
3439
+ //#region src/skills/status.d.ts
3440
+ /**
3441
+ * Three-way reconciliation for list: remote index (live) × skill-lock.json (installation facts) × disk (ground truth).
3442
+ */
3443
+ /** Scan skill directories under canonical (skipping hidden entries, tmp/backup remnants, and plain files) */
3444
+ declare function listSkillDirsOnDisk(): string[];
3445
+ declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[];
3446
+ //#endregion
3447
+ export { ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AgentTarget, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BAILIAN_HOST, BILLING_METHOD, BINARY_PRODUCT_CLIENT_NAME, 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_CLI_CDN_BASE, DEFAULT_DEPLOY_PLAN, DEFAULT_INSTALL_PS1_URL, DEFAULT_INSTALL_SCRIPT_URL, 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, FetchImplementation, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, FlagDef, FlagsDef, GITHUB_RELEASES_BASE, GLOBAL_FLAGS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, HttpDeps, INSUFFICIENT_SAMPLES_CODE, Identity, ImageApiKind, ImageApiRoute, ImageInputStyle, ImageSizeProfile, InstallMethod, InstallMethodIdentity, InstalledSkill, IntentProfile, IntentSegment, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, KnowledgeChatStreamChunk, KnowledgeSearchRequest, KnowledgeSearchResponse, LinkResult, 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, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, 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, atomicSwap, bailianMcpPath, binaryAssetFileName, binaryInnerFileName, buildAcsCanonicalQuery, buildDocLink, buildSettings, buildSkillLockEntry, buildSources, callConsoleGateway, cancelFineTune, channelManifestUrl, chatPath, computeDirContentHash, computeSkillStatuses, createBailianControlUser, createDeployment, createFineTune, createInstrumentedFetch, createTrackingEvent, credentialFlagDefs, defaultDeployPlan, defineCommand, deleteConfigProfile, deleteDataset, deleteDeployment, deleteFineTune, describeAuthState, detectBinaryPlatform, detectInstallMethod, detectInstalledAgents, detectModality, detectOutputFormat, downloadSkillAsset, effectiveConsoleGatewayConfig, emptySkillLock, ensureConfigDir, exportCheckpoint, extractTarBr, extractZipEntryToFile, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchPredictConfig, fetchSkillsIndex, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateCLIAccessToken, generateFilename, getAgentTargets, getCliCdnBase, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getInstallMethod, getModelProfilePreset, getModels, getProfile, getSkillLockPath, getSkillRegistryBaseUrl, getSkillsDir, getUpdateInstallMethod, image2ImagePath, imageFileToDataUri, imagePath, imageSyncPath, imageText2ImagePath, installSkill, installSkillFromBuffer, installSkillWithFanout, isCompiledBinary, isLegacyImage2ImageModel, isLegacyText2ImageModel, isLocalFile, isSafeEntryName, isSafeSkillName, isSemanticAvailable, isSyncMultimodalImageModel, isTrainingTypeCli, isWanxFunctionImageEditModel, knowledgeChatEndpoint, knowledgeRetrievePath, knowledgeSearchEndpoint, linkSkillToAgents, listBailianControlWorkspaces, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listSkillDirsOnDisk, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, maybeSyncWikiData, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, normalizeConfigName, normalizeModelBaseUrl, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, parseSkillNames, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, rankModels, readConfigFile, readConfigProfiles, readSkillLock, readTextFromPathOrStdin, recallCandidates, recallSemantic, redactDataUri, refreshAccessToken, registerValidator, releaseAssetUrl, remoteSink, removeSkillDir, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveAssetFileName, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveImageEditApi, resolveImageGenerateApi, resolveImageSizeProfile, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolvePromptExtendDefault, resolveWatermark, runWithConcurrency, sanitizeSkillName, scaleDeployment, signAcsRequest, speechRecognizePath, speechSynthesizePath, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unlinkSkillFromAgents, unwrapResponse, updateDeployment, uploadDataset, uploadFile, upsertSkillLockEntry, userProfilePath, validateConfigProfileActivation, validateDataset, validateSkillDir, videoGeneratePath, writeConfigFile, writeInstallMethodSync, writeSkillLock };
package/dist/index.mjs CHANGED
@@ -1,15 +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 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}})}function j(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw ye(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw ye(e);return n.origin}function ye(e){return new A(`Invalid model base URL "${e}".`,k.USAGE,`Use an absolute http(s) URL.`)}const be={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},xe={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Se=`https://bailian.cn-beijing.aliyuncs.com`,Ce=[`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_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_omni_model`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],we=new Set([`text`,`json`]),Te=new Set([`domestic`,`international`]);function Ee(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=Ee(t.base_url);e&&(n.base_url=e)}return typeof t.output==`string`&&we.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_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_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`&&Te.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 De(e,t=be.cn){return j(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function Oe(e){let t=De(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 ke(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 Ae(e){let t=je(`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=je(`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=je(`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 je(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,Me(e));return{accessKeyId:a,accessKeySecret:o,securityToken:N(i),source:e}}function N(e){return e?.trim()||void 0}function Me(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 Ne(e){let t={};try{t.apiKey=Oe(e)}catch{}try{t.console=ke(e)}catch{}try{t.openapi=Ae(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 Pe(){return g(P(),`credentials.json`)}async function Fe(){let e=P(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Ie(e){return _(e).replace(/\n$/,``)}function Le(e){return JSON.stringify(e,null,2)}function Re(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function ze(e){return e===`json`||e===`text`?e:`text`}function Be(e,t){switch(t){case`json`:return Le(e);case`text`:return Ie(e)}}const Ve=/^[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`||!Ve.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(Ce.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 He(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 Ue(e,t){if(!t)return e;let n=e[t];return L(n)?n:{}}function B(e){return M(Ue(z(),e))}async function V(e,t,n={}){let r=z();if(t)r[t]=e;else{for(let e of Object.keys(r))Ce.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[I]=t??`default`),await We(r)}async function We(e){await Fe();let t=F(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),s(n,t)}function Ge(){let e=z(),t={};for(let[n,r]of Object.entries(e))Ce.includes(n)||n===I||L(r)&&(t[n]=M(r));return{default:M(e),named:t,active:He(e,!0)??`default`}}function Ke(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 qe(e){return Ke(z(),e)}async function Je(e){let t=z(),n=Ke(t,e);return t[I]=n,await We(t),n}async function Ye(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],He(n,!1)===t&&(n[I]=`default`),await We(n),!0):!1}function Xe(e){let t=z(),n=e.config!==void 0,r=He(t,!n),i=n?R(e.config):r;return{flags:e,file:M(Ue(t,i)),env:process.env,configName:i,configPath:F()}}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 A(`Timeout must be a positive finite number.`,k.USAGE);return{configPath:e.configPath??F(),configName:e.configName,output:ze(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,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_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 Qe={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function $e(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Ne({...e,file:B(t)}),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=>De(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=Qe[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 H(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const et=`bailian-cli`,tt={t1:`public`,t2:``},nt=JSON.stringify({channel:et,tags:tt});function U(){return{"x-dashscope-source-config":nt}}function rt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function it(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...U(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),rt(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: ${H(e.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${nt}`)}let i=at((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 at(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 ot(e,t){let n=await it(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 st(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])=>`${lt(e)}=${lt(String(t))}`).join(`&`)}function ct(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=ne(),i=ut(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(`
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{parse as _,stringify as v}from"yaml";import{createHash as ee,createHmac as te,randomBytes as ne,randomUUID as re}from"crypto";import{Readable as ie}from"stream";import{createInterface as y}from"readline";import{pipeline as ae}from"stream/promises";import*as b from"yauzl";import{cpSync as oe,createWriteStream as se,existsSync as x,lstatSync as ce,mkdirSync as S,readFileSync as C,readdirSync as w,readlinkSync as le,renameSync as T,rmSync as E,statSync as ue,symlinkSync as de,writeFileSync as D}from"node:fs";import{dirname as O,isAbsolute as fe,join as k,resolve as A,sep as pe}from"node:path";import{homedir as me}from"node:os";import{createHash as he}from"node:crypto";import{Readable as ge}from"node:stream";import{pipeline as _e}from"node:stream/promises";import{createBrotliDecompress as ve}from"node:zlib";import ye from"tar-stream";import{mkdir as be}from"node:fs/promises";var xe=Object.create,Se=Object.defineProperty,Ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,De=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=we(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ee.call(e,s)&&s!==n&&Se(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ce(t,s))||r.enumerable});return e},ke=(e,t,n)=>(n=e==null?{}:xe(Te(e)),Oe(t||!e||!e.__esModule?Se(n,`default`,{value:e,enumerable:!0}):n,e)),Ae=e(import.meta.url);const j={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var M=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=j.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=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}:{}}}}},je=class extends M{constructor(e,t){super(e,j.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 Ne(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 M(r,j.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}function Pe(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Fe(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Fe(e);return n.origin}function Fe(e){return new M(`Invalid model base URL "${e}".`,j.USAGE,`Use an absolute http(s) URL.`)}const Ie={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},Le={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Re=`https://bailian.cn-beijing.aliyuncs.com`,ze=[`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_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_omni_model`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],Be=new Set([`text`,`json`]),Ve=new Set([`domestic`,`international`]);function He(e){try{return Pe(e)}catch{return}}function Ue(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=He(t.base_url);e&&(n.base_url=e)}return typeof t.output==`string`&&Be.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_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_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`&&Ve.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 We(e,t=Ie.cn){return Pe(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function Ge(e){let t=We(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 M(`No API key found.`,j.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Ke(e){let t=e.file.access_token?.trim();if(!t)throw new M(`No console access token found.`,j.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 qe(e){let t=Je(`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=Je(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Ye(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Ye(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=Je(`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 M(`No OpenAPI AK/SK credentials found.`,j.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 Je(e,t,n,r,i){if(!r)return;let a=Ye(t),o=Ye(n);if(!a||!o)throw new M(`Incomplete OpenAPI AK/SK credentials found.`,j.AUTH,Xe(e));return{accessKeyId:a,accessKeySecret:o,securityToken:Ye(i),source:e}}function Ye(e){return e?.trim()||void 0}function Xe(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 Ze(e){let t={};try{t.apiKey=Ge(e)}catch{}try{t.console=Ke(e)}catch{}try{t.openapi=qe(e)}catch{}return t}function N(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function P(){return g(N(),`config.json`)}function Qe(){return g(N(),`credentials.json`)}async function $e(){let e=N(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function et(e){return v(e).replace(/\n$/,``)}function tt(e){return JSON.stringify(e,null,2)}function nt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function rt(e){return e===`json`||e===`text`?e:`text`}function it(e,t){switch(t){case`json`:return tt(e);case`text`:return et(e)}}const at=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,F=`active_config`;function I(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function ot(e){if(!(e===void 0||e===``||e===`default`)){if(typeof e!=`string`||!at.test(e))throw new M(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,j.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(ze.includes(e)||e===F)throw new M(`Invalid config name "${e}". It conflicts with a config key.`,j.USAGE);return e}}function L(){let e=P();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 st(e,t){let n=ot(e[F]);if(n&&t&&!I(e[n]))throw new M(`Active config "${n}" does not exist.`,j.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function ct(e,t){if(!t)return e;let n=e[t];return I(n)?n:{}}function R(e){return Ue(ct(L(),e))}async function z(e,t,n={}){let r=L();if(t)r[t]=e;else{for(let e of Object.keys(r))ze.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[F]=t??`default`),await lt(r)}async function lt(e){await $e();let t=P(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),s(n,t)}function ut(){let e=L(),t={};for(let[n,r]of Object.entries(e))ze.includes(n)||n===F||I(r)&&(t[n]=Ue(r));return{default:Ue(e),named:t,active:st(e,!0)??`default`}}function dt(e,t){let n=ot(t);if(n&&!I(e[n]))throw new M(`Config "${n}" does not exist.`,j.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function ft(e){return dt(L(),e)}async function pt(e){let t=L(),n=dt(t,e);return t[F]=n,await lt(t),n}async function mt(e){let t=ot(e);if(!t)throw new M(`Cannot delete the default profile.`,j.USAGE);let n=L();return I(n[t])?(delete n[t],st(n,!1)===t&&(n[F]=`default`),await lt(n),!0):!1}function ht(e){let t=L(),n=e.config!==void 0,r=st(t,!n),i=n?ot(e.config):r;return{flags:e,file:Ue(ct(t,i)),env:process.env,configName:i,configPath:P()}}function gt(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 M(`Timeout must be a positive finite number.`,j.USAGE);return{configPath:e.configPath??P(),configName:e.configName,output:rt(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,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_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 _t={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function vt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Ze({...e,file:R(t)}),stored(){let e=R(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=>We(e,t),async login(e){let r=R(t);for(let[t,n]of Object.entries(e))n!==void 0&&(r[t]=t===`base_url`?Pe(String(n)):n);await z(r,t,{activate:n})},async logout(e){let n=R(t),r=_t[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await z(n,t),!0},get path(){return e.configPath??P()}}}function yt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const bt=`bailian-cli`,xt={t1:`public`,t2:``},St=JSON.stringify({channel:bt,tags:xt});function B(){return{"x-dashscope-source-config":St}}function Ct(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function wt(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...B(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),Ct(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: ${yt(e.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${St}`)}let i=Tt((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 Ne(a.status,e,t.url)}return a}function Tt(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 Et(e,t){let n=await wt(e,t),r;try{r=await n.json()}catch{throw new M(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,j.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw Ne(200,{error:{message:r.message,type:r.code}},t.url);return r}function Dt(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])=>`${kt(e)}=${kt(String(t))}`).join(`&`)}function Ot(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=re(),i=At(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${ut(u)}`,p=dt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function lt(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function ut(e){return v(`sha256`).update(e,`utf8`).digest(`hex`)}function dt(e,t){return ee(`sha256`,e).update(t,`utf8`).digest(`hex`)}const ft=`${be.cn}/api/v1/uploads`;async function pt(e,t,n){let r=`${ft}?action=getPolicy&model=${encodeURIComponent(t)}`,i=xt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...U()},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 mt(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=xt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...U()},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}`}const ht={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function gt(e){if(!i(e))throw new A(`File not found: ${e}`,k.USAGE);if(!l(e).isFile())throw new A(`Not a file: ${e}`,k.USAGE);let t=h(e).toLowerCase(),n=ht[t];if(!n)throw new A(`Unsupported image format "${t||`unknown`}".`,k.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function _t(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function vt(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 mt(await pt(t,n,a),r,a)}function yt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function bt(e,t,n,r={}){return yt(e)?vt({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function xt(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 St(e){return`/api/v1/mcps/${e}/mcp`}var Ct=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}`,...U()};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 wt={"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 Tt(e,t){return wt[e]?.[t]??wt[`cn-beijing`][t]}function Et(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 Dt(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 W(e,t,{api:n,data:r},i){let a=Tt(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Dt(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 Ot=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}exportApiCredential(){return this.deps.apiCred}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 it(this.http,this.toOpts(e))}requestJson(e){return ot(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return yt(e)?bt(e,this.requireApi().token,t,n):Promise.resolve(e)}resolveImageInput(e,t,n={}){return yt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(gt(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){if(this.deps.settings.configName===`token-plan`)return!0;try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Ct(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 W(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 Nt({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await W({...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?st(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=ct({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: ${H(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${H(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,...U()},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 kt={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function At(e){for(let[t,n]of Object.entries(be))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function jt(e){return kt[At(e)]??kt.cn}async function Mt(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Ot({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=jt(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function Nt(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 Mt({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 Pt(){return`/compatible-mode/v1/chat/completions`}function Ft(){return`/api/v1/services/aigc/image-generation/generation`}function It(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Lt(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Rt(){return`/api/v1/services/aigc/image2image/image-synthesis`}function zt(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Bt(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Vt(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Ht(){return`/api/v2/apps/memory/add`}function Ut(){return`/api/v2/apps/memory/memory_nodes/search`}function Wt(){return`/api/v2/apps/memory/memory_nodes`}function Gt(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Kt(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function qt(){return`/api/v1/services/audio/asr/transcription`}function Jt(){return`/api/v2/apps/memory/profile_schemas`}function Yt(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Xt(){return`/api/v1/indices/rag/index/retrieve`}function Zt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Qt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function $t(){return`/api/v1/mcps/WebSearch/mcp`}function en(){return`/compatible-mode/v1/files`}function tn(){return`/api/v1/files`}function nn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function rn(){return`/api/v1/fine-tunes`}function an(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function on(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function sn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function cn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function ln(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function un(){return`/api/v1/deployments`}function dn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function fn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function pn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function mn(){return`/api/v1/deployments/models`}const hn=[`qwen-image`,`wan2.7-image`,`z-image`],gn=[`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function _n(e,t){return t.some(t=>e.startsWith(t))}function vn(e){return _n(e,hn)||e.startsWith(`wan2.6-image`)}function yn(e){return _n(e,hn)}function bn(e){return _n(e,gn)}function xn(e){return/^wanx-v1(?:-|$)/i.test(e)}function Sn(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||yn(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||xn(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function Cn(e){return/wan2\.5-i2i/i.test(e)}function wn(e){return/imageedit/i.test(e)}function Tn(e){return e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:xn(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Sn(e)?`wan-legacy`:`wan26`}function En(e){if(e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function G(e,t){return{...e,sizeProfile:Tn(t),promptExtendDefault:En(t)}}function Dn(e){return yn(e)?G({kind:`sync-multimodal`,path:It(),useSync:!0,inputStyle:`messages`},e):Sn(e)?G({kind:`async-text2image`,path:Lt(),useSync:!1,inputStyle:`prompt`},e):G({kind:`async-image-generation`,path:Ft(),useSync:!1,inputStyle:`messages`},e)}function On(e){return bn(e)?G({kind:`sync-multimodal`,path:It(),useSync:!0,inputStyle:`messages`},e):wn(e)?G({kind:`async-image2image`,path:Rt(),useSync:!1,inputStyle:`function-base-image`},e):Cn(e)?G({kind:`async-image2image`,path:Rt(),useSync:!1,inputStyle:`prompt-images`},e):G({kind:`async-image-generation`,path:Ft(),useSync:!1,inputStyle:`messages`},e)}function kn(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function An(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jn(e){return async(t,n={})=>{let r=An(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),kn(r))for(let[e,t]of Object.entries(U()))i.set(e,t);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${H(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Mn=`2024-08-16`;function Nn(e){return`bailiancontrol.${e}.aliyuncs.com`}function Pn(e){return new Ot({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Fn(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Mn,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function In(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Mn,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ln(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Mn,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}async function*Rn(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 zn=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Bn=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Vn(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 Hn(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Vn(await e(zn,{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 Un(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=Vn(await e(zn,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Wn(e,t){return(Vn(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 Gn=[`name`,`key`,`default`,`tip`,`range`];function Kn(e){return e.map(e=>{let t={};for(let n of Gn)e[n]!==void 0&&(t[n]=e[n]);return t})}async function qn(e,t){let n=Vn(await e(Bn,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Kn(e):null}catch{return null}return Array.isArray(n)?Kn(n):null}function Jn(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:()=>Ge(),activate:e=>Je(e),validateActivation:e=>qe(e),get path(){return F()}}}const Yn={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function Xn(e){return e?Yn[e]:void 0}async function Zn(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:en(),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 Qn(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=tn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function $n(e,t,n){return e.requestJson({path:nn(t),method:`GET`,signal:n})}async function er(e,t,n){let r=await e.request({path:nn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const tr=300*1024*1024,nr=1024*1024*1024;function rr(e,t=tr){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 K(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ir(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 ar(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 or=new Set([`system`,`user`,`assistant`]);function sr(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(K(`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`||!or.has(a))&&r.push(K(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(K(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function cr(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(K(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(K(`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(...sr(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(K(`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(K(`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(K(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(K(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const lr={name:`chatml`,detect:()=>!0,inspect:cr};function ur(e,t){let n=[];if(!(`text`in e))return n.push(K(`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(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const dr={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ur};function fr(e,t){let n=cr(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(K(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(K(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...sr(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...sr(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const pr={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:fr};function mr(e,t){let n=[];if(!(`wav_fn`in e))n.push(K(`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(K(`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(K(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(K(`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(K(`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(K(`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(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const hr={name:`tts`,detect:e=>`wav_fn`in e,inspect:mr},gr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function _r(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function vr(e){return/^[\x20-\x7E]+$/.test(e)}function yr(e,t){let n=[];if(!(`prompt`in e))n.push(K(`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(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(K(`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(K(`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(K(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`img_path`})),vr(r)||n.push(K(`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(K(`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(K(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`input_img`})),vr(r)||n.push(K(`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 br={name:`image`,detect:e=>`img_path`in e,inspect:yr},xr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Sr=new Set([`.mp4`,`.mov`]);function Cr(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function wr(e){return/^[\x20-\x7E]+$/.test(e)}function Tr(e,t,n,r,i,a){if(!(n in t)){r&&e.push(K(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(K(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(K(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Cr(o);i.has(s)||e.push(K(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),wr(o)||e.push(K(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Er(e,t){let n=[];if(!(`prompt`in e))n.push(K(`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(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Tr(n,e,`first_frame_path`,!0,xr,t),Tr(n,e,`last_frame_path`,!1,xr,t),Tr(n,e,`video_path`,!1,Sr,t),n}const Dr=[hr,br,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Er},pr,dr,lr];function Or(e,t){return t===void 0?Dr.find(t=>t.detect(e))??lr:Dr.find(e=>e.name===t)||lr}async function kr(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(K(`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 Ar(e,t,r,i,a){let o=r?null:new Set(ar(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(K(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...jr(n,u,i))}return{sampled:c,issues:s}}function jr(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[K(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Or(r,n).inspect(r,t)}const Mr={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await kr(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[K(`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 Ar(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 Nr(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 Fr(e,t,n){let{entry:i,zipfile:a}=await Nr(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 Ir(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 Lr={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:[K(`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:[K(`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(K(`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(K(`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 gr.has(n)});e.length<25&&r.push(K(`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 Fr(e,m,_)}catch(t){return r.push(K(`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 Mr.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await Ir(_),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(K(`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 Rr(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return zr(e);if(t===`.zip`)return Br(e);throw new A(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,k.USAGE)}async function zr(e){let t=await Hr(e);if(!t)throw new A(`JSONL file is empty or contains only blank lines: ${e}`,k.USAGE);let n=Vr(t);return n===`unknown`?`text`:n}async function Br(e){let t=await Ur(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=Vr(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 Vr(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 Hr(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 Ur(e,t){return Nr(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 Wr=[Mr,Lr];function Gr(e){let t=h(e).toLowerCase(),n=Wr.find(e=>e.extensions.includes(t));if(!n){let e=Wr.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 Kr(e){Wr.some(t=>t.format===e.format)||Wr.push(e)}async function q(e,t={}){let{bytes:n}=rr(e,t.maxBytes??314572800),r=await Gr(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function qr(){return Wr.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Jr(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 Yr(e,t,n){return e.requestJson({path:rn(),method:`POST`,body:t,signal:n})}async function Xr(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=rn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Zr(e,t,n){return e.requestJson({path:an(t),method:`GET`,signal:n})}async function Qr(e,t,n){return e.requestJson({path:on(t),method:`POST`,signal:n})}async function $r(e,t,n){return e.requestJson({path:an(t),method:`DELETE`,signal:n})}async function ei(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=sn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ti(e,t,n){return e.requestJson({path:cn(t),method:`GET`,signal:n})}async function ni(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${ln(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const ri={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`}},ii=Object.keys(ri),ai=`sft-lora`;function oi(e){return e in ri}function si(e){let{method:t,variant:n}=ri[e];return{method:t,variant:n}}function ci(e,t){if(!e)return!1;let{method:n,variant:r}=ri[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function li(e){return e?ii.filter(t=>ci(e,t)):[]}async function ui(e,t){let n=Et(e);return(await Hn((t,r)=>W({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 di=`INSUFFICIENT_SAMPLES`;function fi(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:di,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 pi(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 mi(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return q(e,{...r,schema:n})},resolveHyperParameters(e,t){return pi(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const hi=mi(`sft`,`sft`,`chatml`),gi={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},_i={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},vi={..._i,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},yi={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 bi(e){return e===`image`||e===`image-i2i`}function xi(e){return e===`video`||e===`video-kf2v`}function Si(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const Ci=[hi,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return q(e,{...n,schema:`tts`});if(bi(t))return q(e,{...n,schema:`image`,maxBytes:nr});if(xi(t)){let r=await q(e,{...n,schema:`video`,maxBytes:nr});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(K(`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(K(`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 q(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...gi};if(bi(e)){let n={...e===`image-i2i`?vi:_i};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(xi(e)){let e=Si(t.model),n={...yi,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 pi(t)},shouldSkipGate(e,t){return!!((t===`audio`||bi(t)||xi(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||bi(e)||xi(e)}},mi(`dpo`,`dpo_full`,`dpo`),mi(`dpo-lora`,`dpo_lora`,`dpo`),mi(`cpt`,`cpt`,`cpt`)];function wi(e){let t=Ci.find(t=>t.clientTrainingType===e);if(!t){let t=Ci.map(e=>e.clientTrainingType).join(`, `);throw new A(`Unknown training type "${e}".`,k.USAGE,`Supported training types: ${t}.`)}return t}function Ti(){return Ci.map(e=>e.clientTrainingType)}async function Ei(e,t,n){return e.requestJson({path:un(),method:`POST`,body:t,signal:n})}async function Di(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=un(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Oi(e,t,n){return e.requestJson({path:dn(t),method:`GET`,signal:n})}async function ki(e,t,n){return e.requestJson({path:dn(t),method:`DELETE`,signal:n})}async function Ai(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=mn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ji(e,t,n,r){return e.requestJson({path:fn(t),method:`PUT`,body:n,signal:r})}async function Mi(e,t,n,r){return e.requestJson({path:pn(t),method:`PUT`,body:n,signal:r})}const J={LORA:`lora`,PTU:`ptu`,MU:`mu`},Ni=J.LORA;function Pi(e){return e===`audio`?J.MU:Ni}const Fi={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},Ii=Fi.POST_PAY,Li={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},Ri={name:J.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},zi={name:J.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}}}},Bi={name:J.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||Ii,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 Ai(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===J.MU)?.templates??[];if(o.length===0)throw i();let s=t===Fi.POST_PAY?Li.POST_PAID:Li.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}}},Vi={[J.LORA]:Ri,[J.PTU]:zi,[J.MU]:Bi};function Hi(e){let t=Vi[e];if(!t)throw new A(`Unsupported plan "${e}". Supported plans: ${Object.keys(Vi).join(`, `)}.`,k.USAGE);return t}const Ui={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`}},Wi={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Gi={async:{type:`switch`,description:`Return async task id without waiting`}},Ki={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},qi={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)`}},Ji={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 Yi(e){return e.auth===`apiKey`?Ki:e.auth===`console`?qi:e.auth===`openapi`?Ji:{}}function Xi(e){return e}const Zi=1;function Qi(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function $i(e,t){return`${Qi(e||`image`,`image`)}_${Qi((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const ea=()=>g(f(),`bailian-output`);function ta(e,t){let n=t?.flagDir||e.outputDir||ea(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function na(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function ra(e){return o(e===`-`?0:e,`utf-8`)}function ia(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 aa(e,t=`boolean`){if(e!=null)return ia(e,t)}function oa(e,t,n=`boolean`){let r=aa(e,n);return r===void 0?t:r}function sa(e){return aa(e,`watermark`)??!0}function ca(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 la(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function ua(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=la(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let da;function fa(){return da||(process.env.NODE_ENV===`development`?(da=`dev`,da):(da=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,da))}var pa=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})),ma=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})),ha=O(pa(),1),ga=O(ma(),1);const _a=()=>g(P(),`telemetry.jsonl`);let va;const ya=new Set;let ba;try{let e=new ha.default({pid:`bailian-cli-node`,env:fa()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;ya.add(e),e.finally(()=>ya.delete(e))}return n},ba=e,va=e.use(ga.default)}catch{}async function xa(e=1e3){try{if(ba)try{typeof ba._sendAll==`function`&&ba._sendAll()}catch{}if(ya.size===0)return;let t=[...ya].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Sa(e){try{await Fe();let n=_a();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
11
- `,{mode:384})}catch{}}async function Ca(e){try{if(!va)return;va(e.command,ua(e))}catch{}}const wa=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),Ta=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 Ea(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||wa.has(n)||Ta.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function Da(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=ca({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:Ea(n)});Sa(l).catch(()=>{}),Ca(l).catch(()=>{})}}function Oa(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 ka=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=Et(this.settings),t=(t,n)=>W({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await Hn(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await Hn(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(Oa).filter(e=>e!==null)}};const Aa=`models.jsonl`;function ja(){return T(P(),`skills/bailian-docs-llm-wiki`)}function Ma(){return T(ja(),Aa)}function Na(){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 Fa(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 Ia(){let e=Na();if(!x(T(e,Aa)))return!1;let t=ja();try{return S(t,{recursive:!0}),b(e,t,{recursive:!0}),!0}catch{return!1}}var La=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return x(Ma())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!Ia())?[]:Fa(Ma())}};async function Ra(e,t){let n=[new La({onPrepareStart:t?.onPrepareStart}),new ka(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 za={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},Y={Single:`single`,Pipeline:`pipeline`},Ba={Low:`low`,Medium:`medium`,High:`high`},Va={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},X={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},Z={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`},Ha={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Q={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Ua=20,Wa=/-\d{4}-\d{2}-\d{2}$/,Ga=new Set([Z.IG,Z.VG,Z.TTS,Z.RealtimeTTS,Z.ThreeDGeneration]),Ka=new Set([Z.TG,Z.Reasoning,Z.ASR,Z.RealtimeASR,Z.RealtimeAudioTranslate,Z.TR,Z.ME]),qa={standard:0,large:32e3,"extra-large":128e3},Ja=.4,Ya=.6,Xa=.4,Za=.2,Qa=.2,$a=.2;console.assert(Math.abs(Ja+Ya-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Xa+Za+Qa+$a-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const eo=`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${At(u)}`,p=jt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function kt(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function At(e){return ee(`sha256`).update(e,`utf8`).digest(`hex`)}function jt(e,t){return te(`sha256`,e).update(t,`utf8`).digest(`hex`)}const Mt=`${Ie.cn}/api/v1/uploads`;async function Nt(e,t,n){let r=`${Mt}?action=getPolicy&model=${encodeURIComponent(t)}`,i=Vt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...B()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new M(`Failed to get upload policy (HTTP ${a.status}): ${e}`,j.GENERAL)}return(await a.json()).data}async function Pt(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=Vt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...B()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new M(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,j.GENERAL)}return`oss://${i}`}const Ft={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function It(e){if(!i(e))throw new M(`File not found: ${e}`,j.USAGE);if(!l(e).isFile())throw new M(`Not a file: ${e}`,j.USAGE);let t=h(e).toLowerCase(),n=Ft[t];if(!n)throw new M(`Unsupported image format "${t||`unknown`}".`,j.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function Lt(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function Rt(e){let{apiKey:t,model:n,filePath:r,signal:a}=e;if(!i(r))throw new M(`File not found: ${r}`,j.USAGE);if(!l(r).isFile())throw new M(`Not a file: ${r}`,j.USAGE);return Pt(await Nt(t,n,a),r,a)}function zt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Bt(e,t,n,r={}){return zt(e)?Rt({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function Vt(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 Ht(e){return`/api/v1/mcps/${e}/mcp`}var Ut=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 M(`This command needs a model-domain API key.`,j.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 M(`MCP error (${r.error.code}): ${r.error.message}`,j.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}`,...B()};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 M(e,j.GENERAL)}return r}};const Wt={"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 Gt(e,t){return Wt[e]?.[t]??Wt[`cn-beijing`][t]}function Kt(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 qt(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 V(e,t,{api:n,data:r},i){let a=Gt(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=qt(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 M(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,j.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 M(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?j.AUTH:j.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var Jt=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new M(`This command needs a model-domain API key.`,j.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new M(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,j.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}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 wt(this.http,this.toOpts(e))}requestJson(e){return Et(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return zt(e)?Bt(e,this.requireApi().token,t,n):Promise.resolve(e)}resolveImageInput(e,t,n={}){return zt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(It(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){if(this.deps.settings.configName===`token-plan`)return!0;try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Ut(this.http,t,this.deps.apiCred?.token)}async console(e,t){if(!this.deps.consoleCred)throw new M(`This command needs a console access token.`,j.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await V(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof M)||e.exitCode!==j.AUTH||!e.message.includes(`not logged in`))throw e;let t=await $t({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await V({...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?Dt(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Ot({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: ${yt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${yt(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,...B()},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 M(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,j.GENERAL)}if(!s.ok||l.Success===!1)throw new M(`${l.Code||s.status} - ${l.Message||s.statusText}`,j.GENERAL);return l}};const Yt={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function Xt(e){for(let[t,n]of Object.entries(Ie))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function Zt(e){return Yt[Xt(e)]??Yt.cn}async function Qt(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Jt({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=Zt(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function $t(e){let t=e.settings.configName,n=R(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 Qt({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=R(t);return o.access_token=a,await z(o,t),a}function en(){return`/compatible-mode/v1/chat/completions`}function tn(){return`/api/v1/services/aigc/image-generation/generation`}function nn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function rn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function an(){return`/api/v1/services/aigc/image2image/image-synthesis`}function on(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function sn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function cn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function ln(){return`/api/v2/apps/memory/add`}function un(){return`/api/v2/apps/memory/memory_nodes/search`}function dn(){return`/api/v2/apps/memory/memory_nodes`}function fn(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function pn(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function mn(){return`/api/v1/services/audio/asr/transcription`}function hn(){return`/api/v2/apps/memory/profile_schemas`}function gn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function _n(){return`/api/v1/indices/rag/index/retrieve`}function vn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function yn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function bn(){return`/api/v1/mcps/WebSearch/mcp`}function xn(){return`/compatible-mode/v1/files`}function Sn(){return`/api/v1/files`}function Cn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function wn(){return`/api/v1/fine-tunes`}function Tn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function En(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Dn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function On(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function kn(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function An(){return`/api/v1/deployments`}function jn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Mn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function Nn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function Pn(){return`/api/v1/deployments/models`}const Fn=[`qwen-image`,`wan2.7-image`,`z-image`],In=[`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function Ln(e,t){return t.some(t=>e.startsWith(t))}function Rn(e){return Ln(e,Fn)||e.startsWith(`wan2.6-image`)}function zn(e){return Ln(e,Fn)}function Bn(e){return Ln(e,In)}function Vn(e){return/^wanx-v1(?:-|$)/i.test(e)}function Hn(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||zn(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||Vn(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function Un(e){return/wan2\.5-i2i/i.test(e)}function Wn(e){return/imageedit/i.test(e)}function Gn(e){return e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:Vn(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Hn(e)?`wan-legacy`:`wan26`}function Kn(e){if(e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function H(e,t){return{...e,sizeProfile:Gn(t),promptExtendDefault:Kn(t)}}function qn(e){return zn(e)?H({kind:`sync-multimodal`,path:nn(),useSync:!0,inputStyle:`messages`},e):Hn(e)?H({kind:`async-text2image`,path:rn(),useSync:!1,inputStyle:`prompt`},e):H({kind:`async-image-generation`,path:tn(),useSync:!1,inputStyle:`messages`},e)}function Jn(e){return Bn(e)?H({kind:`sync-multimodal`,path:nn(),useSync:!0,inputStyle:`messages`},e):Wn(e)?H({kind:`async-image2image`,path:an(),useSync:!1,inputStyle:`function-base-image`},e):Un(e)?H({kind:`async-image2image`,path:an(),useSync:!1,inputStyle:`prompt-images`},e):H({kind:`async-image-generation`,path:tn(),useSync:!1,inputStyle:`messages`},e)}function Yn(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function Xn(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Zn(e){return async(t,n={})=>{let r=Xn(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),Yn(r))for(let[e,t]of Object.entries(B()))i.set(e,t);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${yt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Qn=`2024-08-16`;function $n(e){return`bailiancontrol.${e}.aliyuncs.com`}function er(e){return new Jt({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function tr(e){return er(e).openApiJson({host:$n(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Qn,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function nr(e){return er(e).openApiJson({host:$n(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Qn,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function rr(e){return er(e).openApiJson({host:$n(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Qn,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}async function*ir(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 M(`SSE stream exceeded the maximum buffer size.`,j.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 M(`SSE event exceeded the maximum buffer size.`,j.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 ar=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,or=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function sr(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 cr(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=sr(await e(ar,{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 lr(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=sr(await e(ar,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function ur(e,t){return(sr(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 dr=[`name`,`key`,`default`,`tip`,`range`];function fr(e){return e.map(e=>{let t={};for(let n of dr)e[n]!==void 0&&(t[n]=e[n]);return t})}async function pr(e,t){let n=sr(await e(or,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?fr(e):null}catch{return null}return Array.isArray(n)?fr(n):null}function mr(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Pe(String(r)):r;await z(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await z(n,e)},profiles:()=>ut(),activate:e=>pt(e),validateActivation:e=>ft(e),get path(){return P()}}}const hr={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function gr(e){return e?hr[e]:void 0}async function _r(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.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:xn(),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,request_id:f.request_id};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new M(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,j.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new M(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,j.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 vr(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=Sn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function yr(e,t,n){return e.requestJson({path:Cn(t),method:`GET`,signal:n})}async function br(e,t,n){let r=await e.request({path:Cn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const xr=300*1024*1024,Sr=1024*1024*1024;function Cr(e,t=xr){if(!i(e))throw new M(`File not found: ${e}`,j.USAGE);let n=l(e);if(!n.isFile())throw new M(`Not a regular file: ${e}`,j.USAGE);if(n.size===0)throw new M(`File is empty: ${e}`,j.USAGE);if(n.size>t)throw new M(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,j.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function U(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function wr(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 M(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,j.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function Tr(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 Er=new Set([`system`,`user`,`assistant`]);function Dr(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(U(`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`||!Er.has(a))&&r.push(U(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(U(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function Or(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(U(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(U(`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(...Dr(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(U(`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(U(`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(U(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(U(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const kr={name:`chatml`,detect:()=>!0,inspect:Or};function Ar(e,t){let n=[];if(!(`text`in e))return n.push(U(`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(U(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(U(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const jr={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ar};function Mr(e,t){let n=Or(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(U(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(U(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...Dr(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(U(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...Dr(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(U(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Nr={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Mr};function Pr(e,t){let n=[];if(!(`wav_fn`in e))n.push(U(`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(U(`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(U(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(U(`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(U(`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(U(`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(U(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(U(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Fr={name:`tts`,detect:e=>`wav_fn`in e,inspect:Pr},Ir=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function Lr(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Rr(e){return/^[\x20-\x7E]+$/.test(e)}function zr(e,t){let n=[];if(!(`prompt`in e))n.push(U(`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(U(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(U(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(U(`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(U(`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(U(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Lr(r);Ir.has(e)||n.push(U(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ir].join(`, `)}.`,{line:t,path:`img_path`})),Rr(r)||n.push(U(`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(U(`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(U(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Lr(r);Ir.has(e)||n.push(U(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ir].join(`, `)}.`,{line:t,path:`input_img`})),Rr(r)||n.push(U(`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 Br={name:`image`,detect:e=>`img_path`in e,inspect:zr},Vr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Hr=new Set([`.mp4`,`.mov`]);function Ur(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Wr(e){return/^[\x20-\x7E]+$/.test(e)}function Gr(e,t,n,r,i,a){if(!(n in t)){r&&e.push(U(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(U(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(U(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Ur(o);i.has(s)||e.push(U(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Wr(o)||e.push(U(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Kr(e,t){let n=[];if(!(`prompt`in e))n.push(U(`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(U(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(U(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Gr(n,e,`first_frame_path`,!0,Vr,t),Gr(n,e,`last_frame_path`,!1,Vr,t),Gr(n,e,`video_path`,!1,Hr,t),n}const qr=[Fr,Br,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Kr},Nr,jr,kr];function Jr(e,t){return t===void 0?qr.find(t=>t.detect(e))??kr:qr.find(e=>e.name===t)||kr}async function Yr(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(U(`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 Xr(e,t,r,i,a){let o=r?null:new Set(Tr(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(U(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Zr(n,u,i))}return{sampled:c,issues:s}}function Zr(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[U(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Jr(r,n).inspect(r,t)}const Qr={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Yr(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[U(`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 Xr(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 $r(e,t){return new Promise((n,r)=>{b.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 ei(e){return new Promise((t,n)=>{b.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 ti(e,t,n){let{entry:i,zipfile:a}=await $r(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}ae(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function ni(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 ri={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await ei(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[U(`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:[U(`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(U(`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(U(`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 Ir.has(n)});e.length<25&&r.push(U(`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-${ne(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await ti(e,m,_)}catch(t){return r.push(U(`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 Qr.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await ni(_),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(U(`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 ii(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return ai(e);if(t===`.zip`)return oi(e);throw new M(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,j.USAGE)}async function ai(e){let t=await ci(e);if(!t)throw new M(`JSONL file is empty or contains only blank lines: ${e}`,j.USAGE);let n=si(t);return n===`unknown`?`text`:n}async function oi(e){let t=await li(e,`data.jsonl`);if(!t)throw new M(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,j.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=si(t);if(n===`unknown`)throw new M(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,j.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function si(e){let t;try{t=JSON.parse(e)}catch{throw new M(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,j.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new M(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,j.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 ci(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 li(e,t){return $r(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new M(`Failed to read "${t}" from ZIP: ${e?.message}`,j.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 ui=[Qr,ri];function di(e){let t=h(e).toLowerCase(),n=ui.find(e=>e.extensions.includes(t));if(!n){let e=ui.flatMap(e=>e.extensions).join(`, `);throw new M(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,j.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function fi(e){ui.some(t=>t.format===e.format)||ui.push(e)}async function W(e,t={}){let{bytes:n}=Cr(e,t.maxBytes??314572800),r=await di(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function pi(){return ui.map(e=>({format:e.format,extensions:[...e.extensions]}))}function mi(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 hi(e,t,n){return e.requestJson({path:wn(),method:`POST`,body:t,signal:n})}async function gi(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=wn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function _i(e,t,n){return e.requestJson({path:Tn(t),method:`GET`,signal:n})}async function vi(e,t,n){return e.requestJson({path:En(t),method:`POST`,signal:n})}async function yi(e,t,n){return e.requestJson({path:Tn(t),method:`DELETE`,signal:n})}async function bi(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=Dn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function xi(e,t,n){return e.requestJson({path:On(t),method:`GET`,signal:n})}async function Si(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${kn(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const Ci={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`}},wi=Object.keys(Ci),Ti=`sft-lora`;function Ei(e){return e in Ci}function Di(e){let{method:t,variant:n}=Ci[e];return{method:t,variant:n}}function Oi(e,t){if(!e)return!1;let{method:n,variant:r}=Ci[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function ki(e){return e?wi.filter(t=>Oi(e,t)):[]}async function Ai(e,t){let n=Kt(e);return(await cr((t,r)=>V({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 ji=`INSUFFICIENT_SAMPLES`;function Mi(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ji,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 Ni(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 Pi(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return W(e,{...r,schema:n})},resolveHyperParameters(e,t){return Ni(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const Fi=Pi(`sft`,`sft`,`chatml`),Ii={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},Li={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},Ri={...Li,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},zi={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 Bi(e){return e===`image`||e===`image-i2i`}function Vi(e){return e===`video`||e===`video-kf2v`}function Hi(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const Ui=[Fi,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return W(e,{...n,schema:`tts`});if(Bi(t))return W(e,{...n,schema:`image`,maxBytes:Sr});if(Vi(t)){let r=await W(e,{...n,schema:`video`,maxBytes:Sr});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(U(`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(U(`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 W(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Ii};if(Bi(e)){let n={...e===`image-i2i`?Ri:Li};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Vi(e)){let e=Hi(t.model),n={...zi,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 Ni(t)},shouldSkipGate(e,t){return!!((t===`audio`||Bi(t)||Vi(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Bi(e)||Vi(e)}},Pi(`dpo`,`dpo_full`,`dpo`),Pi(`dpo-lora`,`dpo_lora`,`dpo`),Pi(`cpt`,`cpt`,`cpt`)];function Wi(e){let t=Ui.find(t=>t.clientTrainingType===e);if(!t){let t=Ui.map(e=>e.clientTrainingType).join(`, `);throw new M(`Unknown training type "${e}".`,j.USAGE,`Supported training types: ${t}.`)}return t}function Gi(){return Ui.map(e=>e.clientTrainingType)}async function Ki(e,t,n){return e.requestJson({path:An(),method:`POST`,body:t,signal:n})}async function qi(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=An(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ji(e,t,n){return e.requestJson({path:jn(t),method:`GET`,signal:n})}async function Yi(e,t,n){return e.requestJson({path:jn(t),method:`DELETE`,signal:n})}async function Xi(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=Pn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Zi(e,t,n,r){return e.requestJson({path:Mn(t),method:`PUT`,body:n,signal:r})}async function Qi(e,t,n,r){return e.requestJson({path:Nn(t),method:`PUT`,body:n,signal:r})}const G={LORA:`lora`,PTU:`ptu`,MU:`mu`},$i=G.LORA;function ea(e){return e===`audio`?G.MU:$i}const ta={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},na=ta.POST_PAY,ra={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},ia={name:G.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},aa={name:G.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}}}},oa={name:G.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||na,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new M(`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.`,j.USAGE);try{let a=await Xi(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===G.MU)?.templates??[];if(o.length===0)throw i();let s=t===ta.POST_PAY?ra.POST_PAID:ra.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 M?e:new M(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,j.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},sa={[G.LORA]:ia,[G.PTU]:aa,[G.MU]:oa};function ca(e){let t=sa[e];if(!t)throw new M(`Unsupported plan "${e}". Supported plans: ${Object.keys(sa).join(`, `)}.`,j.USAGE);return t}const la={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`}},ua={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},da={async:{type:`switch`,description:`Return async task id without waiting`}},fa={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},pa={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)`}},ma={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 ha(e){return e.auth===`apiKey`?fa:e.auth===`console`?pa:e.auth===`openapi`?ma:{}}function ga(e){return e}const _a=1;function va(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function ya(e,t){return`${va(e||`image`,`image`)}_${va((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const ba=()=>g(f(),`bailian-output`);function xa(e,t){let n=t?.flagDir||e.outputDir||ba(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Sa(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Ca(e){return o(e===`-`?0:e,`utf-8`)}async function wa(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function Ta(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 M(`Invalid ${t} value "${String(e)}". Use true or false.`,j.USAGE)}function Ea(e,t=`boolean`){if(e!=null)return Ta(e,t)}function Da(e,t,n=`boolean`){let r=Ea(e,n);return r===void 0?t:r}function Oa(e){return Ea(e,`watermark`)??!0}function ka(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 Aa(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function ja(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=Aa(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let K;function Ma(){return K||(process.env.NODE_ENV===`development`?(K=`dev`,K):process.env.BAILIAN_COMPILED===`1`?(K=`prod`,K):(K=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,K))}var Na=De(((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=Ae(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Ae(`dns`)},function(e,t){e.exports=Ae(`util`)},function(e,t){e.exports=Ae(`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`},ie=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},y=(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`},oe=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},O=(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`,ee),k.set(`Spider`,te),k.set(`Ai2Bot-Dolma`,ne),k.set(`dianjing_ad_spider`,re),A.set(`Baiduspider-render`,ie),A.set(`Baiduspider+`,ie),A.set(`Baiduspider-image+`,ie),A.set(`360Spider`,y),A.set(`360Spider-Image`,y),A.set(`bingbot`,ae),A.set(`Googlebot`,b),A.set(`YandexRenderResourcesBot`,oe),A.set(`spider`,se),A.set(`Dataprovider.com`,x),A.set(`AhrefsBot`,ce),A.set(`BitSightBot`,S),A.set(`oBot`,C),A.set(`Cincraw`,w),A.set(`DingTalkBot-LinkService`,le),A.set(`YisouSpider`,T),A.set(`Bytespider`,E),A.set(`ev-crawler`,ue),A.set(`bitdiscovery`,de),A.set(`Spider`,D),A.set(`Ai2Bot-Dolma`,O),A.set(`dianjing_ad_spider`,fe);let pe={productHandlerMap:k,commentHandlerMap:A,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,pe),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),ie=n(4),y=n(5),ae=n.n(y);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 oe(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 se(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oe(Object(n),!0).forEach(function(t){x(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function x(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 ce(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=C(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 S(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)||C(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 C(e,t){if(e){if(typeof e==`string`)return w(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)?w(e,t):void 0}}function w(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 le(){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=S(r[n],2),o=(a[0],a[1]);if(o){var s,c=ce(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 T,E,ue=(T=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:T,device_id:ae.a.createHash(`md5`).update(le()).digest(`hex`),platform:`node`}),de=(0,ie.promisify)(re.a.resolve);function D(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,te.call(this,se(se({},ue),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}D.prototype=((E=function(){}).prototype=te.prototype,new E),D.prototype.constructor=D,D.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,de(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=D}]).default})),Pa=De(((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})),Fa=ke(Na(),1),Ia=ke(Pa(),1);const La=()=>g(N(),`telemetry.jsonl`);let Ra;const za=new Set;let Ba;try{let e=new Fa.default({pid:`bailian-cli-node`,env:Ma()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;za.add(e),e.finally(()=>za.delete(e))}return n},Ba=e,Ra=e.use(Ia.default)}catch{}async function Va(e=1e3){try{if(Ba)try{typeof Ba._sendAll==`function`&&Ba._sendAll()}catch{}if(za.size===0)return;let t=[...za].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Ha(e){try{await $e();let n=La();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
11
+ `,{mode:384})}catch{}}async function Ua(e){try{if(!Ra)return;Ra(e.command,ja(e))}catch{}}const Wa=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),Ga=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 Ka(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||Wa.has(n)||Ga.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function qa(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 M?(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=ka({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:Ka(n)});Ha(l).catch(()=>{}),Ua(l).catch(()=>{})}}function Ja(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 Ya=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=Kt(this.settings),t=(t,n)=>V({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await cr(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await cr(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(Ja).filter(e=>e!==null)}};function Xa(){return k(N(),`skills/bailian-docs-llm-wiki`)}function Za(){return k(Xa(),`models`,`models.jsonl`)}function Qa(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 $a(e){let t=C(e,`utf-8`).split(`
12
+ `).filter(Boolean),n=[];for(let e of t)try{let t=Qa(JSON.parse(e));t&&n.push(t)}catch{}return n}var eo=class{name=`catalog`;constructor(e){}available(){return x(Za())}async load(){return this.available()?$a(Za()):[]}};async function to(e,t){let n=[new eo({onPrepareStart:t?.onPrepareStart}),new Ya(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 M(`No model data available.`,j.GENERAL)}const no={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},q={Single:`single`,Pipeline:`pipeline`},ro={Low:`low`,Medium:`medium`,High:`high`},io={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},J={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},Y={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`},ao={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},X={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},oo=20,so=/-\d{4}-\d{2}-\d{2}$/,co=new Set([Y.IG,Y.VG,Y.TTS,Y.RealtimeTTS,Y.ThreeDGeneration]),lo=new Set([Y.TG,Y.Reasoning,Y.ASR,Y.RealtimeASR,Y.RealtimeAudioTranslate,Y.TR,Y.ME]),uo={standard:0,large:32e3,"extra-large":128e3},fo=.4,po=.6,mo=.4,ho=.2,go=.2,_o=.2;console.assert(Math.abs(fo+po-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(mo+ho+go+_o-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const vo=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
13
13
 
14
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.
15
15
 
@@ -50,7 +50,7 @@ Single task:
50
50
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
51
51
 
52
52
  Pipeline (only when confident multi-model is needed):
53
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,to=`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"]}]}]}`,yo=`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.
54
54
 
55
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.
56
56
 
@@ -89,7 +89,7 @@ Key principles:
89
89
 
90
90
  Or (if single model suffices):
91
91
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
92
- ["key highlights"]}]}`,$={complexity:Y.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[Z.TG],requiredFeatures:[],budget:Ba.Medium,contextNeed:Va.Standard,qualityPreference:X.Balanced,confidence:0},no=[`unconstrained`,`scoped`,`comparison`,`alternative`];function ro(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&no.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 io(e,t){let n=Pt(),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"]}]}`,bo={complexity:q.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[Y.TG],requiredFeatures:[],budget:ro.Medium,contextNeed:io.Standard,qualityPreference:J.Balanced,confidence:0},xo=[`unconstrained`,`scoped`,`comparison`,`alternative`];function So(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&xo.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 Co(e,t){let n=en(),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.
93
93
 
94
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.
95
95
 
@@ -136,9 +136,9 @@ Analyze whether the user mentioned specific models, model families, or vendors:
136
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
137
137
  - modelPreference: { mode, targets?, excludes? }
138
138
 
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{...$}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...$};let o=JSON.parse(a[0]),s=o.modelPreference,c=ro(s);return{complexity:o.complexity===Y.Pipeline?Y.Pipeline:Y.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??$.budget,contextNeed:o.contextNeed??$.contextNeed,qualityPreference:o.qualityPreference??$.qualityPreference,confidence:1,modelPreference:c}}function ao(e){let t=!1,n=!1;for(let r of e)Ga.has(r)&&(t=!0),Ka.has(r)&&(n=!0);return t&&n}function oo(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Wa,``);return n===e?!0:!t.has(n)})}function so(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 co(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function lo(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=qa[i];return d>0&&(c??0)>=d&&(u+=8),a===X.Flagship&&l===Q.Flagship||a===X.CostOptimized&&l===Q.CostOptimized?u+=15:a===X.Balanced&&l===Q.Flagship&&(u+=5),u}function uo(e,t,n){return e.map(e=>({model:e,score:lo(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function fo(e){return new Set(e.map(({model:e})=>e.model))}function po(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 mo(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function ho(e,t,n){return n.size>=10?[]:uo(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function go(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:Y.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:Va.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>so(e,a,o)&&co(e,n));return l.length<5&&(l=e.filter(e=>so(e,a,o))),l.length<5&&(l=e),uo(l,c,5)}function _o(e,t){e=oo(e);let n;if(t.complexity===Y.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=mo(go(e,i,a,t.budget,t.qualityPreference),fo(r));r=[...r,...o]}let i=ho(e,t,fo(r));n=[...r,...i]}else if(ao(t.requiredCapabilities))n=vo(e,t);else{let r=e.filter(e=>so(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=uo(r,t,50)}return po(n,3)}function vo(e,t){let n=t.requiredCapabilities.filter(e=>Ga.has(e)),r=t.requiredCapabilities.filter(e=>Ka.has(e)),i=[];if(n.length>0&&(i=uo(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=fo(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...uo(o,a,25)]}let a=ho(e,t,fo(i));return[...i,...a]}const yo=`text-embedding-v4`;function bo(){return T(P(),`skills/bailian-docs-llm-wiki`)}function xo(){return T(bo(),`models-embeddings.json`)}function So(){let e=xo();if(!x(e))return null;try{return JSON.parse(C(e,`utf-8`)).items}catch{return null}}async function Co(e,t){let n={model:yo,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 wo(e,t){let n={model:yo,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 To={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Eo={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Do(){let e=T(bo(),`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=>To[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Eo[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Eo[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 ko(e,t){let n=Do(),r=t.map(e=>Oo(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await wo(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:yo,dimensions:512,count:a.length,items:a},s=xo();return S(w(s),{recursive:!0}),se(s,JSON.stringify(o)),a}function Ao(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 jo=null;function Mo(){return jo===null&&(jo=So()),jo}function No(){return Mo()!==null}function Po(e){return(e??``).toLowerCase().replace(Wa,``).replace(/[\s_-]+/g,``).trim()}function Fo(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 Io(e,t){return t.some(t=>Fo(e,t))}function Lo(e,t){return t.length===0?[]:e.filter(e=>Io(e,t))}function Ro(e,t){return t.length===0?e:e.filter(({model:e})=>!Io(e,t))}function zo(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 Bo(e,t){return zo(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Vo(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=qa[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===X.Flagship?u=e.category===Q.Flagship?1:.5:a===X.CostOptimized&&(u=e.category===Q.CostOptimized?1:.5),Xa*o+Za*s+Qa*c+$a*u}function Ho(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Bo(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function Uo(e,t){return zo(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Wo(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=Ao(t,e.vector),o=a?Vo(n,a):0;return[{model:n,score:a?Ja*o+Ya*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 Go(e){return{model:e,score:1,hardScore:1,softScore:1}}function Ko(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?Lo(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Go(e));let r=new Set(l.map(({model:e})=>e.model)),s=Wo(t,n,Ho(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 Wo(t,n,Ho(c,o),i,a,o)}function qo(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)Io(t,s)&&!l.has(t.model)&&(c.push(Go(t)),l.add(t.model));return c}function Jo(e,t,n,r,i,a,o){let s=Lo(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Go(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Wo(t,n,Ho(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 Yo(e,t,n,r,i){let a=Mo();if(!a)a=await ko(e,t),jo=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 ko(e,t),jo=a)}let o=await Co(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=Ko(t,a,o,c,r,s,i);break;case`comparison`:e=qo(t,a,o,c,r,s,i);break;case`alternative`:e=Jo(t,a,o,c,r,s,i);break;default:e=[]}return Ro(e,l)}if(i?.complexity===Y.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=>Uo(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Wo(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 Ro(n,l)}let u=Ho(t,i);return Ro(Wo(a,o,u,r,s,i),l)}function Xo(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Zo(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=Xo(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
140
- `)}function Qo(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!==Va.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 $o(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 es(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 ts(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 ns(e,t,n,r,i,a){let o=Zo(t),s=Qo(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{...bo}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...bo};let o=JSON.parse(a[0]),s=o.modelPreference,c=So(s);return{complexity:o.complexity===q.Pipeline?q.Pipeline:q.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??bo.budget,contextNeed:o.contextNeed??bo.contextNeed,qualityPreference:o.qualityPreference??bo.qualityPreference,confidence:1,modelPreference:c}}function wo(e){let t=!1,n=!1;for(let r of e)co.has(r)&&(t=!0),lo.has(r)&&(n=!0);return t&&n}function To(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(so,``);return n===e?!0:!t.has(n)})}function Eo(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 Do(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Oo(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=uo[i];return d>0&&(c??0)>=d&&(u+=8),a===J.Flagship&&l===X.Flagship||a===J.CostOptimized&&l===X.CostOptimized?u+=15:a===J.Balanced&&l===X.Flagship&&(u+=5),u}function ko(e,t,n){return e.map(e=>({model:e,score:Oo(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Ao(e){return new Set(e.map(({model:e})=>e.model))}function jo(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 Mo(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function No(e,t,n){return n.size>=10?[]:ko(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Po(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:q.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:io.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Eo(e,a,o)&&Do(e,n));return l.length<5&&(l=e.filter(e=>Eo(e,a,o))),l.length<5&&(l=e),ko(l,c,5)}function Fo(e,t){e=To(e);let n;if(t.complexity===q.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=Mo(Po(e,i,a,t.budget,t.qualityPreference),Ao(r));r=[...r,...o]}let i=No(e,t,Ao(r));n=[...r,...i]}else if(wo(t.requiredCapabilities))n=Io(e,t);else{let r=e.filter(e=>Eo(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=ko(r,t,50)}return jo(n,3)}function Io(e,t){let n=t.requiredCapabilities.filter(e=>co.has(e)),r=t.requiredCapabilities.filter(e=>lo.has(e)),i=[];if(n.length>0&&(i=ko(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Ao(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...ko(o,a,25)]}let a=No(e,t,Ao(i));return[...i,...a]}const Lo=`text-embedding-v4`;function Ro(){return k(N(),`skills/bailian-docs-llm-wiki`)}function zo(){return k(Ro(),`models-embeddings.json`)}function Bo(){let e=zo();if(!x(e))return null;try{return JSON.parse(C(e,`utf-8`)).items}catch{return null}}async function Vo(e,t){let n={model:Lo,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 Ho(e,t){let n={model:Lo,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 Uo={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Wo={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Go(){let e=k(Ro(),`groups`),t=new Map;if(!x(e))return t;for(let n of w(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(C(k(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 Ko(e,t){let n=(e.capabilities??[]).map(e=>Uo[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Wo[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Wo[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 qo(e,t){let n=Go(),r=t.map(e=>Ko(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Ho(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Lo,dimensions:512,count:a.length,items:a},s=zo();return S(O(s),{recursive:!0}),D(s,JSON.stringify(o)),a}function Jo(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 Z=null;function Yo(){return Z===null&&(Z=Bo()),Z}function Xo(){return Yo()!==null}function Zo(e){return(e??``).toLowerCase().replace(so,``).replace(/[\s_-]+/g,``).trim()}function Qo(e,t){let n=Zo(t);if(!n)return!1;if(Zo(e.model)===n||Zo(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&Zo(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=Zo(e);return t.length>0&&n.includes(t)})}function $o(e,t){return t.some(t=>Qo(e,t))}function es(e,t){return t.length===0?[]:e.filter(e=>$o(e,t))}function ts(e,t){return t.length===0?e:e.filter(({model:e})=>!$o(e,t))}function ns(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 rs(e,t){return ns(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function is(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=uo[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===J.Flagship?u=e.category===X.Flagship?1:.5:a===J.CostOptimized&&(u=e.category===X.CostOptimized?1:.5),mo*o+ho*s+go*c+_o*u}function as(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>rs(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function os(e,t){return ns(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function ss(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=Jo(t,e.vector),o=a?is(n,a):0;return[{model:n,score:a?fo*o+po*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 cs(e){return{model:e,score:1,hardScore:1,softScore:1}}function ls(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?es(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(cs(e));let r=new Set(l.map(({model:e})=>e.model)),s=ss(t,n,as(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 ss(t,n,as(c,o),i,a,o)}function us(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)$o(t,s)&&!l.has(t.model)&&(c.push(cs(t)),l.add(t.model));return c}function ds(e,t,n,r,i,a,o){let s=es(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(cs(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=ss(t,n,as(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 fs(e,t,n,r,i){let a=Yo();if(!a)a=await qo(e,t),Z=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 qo(e,t),Z=a)}let o=await Vo(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=ls(t,a,o,c,r,s,i);break;case`comparison`:e=us(t,a,o,c,r,s,i);break;case`alternative`:e=ds(t,a,o,c,r,s,i);break;default:e=[]}return ts(e,l)}if(i?.complexity===q.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=>os(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=ss(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 ts(n,l)}let u=as(t,i);return ts(ss(a,o,u,r,s,i),l)}function ps(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function ms(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=ps(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
140
+ `)}function hs(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!==io.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 gs(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 _s(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 vs(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 ys(e,t,n,r,i,a){let o=ms(t),s=hs(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.
142
142
 
143
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.
144
144
 
@@ -180,4 +180,6 @@ The intent's modelPreference.targets is the reference model.
180
180
  - Output strict JSON
181
181
 
182
182
  ## Output Format
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===Y.Pipeline?to:eo)+e}else l=n.complexity===Y.Pipeline?to:eo;let u=a?.enableThinking??!1,d=n.complexity===Y.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=Pt(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Rn(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:Y.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===Y.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=es(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return ts(e,g),{type:Y.Pipeline,summary:h.summary??``,steps:e}}let _=es(h.recommendations??h??[],g,i);return{type:Y.Single,recommendations:_}}export{Gi as ASYNC_FLAG,Se as BAILIAN_HOST,Fi as BILLING_METHOD,A as BailianError,Ba as Budgets,et as CHANNEL,Li as CHARGE_TYPE,Zi as COMMAND_PACK_API_VERSION,Wi as CONCURRENT_FLAG,Ce as CONFIG_FILE_KEYS,qi as CONSOLE_AUTH_FLAGS,Z as Capabilities,Ot as Client,Y as Complexities,Va as ContextNeeds,Ii as DEFAULT_BILLING_METHOD,Ni as DEFAULT_DEPLOY_PLAN,ai as DEFAULT_TRAINING_TYPE,J as DEPLOY_PLAN,xe as DOCS_HOSTS,k as ExitCode,Ha as Features,Ui as GLOBAL_FLAGS,di as INSUFFICIENT_SAMPLES_CODE,tr as MAX_DATASET_BYTES,nr as MAX_MEDIA_ZIP_BYTES,Ki as MODEL_AUTH_FLAGS,zn as MODEL_LIST_API,Ct as McpClient,za as Modalities,Q as ModelCategories,Ji as OPENAPI_AUTH_FLAGS,Bn as PREDICT_CONFIG_API,X as QualityPreferences,be as REGIONS,Ua as SEMANTIC_TOP_K,nt as SOURCE_CONFIG,Vi as STRATEGIES,tt as TAGS,ii as TRAINING_TYPES_CLI,ri as TRAINING_TYPE_MAP,ge as UsageError,Je as activateConfigProfile,io as analyzeIntent,Vt as appCompletionPath,St as bailianMcpPath,st as buildAcsCanonicalQuery,$o as buildDocLink,Ze as buildSettings,Xe as buildSources,W as callConsoleGateway,Qr as cancelFineTune,Pt as chatPath,Fn as createBailianControlUser,Ei as createDeployment,Yr as createFineTune,jn as createInstrumentedFetch,ca as createTrackingEvent,Yi as credentialFlagDefs,Pi as defaultDeployPlan,Xi as defineCommand,Ye as deleteConfigProfile,er as deleteDataset,ki as deleteDeployment,$r as deleteFineTune,Ne as describeAuthState,Rr as detectModality,ze as detectOutputFormat,Et as effectiveConsoleGatewayConfig,Fe as ensureConfigDir,ni as exportCheckpoint,ui as fetchModelCapability,Wn as fetchModelDetail,Un as fetchModelGroups,Hn as fetchModelList,qn as fetchPredictConfig,xa as flushTelemetry,Re as formatErrorJson,Jr as formatIssue,Le as formatJson,Be as formatOutput,Ie as formatText,Mt as generateCLIAccessToken,$i as generateFilename,P as getConfigDir,F as getConfigPath,Pe as getCredentialsPath,$n as getDataset,Oi as getDeployment,Zr as getFineTune,ei as getFineTuneLogs,Xn as getModelProfilePreset,Ra as getModels,wi as getProfile,Rt as image2ImagePath,gt as imageFileToDataUri,Ft as imagePath,It as imageSyncPath,Lt as imageText2ImagePath,Cn as isLegacyImage2ImageModel,Sn as isLegacyText2ImageModel,yt as isLocalFile,No as isSemanticAvailable,vn as isSyncMultimodalImageModel,oi as isTrainingTypeCli,wn as isWanxFunctionImageEditModel,Qt as knowledgeChatEndpoint,Xt as knowledgeRetrievePath,Zt as knowledgeSearchEndpoint,In as listBailianControlWorkspaces,ti as listCheckpoints,Qn as listDatasets,Ai as listDeployableModels,Di as listDeployments,Xr as listFineTunes,qr as listSupportedFormats,li as listSupportedTrainingTypes,Ti as listTrainingTypes,Sa as localSink,$e as makeAuthStore,Jn as makeConfigStore,ve as mapApiError,H as maskToken,$t as mcpWebSearchPath,Ht as memoryAddPath,Wt as memoryListPath,Gt as memoryNodePath,Ut as memorySearchPath,ci as modelSupportsTrainingType,R as normalizeConfigName,j as normalizeModelBaseUrl,ia as parseBooleanValue,M as parseConfigFile,ir as parseDatasetSchemaFlag,aa as parseOptionalBooleanValue,Rn as parseSSE,Hi as pickPlanStrategy,Gr as pickValidator,fi as preflightBatchSizeGate,Jt as profileSchemaPath,ns as rankModels,B as readConfigFile,Ge as readConfigProfiles,ra as readTextFromPathOrStdin,_o as recallCandidates,Yo as recallSemantic,_t as redactDataUri,Nt as refreshAccessToken,Kr as registerValidator,Ca as remoteSink,it as request,ot as requestJson,Ln as resetBailianControlPolicies4Agent,Oe as resolveApiKey,oa as resolveBooleanFlag,ke as resolveConsole,bt as resolveFileUrl,On as resolveImageEditApi,Dn as resolveImageGenerateApi,Tn as resolveImageSizeProfile,De as resolveModelBaseUrl,Ae as resolveOpenApi,ta as resolveOutputDir,En as resolvePromptExtendDefault,sa as resolveWatermark,ji as scaleDeployment,ct as signAcsRequest,qt as speechRecognizePath,Kt as speechSynthesizePath,na as stripUndefined,Bt as taskPath,Da as trackCommandExecution,U as trackingHeaders,si as trainingTypeMethodVariant,Vn as unwrapResponse,Mi as updateDeployment,Zn as uploadDataset,vt as uploadFile,Yt as userProfilePath,qe as validateConfigProfileActivation,q as validateDataset,zt as videoGeneratePath,V 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===q.Pipeline?yo:vo)+e}else l=n.complexity===q.Pipeline?yo:vo;let u=a?.enableThinking??!1,d=n.complexity===q.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=en(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of ir(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:q.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===q.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=_s(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return vs(e,g),{type:q.Pipeline,summary:h.summary??``,steps:e}}let _=_s(h.recommendations??h??[],g,i);return{type:q.Single,recommendations:_}}function Q(){return k(N(),`skills`)}function bs(){return k(Q(),`skill-lock.json`)}function xs(){return{version:1,skills:{}}}function Ss(){let e=bs();if(!x(e))return xs();try{let t=JSON.parse(C(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?xs():t}catch{return xs()}}function Cs(e){S(Q(),{recursive:!0}),D(bs(),JSON.stringify(e,null,2)+`
184
+ `)}function ws(e,t){let n=Ss();n.skills[e]={...n.skills[e],...t},Cs(n)}function Ts(){let e=me(),t=process.env.XDG_CONFIG_HOME||k(e,`.config`),n=(t,n,r)=>({id:t,displayName:n,skillsDir:k(e,r,`skills`),detectDirs:[k(e,r)]});return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:k(e,`.agents`,`skills`),detectDirs:[k(e,`.agents`),k(e,`.cline`)]},n(`claude-code`,`Claude Code`,`.claude`),n(`openclaw`,`OpenClaw`,`.openclaw`),n(`hermes`,`Hermes Agent`,`.hermes`),{id:`opencode`,displayName:`OpenCode`,skillsDir:k(t,`opencode`,`skills`),detectDirs:[k(t,`opencode`)]},n(`cursor`,`Cursor`,`.cursor`),n(`codex`,`Codex`,`.codex`),n(`qwen-code`,`Qwen Code`,`.qwen`),n(`qoder`,`Qoder`,`.qoder`),n(`qoder-cn`,`Qoder CN`,`.qoder-cn`),n(`kilo`,`Kilo Code`,`.kilocode`)]}function Es(){return Ts().filter(e=>e.detectDirs.some(e=>x(e)))}function Ds(e){try{if(!ce(e).isSymbolicLink())return!1;let t=le(e),n=fe(t)?t:A(O(e),t);return n===Q()||n.startsWith(Q()+pe)}catch{return!1}}function Os(e,t=Es()){let n=k(Q(),e),r=[];for(let i of t){let t=k(i.skillsDir,e);try{let e=!1;try{ce(t),e=!0}catch{}if(e){if(!Ds(t)){r.push({agent:i.id,path:t,mode:`skipped`,reason:`existing file/dir not managed by bl skill`});continue}E(t)}S(i.skillsDir,{recursive:!0});try{de(n,t,process.platform===`win32`?`junction`:`dir`),r.push({agent:i.id,path:t,mode:`symlink`})}catch{oe(n,t,{recursive:!0}),r.push({agent:i.id,path:t,mode:`copy`})}}catch(e){r.push({agent:i.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return r}function ks(e,t=[]){let n=[],r=new Set(t);for(let t of Ts())r.add(k(t.skillsDir,e));for(let e of r)try{let r;try{r=ce(e)}catch{continue}r.isSymbolicLink()?Ds(e)&&(E(e),n.push(e)):t.includes(e)&&(E(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function As(e){return e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function js(e,t){let n=ye.extract();n.on(`entry`,(e,r,i)=>{if(!As(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=k(t,e.name);if(e.type===`directory`){S(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}S(O(a),{recursive:!0});let o=se(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await _e(ge.from(e),ve(),n)}function Ms(e){let t=[],n=r=>{for(let i of w(r?k(e,r):e,{withFileTypes:!0})){let e=r?`${r}/${i.name}`:i.name;i.isDirectory()?n(e):i.isFile()&&t.push(e)}};n(``),t.sort((e,t)=>e<t?-1:+(e>t));let r=he(`sha256`);for(let n of t)r.update(n),r.update(C(k(e,n)));return`sha256:${r.digest(`hex`)}`}function Ns(e,t){S(O(t),{recursive:!0});let n=`${t}.old-${Date.now()}`;x(t)&&T(t,n);try{T(e,t)}catch(e){throw x(n)&&!x(t)&&T(n,t),e}x(n)&&E(n,{recursive:!0,force:!0})}function Ps(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function Fs(e=1e4){let t=`${Ps()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new M(`Cannot access skill registry: ${t}`,j.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new M(`Skill registry returned HTTP ${n.status}: ${t}`,j.NETWORK,n.status===404?`Skill index not yet published or registry URL is incorrect; confirm the publisher has generated index.json`:`Remote error, retry later`);let r;try{r=await n.json()}catch(e){throw new M(`Skill index index.json is not valid JSON`,j.GENERAL,`Remote may be in the middle of publishing, retry later`,{cause:e})}let i=r;if(typeof i!=`object`||!i||typeof i.skills!=`object`||i.skills===null)throw new M(`Skill index index.json has invalid structure`,j.GENERAL,`Retry later or contact the publisher`);return i}const Is=/^sha256-[0-9a-f]{64}\.tar\.br$/;function Ls(e){let t=e?.object;return t&&Is.test(t)?t:`skill.tar.br`}async function Rs(e,t){let n=`${Ps()}/${e}/${Ls(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new M(`Failed to download skill ${e}: ${n}`,j.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new M(`Failed to download skill ${e}: HTTP ${r.status}`,j.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())}function zs(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function Bs(e){return e.length>0&&zs(e)===e}function $(e,t){throw new M(`Skill ${e} validation failed: ${t}`,j.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function Vs(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function Hs(e,t){let n=k(e,`SKILL.md`),r;try{ue(n).isFile()||$(t,`SKILL.md is not a regular file`),r=C(n,`utf-8`)}catch(e){if(e instanceof M)throw e;$(t,`missing SKILL.md`)}let i=Vs(r);i===null&&$(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{$(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&$(t,`frontmatter is not a key-value structure`);let o=a,s=typeof o.name==`string`?o.name.trim():``,c=typeof o.description==`string`?o.description.trim():``;return(!s||!c)&&$(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function Us(e){if(!Bs(e))throw new M(`Invalid skill name: ${e}`,j.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function Ws(e,t,n){Us(e);let r=Q(),i=k(r,e),a=k(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(S(a,{recursive:!0}),await js(t,a),n?.startsWith(`sha256:`)){let t=Ms(a);if(t!==n)throw new M(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,j.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=Hs(a,e);return Ns(a,i),{name:e,path:i,meta:r}}finally{x(a)&&E(a,{recursive:!0,force:!0})}}async function Gs(e,t){if(t.compression&&t.compression!==`tar.br`)throw new M(`Skill ${e} uses unsupported compression format: ${t.compression}`,j.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return Ws(e,await Rs(e,t),t.contentHash)}function Ks(e){Us(e);let t=k(Q(),e);return x(t)?(E(t,{recursive:!0,force:!0}),!0):!1}function qs(e,t){return{...e.contentHash?{contentHash:e.contentHash}:{},...e.publishedAt?{publishedAt:e.publishedAt}:{},installedAt:new Date().toISOString(),sourceType:`oss`,...e.description?{description:e.description}:{},links:t}}async function Js(e,t,n=Es()){await Gs(e,t);let r=Os(e,n).filter(e=>e.mode!==`skipped`);return{lockEntry:qs(t,r.map(e=>e.path)),linkedAgents:r.map(e=>e.agent)}}const Ys=`bailian-docs-llm-wiki`;function Xs(){return k(N(),`skills/bailian-docs-llm-wiki`)}function Zs(){return x(k(Xs(),`models`,`models.jsonl`))}function Qs(){return k(N(),`wiki-sync-state.json`)}function $s(){try{return JSON.parse(C(Qs(),`utf-8`))}catch{return null}}function ec(e){try{D(Qs(),JSON.stringify(e))}catch{}}function tc(e){try{ws(Ys,e)}catch{}}function nc(e){try{return Ss().skills[Ys]?.contentHash===e}catch{return!1}}async function rc(){try{return(await Fs(3e3)).skills[Ys]??null}catch{return null}}async function ic(){let e=$s(),t=Date.now();if(e&&t-e.lastChecked<432e5&&Zs())return!1;let n=await rc();if(!n?.contentHash)return!1;if(Zs()&&(!e||e.contentHash===n.contentHash))return ec({lastChecked:t,contentHash:n.contentHash}),nc(n.contentHash)||tc(qs(n,[])),!1;try{tc((await Js(Ys,n)).lockEntry)}catch{return!1}return ec({lastChecked:t,contentHash:n.contentHash}),!0}const ac=`bailian-cli`,oc=`install-method`,sc=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function cc(e){return e?k(N(),`${oc}.${e}`):k(N(),oc)}function lc(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function uc(e){if(!e)return null;let t=e.trim().toLowerCase();return sc.has(t)?t:null}function dc(e){try{return uc(C(e,`utf-8`).split(`
185
+ `)[0])}catch{return null}}function fc(){let e=uc(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(lc()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function pc(e){let t=uc(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=dc(cc(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=dc(cc());if(e)return e}return fc()}return dc(cc())||fc()}function mc(e){let t=pc(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function hc(e,t={clientName:ac}){try{let n=N();x(n)||S(n,{recursive:!0,mode:448}),D(cc(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&D(cc(),`${e}\n`,{mode:384})}catch{}}const gc=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,_c=`https://github.com/modelstudioai/cli/releases`,vc=`https://bailian.aliyun.com/cli/install.sh`,yc=`https://bailian.aliyun.com/cli/install.ps1`;function bc(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):gc}function xc(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${bc()}/manifest.json`:`${bc()}/${t}.json`}function Sc(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${bc()}/${n}/${t}`}function Cc(){let e=process.platform,t=process.arch,n;if(e===`darwin`)n=`darwin`;else if(e===`linux`)n=`linux`;else if(e===`win32`)n=`windows`;else throw Error(`Unsupported platform for binary updates: ${e}`);let r;if(t===`arm64`)r=`arm64`;else if(t===`x64`)r=`x64`;else throw Error(`Unsupported architecture for binary updates: ${t}`);if(n===`linux`&&r===`arm64`)throw Error(`linux arm64 is not supported for binary updates; use: npm install -g bailian-cli`);if(n===`windows`&&r===`arm64`)throw Error(`windows arm64 is not supported for binary updates; use: npm install -g bailian-cli`);return{os:n,arch:r,fileSuffix:e===`win32`?`.exe`:``}}function wc(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function Tc(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function Ec(e){return new Promise((t,n)=>{b.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??Error(`Failed to open zip: ${e}`));return}t(i)})})}function Dc(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function Oc(e,t,n){let r=await Ec(e);return new Promise((i,a)=>{let o=!1,s=e=>{if(!o){o=!0;try{r.close()}catch{}a(e instanceof Error?e:Error(String(e)))}},c=e=>{if(!o){o=!0;try{r.close()}catch{}i(e)}};r.on(`error`,s),r.on(`end`,()=>{o||s(Error(n?`Zip entry not found: ${n} in ${e}`:`Zip has no file entries: ${e}`))}),r.on(`entry`,e=>{if(o)return;let i=e.fileName.replace(/\\/g,`/`);if(i.endsWith(`/`)){r.readEntry();return}let a=Dc(i);if(!(!n||i===n||a===n)){r.readEntry();return}r.openReadStream(e,(n,r)=>{if(n||!r){s(n??Error(`Failed to read zip entry: ${e.fileName}`));return}(async()=>{try{await be(O(t),{recursive:!0}),await _e(r,se(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function kc(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new je(`--name cannot be empty`,`Use --name all or --name skill-a,skill-b`);let r=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))];if(r.includes(`all`)){if(r.length>1)throw new je(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Ac(){let e=Q();return x(e)?w(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return ue(k(e,t)).isDirectory()}catch{return!1}}):[]}function jc(e,t,n){let r=new Set(n),i=new Set,a=[];for(let[n,o]of Object.entries(e.skills)){i.add(n);let e=t.skills[n];if(e){let t=r.has(n)?e.contentHash===o.contentHash?`installed`:`outdated`:`missing`;a.push({name:n,status:t,publishedAt:o.publishedAt,description:o.description})}else r.has(n)?a.push({name:n,status:`untracked`,publishedAt:o.publishedAt,description:o.description}):a.push({name:n,status:`not-installed`,publishedAt:o.publishedAt,description:o.description})}for(let[e,n]of Object.entries(t.skills))i.has(e)||(i.add(e),a.push({name:e,status:r.has(e)?`installed`:`missing`,publishedAt:n.publishedAt,description:n.description}));for(let e of n)i.has(e)||a.push({name:e,status:`untracked`});return a.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}export{da as ASYNC_FLAG,Re as BAILIAN_HOST,ta as BILLING_METHOD,ac as BINARY_PRODUCT_CLIENT_NAME,M as BailianError,ro as Budgets,bt as CHANNEL,ra as CHARGE_TYPE,_a as COMMAND_PACK_API_VERSION,ua as CONCURRENT_FLAG,ze as CONFIG_FILE_KEYS,pa as CONSOLE_AUTH_FLAGS,Y as Capabilities,Jt as Client,q as Complexities,io as ContextNeeds,na as DEFAULT_BILLING_METHOD,gc as DEFAULT_CLI_CDN_BASE,$i as DEFAULT_DEPLOY_PLAN,yc as DEFAULT_INSTALL_PS1_URL,vc as DEFAULT_INSTALL_SCRIPT_URL,Ti as DEFAULT_TRAINING_TYPE,G as DEPLOY_PLAN,Le as DOCS_HOSTS,j as ExitCode,ao as Features,_c as GITHUB_RELEASES_BASE,la as GLOBAL_FLAGS,ji as INSUFFICIENT_SAMPLES_CODE,xr as MAX_DATASET_BYTES,Sr as MAX_MEDIA_ZIP_BYTES,fa as MODEL_AUTH_FLAGS,ar as MODEL_LIST_API,Ut as McpClient,no as Modalities,X as ModelCategories,ma as OPENAPI_AUTH_FLAGS,or as PREDICT_CONFIG_API,J as QualityPreferences,Ie as REGIONS,oo as SEMANTIC_TOP_K,St as SOURCE_CONFIG,sa as STRATEGIES,xt as TAGS,wi as TRAINING_TYPES_CLI,Ci as TRAINING_TYPE_MAP,je as UsageError,pt as activateConfigProfile,Co as analyzeIntent,cn as appCompletionPath,Ns as atomicSwap,Ht as bailianMcpPath,wc as binaryAssetFileName,Tc as binaryInnerFileName,Dt as buildAcsCanonicalQuery,gs as buildDocLink,gt as buildSettings,qs as buildSkillLockEntry,ht as buildSources,V as callConsoleGateway,vi as cancelFineTune,xc as channelManifestUrl,en as chatPath,Ms as computeDirContentHash,jc as computeSkillStatuses,tr as createBailianControlUser,Ki as createDeployment,hi as createFineTune,Zn as createInstrumentedFetch,ka as createTrackingEvent,ha as credentialFlagDefs,ea as defaultDeployPlan,ga as defineCommand,mt as deleteConfigProfile,br as deleteDataset,Yi as deleteDeployment,yi as deleteFineTune,Ze as describeAuthState,Cc as detectBinaryPlatform,fc as detectInstallMethod,Es as detectInstalledAgents,ii as detectModality,rt as detectOutputFormat,Rs as downloadSkillAsset,Kt as effectiveConsoleGatewayConfig,xs as emptySkillLock,$e as ensureConfigDir,Si as exportCheckpoint,js as extractTarBr,Oc as extractZipEntryToFile,Ai as fetchModelCapability,ur as fetchModelDetail,lr as fetchModelGroups,cr as fetchModelList,pr as fetchPredictConfig,Fs as fetchSkillsIndex,Va as flushTelemetry,nt as formatErrorJson,mi as formatIssue,tt as formatJson,it as formatOutput,et as formatText,Qt as generateCLIAccessToken,ya as generateFilename,Ts as getAgentTargets,bc as getCliCdnBase,N as getConfigDir,P as getConfigPath,Qe as getCredentialsPath,yr as getDataset,Ji as getDeployment,_i as getFineTune,bi as getFineTuneLogs,pc as getInstallMethod,gr as getModelProfilePreset,to as getModels,Wi as getProfile,bs as getSkillLockPath,Ps as getSkillRegistryBaseUrl,Q as getSkillsDir,mc as getUpdateInstallMethod,an as image2ImagePath,It as imageFileToDataUri,tn as imagePath,nn as imageSyncPath,rn as imageText2ImagePath,Gs as installSkill,Ws as installSkillFromBuffer,Js as installSkillWithFanout,lc as isCompiledBinary,Un as isLegacyImage2ImageModel,Hn as isLegacyText2ImageModel,zt as isLocalFile,As as isSafeEntryName,Bs as isSafeSkillName,Xo as isSemanticAvailable,Rn as isSyncMultimodalImageModel,Ei as isTrainingTypeCli,Wn as isWanxFunctionImageEditModel,yn as knowledgeChatEndpoint,_n as knowledgeRetrievePath,vn as knowledgeSearchEndpoint,Os as linkSkillToAgents,nr as listBailianControlWorkspaces,xi as listCheckpoints,vr as listDatasets,Xi as listDeployableModels,qi as listDeployments,gi as listFineTunes,Ac as listSkillDirsOnDisk,pi as listSupportedFormats,ki as listSupportedTrainingTypes,Gi as listTrainingTypes,Ha as localSink,vt as makeAuthStore,mr as makeConfigStore,Ne as mapApiError,yt as maskToken,ic as maybeSyncWikiData,bn as mcpWebSearchPath,ln as memoryAddPath,dn as memoryListPath,fn as memoryNodePath,un as memorySearchPath,Oi as modelSupportsTrainingType,ot as normalizeConfigName,Pe as normalizeModelBaseUrl,Ta as parseBooleanValue,Ue as parseConfigFile,wr as parseDatasetSchemaFlag,Ea as parseOptionalBooleanValue,ir as parseSSE,kc as parseSkillNames,ca as pickPlanStrategy,di as pickValidator,Mi as preflightBatchSizeGate,hn as profileSchemaPath,ys as rankModels,R as readConfigFile,ut as readConfigProfiles,Ss as readSkillLock,Ca as readTextFromPathOrStdin,Fo as recallCandidates,fs as recallSemantic,Lt as redactDataUri,$t as refreshAccessToken,fi as registerValidator,Sc as releaseAssetUrl,Ua as remoteSink,Ks as removeSkillDir,wt as request,Et as requestJson,rr as resetBailianControlPolicies4Agent,Ge as resolveApiKey,Ls as resolveAssetFileName,Da as resolveBooleanFlag,Ke as resolveConsole,Bt as resolveFileUrl,Jn as resolveImageEditApi,qn as resolveImageGenerateApi,Gn as resolveImageSizeProfile,We as resolveModelBaseUrl,qe as resolveOpenApi,xa as resolveOutputDir,Kn as resolvePromptExtendDefault,Oa as resolveWatermark,wa as runWithConcurrency,zs as sanitizeSkillName,Zi as scaleDeployment,Ot as signAcsRequest,mn as speechRecognizePath,pn as speechSynthesizePath,Sa as stripUndefined,sn as taskPath,qa as trackCommandExecution,B as trackingHeaders,Di as trainingTypeMethodVariant,ks as unlinkSkillFromAgents,sr as unwrapResponse,Qi as updateDeployment,_r as uploadDataset,Rt as uploadFile,ws as upsertSkillLockEntry,gn as userProfilePath,ft as validateConfigProfileActivation,W as validateDataset,Hs as validateSkillDir,on as videoGeneratePath,z as writeConfigFile,hc as writeInstallMethodSync,Cs as writeSkillLock};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.13.1",
3
+ "version": "1.14.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": {
@@ -27,11 +27,13 @@
27
27
  "registry": "https://registry.npmjs.org/"
28
28
  },
29
29
  "dependencies": {
30
+ "tar-stream": "^3.2.0",
30
31
  "yaml": "^2.8.3",
31
32
  "yauzl": "^3.4.0"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@types/node": "^24",
36
+ "@types/tar-stream": "^3.1.4",
35
37
  "@types/yauzl": "^3.4.0",
36
38
  "@typescript/native-preview": "7.0.0-dev.20260328.1",
37
39
  "typescript": "^6.0.2",