bailian-cli-core 1.22.0 → 1.24.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
@@ -53,9 +53,10 @@ interface ApiErrorBody {
53
53
  type?: string;
54
54
  code?: number | string;
55
55
  };
56
- code?: string;
56
+ code?: number | string;
57
57
  message?: string;
58
58
  request_id?: string;
59
+ requestID?: string;
59
60
  }
60
61
  declare function mapApiError(status: number, body: ApiErrorBody, _url?: string): BailianError;
61
62
  //#endregion
@@ -618,11 +619,20 @@ interface DashScopeTTSStreamChunk {
618
619
  usage?: Record<string, unknown>;
619
620
  request_id?: string;
620
621
  }
622
+ /** Context-enhancement message for async ASR `input.context` / sync Flash `input.messages`. */
623
+ interface AsrContextMessage {
624
+ role: "user" | "assistant";
625
+ content: Array<{
626
+ type: "input_text" | "text";
627
+ text: string;
628
+ }>;
629
+ }
621
630
  interface DashScopeASRRequest {
622
631
  model: string;
623
632
  input: {
624
633
  file_urls?: string[];
625
- file_url?: string;
634
+ file_url?: string; /** Context enhancement for async filetrans (array of chat-style messages). */
635
+ context?: AsrContextMessage[];
626
636
  };
627
637
  parameters?: {
628
638
  channel_id?: number[]; /** Classic async models (fun-asr / paraformer / qwen-audio filetrans, etc.) */
@@ -630,7 +640,8 @@ interface DashScopeASRRequest {
630
640
  language?: string;
631
641
  diarization_enabled?: boolean;
632
642
  speaker_count?: number;
633
- vocabulary_id?: string;
643
+ vocabulary_id?: string; /** Instant hot words (word → weight); takes effect on Qwen-Audio-3.0-ASR-Flash series. */
644
+ vocabulary?: Record<string, number>;
634
645
  };
635
646
  }
636
647
  interface DashScopeASRTranscriptionItem {
@@ -1060,6 +1071,7 @@ interface ConfigFile {
1060
1071
  output?: "text" | "json";
1061
1072
  output_dir?: string;
1062
1073
  timeout?: number;
1074
+ watermark?: boolean;
1063
1075
  default_text_model?: string;
1064
1076
  default_video_model?: string;
1065
1077
  default_image_to_video_model?: string;
@@ -1076,7 +1088,7 @@ interface ConfigFile {
1076
1088
  console_switch_agent?: number;
1077
1089
  telemetry?: boolean;
1078
1090
  }
1079
- declare const CONFIG_FILE_KEYS: readonly ["language", "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_speech_recognition_model", "default_omni_model", "api_key_capabilities", "workspace_id", "console_site", "console_region", "console_switch_agent", "telemetry"];
1091
+ declare const CONFIG_FILE_KEYS: readonly ["language", "api_key", "access_token", "access_key_id", "access_key_secret", "security_token", "base_url", "output", "output_dir", "timeout", "watermark", "default_text_model", "default_video_model", "default_image_to_video_model", "default_reference_to_video_model", "default_image_model", "default_speech_model", "default_speech_recognition_model", "default_omni_model", "api_key_capabilities", "workspace_id", "console_site", "console_region", "console_switch_agent", "telemetry"];
1080
1092
  declare const API_KEY_CAPABILITY_PATTERN: RegExp;
1081
1093
  declare function isApiKeyCapability(value: string): boolean;
1082
1094
  /**
@@ -1112,6 +1124,7 @@ interface Settings {
1112
1124
  outputExplicit: boolean;
1113
1125
  outputDir?: string;
1114
1126
  timeout: number;
1127
+ watermark: boolean;
1115
1128
  defaultTextModel?: string;
1116
1129
  defaultVideoModel?: string;
1117
1130
  defaultImageToVideoModel?: string;
@@ -1334,6 +1347,8 @@ interface ClientDeps {
1334
1347
  settings: Settings;
1335
1348
  /** Model 域 base URL(凭证无关链解析,resolveModelBaseUrl;有 apiCred 时两者一致)。 */
1336
1349
  baseUrl: string;
1350
+ /** True only when the shared URL chain used its default; explicit origins win over service defaults. */
1351
+ baseUrlIsDefault?: boolean;
1337
1352
  apiCred?: ApiKeyCredential;
1338
1353
  consoleCred?: ConsoleCredential;
1339
1354
  openApiCred?: OpenApiCredential;
@@ -1390,8 +1405,11 @@ declare class Client {
1390
1405
  * resolved (authStage tolerates that only under dry-run).
1391
1406
  */
1392
1407
  exportApiCredential(): ApiKeyCredential | undefined;
1393
- /** Full URL for a model-domain {@link path}; build request/display URLs only through this. */
1394
- url(path: string): string;
1408
+ /**
1409
+ * Full URL for a model-domain path. Services may supply a lazy default origin,
1410
+ * evaluated only when no flag/env/profile base URL was configured.
1411
+ */
1412
+ url(path: string, defaultBaseUrl?: () => string): string;
1395
1413
  private toOpts;
1396
1414
  request(opts: ClientRequestOpts): Promise<Response>;
1397
1415
  requestJson<T>(opts: ClientRequestOpts): Promise<T>;
@@ -1789,6 +1807,11 @@ declare function buildSources(flags: Partial<SourceFlags>): ResolutionSources;
1789
1807
  declare function buildSettings(s: ResolutionSources): Settings;
1790
1808
  //#endregion
1791
1809
  //#region src/auth/resolver.d.ts
1810
+ /** Preserve whether the shared base URL chain selected a configured origin or its default. */
1811
+ declare function resolveModelBaseUrlState(sources: ResolutionSources, fallback?: string): {
1812
+ baseUrl: string;
1813
+ baseUrlIsDefault: boolean;
1814
+ };
1792
1815
  /** Model-domain baseUrl(flag > env > config file > fallback);无需 key 也可解析。 */
1793
1816
  declare function resolveModelBaseUrl(s: ResolutionSources, fallback?: string): string;
1794
1817
  /**
@@ -1846,6 +1869,7 @@ declare function memoryListPath(): string;
1846
1869
  declare function memoryNodePath(nodeId: string): string;
1847
1870
  declare function speechSynthesizePath(): string;
1848
1871
  declare function speechRecognizePath(): string;
1872
+ declare function speechVocabularyPath(): string;
1849
1873
  declare function profileSchemaPath(): string;
1850
1874
  declare function userProfilePath(schemaId: string): string;
1851
1875
  declare function knowledgeRetrievePath(): string;
@@ -1853,6 +1877,25 @@ declare function knowledgeSearchEndpoint(workspaceId: string): string;
1853
1877
  declare function knowledgeChatEndpoint(workspaceId: string): string;
1854
1878
  declare function mcpWebSearchPath(): string;
1855
1879
  declare function ragEndpoint(workspaceId: string, path: string): string;
1880
+ /** AgentStudio workspace files; template uploads send source=sandbox_template. */
1881
+ declare function agentStudioFilesPath(): string;
1882
+ /** Default Sandbox origin when no shared base URL was configured (cn-beijing only). */
1883
+ declare function sandboxBaseUrl(workspaceId: string): string;
1884
+ /** Sandbox service prefix, appended to the selected origin just like AgentStudio SDK paths. */
1885
+ declare function sandboxApiPath(path: string): string;
1886
+ /** Build the default workspace-scoped absolute Sandbox control-plane URL. */
1887
+ declare function sandboxEndpoint(workspaceId: string, path: string): string;
1888
+ declare const SANDBOX_PATHS: {
1889
+ readonly sandboxes: "/sandboxes";
1890
+ readonly sandboxList: "/v2/sandboxes";
1891
+ readonly templates: "/templates";
1892
+ readonly templateCreate: "/v3/templates";
1893
+ readonly templateList: "/v2/templates";
1894
+ };
1895
+ declare function sandboxInstancePath(sandboxId: string): string;
1896
+ declare function sandboxInstanceActionPath(sandboxId: string, action: "connect" | "pause" | "resume"): string;
1897
+ declare function sandboxTemplatePath(templateId: string): string;
1898
+ declare function sandboxTemplateBuildStatusPath(templateId: string, buildId: string): string;
1856
1899
  declare const RAG_PATHS: {
1857
1900
  readonly indexList: "/api/v1/indices/rag/index/list";
1858
1901
  readonly indexCreateV2: "/api/v1/indices/rag/index/create_v2";
@@ -1944,12 +1987,14 @@ declare function resolveImageEditApi(model: string): ImageApiRoute;
1944
1987
  *
1945
1988
  * - async file transcription (`.../audio/asr/transcription`):
1946
1989
  * fun-asr*, paraformer* (non-realtime), *-filetrans, sensevoice*
1947
- * language via `parameters.language_hints`
1990
+ * language via `parameters.language_hints`; optional `input.context` /
1991
+ * `parameters.vocabulary` (model-dependent effective range)
1948
1992
  * - sync multimodal (`.../aigc/multimodal-generation/generation`):
1949
1993
  * - qwen3: `{ content: [{ audio }] }` + optional `asr_options.language`
1950
- * (qwen3-asr-flash*)
1994
+ * (qwen3-asr-flash*) — no vocabulary / context fields in this body shape
1951
1995
  * - input-audio: `{ type: input_audio, input_audio.data }` +
1952
- * `format`/`sample_rate` + optional `language_hints`
1996
+ * `format`/`sample_rate` + optional `language_hints` /
1997
+ * `vocabulary_id` / `vocabulary`; optional leading `input_text` for context
1953
1998
  * (fun-asr-flash*, qwen-audio-*-asr-flash*)
1954
1999
  * - realtime / streaming: WebSocket — not supported by `speech recognize`
1955
2000
  */
@@ -1990,8 +2035,14 @@ interface BuildAsrFlashRequestOpts {
1990
2035
  language?: string;
1991
2036
  /** Precompiled hotword vocabulary ID; supported for input-audio Flash (fun-asr-flash* / qwen-audio-*-asr-flash). */
1992
2037
  vocabularyId?: string;
2038
+ /** Instant hot words (word → weight); input-audio Flash only (command layer rejects qwen3). */
2039
+ vocabulary?: Record<string, number>;
2040
+ /** Context enhancement text; prepended as input_text before input_audio. */
2041
+ context?: string;
1993
2042
  flashFamily: AsrFlashFamily;
1994
2043
  }
2044
+ /** Wrap plain text as a single user context message for ASR. */
2045
+ declare function buildAsrContextMessages(text: string): AsrContextMessage[];
1995
2046
  /**
1996
2047
  * Build language fields for async ASR routes.
1997
2048
  * qwen3-asr-flash-filetrans* → `language`; other async models → `language_hints`.
@@ -3461,6 +3512,71 @@ declare function listIndependentDeployedModels(client: Client): Promise<ModelSer
3461
3512
  */
3462
3513
  declare function findDeploymentEntry(entries: ModelServiceEntry[], deployedModel: string): ModelServiceEntry | undefined;
3463
3514
  //#endregion
3515
+ //#region src/speech/vocabulary.d.ts
3516
+ /** Fixed model id for the hot-word customization endpoint. */
3517
+ declare const SPEECH_BIASING_MODEL = "speech-biasing";
3518
+ interface VocabularyEntry {
3519
+ text: string;
3520
+ weight: number;
3521
+ lang?: string;
3522
+ }
3523
+ interface VocabularyListItem {
3524
+ vocabulary_id?: string;
3525
+ gmt_create?: string;
3526
+ gmt_modified?: string;
3527
+ /** OK | UNDEPLOYED — UNDEPLOYED vocabularies are silently ignored by ASR. */
3528
+ status?: string;
3529
+ }
3530
+ interface VocabularyEnvelope<T> {
3531
+ request_id?: string;
3532
+ output?: T;
3533
+ usage?: {
3534
+ count?: number;
3535
+ };
3536
+ }
3537
+ interface VocabularyRequest {
3538
+ model: string;
3539
+ input: Record<string, unknown>;
3540
+ }
3541
+ /** Shared request body builder for dry-run and live calls. */
3542
+ declare function buildVocabularyRequest(action: string, input: Record<string, unknown>): VocabularyRequest;
3543
+ declare function createVocabulary(client: Client, params: {
3544
+ targetModel: string;
3545
+ prefix: string;
3546
+ vocabulary: VocabularyEntry[];
3547
+ }, signal?: AbortSignal): Promise<VocabularyEnvelope<{
3548
+ vocabulary_id?: string;
3549
+ }>>;
3550
+ declare function listVocabularies(client: Client, params?: {
3551
+ prefix?: string;
3552
+ pageIndex?: number;
3553
+ pageSize?: number;
3554
+ }, signal?: AbortSignal): Promise<VocabularyEnvelope<{
3555
+ vocabulary_list?: VocabularyListItem[];
3556
+ }>>;
3557
+ declare function queryVocabulary(client: Client, vocabularyId: string, signal?: AbortSignal): Promise<VocabularyEnvelope<{
3558
+ gmt_create?: string;
3559
+ gmt_modified?: string;
3560
+ status?: string;
3561
+ target_model?: string;
3562
+ vocabulary?: VocabularyEntry[];
3563
+ }>>;
3564
+ declare function updateVocabulary(client: Client, vocabularyId: string, vocabulary: VocabularyEntry[], signal?: AbortSignal): Promise<VocabularyEnvelope<Record<string, never>>>;
3565
+ declare function deleteVocabulary(client: Client, vocabularyId: string, signal?: AbortSignal): Promise<VocabularyEnvelope<Record<string, never>>>;
3566
+ //#endregion
3567
+ //#region src/speech/vocabulary-input.d.ts
3568
+ /**
3569
+ * Instant hot words for `recognize --vocabulary`.
3570
+ * The API field is a flat word→weight object, so an array is a usage error here.
3571
+ */
3572
+ declare function parseInstantVocabulary(raw: string): Record<string, number>;
3573
+ /**
3574
+ * Vocabulary create/update --words.
3575
+ * Accepts the same word→weight object as recognize, or the API entry array
3576
+ * when per-entry lang is needed. Array form ignores the optional lang param.
3577
+ */
3578
+ declare function parseVocabularyEntries(raw: string, lang?: string): VocabularyEntry[];
3579
+ //#endregion
3464
3580
  //#region src/types/command-pack.d.ts
3465
3581
  /** Current Command Pack protocol version understood by this release. */
3466
3582
  declare const COMMAND_PACK_API_VERSION: 1;
@@ -3574,8 +3690,8 @@ declare function parseOptionalBooleanValue(value: unknown, label?: string): bool
3574
3690
  * Returns `defaultWhenUnset` when the flag is omitted.
3575
3691
  */
3576
3692
  declare function resolveBooleanFlag(flagValue: unknown, defaultWhenUnset: boolean | undefined, label?: string): boolean | undefined;
3577
- /** Resolve `--watermark` flag; default true when unset. */
3578
- declare function resolveWatermark(flagValue: unknown): boolean;
3693
+ /** Resolve `--watermark`; command flag overrides config, then defaults to true. */
3694
+ declare function resolveWatermark(flagValue: unknown, configuredValue?: boolean): boolean;
3579
3695
  //#endregion
3580
3696
  //#region src/telemetry/event.d.ts
3581
3697
  interface TrackingEvent {
@@ -4226,4 +4342,4 @@ declare function installSkillWithFanout(name: string, entry: SkillIndexEntry, ag
4226
4342
  declare function listSkillDirsOnDisk(): string[];
4227
4343
  declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[];
4228
4344
  //#endregion
4229
- export { API_KEY_CAPABILITY_PATTERN, ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AgentTarget, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, ApiKeyResolutionSourceSelection, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AsrApiKind, AsrApiRoute, AsrFlashFamily, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BAILIAN_HOST, BILLING_METHOD, BINARY_PRODUCT_CLIENT_NAME, BailianControlAuth, BailianError, BatchSizeGateInput, BatchSizeGateResult, BillingMethod, Budget, Budgets, BuildAsrFlashRequestOpts, CALC_DATASETS_TOKENS_API, 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, CommandRisk, CommandRiskLevel, Complexities, Complexity, ConfigFile, ConfigProfiles, ConfigStore, ConnectBailianMcpOptions, ConsoleCall, 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_LANGUAGE, DEFAULT_TRAINING_TYPE, DEPLOY_LIST_INDEPENDENT_API, DEPLOY_PLAN, DEPLOY_START_API, DEPLOY_STOP_API, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeASRTranscriptionItem, 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, ESTIMATE_FINETUNE_TOKENS_API, ExitCode, ExportCheckpointResponse, FanoutOutcome, 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, Language, LinkResult, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, LocalizedText, MAX_CPT_BYTES, MAX_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, MODEL_AUTH_FLAGS, MODEL_LIST_API, McpClient, McpConnectedClient, 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, ModelServiceEntry, ModelSource, OPENAPI_AUTH_FLAGS, OPEN_API_SOURCE, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, RAG_PATHS, REGIONS, RagAddCategoryData, RagAddCategoryResponse, RagAddConnectorResponse, RagAddFileData, RagAddFileResponse, RagAgentConfig, RagAgentDetail, RagAgentGetData, RagAgentGetResponse, RagAgentListData, RagAgentListResponse, RagAgentMutationData, RagAgentMutationResponse, RagAgentRow, RagBatchUpdateTagResponse, RagCategory, RagChunkListData, RagChunkListResponse, RagChunkNode, RagChunkNodeMetadata, RagConnectorInfo, RagConnectorResponse, RagCreateIndexV2Data, RagCreateIndexV2Response, RagDataCenterFile, RagDeleteFileData, RagDeleteFileResponse, RagDescribeFileResponse, RagGetConnectorResponse, RagIndexFileRow, RagIndexFilesData, RagIndexFilesResponse, RagIndexJobDoc, RagIndexJobStatusData, RagIndexJobStatusResponse, RagIndexListData, RagIndexListResponse, RagIndexRow, RagJobCreateData, RagJobCreateResponse, RagListCategoryData, RagListCategoryResponse, RagListFileData, RagListFileResponse, RagMonitorData, RagMonitorResponse, RagMutationResponse, RagOssImportData, RagOssImportFileResult, RagOssImportResponse, RagQpsMonitorData, RagResponse, RagStorageMonitorData, RagUploadLeaseData, RagUploadLeaseParam, RagUploadLeaseResponse, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, ResponsesOutputContent, ResponsesOutputItem, ResponsesRequest, ResponsesResponse, ResponsesStreamEvent, SEMANTIC_TOP_K, STRATEGIES, SUPPORTED_LANGUAGES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, SourceFlags, StreamChoice, StreamChunk, TRAINING_MODEL_PRICE_API, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TokenEstimate, TrackingEvent, TrackingIdentity, TrainingModelPrice, type TrainingProfile, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UsageError, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, activateConfigProfile, analyzeIntent, anonymousConsoleCall, appCompletionPath, atomicSwap, bailianMcpPath, bailianMcpSsePath, binaryAssetFileName, binaryInnerFileName, buildAcsCanonicalQuery, buildAsrFlashRequest, buildAsyncAsrLanguageFields, buildDocLink, buildSettings, buildSkillLockEntry, buildSources, callConsoleGateway, cancelFineTune, channelManifestUrl, chatPath, collectAsrTranscriptionItems, computeDirContentHash, computeSkillStatuses, connectBailianMcpWithFallback, createBailianControlUser, createDeployment, createFineTune, createInstrumentedFetch, createTrackingEvent, credentialFlagDefs, defaultDeployPlan, defineCommand, deleteConfigProfile, deleteDataset, deleteDeployment, deleteFineTune, describeAuthState, detectBinaryPlatform, detectInstallMethod, detectInstalledAgents, detectModality, detectOutputFormat, downloadSkillAsset, effectiveConsoleGatewayConfig, emptySkillLock, ensureConfigDir, estimateCptTokens, estimateSftDpoTokens, exportCheckpoint, extractAsrFlashText, extractTarBr, extractZipEntryToFile, fanOutSkillToAgents, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchModelListAll, fetchPredictConfig, fetchSkillsIndex, fetchTrainingModelPrice, findDeploymentEntry, findModelByName, 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, image2videoPath, imageFileToDataUri, imagePath, imageSyncPath, imageText2ImagePath, inferAudioFormatHint, installSkill, installSkillFromBuffer, installSkillWithFanout, isApiKeyCapability, isCompiledBinary, isLegacyImage2ImageModel, isLegacyText2ImageModel, isLocalFile, isSafeEntryName, isSafeSkillName, isSemanticAvailable, isStreamableHttpUnsupported, isSyncMultimodalImageModel, isTrainingTypeCli, isUrlOverrideSseFallbackCandidate, isWanxFunctionImageEditModel, knowledgeChatEndpoint, knowledgeRetrievePath, knowledgeSearchEndpoint, linkSkillToAgents, listBailianControlWorkspaces, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listIndependentDeployedModels, listSkillDirsOnDisk, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, maybeSyncWikiData, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, modelsLimitsPath, modelsPermissionsPath, normalizeApiKeyCapabilities, normalizeConfigName, normalizeModelBaseUrl, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, parseSkillNames, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, ragEndpoint, rankModels, readConfigFile, readConfigProfiles, readSkillLock, readTextFromPathOrStdin, recallCandidates, recallSemantic, redactDataUri, refreshAccessToken, registerValidator, releaseAssetUrl, remoteSink, removeSkillDir, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveAsrApi, resolveAssetFileName, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveImageEditApi, resolveImageGenerateApi, resolveImageSizeProfile, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolvePromptExtendDefault, resolveWatermark, responsesPath, runWithConcurrency, sanitizeSkillName, scaleDeployment, selectApiKeyResolutionSources, signAcsRequest, sourceConfig, speechRecognizePath, speechSynthesizePath, startModelService, stopModelService, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unlinkSkillFromAgents, unwrapResponse, updateDeployment, uploadDataset, uploadFile, upsertSkillLockEntry, userProfilePath, validateConfigProfileActivation, validateDataset, validateSkillDir, videoGeneratePath, writeConfigFile, writeInstallMethodSync, writeSkillLock };
4345
+ export { API_KEY_CAPABILITY_PATTERN, ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AgentTarget, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, ApiKeyResolutionSourceSelection, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AsrApiKind, AsrApiRoute, AsrContextMessage, AsrFlashFamily, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BAILIAN_HOST, BILLING_METHOD, BINARY_PRODUCT_CLIENT_NAME, BailianControlAuth, BailianError, BatchSizeGateInput, BatchSizeGateResult, BillingMethod, Budget, Budgets, BuildAsrFlashRequestOpts, CALC_DATASETS_TOKENS_API, 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, CommandRisk, CommandRiskLevel, Complexities, Complexity, ConfigFile, ConfigProfiles, ConfigStore, ConnectBailianMcpOptions, ConsoleCall, 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_LANGUAGE, DEFAULT_TRAINING_TYPE, DEPLOY_LIST_INDEPENDENT_API, DEPLOY_PLAN, DEPLOY_START_API, DEPLOY_STOP_API, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeASRTranscriptionItem, 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, ESTIMATE_FINETUNE_TOKENS_API, ExitCode, ExportCheckpointResponse, FanoutOutcome, 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, Language, LinkResult, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, LocalizedText, MAX_CPT_BYTES, MAX_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, MODEL_AUTH_FLAGS, MODEL_LIST_API, McpClient, McpConnectedClient, 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, ModelServiceEntry, ModelSource, OPENAPI_AUTH_FLAGS, OPEN_API_SOURCE, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, RAG_PATHS, REGIONS, RagAddCategoryData, RagAddCategoryResponse, RagAddConnectorResponse, RagAddFileData, RagAddFileResponse, RagAgentConfig, RagAgentDetail, RagAgentGetData, RagAgentGetResponse, RagAgentListData, RagAgentListResponse, RagAgentMutationData, RagAgentMutationResponse, RagAgentRow, RagBatchUpdateTagResponse, RagCategory, RagChunkListData, RagChunkListResponse, RagChunkNode, RagChunkNodeMetadata, RagConnectorInfo, RagConnectorResponse, RagCreateIndexV2Data, RagCreateIndexV2Response, RagDataCenterFile, RagDeleteFileData, RagDeleteFileResponse, RagDescribeFileResponse, RagGetConnectorResponse, RagIndexFileRow, RagIndexFilesData, RagIndexFilesResponse, RagIndexJobDoc, RagIndexJobStatusData, RagIndexJobStatusResponse, RagIndexListData, RagIndexListResponse, RagIndexRow, RagJobCreateData, RagJobCreateResponse, RagListCategoryData, RagListCategoryResponse, RagListFileData, RagListFileResponse, RagMonitorData, RagMonitorResponse, RagMutationResponse, RagOssImportData, RagOssImportFileResult, RagOssImportResponse, RagQpsMonitorData, RagResponse, RagStorageMonitorData, RagUploadLeaseData, RagUploadLeaseParam, RagUploadLeaseResponse, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, ResponsesOutputContent, ResponsesOutputItem, ResponsesRequest, ResponsesResponse, ResponsesStreamEvent, SANDBOX_PATHS, SEMANTIC_TOP_K, SPEECH_BIASING_MODEL, STRATEGIES, SUPPORTED_LANGUAGES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, SourceFlags, StreamChoice, StreamChunk, TRAINING_MODEL_PRICE_API, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TokenEstimate, TrackingEvent, TrackingIdentity, TrainingModelPrice, type TrainingProfile, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UsageError, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, VocabularyEntry, VocabularyEnvelope, VocabularyListItem, VocabularyRequest, activateConfigProfile, agentStudioFilesPath, analyzeIntent, anonymousConsoleCall, appCompletionPath, atomicSwap, bailianMcpPath, bailianMcpSsePath, binaryAssetFileName, binaryInnerFileName, buildAcsCanonicalQuery, buildAsrContextMessages, buildAsrFlashRequest, buildAsyncAsrLanguageFields, buildDocLink, buildSettings, buildSkillLockEntry, buildSources, buildVocabularyRequest, callConsoleGateway, cancelFineTune, channelManifestUrl, chatPath, collectAsrTranscriptionItems, computeDirContentHash, computeSkillStatuses, connectBailianMcpWithFallback, createBailianControlUser, createDeployment, createFineTune, createInstrumentedFetch, createTrackingEvent, createVocabulary, credentialFlagDefs, defaultDeployPlan, defineCommand, deleteConfigProfile, deleteDataset, deleteDeployment, deleteFineTune, deleteVocabulary, describeAuthState, detectBinaryPlatform, detectInstallMethod, detectInstalledAgents, detectModality, detectOutputFormat, downloadSkillAsset, effectiveConsoleGatewayConfig, emptySkillLock, ensureConfigDir, estimateCptTokens, estimateSftDpoTokens, exportCheckpoint, extractAsrFlashText, extractTarBr, extractZipEntryToFile, fanOutSkillToAgents, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchModelListAll, fetchPredictConfig, fetchSkillsIndex, fetchTrainingModelPrice, findDeploymentEntry, findModelByName, 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, image2videoPath, imageFileToDataUri, imagePath, imageSyncPath, imageText2ImagePath, inferAudioFormatHint, installSkill, installSkillFromBuffer, installSkillWithFanout, isApiKeyCapability, isCompiledBinary, isLegacyImage2ImageModel, isLegacyText2ImageModel, isLocalFile, isSafeEntryName, isSafeSkillName, isSemanticAvailable, isStreamableHttpUnsupported, isSyncMultimodalImageModel, isTrainingTypeCli, isUrlOverrideSseFallbackCandidate, isWanxFunctionImageEditModel, knowledgeChatEndpoint, knowledgeRetrievePath, knowledgeSearchEndpoint, linkSkillToAgents, listBailianControlWorkspaces, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listIndependentDeployedModels, listSkillDirsOnDisk, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, listVocabularies, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, maybeSyncWikiData, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, modelsLimitsPath, modelsPermissionsPath, normalizeApiKeyCapabilities, normalizeConfigName, normalizeModelBaseUrl, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseInstantVocabulary, parseOptionalBooleanValue, parseSSE, parseSkillNames, parseVocabularyEntries, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, queryVocabulary, ragEndpoint, rankModels, readConfigFile, readConfigProfiles, readSkillLock, readTextFromPathOrStdin, recallCandidates, recallSemantic, redactDataUri, refreshAccessToken, registerValidator, releaseAssetUrl, remoteSink, removeSkillDir, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveAsrApi, resolveAssetFileName, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveImageEditApi, resolveImageGenerateApi, resolveImageSizeProfile, resolveModelBaseUrl, resolveModelBaseUrlState, resolveOpenApi, resolveOutputDir, resolvePromptExtendDefault, resolveWatermark, responsesPath, runWithConcurrency, sandboxApiPath, sandboxBaseUrl, sandboxEndpoint, sandboxInstanceActionPath, sandboxInstancePath, sandboxTemplateBuildStatusPath, sandboxTemplatePath, sanitizeSkillName, scaleDeployment, selectApiKeyResolutionSources, signAcsRequest, sourceConfig, speechRecognizePath, speechSynthesizePath, speechVocabularyPath, startModelService, stopModelService, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unlinkSkillFromAgents, unwrapResponse, updateDeployment, updateVocabulary, uploadDataset, uploadFile, upsertSkillLockEntry, userProfilePath, validateConfigProfileActivation, validateDataset, validateSkillDir, videoGeneratePath, writeConfigFile, writeInstallMethodSync, writeSkillLock };
package/dist/index.mjs CHANGED
@@ -1,20 +1,20 @@
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 y,createHmac as b,randomBytes as ee,randomUUID as te}from"crypto";import{Readable as ne}from"stream";import{createInterface as x}from"readline";import{pipeline as re}from"stream/promises";import*as S from"yauzl";import{cpSync as ie,createWriteStream as ae,existsSync as C,lstatSync as w,mkdirSync as T,readFileSync as E,readdirSync as D,readlinkSync as oe,renameSync as O,rmSync as k,statSync as se,symlinkSync as ce,writeFileSync as A}from"node:fs";import{dirname as le,isAbsolute as ue,join as j,resolve as M,sep as de}from"node:path";import{homedir as fe}from"node:os";import{createHash as pe}from"node:crypto";import{Readable as me}from"node:stream";import{pipeline as he}from"node:stream/promises";import{createBrotliDecompress as ge}from"node:zlib";import _e from"tar-stream";import{mkdir as ve}from"node:fs/promises";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e)),Oe=e(import.meta.url);const N={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10};var P=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=N.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=Ae(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}:{}}}}},ke=class extends P{constructor(e,t){super(e,N.USAGE,t),this.name=`UsageError`}};function Ae(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 je(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 P(r,N.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}function Me(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Ne(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Ne(e);return n.origin}function Ne(e){return new P(`Invalid model base URL "${e}".`,N.USAGE,`Use an absolute http(s) URL.`)}const Pe={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},Fe={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Ie=`https://bailian.cn-beijing.aliyuncs.com`,Le=[`en-US`,`zh-CN`],Re=`en-US`,ze=[`language`,`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_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],Be=new Set([`text`,`json`]),Ve=new Set([`domestic`,`international`]),He=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function Ue(e){return He.test(e)}function We(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!Ue(e))return[];t.includes(e)||t.push(e)}return t}function Ge(e){try{return Me(e)}catch{return}}function Ke(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&Le.includes(t.language)&&(n.language=t.language),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=Ge(t.base_url);e&&(n.base_url=e)}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_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=We(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),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 qe(e,t=Pe.cn){return Me(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function Je(e){let t=qe(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 P(`No API key found.`,N.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Ye(e){let t=e.file.access_token?.trim();if(!t)throw new P(`No console access token found.`,N.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 Xe(e){let t=Ze(`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=Ze(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Qe(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Qe(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=Ze(`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 P(`No OpenAPI AK/SK credentials found.`,N.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 Ze(e,t,n,r,i){if(!r)return;let a=Qe(t),o=Qe(n);if(!a||!o)throw new P(`Incomplete OpenAPI AK/SK credentials found.`,N.AUTH,$e(e));return{accessKeyId:a,accessKeySecret:o,securityToken:Qe(i),source:e}}function Qe(e){return e?.trim()||void 0}function $e(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 et(e){let t={};try{t.apiKey=Je(e)}catch{}try{t.console=Ye(e)}catch{}try{t.openapi=Xe(e)}catch{}return t}function F(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function I(){return g(F(),`config.json`)}function tt(){return g(F(),`credentials.json`)}async function nt(){let e=F(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function rt(e){return v(e).replace(/\n$/,``)}function it(e){return JSON.stringify(e,null,2)}function at(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function ot(e){return e===`json`||e===`text`?e:`text`}function st(e,t){switch(t){case`json`:return it(e);case`text`:return rt(e)}}const ct=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,lt=`active_config`;function ut(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function dt(e){if(!(e===void 0||e===``||e===`default`)){if(typeof e!=`string`||!ct.test(e))throw new P(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,N.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(ze.includes(e)||e===lt)throw new P(`Invalid config name "${e}". It conflicts with a config key.`,N.USAGE);return e}}function L(){let e=I();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 ft(e,t){let n=dt(e[lt]);if(n&&t&&!ut(e[n]))throw new P(`Active config "${n}" does not exist.`,N.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function pt(e,t){if(!t)return e;let n=e[t];return ut(n)?n:{}}function R(e){return Ke(pt(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[lt]=t??`default`),await mt(r)}async function mt(e){await nt();let t=I(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),s(n,t)}function ht(){let e=L(),t={};for(let[n,r]of Object.entries(e))ze.includes(n)||n===lt||ut(r)&&(t[n]=Ke(r));return{default:Ke(e),named:t,active:ft(e,!0)??`default`}}function gt(e,t){let n=dt(t);if(n&&!ut(e[n]))throw new P(`Config "${n}" does not exist.`,N.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function _t(e){return gt(L(),e)}async function vt(e){let t=L(),n=gt(t,e);return t[lt]=n,await mt(t),n}async function yt(e){let t=dt(e);if(!t)throw new P(`Cannot delete the default profile.`,N.USAGE);let n=L();return ut(n[t])?(delete n[t],ft(n,!1)===t&&(n[lt]=`default`),await mt(n),!0):!1}function bt(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:R(),configName:void 0},fallbackFrom:e.configName}}function xt(e){let t=L(),n=e.config!==void 0,r=ft(t,!n),i=n?dt(e.config):r;return{flags:e,file:Ke(pt(t,i)),env:process.env,configName:i,configPath:I()}}function St(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 P(`Timeout must be a positive finite number.`,N.USAGE);return{configPath:e.configPath??I(),configName:e.configName,output:ot(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,defaultSpeechRecognitionModel:n.default_speech_recognition_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 Ct={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 wt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>et({...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,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>qe(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`?Me(String(n)):n);await z(r,t,{activate:n})},async logout(e){let n=R(t),r=Ct[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??I()}}}function Tt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const Et=`bailian-cli`,Dt=`BailianCLI`;function Ot(e){return JSON.stringify({channel:Et,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function B(e){return{"x-dashscope-source-config":Ot(e),"x-dashscope-openapisource":Dt}}function kt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function At(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...B(e.identity),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),kt(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=r.Authorization;n&&console.error(`> Auth: ${Tt(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${Ot(e.identity)}`)}let i=jt((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 je(a.status,e,t.url)}return a}function jt(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 Mt(e,t){let n=await At(e,t),r;try{r=await n.json()}catch{throw new P(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,N.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw je(200,{error:{message:r.message,type:r.code}},t.url);return r}function Nt(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])=>`${Ft(e)}=${Ft(String(t))}`).join(`&`)}function Pt(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=te(),i=It(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 y,createHmac as b,randomBytes as ee,randomUUID as te}from"crypto";import{Readable as ne}from"stream";import{createInterface as x}from"readline";import{pipeline as re}from"stream/promises";import*as S from"yauzl";import{cpSync as ie,createWriteStream as ae,existsSync as C,lstatSync as w,mkdirSync as T,readFileSync as E,readdirSync as D,readlinkSync as oe,renameSync as se,rmSync as O,statSync as ce,symlinkSync as le,writeFileSync as k}from"node:fs";import{dirname as A,isAbsolute as ue,join as j,resolve as M,sep as de}from"node:path";import{homedir as fe}from"node:os";import{createHash as pe}from"node:crypto";import{Readable as me}from"node:stream";import{pipeline as he}from"node:stream/promises";import{createBrotliDecompress as ge}from"node:zlib";import _e from"tar-stream";import{mkdir as ve}from"node:fs/promises";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e)),Oe=e(import.meta.url);const N={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10};var P=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=N.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=ke(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}:{}}}}},F=class extends P{constructor(e,t){super(e,N.USAGE,t),this.name=`UsageError`}};function ke(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 Ae(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 P(r,N.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function je(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Me(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Me(e);return n.origin}function Me(e){return new P(`Invalid model base URL "${e}".`,N.USAGE,`Use an absolute http(s) URL.`)}const Ne={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},Pe={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Fe=`https://bailian.cn-beijing.aliyuncs.com`,Ie=[`en-US`,`zh-CN`],Le=`en-US`,Re=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],ze=new Set([`text`,`json`]),Be=new Set([`domestic`,`international`]),Ve=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function He(e){return Ve.test(e)}function Ue(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!He(e))return[];t.includes(e)||t.push(e)}return t}function We(e){try{return je(e)}catch{return}}function Ge(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&Ie.includes(t.language)&&(n.language=t.language),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=We(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&ze.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.watermark==`boolean`&&(n.watermark=t.watermark),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_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=Ue(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&Be.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function Ke(e,t=Ne.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:je(n||t),baseUrlIsDefault:!n}}function qe(e,t=Ne.cn){return Ke(e,t).baseUrl}function Je(e){let t=qe(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 P(`No API key found.`,N.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Ye(e){let t=e.file.access_token?.trim();if(!t)throw new P(`No console access token found.`,N.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 Xe(e){let t=Ze(`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=Ze(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Qe(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Qe(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=Ze(`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 P(`No OpenAPI AK/SK credentials found.`,N.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 Ze(e,t,n,r,i){if(!r)return;let a=Qe(t),o=Qe(n);if(!a||!o)throw new P(`Incomplete OpenAPI AK/SK credentials found.`,N.AUTH,$e(e));return{accessKeyId:a,accessKeySecret:o,securityToken:Qe(i),source:e}}function Qe(e){return e?.trim()||void 0}function $e(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 et(e){let t={};try{t.apiKey=Je(e)}catch{}try{t.console=Ye(e)}catch{}try{t.openapi=Xe(e)}catch{}return t}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function L(){return g(I(),`config.json`)}function tt(){return g(I(),`credentials.json`)}async function nt(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function rt(e){return v(e).replace(/\n$/,``)}function it(e){return JSON.stringify(e,null,2)}function at(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function ot(e){return e===`json`||e===`text`?e:`text`}function st(e,t){switch(t){case`json`:return it(e);case`text`:return rt(e)}}const ct=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,R=`active_config`;function lt(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function ut(e){if(!(e===void 0||e===``||e===`default`)){if(typeof e!=`string`||!ct.test(e))throw new P(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,N.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(Re.includes(e)||e===R)throw new P(`Invalid config name "${e}". It conflicts with a config key.`,N.USAGE);return e}}function z(){let e=L();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 dt(e,t){let n=ut(e[R]);if(n&&t&&!lt(e[n]))throw new P(`Active config "${n}" does not exist.`,N.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function ft(e,t){if(!t)return e;let n=e[t];return lt(n)?n:{}}function B(e){return Ge(ft(z(),e))}async function V(e,t,n={}){let r=z();if(t)r[t]=e;else{for(let e of Object.keys(r))Re.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[R]=t??`default`),await pt(r)}async function pt(e){await nt();let t=L(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),s(n,t)}function mt(){let e=z(),t={};for(let[n,r]of Object.entries(e))Re.includes(n)||n===R||lt(r)&&(t[n]=Ge(r));return{default:Ge(e),named:t,active:dt(e,!0)??`default`}}function ht(e,t){let n=ut(t);if(n&&!lt(e[n]))throw new P(`Config "${n}" does not exist.`,N.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function gt(e){return ht(z(),e)}async function _t(e){let t=z(),n=ht(t,e);return t[R]=n,await pt(t),n}async function vt(e){let t=ut(e);if(!t)throw new P(`Cannot delete the default profile.`,N.USAGE);let n=z();return lt(n[t])?(delete n[t],dt(n,!1)===t&&(n[R]=`default`),await pt(n),!0):!1}function yt(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:B(),configName:void 0},fallbackFrom:e.configName}}function bt(e){let t=z(),n=e.config!==void 0,r=dt(t,!n),i=n?ut(e.config):r;return{flags:e,file:Ge(ft(t,i)),env:process.env,configName:i,configPath:L()}}function xt(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 P(`Timeout must be a positive finite number.`,N.USAGE);return{configPath:e.configPath??L(),configName:e.configName,output:ot(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,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,defaultSpeechRecognitionModel:n.default_speech_recognition_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 St={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 Ct(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>et({...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,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>qe(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`?je(String(n)):n);await V(r,t,{activate:n})},async logout(e){let n=B(t),r=St[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??L()}}}function wt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const Tt=`bailian-cli`,Et=`BailianCLI`;function Dt(e){return JSON.stringify({channel:Tt,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function H(e){return{"x-dashscope-source-config":Dt(e),"x-dashscope-openapisource":Et}}function Ot(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function kt(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...H(e.identity),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),Ot(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=r.Authorization;n&&console.error(`> Auth: ${wt(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${Dt(e.identity)}`)}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 Ae(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 jt(e,t){let n=await kt(e,t),r;try{r=await n.json()}catch{throw new P(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,N.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw Ae(200,{error:{message:r.message,type:r.code}},t.url);return r}function Mt(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])=>`${Pt(e)}=${Pt(String(t))}`).join(`&`)}function Nt(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=te(),i=Ft(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
3
3
  `)+`
4
4
  `,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
5
- `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${It(u)}`,p=Lt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function Ft(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function It(e){return y(`sha256`).update(e,`utf8`).digest(`hex`)}function Lt(e,t){return b(`sha256`,e).update(t,`utf8`).digest(`hex`)}const Rt=`${Pe.cn}/api/v1/uploads`;async function zt(e,t,n,r){let i=`${Rt}?action=getPolicy&model=${encodeURIComponent(t)}`,a=qt(15e3,r),o=await fetch(i,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...B(n)},signal:a.signal}).finally(a.cleanup);if(!o.ok){let e=await o.text().catch(()=>``);throw new P(`Failed to get upload policy (HTTP ${o.status}): ${e}`,N.GENERAL)}return(await o.json()).data}async function Bt(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=qt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new P(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,N.GENERAL)}return`oss://${i}`}const Vt={".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 Ht(e){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);if(!l(e).isFile())throw new P(`Not a file: ${e}`,N.USAGE);let t=h(e).toLowerCase(),n=Vt[t];if(!n)throw new P(`Unsupported image format "${t||`unknown`}".`,N.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function Ut(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function Wt(e){let{apiKey:t,model:n,filePath:r,identity:a,signal:o}=e;if(!i(r))throw new P(`File not found: ${r}`,N.USAGE);if(!l(r).isFile())throw new P(`Not a file: ${r}`,N.USAGE);return Bt(await zt(t,n,a,o),r,o)}function Gt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Kt(e,t,n,r){return Gt(e)?Wt({apiKey:t,model:n,filePath:e,identity:r.identity,signal:r.signal}):e}function qt(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 Jt(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
5
+ `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Ft(u)}`,p=It(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function Pt(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Ft(e){return y(`sha256`).update(e,`utf8`).digest(`hex`)}function It(e,t){return b(`sha256`,e).update(t,`utf8`).digest(`hex`)}const Lt=`${Ne.cn}/api/v1/uploads`;async function Rt(e,t,n,r){let i=`${Lt}?action=getPolicy&model=${encodeURIComponent(t)}`,a=Kt(15e3,r),o=await fetch(i,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...H(n)},signal:a.signal}).finally(a.cleanup);if(!o.ok){let e=await o.text().catch(()=>``);throw new P(`Failed to get upload policy (HTTP ${o.status}): ${e}`,N.GENERAL)}return(await o.json()).data}async function zt(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=Kt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new P(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,N.GENERAL)}return`oss://${i}`}const Bt={".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 Vt(e){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);if(!l(e).isFile())throw new P(`Not a file: ${e}`,N.USAGE);let t=h(e).toLowerCase(),n=Bt[t];if(!n)throw new P(`Unsupported image format "${t||`unknown`}".`,N.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function Ht(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function Ut(e){let{apiKey:t,model:n,filePath:r,identity:a,signal:o}=e;if(!i(r))throw new P(`File not found: ${r}`,N.USAGE);if(!l(r).isFile())throw new P(`Not a file: ${r}`,N.USAGE);return zt(await Rt(t,n,a,o),r,o)}function Wt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Gt(e,t,n,r){return Wt(e)?Ut({apiKey:t,model:n,filePath:e,identity:r.identity,signal:r.signal}):e}function Kt(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 qt(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
6
6
  `).replace(/\r/g,`
7
7
  `);let r=t.split(`
8
- `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Yt(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new P(`SSE event exceeded the maximum buffer size.`,N.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a;break}return{event:o}}async function*Xt(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
8
+ `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Jt(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new P(`SSE event exceeded the maximum buffer size.`,N.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a;break}return{event:o}}async function*Yt(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
9
9
  `).replace(/\r/g,`
10
10
  `).split(`
11
- `);r=t.pop()??``;for(let n of t){let t=Yt(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new P(`SSE stream exceeded the maximum buffer size.`,N.GENERAL);let{lines:s,rest:c}=Jt(r);r=c;for(let t of s){let n=Yt(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Yt(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{t.releaseLock()}}function Zt(e){return String(e)}var Qt=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);await this.openSse();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 SSE] Session initialized`),console.error(`[MCP SSE] 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})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new P(`MCP SSE session closed.`,N.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out waiting for response headers.`,N.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new P(e,N.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof P?e:new P(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,N.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=en(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of Xt(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=$t(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Zt(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new P(`MCP SSE stream ended before endpoint event.`,N.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let n=this.nextId++,r=Zt(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=en(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new P(`MCP error (${e.error.code}): ${e.error.message}`,N.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);if(!this.messageUrl)throw new P(`MCP SSE message endpoint is not ready.`,N.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=tn(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):n.timedOut?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:t})}throw new P(e,N.GENERAL)}}finally{n.cleanup()}}};function $t(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new P(`MCP SSE endpoint is not a valid URL: ${t}`,N.GENERAL)}if(n.origin!==r.origin)throw new P(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,N.GENERAL);return n.toString()}function en(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new P(t,N.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function tn(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function nn(e){return`/api/v1/mcps/${e}/mcp`}function rn(e){return`/api/v1/mcps/${e}/sse`}function an(e){return e instanceof P?/^MCP request failed:\s*405\b/i.test(e.message):!1}function on(e){return e instanceof P?/^MCP request failed:\s*(405|404)\b/i.test(e.message):!1}async function sn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new cn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!on(e))throw e}let r=new Qt(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new cn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!an(e)||a===`WebSearch`)throw e}let c=new Qt(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var cn=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 P(`This command needs a model-domain API key.`,N.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=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new P(`MCP error (${a.error.code}): ${a.error.message}`,N.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of Xt(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new P(`MCP SSE response stream ended without a matching JSON-RPC response.`,N.GENERAL)}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.deps.identity)};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 P(e,N.GENERAL)}return r}};const ln={"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 un(e,t){return ln[e]?.[t]??ln[`cn-beijing`][t]}function dn(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 fn(e){let t=dn(e);return(n,r)=>mn({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function pn(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 mn(e,t,{api:n,data:r},i){let a=un(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=pn(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 P(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,N.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 P(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?N.AUTH:N.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var hn=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new P(`This command needs a model-domain API key.`,N.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new P(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,N.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 At(this.http,this.toOpts(e))}requestJson(e){return Mt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Gt(e)?Kt(e,this.requireApi().token,t,{...n,identity:this.deps.identity}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Gt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Ht(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){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 cn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),sn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(nn(e)),sseUrl:this.url(rn(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new P(`This command needs a console access token.`,N.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await mn(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof P)||e.exitCode!==N.AUTH||!e.message.includes(`not logged in`))throw e;let t=await bn({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await mn({...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?Nt(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Pt({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${Tt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${Tt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...B(this.deps.identity)},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 P(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,N.GENERAL)}if(!s.ok||l.Success===!1)throw new P(`${l.Code||s.status} - ${l.Message||s.statusText}`,N.GENERAL);return l}};const gn={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function _n(e){for(let[t,n]of Object.entries(Pe))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function vn(e){return gn[_n(e)]??gn.cn}async function yn(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new hn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=vn(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function bn(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...
12
- `);let a=(await yn({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 xn(){return`/compatible-mode/v1/chat/completions`}function Sn(){return`/compatible-mode/v1/responses`}function Cn(){return`/api/v1/services/aigc/image-generation/generation`}function wn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Tn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function En(){return`/api/v1/services/aigc/image2image/image-synthesis`}function Dn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function On(){return`/api/v1/services/aigc/image2video/video-synthesis`}function kn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function An(){return`/api/v1/models/limits`}function jn(){return`/api/v1/models/permissions`}function Mn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Nn(){return`/api/v2/apps/memory/add`}function Pn(){return`/api/v2/apps/memory/memory_nodes/search`}function Fn(){return`/api/v2/apps/memory/memory_nodes`}function In(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Ln(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Rn(){return`/api/v1/services/audio/asr/transcription`}function zn(){return`/api/v2/apps/memory/profile_schemas`}function Bn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Vn(){return`/api/v1/indices/rag/index/retrieve`}function Hn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Un(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Wn(){return`/api/v1/mcps/WebSearch/mcp`}function Gn(){return`/compatible-mode/v1/files`}function Kn(){return`/api/v1/files`}function qn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Jn(){return`/api/v1/fine-tunes`}function Yn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Xn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Zn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Qn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function $n(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function er(){return`/api/v1/deployments`}function tr(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function nr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function rr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function ir(){return`/api/v1/deployments/models`}function ar(e,t){return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}const or={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},sr=[`qwen-image`,`wan2.7-image`,`z-image`],cr=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function lr(e,t){return t.some(t=>e.startsWith(t))}function ur(e){return lr(e,sr)||e.startsWith(`wan2.6-image`)}function dr(e){return lr(e,sr)}function fr(e){return lr(e,cr)}function pr(e){return/^wanx-v1(?:-|$)/i.test(e)}function mr(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||dr(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||pr(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function hr(e){return/wan2\.5-i2i/i.test(e)}function gr(e){return/imageedit/i.test(e)}function _r(e){return e.startsWith(`qwen-image-3.0`)||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`:pr(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:mr(e)?`wan-legacy`:`wan26`}function vr(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function V(e,t){return{...e,sizeProfile:_r(t),promptExtendDefault:vr(t)}}function yr(e){return dr(e)?V({kind:`sync-multimodal`,path:wn(),useSync:!0,inputStyle:`messages`},e):mr(e)?V({kind:`async-text2image`,path:Tn(),useSync:!1,inputStyle:`prompt`},e):V({kind:`async-image-generation`,path:Cn(),useSync:!1,inputStyle:`messages`},e)}function br(e){return fr(e)?V({kind:`sync-multimodal`,path:wn(),useSync:!0,inputStyle:`messages`},e):gr(e)?V({kind:`async-image2image`,path:En(),useSync:!1,inputStyle:`function-base-image`},e):hr(e)?V({kind:`async-image2image`,path:En(),useSync:!1,inputStyle:`prompt-images`},e):V({kind:`async-image-generation`,path:Cn(),useSync:!1,inputStyle:`messages`},e)}function xr(e){return/realtime|streaming/i.test(e)}function Sr(e){return/filetrans/i.test(e)}function Cr(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const wr=[`fun-asr-flash`,`qwen-audio`];function Tr(e){return xr(e)||Sr(e)?!1:!!(e.startsWith(wr[0])||e.startsWith(wr[1])&&/asr-flash/i.test(e))}function Er(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||Sr(e)||xr(e)||Tr(e))}function Dr(e){if(xr(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(Sr(e)){let t=Cr(e);return{kind:`async-filetrans`,path:Rn(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return Tr(e)?{kind:`sync-flash`,path:wn(),useSync:!0,flashFamily:`input-audio`}:Er(e)?{kind:`sync-flash`,path:wn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Rn(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Or(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function kr(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Ar(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,flashFamily:a}=e;if(a===`input-audio`){let e={format:Or(n),sample_rate:`16000`};return r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),{model:t,input:{messages:[{role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}]},parameters:e}}let o={};r&&(o.language=r);let s={};Object.keys(o).length>0&&(s.asr_options=o);let c={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(s).length>0&&(c.parameters=s),c}function jr(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function Mr(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}function Nr(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function Pr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Fr(e){return async(t,n={})=>{let r=Pr(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}`),Nr(r))for(let[t,n]of Object.entries(B(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${Tt(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 Ir=`2024-08-16`;function Lr(e){return`bailiancontrol.${e}.aliyuncs.com`}function Rr(e){return new hn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function zr(e){return Rr(e).openApiJson({host:Lr(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Ir,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Br(e){return Rr(e).openApiJson({host:Lr(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Ir,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Vr(e){return Rr(e).openApiJson({host:Lr(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Ir,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const Hr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ur=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function H(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 Wr(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=H(await e(Hr,{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 Gr(e,t={}){let n=t.pageSize??50,r=await Wr(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await Wr(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Kr(e,t){return(await Wr(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function qr(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=H(await e(Hr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Jr(e,t){return(H(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 Yr=[`name`,`key`,`default`,`tip`,`range`];function Xr(e){return e.map(e=>{let t={};for(let n of Yr)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Zr(e,t){let n=H(await e(Ur,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Xr(e):null}catch{return null}return Array.isArray(n)?Xr(n):null}function Qr(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`?Me(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:()=>ht(),activate:e=>vt(e),validateActivation:e=>_t(e),get path(){return I()}}}const $r={"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`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function ei(e){return e?$r[e]:void 0}async function ti(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ne.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:Gn(),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 P(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,N.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new P(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,N.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 ni(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=Kn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ri(e,t,n){return e.requestJson({path:qn(t),method:`GET`,signal:n})}async function ii(e,t,n){let r=await e.request({path:qn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ai=200*1024*1024,oi=300*1024*1024,si=2*1024*1024*1024;function ci(e,t=ai){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);let n=l(e);if(!n.isFile())throw new P(`Not a regular file: ${e}`,N.USAGE);if(n.size===0)throw new P(`File is empty: ${e}`,N.USAGE);if(n.size>t)throw new P(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,N.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function U(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function li(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 P(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,N.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function ui(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 di=new Set([`system`,`user`,`assistant`,`tool`]),fi=.1;function pi(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<fi||a>10)&&i.push(U(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${fi} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(U(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(U(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function mi(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(U(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(U(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(U(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(U(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(U(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(U(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(U(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(U(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...pi(s,Array.isArray(e),t,o))}}}return r}function hi(e,t,n){let r=[];if(!Array.isArray(e))return r.push(U(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(U(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(U(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(U(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(U(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(U(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(U(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function gi(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;return(typeof a!=`string`||!di.has(a))&&r.push(U(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(U(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...mi(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(U(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...hi(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(U(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(U(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function _i(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,o=-1,s=new Set,c=new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...gi(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(U(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(U(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}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`}));for(let e of c)s.has(e)||n.push(U(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(U(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;vi(a)&&n.push(U(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(U(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];!i||!(`loss_weight`in i)||(l(i.loss_weight,`messages[${e}].loss_weight`),i.role===`assistant`&&e===o||n.push(U(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(U(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function vi(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const yi={name:`chatml`,detect:()=>!0,inspect:_i};function bi(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 xi={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:bi};function Si(e,t){let n=_i(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!(!a||typeof a!=`object`))for(let e of[`image`,`video`])e in a&&r.push(U(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(U(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(U(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(U(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(U(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(U(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...gi(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`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(s){n.push(...gi(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`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 Ci={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Si};function wi(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 Ti={name:`tts`,detect:e=>`wav_fn`in e,inspect:wi},Ei=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Di(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Oi(e){return/^[\x20-\x7E]+$/.test(e)}function ki(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=Di(r);Ei.has(e)||n.push(U(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ei].join(`, `)}.`,{line:t,path:`img_path`})),Oi(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=Di(r);Ei.has(e)||n.push(U(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ei].join(`, `)}.`,{line:t,path:`input_img`})),Oi(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 Ai={name:`image`,detect:e=>`img_path`in e,inspect:ki},ji=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Mi=new Set([`.mp4`,`.mov`]);function Ni(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Pi(e){return/^[\x20-\x7E]+$/.test(e)}function Fi(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=Ni(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})),Pi(o)||e.push(U(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Ii(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 Fi(n,e,`first_frame_path`,!0,ji,t),Fi(n,e,`last_frame_path`,!1,ji,t),Fi(n,e,`video_path`,!1,Mi,t),n}const Li=[Ti,Ai,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Ii},Ci,xi,yi];function Ri(e,t){return t===void 0?Li.find(t=>t.detect(e))??yi:Li.find(e=>e.name===t)||yi}async function zi(e,t){let r=x({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 Bi(e,t,r,i,a){let o=r?null:new Set(ui(t)),s=[],c=0,l=x({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(...Vi(n,u,i))}return{sampled:c,issues:s}}function Vi(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 Ri(r,n).inspect(r,t)}const Hi={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await zi(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 Bi(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 Ui(e,t){return new Promise((n,r)=>{S.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 Wi(e){return new Promise((t,n)=>{S.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)})})}const Gi=/^[a-zA-Z0-9_-]+$/;function Ki(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function qi(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function Ji(e){let t=[],n=new Map;for(let r of e){if(r.endsWith(`/`)||qi(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Ki(n),i=n.slice(e.length);e.length>0&&!Gi.test(e)&&t.length<10&&t.push(U(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(U(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Ki(i);if(a.length>120&&t.length<10&&t.push(U(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(U(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(U(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Yi(e,t,n){let{entry:i,zipfile:a}=await Ui(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}re(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Xi(e,t=100){let r=x({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 Zi={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Wi(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`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(U(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(U(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=Ji(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&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.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||qi(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Ei.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&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ee(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Yi(e,_,y)}catch(t){return r.push(U(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await Hi.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Xi(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.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(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Qi(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return $i(e);if(t===`.zip`)return ea(e);throw new P(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,N.USAGE)}async function $i(e){let t=await na(e);if(!t)throw new P(`JSONL file is empty or contains only blank lines: ${e}`,N.USAGE);let n=ta(t);return n===`unknown`?`text`:n}async function ea(e){let t=await ra(e,`data.jsonl`);if(!t)throw new P(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,N.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ta(t);if(n===`unknown`)throw new P(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,N.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ta(e){let t;try{t=JSON.parse(e)}catch{throw new P(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,N.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,N.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 na(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({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 ra(e,t){return Ui(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new P(`Failed to read "${t}" from ZIP: ${e?.message}`,N.USAGE));return}let o=x({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 ia=[Hi,Zi];function aa(e){let t=h(e).toLowerCase(),n=ia.find(e=>e.extensions.includes(t));if(!n){let e=ia.flatMap(e=>e.extensions).join(`, `);throw new P(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,N.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function oa(e){ia.some(t=>t.format===e.format)||ia.push(e)}async function W(e,t={}){let{bytes:n}=ci(e,t.maxBytes??209715200),r=await aa(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function sa(){return ia.map(e=>({format:e.format,extensions:[...e.extensions]}))}function ca(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 la(e,t,n){return e.requestJson({path:Jn(),method:`POST`,body:t,signal:n})}async function ua(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),t.model&&n.set(`model`,t.model);let r=Jn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function da(e,t,n){return e.requestJson({path:Yn(t),method:`GET`,signal:n})}async function fa(e,t,n){return e.requestJson({path:Xn(t),method:`POST`,signal:n})}async function pa(e,t,n){return e.requestJson({path:Yn(t),method:`DELETE`,signal:n})}async function ma(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=Zn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ha(e,t,n){return e.requestJson({path:Qn(t),method:`GET`,signal:n})}async function ga(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${$n(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const _a={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`}},va=Object.keys(_a),ya=`sft-lora`;function ba(e){return e in _a}function xa(e){let{method:t,variant:n}=_a[e];return{method:t,variant:n}}function Sa(e,t){if(!e)return!1;let{method:n,variant:r}=_a[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Ca(e){return e?va.filter(t=>Sa(e,t)):[]}async function wa(e,t){return await Kr(fn(e),t)}const Ta=`INSUFFICIENT_SAMPLES`;function Ea(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Ta,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(`
13
- `)}}function Da(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 Oa(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 Da(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const ka=Oa(`sft`,`sft`,`chatml`),Aa={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},ja={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},Ma={...ja,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Na={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Pa(e){return e===`image`||e===`image-i2i`}function Fa(e){return e===`video`||e===`video-kf2v`}function Ia(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function La(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Ra=[ka,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return W(e,{...n,schema:`tts`});if(Pa(t))return W(e,{...n,schema:`image`,maxBytes:si});if(Fa(t)){let r=await W(e,{...n,schema:`video`,maxBytes:si});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{...Aa};if(Pa(e)){let n={...e===`image-i2i`?Ma:ja};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Fa(e)){let e=t.model??t.baseModel,n={...Na,batch_size:La(e)?1:4,max_pixels:La(e)?102400:Ia(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return Da(t)},shouldSkipGate(e,t){return!!((t===`audio`||Pa(t)||Fa(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Pa(e)||Fa(e)}},Oa(`dpo`,`dpo_full`,`dpo`),Oa(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return W(e,{...n,schema:`cpt`,maxBytes:oi})},resolveHyperParameters(e,t){return Da(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function za(e){let t=Ra.find(t=>t.clientTrainingType===e);if(!t){let t=Ra.map(e=>e.clientTrainingType).join(`, `);throw new P(`Unknown training type "${e}".`,N.USAGE,`Supported training types: ${t}.`)}return t}function Ba(){return Ra.map(e=>e.clientTrainingType)}const Va=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,Ha=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,Ua=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Wa(e,t){return H(await e.console(Va,{query:{type:0,modelId:t}}))}async function Ga(e,t,n){return H(await e.console(Ha,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Ka(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return H(await e.console(Ua,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}async function qa(e,t,n){return e.requestJson({path:er(),method:`POST`,body:t,signal:n})}async function Ja(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=er(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ya(e,t,n){return e.requestJson({path:tr(t),method:`GET`,signal:n})}async function Xa(e,t,n){return e.requestJson({path:tr(t),method:`DELETE`,signal:n})}async function Za(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=ir(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Qa(e,t,n,r){return e.requestJson({path:nr(t),method:`PUT`,body:n,signal:r})}async function $a(e,t,n,r){return e.requestJson({path:rr(t),method:`PUT`,body:n,signal:r})}const G={LORA:`lora`,PTU:`ptu`,MU:`mu`},eo=G.LORA;function to(e){return e===`audio`?G.MU:eo}const no={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},ro=no.POST_PAY,io={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},ao={name:G.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},oo={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}}}},so={name:G.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||ro,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new P(`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.`,N.USAGE);try{let a=await Za(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===no.POST_PAY?io.POST_PAID:io.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 P?e:new P(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,N.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},co={[G.LORA]:ao,[G.PTU]:oo,[G.MU]:so};function lo(e){let t=co[e];if(!t)throw new P(`Unsupported plan "${e}". Supported plans: ${Object.keys(co).join(`, `)}.`,N.USAGE);return t}const uo=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,fo=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,po=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function mo(e,t){return H(await e.console(uo,{input:{modelServiceId:t}}))}async function ho(e,t){return H(await e.console(fo,{input:{modelServiceId:t}}))}async function go(e){let t=[],n=1;for(;;){let r=H(await e.console(po,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function _o(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const vo={output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},yo={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},bo={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},xo={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},So={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Co={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function wo(e){return e.auth===`apiKey`?xo:e.auth===`console`?So:e.auth===`openapi`?Co:{}}function To(e){return e}const Eo=1;function Do(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Oo(e,t){return`${Do(e||`image`,`image`)}_${Do((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const ko=()=>g(f(),`bailian-output`);function Ao(e,t){let n=t?.flagDir||e.outputDir||ko(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function jo(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Mo(e){return o(e===`-`?0:e,`utf-8`)}async function No(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 Po(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 P(`Invalid ${t} value "${String(e)}". Use true or false.`,N.USAGE)}function Fo(e,t=`boolean`){if(e!=null)return Po(e,t)}function Io(e,t,n=`boolean`){let r=Fo(e,n);return r===void 0?t:r}function Lo(e){return Fo(e,`watermark`)??!0}function Ro(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.exitCode!==void 0&&(t.exitCode=e.error.exitCode),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 zo(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Bo(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=zo(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let K;function Vo(){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 Ho=Te(((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=Oe(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Oe(`dns`)},function(e,t){e.exports=Oe(`util`)},function(e,t){e.exports=Oe(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},re=(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`},ie=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},ae=(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`},w=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},k=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},A=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},le=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},j=new Map,M=new Map;j.set(`Baiduspider-render`,i),j.set(`Baiduspider+`,i),j.set(`Baiduspider-image+`,i),j.set(`360Spider`,a),j.set(`360Spider-Image`,a),j.set(`bingbot`,o),j.set(`Googlebot`,s),j.set(`YandexRenderResourcesBot`,c),j.set(`spider`,l),j.set(`Dataprovider.com`,u),j.set(`AhrefsBot`,d),j.set(`BitSightBot`,f),j.set(`oBot`,p),j.set(`Cincraw`,m),j.set(`DingTalkBot-LinkService`,h),j.set(`YisouSpider`,g),j.set(`Bytespider`,_),j.set(`ev-crawler`,v),j.set(`bitdiscovery`,y),j.set(`Spider`,b),j.set(`Ai2Bot-Dolma`,ee),j.set(`dianjing_ad_spider`,te),M.set(`Baiduspider-render`,ne),M.set(`Baiduspider+`,ne),M.set(`Baiduspider-image+`,ne),M.set(`360Spider`,x),M.set(`360Spider-Image`,x),M.set(`bingbot`,re),M.set(`Googlebot`,S),M.set(`YandexRenderResourcesBot`,ie),M.set(`spider`,ae),M.set(`Dataprovider.com`,C),M.set(`AhrefsBot`,w),M.set(`BitSightBot`,T),M.set(`oBot`,E),M.set(`Cincraw`,D),M.set(`DingTalkBot-LinkService`,oe),M.set(`YisouSpider`,O),M.set(`Bytespider`,k),M.set(`ev-crawler`,se),M.set(`bitdiscovery`,ce),M.set(`Spider`,A),M.set(`Ai2Bot-Dolma`,le),M.set(`dianjing_ad_spider`,ue);let de={productHandlerMap:j,commentHandlerMap:M,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,de),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),x=n(5),re=n.n(x);function S(e){return(S=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 ie(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 ae(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ie(Object(n),!0).forEach(function(t){C(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ie(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(S(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(S(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return S(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function w(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=E(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.
11
+ `);r=t.pop()??``;for(let n of t){let t=Jt(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new P(`SSE stream exceeded the maximum buffer size.`,N.GENERAL);let{lines:s,rest:c}=qt(r);r=c;for(let t of s){let n=Jt(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Jt(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{t.releaseLock()}}function Xt(e){return String(e)}var Zt=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);await this.openSse();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 SSE] Session initialized`),console.error(`[MCP SSE] 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})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new P(`MCP SSE session closed.`,N.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...H(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out waiting for response headers.`,N.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new P(e,N.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof P?e:new P(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,N.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=$t(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of Yt(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Qt(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Xt(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new P(`MCP SSE stream ended before endpoint event.`,N.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let n=this.nextId++,r=Xt(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=$t(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new P(`MCP error (${e.error.code}): ${e.error.message}`,N.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);if(!this.messageUrl)throw new P(`MCP SSE message endpoint is not ready.`,N.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...H(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=en(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):n.timedOut?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:t})}throw new P(e,N.GENERAL)}}finally{n.cleanup()}}};function Qt(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new P(`MCP SSE endpoint is not a valid URL: ${t}`,N.GENERAL)}if(n.origin!==r.origin)throw new P(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,N.GENERAL);return n.toString()}function $t(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new P(t,N.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function en(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function tn(e){return`/api/v1/mcps/${e}/mcp`}function nn(e){return`/api/v1/mcps/${e}/sse`}function rn(e){return e instanceof P?/^MCP request failed:\s*405\b/i.test(e.message):!1}function an(e){return e instanceof P?/^MCP request failed:\s*(405|404)\b/i.test(e.message):!1}async function on(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new sn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!an(e))throw e}let r=new Zt(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new sn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!rn(e)||a===`WebSearch`)throw e}let c=new Zt(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var sn=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 P(`This command needs a model-domain API key.`,N.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=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new P(`MCP error (${a.error.code}): ${a.error.message}`,N.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of Yt(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new P(`MCP SSE response stream ended without a matching JSON-RPC response.`,N.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...H(this.deps.identity)};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 P(e,N.GENERAL)}return r}};const cn={"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 ln(e,t){return cn[e]?.[t]??cn[`cn-beijing`][t]}function un(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 dn(e){let t=un(e);return(n,r)=>pn({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function fn(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 pn(e,t,{api:n,data:r},i){let a=ln(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=fn(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 P(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,N.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 P(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?N.AUTH:N.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var mn=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new P(`This command needs a model-domain API key.`,N.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new P(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,N.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():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 kt(this.http,this.toOpts(e))}requestJson(e){return jt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Wt(e)?Gt(e,this.requireApi().token,t,{...n,identity:this.deps.identity}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Wt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Vt(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){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 sn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),on({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(tn(e)),sseUrl:this.url(nn(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new P(`This command needs a console access token.`,N.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await pn(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof P)||e.exitCode!==N.AUTH||!e.message.includes(`not logged in`))throw e;let t=await yn({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await pn({...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?Mt(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Nt({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: ${wt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${wt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...H(this.deps.identity)},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 P(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,N.GENERAL)}if(!s.ok||l.Success===!1)throw new P(`${l.Code||s.status} - ${l.Message||s.statusText}`,N.GENERAL);return l}};const hn={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function gn(e){for(let[t,n]of Object.entries(Ne))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function _n(e){return hn[gn(e)]??hn.cn}async function vn(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new mn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=_n(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function yn(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...
12
+ `);let a=(await vn({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 bn(){return`/compatible-mode/v1/chat/completions`}function xn(){return`/compatible-mode/v1/responses`}function Sn(){return`/api/v1/services/aigc/image-generation/generation`}function Cn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function wn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Tn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function En(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Dn(){return`/api/v1/services/aigc/image2video/video-synthesis`}function On(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function kn(){return`/api/v1/models/limits`}function An(){return`/api/v1/models/permissions`}function jn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Mn(){return`/api/v2/apps/memory/add`}function Nn(){return`/api/v2/apps/memory/memory_nodes/search`}function Pn(){return`/api/v2/apps/memory/memory_nodes`}function Fn(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function In(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Ln(){return`/api/v1/services/audio/asr/transcription`}function Rn(){return`/api/v1/services/audio/asr/customization`}function zn(){return`/api/v2/apps/memory/profile_schemas`}function Bn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Vn(){return`/api/v1/indices/rag/index/retrieve`}function Hn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Un(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Wn(){return`/api/v1/mcps/WebSearch/mcp`}function Gn(){return`/compatible-mode/v1/files`}function Kn(){return`/api/v1/files`}function qn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Jn(){return`/api/v1/fine-tunes`}function Yn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Xn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Zn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Qn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function $n(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function er(){return`/api/v1/deployments`}function tr(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function nr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function rr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function ir(){return`/api/v1/deployments/models`}function ar(e,t){return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function or(){return`/api/v1/agentstudio/files`}function sr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function cr(e){return`/api/v1/agentstudio/sandbox${e}`}function lr(e,t){return sr(e)+cr(t)}const ur={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function dr(e){return`${ur.sandboxes}/${encodeURIComponent(e)}`}function fr(e,t){return`${dr(e)}/${t}`}function pr(e){return`${ur.templates}/${encodeURIComponent(e)}`}function mr(e,t){return`${pr(e)}/builds/${encodeURIComponent(t)}/status`}const hr={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},gr=[`qwen-image`,`wan2.7-image`,`z-image`],_r=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function vr(e,t){return t.some(t=>e.startsWith(t))}function yr(e){return vr(e,gr)||e.startsWith(`wan2.6-image`)}function br(e){return vr(e,gr)}function xr(e){return vr(e,_r)}function Sr(e){return/^wanx-v1(?:-|$)/i.test(e)}function Cr(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||br(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||Sr(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function wr(e){return/wan2\.5-i2i/i.test(e)}function Tr(e){return/imageedit/i.test(e)}function Er(e){return e.startsWith(`qwen-image-3.0`)||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`:Sr(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Cr(e)?`wan-legacy`:`wan26`}function Dr(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function U(e,t){return{...e,sizeProfile:Er(t),promptExtendDefault:Dr(t)}}function Or(e){return br(e)?U({kind:`sync-multimodal`,path:Cn(),useSync:!0,inputStyle:`messages`},e):Cr(e)?U({kind:`async-text2image`,path:wn(),useSync:!1,inputStyle:`prompt`},e):U({kind:`async-image-generation`,path:Sn(),useSync:!1,inputStyle:`messages`},e)}function kr(e){return xr(e)?U({kind:`sync-multimodal`,path:Cn(),useSync:!0,inputStyle:`messages`},e):Tr(e)?U({kind:`async-image2image`,path:Tn(),useSync:!1,inputStyle:`function-base-image`},e):wr(e)?U({kind:`async-image2image`,path:Tn(),useSync:!1,inputStyle:`prompt-images`},e):U({kind:`async-image-generation`,path:Sn(),useSync:!1,inputStyle:`messages`},e)}function Ar(e){return/realtime|streaming/i.test(e)}function jr(e){return/filetrans/i.test(e)}function Mr(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const Nr=[`fun-asr-flash`,`qwen-audio`];function Pr(e){return Ar(e)||jr(e)?!1:!!(e.startsWith(Nr[0])||e.startsWith(Nr[1])&&/asr-flash/i.test(e))}function Fr(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||jr(e)||Ar(e)||Pr(e))}function Ir(e){if(Ar(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(jr(e)){let t=Mr(e);return{kind:`async-filetrans`,path:Ln(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return Pr(e)?{kind:`sync-flash`,path:Cn(),useSync:!0,flashFamily:`input-audio`}:Fr(e)?{kind:`sync-flash`,path:Cn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Ln(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Lr(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Rr(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function zr(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Br(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:Lr(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Rr(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Vr(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function Hr(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}function Ur(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function Wr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Gr(e){return async(t,n={})=>{let r=Wr(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}`),Ur(r))for(let[t,n]of Object.entries(H(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${wt(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 Kr=`2024-08-16`;function qr(e){return`bailiancontrol.${e}.aliyuncs.com`}function Jr(e){return new mn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Yr(e){return Jr(e).openApiJson({host:qr(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Kr,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Xr(e){return Jr(e).openApiJson({host:qr(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Kr,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Zr(e){return Jr(e).openApiJson({host:qr(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Kr,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const Qr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,$r=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function W(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function ei(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=W(await e(Qr,{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 ti(e,t={}){let n=t.pageSize??50,r=await ei(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await ei(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function ni(e,t){return(await ei(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function ri(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=W(await e(Qr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function ii(e,t){return(W(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const ai=[`name`,`key`,`default`,`tip`,`range`];function oi(e){return e.map(e=>{let t={};for(let n of ai)e[n]!==void 0&&(t[n]=e[n]);return t})}async function si(e,t){let n=W(await e($r,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?oi(e):null}catch{return null}return Array.isArray(n)?oi(n):null}function ci(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`?je(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:()=>mt(),activate:e=>_t(e),validateActivation:e=>gt(e),get path(){return L()}}}const li={"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`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function ui(e){return e?li[e]:void 0}async function di(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ne.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:Gn(),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 P(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,N.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new P(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,N.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 fi(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=Kn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function pi(e,t,n){return e.requestJson({path:qn(t),method:`GET`,signal:n})}async function mi(e,t,n){let r=await e.request({path:qn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const hi=200*1024*1024,gi=300*1024*1024,_i=2*1024*1024*1024;function vi(e,t=hi){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);let n=l(e);if(!n.isFile())throw new P(`Not a regular file: ${e}`,N.USAGE);if(n.size===0)throw new P(`File is empty: ${e}`,N.USAGE);if(n.size>t)throw new P(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,N.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function G(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function yi(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 P(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,N.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function bi(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 xi=new Set([`system`,`user`,`assistant`,`tool`]),Si=.1;function Ci(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<Si||a>10)&&i.push(G(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${Si} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(G(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(G(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function wi(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(G(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(G(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(G(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(G(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(G(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(G(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(G(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(G(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...Ci(s,Array.isArray(e),t,o))}}}return r}function Ti(e,t,n){let r=[];if(!Array.isArray(e))return r.push(G(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(G(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(G(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(G(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(G(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(G(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(G(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Ei(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(G(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!xi.has(a))&&r.push(G(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(G(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...wi(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(G(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...Ti(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(G(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(G(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function Di(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(G(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(G(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=new Set,c=new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Ei(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(G(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(G(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(G(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(G(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(G(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(G(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;Oi(a)&&n.push(G(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(G(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];!i||!(`loss_weight`in i)||(l(i.loss_weight,`messages[${e}].loss_weight`),i.role===`assistant`&&e===o||n.push(G(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(G(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function Oi(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const ki={name:`chatml`,detect:()=>!0,inspect:Di};function Ai(e,t){let n=[];if(!(`text`in e))return n.push(G(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(G(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(G(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const ji={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ai};function Mi(e,t){let n=Di(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!(!a||typeof a!=`object`))for(let e of[`image`,`video`])e in a&&r.push(G(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(G(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(G(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(G(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(G(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(G(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Ei(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(G(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Ei(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(G(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Ni={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Mi};function Pi(e,t){let n=[];if(!(`wav_fn`in e))n.push(G(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(G(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(G(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(G(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(G(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(G(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Fi={name:`tts`,detect:e=>`wav_fn`in e,inspect:Pi},Ii=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Li(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Ri(e){return/^[\x20-\x7E]+$/.test(e)}function zi(e,t){let n=[];if(!(`prompt`in e))n.push(G(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(G(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(G(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(G(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Li(r);Ii.has(e)||n.push(G(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ii].join(`, `)}.`,{line:t,path:`img_path`})),Ri(r)||n.push(G(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(G(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(G(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Li(r);Ii.has(e)||n.push(G(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ii].join(`, `)}.`,{line:t,path:`input_img`})),Ri(r)||n.push(G(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const Bi={name:`image`,detect:e=>`img_path`in e,inspect:zi},Vi=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Hi=new Set([`.mp4`,`.mov`]);function Ui(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Wi(e){return/^[\x20-\x7E]+$/.test(e)}function Gi(e,t,n,r,i,a){if(!(n in t)){r&&e.push(G(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(G(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(G(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Ui(o);i.has(s)||e.push(G(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Wi(o)||e.push(G(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Ki(e,t){let n=[];if(!(`prompt`in e))n.push(G(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(G(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(G(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Gi(n,e,`first_frame_path`,!0,Vi,t),Gi(n,e,`last_frame_path`,!1,Vi,t),Gi(n,e,`video_path`,!1,Hi,t),n}const qi=[Fi,Bi,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Ki},Ni,ji,ki];function Ji(e,t){return t===void 0?qi.find(t=>t.detect(e))??ki:qi.find(e=>e.name===t)||ki}async function Yi(e,t){let r=x({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(G(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function Xi(e,t,r,i,a){let o=r?null:new Set(bi(t)),s=[],c=0,l=x({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(G(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Zi(n,u,i))}return{sampled:c,issues:s}}function Zi(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[G(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Ji(r,n).inspect(r,t)}const Qi={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Yi(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[G(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Xi(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 $i(e,t){return new Promise((n,r)=>{S.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 ea(e){return new Promise((t,n)=>{S.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)})})}const ta=/^[a-zA-Z0-9_-]+$/;function na(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function ra(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function ia(e){let t=[],n=new Map;for(let r of e){if(r.endsWith(`/`)||ra(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=na(n),i=n.slice(e.length);e.length>0&&!ta.test(e)&&t.length<10&&t.push(G(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(G(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=na(i);if(a.length>120&&t.length<10&&t.push(G(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(G(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(G(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function aa(e,t,n){let{entry:i,zipfile:a}=await $i(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}re(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function oa(e,t=100){let r=x({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 sa={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await ea(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[G(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[G(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(G(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(G(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=ia(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(G(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||ra(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Ii.has(n)});e.length<25&&r.push(G(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ee(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await aa(e,_,y)}catch(t){return r.push(G(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await Qi.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await oa(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(G(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function ca(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return la(e);if(t===`.zip`)return ua(e);throw new P(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,N.USAGE)}async function la(e){let t=await fa(e);if(!t)throw new P(`JSONL file is empty or contains only blank lines: ${e}`,N.USAGE);let n=da(t);return n===`unknown`?`text`:n}async function ua(e){let t=await pa(e,`data.jsonl`);if(!t)throw new P(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,N.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=da(t);if(n===`unknown`)throw new P(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,N.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function da(e){let t;try{t=JSON.parse(e)}catch{throw new P(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,N.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,N.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 fa(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({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 pa(e,t){return $i(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new P(`Failed to read "${t}" from ZIP: ${e?.message}`,N.USAGE));return}let o=x({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 ma=[Qi,sa];function ha(e){let t=h(e).toLowerCase(),n=ma.find(e=>e.extensions.includes(t));if(!n){let e=ma.flatMap(e=>e.extensions).join(`, `);throw new P(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,N.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function ga(e){ma.some(t=>t.format===e.format)||ma.push(e)}async function K(e,t={}){let{bytes:n}=vi(e,t.maxBytes??209715200),r=await ha(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function _a(){return ma.map(e=>({format:e.format,extensions:[...e.extensions]}))}function va(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 ya(e,t,n){return e.requestJson({path:Jn(),method:`POST`,body:t,signal:n})}async function ba(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),t.model&&n.set(`model`,t.model);let r=Jn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function xa(e,t,n){return e.requestJson({path:Yn(t),method:`GET`,signal:n})}async function Sa(e,t,n){return e.requestJson({path:Xn(t),method:`POST`,signal:n})}async function Ca(e,t,n){return e.requestJson({path:Yn(t),method:`DELETE`,signal:n})}async function wa(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=Zn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Ta(e,t,n){return e.requestJson({path:Qn(t),method:`GET`,signal:n})}async function Ea(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${$n(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const Da={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`}},Oa=Object.keys(Da),ka=`sft-lora`;function Aa(e){return e in Da}function ja(e){let{method:t,variant:n}=Da[e];return{method:t,variant:n}}function Ma(e,t){if(!e)return!1;let{method:n,variant:r}=Da[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Na(e){return e?Oa.filter(t=>Ma(e,t)):[]}async function Pa(e,t){return await ni(dn(e),t)}const Fa=`INSUFFICIENT_SAMPLES`;function Ia(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Fa,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(`
13
+ `)}}function La(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 Ra(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return K(e,{...r,schema:n})},resolveHyperParameters(e,t){return La(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const za=Ra(`sft`,`sft`,`chatml`),Ba={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},Va={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},Ha={...Va,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Ua={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Wa(e){return e===`image`||e===`image-i2i`}function Ga(e){return e===`video`||e===`video-kf2v`}function Ka(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function qa(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Ja=[za,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return K(e,{...n,schema:`tts`});if(Wa(t))return K(e,{...n,schema:`image`,maxBytes:_i});if(Ga(t)){let r=await K(e,{...n,schema:`video`,maxBytes:_i});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(G(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(G(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return K(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Ba};if(Wa(e)){let n={...e===`image-i2i`?Ha:Va};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Ga(e)){let e=t.model??t.baseModel,n={...Ua,batch_size:qa(e)?1:4,max_pixels:qa(e)?102400:Ka(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return La(t)},shouldSkipGate(e,t){return!!((t===`audio`||Wa(t)||Ga(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Wa(e)||Ga(e)}},Ra(`dpo`,`dpo_full`,`dpo`),Ra(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return K(e,{...n,schema:`cpt`,maxBytes:gi})},resolveHyperParameters(e,t){return La(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Ya(e){let t=Ja.find(t=>t.clientTrainingType===e);if(!t){let t=Ja.map(e=>e.clientTrainingType).join(`, `);throw new P(`Unknown training type "${e}".`,N.USAGE,`Supported training types: ${t}.`)}return t}function Xa(){return Ja.map(e=>e.clientTrainingType)}const Za=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,Qa=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,$a=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function eo(e,t){return W(await e.console(Za,{query:{type:0,modelId:t}}))}async function to(e,t,n){return W(await e.console(Qa,{input:{trainDatasetIds:t,hyperParams:n}}))}async function no(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return W(await e.console($a,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}async function ro(e,t,n){return e.requestJson({path:er(),method:`POST`,body:t,signal:n})}async function io(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=er(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ao(e,t,n){return e.requestJson({path:tr(t),method:`GET`,signal:n})}async function oo(e,t,n){return e.requestJson({path:tr(t),method:`DELETE`,signal:n})}async function so(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=ir(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function co(e,t,n,r){return e.requestJson({path:nr(t),method:`PUT`,body:n,signal:r})}async function lo(e,t,n,r){return e.requestJson({path:rr(t),method:`PUT`,body:n,signal:r})}const q={LORA:`lora`,PTU:`ptu`,MU:`mu`},uo=q.LORA;function fo(e){return e===`audio`?q.MU:uo}const po={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},mo=po.POST_PAY,ho={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},go={name:q.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},_o={name:q.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},vo={name:q.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||mo,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new P(`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.`,N.USAGE);try{let a=await so(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===q.MU)?.templates??[];if(o.length===0)throw i();let s=t===po.POST_PAY?ho.POST_PAID:ho.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 P?e:new P(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,N.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},yo={[q.LORA]:go,[q.PTU]:_o,[q.MU]:vo};function bo(e){let t=yo[e];if(!t)throw new P(`Unsupported plan "${e}". Supported plans: ${Object.keys(yo).join(`, `)}.`,N.USAGE);return t}const xo=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,So=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,Co=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function wo(e,t){return W(await e.console(xo,{input:{modelServiceId:t}}))}async function To(e,t){return W(await e.console(So,{input:{modelServiceId:t}}))}async function Eo(e){let t=[],n=1;for(;;){let r=W(await e.console(Co,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function Do(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const Oo=`speech-biasing`;function ko(e,t){return{model:Oo,input:{action:e,...t}}}async function Ao(e,t,n,r){return e.requestJson({path:Rn(),method:`POST`,body:ko(t,n),signal:r})}function jo(e,t,n){return Ao(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function Mo(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),Ao(e,`list_vocabulary`,r,n)}function No(e,t,n){return Ao(e,`query_vocabulary`,{vocabulary_id:t},n)}function Po(e,t,n,r){return Ao(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function Fo(e,t,n){return Ao(e,`delete_vocabulary`,{vocabulary_id:t},n)}function Io(e,t){try{return JSON.parse(e)}catch(e){throw new F(`${t} is not valid JSON — ${e.message}`)}}function Lo(e){let t=Io(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new F(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new F(`--vocabulary weight for "${e}" must be a number.`);return t}function Ro(e,t){let n=`--words`,r=Io(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new F(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new F(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new F(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new F(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new F(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new F(`${n} must contain at least one hot word.`);return i}const zo={output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},Bo={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},Vo={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},Ho={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},Uo={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Wo={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function Go(e){return e.auth===`apiKey`?Ho:e.auth===`console`?Uo:e.auth===`openapi`?Wo:{}}function Ko(e){return e}const qo=1;function Jo(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Yo(e,t){return`${Jo(e||`image`,`image`)}_${Jo((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Xo=()=>g(f(),`bailian-output`);function Zo(e,t){let n=t?.flagDir||e.outputDir||Xo(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Qo(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function $o(e){return o(e===`-`?0:e,`utf-8`)}async function es(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 ts(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 P(`Invalid ${t} value "${String(e)}". Use true or false.`,N.USAGE)}function ns(e,t=`boolean`){if(e!=null)return ts(e,t)}function rs(e,t,n=`boolean`){let r=ns(e,n);return r===void 0?t:r}function is(e,t){return ns(e,`watermark`)??t??!0}function as(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.exitCode!==void 0&&(t.exitCode=e.error.exitCode),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 os(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function ss(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=os(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let J;function cs(){return J||(process.env.NODE_ENV===`development`?(J=`dev`,J):process.env.BAILIAN_COMPILED===`1`?(J=`prod`,J):(J=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,J))}var ls=Te(((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=Oe(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Oe(`dns`)},function(e,t){e.exports=Oe(`util`)},function(e,t){e.exports=Oe(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},re=(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`},ie=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},ae=(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`},w=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},k=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},A=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},j=new Map,M=new Map;j.set(`Baiduspider-render`,i),j.set(`Baiduspider+`,i),j.set(`Baiduspider-image+`,i),j.set(`360Spider`,a),j.set(`360Spider-Image`,a),j.set(`bingbot`,o),j.set(`Googlebot`,s),j.set(`YandexRenderResourcesBot`,c),j.set(`spider`,l),j.set(`Dataprovider.com`,u),j.set(`AhrefsBot`,d),j.set(`BitSightBot`,f),j.set(`oBot`,p),j.set(`Cincraw`,m),j.set(`DingTalkBot-LinkService`,h),j.set(`YisouSpider`,g),j.set(`Bytespider`,_),j.set(`ev-crawler`,v),j.set(`bitdiscovery`,y),j.set(`Spider`,b),j.set(`Ai2Bot-Dolma`,ee),j.set(`dianjing_ad_spider`,te),M.set(`Baiduspider-render`,ne),M.set(`Baiduspider+`,ne),M.set(`Baiduspider-image+`,ne),M.set(`360Spider`,x),M.set(`360Spider-Image`,x),M.set(`bingbot`,re),M.set(`Googlebot`,S),M.set(`YandexRenderResourcesBot`,ie),M.set(`spider`,ae),M.set(`Dataprovider.com`,C),M.set(`AhrefsBot`,w),M.set(`BitSightBot`,T),M.set(`oBot`,E),M.set(`Cincraw`,D),M.set(`DingTalkBot-LinkService`,oe),M.set(`YisouSpider`,se),M.set(`Bytespider`,O),M.set(`ev-crawler`,ce),M.set(`bitdiscovery`,le),M.set(`Spider`,k),M.set(`Ai2Bot-Dolma`,A),M.set(`dianjing_ad_spider`,ue);let de={productHandlerMap:j,commentHandlerMap:M,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,de),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),x=n(5),re=n.n(x);function S(e){return(S=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 ie(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 ae(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ie(Object(n),!0).forEach(function(t){C(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ie(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(S(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(S(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return S(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function w(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=E(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.
14
14
  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 T(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)||E(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
15
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function E(e,t){if(e){if(typeof e==`string`)return D(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)?D(e,t):void 0}}function D(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 oe(){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=T(r[n],2),o=(a[0],a[1]);if(o){var s,c=w(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 O,k,se=(O=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:O,device_id:re.a.createHash(`md5`).update(oe()).digest(`hex`),platform:`node`}),ce=(0,ne.promisify)(te.a.resolve);function A(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,ae(ae({},se),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}A.prototype=((k=function(){}).prototype=b.prototype,new k),A.prototype.constructor=A,A.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,ce(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=A}]).default})),Uo=Te(((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})),Wo=De(Ho(),1),Go=De(Uo(),1);const Ko=()=>g(F(),`telemetry.jsonl`);let qo;const Jo=new Set;let Yo;try{let e=new Wo.default({pid:`bailian-cli-node`,env:Vo()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;Jo.add(e),e.finally(()=>Jo.delete(e))}return n},Yo=e,qo=e.use(Go.default)}catch{}async function Xo(e=1e3){try{if(Yo)try{typeof Yo._sendAll==`function`&&Yo._sendAll()}catch{}if(Jo.size===0)return;let t=[...Jo].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Zo(e){try{await nt();let n=Ko();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
16
- `,{mode:384})}catch{}}async function Qo(e){try{if(!qo)return;qo(e.command,Bo(e))}catch{}}const $o=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),es=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 ts(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||$o.has(n)||es.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function ns(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof P?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=Ro({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:ts(n)});Zo(u).catch(()=>{}),Qo(u).catch(()=>{})}}function rs(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 is=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await Gr(fn(this.settings))).map(rs).filter(e=>e!==null)}};function as(){return j(F(),`skills/bailian-docs-llm-wiki`)}function os(){return j(as(),`models`,`models.jsonl`)}function ss(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 cs(e){let t=E(e,`utf-8`).split(`
17
- `).filter(Boolean),n=[];for(let e of t)try{let t=ss(JSON.parse(e));t&&n.push(t)}catch{}return n}var ls=class{name=`catalog`;constructor(e){}available(){return C(os())}async load(){return this.available()?cs(os()):[]}};async function us(e,t){let n=[new ls({onPrepareStart:t?.onPrepareStart}),new is(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 P(`No model data available.`,N.GENERAL)}const ds={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},q={Single:`single`,Pipeline:`pipeline`},fs={Low:`low`,Medium:`medium`,High:`high`},ps={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`},ms={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},X={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},hs=20,gs=/-\d{4}-\d{2}-\d{2}$/,_s=new Set([Y.IG,Y.VG,Y.TTS,Y.RealtimeTTS,Y.ThreeDGeneration]),vs=new Set([Y.TG,Y.Reasoning,Y.ASR,Y.RealtimeASR,Y.RealtimeAudioTranslate,Y.TR,Y.ME]),ys={standard:0,large:32e3,"extra-large":128e3},bs=.4,xs=.6,Ss=.4,Cs=.2,ws=.2,Ts=.2;console.assert(Math.abs(bs+xs-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Ss+Cs+ws+Ts-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Es=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
15
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function E(e,t){if(e){if(typeof e==`string`)return D(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)?D(e,t):void 0}}function D(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 oe(){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=T(r[n],2),o=(a[0],a[1]);if(o){var s,c=w(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 se,O,ce=(se=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:se,device_id:re.a.createHash(`md5`).update(oe()).digest(`hex`),platform:`node`}),le=(0,ne.promisify)(te.a.resolve);function k(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,ae(ae({},ce),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}k.prototype=((O=function(){}).prototype=b.prototype,new O),k.prototype.constructor=k,k.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,le(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=k}]).default})),us=Te(((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})),ds=De(ls(),1),fs=De(us(),1);const ps=()=>g(I(),`telemetry.jsonl`);let ms;const hs=new Set;let gs;try{let e=new ds.default({pid:`bailian-cli-node`,env:cs()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;hs.add(e),e.finally(()=>hs.delete(e))}return n},gs=e,ms=e.use(fs.default)}catch{}async function _s(e=1e3){try{if(gs)try{typeof gs._sendAll==`function`&&gs._sendAll()}catch{}if(hs.size===0)return;let t=[...hs].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function vs(e){try{await nt();let n=ps();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
16
+ `,{mode:384})}catch{}}async function ys(e){try{if(!ms)return;ms(e.command,ss(e))}catch{}}const bs=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),xs=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 Ss(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||bs.has(n)||xs.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function Cs(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof P?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=as({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:Ss(n)});vs(u).catch(()=>{}),ys(u).catch(()=>{})}}function ws(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 Ts=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await ti(dn(this.settings))).map(ws).filter(e=>e!==null)}};function Es(){return j(I(),`skills/bailian-docs-llm-wiki`)}function Ds(){return j(Es(),`models`,`models.jsonl`)}function Os(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 ks(e){let t=E(e,`utf-8`).split(`
17
+ `).filter(Boolean),n=[];for(let e of t)try{let t=Os(JSON.parse(e));t&&n.push(t)}catch{}return n}var As=class{name=`catalog`;constructor(e){}available(){return C(Ds())}async load(){return this.available()?ks(Ds()):[]}};async function js(e,t){let n=[new As({onPrepareStart:t?.onPrepareStart}),new Ts(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 P(`No model data available.`,N.GENERAL)}const Ms={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},Y={Single:`single`,Pipeline:`pipeline`},Ns={Low:`low`,Medium:`medium`,High:`high`},Ps={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`},Fs={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Is={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Ls=20,Rs=/-\d{4}-\d{2}-\d{2}$/,zs=new Set([Z.IG,Z.VG,Z.TTS,Z.RealtimeTTS,Z.ThreeDGeneration]),Bs=new Set([Z.TG,Z.Reasoning,Z.ASR,Z.RealtimeASR,Z.RealtimeAudioTranslate,Z.TR,Z.ME]),Vs={standard:0,large:32e3,"extra-large":128e3},Hs=.4,Us=.6,Ws=.4,Gs=.2,Ks=.2,qs=.2;console.assert(Math.abs(Hs+Us-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Ws+Gs+Ks+qs-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Js=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
18
18
 
19
19
  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.
20
20
 
@@ -55,7 +55,7 @@ Single task:
55
55
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
56
56
 
57
57
  Pipeline (only when confident multi-model is needed):
58
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Ds=`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.
58
+ {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Ys=`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.
59
59
 
60
60
  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.
61
61
 
@@ -94,7 +94,7 @@ Key principles:
94
94
 
95
95
  Or (if single model suffices):
96
96
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
97
- ["key highlights"]}]}`,Os={complexity:q.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[Y.TG],requiredFeatures:[],budget:fs.Medium,contextNeed:ps.Standard,qualityPreference:J.Balanced,confidence:0},ks=[`unconstrained`,`scoped`,`comparison`,`alternative`];function As(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&ks.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 js(e,t){let n=xn(),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.
97
+ ["key highlights"]}]}`,Xs={complexity:Y.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[Z.TG],requiredFeatures:[],budget:Ns.Medium,contextNeed:Ps.Standard,qualityPreference:X.Balanced,confidence:0},Zs=[`unconstrained`,`scoped`,`comparison`,`alternative`];function Qs(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Zs.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 $s(e,t){let n=bn(),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.
98
98
 
99
99
  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.
100
100
 
@@ -141,9 +141,9 @@ Analyze whether the user mentioned specific models, model families, or vendors:
141
141
  - 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
142
142
  - modelPreference: { mode, targets?, excludes? }
143
143
 
144
- 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{...Os}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Os};let o=JSON.parse(a[0]),s=o.modelPreference,c=As(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??Os.budget,contextNeed:o.contextNeed??Os.contextNeed,qualityPreference:o.qualityPreference??Os.qualityPreference,confidence:1,modelPreference:c}}function Ms(e){let t=!1,n=!1;for(let r of e)_s.has(r)&&(t=!0),vs.has(r)&&(n=!0);return t&&n}function Ns(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(gs,``);return n===e?!0:!t.has(n)})}function Ps(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 Fs(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Is(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=ys[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 Ls(e,t,n){return e.map(e=>({model:e,score:Is(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Rs(e){return new Set(e.map(({model:e})=>e.model))}function zs(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 Bs(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function Vs(e,t,n){return n.size>=10?[]:Ls(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Hs(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:ps.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Ps(e,a,o)&&Fs(e,n));return l.length<5&&(l=e.filter(e=>Ps(e,a,o))),l.length<5&&(l=e),Ls(l,c,5)}function Us(e,t){e=Ns(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=Bs(Hs(e,i,a,t.budget,t.qualityPreference),Rs(r));r=[...r,...o]}let i=Vs(e,t,Rs(r));n=[...r,...i]}else if(Ms(t.requiredCapabilities))n=Ws(e,t);else{let r=e.filter(e=>Ps(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Ls(r,t,50)}return zs(n,3)}function Ws(e,t){let n=t.requiredCapabilities.filter(e=>_s.has(e)),r=t.requiredCapabilities.filter(e=>vs.has(e)),i=[];if(n.length>0&&(i=Ls(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Rs(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Ls(o,a,25)]}let a=Vs(e,t,Rs(i));return[...i,...a]}const Gs=`text-embedding-v4`;function Ks(){return j(F(),`skills/bailian-docs-llm-wiki`)}function qs(){return j(Ks(),`models-embeddings.json`)}function Js(){let e=qs();if(!C(e))return null;try{return JSON.parse(E(e,`utf-8`)).items}catch{return null}}async function Ys(e,t){let n={model:Gs,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 Xs(e,t){let n={model:Gs,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 Zs={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Qs={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function $s(){let e=j(Ks(),`groups`),t=new Map;if(!C(e))return t;for(let n of D(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(E(j(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 ec(e,t){let n=(e.capabilities??[]).map(e=>Zs[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Qs[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Qs[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 tc(e,t){let n=$s(),r=t.map(e=>ec(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Xs(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Gs,dimensions:512,count:a.length,items:a},s=qs();return T(le(s),{recursive:!0}),A(s,JSON.stringify(o)),a}function nc(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 rc=null;function ic(){return rc===null&&(rc=Js()),rc}function ac(){return ic()!==null}function oc(e){return(e??``).toLowerCase().replace(gs,``).replace(/[\s_-]+/g,``).trim()}function sc(e,t){let n=oc(t);if(!n)return!1;if(oc(e.model)===n||oc(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&oc(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=oc(e);return t.length>0&&n.includes(t)})}function cc(e,t){return t.some(t=>sc(e,t))}function lc(e,t){return t.length===0?[]:e.filter(e=>cc(e,t))}function uc(e,t){return t.length===0?e:e.filter(({model:e})=>!cc(e,t))}function dc(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 fc(e,t){return dc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function pc(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=ys[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),Ss*o+Cs*s+ws*c+Ts*u}function mc(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>fc(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function hc(e,t){return dc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function gc(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=nc(t,e.vector),o=a?pc(n,a):0;return[{model:n,score:a?bs*o+xs*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 _c(e){return{model:e,score:1,hardScore:1,softScore:1}}function vc(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?lc(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(_c(e));let r=new Set(l.map(({model:e})=>e.model)),s=gc(t,n,mc(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 gc(t,n,mc(c,o),i,a,o)}function yc(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)cc(t,s)&&!l.has(t.model)&&(c.push(_c(t)),l.add(t.model));return c}function bc(e,t,n,r,i,a,o){let s=lc(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(_c(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=gc(t,n,mc(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 xc(e,t,n,r,i){let a=ic();if(!a)a=await tc(e,t),rc=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 tc(e,t),rc=a)}let o=await Ys(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=vc(t,a,o,c,r,s,i);break;case`comparison`:e=yc(t,a,o,c,r,s,i);break;case`alternative`:e=bc(t,a,o,c,r,s,i);break;default:e=[]}return uc(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=>hc(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=gc(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 uc(n,l)}let u=mc(t,i);return uc(gc(a,o,u,r,s,i),l)}function Sc(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Cc(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=Sc(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
145
- `)}function wc(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!==ps.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(`
146
- `)}function Tc(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 Ec(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 Dc(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 Oc(e,t,n,r,i,a){let o=Cc(t),s=wc(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.
144
+ 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{...Xs}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Xs};let o=JSON.parse(a[0]),s=o.modelPreference,c=Qs(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??Xs.budget,contextNeed:o.contextNeed??Xs.contextNeed,qualityPreference:o.qualityPreference??Xs.qualityPreference,confidence:1,modelPreference:c}}function ec(e){let t=!1,n=!1;for(let r of e)zs.has(r)&&(t=!0),Bs.has(r)&&(n=!0);return t&&n}function tc(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Rs,``);return n===e?!0:!t.has(n)})}function nc(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 rc(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function ic(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=Vs[i];return d>0&&(c??0)>=d&&(u+=8),a===X.Flagship&&l===Is.Flagship||a===X.CostOptimized&&l===Is.CostOptimized?u+=15:a===X.Balanced&&l===Is.Flagship&&(u+=5),u}function ac(e,t,n){return e.map(e=>({model:e,score:ic(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function oc(e){return new Set(e.map(({model:e})=>e.model))}function sc(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 cc(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function lc(e,t,n){return n.size>=10?[]:ac(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function uc(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:Ps.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>nc(e,a,o)&&rc(e,n));return l.length<5&&(l=e.filter(e=>nc(e,a,o))),l.length<5&&(l=e),ac(l,c,5)}function dc(e,t){e=tc(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=cc(uc(e,i,a,t.budget,t.qualityPreference),oc(r));r=[...r,...o]}let i=lc(e,t,oc(r));n=[...r,...i]}else if(ec(t.requiredCapabilities))n=fc(e,t);else{let r=e.filter(e=>nc(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=ac(r,t,50)}return sc(n,3)}function fc(e,t){let n=t.requiredCapabilities.filter(e=>zs.has(e)),r=t.requiredCapabilities.filter(e=>Bs.has(e)),i=[];if(n.length>0&&(i=ac(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=oc(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...ac(o,a,25)]}let a=lc(e,t,oc(i));return[...i,...a]}const pc=`text-embedding-v4`;function mc(){return j(I(),`skills/bailian-docs-llm-wiki`)}function hc(){return j(mc(),`models-embeddings.json`)}function gc(){let e=hc();if(!C(e))return null;try{return JSON.parse(E(e,`utf-8`)).items}catch{return null}}async function _c(e,t){let n={model:pc,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 vc(e,t){let n={model:pc,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 yc={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},bc={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function xc(){let e=j(mc(),`groups`),t=new Map;if(!C(e))return t;for(let n of D(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(E(j(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 Sc(e,t){let n=(e.capabilities??[]).map(e=>yc[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>bc[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>bc[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 Cc(e,t){let n=xc(),r=t.map(e=>Sc(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await vc(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:pc,dimensions:512,count:a.length,items:a},s=hc();return T(A(s),{recursive:!0}),k(s,JSON.stringify(o)),a}function wc(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 Tc=null;function Ec(){return Tc===null&&(Tc=gc()),Tc}function Dc(){return Ec()!==null}function Oc(e){return(e??``).toLowerCase().replace(Rs,``).replace(/[\s_-]+/g,``).trim()}function kc(e,t){let n=Oc(t);if(!n)return!1;if(Oc(e.model)===n||Oc(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&Oc(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=Oc(e);return t.length>0&&n.includes(t)})}function Ac(e,t){return t.some(t=>kc(e,t))}function jc(e,t){return t.length===0?[]:e.filter(e=>Ac(e,t))}function Mc(e,t){return t.length===0?e:e.filter(({model:e})=>!Ac(e,t))}function Nc(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 Pc(e,t){return Nc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Fc(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=Vs[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===Is.Flagship?1:.5:a===X.CostOptimized&&(u=e.category===Is.CostOptimized?1:.5),Ws*o+Gs*s+Ks*c+qs*u}function Ic(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Pc(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function Lc(e,t){return Nc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Rc(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=wc(t,e.vector),o=a?Fc(n,a):0;return[{model:n,score:a?Hs*o+Us*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 zc(e){return{model:e,score:1,hardScore:1,softScore:1}}function Bc(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?jc(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(zc(e));let r=new Set(l.map(({model:e})=>e.model)),s=Rc(t,n,Ic(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 Rc(t,n,Ic(c,o),i,a,o)}function Vc(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)Ac(t,s)&&!l.has(t.model)&&(c.push(zc(t)),l.add(t.model));return c}function Hc(e,t,n,r,i,a,o){let s=jc(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(zc(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Rc(t,n,Ic(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 Uc(e,t,n,r,i){let a=Ec();if(!a)a=await Cc(e,t),Tc=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 Cc(e,t),Tc=a)}let o=await _c(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=Bc(t,a,o,c,r,s,i);break;case`comparison`:e=Vc(t,a,o,c,r,s,i);break;case`alternative`:e=Hc(t,a,o,c,r,s,i);break;default:e=[]}return Mc(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=>Lc(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Rc(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 Mc(n,l)}let u=Ic(t,i);return Mc(Rc(a,o,u,r,s,i),l)}function Wc(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Gc(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=Wc(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
145
+ `)}function Kc(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!==Ps.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(`
146
+ `)}function qc(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 Jc(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 Yc(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 Xc(e,t,n,r,i,a){let o=Gc(t),s=Kc(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.
147
147
 
148
148
  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.
149
149
 
@@ -185,6 +185,6 @@ The intent's modelPreference.targets is the reference model.
185
185
  - Output strict JSON
186
186
 
187
187
  ## Output Format
188
- {"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?Ds:Es)+e}else l=n.complexity===q.Pipeline?Ds:Es;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=xn(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Xt(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=Ec(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Dc(e,g),{type:q.Pipeline,summary:h.summary??``,steps:e}}let _=Ec(h.recommendations??h??[],g,i);return{type:q.Single,recommendations:_}}function Z(){return j(F(),`skills`)}function kc(){return j(Z(),`skill-lock.json`)}function Ac(){return{version:1,skills:{}}}function jc(){let e=kc();if(!C(e))return Ac();try{let t=JSON.parse(E(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?Ac():t}catch{return Ac()}}function Mc(e){T(Z(),{recursive:!0}),A(kc(),JSON.stringify(e,null,2)+`
189
- `)}function Nc(e,t){let n=jc();n.skills[e]={...n.skills[e],...t},Mc(n)}function Pc(){let e=fe(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||j(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:j(e,r,`skills`),detectDirs:[j(e,r)]}),i=(t,n)=>t?.trim()||j(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:j(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>j(e,t)),s=o.find(e=>C(e))??o[0],c=[j(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(j(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(j(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:j(e,`.agents`,`skills`),detectDirs:[j(e,`.agents`),j(e,`.cline`),j(e,`.dexto`),j(e,`.firebender`),j(e,`.kimi-code`),j(e,`.kimi`),j(e,`.loaf`),j(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:j(n,`agents`,`skills`),detectDirs:[j(n,`agents`),j(n,`amp`),j(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:j(e,`.astrbot`,`data`,`skills`),detectDirs:[j(t,`data`,`skills`),j(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:j(e,`.codebuddy`,`skills`),detectDirs:[j(t,`.codebuddy`),j(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:j(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:j(e,`.continue`,`skills`),detectDirs:[j(t,`.continue`),j(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:j(e,`.deepagents`,`agent`,`skills`),detectDirs:[j(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:j(n,`devin`,`skills`),detectDirs:[j(n,`devin`)]},r(`droid`,`Droid`,`.factory`),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:j(n,`goose`,`skills`),detectDirs:[j(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,i(process.env.HERMES_HOME,`.hermes`)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:j(e,`.jazz`,`skills`),detectDirs:[j(e,`.jazz`),j(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:j(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[j(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:j(e,`.minimax`,`skills`),detectDirs:[j(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:j(n,`opencode`,`skills`),detectDirs:[j(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:j(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:j(e,`.tabnine`,`agent`,`skills`),detectDirs:[j(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),{id:`zcode`,displayName:`ZCode`,skillsDir:j(e,`.zcode`,`skills`),detectDirs:[j(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Q(){return Pc().filter(e=>e.detectDirs.some(e=>C(e)))}function Fc(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function Ic(e){let t=Z();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+de)}return e===t||e.startsWith(t+de)}function Lc(e){try{if(!w(e).isSymbolicLink())return!1;let t=oe(e);return Ic(ue(t)?t:M(le(e),t))}catch{return!1}}function Rc(e,t){if(!t.some(t=>Fc(t,e)))return!1;try{return w(e).isDirectory()}catch{return!1}}function zc(e){try{return w(e).isDirectory()?C(j(e,`SKILL.md`)):!1}catch{return!1}}const Bc=`existing file/dir not managed by bl skill`;function Vc(e,t=Q(),n=[]){let r=j(Z(),e),i=[];for(let a of t){let t=j(a.skillsDir,e);try{let e=!1;try{w(t),e=!0}catch{}if(e)if(Lc(t))k(t);else if(Rc(t,n))k(t,{recursive:!0,force:!0});else if(zc(t))k(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:Bc});continue}T(a.skillsDir,{recursive:!0});try{ce(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{ie(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function Hc(e,t=Q(),n=[]){let r=Vc(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===Bc).map(e=>e.path),s=n.filter(e=>!a.some(t=>Fc(t,e))&&!o.some(t=>Fc(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function Uc(e,t=[]){let n=[],r=new Set(t);for(let t of Pc())r.add(j(t.skillsDir,e));for(let e of r)try{let r;try{r=w(e)}catch{continue}r.isSymbolicLink()?Lc(e)&&(k(e),n.push(e)):t.some(t=>Fc(t,e))&&(k(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function Wc(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function Gc(e,t){let n=_e.extract();n.on(`entry`,(e,r,i)=>{if(!Wc(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=j(t,e.name);if(e.type===`directory`){T(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}T(le(a),{recursive:!0});let o=ae(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await he(me.from(e),ge(),n)}function Kc(e){let t=[],n=r=>{for(let i of D(r?j(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=pe(`sha256`);for(let n of t)r.update(n),r.update(E(j(e,n)));return`sha256:${r.digest(`hex`)}`}function qc(e,t){T(le(t),{recursive:!0});let n=`${t}.old-${Date.now()}`;C(t)&&O(t,n);try{O(e,t)}catch(e){throw C(n)&&!C(t)&&O(n,t),e}try{C(n)&&k(n,{recursive:!0,force:!0})}catch{}}function Jc(e){if(e instanceof P){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function Yc(e){return e instanceof P&&e.api?.httpStatus===429}function Xc(e,t){return Math.min(t*2**(e-1),1e4)}function Zc(e){return new Promise(t=>setTimeout(t,e))}async function Qc(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??Jc,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;Yc(e)&&await Zc(Xc(t,a))}throw o}function $c(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function el(e=3e4,t=3){return Qc(async()=>{let t=`${$c()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new P(`Cannot access skill registry: ${t}`,N.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new P(`Skill registry returned HTTP ${n.status}: ${t}`,N.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 P(`Skill index index.json is not valid JSON`,N.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 P(`Skill index index.json has invalid structure`,N.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const tl=/^sha256-[0-9a-f]{64}\.tar\.br$/;function nl(e){let t=e?.object;return t&&tl.test(t)?t:`skill.tar.br`}async function rl(e,t,n=3){return Qc(async()=>{let n=`${$c()}/${e}/${nl(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new P(`Failed to download skill ${e}: ${n}`,N.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new P(`Failed to download skill ${e}: HTTP ${r.status}`,N.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())},{attempts:n})}function il(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function al(e){return e.length>0&&il(e)===e}function ol(e,t){throw new P(`Skill ${e} validation failed: ${t}`,N.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function sl(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function cl(e,t){let n=j(e,`SKILL.md`),r;try{se(n).isFile()||ol(t,`SKILL.md is not a regular file`),r=E(n,`utf-8`)}catch(e){if(e instanceof P)throw e;ol(t,`missing SKILL.md`)}let i=sl(r);i===null&&ol(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{ol(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&ol(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)&&ol(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function ll(e){if(!al(e))throw new P(`Invalid skill name: ${e}`,N.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function ul(e,t,n){ll(e);let r=Z(),i=j(r,e),a=j(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(T(a,{recursive:!0}),await Gc(t,a),n?.startsWith(`sha256:`)){let t=Kc(a);if(t!==n)throw new P(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,N.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=cl(a,e);return qc(a,i),{name:e,path:i,meta:r}}finally{try{C(a)&&k(a,{recursive:!0,force:!0})}catch{}}}async function dl(e,t,n){if(t.compression&&t.compression!==`tar.br`)throw new P(`Skill ${e} uses unsupported compression format: ${t.compression}`,N.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return ul(e,await rl(e,t,n),t.contentHash)}function fl(e){ll(e);let t=j(Z(),e);return C(t)?(k(t,{recursive:!0,force:!0}),!0):!1}function pl(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 ml(e,t,n=Q(),r=[],i){await dl(e,t,i);let a=Hc(e,n,r);return{lockEntry:pl(t,a.links),linkedAgents:a.linkedAgents}}const $=`bailian-docs-llm-wiki`;function hl(){return j(F(),`skills/bailian-docs-llm-wiki`)}function gl(){return C(j(hl(),`models`,`models.jsonl`))}function _l(){return j(F(),`wiki-sync-state.json`)}function vl(){try{return JSON.parse(E(_l(),`utf-8`))}catch{return null}}function yl(e){try{A(_l(),JSON.stringify(e))}catch{}}function bl(e){try{Nc($,e)}catch{}}function xl(e){try{let t=jc().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function Sl(){try{return(await el(3e3,1)).skills[$]??null}catch{return null}}async function Cl(){let e=vl(),t=Date.now();if(e&&t-e.lastChecked<432e5&&gl())return!1;let n=await Sl();if(!n?.contentHash)return!1;if(gl()&&(!e||e.contentHash===n.contentHash)){if(yl({lastChecked:t,contentHash:n.contentHash}),xl(n.contentHash)){let e=jc().skills[$]?.links??[];bl(pl(n,Hc($,Q(),e).links))}return!1}try{let e=jc().skills[$]?.links??[];bl((await ml($,n,Q(),e,1)).lockEntry)}catch{return!1}return yl({lastChecked:t,contentHash:n.contentHash}),!0}const wl=`bailian-cli`,Tl=`install-method`,El=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function Dl(e){return e?j(F(),`${Tl}.${e}`):j(F(),Tl)}function Ol(){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 kl(e){if(!e)return null;let t=e.trim().toLowerCase();return El.has(t)?t:null}function Al(e){try{return kl(E(e,`utf-8`).split(`
190
- `)[0])}catch{return null}}function jl(){let e=kl(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Ol()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Ml(e){let t=kl(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=Al(Dl(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=Al(Dl());if(e)return e}return jl()}return Al(Dl())||jl()}function Nl(e){let t=Ml(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function Pl(e,t={clientName:wl}){try{let n=F();C(n)||T(n,{recursive:!0,mode:448}),A(Dl(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&A(Dl(),`${e}\n`,{mode:384})}catch{}}const Fl=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Il=`https://github.com/modelstudioai/cli/releases`,Ll=`https://bailian.aliyun.com/cli/install.sh`,Rl=`https://bailian.aliyun.com/cli/install.ps1`;function zl(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):Fl}function Bl(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${zl()}/manifest.json`:`${zl()}/${t}.json`}function Vl(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${zl()}/${n}/${t}`}function Hl(){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 Ul(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function Wl(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function Gl(e){return new Promise((t,n)=>{S.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??Error(`Failed to open zip: ${e}`));return}t(i)})})}function Kl(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function ql(e,t,n){let r=await Gl(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=Kl(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 ve(le(t),{recursive:!0}),await he(r,ae(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function Jl(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new ke(`--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 ke(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Yl(){let e=Z();return C(e)?D(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return se(j(e,t)).isDirectory()}catch{return!1}}):[]}function Xl(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{He as API_KEY_CAPABILITY_PATTERN,bo as ASYNC_FLAG,Ie as BAILIAN_HOST,no as BILLING_METHOD,wl as BINARY_PRODUCT_CLIENT_NAME,P as BailianError,fs as Budgets,Ha as CALC_DATASETS_TOKENS_API,Et as CHANNEL,io as CHARGE_TYPE,Eo as COMMAND_PACK_API_VERSION,yo as CONCURRENT_FLAG,ze as CONFIG_FILE_KEYS,So as CONSOLE_AUTH_FLAGS,Y as Capabilities,hn as Client,q as Complexities,ps as ContextNeeds,ro as DEFAULT_BILLING_METHOD,Fl as DEFAULT_CLI_CDN_BASE,eo as DEFAULT_DEPLOY_PLAN,Rl as DEFAULT_INSTALL_PS1_URL,Ll as DEFAULT_INSTALL_SCRIPT_URL,Re as DEFAULT_LANGUAGE,ya as DEFAULT_TRAINING_TYPE,po as DEPLOY_LIST_INDEPENDENT_API,G as DEPLOY_PLAN,uo as DEPLOY_START_API,fo as DEPLOY_STOP_API,Fe as DOCS_HOSTS,Ua as ESTIMATE_FINETUNE_TOKENS_API,N as ExitCode,ms as Features,Il as GITHUB_RELEASES_BASE,vo as GLOBAL_FLAGS,Ta as INSUFFICIENT_SAMPLES_CODE,oi as MAX_CPT_BYTES,ai as MAX_DATASET_BYTES,si as MAX_MEDIA_ZIP_BYTES,xo as MODEL_AUTH_FLAGS,Hr as MODEL_LIST_API,cn as McpClient,ds as Modalities,X as ModelCategories,Co as OPENAPI_AUTH_FLAGS,Dt as OPEN_API_SOURCE,Ur as PREDICT_CONFIG_API,J as QualityPreferences,or as RAG_PATHS,Pe as REGIONS,hs as SEMANTIC_TOP_K,co as STRATEGIES,Le as SUPPORTED_LANGUAGES,Va as TRAINING_MODEL_PRICE_API,va as TRAINING_TYPES_CLI,_a as TRAINING_TYPE_MAP,ke as UsageError,vt as activateConfigProfile,js as analyzeIntent,fn as anonymousConsoleCall,Mn as appCompletionPath,qc as atomicSwap,nn as bailianMcpPath,rn as bailianMcpSsePath,Ul as binaryAssetFileName,Wl as binaryInnerFileName,Nt as buildAcsCanonicalQuery,Ar as buildAsrFlashRequest,kr as buildAsyncAsrLanguageFields,Tc as buildDocLink,St as buildSettings,pl as buildSkillLockEntry,xt as buildSources,mn as callConsoleGateway,fa as cancelFineTune,Bl as channelManifestUrl,xn as chatPath,Mr as collectAsrTranscriptionItems,Kc as computeDirContentHash,Xl as computeSkillStatuses,sn as connectBailianMcpWithFallback,zr as createBailianControlUser,qa as createDeployment,la as createFineTune,Fr as createInstrumentedFetch,Ro as createTrackingEvent,wo as credentialFlagDefs,to as defaultDeployPlan,To as defineCommand,yt as deleteConfigProfile,ii as deleteDataset,Xa as deleteDeployment,pa as deleteFineTune,et as describeAuthState,Hl as detectBinaryPlatform,jl as detectInstallMethod,Q as detectInstalledAgents,Qi as detectModality,ot as detectOutputFormat,rl as downloadSkillAsset,dn as effectiveConsoleGatewayConfig,Ac as emptySkillLock,nt as ensureConfigDir,Ka as estimateCptTokens,Ga as estimateSftDpoTokens,ga as exportCheckpoint,jr as extractAsrFlashText,Gc as extractTarBr,ql as extractZipEntryToFile,Hc as fanOutSkillToAgents,wa as fetchModelCapability,Jr as fetchModelDetail,qr as fetchModelGroups,Wr as fetchModelList,Gr as fetchModelListAll,Zr as fetchPredictConfig,el as fetchSkillsIndex,Wa as fetchTrainingModelPrice,_o as findDeploymentEntry,Kr as findModelByName,Xo as flushTelemetry,at as formatErrorJson,ca as formatIssue,it as formatJson,st as formatOutput,rt as formatText,yn as generateCLIAccessToken,Oo as generateFilename,Pc as getAgentTargets,zl as getCliCdnBase,F as getConfigDir,I as getConfigPath,tt as getCredentialsPath,ri as getDataset,Ya as getDeployment,da as getFineTune,ma as getFineTuneLogs,Ml as getInstallMethod,ei as getModelProfilePreset,us as getModels,za as getProfile,kc as getSkillLockPath,$c as getSkillRegistryBaseUrl,Z as getSkillsDir,Nl as getUpdateInstallMethod,En as image2ImagePath,On as image2videoPath,Ht as imageFileToDataUri,Cn as imagePath,wn as imageSyncPath,Tn as imageText2ImagePath,Or as inferAudioFormatHint,dl as installSkill,ul as installSkillFromBuffer,ml as installSkillWithFanout,Ue as isApiKeyCapability,Ol as isCompiledBinary,hr as isLegacyImage2ImageModel,mr as isLegacyText2ImageModel,Gt as isLocalFile,Wc as isSafeEntryName,al as isSafeSkillName,ac as isSemanticAvailable,an as isStreamableHttpUnsupported,ur as isSyncMultimodalImageModel,ba as isTrainingTypeCli,on as isUrlOverrideSseFallbackCandidate,gr as isWanxFunctionImageEditModel,Un as knowledgeChatEndpoint,Vn as knowledgeRetrievePath,Hn as knowledgeSearchEndpoint,Vc as linkSkillToAgents,Br as listBailianControlWorkspaces,ha as listCheckpoints,ni as listDatasets,Za as listDeployableModels,Ja as listDeployments,ua as listFineTunes,go as listIndependentDeployedModels,Yl as listSkillDirsOnDisk,sa as listSupportedFormats,Ca as listSupportedTrainingTypes,Ba as listTrainingTypes,Zo as localSink,wt as makeAuthStore,Qr as makeConfigStore,je as mapApiError,Tt as maskToken,Cl as maybeSyncWikiData,Wn as mcpWebSearchPath,Nn as memoryAddPath,Fn as memoryListPath,In as memoryNodePath,Pn as memorySearchPath,Sa as modelSupportsTrainingType,An as modelsLimitsPath,jn as modelsPermissionsPath,We as normalizeApiKeyCapabilities,dt as normalizeConfigName,Me as normalizeModelBaseUrl,Po as parseBooleanValue,Ke as parseConfigFile,li as parseDatasetSchemaFlag,Fo as parseOptionalBooleanValue,Xt as parseSSE,Jl as parseSkillNames,lo as pickPlanStrategy,aa as pickValidator,Ea as preflightBatchSizeGate,zn as profileSchemaPath,ar as ragEndpoint,Oc as rankModels,R as readConfigFile,ht as readConfigProfiles,jc as readSkillLock,Mo as readTextFromPathOrStdin,Us as recallCandidates,xc as recallSemantic,Ut as redactDataUri,bn as refreshAccessToken,oa as registerValidator,Vl as releaseAssetUrl,Qo as remoteSink,fl as removeSkillDir,At as request,Mt as requestJson,Vr as resetBailianControlPolicies4Agent,Je as resolveApiKey,Dr as resolveAsrApi,nl as resolveAssetFileName,Io as resolveBooleanFlag,Ye as resolveConsole,Kt as resolveFileUrl,br as resolveImageEditApi,yr as resolveImageGenerateApi,_r as resolveImageSizeProfile,qe as resolveModelBaseUrl,Xe as resolveOpenApi,Ao as resolveOutputDir,vr as resolvePromptExtendDefault,Lo as resolveWatermark,Sn as responsesPath,No as runWithConcurrency,il as sanitizeSkillName,Qa as scaleDeployment,bt as selectApiKeyResolutionSources,Pt as signAcsRequest,Ot as sourceConfig,Rn as speechRecognizePath,Ln as speechSynthesizePath,mo as startModelService,ho as stopModelService,jo as stripUndefined,kn as taskPath,ns as trackCommandExecution,B as trackingHeaders,xa as trainingTypeMethodVariant,Uc as unlinkSkillFromAgents,H as unwrapResponse,$a as updateDeployment,ti as uploadDataset,Wt as uploadFile,Nc as upsertSkillLockEntry,Bn as userProfilePath,_t as validateConfigProfileActivation,W as validateDataset,cl as validateSkillDir,Dn as videoGeneratePath,z as writeConfigFile,Pl as writeInstallMethodSync,Mc as writeSkillLock};
188
+ {"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?Ys:Js)+e}else l=n.complexity===Y.Pipeline?Ys:Js;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=bn(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Yt(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=Jc(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Yc(e,g),{type:Y.Pipeline,summary:h.summary??``,steps:e}}let _=Jc(h.recommendations??h??[],g,i);return{type:Y.Single,recommendations:_}}function Q(){return j(I(),`skills`)}function Zc(){return j(Q(),`skill-lock.json`)}function Qc(){return{version:1,skills:{}}}function $c(){let e=Zc();if(!C(e))return Qc();try{let t=JSON.parse(E(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?Qc():t}catch{return Qc()}}function el(e){T(Q(),{recursive:!0}),k(Zc(),JSON.stringify(e,null,2)+`
189
+ `)}function tl(e,t){let n=$c();n.skills[e]={...n.skills[e],...t},el(n)}function nl(){let e=fe(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||j(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:j(e,r,`skills`),detectDirs:[j(e,r)]}),i=(t,n)=>t?.trim()||j(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:j(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>j(e,t)),s=o.find(e=>C(e))??o[0],c=[j(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(j(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(j(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:j(e,`.agents`,`skills`),detectDirs:[j(e,`.agents`),j(e,`.cline`),j(e,`.dexto`),j(e,`.firebender`),j(e,`.kimi-code`),j(e,`.kimi`),j(e,`.loaf`),j(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:j(n,`agents`,`skills`),detectDirs:[j(n,`agents`),j(n,`amp`),j(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:j(e,`.astrbot`,`data`,`skills`),detectDirs:[j(t,`data`,`skills`),j(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:j(e,`.codebuddy`,`skills`),detectDirs:[j(t,`.codebuddy`),j(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:j(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:j(e,`.continue`,`skills`),detectDirs:[j(t,`.continue`),j(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:j(e,`.deepagents`,`agent`,`skills`),detectDirs:[j(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:j(n,`devin`,`skills`),detectDirs:[j(n,`devin`)]},r(`droid`,`Droid`,`.factory`),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:j(n,`goose`,`skills`),detectDirs:[j(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,i(process.env.HERMES_HOME,`.hermes`)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:j(e,`.jazz`,`skills`),detectDirs:[j(e,`.jazz`),j(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:j(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[j(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:j(e,`.minimax`,`skills`),detectDirs:[j(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:j(n,`opencode`,`skills`),detectDirs:[j(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:j(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:j(e,`.tabnine`,`agent`,`skills`),detectDirs:[j(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),{id:`zcode`,displayName:`ZCode`,skillsDir:j(e,`.zcode`,`skills`),detectDirs:[j(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function rl(){return nl().filter(e=>e.detectDirs.some(e=>C(e)))}function il(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function al(e){let t=Q();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+de)}return e===t||e.startsWith(t+de)}function ol(e){try{if(!w(e).isSymbolicLink())return!1;let t=oe(e);return al(ue(t)?t:M(A(e),t))}catch{return!1}}function sl(e,t){if(!t.some(t=>il(t,e)))return!1;try{return w(e).isDirectory()}catch{return!1}}function cl(e){try{return w(e).isDirectory()?C(j(e,`SKILL.md`)):!1}catch{return!1}}const ll=`existing file/dir not managed by bl skill`;function ul(e,t=rl(),n=[]){let r=j(Q(),e),i=[];for(let a of t){let t=j(a.skillsDir,e);try{let e=!1;try{w(t),e=!0}catch{}if(e)if(ol(t))O(t);else if(sl(t,n))O(t,{recursive:!0,force:!0});else if(cl(t))O(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:ll});continue}T(a.skillsDir,{recursive:!0});try{le(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{ie(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function dl(e,t=rl(),n=[]){let r=ul(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===ll).map(e=>e.path),s=n.filter(e=>!a.some(t=>il(t,e))&&!o.some(t=>il(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function fl(e,t=[]){let n=[],r=new Set(t);for(let t of nl())r.add(j(t.skillsDir,e));for(let e of r)try{let r;try{r=w(e)}catch{continue}r.isSymbolicLink()?ol(e)&&(O(e),n.push(e)):t.some(t=>il(t,e))&&(O(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function pl(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function ml(e,t){let n=_e.extract();n.on(`entry`,(e,r,i)=>{if(!pl(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=j(t,e.name);if(e.type===`directory`){T(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}T(A(a),{recursive:!0});let o=ae(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await he(me.from(e),ge(),n)}function hl(e){let t=[],n=r=>{for(let i of D(r?j(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=pe(`sha256`);for(let n of t)r.update(n),r.update(E(j(e,n)));return`sha256:${r.digest(`hex`)}`}function gl(e,t){T(A(t),{recursive:!0});let n=`${t}.old-${Date.now()}`;C(t)&&se(t,n);try{se(e,t)}catch(e){throw C(n)&&!C(t)&&se(n,t),e}try{C(n)&&O(n,{recursive:!0,force:!0})}catch{}}function _l(e){if(e instanceof P){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function vl(e){return e instanceof P&&e.api?.httpStatus===429}function yl(e,t){return Math.min(t*2**(e-1),1e4)}function bl(e){return new Promise(t=>setTimeout(t,e))}async function xl(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??_l,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;vl(e)&&await bl(yl(t,a))}throw o}function Sl(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function Cl(e=3e4,t=3){return xl(async()=>{let t=`${Sl()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new P(`Cannot access skill registry: ${t}`,N.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new P(`Skill registry returned HTTP ${n.status}: ${t}`,N.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 P(`Skill index index.json is not valid JSON`,N.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 P(`Skill index index.json has invalid structure`,N.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const wl=/^sha256-[0-9a-f]{64}\.tar\.br$/;function Tl(e){let t=e?.object;return t&&wl.test(t)?t:`skill.tar.br`}async function El(e,t,n=3){return xl(async()=>{let n=`${Sl()}/${e}/${Tl(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new P(`Failed to download skill ${e}: ${n}`,N.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new P(`Failed to download skill ${e}: HTTP ${r.status}`,N.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())},{attempts:n})}function Dl(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function Ol(e){return e.length>0&&Dl(e)===e}function kl(e,t){throw new P(`Skill ${e} validation failed: ${t}`,N.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function Al(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function jl(e,t){let n=j(e,`SKILL.md`),r;try{ce(n).isFile()||kl(t,`SKILL.md is not a regular file`),r=E(n,`utf-8`)}catch(e){if(e instanceof P)throw e;kl(t,`missing SKILL.md`)}let i=Al(r);i===null&&kl(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{kl(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&kl(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)&&kl(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function Ml(e){if(!Ol(e))throw new P(`Invalid skill name: ${e}`,N.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function Nl(e,t,n){Ml(e);let r=Q(),i=j(r,e),a=j(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(T(a,{recursive:!0}),await ml(t,a),n?.startsWith(`sha256:`)){let t=hl(a);if(t!==n)throw new P(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,N.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=jl(a,e);return gl(a,i),{name:e,path:i,meta:r}}finally{try{C(a)&&O(a,{recursive:!0,force:!0})}catch{}}}async function Pl(e,t,n){if(t.compression&&t.compression!==`tar.br`)throw new P(`Skill ${e} uses unsupported compression format: ${t.compression}`,N.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return Nl(e,await El(e,t,n),t.contentHash)}function Fl(e){Ml(e);let t=j(Q(),e);return C(t)?(O(t,{recursive:!0,force:!0}),!0):!1}function Il(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 Ll(e,t,n=rl(),r=[],i){await Pl(e,t,i);let a=dl(e,n,r);return{lockEntry:Il(t,a.links),linkedAgents:a.linkedAgents}}const $=`bailian-docs-llm-wiki`;function Rl(){return j(I(),`skills/bailian-docs-llm-wiki`)}function zl(){return C(j(Rl(),`models`,`models.jsonl`))}function Bl(){return j(I(),`wiki-sync-state.json`)}function Vl(){try{return JSON.parse(E(Bl(),`utf-8`))}catch{return null}}function Hl(e){try{k(Bl(),JSON.stringify(e))}catch{}}function Ul(e){try{tl($,e)}catch{}}function Wl(e){try{let t=$c().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function Gl(){try{return(await Cl(3e3,1)).skills[$]??null}catch{return null}}async function Kl(){let e=Vl(),t=Date.now();if(e&&t-e.lastChecked<432e5&&zl())return!1;let n=await Gl();if(!n?.contentHash)return!1;if(zl()&&(!e||e.contentHash===n.contentHash)){if(Hl({lastChecked:t,contentHash:n.contentHash}),Wl(n.contentHash)){let e=$c().skills[$]?.links??[];Ul(Il(n,dl($,rl(),e).links))}return!1}try{let e=$c().skills[$]?.links??[];Ul((await Ll($,n,rl(),e,1)).lockEntry)}catch{return!1}return Hl({lastChecked:t,contentHash:n.contentHash}),!0}const ql=`bailian-cli`,Jl=`install-method`,Yl=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function Xl(e){return e?j(I(),`${Jl}.${e}`):j(I(),Jl)}function Zl(){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 Ql(e){if(!e)return null;let t=e.trim().toLowerCase();return Yl.has(t)?t:null}function $l(e){try{return Ql(E(e,`utf-8`).split(`
190
+ `)[0])}catch{return null}}function eu(){let e=Ql(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Zl()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function tu(e){let t=Ql(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=$l(Xl(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=$l(Xl());if(e)return e}return eu()}return $l(Xl())||eu()}function nu(e){let t=tu(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function ru(e,t={clientName:ql}){try{let n=I();C(n)||T(n,{recursive:!0,mode:448}),k(Xl(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&k(Xl(),`${e}\n`,{mode:384})}catch{}}const iu=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,au=`https://github.com/modelstudioai/cli/releases`,ou=`https://bailian.aliyun.com/cli/install.sh`,su=`https://bailian.aliyun.com/cli/install.ps1`;function cu(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):iu}function lu(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${cu()}/manifest.json`:`${cu()}/${t}.json`}function uu(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${cu()}/${n}/${t}`}function du(){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 fu(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function pu(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function mu(e){return new Promise((t,n)=>{S.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??Error(`Failed to open zip: ${e}`));return}t(i)})})}function hu(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function gu(e,t,n){let r=await mu(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=hu(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 ve(A(t),{recursive:!0}),await he(r,ae(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function _u(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new F(`--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 F(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function vu(){let e=Q();return C(e)?D(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return ce(j(e,t)).isDirectory()}catch{return!1}}):[]}function yu(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{Ve as API_KEY_CAPABILITY_PATTERN,Vo as ASYNC_FLAG,Fe as BAILIAN_HOST,po as BILLING_METHOD,ql as BINARY_PRODUCT_CLIENT_NAME,P as BailianError,Ns as Budgets,Qa as CALC_DATASETS_TOKENS_API,Tt as CHANNEL,ho as CHARGE_TYPE,qo as COMMAND_PACK_API_VERSION,Bo as CONCURRENT_FLAG,Re as CONFIG_FILE_KEYS,Uo as CONSOLE_AUTH_FLAGS,Z as Capabilities,mn as Client,Y as Complexities,Ps as ContextNeeds,mo as DEFAULT_BILLING_METHOD,iu as DEFAULT_CLI_CDN_BASE,uo as DEFAULT_DEPLOY_PLAN,su as DEFAULT_INSTALL_PS1_URL,ou as DEFAULT_INSTALL_SCRIPT_URL,Le as DEFAULT_LANGUAGE,ka as DEFAULT_TRAINING_TYPE,Co as DEPLOY_LIST_INDEPENDENT_API,q as DEPLOY_PLAN,xo as DEPLOY_START_API,So as DEPLOY_STOP_API,Pe as DOCS_HOSTS,$a as ESTIMATE_FINETUNE_TOKENS_API,N as ExitCode,Fs as Features,au as GITHUB_RELEASES_BASE,zo as GLOBAL_FLAGS,Fa as INSUFFICIENT_SAMPLES_CODE,gi as MAX_CPT_BYTES,hi as MAX_DATASET_BYTES,_i as MAX_MEDIA_ZIP_BYTES,Ho as MODEL_AUTH_FLAGS,Qr as MODEL_LIST_API,sn as McpClient,Ms as Modalities,Is as ModelCategories,Wo as OPENAPI_AUTH_FLAGS,Et as OPEN_API_SOURCE,$r as PREDICT_CONFIG_API,X as QualityPreferences,hr as RAG_PATHS,Ne as REGIONS,ur as SANDBOX_PATHS,Ls as SEMANTIC_TOP_K,Oo as SPEECH_BIASING_MODEL,yo as STRATEGIES,Ie as SUPPORTED_LANGUAGES,Za as TRAINING_MODEL_PRICE_API,Oa as TRAINING_TYPES_CLI,Da as TRAINING_TYPE_MAP,F as UsageError,_t as activateConfigProfile,or as agentStudioFilesPath,$s as analyzeIntent,dn as anonymousConsoleCall,jn as appCompletionPath,gl as atomicSwap,tn as bailianMcpPath,nn as bailianMcpSsePath,fu as binaryAssetFileName,pu as binaryInnerFileName,Mt as buildAcsCanonicalQuery,Rr as buildAsrContextMessages,Br as buildAsrFlashRequest,zr as buildAsyncAsrLanguageFields,qc as buildDocLink,xt as buildSettings,Il as buildSkillLockEntry,bt as buildSources,ko as buildVocabularyRequest,pn as callConsoleGateway,Sa as cancelFineTune,lu as channelManifestUrl,bn as chatPath,Hr as collectAsrTranscriptionItems,hl as computeDirContentHash,yu as computeSkillStatuses,on as connectBailianMcpWithFallback,Yr as createBailianControlUser,ro as createDeployment,ya as createFineTune,Gr as createInstrumentedFetch,as as createTrackingEvent,jo as createVocabulary,Go as credentialFlagDefs,fo as defaultDeployPlan,Ko as defineCommand,vt as deleteConfigProfile,mi as deleteDataset,oo as deleteDeployment,Ca as deleteFineTune,Fo as deleteVocabulary,et as describeAuthState,du as detectBinaryPlatform,eu as detectInstallMethod,rl as detectInstalledAgents,ca as detectModality,ot as detectOutputFormat,El as downloadSkillAsset,un as effectiveConsoleGatewayConfig,Qc as emptySkillLock,nt as ensureConfigDir,no as estimateCptTokens,to as estimateSftDpoTokens,Ea as exportCheckpoint,Vr as extractAsrFlashText,ml as extractTarBr,gu as extractZipEntryToFile,dl as fanOutSkillToAgents,Pa as fetchModelCapability,ii as fetchModelDetail,ri as fetchModelGroups,ei as fetchModelList,ti as fetchModelListAll,si as fetchPredictConfig,Cl as fetchSkillsIndex,eo as fetchTrainingModelPrice,Do as findDeploymentEntry,ni as findModelByName,_s as flushTelemetry,at as formatErrorJson,va as formatIssue,it as formatJson,st as formatOutput,rt as formatText,vn as generateCLIAccessToken,Yo as generateFilename,nl as getAgentTargets,cu as getCliCdnBase,I as getConfigDir,L as getConfigPath,tt as getCredentialsPath,pi as getDataset,ao as getDeployment,xa as getFineTune,wa as getFineTuneLogs,tu as getInstallMethod,ui as getModelProfilePreset,js as getModels,Ya as getProfile,Zc as getSkillLockPath,Sl as getSkillRegistryBaseUrl,Q as getSkillsDir,nu as getUpdateInstallMethod,Tn as image2ImagePath,Dn as image2videoPath,Vt as imageFileToDataUri,Sn as imagePath,Cn as imageSyncPath,wn as imageText2ImagePath,Lr as inferAudioFormatHint,Pl as installSkill,Nl as installSkillFromBuffer,Ll as installSkillWithFanout,He as isApiKeyCapability,Zl as isCompiledBinary,wr as isLegacyImage2ImageModel,Cr as isLegacyText2ImageModel,Wt as isLocalFile,pl as isSafeEntryName,Ol as isSafeSkillName,Dc as isSemanticAvailable,rn as isStreamableHttpUnsupported,yr as isSyncMultimodalImageModel,Aa as isTrainingTypeCli,an as isUrlOverrideSseFallbackCandidate,Tr as isWanxFunctionImageEditModel,Un as knowledgeChatEndpoint,Vn as knowledgeRetrievePath,Hn as knowledgeSearchEndpoint,ul as linkSkillToAgents,Xr as listBailianControlWorkspaces,Ta as listCheckpoints,fi as listDatasets,so as listDeployableModels,io as listDeployments,ba as listFineTunes,Eo as listIndependentDeployedModels,vu as listSkillDirsOnDisk,_a as listSupportedFormats,Na as listSupportedTrainingTypes,Xa as listTrainingTypes,Mo as listVocabularies,vs as localSink,Ct as makeAuthStore,ci as makeConfigStore,Ae as mapApiError,wt as maskToken,Kl as maybeSyncWikiData,Wn as mcpWebSearchPath,Mn as memoryAddPath,Pn as memoryListPath,Fn as memoryNodePath,Nn as memorySearchPath,Ma as modelSupportsTrainingType,kn as modelsLimitsPath,An as modelsPermissionsPath,Ue as normalizeApiKeyCapabilities,ut as normalizeConfigName,je as normalizeModelBaseUrl,ts as parseBooleanValue,Ge as parseConfigFile,yi as parseDatasetSchemaFlag,Lo as parseInstantVocabulary,ns as parseOptionalBooleanValue,Yt as parseSSE,_u as parseSkillNames,Ro as parseVocabularyEntries,bo as pickPlanStrategy,ha as pickValidator,Ia as preflightBatchSizeGate,zn as profileSchemaPath,No as queryVocabulary,ar as ragEndpoint,Xc as rankModels,B as readConfigFile,mt as readConfigProfiles,$c as readSkillLock,$o as readTextFromPathOrStdin,dc as recallCandidates,Uc as recallSemantic,Ht as redactDataUri,yn as refreshAccessToken,ga as registerValidator,uu as releaseAssetUrl,ys as remoteSink,Fl as removeSkillDir,kt as request,jt as requestJson,Zr as resetBailianControlPolicies4Agent,Je as resolveApiKey,Ir as resolveAsrApi,Tl as resolveAssetFileName,rs as resolveBooleanFlag,Ye as resolveConsole,Gt as resolveFileUrl,kr as resolveImageEditApi,Or as resolveImageGenerateApi,Er as resolveImageSizeProfile,qe as resolveModelBaseUrl,Ke as resolveModelBaseUrlState,Xe as resolveOpenApi,Zo as resolveOutputDir,Dr as resolvePromptExtendDefault,is as resolveWatermark,xn as responsesPath,es as runWithConcurrency,cr as sandboxApiPath,sr as sandboxBaseUrl,lr as sandboxEndpoint,fr as sandboxInstanceActionPath,dr as sandboxInstancePath,mr as sandboxTemplateBuildStatusPath,pr as sandboxTemplatePath,Dl as sanitizeSkillName,co as scaleDeployment,yt as selectApiKeyResolutionSources,Nt as signAcsRequest,Dt as sourceConfig,Ln as speechRecognizePath,In as speechSynthesizePath,Rn as speechVocabularyPath,wo as startModelService,To as stopModelService,Qo as stripUndefined,On as taskPath,Cs as trackCommandExecution,H as trackingHeaders,ja as trainingTypeMethodVariant,fl as unlinkSkillFromAgents,W as unwrapResponse,lo as updateDeployment,Po as updateVocabulary,di as uploadDataset,Ut as uploadFile,tl as upsertSkillLockEntry,Bn as userProfilePath,gt as validateConfigProfileActivation,K as validateDataset,jl as validateSkillDir,En as videoGeneratePath,V as writeConfigFile,ru as writeInstallMethodSync,el as writeSkillLock};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.22.0",
3
+ "version": "1.24.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": {