bailian-cli-core 1.17.1 → 1.18.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 +35 -8
- package/dist/index.mjs +18 -18
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -286,7 +286,7 @@ interface DashScopeVideoRequest {
|
|
|
286
286
|
first_frame_url?: string;
|
|
287
287
|
last_frame_url?: string;
|
|
288
288
|
media?: Array<{
|
|
289
|
-
type: "image" | "video" | "first_frame" | "last_frame" | "driving_audio" | "first_clip";
|
|
289
|
+
type: "image" | "video" | "first_frame" | "last_frame" | "driving_audio" | "first_clip" | "file";
|
|
290
290
|
url: string;
|
|
291
291
|
}>;
|
|
292
292
|
};
|
|
@@ -304,7 +304,7 @@ interface DashScopeVideoRefRequest {
|
|
|
304
304
|
input: {
|
|
305
305
|
prompt: string;
|
|
306
306
|
media: Array<{
|
|
307
|
-
type: "reference_image" | "reference_video";
|
|
307
|
+
type: "reference_image" | "reference_video" | "reference_audio";
|
|
308
308
|
url: string;
|
|
309
309
|
reference_voice?: string;
|
|
310
310
|
}>;
|
|
@@ -1065,14 +1065,24 @@ interface ConfigFile {
|
|
|
1065
1065
|
default_reference_to_video_model?: string;
|
|
1066
1066
|
default_image_model?: string;
|
|
1067
1067
|
default_speech_model?: string;
|
|
1068
|
+
default_speech_recognition_model?: string;
|
|
1068
1069
|
default_omni_model?: string;
|
|
1070
|
+
/** Leaf API-key capabilities this named Profile endpoint can serve. */
|
|
1071
|
+
api_key_capabilities?: string[];
|
|
1069
1072
|
workspace_id?: string;
|
|
1070
1073
|
console_site?: "domestic" | "international";
|
|
1071
1074
|
console_region?: string;
|
|
1072
1075
|
console_switch_agent?: number;
|
|
1073
1076
|
telemetry?: boolean;
|
|
1074
1077
|
}
|
|
1075
|
-
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_omni_model", "workspace_id", "console_site", "console_region", "console_switch_agent", "telemetry"];
|
|
1078
|
+
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"];
|
|
1079
|
+
declare const API_KEY_CAPABILITY_PATTERN: RegExp;
|
|
1080
|
+
declare function isApiKeyCapability(value: string): boolean;
|
|
1081
|
+
/**
|
|
1082
|
+
* Normalize a persisted capability allowlist. Absence keeps the policy disabled;
|
|
1083
|
+
* a present malformed value fails closed to an empty allowlist.
|
|
1084
|
+
*/
|
|
1085
|
+
declare function normalizeApiKeyCapabilities(value: unknown): string[] | undefined;
|
|
1076
1086
|
declare function parseConfigFile(raw: unknown): ConfigFile;
|
|
1077
1087
|
/** 静态产品身份,createCli 注入一次(bl/rag 各异,故注入而非模块常量)。 */
|
|
1078
1088
|
interface Identity {
|
|
@@ -1107,6 +1117,7 @@ interface Settings {
|
|
|
1107
1117
|
defaultReferenceToVideoModel?: string;
|
|
1108
1118
|
defaultImageModel?: string;
|
|
1109
1119
|
defaultSpeechModel?: string;
|
|
1120
|
+
defaultSpeechRecognitionModel?: string;
|
|
1110
1121
|
defaultOmniModel?: string;
|
|
1111
1122
|
workspaceId?: string;
|
|
1112
1123
|
consoleRegion?: string;
|
|
@@ -1173,7 +1184,7 @@ interface AuthState {
|
|
|
1173
1184
|
//#endregion
|
|
1174
1185
|
//#region src/auth/store.d.ts
|
|
1175
1186
|
/** 登录允许落盘的键:凭证本体 + 登录回调携带的连接/作用域字段。 */
|
|
1176
|
-
type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_key_id" | "access_key_secret" | "security_token" | "base_url" | "console_site" | "console_region" | "console_switch_agent" | "workspace_id" | "default_text_model" | "default_video_model" | "default_image_to_video_model" | "default_reference_to_video_model" | "default_image_model">;
|
|
1187
|
+
type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_key_id" | "access_key_secret" | "security_token" | "base_url" | "console_site" | "console_region" | "console_switch_agent" | "workspace_id" | "default_text_model" | "default_video_model" | "default_image_to_video_model" | "default_reference_to_video_model" | "default_image_model" | "default_speech_model" | "default_speech_recognition_model" | "api_key_capabilities">;
|
|
1177
1188
|
/**
|
|
1178
1189
|
* auth 命令族的凭证能力面(lint 限定 commands/auth/** 使用)。
|
|
1179
1190
|
* 登录产生的全部落盘走 login,不放宽 configStore 的边界。
|
|
@@ -1181,12 +1192,13 @@ type AuthPersistPatch = Pick<ConfigFile, "api_key" | "access_token" | "access_ke
|
|
|
1181
1192
|
interface AuthStore {
|
|
1182
1193
|
/** 各域"将会解析出"的凭证快照(auth status 用)。 */
|
|
1183
1194
|
describe(): AuthState;
|
|
1184
|
-
/**
|
|
1195
|
+
/** 磁盘上当前是否存有各域凭证,以及 model baseUrl/capability 配置(只看 file,不含 flag/env 源)。 */
|
|
1185
1196
|
stored(): {
|
|
1186
1197
|
apiKey: boolean;
|
|
1187
1198
|
console: boolean;
|
|
1188
1199
|
openapi: boolean;
|
|
1189
1200
|
baseUrl?: string;
|
|
1201
|
+
apiKeyCapabilities?: string[];
|
|
1190
1202
|
};
|
|
1191
1203
|
/** model 域 baseUrl 链(flag > env > config file > fallback)。 */
|
|
1192
1204
|
resolveBaseUrl(fallback?: string): string;
|
|
@@ -1372,8 +1384,9 @@ declare class Client {
|
|
|
1372
1384
|
* Export the model-domain credential for delegation to an embedded SDK that
|
|
1373
1385
|
* owns its own transport (e.g. @openagentpack/sdk). Deliberate escape hatch:
|
|
1374
1386
|
* regular commands keep calling {@link request}/{@link requestJson} and never
|
|
1375
|
-
* handle tokens
|
|
1376
|
-
*
|
|
1387
|
+
* handle tokens; only trusted internal adapters such as managed-agent/_engine
|
|
1388
|
+
* and the Command Pack host use this export. Undefined when no credential
|
|
1389
|
+
* resolved (authStage tolerates that only under dry-run).
|
|
1377
1390
|
*/
|
|
1378
1391
|
exportApiCredential(): ApiKeyCredential | undefined;
|
|
1379
1392
|
/** Full URL for a model-domain {@link path}; build request/display URLs only through this. */
|
|
@@ -1742,6 +1755,17 @@ interface ResolutionSources {
|
|
|
1742
1755
|
/** 实际 config.json 路径(不受 configName 影响,一直是同一个文件)。 */
|
|
1743
1756
|
configPath?: string;
|
|
1744
1757
|
}
|
|
1758
|
+
interface ApiKeyResolutionSourceSelection {
|
|
1759
|
+
sources: ResolutionSources;
|
|
1760
|
+
/** Named Profile whose file-backed API credential was replaced by default. */
|
|
1761
|
+
fallbackFrom?: string;
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Select the file-backed API-key source for a command capability. Only a
|
|
1765
|
+
* persisted Profile capability list enables fallback. An explicit flag or
|
|
1766
|
+
* environment API connection override bypasses it entirely.
|
|
1767
|
+
*/
|
|
1768
|
+
declare function selectApiKeyResolutionSources(sources: ResolutionSources, capability: string): ApiKeyResolutionSourceSelection;
|
|
1745
1769
|
declare function buildSources(flags: Partial<SourceFlags>): ResolutionSources;
|
|
1746
1770
|
/**
|
|
1747
1771
|
* 纯解析 sources → Settings(命令唯一会读的配置面)。不含身份、baseUrl、鉴权。
|
|
@@ -2204,6 +2228,9 @@ interface ModelProfilePreset {
|
|
|
2204
2228
|
defaultImageToVideoModel: string;
|
|
2205
2229
|
defaultReferenceToVideoModel: string;
|
|
2206
2230
|
defaultImageModel: string;
|
|
2231
|
+
defaultSpeechModel: string;
|
|
2232
|
+
defaultSpeechRecognitionModel: string;
|
|
2233
|
+
apiKeyCapabilities: readonly string[];
|
|
2207
2234
|
}
|
|
2208
2235
|
/** Defaults materialized when logging into a well-known model profile. */
|
|
2209
2236
|
declare function getModelProfilePreset(configName?: string): ModelProfilePreset | undefined;
|
|
@@ -4179,4 +4206,4 @@ declare function installSkillWithFanout(name: string, entry: SkillIndexEntry, ag
|
|
|
4179
4206
|
declare function listSkillDirsOnDisk(): string[];
|
|
4180
4207
|
declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[];
|
|
4181
4208
|
//#endregion
|
|
4182
|
-
export { ASYNC_FLAG, AcsQueryParams, AcsSignConfig, AgentTarget, AigcConfig, AnyCommand, type ApiErrorBody, ApiKeyCredential, 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, 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, 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, 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, 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 };
|
|
4209
|
+
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, 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 };
|
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 j,isAbsolute as le,join as M,resolve as N,sep as ue}from"node:path";import{homedir as de}from"node:os";import{createHash as fe}from"node:crypto";import{Readable as pe}from"node:stream";import{pipeline as me}from"node:stream/promises";import{createBrotliDecompress as he}from"node:zlib";import ge from"tar-stream";import{mkdir as _e}from"node:fs/promises";var ve=Object.create,ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty,we=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Te=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ce.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Ee=(e,t,n)=>(n=e==null?{}:ve(Se(e)),Te(t||!e||!e.__esModule?ye(n,`default`,{value:e,enumerable:!0}):n,e)),De=e(import.meta.url);const P={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var F=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=P.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}:{}}}}},Oe=class extends F{constructor(e,t){super(e,P.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 F(r,P.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}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 F(`Invalid model base URL "${e}".`,P.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`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_omni_model`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],ze=new Set([`text`,`json`]),Be=new Set([`domestic`,`international`]);function Ve(e){try{return je(e)}catch{return}}function He(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=Ve(t.base_url);e&&(n.base_url=e)}return 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.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&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 Ue(e,t=Ne.cn){return je(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function We(e){let t=Ue(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 F(`No API key found.`,P.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Ge(e){let t=e.file.access_token?.trim();if(!t)throw new F(`No console access token found.`,P.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 Ke(e){let t=qe(`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=qe(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Je(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Je(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=qe(`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 F(`No OpenAPI AK/SK credentials found.`,P.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 qe(e,t,n,r,i){if(!r)return;let a=Je(t),o=Je(n);if(!a||!o)throw new F(`Incomplete OpenAPI AK/SK credentials found.`,P.AUTH,Ye(e));return{accessKeyId:a,accessKeySecret:o,securityToken:Je(i),source:e}}function Je(e){return e?.trim()||void 0}function Ye(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 Xe(e){let t={};try{t.apiKey=We(e)}catch{}try{t.console=Ge(e)}catch{}try{t.openapi=Ke(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 Ze(){return g(I(),`credentials.json`)}async function Qe(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function $e(e){return v(e).replace(/\n$/,``)}function et(e){return JSON.stringify(e,null,2)}function tt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function nt(e){return e===`json`||e===`text`?e:`text`}function rt(e,t){switch(t){case`json`:return et(e);case`text`:return $e(e)}}const it=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,at=`active_config`;function ot(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function st(e){if(!(e===void 0||e===``||e===`default`)){if(typeof e!=`string`||!it.test(e))throw new F(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,P.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(Re.includes(e)||e===at)throw new F(`Invalid config name "${e}". It conflicts with a config key.`,P.USAGE);return e}}function R(){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 ct(e,t){let n=st(e[at]);if(n&&t&&!ot(e[n]))throw new F(`Active config "${n}" does not exist.`,P.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function lt(e,t){if(!t)return e;let n=e[t];return ot(n)?n:{}}function z(e){return He(lt(R(),e))}async function B(e,t,n={}){let r=R();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[at]=t??`default`),await ut(r)}async function ut(e){await Qe();let t=L(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
|
|
2
|
-
`,{mode:384}),s(n,t)}function
|
|
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 j,isAbsolute as le,join as M,resolve as N,sep as ue}from"node:path";import{homedir as de}from"node:os";import{createHash as fe}from"node:crypto";import{Readable as pe}from"node:stream";import{pipeline as me}from"node:stream/promises";import{createBrotliDecompress as he}from"node:zlib";import ge from"tar-stream";import{mkdir as _e}from"node:fs/promises";var ve=Object.create,ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty,we=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Te=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ce.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Ee=(e,t,n)=>(n=e==null?{}:ve(Se(e)),Te(t||!e||!e.__esModule?ye(n,`default`,{value:e,enumerable:!0}):n,e)),De=e(import.meta.url);const P={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var F=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=P.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}:{}}}}},Oe=class extends F{constructor(e,t){super(e,P.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 F(r,P.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}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 F(`Invalid model base URL "${e}".`,P.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`,`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.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){return je(e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||t)}function qe(e){let t=Ke(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 F(`No API key found.`,P.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Je(e){let t=e.file.access_token?.trim();if(!t)throw new F(`No console access token found.`,P.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 Ye(e){let t=Xe(`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=Xe(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Ze(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Ze(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=Xe(`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 F(`No OpenAPI AK/SK credentials found.`,P.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 Xe(e,t,n,r,i){if(!r)return;let a=Ze(t),o=Ze(n);if(!a||!o)throw new F(`Incomplete OpenAPI AK/SK credentials found.`,P.AUTH,Qe(e));return{accessKeyId:a,accessKeySecret:o,securityToken:Ze(i),source:e}}function Ze(e){return e?.trim()||void 0}function Qe(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 $e(e){let t={};try{t.apiKey=qe(e)}catch{}try{t.console=Je(e)}catch{}try{t.openapi=Ye(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 et(){return g(I(),`credentials.json`)}async function tt(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function nt(e){return v(e).replace(/\n$/,``)}function rt(e){return JSON.stringify(e,null,2)}function it(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function at(e){return e===`json`||e===`text`?e:`text`}function ot(e,t){switch(t){case`json`:return rt(e);case`text`:return nt(e)}}const st=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,ct=`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`||!st.test(e))throw new F(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,P.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(Re.includes(e)||e===ct)throw new F(`Invalid config name "${e}". It conflicts with a config key.`,P.USAGE);return e}}function R(){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[ct]);if(n&&t&&!lt(e[n]))throw new F(`Active config "${n}" does not exist.`,P.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 z(e){return Ge(ft(R(),e))}async function B(e,t,n={}){let r=R();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[ct]=t??`default`),await pt(r)}async function pt(e){await tt();let t=L(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
|
|
2
|
+
`,{mode:384}),s(n,t)}function mt(){let e=R(),t={};for(let[n,r]of Object.entries(e))Re.includes(n)||n===ct||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 F(`Config "${n}" does not exist.`,P.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function gt(e){return ht(R(),e)}async function _t(e){let t=R(),n=ht(t,e);return t[ct]=n,await pt(t),n}async function vt(e){let t=ut(e);if(!t)throw new F(`Cannot delete the default profile.`,P.USAGE);let n=R();return lt(n[t])?(delete n[t],dt(n,!1)===t&&(n[ct]=`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:z(),configName:void 0},fallbackFrom:e.configName}}function bt(e){let t=R(),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 F(`Timeout must be a positive finite number.`,P.USAGE);return{configPath:e.configPath??L(),configName:e.configName,output:at(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 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:()=>$e({...e,file:z(t)}),stored(){let e=z(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=>Ke(e,t),async login(e){let r=z(t);for(let[t,n]of Object.entries(e))n!==void 0&&(r[t]=t===`base_url`?je(String(n)):n);await B(r,t,{activate:n})},async logout(e){let n=z(t),r=St[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await B(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 V(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}`,...V(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 F(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,P.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${
|
|
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`,...V(n)},signal:a.signal}).finally(a.cleanup);if(!o.ok){let e=await o.text().catch(()=>``);throw new F(`Failed to get upload policy (HTTP ${o.status}): ${e}`,P.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 F(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,P.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 F(`File not found: ${e}`,P.USAGE);if(!l(e).isFile())throw new F(`Not a file: ${e}`,P.USAGE);let t=h(e).toLowerCase(),n=Bt[t];if(!n)throw new F(`Unsupported image format "${t||`unknown`}".`,P.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 F(`File not found: ${r}`,P.USAGE);if(!l(r).isFile())throw new F(`Not a file: ${r}`,P.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
|
|
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 F(`SSE event exceeded the maximum buffer size.`,P.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=Wt(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new F(`SSE stream exceeded the maximum buffer size.`,P.GENERAL);let{lines:s,rest:c}=Ut(r);r=c;for(let t of s){let n=Wt(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Wt(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{t.releaseLock()}}function Kt(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 F(`This command needs a model-domain API key.`,P.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 F(`MCP SSE session closed.`,P.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}`,...V(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 F(`MCP SSE session closed.`,P.GENERAL):t?new F(`MCP SSE timed out waiting for response headers.`,P.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 F(`MCP SSE session closed.`,P.GENERAL):t?new F(`MCP SSE timed out reading error response body.`,P.TIMEOUT):new F(e,P.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new F(e,P.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof F?e:new F(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,P.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Yt(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 Gt(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Jt(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=Kt(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 F(`MCP SSE stream ended before endpoint event.`,P.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new F(`MCP SSE stream ended unexpectedly.`,P.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new F(`MCP SSE stream ended unexpectedly.`,P.GENERAL);let n=this.nextId++,r=Kt(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=Yt(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new F(`MCP SSE stream ended unexpectedly.`,P.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new F(`MCP error (${e.error.code}): ${e.error.message}`,P.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 F(`MCP SSE stream ended unexpectedly.`,P.GENERAL);if(!this.messageUrl)throw new F(`MCP SSE message endpoint is not ready.`,P.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...V(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=Xt(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 F(`MCP SSE session closed.`,P.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 F(`MCP SSE session closed.`,P.GENERAL):n.timedOut?new F(`MCP SSE timed out reading error response body.`,P.TIMEOUT):new F(e,P.GENERAL,void 0,{cause:t})}throw new F(e,P.GENERAL)}}finally{n.cleanup()}}};function Jt(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new F(`MCP SSE endpoint is not a valid URL: ${t}`,P.GENERAL)}if(n.origin!==r.origin)throw new F(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,P.GENERAL);return n.toString()}function Yt(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new F(t,P.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Xt(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 Zt(e){return`/api/v1/mcps/${e}/mcp`}function Qt(e){return`/api/v1/mcps/${e}/sse`}function $t(e){return e instanceof F?/^MCP request failed:\s*405\b/i.test(e.message):!1}function en(e){return e instanceof F?/^MCP request failed:\s*(405|404)\b/i.test(e.message):!1}async function tn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new nn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!en(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 nn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!$t(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 nn=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 F(`This command needs a model-domain API key.`,P.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 F(`MCP error (${a.error.code}): ${a.error.message}`,P.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 Gt(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 F(`MCP SSE response stream ended without a matching JSON-RPC response.`,P.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}`,...V(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 F(e,P.GENERAL)}return r}};const rn={"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 an(e,t){return rn[e]?.[t]??rn[`cn-beijing`][t]}function on(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 sn(e){let t=on(e);return(n,r)=>ln({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function cn(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 ln(e,t,{api:n,data:r},i){let a=an(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=cn(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 F(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,P.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 F(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?P.AUTH:P.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var un=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new F(`This command needs a model-domain API key.`,P.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new F(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,P.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 Tt(this.http,this.toOpts(e))}requestJson(e){return Dt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Bt(e)?Vt(e,this.requireApi().token,t,{...n,identity:this.deps.identity}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Bt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Lt(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){if(this.deps.settings.configName===`token-plan`)return!0;try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new nn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),tn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Zt(e)),sseUrl:this.url(Qt(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new F(`This command needs a console access token.`,P.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await ln(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof F)||e.exitCode!==P.AUTH||!e.message.includes(`not logged in`))throw e;let t=await hn({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await ln({...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?Ot(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=kt({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: ${bt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${bt(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,...V(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 F(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,P.GENERAL)}if(!s.ok||l.Success===!1)throw new F(`${l.Code||s.status} - ${l.Message||s.statusText}`,P.GENERAL);return l}};const dn={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function fn(e){for(let[t,n]of Object.entries(Ne))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function pn(e){return dn[fn(e)]??dn.cn}async function mn(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new un({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=pn(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function hn(e){let t=e.settings.configName,n=z(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 mn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=z(t);return o.access_token=a,await B(o,t),a}function gn(){return`/compatible-mode/v1/chat/completions`}function _n(){return`/compatible-mode/v1/responses`}function vn(){return`/api/v1/services/aigc/image-generation/generation`}function yn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function bn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function xn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function Sn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Cn(){return`/api/v1/services/aigc/image2video/video-synthesis`}function wn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Tn(){return`/api/v1/models/limits`}function En(){return`/api/v1/models/permissions`}function Dn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function On(){return`/api/v2/apps/memory/add`}function kn(){return`/api/v2/apps/memory/memory_nodes/search`}function An(){return`/api/v2/apps/memory/memory_nodes`}function jn(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Mn(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Nn(){return`/api/v1/services/audio/asr/transcription`}function Pn(){return`/api/v2/apps/memory/profile_schemas`}function Fn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function In(){return`/api/v1/indices/rag/index/retrieve`}function Ln(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Rn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function zn(){return`/api/v1/mcps/WebSearch/mcp`}function Bn(){return`/compatible-mode/v1/files`}function Vn(){return`/api/v1/files`}function Hn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Un(){return`/api/v1/fine-tunes`}function Wn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Gn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Kn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function qn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Jn(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Yn(){return`/api/v1/deployments`}function Xn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Zn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function Qn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function $n(){return`/api/v1/deployments/models`}function er(e,t){return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}const tr={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`},nr=[`qwen-image`,`wan2.7-image`,`z-image`],rr=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function ir(e,t){return t.some(t=>e.startsWith(t))}function ar(e){return ir(e,nr)||e.startsWith(`wan2.6-image`)}function or(e){return ir(e,nr)}function sr(e){return ir(e,rr)}function cr(e){return/^wanx-v1(?:-|$)/i.test(e)}function lr(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||or(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||cr(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function ur(e){return/wan2\.5-i2i/i.test(e)}function dr(e){return/imageedit/i.test(e)}function fr(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`:cr(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:lr(e)?`wan-legacy`:`wan26`}function pr(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 H(e,t){return{...e,sizeProfile:fr(t),promptExtendDefault:pr(t)}}function mr(e){return or(e)?H({kind:`sync-multimodal`,path:yn(),useSync:!0,inputStyle:`messages`},e):lr(e)?H({kind:`async-text2image`,path:bn(),useSync:!1,inputStyle:`prompt`},e):H({kind:`async-image-generation`,path:vn(),useSync:!1,inputStyle:`messages`},e)}function hr(e){return sr(e)?H({kind:`sync-multimodal`,path:yn(),useSync:!0,inputStyle:`messages`},e):dr(e)?H({kind:`async-image2image`,path:xn(),useSync:!1,inputStyle:`function-base-image`},e):ur(e)?H({kind:`async-image2image`,path:xn(),useSync:!1,inputStyle:`prompt-images`},e):H({kind:`async-image-generation`,path:vn(),useSync:!1,inputStyle:`messages`},e)}function gr(e){return/realtime|streaming/i.test(e)}function _r(e){return/filetrans/i.test(e)}function vr(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const yr=[`fun-asr-flash`,`qwen-audio`];function br(e){return gr(e)||_r(e)?!1:!!(e.startsWith(yr[0])||e.startsWith(yr[1])&&/asr-flash/i.test(e))}function xr(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||_r(e)||gr(e)||br(e))}function Sr(e){if(gr(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(_r(e)){let t=vr(e);return{kind:`async-filetrans`,path:Nn(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return br(e)?{kind:`sync-flash`,path:yn(),useSync:!0,flashFamily:`input-audio`}:xr(e)?{kind:`sync-flash`,path:yn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Nn(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Cr(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 wr(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Tr(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,flashFamily:a}=e;if(a===`input-audio`){let e={format:Cr(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 Er(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 Dr(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 Or(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function kr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Ar(e){return async(t,n={})=>{let r=kr(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}`),Or(r))for(let[t,n]of Object.entries(V(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: ${bt(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 jr=`2024-08-16`;function Mr(e){return`bailiancontrol.${e}.aliyuncs.com`}function Nr(e){return new un({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Pr(e){return Nr(e).openApiJson({host:Mr(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:jr,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Fr(e){return Nr(e).openApiJson({host:Mr(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:jr,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ir(e){return Nr(e).openApiJson({host:Mr(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:jr,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const Lr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Rr=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function U(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 zr(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=U(await e(Lr,{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 Br(e,t={}){let n=t.pageSize??50,r=await zr(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 zr(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Vr(e,t){return(await zr(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Hr(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=U(await e(Lr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Ur(e,t){return(U(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 Wr=[`name`,`key`,`default`,`tip`,`range`];function Gr(e){return e.map(e=>{let t={};for(let n of Wr)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Kr(e,t){let n=U(await e(Rr,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Gr(e):null}catch{return null}return Array.isArray(n)?Gr(n):null}function qr(e){return{read:()=>z(e),async write(t){let n=z(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 B(n,e)},async unset(t){let n=z(e);for(let e of t)delete n[e];await B(n,e)},profiles:()=>dt(),activate:e=>mt(e),validateActivation:e=>pt(e),get path(){return L()}}}const Jr={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function Yr(e){return e?Jr[e]:void 0}async function Xr(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:Bn(),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 F(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,P.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new F(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,P.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 Zr(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=Vn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Qr(e,t,n){return e.requestJson({path:Hn(t),method:`GET`,signal:n})}async function $r(e,t,n){let r=await e.request({path:Hn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ei=200*1024*1024,ti=300*1024*1024,ni=2*1024*1024*1024;function ri(e,t=ei){if(!i(e))throw new F(`File not found: ${e}`,P.USAGE);let n=l(e);if(!n.isFile())throw new F(`Not a regular file: ${e}`,P.USAGE);if(n.size===0)throw new F(`File is empty: ${e}`,P.USAGE);if(n.size>t)throw new F(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,P.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function W(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ii(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 F(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,P.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function ai(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 oi=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(W(`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(W(`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(W(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function li(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(W(`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(W(`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(W(`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(W(`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(W(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(W(`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(W(`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(W(`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 ui(e,t,n){let r=[];if(!Array.isArray(e))return r.push(W(`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(W(`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(W(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(W(`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(W(`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(W(`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(W(`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 di(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(W(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!oi.has(a))&&r.push(W(`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(W(`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(...li(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(W(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...ui(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(W(`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(W(`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 fi(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(W(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(W(`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(...di(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(W(`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(W(`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(W(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(W(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(W(`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(W(`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;pi(a)&&n.push(W(`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(W(`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(W(`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(W(`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 pi(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 mi={name:`chatml`,detect:()=>!0,inspect:fi};function hi(e,t){let n=[];if(!(`text`in e))return n.push(W(`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(W(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(W(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const gi={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:hi};function _i(e,t){let n=fi(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(W(`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(W(`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(W(`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(W(`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(W(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(W(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...di(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(W(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...di(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(W(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const vi={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:_i};function yi(e,t){let n=[];if(!(`wav_fn`in e))n.push(W(`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(W(`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(W(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(W(`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(W(`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(W(`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(W(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(W(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const bi={name:`tts`,detect:e=>`wav_fn`in e,inspect:yi},xi=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Si(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Ci(e){return/^[\x20-\x7E]+$/.test(e)}function wi(e,t){let n=[];if(!(`prompt`in e))n.push(W(`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(W(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(W(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(W(`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(W(`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(W(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Si(r);xi.has(e)||n.push(W(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...xi].join(`, `)}.`,{line:t,path:`img_path`})),Ci(r)||n.push(W(`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(W(`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(W(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Si(r);xi.has(e)||n.push(W(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...xi].join(`, `)}.`,{line:t,path:`input_img`})),Ci(r)||n.push(W(`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 Ti={name:`image`,detect:e=>`img_path`in e,inspect:wi},Ei=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Di=new Set([`.mp4`,`.mov`]);function Oi(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function ki(e){return/^[\x20-\x7E]+$/.test(e)}function Ai(e,t,n,r,i,a){if(!(n in t)){r&&e.push(W(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(W(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(W(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Oi(o);i.has(s)||e.push(W(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),ki(o)||e.push(W(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function ji(e,t){let n=[];if(!(`prompt`in e))n.push(W(`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(W(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(W(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Ai(n,e,`first_frame_path`,!0,Ei,t),Ai(n,e,`last_frame_path`,!1,Ei,t),Ai(n,e,`video_path`,!1,Di,t),n}const Mi=[bi,Ti,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:ji},vi,gi,mi];function Ni(e,t){return t===void 0?Mi.find(t=>t.detect(e))??mi:Mi.find(e=>e.name===t)||mi}async function Pi(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(W(`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 Fi(e,t,r,i,a){let o=r?null:new Set(ai(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(W(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Ii(n,u,i))}return{sampled:c,issues:s}}function Ii(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[W(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Ni(r,n).inspect(r,t)}const Li={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Pi(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[W(`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 Fi(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 Ri(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 zi(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 Bi=/^[a-zA-Z0-9_-]+$/;function Vi(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function Hi(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 Ui(e){let t=[],n=new Map;for(let r of e){if(r.endsWith(`/`)||Hi(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Vi(n),i=n.slice(e.length);e.length>0&&!Bi.test(e)&&t.length<10&&t.push(W(`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(W(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Vi(i);if(a.length>120&&t.length<10&&t.push(W(`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(W(`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(W(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Wi(e,t,n){let{entry:i,zipfile:a}=await Ri(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 Gi(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 Ki={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await zi(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[W(`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:[W(`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(W(`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(W(`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=Ui(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(W(`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(`/`)||Hi(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return xi.has(n)});e.length<25&&r.push(W(`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 Wi(e,_,y)}catch(t){return r.push(W(`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 Li.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Gi(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(W(`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 Ji(e);if(t===`.zip`)return Yi(e);throw new F(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,P.USAGE)}async function Ji(e){let t=await Zi(e);if(!t)throw new F(`JSONL file is empty or contains only blank lines: ${e}`,P.USAGE);let n=Xi(t);return n===`unknown`?`text`:n}async function Yi(e){let t=await Qi(e,`data.jsonl`);if(!t)throw new F(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,P.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Xi(t);if(n===`unknown`)throw new F(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,P.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Xi(e){let t;try{t=JSON.parse(e)}catch{throw new F(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,P.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new F(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,P.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 Zi(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 Qi(e,t){return Ri(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new F(`Failed to read "${t}" from ZIP: ${e?.message}`,P.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 $i=[Li,Ki];function ea(e){let t=h(e).toLowerCase(),n=$i.find(e=>e.extensions.includes(t));if(!n){let e=$i.flatMap(e=>e.extensions).join(`, `);throw new F(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,P.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function ta(e){$i.some(t=>t.format===e.format)||$i.push(e)}async function G(e,t={}){let{bytes:n}=ri(e,t.maxBytes??209715200),r=await ea(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function na(){return $i.map(e=>({format:e.format,extensions:[...e.extensions]}))}function ra(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 ia(e,t,n){return e.requestJson({path:Un(),method:`POST`,body:t,signal:n})}async function aa(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=Un(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function oa(e,t,n){return e.requestJson({path:Wn(t),method:`GET`,signal:n})}async function sa(e,t,n){return e.requestJson({path:Gn(t),method:`POST`,signal:n})}async function ca(e,t,n){return e.requestJson({path:Wn(t),method:`DELETE`,signal:n})}async function la(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=Kn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ua(e,t,n){return e.requestJson({path:qn(t),method:`GET`,signal:n})}async function da(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Jn(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const fa={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`}},pa=Object.keys(fa),ma=`sft-lora`;function ha(e){return e in fa}function ga(e){let{method:t,variant:n}=fa[e];return{method:t,variant:n}}function _a(e,t){if(!e)return!1;let{method:n,variant:r}=fa[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function va(e){return e?pa.filter(t=>_a(e,t)):[]}async function ya(e,t){return await Vr(sn(e),t)}const ba=`INSUFFICIENT_SAMPLES`;function xa(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ba,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 Sa(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 Ca(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return G(e,{...r,schema:n})},resolveHyperParameters(e,t){return Sa(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const wa=Ca(`sft`,`sft`,`chatml`),Ta={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},Ea={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},Da={...Ea,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Oa={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 ka(e){return e===`image`||e===`image-i2i`}function Aa(e){return e===`video`||e===`video-kf2v`}function ja(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Ma(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Na=[wa,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return G(e,{...n,schema:`tts`});if(ka(t))return G(e,{...n,schema:`image`,maxBytes:ni});if(Aa(t)){let r=await G(e,{...n,schema:`video`,maxBytes:ni});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(W(`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(W(`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 G(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Ta};if(ka(e)){let n={...e===`image-i2i`?Da:Ea};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Aa(e)){let e=t.model??t.baseModel,n={...Oa,batch_size:Ma(e)?1:4,max_pixels:Ma(e)?102400:ja(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 Sa(t)},shouldSkipGate(e,t){return!!((t===`audio`||ka(t)||Aa(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||ka(e)||Aa(e)}},Ca(`dpo`,`dpo_full`,`dpo`),Ca(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return G(e,{...n,schema:`cpt`,maxBytes:ti})},resolveHyperParameters(e,t){return Sa(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Pa(e){let t=Na.find(t=>t.clientTrainingType===e);if(!t){let t=Na.map(e=>e.clientTrainingType).join(`, `);throw new F(`Unknown training type "${e}".`,P.USAGE,`Supported training types: ${t}.`)}return t}function Fa(){return Na.map(e=>e.clientTrainingType)}const Ia=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,La=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,Ra=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function za(e,t){return U(await e.console(Ia,{query:{type:0,modelId:t}}))}async function Ba(e,t,n){return U(await e.console(La,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Va(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 U(await e.console(Ra,{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 Ha(e,t,n){return e.requestJson({path:Yn(),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);let r=Yn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Wa(e,t,n){return e.requestJson({path:Xn(t),method:`GET`,signal:n})}async function Ga(e,t,n){return e.requestJson({path:Xn(t),method:`DELETE`,signal:n})}async function Ka(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=$n(),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:Zn(t),method:`PUT`,body:n,signal:r})}async function Ja(e,t,n,r){return e.requestJson({path:Qn(t),method:`PUT`,body:n,signal:r})}const K={LORA:`lora`,PTU:`ptu`,MU:`mu`},Ya=K.LORA;function Xa(e){return e===`audio`?K.MU:Ya}const Za={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},Qa=Za.POST_PAY,$a={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},eo={name:K.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},to={name:K.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}}}},no={name:K.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||Qa,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new F(`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.`,P.USAGE);try{let a=await Ka(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===K.MU)?.templates??[];if(o.length===0)throw i();let s=t===Za.POST_PAY?$a.POST_PAID:$a.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 F?e:new F(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,P.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},ro={[K.LORA]:eo,[K.PTU]:to,[K.MU]:no};function io(e){let t=ro[e];if(!t)throw new F(`Unsupported plan "${e}". Supported plans: ${Object.keys(ro).join(`, `)}.`,P.USAGE);return t}const ao=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,oo=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,so=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function co(e,t){return U(await e.console(ao,{input:{modelServiceId:t}}))}async function lo(e,t){return U(await e.console(oo,{input:{modelServiceId:t}}))}async function uo(e){let t=[],n=1;for(;;){let r=U(await e.console(so,{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 fo(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const po={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":`显示版本信息`}}},mo={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},ho={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},go={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`}}},_o={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)`}}},vo={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 yo(e){return e.auth===`apiKey`?go:e.auth===`console`?_o:e.auth===`openapi`?vo:{}}function bo(e){return e}const xo=1;function So(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Co(e,t){return`${So(e||`image`,`image`)}_${So((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const wo=()=>g(f(),`bailian-output`);function To(e,t){let n=t?.flagDir||e.outputDir||wo(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Eo(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Do(e){return o(e===`-`?0:e,`utf-8`)}async function Oo(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 ko(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 F(`Invalid ${t} value "${String(e)}". Use true or false.`,P.USAGE)}function Ao(e,t=`boolean`){if(e!=null)return ko(e,t)}function jo(e,t,n=`boolean`){let r=Ao(e,n);return r===void 0?t:r}function Mo(e){return Ao(e,`watermark`)??!0}function No(e){let t={command:e.command,timestamp:new Date().toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform};return e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function Po(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Fo(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=Po(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let q;function Io(){return q||(process.env.NODE_ENV===`development`?(q=`dev`,q):process.env.BAILIAN_COMPILED===`1`?(q=`prod`,q):(q=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,q))}var Lo=we(((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=De(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=De(`dns`)},function(e,t){e.exports=De(`util`)},function(e,t){e.exports=De(`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`},j=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},M=new Map,N=new Map;M.set(`Baiduspider-render`,i),M.set(`Baiduspider+`,i),M.set(`Baiduspider-image+`,i),M.set(`360Spider`,a),M.set(`360Spider-Image`,a),M.set(`bingbot`,o),M.set(`Googlebot`,s),M.set(`YandexRenderResourcesBot`,c),M.set(`spider`,l),M.set(`Dataprovider.com`,u),M.set(`AhrefsBot`,d),M.set(`BitSightBot`,f),M.set(`oBot`,p),M.set(`Cincraw`,m),M.set(`DingTalkBot-LinkService`,h),M.set(`YisouSpider`,g),M.set(`Bytespider`,_),M.set(`ev-crawler`,v),M.set(`bitdiscovery`,y),M.set(`Spider`,b),M.set(`Ai2Bot-Dolma`,ee),M.set(`dianjing_ad_spider`,te),N.set(`Baiduspider-render`,ne),N.set(`Baiduspider+`,ne),N.set(`Baiduspider-image+`,ne),N.set(`360Spider`,x),N.set(`360Spider-Image`,x),N.set(`bingbot`,re),N.set(`Googlebot`,S),N.set(`YandexRenderResourcesBot`,ie),N.set(`spider`,ae),N.set(`Dataprovider.com`,C),N.set(`AhrefsBot`,w),N.set(`BitSightBot`,T),N.set(`oBot`,E),N.set(`Cincraw`,D),N.set(`DingTalkBot-LinkService`,oe),N.set(`YisouSpider`,O),N.set(`Bytespider`,k),N.set(`ev-crawler`,se),N.set(`bitdiscovery`,ce),N.set(`Spider`,A),N.set(`Ai2Bot-Dolma`,j),N.set(`dianjing_ad_spider`,le);let ue={productHandlerMap:M,commentHandlerMap:N,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ue),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 F(`SSE stream exceeded the maximum buffer size.`,P.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 F(`This command needs a model-domain API key.`,P.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 F(`MCP SSE session closed.`,P.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}`,...V(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 F(`MCP SSE session closed.`,P.GENERAL):t?new F(`MCP SSE timed out waiting for response headers.`,P.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 F(`MCP SSE session closed.`,P.GENERAL):t?new F(`MCP SSE timed out reading error response body.`,P.TIMEOUT):new F(e,P.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new F(e,P.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof F?e:new F(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,P.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 F(`MCP SSE stream ended before endpoint event.`,P.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new F(`MCP SSE stream ended unexpectedly.`,P.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new F(`MCP SSE stream ended unexpectedly.`,P.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 F(`MCP SSE stream ended unexpectedly.`,P.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new F(`MCP error (${e.error.code}): ${e.error.message}`,P.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 F(`MCP SSE stream ended unexpectedly.`,P.GENERAL);if(!this.messageUrl)throw new F(`MCP SSE message endpoint is not ready.`,P.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...V(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 F(`MCP SSE session closed.`,P.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 F(`MCP SSE session closed.`,P.GENERAL):n.timedOut?new F(`MCP SSE timed out reading error response body.`,P.TIMEOUT):new F(e,P.GENERAL,void 0,{cause:t})}throw new F(e,P.GENERAL)}}finally{n.cleanup()}}};function Qt(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new F(`MCP SSE endpoint is not a valid URL: ${t}`,P.GENERAL)}if(n.origin!==r.origin)throw new F(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,P.GENERAL);return n.toString()}function $t(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new F(t,P.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 F?/^MCP request failed:\s*405\b/i.test(e.message):!1}function an(e){return e instanceof F?/^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 F(`This command needs a model-domain API key.`,P.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 F(`MCP error (${a.error.code}): ${a.error.message}`,P.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 F(`MCP SSE response stream ended without a matching JSON-RPC response.`,P.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}`,...V(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 F(e,P.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 F(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,P.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 F(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?P.AUTH:P.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 F(`This command needs a model-domain API key.`,P.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new F(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,P.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 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 F(`This command needs a console access token.`,P.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 F)||e.exitCode!==P.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,...V(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 F(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,P.GENERAL)}if(!s.ok||l.Success===!1)throw new F(`${l.Code||s.status} - ${l.Message||s.statusText}`,P.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=z(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=z(t);return o.access_token=a,await B(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/v2/apps/memory/profile_schemas`}function zn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Bn(){return`/api/v1/indices/rag/index/retrieve`}function Vn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Hn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Un(){return`/api/v1/mcps/WebSearch/mcp`}function Wn(){return`/compatible-mode/v1/files`}function Gn(){return`/api/v1/files`}function Kn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function qn(){return`/api/v1/fine-tunes`}function Jn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Yn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Xn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Zn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Qn(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function $n(){return`/api/v1/deployments`}function er(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function tr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function nr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function rr(){return`/api/v1/deployments/models`}function ir(e,t){return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}const ar={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`},or=[`qwen-image`,`wan2.7-image`,`z-image`],sr=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function cr(e,t){return t.some(t=>e.startsWith(t))}function lr(e){return cr(e,or)||e.startsWith(`wan2.6-image`)}function ur(e){return cr(e,or)}function dr(e){return cr(e,sr)}function fr(e){return/^wanx-v1(?:-|$)/i.test(e)}function pr(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||ur(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||fr(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function mr(e){return/wan2\.5-i2i/i.test(e)}function hr(e){return/imageedit/i.test(e)}function gr(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`:fr(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:pr(e)?`wan-legacy`:`wan26`}function _r(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 H(e,t){return{...e,sizeProfile:gr(t),promptExtendDefault:_r(t)}}function vr(e){return ur(e)?H({kind:`sync-multimodal`,path:Cn(),useSync:!0,inputStyle:`messages`},e):pr(e)?H({kind:`async-text2image`,path:wn(),useSync:!1,inputStyle:`prompt`},e):H({kind:`async-image-generation`,path:Sn(),useSync:!1,inputStyle:`messages`},e)}function yr(e){return dr(e)?H({kind:`sync-multimodal`,path:Cn(),useSync:!0,inputStyle:`messages`},e):hr(e)?H({kind:`async-image2image`,path:Tn(),useSync:!1,inputStyle:`function-base-image`},e):mr(e)?H({kind:`async-image2image`,path:Tn(),useSync:!1,inputStyle:`prompt-images`},e):H({kind:`async-image-generation`,path:Sn(),useSync:!1,inputStyle:`messages`},e)}function br(e){return/realtime|streaming/i.test(e)}function xr(e){return/filetrans/i.test(e)}function Sr(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const Cr=[`fun-asr-flash`,`qwen-audio`];function wr(e){return br(e)||xr(e)?!1:!!(e.startsWith(Cr[0])||e.startsWith(Cr[1])&&/asr-flash/i.test(e))}function Tr(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||xr(e)||br(e)||wr(e))}function Er(e){if(br(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(xr(e)){let t=Sr(e);return{kind:`async-filetrans`,path:Ln(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return wr(e)?{kind:`sync-flash`,path:Cn(),useSync:!0,flashFamily:`input-audio`}:Tr(e)?{kind:`sync-flash`,path:Cn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Ln(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Dr(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 Or(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function kr(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,flashFamily:a}=e;if(a===`input-audio`){let e={format:Dr(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 Ar(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 jr(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 Mr(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function Nr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Pr(e){return async(t,n={})=>{let r=Nr(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}`),Mr(r))for(let[t,n]of Object.entries(V(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 Fr=`2024-08-16`;function Ir(e){return`bailiancontrol.${e}.aliyuncs.com`}function Lr(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 Rr(e){return Lr(e).openApiJson({host:Ir(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Fr,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function zr(e){return Lr(e).openApiJson({host:Ir(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Fr,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Br(e){return Lr(e).openApiJson({host:Ir(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Fr,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const Vr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Hr=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function U(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 Ur(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=U(await e(Vr,{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 Wr(e,t={}){let n=t.pageSize??50,r=await Ur(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 Ur(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Gr(e,t){return(await Ur(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Kr(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=U(await e(Vr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function qr(e,t){return(U(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 Jr=[`name`,`key`,`default`,`tip`,`range`];function Yr(e){return e.map(e=>{let t={};for(let n of Jr)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Xr(e,t){let n=U(await e(Hr,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Yr(e):null}catch{return null}return Array.isArray(n)?Yr(n):null}function Zr(e){return{read:()=>z(e),async write(t){let n=z(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 B(n,e)},async unset(t){let n=z(e);for(let e of t)delete n[e];await B(n,e)},profiles:()=>mt(),activate:e=>_t(e),validateActivation:e=>gt(e),get path(){return L()}}}const Qr={"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 $r(e){return e?Qr[e]:void 0}async function ei(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:Wn(),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 F(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,P.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new F(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,P.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 ti(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=Gn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ni(e,t,n){return e.requestJson({path:Kn(t),method:`GET`,signal:n})}async function ri(e,t,n){let r=await e.request({path:Kn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ii=200*1024*1024,ai=300*1024*1024,oi=2*1024*1024*1024;function si(e,t=ii){if(!i(e))throw new F(`File not found: ${e}`,P.USAGE);let n=l(e);if(!n.isFile())throw new F(`Not a regular file: ${e}`,P.USAGE);if(n.size===0)throw new F(`File is empty: ${e}`,P.USAGE);if(n.size>t)throw new F(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,P.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function W(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ci(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 F(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,P.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function li(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 ui=new Set([`system`,`user`,`assistant`,`tool`]),di=.1;function fi(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<di||a>10)&&i.push(W(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${di} 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(W(`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(W(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function pi(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(W(`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(W(`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(W(`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(W(`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(W(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(W(`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(W(`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(W(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...fi(s,Array.isArray(e),t,o))}}}return r}function mi(e,t,n){let r=[];if(!Array.isArray(e))return r.push(W(`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(W(`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(W(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(W(`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(W(`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(W(`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(W(`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 hi(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(W(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!ui.has(a))&&r.push(W(`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(W(`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(...pi(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(W(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...mi(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(W(`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(W(`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 gi(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(W(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(W(`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(...hi(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(W(`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(W(`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(W(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(W(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(W(`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(W(`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;_i(a)&&n.push(W(`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(W(`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(W(`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(W(`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 _i(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 vi={name:`chatml`,detect:()=>!0,inspect:gi};function yi(e,t){let n=[];if(!(`text`in e))return n.push(W(`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(W(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(W(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const bi={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:yi};function xi(e,t){let n=gi(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(W(`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(W(`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(W(`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(W(`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(W(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(W(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...hi(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(W(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...hi(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(W(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Si={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:xi};function Ci(e,t){let n=[];if(!(`wav_fn`in e))n.push(W(`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(W(`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(W(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(W(`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(W(`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(W(`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(W(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(W(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const wi={name:`tts`,detect:e=>`wav_fn`in e,inspect:Ci},Ti=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Ei(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Di(e){return/^[\x20-\x7E]+$/.test(e)}function Oi(e,t){let n=[];if(!(`prompt`in e))n.push(W(`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(W(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(W(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(W(`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(W(`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(W(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Ei(r);Ti.has(e)||n.push(W(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ti].join(`, `)}.`,{line:t,path:`img_path`})),Di(r)||n.push(W(`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(W(`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(W(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Ei(r);Ti.has(e)||n.push(W(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Ti].join(`, `)}.`,{line:t,path:`input_img`})),Di(r)||n.push(W(`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 ki={name:`image`,detect:e=>`img_path`in e,inspect:Oi},Ai=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),ji=new Set([`.mp4`,`.mov`]);function Mi(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Ni(e){return/^[\x20-\x7E]+$/.test(e)}function Pi(e,t,n,r,i,a){if(!(n in t)){r&&e.push(W(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(W(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(W(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Mi(o);i.has(s)||e.push(W(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Ni(o)||e.push(W(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Fi(e,t){let n=[];if(!(`prompt`in e))n.push(W(`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(W(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(W(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Pi(n,e,`first_frame_path`,!0,Ai,t),Pi(n,e,`last_frame_path`,!1,Ai,t),Pi(n,e,`video_path`,!1,ji,t),n}const Ii=[wi,ki,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Fi},Si,bi,vi];function Li(e,t){return t===void 0?Ii.find(t=>t.detect(e))??vi:Ii.find(e=>e.name===t)||vi}async function Ri(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(W(`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 zi(e,t,r,i,a){let o=r?null:new Set(li(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(W(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Bi(n,u,i))}return{sampled:c,issues:s}}function Bi(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[W(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Li(r,n).inspect(r,t)}const Vi={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Ri(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[W(`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 zi(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 Hi(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 Ui(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 Wi=/^[a-zA-Z0-9_-]+$/;function Gi(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function Ki(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 qi(e){let t=[],n=new Map;for(let r of e){if(r.endsWith(`/`)||Ki(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Gi(n),i=n.slice(e.length);e.length>0&&!Wi.test(e)&&t.length<10&&t.push(W(`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(W(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Gi(i);if(a.length>120&&t.length<10&&t.push(W(`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(W(`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(W(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Ji(e,t,n){let{entry:i,zipfile:a}=await Hi(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 Yi(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 Xi={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Ui(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[W(`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:[W(`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(W(`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(W(`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=qi(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(W(`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(`/`)||Ki(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Ti.has(n)});e.length<25&&r.push(W(`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 Ji(e,_,y)}catch(t){return r.push(W(`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 Vi.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Yi(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(W(`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 Zi(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Qi(e);if(t===`.zip`)return $i(e);throw new F(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,P.USAGE)}async function Qi(e){let t=await ta(e);if(!t)throw new F(`JSONL file is empty or contains only blank lines: ${e}`,P.USAGE);let n=ea(t);return n===`unknown`?`text`:n}async function $i(e){let t=await na(e,`data.jsonl`);if(!t)throw new F(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,P.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ea(t);if(n===`unknown`)throw new F(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,P.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ea(e){let t;try{t=JSON.parse(e)}catch{throw new F(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,P.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new F(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,P.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 ta(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 na(e,t){return Hi(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new F(`Failed to read "${t}" from ZIP: ${e?.message}`,P.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 ra=[Vi,Xi];function ia(e){let t=h(e).toLowerCase(),n=ra.find(e=>e.extensions.includes(t));if(!n){let e=ra.flatMap(e=>e.extensions).join(`, `);throw new F(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,P.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function aa(e){ra.some(t=>t.format===e.format)||ra.push(e)}async function G(e,t={}){let{bytes:n}=si(e,t.maxBytes??209715200),r=await ia(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function oa(){return ra.map(e=>({format:e.format,extensions:[...e.extensions]}))}function sa(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 ca(e,t,n){return e.requestJson({path:qn(),method:`POST`,body:t,signal:n})}async function la(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=qn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ua(e,t,n){return e.requestJson({path:Jn(t),method:`GET`,signal:n})}async function da(e,t,n){return e.requestJson({path:Yn(t),method:`POST`,signal:n})}async function fa(e,t,n){return e.requestJson({path:Jn(t),method:`DELETE`,signal:n})}async function pa(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=Xn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ma(e,t,n){return e.requestJson({path:Zn(t),method:`GET`,signal:n})}async function ha(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Qn(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const ga={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`}},_a=Object.keys(ga),va=`sft-lora`;function ya(e){return e in ga}function ba(e){let{method:t,variant:n}=ga[e];return{method:t,variant:n}}function xa(e,t){if(!e)return!1;let{method:n,variant:r}=ga[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Sa(e){return e?_a.filter(t=>xa(e,t)):[]}async function Ca(e,t){return await Gr(dn(e),t)}const wa=`INSUFFICIENT_SAMPLES`;function Ta(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:wa,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 Ea(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 Da(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return G(e,{...r,schema:n})},resolveHyperParameters(e,t){return Ea(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const Oa=Da(`sft`,`sft`,`chatml`),ka={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},Aa={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},ja={...Aa,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},Ma={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 Na(e){return e===`image`||e===`image-i2i`}function Pa(e){return e===`video`||e===`video-kf2v`}function Fa(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Ia(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const La=[Oa,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return G(e,{...n,schema:`tts`});if(Na(t))return G(e,{...n,schema:`image`,maxBytes:oi});if(Pa(t)){let r=await G(e,{...n,schema:`video`,maxBytes:oi});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(W(`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(W(`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 G(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...ka};if(Na(e)){let n={...e===`image-i2i`?ja:Aa};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Pa(e)){let e=t.model??t.baseModel,n={...Ma,batch_size:Ia(e)?1:4,max_pixels:Ia(e)?102400:Fa(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 Ea(t)},shouldSkipGate(e,t){return!!((t===`audio`||Na(t)||Pa(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Na(e)||Pa(e)}},Da(`dpo`,`dpo_full`,`dpo`),Da(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return G(e,{...n,schema:`cpt`,maxBytes:ai})},resolveHyperParameters(e,t){return Ea(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Ra(e){let t=La.find(t=>t.clientTrainingType===e);if(!t){let t=La.map(e=>e.clientTrainingType).join(`, `);throw new F(`Unknown training type "${e}".`,P.USAGE,`Supported training types: ${t}.`)}return t}function za(){return La.map(e=>e.clientTrainingType)}const Ba=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,Va=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,Ha=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Ua(e,t){return U(await e.console(Ba,{query:{type:0,modelId:t}}))}async function Wa(e,t,n){return U(await e.console(Va,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Ga(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 U(await e.console(Ha,{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 Ka(e,t,n){return e.requestJson({path:$n(),method:`POST`,body:t,signal:n})}async function qa(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=$n(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ja(e,t,n){return e.requestJson({path:er(t),method:`GET`,signal:n})}async function Ya(e,t,n){return e.requestJson({path:er(t),method:`DELETE`,signal:n})}async function Xa(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=rr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Za(e,t,n,r){return e.requestJson({path:tr(t),method:`PUT`,body:n,signal:r})}async function Qa(e,t,n,r){return e.requestJson({path:nr(t),method:`PUT`,body:n,signal:r})}const K={LORA:`lora`,PTU:`ptu`,MU:`mu`},$a=K.LORA;function eo(e){return e===`audio`?K.MU:$a}const to={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},no=to.POST_PAY,ro={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},io={name:K.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},ao={name:K.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}}}},oo={name:K.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||no,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new F(`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.`,P.USAGE);try{let a=await Xa(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===K.MU)?.templates??[];if(o.length===0)throw i();let s=t===to.POST_PAY?ro.POST_PAID:ro.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 F?e:new F(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,P.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},so={[K.LORA]:io,[K.PTU]:ao,[K.MU]:oo};function co(e){let t=so[e];if(!t)throw new F(`Unsupported plan "${e}". Supported plans: ${Object.keys(so).join(`, `)}.`,P.USAGE);return t}const lo=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,uo=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,fo=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function po(e,t){return U(await e.console(lo,{input:{modelServiceId:t}}))}async function mo(e,t){return U(await e.console(uo,{input:{modelServiceId:t}}))}async function ho(e){let t=[],n=1;for(;;){let r=U(await e.console(fo,{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 go(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const _o={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":`显示版本信息`}}},vo={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},yo={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},bo={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`}}},xo={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)`}}},So={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 Co(e){return e.auth===`apiKey`?bo:e.auth===`console`?xo:e.auth===`openapi`?So:{}}function wo(e){return e}const To=1;function Eo(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Do(e,t){return`${Eo(e||`image`,`image`)}_${Eo((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Oo=()=>g(f(),`bailian-output`);function ko(e,t){let n=t?.flagDir||e.outputDir||Oo(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Ao(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function jo(e){return o(e===`-`?0:e,`utf-8`)}async function Mo(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 No(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 F(`Invalid ${t} value "${String(e)}". Use true or false.`,P.USAGE)}function Po(e,t=`boolean`){if(e!=null)return No(e,t)}function Fo(e,t,n=`boolean`){let r=Po(e,n);return r===void 0?t:r}function Io(e){return Po(e,`watermark`)??!0}function Lo(e){let t={command:e.command,timestamp:new Date().toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform};return e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function Ro(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function zo(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=Ro(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let q;function Bo(){return q||(process.env.NODE_ENV===`development`?(q=`dev`,q):process.env.BAILIAN_COMPILED===`1`?(q=`prod`,q):(q=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,q))}var Vo=we(((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=De(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=De(`dns`)},function(e,t){e.exports=De(`util`)},function(e,t){e.exports=De(`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`},j=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},M=new Map,N=new Map;M.set(`Baiduspider-render`,i),M.set(`Baiduspider+`,i),M.set(`Baiduspider-image+`,i),M.set(`360Spider`,a),M.set(`360Spider-Image`,a),M.set(`bingbot`,o),M.set(`Googlebot`,s),M.set(`YandexRenderResourcesBot`,c),M.set(`spider`,l),M.set(`Dataprovider.com`,u),M.set(`AhrefsBot`,d),M.set(`BitSightBot`,f),M.set(`oBot`,p),M.set(`Cincraw`,m),M.set(`DingTalkBot-LinkService`,h),M.set(`YisouSpider`,g),M.set(`Bytespider`,_),M.set(`ev-crawler`,v),M.set(`bitdiscovery`,y),M.set(`Spider`,b),M.set(`Ai2Bot-Dolma`,ee),M.set(`dianjing_ad_spider`,te),N.set(`Baiduspider-render`,ne),N.set(`Baiduspider+`,ne),N.set(`Baiduspider-image+`,ne),N.set(`360Spider`,x),N.set(`360Spider-Image`,x),N.set(`bingbot`,re),N.set(`Googlebot`,S),N.set(`YandexRenderResourcesBot`,ie),N.set(`spider`,ae),N.set(`Dataprovider.com`,C),N.set(`AhrefsBot`,w),N.set(`BitSightBot`,T),N.set(`oBot`,E),N.set(`Cincraw`,D),N.set(`DingTalkBot-LinkService`,oe),N.set(`YisouSpider`,O),N.set(`Bytespider`,k),N.set(`ev-crawler`,se),N.set(`bitdiscovery`,ce),N.set(`Spider`,A),N.set(`Ai2Bot-Dolma`,j),N.set(`dianjing_ad_spider`,le);let ue={productHandlerMap:M,commentHandlerMap:N,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ue),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})),
|
|
16
|
-
`,{mode:384})}catch{}}async function
|
|
17
|
-
`).filter(Boolean),n=[];for(let e of t)try{let t=
|
|
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})),Ho=we(((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})),Uo=Ee(Vo(),1),Wo=Ee(Ho(),1);const Go=()=>g(I(),`telemetry.jsonl`);let Ko;const qo=new Set;let Jo;try{let e=new Uo.default({pid:`bailian-cli-node`,env:Bo()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;qo.add(e),e.finally(()=>qo.delete(e))}return n},Jo=e,Ko=e.use(Wo.default)}catch{}async function Yo(e=1e3){try{if(Jo)try{typeof Jo._sendAll==`function`&&Jo._sendAll()}catch{}if(qo.size===0)return;let t=[...qo].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Xo(e){try{await tt();let n=Go();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
|
|
16
|
+
`,{mode:384})}catch{}}async function Zo(e){try{if(!Ko)return;Ko(e.command,zo(e))}catch{}}const Qo=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),$o=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 es(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||Qo.has(n)||$o.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function ts(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof F?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=Lo({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.identity.version,authMethod:e.authMethod,params:es(n)});Xo(l).catch(()=>{}),Zo(l).catch(()=>{})}}function ns(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 rs=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await Wr(dn(this.settings))).map(ns).filter(e=>e!==null)}};function is(){return M(I(),`skills/bailian-docs-llm-wiki`)}function as(){return M(is(),`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 ss(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 cs=class{name=`catalog`;constructor(e){}available(){return C(as())}async load(){return this.available()?ss(as()):[]}};async function ls(e,t){let n=[new cs({onPrepareStart:t?.onPrepareStart}),new rs(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 F(`No model data available.`,P.GENERAL)}const us={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},J={Single:`single`,Pipeline:`pipeline`},ds={Low:`low`,Medium:`medium`,High:`high`},fs={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Y={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},X={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},ps={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Z={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},ms=20,hs=/-\d{4}-\d{2}-\d{2}$/,gs=new Set([X.IG,X.VG,X.TTS,X.RealtimeTTS,X.ThreeDGeneration]),_s=new Set([X.TG,X.Reasoning,X.ASR,X.RealtimeASR,X.RealtimeAudioTranslate,X.TR,X.ME]),vs={standard:0,large:32e3,"extra-large":128e3},ys=.4,bs=.6,xs=.4,Ss=.2,Cs=.2,ws=.2;console.assert(Math.abs(ys+bs-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(xs+Ss+Cs+ws-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Ts=`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"]}]}]}`,
|
|
58
|
+
{"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Es=`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"]}]}`,
|
|
97
|
+
["key highlights"]}]}`,Ds={complexity:J.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[X.TG],requiredFeatures:[],budget:ds.Medium,contextNeed:fs.Standard,qualityPreference:Y.Balanced,confidence:0},Os=[`unconstrained`,`scoped`,`comparison`,`alternative`];function ks(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Os.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 As(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{...Cs}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Cs};let o=JSON.parse(a[0]),s=o.modelPreference,c=Ts(s);return{complexity:o.complexity===J.Pipeline?J.Pipeline:J.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Cs.budget,contextNeed:o.contextNeed??Cs.contextNeed,qualityPreference:o.qualityPreference??Cs.qualityPreference,confidence:1,modelPreference:c}}function Ds(e){let t=!1,n=!1;for(let r of e)fs.has(r)&&(t=!0),ps.has(r)&&(n=!0);return t&&n}function Os(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(ds,``);return n===e?!0:!t.has(n)})}function ks(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 As(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function js(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=ms[i];return d>0&&(c??0)>=d&&(u+=8),a===Y.Flagship&&l===Z.Flagship||a===Y.CostOptimized&&l===Z.CostOptimized?u+=15:a===Y.Balanced&&l===Z.Flagship&&(u+=5),u}function Ms(e,t,n){return e.map(e=>({model:e,score:js(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Ns(e){return new Set(e.map(({model:e})=>e.model))}function Ps(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 Fs(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function Is(e,t,n){return n.size>=10?[]:Ms(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Ls(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:J.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:cs.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>ks(e,a,o)&&As(e,n));return l.length<5&&(l=e.filter(e=>ks(e,a,o))),l.length<5&&(l=e),Ms(l,c,5)}function Rs(e,t){e=Os(e);let n;if(t.complexity===J.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=Fs(Ls(e,i,a,t.budget,t.qualityPreference),Ns(r));r=[...r,...o]}let i=Is(e,t,Ns(r));n=[...r,...i]}else if(Ds(t.requiredCapabilities))n=zs(e,t);else{let r=e.filter(e=>ks(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Ms(r,t,50)}return Ps(n,3)}function zs(e,t){let n=t.requiredCapabilities.filter(e=>fs.has(e)),r=t.requiredCapabilities.filter(e=>ps.has(e)),i=[];if(n.length>0&&(i=Ms(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Ns(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Ms(o,a,25)]}let a=Is(e,t,Ns(i));return[...i,...a]}const Bs=`text-embedding-v4`;function Vs(){return M(I(),`skills/bailian-docs-llm-wiki`)}function Hs(){return M(Vs(),`models-embeddings.json`)}function Us(){let e=Hs();if(!C(e))return null;try{return JSON.parse(E(e,`utf-8`)).items}catch{return null}}async function Ws(e,t){let n={model:Bs,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 Gs(e,t){let n={model:Bs,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 Ks={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 Js(){let e=M(Vs(),`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(M(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 Ys(e,t){let n=(e.capabilities??[]).map(e=>Ks[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 Xs(e,t){let n=Js(),r=t.map(e=>Ys(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Gs(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Bs,dimensions:512,count:a.length,items:a},s=Hs();return T(j(s),{recursive:!0}),A(s,JSON.stringify(o)),a}function Zs(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 Qs=null;function $s(){return Qs===null&&(Qs=Us()),Qs}function ec(){return $s()!==null}function tc(e){return(e??``).toLowerCase().replace(ds,``).replace(/[\s_-]+/g,``).trim()}function nc(e,t){let n=tc(t);if(!n)return!1;if(tc(e.model)===n||tc(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&tc(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=tc(e);return t.length>0&&n.includes(t)})}function rc(e,t){return t.some(t=>nc(e,t))}function ic(e,t){return t.length===0?[]:e.filter(e=>rc(e,t))}function ac(e,t){return t.length===0?e:e.filter(({model:e})=>!rc(e,t))}function oc(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 sc(e,t){return oc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function cc(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=ms[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===Y.Flagship?u=e.category===Z.Flagship?1:.5:a===Y.CostOptimized&&(u=e.category===Z.CostOptimized?1:.5),_s*o+vs*s+ys*c+bs*u}function lc(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>sc(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function uc(e,t){return oc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function dc(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=Zs(t,e.vector),o=a?cc(n,a):0;return[{model:n,score:a?hs*o+gs*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 fc(e){return{model:e,score:1,hardScore:1,softScore:1}}function pc(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?ic(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(fc(e));let r=new Set(l.map(({model:e})=>e.model)),s=dc(t,n,lc(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 dc(t,n,lc(c,o),i,a,o)}function mc(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)rc(t,s)&&!l.has(t.model)&&(c.push(fc(t)),l.add(t.model));return c}function hc(e,t,n,r,i,a,o){let s=ic(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(fc(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=dc(t,n,lc(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 gc(e,t,n,r,i){let a=$s();if(!a)a=await Xs(e,t),Qs=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 Xs(e,t),Qs=a)}let o=await Ws(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=pc(t,a,o,c,r,s,i);break;case`comparison`:e=mc(t,a,o,c,r,s,i);break;case`alternative`:e=hc(t,a,o,c,r,s,i);break;default:e=[]}return ac(e,l)}if(i?.complexity===J.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>uc(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=dc(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 ac(n,l)}let u=lc(t,i);return ac(dc(a,o,u,r,s,i),l)}function _c(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function vc(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=_c(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
|
|
145
|
-
`)}function
|
|
146
|
-
`)}function
|
|
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{...Ds}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Ds};let o=JSON.parse(a[0]),s=o.modelPreference,c=ks(s);return{complexity:o.complexity===J.Pipeline?J.Pipeline:J.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Ds.budget,contextNeed:o.contextNeed??Ds.contextNeed,qualityPreference:o.qualityPreference??Ds.qualityPreference,confidence:1,modelPreference:c}}function js(e){let t=!1,n=!1;for(let r of e)gs.has(r)&&(t=!0),_s.has(r)&&(n=!0);return t&&n}function Ms(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(hs,``);return n===e?!0:!t.has(n)})}function Ns(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 Ps(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Fs(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===Y.Flagship&&l===Z.Flagship||a===Y.CostOptimized&&l===Z.CostOptimized?u+=15:a===Y.Balanced&&l===Z.Flagship&&(u+=5),u}function Is(e,t,n){return e.map(e=>({model:e,score:Fs(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Ls(e){return new Set(e.map(({model:e})=>e.model))}function Rs(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 zs(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function Bs(e,t,n){return n.size>=10?[]:Is(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Vs(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:J.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:fs.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Ns(e,a,o)&&Ps(e,n));return l.length<5&&(l=e.filter(e=>Ns(e,a,o))),l.length<5&&(l=e),Is(l,c,5)}function Hs(e,t){e=Ms(e);let n;if(t.complexity===J.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=zs(Vs(e,i,a,t.budget,t.qualityPreference),Ls(r));r=[...r,...o]}let i=Bs(e,t,Ls(r));n=[...r,...i]}else if(js(t.requiredCapabilities))n=Us(e,t);else{let r=e.filter(e=>Ns(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Is(r,t,50)}return Rs(n,3)}function Us(e,t){let n=t.requiredCapabilities.filter(e=>gs.has(e)),r=t.requiredCapabilities.filter(e=>_s.has(e)),i=[];if(n.length>0&&(i=Is(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Ls(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Is(o,a,25)]}let a=Bs(e,t,Ls(i));return[...i,...a]}const Ws=`text-embedding-v4`;function Gs(){return M(I(),`skills/bailian-docs-llm-wiki`)}function Ks(){return M(Gs(),`models-embeddings.json`)}function qs(){let e=Ks();if(!C(e))return null;try{return JSON.parse(E(e,`utf-8`)).items}catch{return null}}async function Js(e,t){let n={model:Ws,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 Ys(e,t){let n={model:Ws,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 Xs={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Zs={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Qs(){let e=M(Gs(),`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(M(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 $s(e,t){let n=(e.capabilities??[]).map(e=>Xs[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Zs[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Zs[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 ec(e,t){let n=Qs(),r=t.map(e=>$s(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Ys(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Ws,dimensions:512,count:a.length,items:a},s=Ks();return T(j(s),{recursive:!0}),A(s,JSON.stringify(o)),a}function tc(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 nc=null;function rc(){return nc===null&&(nc=qs()),nc}function ic(){return rc()!==null}function ac(e){return(e??``).toLowerCase().replace(hs,``).replace(/[\s_-]+/g,``).trim()}function oc(e,t){let n=ac(t);if(!n)return!1;if(ac(e.model)===n||ac(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&ac(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=ac(e);return t.length>0&&n.includes(t)})}function sc(e,t){return t.some(t=>oc(e,t))}function cc(e,t){return t.length===0?[]:e.filter(e=>sc(e,t))}function lc(e,t){return t.length===0?e:e.filter(({model:e})=>!sc(e,t))}function uc(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 dc(e,t){return uc(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===Y.Flagship?u=e.category===Z.Flagship?1:.5:a===Y.CostOptimized&&(u=e.category===Z.CostOptimized?1:.5),xs*o+Ss*s+Cs*c+ws*u}function pc(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>dc(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function mc(e,t){return uc(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function hc(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=tc(t,e.vector),o=a?fc(n,a):0;return[{model:n,score:a?ys*o+bs*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 gc(e){return{model:e,score:1,hardScore:1,softScore:1}}function _c(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?cc(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(gc(e));let r=new Set(l.map(({model:e})=>e.model)),s=hc(t,n,pc(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 hc(t,n,pc(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)sc(t,s)&&!l.has(t.model)&&(c.push(gc(t)),l.add(t.model));return c}function yc(e,t,n,r,i,a,o){let s=cc(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(gc(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=hc(t,n,pc(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 bc(e,t,n,r,i){let a=rc();if(!a)a=await ec(e,t),nc=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 ec(e,t),nc=a)}let o=await Js(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=_c(t,a,o,c,r,s,i);break;case`comparison`:e=vc(t,a,o,c,r,s,i);break;case`alternative`:e=yc(t,a,o,c,r,s,i);break;default:e=[]}return lc(e,l)}if(i?.complexity===J.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>mc(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=hc(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 lc(n,l)}let u=pc(t,i);return lc(hc(a,o,u,r,s,i),l)}function xc(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Sc(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=xc(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
|
|
145
|
+
`)}function Cc(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!==fs.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 wc(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 Tc(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 Ec(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 Dc(e,t,n,r,i,a){let o=Sc(t),s=Cc(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===J.Pipeline?
|
|
189
|
-
`)}function Oc(e,t){let n=Ec();n.skills[e]={...n.skills[e],...t},Dc(n)}function kc(){let e=de(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||M(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:M(e,r,`skills`),detectDirs:[M(e,r)]}),i=(t,n)=>t?.trim()||M(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:M(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>M(e,t)),s=o.find(e=>C(e))??o[0],c=[M(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(M(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(M(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:M(e,`.agents`,`skills`),detectDirs:[M(e,`.agents`),M(e,`.cline`),M(e,`.dexto`),M(e,`.firebender`),M(e,`.kimi-code`),M(e,`.kimi`),M(e,`.loaf`),M(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:M(n,`agents`,`skills`),detectDirs:[M(n,`agents`),M(n,`amp`),M(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:M(e,`.astrbot`,`data`,`skills`),detectDirs:[M(t,`data`,`skills`),M(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:M(e,`.codebuddy`,`skills`),detectDirs:[M(t,`.codebuddy`),M(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:M(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:M(e,`.continue`,`skills`),detectDirs:[M(t,`.continue`),M(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:M(e,`.deepagents`,`agent`,`skills`),detectDirs:[M(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:M(n,`devin`,`skills`),detectDirs:[M(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:M(n,`goose`,`skills`),detectDirs:[M(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:M(e,`.jazz`,`skills`),detectDirs:[M(e,`.jazz`),M(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:M(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[M(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:M(e,`.minimax`,`skills`),detectDirs:[M(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:M(n,`opencode`,`skills`),detectDirs:[M(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:M(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:M(e,`.tabnine`,`agent`,`skills`),detectDirs:[M(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:M(e,`.zcode`,`skills`),detectDirs:[M(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Ac(){return kc().filter(e=>e.detectDirs.some(e=>C(e)))}function jc(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function Mc(e){let t=Q();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+ue)}return e===t||e.startsWith(t+ue)}function Nc(e){try{if(!w(e).isSymbolicLink())return!1;let t=oe(e);return Mc(le(t)?t:N(j(e),t))}catch{return!1}}function Pc(e,t){if(!t.some(t=>jc(t,e)))return!1;try{return w(e).isDirectory()}catch{return!1}}function Fc(e){try{return w(e).isDirectory()?C(M(e,`SKILL.md`)):!1}catch{return!1}}const Ic=`existing file/dir not managed by bl skill`;function Lc(e,t=Ac(),n=[]){let r=M(Q(),e),i=[];for(let a of t){let t=M(a.skillsDir,e);try{let e=!1;try{w(t),e=!0}catch{}if(e)if(Nc(t))k(t);else if(Pc(t,n))k(t,{recursive:!0,force:!0});else if(Fc(t))k(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:Ic});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 Rc(e,t=Ac(),n=[]){let r=Lc(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===Ic).map(e=>e.path),s=n.filter(e=>!a.some(t=>jc(t,e))&&!o.some(t=>jc(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function zc(e,t=[]){let n=[],r=new Set(t);for(let t of kc())r.add(M(t.skillsDir,e));for(let e of r)try{let r;try{r=w(e)}catch{continue}r.isSymbolicLink()?Nc(e)&&(k(e),n.push(e)):t.some(t=>jc(t,e))&&(k(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function Bc(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function Vc(e,t){let n=ge.extract();n.on(`entry`,(e,r,i)=>{if(!Bc(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=M(t,e.name);if(e.type===`directory`){T(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}T(j(a),{recursive:!0});let o=ae(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await me(pe.from(e),he(),n)}function Hc(e){let t=[],n=r=>{for(let i of D(r?M(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=fe(`sha256`);for(let n of t)r.update(n),r.update(E(M(e,n)));return`sha256:${r.digest(`hex`)}`}function Uc(e,t){T(j(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}C(n)&&k(n,{recursive:!0,force:!0})}function Wc(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function Gc(e=1e4){let t=`${Wc()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new F(`Cannot access skill registry: ${t}`,P.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new F(`Skill registry returned HTTP ${n.status}: ${t}`,P.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 F(`Skill index index.json is not valid JSON`,P.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 F(`Skill index index.json has invalid structure`,P.GENERAL,`Retry later or contact the publisher`);return i}const Kc=/^sha256-[0-9a-f]{64}\.tar\.br$/;function qc(e){let t=e?.object;return t&&Kc.test(t)?t:`skill.tar.br`}async function Jc(e,t){let n=`${Wc()}/${e}/${qc(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new F(`Failed to download skill ${e}: ${n}`,P.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new F(`Failed to download skill ${e}: HTTP ${r.status}`,P.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())}function Yc(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function Xc(e){return e.length>0&&Yc(e)===e}function Zc(e,t){throw new F(`Skill ${e} validation failed: ${t}`,P.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function Qc(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function $c(e,t){let n=M(e,`SKILL.md`),r;try{se(n).isFile()||Zc(t,`SKILL.md is not a regular file`),r=E(n,`utf-8`)}catch(e){if(e instanceof F)throw e;Zc(t,`missing SKILL.md`)}let i=Qc(r);i===null&&Zc(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{Zc(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&Zc(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)&&Zc(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function el(e){if(!Xc(e))throw new F(`Invalid skill name: ${e}`,P.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function tl(e,t,n){el(e);let r=Q(),i=M(r,e),a=M(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(T(a,{recursive:!0}),await Vc(t,a),n?.startsWith(`sha256:`)){let t=Hc(a);if(t!==n)throw new F(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,P.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=$c(a,e);return Uc(a,i),{name:e,path:i,meta:r}}finally{C(a)&&k(a,{recursive:!0,force:!0})}}async function nl(e,t){if(t.compression&&t.compression!==`tar.br`)throw new F(`Skill ${e} uses unsupported compression format: ${t.compression}`,P.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return tl(e,await Jc(e,t),t.contentHash)}function rl(e){el(e);let t=M(Q(),e);return C(t)?(k(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 al(e,t,n=Ac(),r=[]){await nl(e,t);let i=Rc(e,n,r);return{lockEntry:il(t,i.links),linkedAgents:i.linkedAgents}}const $=`bailian-docs-llm-wiki`;function ol(){return M(I(),`skills/bailian-docs-llm-wiki`)}function sl(){return C(M(ol(),`models`,`models.jsonl`))}function cl(){return M(I(),`wiki-sync-state.json`)}function ll(){try{return JSON.parse(E(cl(),`utf-8`))}catch{return null}}function ul(e){try{A(cl(),JSON.stringify(e))}catch{}}function dl(e){try{Oc($,e)}catch{}}function fl(e){try{let t=Ec().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function pl(){try{return(await Gc(3e3)).skills[$]??null}catch{return null}}async function ml(){let e=ll(),t=Date.now();if(e&&t-e.lastChecked<432e5&&sl())return!1;let n=await pl();if(!n?.contentHash)return!1;if(sl()&&(!e||e.contentHash===n.contentHash)){if(ul({lastChecked:t,contentHash:n.contentHash}),fl(n.contentHash)){let e=Ec().skills[$]?.links??[];dl(il(n,Rc($,Ac(),e).links))}return!1}try{let e=Ec().skills[$]?.links??[];dl((await al($,n,Ac(),e)).lockEntry)}catch{return!1}return ul({lastChecked:t,contentHash:n.contentHash}),!0}const hl=`bailian-cli`,gl=`install-method`,_l=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function vl(e){return e?M(I(),`${gl}.${e}`):M(I(),gl)}function yl(){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 bl(e){if(!e)return null;let t=e.trim().toLowerCase();return _l.has(t)?t:null}function xl(e){try{return bl(E(e,`utf-8`).split(`
|
|
190
|
-
`)[0])}catch{return null}}function Sl(){let e=bl(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(yl()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Cl(e){let t=bl(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=xl(vl(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=xl(vl());if(e)return e}return Sl()}return xl(vl())||Sl()}function wl(e){let t=Cl(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function Tl(e,t={clientName:hl}){try{let n=I();C(n)||T(n,{recursive:!0,mode:448}),A(vl(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&A(vl(),`${e}\n`,{mode:384})}catch{}}const El=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Dl=`https://github.com/modelstudioai/cli/releases`,Ol=`https://bailian.aliyun.com/cli/install.sh`,kl=`https://bailian.aliyun.com/cli/install.ps1`;function Al(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):El}function jl(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${Al()}/manifest.json`:`${Al()}/${t}.json`}function Ml(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${Al()}/${n}/${t}`}function Nl(){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 Pl(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function Fl(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function Il(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 Ll(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function Rl(e,t,n){let r=await Il(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=Ll(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 _e(j(t),{recursive:!0}),await me(r,ae(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function zl(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new Oe(`--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 Oe(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Bl(){let e=Q();return C(e)?D(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return se(M(e,t)).isDirectory()}catch{return!1}}):[]}function Vl(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{ho as ASYNC_FLAG,Fe as BAILIAN_HOST,Za as BILLING_METHOD,hl as BINARY_PRODUCT_CLIENT_NAME,F as BailianError,ss as Budgets,La as CALC_DATASETS_TOKENS_API,xt as CHANNEL,$a as CHARGE_TYPE,xo as COMMAND_PACK_API_VERSION,mo as CONCURRENT_FLAG,Re as CONFIG_FILE_KEYS,_o as CONSOLE_AUTH_FLAGS,X as Capabilities,un as Client,J as Complexities,cs as ContextNeeds,Qa as DEFAULT_BILLING_METHOD,El as DEFAULT_CLI_CDN_BASE,Ya as DEFAULT_DEPLOY_PLAN,kl as DEFAULT_INSTALL_PS1_URL,Ol as DEFAULT_INSTALL_SCRIPT_URL,Le as DEFAULT_LANGUAGE,ma as DEFAULT_TRAINING_TYPE,so as DEPLOY_LIST_INDEPENDENT_API,K as DEPLOY_PLAN,ao as DEPLOY_START_API,oo as DEPLOY_STOP_API,Pe as DOCS_HOSTS,Ra as ESTIMATE_FINETUNE_TOKENS_API,P as ExitCode,ls as Features,Dl as GITHUB_RELEASES_BASE,po as GLOBAL_FLAGS,ba as INSUFFICIENT_SAMPLES_CODE,ti as MAX_CPT_BYTES,ei as MAX_DATASET_BYTES,ni as MAX_MEDIA_ZIP_BYTES,go as MODEL_AUTH_FLAGS,Lr as MODEL_LIST_API,nn as McpClient,os as Modalities,Z as ModelCategories,vo as OPENAPI_AUTH_FLAGS,St as OPEN_API_SOURCE,Rr as PREDICT_CONFIG_API,Y as QualityPreferences,tr as RAG_PATHS,Ne as REGIONS,us as SEMANTIC_TOP_K,ro as STRATEGIES,Ie as SUPPORTED_LANGUAGES,Ia as TRAINING_MODEL_PRICE_API,pa as TRAINING_TYPES_CLI,fa as TRAINING_TYPE_MAP,Oe as UsageError,mt as activateConfigProfile,Es as analyzeIntent,sn as anonymousConsoleCall,Dn as appCompletionPath,Uc as atomicSwap,Zt as bailianMcpPath,Qt as bailianMcpSsePath,Pl as binaryAssetFileName,Fl as binaryInnerFileName,Ot as buildAcsCanonicalQuery,Tr as buildAsrFlashRequest,wr as buildAsyncAsrLanguageFields,bc as buildDocLink,_t as buildSettings,il as buildSkillLockEntry,gt as buildSources,ln as callConsoleGateway,sa as cancelFineTune,jl as channelManifestUrl,gn as chatPath,Dr as collectAsrTranscriptionItems,Hc as computeDirContentHash,Vl as computeSkillStatuses,tn as connectBailianMcpWithFallback,Pr as createBailianControlUser,Ha as createDeployment,ia as createFineTune,Ar as createInstrumentedFetch,No as createTrackingEvent,yo as credentialFlagDefs,Xa as defaultDeployPlan,bo as defineCommand,ht as deleteConfigProfile,$r as deleteDataset,Ga as deleteDeployment,ca as deleteFineTune,Xe as describeAuthState,Nl as detectBinaryPlatform,Sl as detectInstallMethod,Ac as detectInstalledAgents,qi as detectModality,nt as detectOutputFormat,Jc as downloadSkillAsset,on as effectiveConsoleGatewayConfig,Tc as emptySkillLock,Qe as ensureConfigDir,Va as estimateCptTokens,Ba as estimateSftDpoTokens,da as exportCheckpoint,Er as extractAsrFlashText,Vc as extractTarBr,Rl as extractZipEntryToFile,Rc as fanOutSkillToAgents,ya as fetchModelCapability,Ur as fetchModelDetail,Hr as fetchModelGroups,zr as fetchModelList,Br as fetchModelListAll,Kr as fetchPredictConfig,Gc as fetchSkillsIndex,za as fetchTrainingModelPrice,fo as findDeploymentEntry,Vr as findModelByName,Go as flushTelemetry,tt as formatErrorJson,ra as formatIssue,et as formatJson,rt as formatOutput,$e as formatText,mn as generateCLIAccessToken,Co as generateFilename,kc as getAgentTargets,Al as getCliCdnBase,I as getConfigDir,L as getConfigPath,Ze as getCredentialsPath,Qr as getDataset,Wa as getDeployment,oa as getFineTune,la as getFineTuneLogs,Cl as getInstallMethod,Yr as getModelProfilePreset,as as getModels,Pa as getProfile,wc as getSkillLockPath,Wc as getSkillRegistryBaseUrl,Q as getSkillsDir,wl as getUpdateInstallMethod,xn as image2ImagePath,Cn as image2videoPath,Lt as imageFileToDataUri,vn as imagePath,yn as imageSyncPath,bn as imageText2ImagePath,Cr as inferAudioFormatHint,nl as installSkill,tl as installSkillFromBuffer,al as installSkillWithFanout,yl as isCompiledBinary,ur as isLegacyImage2ImageModel,lr as isLegacyText2ImageModel,Bt as isLocalFile,Bc as isSafeEntryName,Xc as isSafeSkillName,ec as isSemanticAvailable,$t as isStreamableHttpUnsupported,ar as isSyncMultimodalImageModel,ha as isTrainingTypeCli,en as isUrlOverrideSseFallbackCandidate,dr as isWanxFunctionImageEditModel,Rn as knowledgeChatEndpoint,In as knowledgeRetrievePath,Ln as knowledgeSearchEndpoint,Lc as linkSkillToAgents,Fr as listBailianControlWorkspaces,ua as listCheckpoints,Zr as listDatasets,Ka as listDeployableModels,Ua as listDeployments,aa as listFineTunes,uo as listIndependentDeployedModels,Bl as listSkillDirsOnDisk,na as listSupportedFormats,va as listSupportedTrainingTypes,Fa as listTrainingTypes,Ko as localSink,yt as makeAuthStore,qr as makeConfigStore,Ae as mapApiError,bt as maskToken,ml as maybeSyncWikiData,zn as mcpWebSearchPath,On as memoryAddPath,An as memoryListPath,jn as memoryNodePath,kn as memorySearchPath,_a as modelSupportsTrainingType,Tn as modelsLimitsPath,En as modelsPermissionsPath,st as normalizeConfigName,je as normalizeModelBaseUrl,ko as parseBooleanValue,He as parseConfigFile,ii as parseDatasetSchemaFlag,Ao as parseOptionalBooleanValue,Gt as parseSSE,zl as parseSkillNames,io as pickPlanStrategy,ea as pickValidator,xa as preflightBatchSizeGate,Pn as profileSchemaPath,er as ragEndpoint,Cc as rankModels,z as readConfigFile,dt as readConfigProfiles,Ec as readSkillLock,Do as readTextFromPathOrStdin,Rs as recallCandidates,gc as recallSemantic,Rt as redactDataUri,hn as refreshAccessToken,ta as registerValidator,Ml as releaseAssetUrl,qo as remoteSink,rl as removeSkillDir,Tt as request,Dt as requestJson,Ir as resetBailianControlPolicies4Agent,We as resolveApiKey,Sr as resolveAsrApi,qc as resolveAssetFileName,jo as resolveBooleanFlag,Ge as resolveConsole,Vt as resolveFileUrl,hr as resolveImageEditApi,mr as resolveImageGenerateApi,fr as resolveImageSizeProfile,Ue as resolveModelBaseUrl,Ke as resolveOpenApi,To as resolveOutputDir,pr as resolvePromptExtendDefault,Mo as resolveWatermark,_n as responsesPath,Oo as runWithConcurrency,Yc as sanitizeSkillName,qa as scaleDeployment,kt as signAcsRequest,Ct as sourceConfig,Nn as speechRecognizePath,Mn as speechSynthesizePath,co as startModelService,lo as stopModelService,Eo as stripUndefined,wn as taskPath,Zo as trackCommandExecution,V as trackingHeaders,ga as trainingTypeMethodVariant,zc as unlinkSkillFromAgents,U as unwrapResponse,Ja as updateDeployment,Xr as uploadDataset,zt as uploadFile,Oc as upsertSkillLockEntry,Fn as userProfilePath,pt as validateConfigProfileActivation,G as validateDataset,$c as validateSkillDir,Sn as videoGeneratePath,B as writeConfigFile,Tl as writeInstallMethodSync,Dc 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===J.Pipeline?Es:Ts)+e}else l=n.complexity===J.Pipeline?Es:Ts;let u=a?.enableThinking??!1,d=n.complexity===J.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=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:J.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===J.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=Tc(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Ec(e,g),{type:J.Pipeline,summary:h.summary??``,steps:e}}let _=Tc(h.recommendations??h??[],g,i);return{type:J.Single,recommendations:_}}function Q(){return M(I(),`skills`)}function Oc(){return M(Q(),`skill-lock.json`)}function kc(){return{version:1,skills:{}}}function Ac(){let e=Oc();if(!C(e))return kc();try{let t=JSON.parse(E(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?kc():t}catch{return kc()}}function jc(e){T(Q(),{recursive:!0}),A(Oc(),JSON.stringify(e,null,2)+`
|
|
189
|
+
`)}function Mc(e,t){let n=Ac();n.skills[e]={...n.skills[e],...t},jc(n)}function Nc(){let e=de(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||M(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:M(e,r,`skills`),detectDirs:[M(e,r)]}),i=(t,n)=>t?.trim()||M(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:M(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>M(e,t)),s=o.find(e=>C(e))??o[0],c=[M(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(M(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(M(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:M(e,`.agents`,`skills`),detectDirs:[M(e,`.agents`),M(e,`.cline`),M(e,`.dexto`),M(e,`.firebender`),M(e,`.kimi-code`),M(e,`.kimi`),M(e,`.loaf`),M(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:M(n,`agents`,`skills`),detectDirs:[M(n,`agents`),M(n,`amp`),M(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:M(e,`.astrbot`,`data`,`skills`),detectDirs:[M(t,`data`,`skills`),M(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:M(e,`.codebuddy`,`skills`),detectDirs:[M(t,`.codebuddy`),M(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:M(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:M(e,`.continue`,`skills`),detectDirs:[M(t,`.continue`),M(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:M(e,`.deepagents`,`agent`,`skills`),detectDirs:[M(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:M(n,`devin`,`skills`),detectDirs:[M(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:M(n,`goose`,`skills`),detectDirs:[M(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:M(e,`.jazz`,`skills`),detectDirs:[M(e,`.jazz`),M(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:M(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[M(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:M(e,`.minimax`,`skills`),detectDirs:[M(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:M(n,`opencode`,`skills`),detectDirs:[M(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:M(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:M(e,`.tabnine`,`agent`,`skills`),detectDirs:[M(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:M(e,`.zcode`,`skills`),detectDirs:[M(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Pc(){return Nc().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=Q();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+ue)}return e===t||e.startsWith(t+ue)}function Lc(e){try{if(!w(e).isSymbolicLink())return!1;let t=oe(e);return Ic(le(t)?t:N(j(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(M(e,`SKILL.md`)):!1}catch{return!1}}const Bc=`existing file/dir not managed by bl skill`;function Vc(e,t=Pc(),n=[]){let r=M(Q(),e),i=[];for(let a of t){let t=M(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=Pc(),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 Nc())r.add(M(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=ge.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=M(t,e.name);if(e.type===`directory`){T(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}T(j(a),{recursive:!0});let o=ae(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await me(pe.from(e),he(),n)}function Kc(e){let t=[],n=r=>{for(let i of D(r?M(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=fe(`sha256`);for(let n of t)r.update(n),r.update(E(M(e,n)));return`sha256:${r.digest(`hex`)}`}function qc(e,t){T(j(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}C(n)&&k(n,{recursive:!0,force:!0})}function Jc(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function Yc(e=1e4){let t=`${Jc()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new F(`Cannot access skill registry: ${t}`,P.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new F(`Skill registry returned HTTP ${n.status}: ${t}`,P.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 F(`Skill index index.json is not valid JSON`,P.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 F(`Skill index index.json has invalid structure`,P.GENERAL,`Retry later or contact the publisher`);return i}const Xc=/^sha256-[0-9a-f]{64}\.tar\.br$/;function Zc(e){let t=e?.object;return t&&Xc.test(t)?t:`skill.tar.br`}async function Qc(e,t){let n=`${Jc()}/${e}/${Zc(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new F(`Failed to download skill ${e}: ${n}`,P.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new F(`Failed to download skill ${e}: HTTP ${r.status}`,P.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())}function $c(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function el(e){return e.length>0&&$c(e)===e}function tl(e,t){throw new F(`Skill ${e} validation failed: ${t}`,P.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function nl(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function rl(e,t){let n=M(e,`SKILL.md`),r;try{se(n).isFile()||tl(t,`SKILL.md is not a regular file`),r=E(n,`utf-8`)}catch(e){if(e instanceof F)throw e;tl(t,`missing SKILL.md`)}let i=nl(r);i===null&&tl(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{tl(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&tl(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)&&tl(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function il(e){if(!el(e))throw new F(`Invalid skill name: ${e}`,P.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function al(e,t,n){il(e);let r=Q(),i=M(r,e),a=M(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 F(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,P.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=rl(a,e);return qc(a,i),{name:e,path:i,meta:r}}finally{C(a)&&k(a,{recursive:!0,force:!0})}}async function ol(e,t){if(t.compression&&t.compression!==`tar.br`)throw new F(`Skill ${e} uses unsupported compression format: ${t.compression}`,P.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return al(e,await Qc(e,t),t.contentHash)}function sl(e){il(e);let t=M(Q(),e);return C(t)?(k(t,{recursive:!0,force:!0}),!0):!1}function cl(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=Pc(),r=[]){await ol(e,t);let i=Hc(e,n,r);return{lockEntry:cl(t,i.links),linkedAgents:i.linkedAgents}}const $=`bailian-docs-llm-wiki`;function ul(){return M(I(),`skills/bailian-docs-llm-wiki`)}function dl(){return C(M(ul(),`models`,`models.jsonl`))}function fl(){return M(I(),`wiki-sync-state.json`)}function pl(){try{return JSON.parse(E(fl(),`utf-8`))}catch{return null}}function ml(e){try{A(fl(),JSON.stringify(e))}catch{}}function hl(e){try{Mc($,e)}catch{}}function gl(e){try{let t=Ac().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function _l(){try{return(await Yc(3e3)).skills[$]??null}catch{return null}}async function vl(){let e=pl(),t=Date.now();if(e&&t-e.lastChecked<432e5&&dl())return!1;let n=await _l();if(!n?.contentHash)return!1;if(dl()&&(!e||e.contentHash===n.contentHash)){if(ml({lastChecked:t,contentHash:n.contentHash}),gl(n.contentHash)){let e=Ac().skills[$]?.links??[];hl(cl(n,Hc($,Pc(),e).links))}return!1}try{let e=Ac().skills[$]?.links??[];hl((await ll($,n,Pc(),e)).lockEntry)}catch{return!1}return ml({lastChecked:t,contentHash:n.contentHash}),!0}const yl=`bailian-cli`,bl=`install-method`,xl=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function Sl(e){return e?M(I(),`${bl}.${e}`):M(I(),bl)}function Cl(){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 wl(e){if(!e)return null;let t=e.trim().toLowerCase();return xl.has(t)?t:null}function Tl(e){try{return wl(E(e,`utf-8`).split(`
|
|
190
|
+
`)[0])}catch{return null}}function El(){let e=wl(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Cl()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Dl(e){let t=wl(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=Tl(Sl(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=Tl(Sl());if(e)return e}return El()}return Tl(Sl())||El()}function Ol(e){let t=Dl(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function kl(e,t={clientName:yl}){try{let n=I();C(n)||T(n,{recursive:!0,mode:448}),A(Sl(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&A(Sl(),`${e}\n`,{mode:384})}catch{}}const Al=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,jl=`https://github.com/modelstudioai/cli/releases`,Ml=`https://bailian.aliyun.com/cli/install.sh`,Nl=`https://bailian.aliyun.com/cli/install.ps1`;function Pl(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):Al}function Fl(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${Pl()}/manifest.json`:`${Pl()}/${t}.json`}function Il(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${Pl()}/${n}/${t}`}function Ll(){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 Rl(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function zl(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function Bl(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 Vl(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function Hl(e,t,n){let r=await Bl(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=Vl(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 _e(j(t),{recursive:!0}),await me(r,ae(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function Ul(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new Oe(`--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 Oe(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Wl(){let e=Q();return C(e)?D(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return se(M(e,t)).isDirectory()}catch{return!1}}):[]}function Gl(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,yo as ASYNC_FLAG,Fe as BAILIAN_HOST,to as BILLING_METHOD,yl as BINARY_PRODUCT_CLIENT_NAME,F as BailianError,ds as Budgets,Va as CALC_DATASETS_TOKENS_API,Tt as CHANNEL,ro as CHARGE_TYPE,To as COMMAND_PACK_API_VERSION,vo as CONCURRENT_FLAG,Re as CONFIG_FILE_KEYS,xo as CONSOLE_AUTH_FLAGS,X as Capabilities,mn as Client,J as Complexities,fs as ContextNeeds,no as DEFAULT_BILLING_METHOD,Al as DEFAULT_CLI_CDN_BASE,$a as DEFAULT_DEPLOY_PLAN,Nl as DEFAULT_INSTALL_PS1_URL,Ml as DEFAULT_INSTALL_SCRIPT_URL,Le as DEFAULT_LANGUAGE,va as DEFAULT_TRAINING_TYPE,fo as DEPLOY_LIST_INDEPENDENT_API,K as DEPLOY_PLAN,lo as DEPLOY_START_API,uo as DEPLOY_STOP_API,Pe as DOCS_HOSTS,Ha as ESTIMATE_FINETUNE_TOKENS_API,P as ExitCode,ps as Features,jl as GITHUB_RELEASES_BASE,_o as GLOBAL_FLAGS,wa as INSUFFICIENT_SAMPLES_CODE,ai as MAX_CPT_BYTES,ii as MAX_DATASET_BYTES,oi as MAX_MEDIA_ZIP_BYTES,bo as MODEL_AUTH_FLAGS,Vr as MODEL_LIST_API,sn as McpClient,us as Modalities,Z as ModelCategories,So as OPENAPI_AUTH_FLAGS,Et as OPEN_API_SOURCE,Hr as PREDICT_CONFIG_API,Y as QualityPreferences,ar as RAG_PATHS,Ne as REGIONS,ms as SEMANTIC_TOP_K,so as STRATEGIES,Ie as SUPPORTED_LANGUAGES,Ba as TRAINING_MODEL_PRICE_API,_a as TRAINING_TYPES_CLI,ga as TRAINING_TYPE_MAP,Oe as UsageError,_t as activateConfigProfile,As as analyzeIntent,dn as anonymousConsoleCall,jn as appCompletionPath,qc as atomicSwap,tn as bailianMcpPath,nn as bailianMcpSsePath,Rl as binaryAssetFileName,zl as binaryInnerFileName,Mt as buildAcsCanonicalQuery,kr as buildAsrFlashRequest,Or as buildAsyncAsrLanguageFields,wc as buildDocLink,xt as buildSettings,cl as buildSkillLockEntry,bt as buildSources,pn as callConsoleGateway,da as cancelFineTune,Fl as channelManifestUrl,bn as chatPath,jr as collectAsrTranscriptionItems,Kc as computeDirContentHash,Gl as computeSkillStatuses,on as connectBailianMcpWithFallback,Rr as createBailianControlUser,Ka as createDeployment,ca as createFineTune,Pr as createInstrumentedFetch,Lo as createTrackingEvent,Co as credentialFlagDefs,eo as defaultDeployPlan,wo as defineCommand,vt as deleteConfigProfile,ri as deleteDataset,Ya as deleteDeployment,fa as deleteFineTune,$e as describeAuthState,Ll as detectBinaryPlatform,El as detectInstallMethod,Pc as detectInstalledAgents,Zi as detectModality,at as detectOutputFormat,Qc as downloadSkillAsset,un as effectiveConsoleGatewayConfig,kc as emptySkillLock,tt as ensureConfigDir,Ga as estimateCptTokens,Wa as estimateSftDpoTokens,ha as exportCheckpoint,Ar as extractAsrFlashText,Gc as extractTarBr,Hl as extractZipEntryToFile,Hc as fanOutSkillToAgents,Ca as fetchModelCapability,qr as fetchModelDetail,Kr as fetchModelGroups,Ur as fetchModelList,Wr as fetchModelListAll,Xr as fetchPredictConfig,Yc as fetchSkillsIndex,Ua as fetchTrainingModelPrice,go as findDeploymentEntry,Gr as findModelByName,Yo as flushTelemetry,it as formatErrorJson,sa as formatIssue,rt as formatJson,ot as formatOutput,nt as formatText,vn as generateCLIAccessToken,Do as generateFilename,Nc as getAgentTargets,Pl as getCliCdnBase,I as getConfigDir,L as getConfigPath,et as getCredentialsPath,ni as getDataset,Ja as getDeployment,ua as getFineTune,pa as getFineTuneLogs,Dl as getInstallMethod,$r as getModelProfilePreset,ls as getModels,Ra as getProfile,Oc as getSkillLockPath,Jc as getSkillRegistryBaseUrl,Q as getSkillsDir,Ol as getUpdateInstallMethod,Tn as image2ImagePath,Dn as image2videoPath,Vt as imageFileToDataUri,Sn as imagePath,Cn as imageSyncPath,wn as imageText2ImagePath,Dr as inferAudioFormatHint,ol as installSkill,al as installSkillFromBuffer,ll as installSkillWithFanout,He as isApiKeyCapability,Cl as isCompiledBinary,mr as isLegacyImage2ImageModel,pr as isLegacyText2ImageModel,Wt as isLocalFile,Wc as isSafeEntryName,el as isSafeSkillName,ic as isSemanticAvailable,rn as isStreamableHttpUnsupported,lr as isSyncMultimodalImageModel,ya as isTrainingTypeCli,an as isUrlOverrideSseFallbackCandidate,hr as isWanxFunctionImageEditModel,Hn as knowledgeChatEndpoint,Bn as knowledgeRetrievePath,Vn as knowledgeSearchEndpoint,Vc as linkSkillToAgents,zr as listBailianControlWorkspaces,ma as listCheckpoints,ti as listDatasets,Xa as listDeployableModels,qa as listDeployments,la as listFineTunes,ho as listIndependentDeployedModels,Wl as listSkillDirsOnDisk,oa as listSupportedFormats,Sa as listSupportedTrainingTypes,za as listTrainingTypes,Xo as localSink,Ct as makeAuthStore,Zr as makeConfigStore,Ae as mapApiError,wt as maskToken,vl as maybeSyncWikiData,Un as mcpWebSearchPath,Mn as memoryAddPath,Pn as memoryListPath,Fn as memoryNodePath,Nn as memorySearchPath,xa as modelSupportsTrainingType,kn as modelsLimitsPath,An as modelsPermissionsPath,Ue as normalizeApiKeyCapabilities,ut as normalizeConfigName,je as normalizeModelBaseUrl,No as parseBooleanValue,Ge as parseConfigFile,ci as parseDatasetSchemaFlag,Po as parseOptionalBooleanValue,Yt as parseSSE,Ul as parseSkillNames,co as pickPlanStrategy,ia as pickValidator,Ta as preflightBatchSizeGate,Rn as profileSchemaPath,ir as ragEndpoint,Dc as rankModels,z as readConfigFile,mt as readConfigProfiles,Ac as readSkillLock,jo as readTextFromPathOrStdin,Hs as recallCandidates,bc as recallSemantic,Ht as redactDataUri,yn as refreshAccessToken,aa as registerValidator,Il as releaseAssetUrl,Zo as remoteSink,sl as removeSkillDir,kt as request,jt as requestJson,Br as resetBailianControlPolicies4Agent,qe as resolveApiKey,Er as resolveAsrApi,Zc as resolveAssetFileName,Fo as resolveBooleanFlag,Je as resolveConsole,Gt as resolveFileUrl,yr as resolveImageEditApi,vr as resolveImageGenerateApi,gr as resolveImageSizeProfile,Ke as resolveModelBaseUrl,Ye as resolveOpenApi,ko as resolveOutputDir,_r as resolvePromptExtendDefault,Io as resolveWatermark,xn as responsesPath,Mo as runWithConcurrency,$c as sanitizeSkillName,Za as scaleDeployment,yt as selectApiKeyResolutionSources,Nt as signAcsRequest,Dt as sourceConfig,Ln as speechRecognizePath,In as speechSynthesizePath,po as startModelService,mo as stopModelService,Ao as stripUndefined,On as taskPath,ts as trackCommandExecution,V as trackingHeaders,ba as trainingTypeMethodVariant,Uc as unlinkSkillFromAgents,U as unwrapResponse,Qa as updateDeployment,ei as uploadDataset,Ut as uploadFile,Mc as upsertSkillLockEntry,zn as userProfilePath,gt as validateConfigProfileActivation,G as validateDataset,rl as validateSkillDir,En as videoGeneratePath,B as writeConfigFile,kl as writeInstallMethodSync,jc as writeSkillLock};
|
package/package.json
CHANGED