bailian-cli-core 1.15.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1400,6 +1400,8 @@ declare function imageText2ImagePath(): string;
1400
1400
  declare function image2ImagePath(): string;
1401
1401
  declare function videoGeneratePath(): string;
1402
1402
  declare function taskPath(taskId: string): string;
1403
+ declare function modelsLimitsPath(): string;
1404
+ declare function modelsPermissionsPath(): string;
1403
1405
  declare function appCompletionPath(appId: string): string;
1404
1406
  declare function memoryAddPath(): string;
1405
1407
  declare function memorySearchPath(): string;
@@ -1637,10 +1639,17 @@ declare function effectiveConsoleGatewayConfig(config: Pick<Settings, "consoleRe
1637
1639
  consoleSwitchAgent?: number;
1638
1640
  };
1639
1641
  interface ConsoleGatewayRequest {
1640
- /** Console API name, e.g. zeldaEasy.bailian-commerce.freeTrial.queryFreeTierQuota */
1642
+ /** Console API name, e.g. zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierQuota */
1641
1643
  api: string;
1642
1644
  data: Record<string, unknown>;
1643
1645
  }
1646
+ /** Console-call signature shared by catalog helpers (`client.console` or an anonymous call). */
1647
+ type ConsoleCall = (api: string, data: Record<string, unknown>) => Promise<unknown>;
1648
+ /**
1649
+ * Build an anonymous (token-less) gateway caller for public catalog APIs such
1650
+ * as `listFoundationModels` — no console login required.
1651
+ */
1652
+ declare function anonymousConsoleCall(config: Pick<Settings, "consoleRegion" | "consoleSite" | "consoleSwitchAgent" | "timeout">): ConsoleCall;
1644
1653
  /**
1645
1654
  * Invoke a Bailian **console** OpenAPI via the CLI gateway (`/cli/api.json`).
1646
1655
  * 目标(region/site/switchAgent)与 token 均由调用方解析后传入:Client.console 传
@@ -1660,7 +1669,6 @@ declare function callConsoleGateway(target: ConsoleGatewayTarget, timeoutSec: nu
1660
1669
  //#region src/console/models.d.ts
1661
1670
  declare const MODEL_LIST_API = "zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels";
1662
1671
  declare const PREDICT_CONFIG_API = "zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig";
1663
- type ConsoleCall = (api: string, data: Record<string, unknown>) => Promise<unknown>;
1664
1672
  /** Unwrap the DataV2 double-envelope that console gateway returns. */
1665
1673
  declare function unwrapResponse(result: Record<string, unknown>): Record<string, unknown>;
1666
1674
  interface ModelListParams {
@@ -1676,6 +1684,14 @@ interface ModelListResult {
1676
1684
  }
1677
1685
  /** Page the console model-list API. `call` makes the gateway request (e.g. `client.console`). */
1678
1686
  declare function fetchModelList(call: ConsoleCall, params?: ModelListParams): Promise<ModelListResult>;
1687
+ /** Page through every model-list page and return all raw model items. */
1688
+ declare function fetchModelListAll(call: ConsoleCall, params?: Omit<ModelListParams, "pageNo">): Promise<Record<string, unknown>[]>;
1689
+ /**
1690
+ * Look up a single model by exact id. The server's `name` filter is a
1691
+ * substring match, so an exact `model` equality check narrows the result
1692
+ * (e.g. avoids `qwen3-8b` matching `qwen3-8b-v2`).
1693
+ */
1694
+ declare function findModelByName(call: ConsoleCall, modelName: string): Promise<Record<string, unknown> | null>;
1679
1695
  interface ModelPriceInfo {
1680
1696
  type?: string;
1681
1697
  priceUnit?: string;
@@ -3649,4 +3665,4 @@ declare function installSkillWithFanout(name: string, entry: SkillIndexEntry, ag
3649
3665
  declare function listSkillDirsOnDisk(): string[];
3650
3666
  declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[];
3651
3667
  //#endregion
3652
- 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, 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, ConsoleCredential, ConsoleGatewayRequest, ConsoleGatewayTarget, ConsoleSite, ContextNeed, ContextNeeds, CreateDeploymentRequest, CreateDeploymentResponse, CreateFineTuneRequest, CreateFineTuneResponse, CreatePlanFlags, CreateUserReqDTO, CredentialSource, DEFAULT_BILLING_METHOD, DEFAULT_CLI_CDN_BASE, DEFAULT_DEPLOY_PLAN, DEFAULT_INSTALL_PS1_URL, DEFAULT_INSTALL_SCRIPT_URL, DEFAULT_TRAINING_TYPE, DEPLOY_PLAN, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, 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, 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, LinkResult, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, 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, ModelSource, OPENAPI_AUTH_FLAGS, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, ResponsesOutputContent, ResponsesOutputItem, ResponsesRequest, ResponsesResponse, ResponsesStreamEvent, SEMANTIC_TOP_K, STRATEGIES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, SourceFlags, StreamChoice, StreamChunk, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, TrackingIdentity, type TrainingProfile, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UsageError, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, activateConfigProfile, analyzeIntent, 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, exportCheckpoint, extractAsrFlashText, extractTarBr, extractZipEntryToFile, fanOutSkillToAgents, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchPredictConfig, fetchSkillsIndex, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateCLIAccessToken, generateFilename, getAgentTargets, getCliCdnBase, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getInstallMethod, getModelProfilePreset, getModels, getProfile, getSkillLockPath, getSkillRegistryBaseUrl, getSkillsDir, getUpdateInstallMethod, image2ImagePath, imageFileToDataUri, imagePath, imageSyncPath, imageText2ImagePath, 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, listSkillDirsOnDisk, listSupportedFormats, listSupportedTrainingTypes, listTrainingTypes, localSink, makeAuthStore, makeConfigStore, mapApiError, maskToken, maybeSyncWikiData, mcpWebSearchPath, memoryAddPath, memoryListPath, memoryNodePath, memorySearchPath, modelSupportsTrainingType, normalizeConfigName, normalizeModelBaseUrl, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, parseSkillNames, pickPlanStrategy, pickValidator, preflightBatchSizeGate, profileSchemaPath, rankModels, readConfigFile, readConfigProfiles, readSkillLock, readTextFromPathOrStdin, recallCandidates, recallSemantic, redactDataUri, refreshAccessToken, registerValidator, releaseAssetUrl, remoteSink, removeSkillDir, request, requestJson, resetBailianControlPolicies4Agent, resolveApiKey, resolveAsrApi, resolveAssetFileName, resolveBooleanFlag, resolveConsole, resolveFileUrl, resolveImageEditApi, resolveImageGenerateApi, resolveImageSizeProfile, resolveModelBaseUrl, resolveOpenApi, resolveOutputDir, resolvePromptExtendDefault, resolveWatermark, responsesPath, runWithConcurrency, sanitizeSkillName, scaleDeployment, signAcsRequest, sourceConfig, speechRecognizePath, speechSynthesizePath, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unlinkSkillFromAgents, unwrapResponse, updateDeployment, uploadDataset, uploadFile, upsertSkillLockEntry, userProfilePath, validateConfigProfileActivation, validateDataset, validateSkillDir, videoGeneratePath, writeConfigFile, writeInstallMethodSync, writeSkillLock };
3668
+ 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, 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_TRAINING_TYPE, DEPLOY_PLAN, 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, 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, LinkResult, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, 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, ModelSource, OPENAPI_AUTH_FLAGS, OpenApiCredential, OutputFormat, PREDICT_CONFIG_API, ParsedFlags, PipelineResult, PipelineStep, PlanContext, PlanResolved, PlanStrategy, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, ResponsesOutputContent, ResponsesOutputItem, ResponsesRequest, ResponsesResponse, ResponsesStreamEvent, SEMANTIC_TOP_K, STRATEGIES, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, Settings, SingleResult, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, SourceFlags, StreamChoice, StreamChunk, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, TrackingIdentity, 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, exportCheckpoint, extractAsrFlashText, extractTarBr, extractZipEntryToFile, fanOutSkillToAgents, fetchModelCapability, fetchModelDetail, fetchModelGroups, fetchModelList, fetchModelListAll, fetchPredictConfig, fetchSkillsIndex, 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, 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, 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, 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, stripUndefined, taskPath, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, unlinkSkillFromAgents, unwrapResponse, updateDeployment, uploadDataset, uploadFile, upsertSkillLockEntry, userProfilePath, validateConfigProfileActivation, validateDataset, validateSkillDir, videoGeneratePath, writeConfigFile, writeInstallMethodSync, writeSkillLock };
package/dist/index.mjs CHANGED
@@ -8,13 +8,13 @@ import{createRequire as e}from"node:module";import{appendFileSync as t,createRea
8
8
  `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Ht(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 N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a;break}return{event:o}}async function*Ut(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=Ht(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let{lines:s,rest:c}=Vt(r);r=c;for(let t of s){let n=Ht(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Ht(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{t.releaseLock()}}function Wt(e){return String(e)}var Gt=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 N(`This command needs a model-domain API key.`,M.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 N(`MCP SSE session closed.`,M.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out waiting for response headers.`,M.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 N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new N(e,M.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof N?e:new N(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,M.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=qt(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 Ut(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Kt(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=Wt(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 N(`MCP SSE stream ended before endpoint event.`,M.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let n=this.nextId++,r=Wt(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=qt(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new N(`MCP error (${e.error.code}): ${e.error.message}`,M.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 N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);if(!this.messageUrl)throw new N(`MCP SSE message endpoint is not ready.`,M.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=Jt(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 N(`MCP SSE session closed.`,M.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 N(`MCP SSE session closed.`,M.GENERAL):n.timedOut?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:t})}throw new N(e,M.GENERAL)}}finally{n.cleanup()}}};function Kt(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new N(`MCP SSE endpoint is not a valid URL: ${t}`,M.GENERAL)}if(n.origin!==r.origin)throw new N(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,M.GENERAL);return n.toString()}function qt(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new N(t,M.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Jt(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 Yt(e){return`/api/v1/mcps/${e}/mcp`}function Xt(e){return`/api/v1/mcps/${e}/sse`}function Zt(e){return e instanceof N?/^MCP request failed:\s*405\b/i.test(e.message):!1}function Qt(e){return e instanceof N?/^MCP request failed:\s*(405|404)\b/i.test(e.message):!1}async function $t(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new en(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Qt(e))throw e}let r=new Gt(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new en(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!Zt(e)||a===`WebSearch`)throw e}let c=new Gt(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var en=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=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 N(`MCP error (${a.error.code}): ${a.error.message}`,M.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 Ut(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 N(`MCP SSE response stream ended without a matching JSON-RPC response.`,M.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}};const tn={"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 nn(e,t){return tn[e]?.[t]??tn[`cn-beijing`][t]}function rn(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 an(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 on(e,t,{api:n,data:r},i){let a=nn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=an(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 N(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,M.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 N(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?M.AUTH:M.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var sn=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}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 Ct(this.http,this.toOpts(e))}requestJson(e){return Tt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Rt(e)?zt(e,this.requireApi().token,t,{...n,identity:this.deps.identity}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Rt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Ft(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 en(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),$t({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Yt(e)),sseUrl:this.url(Xt(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await on(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof N)||e.exitCode!==M.AUTH||!e.message.includes(`not logged in`))throw e;let t=await fn({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await on({...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?Et(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Dt({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${yt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${yt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...B(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 N(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,M.GENERAL)}if(!s.ok||l.Success===!1)throw new N(`${l.Code||s.status} - ${l.Message||s.statusText}`,M.GENERAL);return l}};const cn={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function ln(e){for(let[t,n]of Object.entries(Fe))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function un(e){return cn[ln(e)]??cn.cn}async function dn(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new sn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=un(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function fn(e){let t=e.settings.configName,n=R(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
12
- `);let a=(await dn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=R(t);return o.access_token=a,await z(o,t),a}function pn(){return`/compatible-mode/v1/chat/completions`}function mn(){return`/compatible-mode/v1/responses`}function hn(){return`/api/v1/services/aigc/image-generation/generation`}function gn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function _n(){return`/api/v1/services/aigc/text2image/image-synthesis`}function vn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function yn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function bn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function xn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Sn(){return`/api/v2/apps/memory/add`}function Cn(){return`/api/v2/apps/memory/memory_nodes/search`}function wn(){return`/api/v2/apps/memory/memory_nodes`}function Tn(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function En(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Dn(){return`/api/v1/services/audio/asr/transcription`}function On(){return`/api/v2/apps/memory/profile_schemas`}function kn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function An(){return`/api/v1/indices/rag/index/retrieve`}function jn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Mn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Nn(){return`/api/v1/mcps/WebSearch/mcp`}function Pn(){return`/compatible-mode/v1/files`}function Fn(){return`/api/v1/files`}function In(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Ln(){return`/api/v1/fine-tunes`}function Rn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function zn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Bn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Vn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Hn(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Un(){return`/api/v1/deployments`}function Wn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Gn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function Kn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function qn(){return`/api/v1/deployments/models`}const Jn=[`qwen-image`,`wan2.7-image`,`z-image`],Yn=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function Xn(e,t){return t.some(t=>e.startsWith(t))}function Zn(e){return Xn(e,Jn)||e.startsWith(`wan2.6-image`)}function Qn(e){return Xn(e,Jn)}function $n(e){return Xn(e,Yn)}function er(e){return/^wanx-v1(?:-|$)/i.test(e)}function tr(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||Qn(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||er(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function nr(e){return/wan2\.5-i2i/i.test(e)}function rr(e){return/imageedit/i.test(e)}function ir(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`:er(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:tr(e)?`wan-legacy`:`wan26`}function ar(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function V(e,t){return{...e,sizeProfile:ir(t),promptExtendDefault:ar(t)}}function or(e){return Qn(e)?V({kind:`sync-multimodal`,path:gn(),useSync:!0,inputStyle:`messages`},e):tr(e)?V({kind:`async-text2image`,path:_n(),useSync:!1,inputStyle:`prompt`},e):V({kind:`async-image-generation`,path:hn(),useSync:!1,inputStyle:`messages`},e)}function sr(e){return $n(e)?V({kind:`sync-multimodal`,path:gn(),useSync:!0,inputStyle:`messages`},e):rr(e)?V({kind:`async-image2image`,path:vn(),useSync:!1,inputStyle:`function-base-image`},e):nr(e)?V({kind:`async-image2image`,path:vn(),useSync:!1,inputStyle:`prompt-images`},e):V({kind:`async-image-generation`,path:hn(),useSync:!1,inputStyle:`messages`},e)}function cr(e){return/realtime|streaming/i.test(e)}function lr(e){return/filetrans/i.test(e)}function ur(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const dr=[`fun-asr-flash`,`qwen-audio`];function fr(e){return cr(e)||lr(e)?!1:!!(e.startsWith(dr[0])||e.startsWith(dr[1])&&/asr-flash/i.test(e))}function pr(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||lr(e)||cr(e)||fr(e))}function mr(e){if(cr(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(lr(e)){let t=ur(e);return{kind:`async-filetrans`,path:Dn(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return fr(e)?{kind:`sync-flash`,path:gn(),useSync:!0,flashFamily:`input-audio`}:pr(e)?{kind:`sync-flash`,path:gn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Dn(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function hr(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 gr(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function _r(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,flashFamily:a}=e;if(a===`input-audio`){let e={format:hr(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 vr(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function yr(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 br(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function xr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Sr(e){return async(t,n={})=>{let r=xr(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}`),br(r))for(let[t,n]of Object.entries(B(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${yt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Cr=`2024-08-16`;function wr(e){return`bailiancontrol.${e}.aliyuncs.com`}function Tr(e){return new sn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Er(e){return Tr(e).openApiJson({host:wr(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Cr,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Dr(e){return Tr(e).openApiJson({host:wr(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Cr,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Or(e){return Tr(e).openApiJson({host:wr(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Cr,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const kr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ar=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function jr(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 Mr(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=jr(await e(kr,{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 Nr(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=jr(await e(kr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Pr(e,t){return(jr(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 Fr=[`name`,`key`,`default`,`tip`,`range`];function Ir(e){return e.map(e=>{let t={};for(let n of Fr)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Lr(e,t){let n=jr(await e(Ar,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Ir(e):null}catch{return null}return Array.isArray(n)?Ir(n):null}function Rr(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Ne(String(r)):r;await z(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await z(n,e)},profiles:()=>ut(),activate:e=>pt(e),validateActivation:e=>ft(e),get path(){return F()}}}const zr={"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 Br(e){return e?zr[e]:void 0}async function Vr(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:Pn(),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 N(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,M.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new N(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,M.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function Hr(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=Fn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ur(e,t,n){return e.requestJson({path:In(t),method:`GET`,signal:n})}async function Wr(e,t,n){let r=await e.request({path:In(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Gr=300*1024*1024,Kr=1024*1024*1024;function qr(e,t=Gr){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);let n=l(e);if(!n.isFile())throw new N(`Not a regular file: ${e}`,M.USAGE);if(n.size===0)throw new N(`File is empty: ${e}`,M.USAGE);if(n.size>t)throw new N(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,M.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function Jr(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,M.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function Yr(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 Xr=new Set([`system`,`user`,`assistant`]);function Zr(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(H(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!Xr.has(a))&&r.push(H(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(H(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function Qr(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(H(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(H(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...Zr(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(H(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(H(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(H(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(H(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const $r={name:`chatml`,detect:()=>!0,inspect:Qr};function ei(e,t){let n=[];if(!(`text`in e))return n.push(H(`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(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const ti={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ei};function ni(e,t){let n=Qr(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(H(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(H(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...Zr(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...Zr(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const ri={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:ni};function ii(e,t){let n=[];if(!(`wav_fn`in e))n.push(H(`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(H(`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(H(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(H(`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(H(`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(H(`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(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const ai={name:`tts`,detect:e=>`wav_fn`in e,inspect:ii},oi=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function si(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function ci(e){return/^[\x20-\x7E]+$/.test(e)}function li(e,t){let n=[];if(!(`prompt`in e))n.push(H(`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(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(H(`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(H(`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(H(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=si(r);oi.has(e)||n.push(H(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...oi].join(`, `)}.`,{line:t,path:`img_path`})),ci(r)||n.push(H(`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(H(`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(H(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=si(r);oi.has(e)||n.push(H(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...oi].join(`, `)}.`,{line:t,path:`input_img`})),ci(r)||n.push(H(`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 ui={name:`image`,detect:e=>`img_path`in e,inspect:li},di=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),fi=new Set([`.mp4`,`.mov`]);function pi(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function mi(e){return/^[\x20-\x7E]+$/.test(e)}function hi(e,t,n,r,i,a){if(!(n in t)){r&&e.push(H(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(H(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(H(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=pi(o);i.has(s)||e.push(H(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),mi(o)||e.push(H(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function gi(e,t){let n=[];if(!(`prompt`in e))n.push(H(`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(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return hi(n,e,`first_frame_path`,!0,di,t),hi(n,e,`last_frame_path`,!1,di,t),hi(n,e,`video_path`,!1,fi,t),n}const _i=[ai,ui,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:gi},ri,ti,$r];function vi(e,t){return t===void 0?_i.find(t=>t.detect(e))??$r:_i.find(e=>e.name===t)||$r}async function yi(e,t){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(H(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function bi(e,t,r,i,a){let o=r?null:new Set(Yr(t)),s=[],c=0,l=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(H(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...xi(n,u,i))}return{sampled:c,issues:s}}function xi(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[H(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return vi(r,n).inspect(r,t)}const Si={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await yi(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[H(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await bi(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Ci(e,t){return new Promise((n,r)=>{b.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function wi(e){return new Promise((t,n)=>{b.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function Ti(e,t,n){let{entry:i,zipfile:a}=await Ci(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}ae(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Ei(e,t=100){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const Di={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await wi(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[H(`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:[H(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(H(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(H(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return oi.has(n)});e.length<25&&r.push(H(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${ne(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await Ti(e,m,_)}catch(t){return r.push(H(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await Si.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await Ei(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(H(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Oi(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return ki(e);if(t===`.zip`)return Ai(e);throw new N(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,M.USAGE)}async function ki(e){let t=await Mi(e);if(!t)throw new N(`JSONL file is empty or contains only blank lines: ${e}`,M.USAGE);let n=ji(t);return n===`unknown`?`text`:n}async function Ai(e){let t=await Ni(e,`data.jsonl`);if(!t)throw new N(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,M.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ji(t);if(n===`unknown`)throw new N(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,M.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ji(e){let t;try{t=JSON.parse(e)}catch{throw new N(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,M.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,M.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Mi(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=y({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Ni(e,t){return Ci(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new N(`Failed to read "${t}" from ZIP: ${e?.message}`,M.USAGE));return}let o=y({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Pi=[Si,Di];function Fi(e){let t=h(e).toLowerCase(),n=Pi.find(e=>e.extensions.includes(t));if(!n){let e=Pi.flatMap(e=>e.extensions).join(`, `);throw new N(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,M.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Ii(e){Pi.some(t=>t.format===e.format)||Pi.push(e)}async function U(e,t={}){let{bytes:n}=qr(e,t.maxBytes??314572800),r=await Fi(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Li(){return Pi.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Ri(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 zi(e,t,n){return e.requestJson({path:Ln(),method:`POST`,body:t,signal:n})}async function Bi(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=Ln(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Vi(e,t,n){return e.requestJson({path:Rn(t),method:`GET`,signal:n})}async function Hi(e,t,n){return e.requestJson({path:zn(t),method:`POST`,signal:n})}async function Ui(e,t,n){return e.requestJson({path:Rn(t),method:`DELETE`,signal:n})}async function Wi(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=Bn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Gi(e,t,n){return e.requestJson({path:Vn(t),method:`GET`,signal:n})}async function Ki(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Hn(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const qi={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`}},Ji=Object.keys(qi),Yi=`sft-lora`;function Xi(e){return e in qi}function Zi(e){let{method:t,variant:n}=qi[e];return{method:t,variant:n}}function Qi(e,t){if(!e)return!1;let{method:n,variant:r}=qi[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function $i(e){return e?Ji.filter(t=>Qi(e,t)):[]}async function ea(e,t){let n=rn(e);return(await Mr((t,r)=>on({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const ta=`INSUFFICIENT_SAMPLES`;function na(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ta,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
13
- `)}}function ra(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 ia(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return U(e,{...r,schema:n})},resolveHyperParameters(e,t){return ra(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const aa=ia(`sft`,`sft`,`chatml`),oa={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},sa={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},ca={...sa,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},la={n_epochs:400,learning_rate:`2e-5`,split:.9,max_split_val_dataset_sample:5,eval_epochs:50,save_total_limit:10,lora_rank:32,lora_alpha:32};function ua(e){return e===`image`||e===`image-i2i`}function da(e){return e===`video`||e===`video-kf2v`}function fa(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const pa=[aa,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return U(e,{...n,schema:`tts`});if(ua(t))return U(e,{...n,schema:`image`,maxBytes:Kr});if(da(t)){let r=await U(e,{...n,schema:`video`,maxBytes:Kr});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(H(`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(H(`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 U(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...oa};if(ua(e)){let n={...e===`image-i2i`?ca:sa};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(da(e)){let e=fa(t.model),n={...la,batch_size:4,max_pixels:e?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return ra(t)},shouldSkipGate(e,t){return!!((t===`audio`||ua(t)||da(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||ua(e)||da(e)}},ia(`dpo`,`dpo_full`,`dpo`),ia(`dpo-lora`,`dpo_lora`,`dpo`),ia(`cpt`,`cpt`,`cpt`)];function ma(e){let t=pa.find(t=>t.clientTrainingType===e);if(!t){let t=pa.map(e=>e.clientTrainingType).join(`, `);throw new N(`Unknown training type "${e}".`,M.USAGE,`Supported training types: ${t}.`)}return t}function ha(){return pa.map(e=>e.clientTrainingType)}async function ga(e,t,n){return e.requestJson({path:Un(),method:`POST`,body:t,signal:n})}async function _a(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=Un(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function va(e,t,n){return e.requestJson({path:Wn(t),method:`GET`,signal:n})}async function ya(e,t,n){return e.requestJson({path:Wn(t),method:`DELETE`,signal:n})}async function ba(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=qn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function xa(e,t,n,r){return e.requestJson({path:Gn(t),method:`PUT`,body:n,signal:r})}async function Sa(e,t,n,r){return e.requestJson({path:Kn(t),method:`PUT`,body:n,signal:r})}const W={LORA:`lora`,PTU:`ptu`,MU:`mu`},Ca=W.LORA;function wa(e){return e===`audio`?W.MU:Ca}const Ta={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},Ea=Ta.POST_PAY,Da={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},Oa={name:W.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},ka={name:W.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},Aa={name:W.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||Ea,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new N(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,M.USAGE);try{let a=await ba(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===W.MU)?.templates??[];if(o.length===0)throw i();let s=t===Ta.POST_PAY?Da.POST_PAID:Da.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof N?e:new N(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,M.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},ja={[W.LORA]:Oa,[W.PTU]:ka,[W.MU]:Aa};function Ma(e){let t=ja[e];if(!t)throw new N(`Unsupported plan "${e}". Supported plans: ${Object.keys(ja).join(`, `)}.`,M.USAGE);return t}const Na={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},config:{type:`string`,valueHint:`<name>`,description:`Use a config profile for this command`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},Pa={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Fa={async:{type:`switch`,description:`Return async task id without waiting`}},Ia={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},La={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},Ra={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`},securityToken:{type:`string`,valueHint:`<token>`,description:`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`}};function za(e){return e.auth===`apiKey`?Ia:e.auth===`console`?La:e.auth===`openapi`?Ra:{}}function Ba(e){return e}const Va=1;function Ha(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Ua(e,t){return`${Ha(e||`image`,`image`)}_${Ha((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Wa=()=>g(f(),`bailian-output`);function Ga(e,t){let n=t?.flagDir||e.outputDir||Wa(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Ka(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function qa(e){return o(e===`-`?0:e,`utf-8`)}async function Ja(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 Ya(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new N(`Invalid ${t} value "${String(e)}". Use true or false.`,M.USAGE)}function Xa(e,t=`boolean`){if(e!=null)return Ya(e,t)}function Za(e,t,n=`boolean`){let r=Xa(e,n);return r===void 0?t:r}function Qa(e){return Xa(e,`watermark`)??!0}function $a(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 eo(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function to(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=eo(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let G;function no(){return G||(process.env.NODE_ENV===`development`?(G=`dev`,G):process.env.BAILIAN_COMPILED===`1`?(G=`prod`,G):(G=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,G))}var ro=Ee(((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=ke(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=ke(`dns`)},function(e,t){e.exports=ke(`util`)},function(e,t){e.exports=ke(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ne=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},k=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},A=new Map,j=new Map;A.set(`Baiduspider-render`,i),A.set(`Baiduspider+`,i),A.set(`Baiduspider-image+`,i),A.set(`360Spider`,a),A.set(`360Spider-Image`,a),A.set(`bingbot`,o),A.set(`Googlebot`,s),A.set(`YandexRenderResourcesBot`,c),A.set(`spider`,l),A.set(`Dataprovider.com`,u),A.set(`AhrefsBot`,d),A.set(`BitSightBot`,f),A.set(`oBot`,p),A.set(`Cincraw`,m),A.set(`DingTalkBot-LinkService`,h),A.set(`YisouSpider`,g),A.set(`Bytespider`,_),A.set(`ev-crawler`,v),A.set(`bitdiscovery`,ee),A.set(`Spider`,te),A.set(`Ai2Bot-Dolma`,ne),A.set(`dianjing_ad_spider`,re),j.set(`Baiduspider-render`,ie),j.set(`Baiduspider+`,ie),j.set(`Baiduspider-image+`,ie),j.set(`360Spider`,y),j.set(`360Spider-Image`,y),j.set(`bingbot`,ae),j.set(`Googlebot`,b),j.set(`YandexRenderResourcesBot`,oe),j.set(`spider`,se),j.set(`Dataprovider.com`,x),j.set(`AhrefsBot`,S),j.set(`BitSightBot`,C),j.set(`oBot`,w),j.set(`Cincraw`,T),j.set(`DingTalkBot-LinkService`,ce),j.set(`YisouSpider`,E),j.set(`Bytespider`,D),j.set(`ev-crawler`,le),j.set(`bitdiscovery`,ue),j.set(`Spider`,O),j.set(`Ai2Bot-Dolma`,k),j.set(`dianjing_ad_spider`,de);let fe={productHandlerMap:A,commentHandlerMap:j,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,fe),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function ee(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}ee.prototype={constructor:ee,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var te=ee,ne=n(3),re=n.n(ne),ie=n(4),y=n(5),ae=n.n(y);function b(e){return(b=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function oe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function se(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oe(Object(n),!0).forEach(function(t){x(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function x(e,t,n){return(t=(function(e){var t=(function(e,t){if(b(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(b(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return b(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function S(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=w(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
11
+ `);r=t.pop()??``;for(let n of t){let t=Ht(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let{lines:s,rest:c}=Vt(r);r=c;for(let t of s){let n=Ht(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Ht(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{t.releaseLock()}}function Wt(e){return String(e)}var Gt=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 N(`This command needs a model-domain API key.`,M.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 N(`MCP SSE session closed.`,M.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out waiting for response headers.`,M.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 N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new N(e,M.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof N?e:new N(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,M.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=qt(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 Ut(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Kt(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=Wt(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 N(`MCP SSE stream ended before endpoint event.`,M.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let n=this.nextId++,r=Wt(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=qt(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new N(`MCP error (${e.error.code}): ${e.error.message}`,M.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 N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);if(!this.messageUrl)throw new N(`MCP SSE message endpoint is not ready.`,M.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=Jt(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 N(`MCP SSE session closed.`,M.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 N(`MCP SSE session closed.`,M.GENERAL):n.timedOut?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:t})}throw new N(e,M.GENERAL)}}finally{n.cleanup()}}};function Kt(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new N(`MCP SSE endpoint is not a valid URL: ${t}`,M.GENERAL)}if(n.origin!==r.origin)throw new N(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,M.GENERAL);return n.toString()}function qt(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new N(t,M.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Jt(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 Yt(e){return`/api/v1/mcps/${e}/mcp`}function Xt(e){return`/api/v1/mcps/${e}/sse`}function Zt(e){return e instanceof N?/^MCP request failed:\s*405\b/i.test(e.message):!1}function Qt(e){return e instanceof N?/^MCP request failed:\s*(405|404)\b/i.test(e.message):!1}async function $t(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new en(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Qt(e))throw e}let r=new Gt(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new en(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!Zt(e)||a===`WebSearch`)throw e}let c=new Gt(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var en=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=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 N(`MCP error (${a.error.code}): ${a.error.message}`,M.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 Ut(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 N(`MCP SSE response stream ended without a matching JSON-RPC response.`,M.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...B(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}};const tn={"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 nn(e,t){return tn[e]?.[t]??tn[`cn-beijing`][t]}function rn(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 an(e){let t=rn(e);return(n,r)=>sn({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function on(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 sn(e,t,{api:n,data:r},i){let a=nn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=on(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 N(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,M.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 N(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?M.AUTH:M.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var cn=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}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 Ct(this.http,this.toOpts(e))}requestJson(e){return Tt(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Rt(e)?zt(e,this.requireApi().token,t,{...n,identity:this.deps.identity}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Rt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Ft(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 en(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),$t({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Yt(e)),sseUrl:this.url(Xt(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await sn(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof N)||e.exitCode!==M.AUTH||!e.message.includes(`not logged in`))throw e;let t=await pn({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await sn({...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?Et(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Dt({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${yt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${yt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...B(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 N(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,M.GENERAL)}if(!s.ok||l.Success===!1)throw new N(`${l.Code||s.status} - ${l.Message||s.statusText}`,M.GENERAL);return l}};const ln={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function un(e){for(let[t,n]of Object.entries(Fe))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function dn(e){return ln[un(e)]??ln.cn}async function fn(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new cn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=dn(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function pn(e){let t=e.settings.configName,n=R(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
12
+ `);let a=(await fn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=R(t);return o.access_token=a,await z(o,t),a}function mn(){return`/compatible-mode/v1/chat/completions`}function hn(){return`/compatible-mode/v1/responses`}function gn(){return`/api/v1/services/aigc/image-generation/generation`}function _n(){return`/api/v1/services/aigc/multimodal-generation/generation`}function vn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function yn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function bn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function xn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Sn(){return`/api/v1/models/limits`}function Cn(){return`/api/v1/models/permissions`}function wn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Tn(){return`/api/v2/apps/memory/add`}function En(){return`/api/v2/apps/memory/memory_nodes/search`}function Dn(){return`/api/v2/apps/memory/memory_nodes`}function On(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function kn(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function An(){return`/api/v1/services/audio/asr/transcription`}function jn(){return`/api/v2/apps/memory/profile_schemas`}function Mn(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Nn(){return`/api/v1/indices/rag/index/retrieve`}function Pn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Fn(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function In(){return`/api/v1/mcps/WebSearch/mcp`}function Ln(){return`/compatible-mode/v1/files`}function Rn(){return`/api/v1/files`}function zn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Bn(){return`/api/v1/fine-tunes`}function Vn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Hn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Un(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Wn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Gn(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Kn(){return`/api/v1/deployments`}function qn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Jn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function Yn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function Xn(){return`/api/v1/deployments/models`}const Zn=[`qwen-image`,`wan2.7-image`,`z-image`],Qn=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function $n(e,t){return t.some(t=>e.startsWith(t))}function er(e){return $n(e,Zn)||e.startsWith(`wan2.6-image`)}function tr(e){return $n(e,Zn)}function nr(e){return $n(e,Qn)}function rr(e){return/^wanx-v1(?:-|$)/i.test(e)}function ir(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||tr(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||rr(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function ar(e){return/wan2\.5-i2i/i.test(e)}function or(e){return/imageedit/i.test(e)}function sr(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`:rr(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:ir(e)?`wan-legacy`:`wan26`}function cr(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function V(e,t){return{...e,sizeProfile:sr(t),promptExtendDefault:cr(t)}}function lr(e){return tr(e)?V({kind:`sync-multimodal`,path:_n(),useSync:!0,inputStyle:`messages`},e):ir(e)?V({kind:`async-text2image`,path:vn(),useSync:!1,inputStyle:`prompt`},e):V({kind:`async-image-generation`,path:gn(),useSync:!1,inputStyle:`messages`},e)}function ur(e){return nr(e)?V({kind:`sync-multimodal`,path:_n(),useSync:!0,inputStyle:`messages`},e):or(e)?V({kind:`async-image2image`,path:yn(),useSync:!1,inputStyle:`function-base-image`},e):ar(e)?V({kind:`async-image2image`,path:yn(),useSync:!1,inputStyle:`prompt-images`},e):V({kind:`async-image-generation`,path:gn(),useSync:!1,inputStyle:`messages`},e)}function dr(e){return/realtime|streaming/i.test(e)}function fr(e){return/filetrans/i.test(e)}function pr(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const mr=[`fun-asr-flash`,`qwen-audio`];function hr(e){return dr(e)||fr(e)?!1:!!(e.startsWith(mr[0])||e.startsWith(mr[1])&&/asr-flash/i.test(e))}function gr(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||fr(e)||dr(e)||hr(e))}function _r(e){if(dr(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(fr(e)){let t=pr(e);return{kind:`async-filetrans`,path:An(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return hr(e)?{kind:`sync-flash`,path:_n(),useSync:!0,flashFamily:`input-audio`}:gr(e)?{kind:`sync-flash`,path:_n(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:An(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function vr(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 yr(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function br(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,flashFamily:a}=e;if(a===`input-audio`){let e={format:vr(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 xr(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 Sr(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 Cr(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function wr(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Tr(e){return async(t,n={})=>{let r=wr(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),Cr(r))for(let[t,n]of Object.entries(B(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${yt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Er=`2024-08-16`;function Dr(e){return`bailiancontrol.${e}.aliyuncs.com`}function Or(e){return new cn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function kr(e){return Or(e).openApiJson({host:Dr(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Er,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Ar(e){return Or(e).openApiJson({host:Dr(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Er,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function jr(e){return Or(e).openApiJson({host:Dr(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Er,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const Mr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Nr=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Pr(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 Fr(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Pr(await e(Mr,{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 Ir(e,t={}){let n=t.pageSize??50,r=await Fr(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 Fr(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Lr(e,t){return(await Fr(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Rr(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=Pr(await e(Mr,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function zr(e,t){return(Pr(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 Br=[`name`,`key`,`default`,`tip`,`range`];function Vr(e){return e.map(e=>{let t={};for(let n of Br)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Hr(e,t){let n=Pr(await e(Nr,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Vr(e):null}catch{return null}return Array.isArray(n)?Vr(n):null}function Ur(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Ne(String(r)):r;await z(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await z(n,e)},profiles:()=>ut(),activate:e=>pt(e),validateActivation:e=>ft(e),get path(){return F()}}}const Wr={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function Gr(e){return e?Wr[e]:void 0}async function Kr(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:Ln(),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 N(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,M.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new N(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,M.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function qr(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=Rn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Jr(e,t,n){return e.requestJson({path:zn(t),method:`GET`,signal:n})}async function Yr(e,t,n){let r=await e.request({path:zn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Xr=300*1024*1024,Zr=1024*1024*1024;function Qr(e,t=Xr){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);let n=l(e);if(!n.isFile())throw new N(`Not a regular file: ${e}`,M.USAGE);if(n.size===0)throw new N(`File is empty: ${e}`,M.USAGE);if(n.size>t)throw new N(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,M.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function $r(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,M.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function ei(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 ti=new Set([`system`,`user`,`assistant`]);function ni(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(H(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!ti.has(a))&&r.push(H(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(H(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function ri(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(H(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(H(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...ni(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(H(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(H(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(H(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(H(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const ii={name:`chatml`,detect:()=>!0,inspect:ri};function ai(e,t){let n=[];if(!(`text`in e))return n.push(H(`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(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const oi={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ai};function si(e,t){let n=ri(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(H(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(H(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...ni(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...ni(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const ci={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:si};function li(e,t){let n=[];if(!(`wav_fn`in e))n.push(H(`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(H(`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(H(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(H(`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(H(`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(H(`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(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const ui={name:`tts`,detect:e=>`wav_fn`in e,inspect:li},di=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function fi(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function pi(e){return/^[\x20-\x7E]+$/.test(e)}function mi(e,t){let n=[];if(!(`prompt`in e))n.push(H(`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(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(H(`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(H(`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(H(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=fi(r);di.has(e)||n.push(H(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...di].join(`, `)}.`,{line:t,path:`img_path`})),pi(r)||n.push(H(`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(H(`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(H(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=fi(r);di.has(e)||n.push(H(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...di].join(`, `)}.`,{line:t,path:`input_img`})),pi(r)||n.push(H(`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 hi={name:`image`,detect:e=>`img_path`in e,inspect:mi},gi=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),_i=new Set([`.mp4`,`.mov`]);function vi(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function yi(e){return/^[\x20-\x7E]+$/.test(e)}function bi(e,t,n,r,i,a){if(!(n in t)){r&&e.push(H(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(H(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(H(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=vi(o);i.has(s)||e.push(H(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),yi(o)||e.push(H(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function xi(e,t){let n=[];if(!(`prompt`in e))n.push(H(`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(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return bi(n,e,`first_frame_path`,!0,gi,t),bi(n,e,`last_frame_path`,!1,gi,t),bi(n,e,`video_path`,!1,_i,t),n}const Si=[ui,hi,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:xi},ci,oi,ii];function Ci(e,t){return t===void 0?Si.find(t=>t.detect(e))??ii:Si.find(e=>e.name===t)||ii}async function wi(e,t){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(H(`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 Ti(e,t,r,i,a){let o=r?null:new Set(ei(t)),s=[],c=0,l=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(H(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Ei(n,u,i))}return{sampled:c,issues:s}}function Ei(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[H(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Ci(r,n).inspect(r,t)}const Di={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await wi(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[H(`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 Ti(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 Oi(e,t){return new Promise((n,r)=>{b.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function ki(e){return new Promise((t,n)=>{b.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function Ai(e,t,n){let{entry:i,zipfile:a}=await Oi(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}ae(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function ji(e,t=100){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const Mi={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await ki(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[H(`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:[H(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(H(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(H(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return di.has(n)});e.length<25&&r.push(H(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${ne(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await Ai(e,m,_)}catch(t){return r.push(H(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await Di.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await ji(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(H(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Ni(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Pi(e);if(t===`.zip`)return Fi(e);throw new N(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,M.USAGE)}async function Pi(e){let t=await Li(e);if(!t)throw new N(`JSONL file is empty or contains only blank lines: ${e}`,M.USAGE);let n=Ii(t);return n===`unknown`?`text`:n}async function Fi(e){let t=await Ri(e,`data.jsonl`);if(!t)throw new N(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,M.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Ii(t);if(n===`unknown`)throw new N(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,M.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Ii(e){let t;try{t=JSON.parse(e)}catch{throw new N(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,M.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,M.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Li(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=y({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Ri(e,t){return Oi(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new N(`Failed to read "${t}" from ZIP: ${e?.message}`,M.USAGE));return}let o=y({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const zi=[Di,Mi];function Bi(e){let t=h(e).toLowerCase(),n=zi.find(e=>e.extensions.includes(t));if(!n){let e=zi.flatMap(e=>e.extensions).join(`, `);throw new N(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,M.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Vi(e){zi.some(t=>t.format===e.format)||zi.push(e)}async function U(e,t={}){let{bytes:n}=Qr(e,t.maxBytes??314572800),r=await Bi(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Hi(){return zi.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Ui(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 Wi(e,t,n){return e.requestJson({path:Bn(),method:`POST`,body:t,signal:n})}async function Gi(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=Bn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ki(e,t,n){return e.requestJson({path:Vn(t),method:`GET`,signal:n})}async function qi(e,t,n){return e.requestJson({path:Hn(t),method:`POST`,signal:n})}async function Ji(e,t,n){return e.requestJson({path:Vn(t),method:`DELETE`,signal:n})}async function Yi(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=Un(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Xi(e,t,n){return e.requestJson({path:Wn(t),method:`GET`,signal:n})}async function Zi(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Gn(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const Qi={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`}},$i=Object.keys(Qi),ea=`sft-lora`;function ta(e){return e in Qi}function na(e){let{method:t,variant:n}=Qi[e];return{method:t,variant:n}}function ra(e,t){if(!e)return!1;let{method:n,variant:r}=Qi[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function ia(e){return e?$i.filter(t=>ra(e,t)):[]}async function aa(e,t){return await Lr(an(e),t)}const oa=`INSUFFICIENT_SAMPLES`;function sa(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:oa,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 ca(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 la(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return U(e,{...r,schema:n})},resolveHyperParameters(e,t){return ca(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const ua=la(`sft`,`sft`,`chatml`),da={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},fa={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},pa={...fa,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},ma={n_epochs:400,learning_rate:`2e-5`,split:.9,max_split_val_dataset_sample:5,eval_epochs:50,save_total_limit:10,lora_rank:32,lora_alpha:32};function ha(e){return e===`image`||e===`image-i2i`}function ga(e){return e===`video`||e===`video-kf2v`}function _a(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const va=[ua,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return U(e,{...n,schema:`tts`});if(ha(t))return U(e,{...n,schema:`image`,maxBytes:Zr});if(ga(t)){let r=await U(e,{...n,schema:`video`,maxBytes:Zr});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(H(`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(H(`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 U(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...da};if(ha(e)){let n={...e===`image-i2i`?pa:fa};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(ga(e)){let e=_a(t.model),n={...ma,batch_size:4,max_pixels:e?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return ca(t)},shouldSkipGate(e,t){return!!((t===`audio`||ha(t)||ga(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||ha(e)||ga(e)}},la(`dpo`,`dpo_full`,`dpo`),la(`dpo-lora`,`dpo_lora`,`dpo`),la(`cpt`,`cpt`,`cpt`)];function ya(e){let t=va.find(t=>t.clientTrainingType===e);if(!t){let t=va.map(e=>e.clientTrainingType).join(`, `);throw new N(`Unknown training type "${e}".`,M.USAGE,`Supported training types: ${t}.`)}return t}function ba(){return va.map(e=>e.clientTrainingType)}async function xa(e,t,n){return e.requestJson({path:Kn(),method:`POST`,body:t,signal:n})}async function Sa(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=Kn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ca(e,t,n){return e.requestJson({path:qn(t),method:`GET`,signal:n})}async function wa(e,t,n){return e.requestJson({path:qn(t),method:`DELETE`,signal:n})}async function Ta(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=Xn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ea(e,t,n,r){return e.requestJson({path:Jn(t),method:`PUT`,body:n,signal:r})}async function Da(e,t,n,r){return e.requestJson({path:Yn(t),method:`PUT`,body:n,signal:r})}const W={LORA:`lora`,PTU:`ptu`,MU:`mu`},Oa=W.LORA;function ka(e){return e===`audio`?W.MU:Oa}const Aa={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},ja=Aa.POST_PAY,Ma={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},Na={name:W.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},Pa={name:W.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},Fa={name:W.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||ja,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new N(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,M.USAGE);try{let a=await Ta(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===W.MU)?.templates??[];if(o.length===0)throw i();let s=t===Aa.POST_PAY?Ma.POST_PAID:Ma.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof N?e:new N(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,M.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},Ia={[W.LORA]:Na,[W.PTU]:Pa,[W.MU]:Fa};function La(e){let t=Ia[e];if(!t)throw new N(`Unsupported plan "${e}". Supported plans: ${Object.keys(Ia).join(`, `)}.`,M.USAGE);return t}const Ra={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},config:{type:`string`,valueHint:`<name>`,description:`Use a config profile for this command`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},za={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Ba={async:{type:`switch`,description:`Return async task id without waiting`}},Va={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},Ha={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},Ua={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`},securityToken:{type:`string`,valueHint:`<token>`,description:`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`}};function Wa(e){return e.auth===`apiKey`?Va:e.auth===`console`?Ha:e.auth===`openapi`?Ua:{}}function Ga(e){return e}const Ka=1;function qa(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Ja(e,t){return`${qa(e||`image`,`image`)}_${qa((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Ya=()=>g(f(),`bailian-output`);function Xa(e,t){let n=t?.flagDir||e.outputDir||Ya(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Za(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Qa(e){return o(e===`-`?0:e,`utf-8`)}async function $a(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 eo(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new N(`Invalid ${t} value "${String(e)}". Use true or false.`,M.USAGE)}function to(e,t=`boolean`){if(e!=null)return eo(e,t)}function no(e,t,n=`boolean`){let r=to(e,n);return r===void 0?t:r}function ro(e){return to(e,`watermark`)??!0}function io(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 ao(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function oo(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=ao(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let G;function so(){return G||(process.env.NODE_ENV===`development`?(G=`dev`,G):process.env.BAILIAN_COMPILED===`1`?(G=`prod`,G):(G=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,G))}var co=Ee(((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=ke(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=ke(`dns`)},function(e,t){e.exports=ke(`util`)},function(e,t){e.exports=ke(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ne=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},k=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},A=new Map,j=new Map;A.set(`Baiduspider-render`,i),A.set(`Baiduspider+`,i),A.set(`Baiduspider-image+`,i),A.set(`360Spider`,a),A.set(`360Spider-Image`,a),A.set(`bingbot`,o),A.set(`Googlebot`,s),A.set(`YandexRenderResourcesBot`,c),A.set(`spider`,l),A.set(`Dataprovider.com`,u),A.set(`AhrefsBot`,d),A.set(`BitSightBot`,f),A.set(`oBot`,p),A.set(`Cincraw`,m),A.set(`DingTalkBot-LinkService`,h),A.set(`YisouSpider`,g),A.set(`Bytespider`,_),A.set(`ev-crawler`,v),A.set(`bitdiscovery`,ee),A.set(`Spider`,te),A.set(`Ai2Bot-Dolma`,ne),A.set(`dianjing_ad_spider`,re),j.set(`Baiduspider-render`,ie),j.set(`Baiduspider+`,ie),j.set(`Baiduspider-image+`,ie),j.set(`360Spider`,y),j.set(`360Spider-Image`,y),j.set(`bingbot`,ae),j.set(`Googlebot`,b),j.set(`YandexRenderResourcesBot`,oe),j.set(`spider`,se),j.set(`Dataprovider.com`,x),j.set(`AhrefsBot`,S),j.set(`BitSightBot`,C),j.set(`oBot`,w),j.set(`Cincraw`,T),j.set(`DingTalkBot-LinkService`,ce),j.set(`YisouSpider`,E),j.set(`Bytespider`,D),j.set(`ev-crawler`,le),j.set(`bitdiscovery`,ue),j.set(`Spider`,O),j.set(`Ai2Bot-Dolma`,k),j.set(`dianjing_ad_spider`,de);let fe={productHandlerMap:A,commentHandlerMap:j,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,fe),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function ee(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}ee.prototype={constructor:ee,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var te=ee,ne=n(3),re=n.n(ne),ie=n(4),y=n(5),ae=n.n(y);function b(e){return(b=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function oe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function se(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oe(Object(n),!0).forEach(function(t){x(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function x(e,t,n){return(t=(function(e){var t=(function(e,t){if(b(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(b(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return b(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function S(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=w(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
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 C(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||w(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
15
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function w(e,t){if(e){if(typeof e==`string`)return T(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}function T(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ce(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=C(r[n],2),o=(a[0],a[1]);if(o){var s,c=S(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 E,D,le=(E=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:E,device_id:ae.a.createHash(`md5`).update(ce()).digest(`hex`),platform:`node`}),ue=(0,ie.promisify)(re.a.resolve);function O(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,te.call(this,se(se({},le),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}O.prototype=((D=function(){}).prototype=te.prototype,new D),O.prototype.constructor=O,O.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,ue(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=O}]).default})),io=Ee(((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})),ao=Oe(ro(),1),oo=Oe(io(),1);const so=()=>g(P(),`telemetry.jsonl`);let co;const lo=new Set;let uo;try{let e=new ao.default({pid:`bailian-cli-node`,env:no()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;lo.add(e),e.finally(()=>lo.delete(e))}return n},uo=e,co=e.use(oo.default)}catch{}async function fo(e=1e3){try{if(uo)try{typeof uo._sendAll==`function`&&uo._sendAll()}catch{}if(lo.size===0)return;let t=[...lo].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function po(e){try{await Qe();let n=so();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
16
- `,{mode:384})}catch{}}async function mo(e){try{if(!co)return;co(e.command,to(e))}catch{}}const ho=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),go=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 _o(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||ho.has(n)||go.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function vo(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof N?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=$a({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:_o(n)});po(l).catch(()=>{}),mo(l).catch(()=>{})}}function yo(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 bo=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=rn(this.settings),t=(t,n)=>on({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await Mr(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await Mr(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(yo).filter(e=>e!==null)}};function xo(){return A(P(),`skills/bailian-docs-llm-wiki`)}function So(){return A(xo(),`models`,`models.jsonl`)}function Co(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 wo(e){let t=w(e,`utf-8`).split(`
17
- `).filter(Boolean),n=[];for(let e of t)try{let t=Co(JSON.parse(e));t&&n.push(t)}catch{}return n}var To=class{name=`catalog`;constructor(e){}available(){return x(So())}async load(){return this.available()?wo(So()):[]}};async function Eo(e,t){let n=[new To({onPrepareStart:t?.onPrepareStart}),new bo(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new N(`No model data available.`,M.GENERAL)}const Do={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},K={Single:`single`,Pipeline:`pipeline`},Oo={Low:`low`,Medium:`medium`,High:`high`},ko={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},q={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},J={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},Ao={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Y={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},jo=20,Mo=/-\d{4}-\d{2}-\d{2}$/,No=new Set([J.IG,J.VG,J.TTS,J.RealtimeTTS,J.ThreeDGeneration]),Po=new Set([J.TG,J.Reasoning,J.ASR,J.RealtimeASR,J.RealtimeAudioTranslate,J.TR,J.ME]),Fo={standard:0,large:32e3,"extra-large":128e3},Io=.4,Lo=.6,Ro=.4,zo=.2,Bo=.2,Vo=.2;console.assert(Math.abs(Io+Lo-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Ro+zo+Bo+Vo-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Ho=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
15
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function w(e,t){if(e){if(typeof e==`string`)return T(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}function T(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ce(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=C(r[n],2),o=(a[0],a[1]);if(o){var s,c=S(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 E,D,le=(E=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:E,device_id:ae.a.createHash(`md5`).update(ce()).digest(`hex`),platform:`node`}),ue=(0,ie.promisify)(re.a.resolve);function O(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,te.call(this,se(se({},le),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}O.prototype=((D=function(){}).prototype=te.prototype,new D),O.prototype.constructor=O,O.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,ue(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=O}]).default})),lo=Ee(((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=Oe(co(),1),fo=Oe(lo(),1);const po=()=>g(P(),`telemetry.jsonl`);let mo;const ho=new Set;let go;try{let e=new uo.default({pid:`bailian-cli-node`,env:so()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;ho.add(e),e.finally(()=>ho.delete(e))}return n},go=e,mo=e.use(fo.default)}catch{}async function _o(e=1e3){try{if(go)try{typeof go._sendAll==`function`&&go._sendAll()}catch{}if(ho.size===0)return;let t=[...ho].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function vo(e){try{await Qe();let n=po();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
16
+ `,{mode:384})}catch{}}async function yo(e){try{if(!mo)return;mo(e.command,oo(e))}catch{}}const bo=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),xo=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 So(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||bo.has(n)||xo.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function Co(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof N?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=io({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:So(n)});vo(l).catch(()=>{}),yo(l).catch(()=>{})}}function wo(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 To=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await Ir(an(this.settings))).map(wo).filter(e=>e!==null)}};function Eo(){return A(P(),`skills/bailian-docs-llm-wiki`)}function Do(){return A(Eo(),`models`,`models.jsonl`)}function Oo(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 ko(e){let t=w(e,`utf-8`).split(`
17
+ `).filter(Boolean),n=[];for(let e of t)try{let t=Oo(JSON.parse(e));t&&n.push(t)}catch{}return n}var Ao=class{name=`catalog`;constructor(e){}available(){return x(Do())}async load(){return this.available()?ko(Do()):[]}};async function jo(e,t){let n=[new Ao({onPrepareStart:t?.onPrepareStart}),new To(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new N(`No model data available.`,M.GENERAL)}const Mo={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},K={Single:`single`,Pipeline:`pipeline`},No={Low:`low`,Medium:`medium`,High:`high`},Po={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},q={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},J={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},Fo={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Y={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Io=20,Lo=/-\d{4}-\d{2}-\d{2}$/,Ro=new Set([J.IG,J.VG,J.TTS,J.RealtimeTTS,J.ThreeDGeneration]),zo=new Set([J.TG,J.Reasoning,J.ASR,J.RealtimeASR,J.RealtimeAudioTranslate,J.TR,J.ME]),Bo={standard:0,large:32e3,"extra-large":128e3},Vo=.4,Ho=.6,Uo=.4,Wo=.2,Go=.2,Ko=.2;console.assert(Math.abs(Vo+Ho-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Uo+Wo+Go+Ko-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const qo=`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"]}]}]}`,Uo=`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's need has been decomposed into multi-step pipeline. Select the best model for each step.
58
+ {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Jo=`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"]}]}`,Wo={complexity:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[J.TG],requiredFeatures:[],budget:Oo.Medium,contextNeed:ko.Standard,qualityPreference:q.Balanced,confidence:0},Go=[`unconstrained`,`scoped`,`comparison`,`alternative`];function Ko(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Go.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 qo(e,t){let n=pn(),r={model:`qwen3.6-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
97
+ ["key highlights"]}]}`,Yo={complexity:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[J.TG],requiredFeatures:[],budget:No.Medium,contextNeed:Po.Standard,qualityPreference:q.Balanced,confidence:0},Xo=[`unconstrained`,`scoped`,`comparison`,`alternative`];function Zo(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Xo.includes(e.mode)?e.mode:`unconstrained`,n=Array.isArray(e.targets)?e.targets.filter(e=>typeof e==`string`):[],r=Array.isArray(e.excludes)?e.excludes.filter(e=>typeof e==`string`):[];return{mode:t,targets:n.length>0?n:void 0,excludes:r.length>0?r:void 0}}async function Qo(e,t){let n=mn(),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{...Wo}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Wo};let o=JSON.parse(a[0]),s=o.modelPreference,c=Ko(s);return{complexity:o.complexity===K.Pipeline?K.Pipeline:K.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Wo.budget,contextNeed:o.contextNeed??Wo.contextNeed,qualityPreference:o.qualityPreference??Wo.qualityPreference,confidence:1,modelPreference:c}}function Jo(e){let t=!1,n=!1;for(let r of e)No.has(r)&&(t=!0),Po.has(r)&&(n=!0);return t&&n}function Yo(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Mo,``);return n===e?!0:!t.has(n)})}function Xo(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 Zo(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Qo(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=Fo[i];return d>0&&(c??0)>=d&&(u+=8),a===q.Flagship&&l===Y.Flagship||a===q.CostOptimized&&l===Y.CostOptimized?u+=15:a===q.Balanced&&l===Y.Flagship&&(u+=5),u}function $o(e,t,n){return e.map(e=>({model:e,score:Qo(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function es(e){return new Set(e.map(({model:e})=>e.model))}function ts(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 ns(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function rs(e,t,n){return n.size>=10?[]:$o(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function is(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:ko.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Xo(e,a,o)&&Zo(e,n));return l.length<5&&(l=e.filter(e=>Xo(e,a,o))),l.length<5&&(l=e),$o(l,c,5)}function as(e,t){e=Yo(e);let n;if(t.complexity===K.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=ns(is(e,i,a,t.budget,t.qualityPreference),es(r));r=[...r,...o]}let i=rs(e,t,es(r));n=[...r,...i]}else if(Jo(t.requiredCapabilities))n=os(e,t);else{let r=e.filter(e=>Xo(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=$o(r,t,50)}return ts(n,3)}function os(e,t){let n=t.requiredCapabilities.filter(e=>No.has(e)),r=t.requiredCapabilities.filter(e=>Po.has(e)),i=[];if(n.length>0&&(i=$o(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=es(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...$o(o,a,25)]}let a=rs(e,t,es(i));return[...i,...a]}const ss=`text-embedding-v4`;function cs(){return A(P(),`skills/bailian-docs-llm-wiki`)}function ls(){return A(cs(),`models-embeddings.json`)}function us(){let e=ls();if(!x(e))return null;try{return JSON.parse(w(e,`utf-8`)).items}catch{return null}}async function ds(e,t){let n={model:ss,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 fs(e,t){let n={model:ss,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 ps={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},ms={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function hs(){let e=A(cs(),`groups`),t=new Map;if(!x(e))return t;for(let n of T(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(w(A(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 gs(e,t){let n=(e.capabilities??[]).map(e=>ps[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>ms[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>ms[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 _s(e,t){let n=hs(),r=t.map(e=>gs(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await fs(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:ss,dimensions:512,count:a.length,items:a},s=ls();return C(k(s),{recursive:!0}),O(s,JSON.stringify(o)),a}function vs(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 ys=null;function bs(){return ys===null&&(ys=us()),ys}function xs(){return bs()!==null}function Ss(e){return(e??``).toLowerCase().replace(Mo,``).replace(/[\s_-]+/g,``).trim()}function Cs(e,t){let n=Ss(t);if(!n)return!1;if(Ss(e.model)===n||Ss(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&Ss(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=Ss(e);return t.length>0&&n.includes(t)})}function ws(e,t){return t.some(t=>Cs(e,t))}function Ts(e,t){return t.length===0?[]:e.filter(e=>ws(e,t))}function Es(e,t){return t.length===0?e:e.filter(({model:e})=>!ws(e,t))}function Ds(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 Os(e,t){return Ds(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function ks(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=Fo[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===q.Flagship?u=e.category===Y.Flagship?1:.5:a===q.CostOptimized&&(u=e.category===Y.CostOptimized?1:.5),Ro*o+zo*s+Bo*c+Vo*u}function As(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Os(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function js(e,t){return Ds(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Ms(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=vs(t,e.vector),o=a?ks(n,a):0;return[{model:n,score:a?Io*o+Lo*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 Ns(e){return{model:e,score:1,hardScore:1,softScore:1}}function Ps(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?Ts(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Ns(e));let r=new Set(l.map(({model:e})=>e.model)),s=Ms(t,n,As(e,o),i,a,o);for(let e of s)if(!r.has(e.model.model)&&(l.push(e),l.length>=i))break;return l}return Ms(t,n,As(c,o),i,a,o)}function Fs(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)ws(t,s)&&!l.has(t.model)&&(c.push(Ns(t)),l.add(t.model));return c}function Is(e,t,n,r,i,a,o){let s=Ts(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Ns(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Ms(t,n,As(e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),o),d,a,o);for(let e of r)l.push(e)}return l}async function Ls(e,t,n,r,i){let a=bs();if(!a)a=await _s(e,t),ys=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 _s(e,t),ys=a)}let o=await ds(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=Ps(t,a,o,c,r,s,i);break;case`comparison`:e=Fs(t,a,o,c,r,s,i);break;case`alternative`:e=Is(t,a,o,c,r,s,i);break;default:e=[]}return Es(e,l)}if(i?.complexity===K.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>js(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Ms(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 Es(n,l)}let u=As(t,i);return Es(Ms(a,o,u,r,s,i),l)}function Rs(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function zs(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=Rs(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
145
- `)}function Bs(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!==ko.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 Vs(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 Hs(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 Us(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 Ws(e,t,n,r,i,a){let o=zs(t),s=Bs(n),c=n.modelPreference?.mode,l;if(c===`comparison`)l=`You are a model comparison advisor for Alibaba Cloud Model Studio. The user wants to compare specific models — analyze them against the use case.
144
+ Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0},i;try{i=await e.requestJson({path:n,method:`POST`,body:r,timeout:30})}catch{return{...Yo}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Yo};let o=JSON.parse(a[0]),s=o.modelPreference,c=Zo(s);return{complexity:o.complexity===K.Pipeline?K.Pipeline:K.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Yo.budget,contextNeed:o.contextNeed??Yo.contextNeed,qualityPreference:o.qualityPreference??Yo.qualityPreference,confidence:1,modelPreference:c}}function $o(e){let t=!1,n=!1;for(let r of e)Ro.has(r)&&(t=!0),zo.has(r)&&(n=!0);return t&&n}function es(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Lo,``);return n===e?!0:!t.has(n)})}function ts(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 ns(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function rs(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=Bo[i];return d>0&&(c??0)>=d&&(u+=8),a===q.Flagship&&l===Y.Flagship||a===q.CostOptimized&&l===Y.CostOptimized?u+=15:a===q.Balanced&&l===Y.Flagship&&(u+=5),u}function is(e,t,n){return e.map(e=>({model:e,score:rs(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function as(e){return new Set(e.map(({model:e})=>e.model))}function os(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 ss(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function cs(e,t,n){return n.size>=10?[]:is(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:K.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:Po.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>ts(e,a,o)&&ns(e,n));return l.length<5&&(l=e.filter(e=>ts(e,a,o))),l.length<5&&(l=e),is(l,c,5)}function us(e,t){e=es(e);let n;if(t.complexity===K.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=ss(ls(e,i,a,t.budget,t.qualityPreference),as(r));r=[...r,...o]}let i=cs(e,t,as(r));n=[...r,...i]}else if($o(t.requiredCapabilities))n=ds(e,t);else{let r=e.filter(e=>ts(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=is(r,t,50)}return os(n,3)}function ds(e,t){let n=t.requiredCapabilities.filter(e=>Ro.has(e)),r=t.requiredCapabilities.filter(e=>zo.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=as(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=cs(e,t,as(i));return[...i,...a]}const fs=`text-embedding-v4`;function ps(){return A(P(),`skills/bailian-docs-llm-wiki`)}function ms(){return A(ps(),`models-embeddings.json`)}function hs(){let e=ms();if(!x(e))return null;try{return JSON.parse(w(e,`utf-8`)).items}catch{return null}}async function gs(e,t){let n={model:fs,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 _s(e,t){let n={model:fs,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 vs={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},ys={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function bs(){let e=A(ps(),`groups`),t=new Map;if(!x(e))return t;for(let n of T(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(w(A(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 xs(e,t){let n=(e.capabilities??[]).map(e=>vs[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>ys[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>ys[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 Ss(e,t){let n=bs(),r=t.map(e=>xs(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await _s(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:fs,dimensions:512,count:a.length,items:a},s=ms();return C(k(s),{recursive:!0}),O(s,JSON.stringify(o)),a}function Cs(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 ws=null;function Ts(){return ws===null&&(ws=hs()),ws}function Es(){return Ts()!==null}function Ds(e){return(e??``).toLowerCase().replace(Lo,``).replace(/[\s_-]+/g,``).trim()}function Os(e,t){let n=Ds(t);if(!n)return!1;if(Ds(e.model)===n||Ds(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&Ds(r.slice(i+1))===n?!0:[e.family,e.familyName].some(e=>{if(!e)return!1;let t=Ds(e);return t.length>0&&n.includes(t)})}function ks(e,t){return t.some(t=>Os(e,t))}function As(e,t){return t.length===0?[]:e.filter(e=>ks(e,t))}function js(e,t){return t.length===0?e:e.filter(({model:e})=>!ks(e,t))}function Ms(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 Ns(e,t){return Ms(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Ps(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=Bo[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===q.Flagship?u=e.category===Y.Flagship?1:.5:a===q.CostOptimized&&(u=e.category===Y.CostOptimized?1:.5),Uo*o+Wo*s+Go*c+Ko*u}function Fs(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Ns(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function Is(e,t){return Ms(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Ls(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=Cs(t,e.vector),o=a?Ps(n,a):0;return[{model:n,score:a?Vo*o+Ho*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 Rs(e){return{model:e,score:1,hardScore:1,softScore:1}}function zs(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?As(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Rs(e));let r=new Set(l.map(({model:e})=>e.model)),s=Ls(t,n,Fs(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 Ls(t,n,Fs(c,o),i,a,o)}function Bs(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)ks(t,s)&&!l.has(t.model)&&(c.push(Rs(t)),l.add(t.model));return c}function Vs(e,t,n,r,i,a,o){let s=As(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Rs(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Ls(t,n,Fs(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 Hs(e,t,n,r,i){let a=Ts();if(!a)a=await Ss(e,t),ws=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 Ss(e,t),ws=a)}let o=await gs(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=zs(t,a,o,c,r,s,i);break;case`comparison`:e=Bs(t,a,o,c,r,s,i);break;case`alternative`:e=Vs(t,a,o,c,r,s,i);break;default:e=[]}return js(e,l)}if(i?.complexity===K.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>Is(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Ls(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 js(n,l)}let u=Fs(t,i);return js(Ls(a,o,u,r,s,i),l)}function Us(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Ws(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=Us(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
145
+ `)}function Gs(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!==Po.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 Ks(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 qs(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 Js(e,t){for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n],a=new Set(r.recommendations.flatMap(e=>t.get(e.model)?.inferenceMetadata?.response_modality??[]));if(a.size===0)continue;let o=[];for(let e of i.recommendations){let n=t.get(e.model)?.inferenceMetadata?.request_modality??[];!n.some(e=>a.has(e))&&n.length>0&&o.push(`${e.name}'s input modalities [${n.join(`, `)}] may not be compatible with the previous step's output modalities [${[...a].join(`, `)}]`)}o.length>0&&(i.warnings=o)}}async function Ys(e,t,n,r,i,a){let o=Ws(t),s=Gs(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===K.Pipeline?Uo:Ho)+e}else l=n.complexity===K.Pipeline?Uo:Ho;let u=a?.enableThinking??!1,d=n.complexity===K.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=pn(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Ut(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await e.requestJson({path:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:K.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===K.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=Hs(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Us(e,g),{type:K.Pipeline,summary:h.summary??``,steps:e}}let _=Hs(h.recommendations??h??[],g,i);return{type:K.Single,recommendations:_}}function X(){return A(P(),`skills`)}function Gs(){return A(X(),`skill-lock.json`)}function Ks(){return{version:1,skills:{}}}function qs(){let e=Gs();if(!x(e))return Ks();try{let t=JSON.parse(w(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?Ks():t}catch{return Ks()}}function Js(e){C(X(),{recursive:!0}),O(Gs(),JSON.stringify(e,null,2)+`
189
- `)}function Ys(e,t){let n=qs();n.skills[e]={...n.skills[e],...t},Js(n)}function Xs(){let e=pe(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||A(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:A(e,r,`skills`),detectDirs:[A(e,r)]}),i=(t,n)=>t?.trim()||A(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:A(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>A(e,t)),s=o.find(e=>x(e))??o[0],c=[A(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(A(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(A(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:A(e,`.agents`,`skills`),detectDirs:[A(e,`.agents`),A(e,`.cline`),A(e,`.dexto`),A(e,`.firebender`),A(e,`.kimi-code`),A(e,`.kimi`),A(e,`.loaf`),A(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:A(n,`agents`,`skills`),detectDirs:[A(n,`agents`),A(n,`amp`),A(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:A(e,`.astrbot`,`data`,`skills`),detectDirs:[A(t,`data`,`skills`),A(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:A(e,`.codebuddy`,`skills`),detectDirs:[A(t,`.codebuddy`),A(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:A(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:A(e,`.continue`,`skills`),detectDirs:[A(t,`.continue`),A(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:A(e,`.deepagents`,`agent`,`skills`),detectDirs:[A(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:A(n,`devin`,`skills`),detectDirs:[A(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:A(n,`goose`,`skills`),detectDirs:[A(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:A(e,`.jazz`,`skills`),detectDirs:[A(e,`.jazz`),A(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:A(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[A(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:A(e,`.minimax`,`skills`),detectDirs:[A(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:A(n,`opencode`,`skills`),detectDirs:[A(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:A(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:A(e,`.tabnine`,`agent`,`skills`),detectDirs:[A(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:A(e,`.zcode`,`skills`),detectDirs:[A(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Z(){return Xs().filter(e=>e.detectDirs.some(e=>x(e)))}function Zs(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function Qs(e){let t=X();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+fe)}return e===t||e.startsWith(t+fe)}function $s(e){try{if(!S(e).isSymbolicLink())return!1;let t=ce(e);return Qs(de(t)?t:j(k(e),t))}catch{return!1}}function ec(e,t){if(!t.some(t=>Zs(t,e)))return!1;try{return S(e).isDirectory()}catch{return!1}}const tc=`existing file/dir not managed by bl skill`;function nc(e,t=Z(),n=[]){let r=A(X(),e),i=[];for(let a of t){let t=A(a.skillsDir,e);try{let e=!1;try{S(t),e=!0}catch{}if(e)if($s(t))D(t);else if(ec(t,n))D(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:tc});continue}C(a.skillsDir,{recursive:!0});try{ue(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{oe(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=Z(),n=[]){let r=nc(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===tc).map(e=>e.path),s=n.filter(e=>!a.some(t=>Zs(t,e))&&!o.some(t=>Zs(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function ic(e,t=[]){let n=[],r=new Set(t);for(let t of Xs())r.add(A(t.skillsDir,e));for(let e of r)try{let r;try{r=S(e)}catch{continue}r.isSymbolicLink()?$s(e)&&(D(e),n.push(e)):t.some(t=>Zs(t,e))&&(D(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function ac(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function oc(e,t){let n=ve.extract();n.on(`entry`,(e,r,i)=>{if(!ac(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=A(t,e.name);if(e.type===`directory`){C(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}C(k(a),{recursive:!0});let o=se(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await ge(he.from(e),_e(),n)}function sc(e){let t=[],n=r=>{for(let i of T(r?A(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=me(`sha256`);for(let n of t)r.update(n),r.update(w(A(e,n)));return`sha256:${r.digest(`hex`)}`}function cc(e,t){C(k(t),{recursive:!0});let n=`${t}.old-${Date.now()}`;x(t)&&E(t,n);try{E(e,t)}catch(e){throw x(n)&&!x(t)&&E(n,t),e}x(n)&&D(n,{recursive:!0,force:!0})}function lc(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function uc(e=1e4){let t=`${lc()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new N(`Cannot access skill registry: ${t}`,M.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new N(`Skill registry returned HTTP ${n.status}: ${t}`,M.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 N(`Skill index index.json is not valid JSON`,M.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 N(`Skill index index.json has invalid structure`,M.GENERAL,`Retry later or contact the publisher`);return i}const dc=/^sha256-[0-9a-f]{64}\.tar\.br$/;function fc(e){let t=e?.object;return t&&dc.test(t)?t:`skill.tar.br`}async function pc(e,t){let n=`${lc()}/${e}/${fc(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new N(`Failed to download skill ${e}: ${n}`,M.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new N(`Failed to download skill ${e}: HTTP ${r.status}`,M.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 mc(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function hc(e){return e.length>0&&mc(e)===e}function Q(e,t){throw new N(`Skill ${e} validation failed: ${t}`,M.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function gc(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=A(e,`SKILL.md`),r;try{le(n).isFile()||Q(t,`SKILL.md is not a regular file`),r=w(n,`utf-8`)}catch(e){if(e instanceof N)throw e;Q(t,`missing SKILL.md`)}let i=gc(r);i===null&&Q(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{Q(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&Q(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)&&Q(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function vc(e){if(!hc(e))throw new N(`Invalid skill name: ${e}`,M.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function yc(e,t,n){vc(e);let r=X(),i=A(r,e),a=A(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(C(a,{recursive:!0}),await oc(t,a),n?.startsWith(`sha256:`)){let t=sc(a);if(t!==n)throw new N(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,M.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=_c(a,e);return cc(a,i),{name:e,path:i,meta:r}}finally{x(a)&&D(a,{recursive:!0,force:!0})}}async function bc(e,t){if(t.compression&&t.compression!==`tar.br`)throw new N(`Skill ${e} uses unsupported compression format: ${t.compression}`,M.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return yc(e,await pc(e,t),t.contentHash)}function xc(e){vc(e);let t=A(X(),e);return x(t)?(D(t,{recursive:!0,force:!0}),!0):!1}function Sc(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 Cc(e,t,n=Z(),r=[]){await bc(e,t);let i=rc(e,n,r);return{lockEntry:Sc(t,i.links),linkedAgents:i.linkedAgents}}const $=`bailian-docs-llm-wiki`;function wc(){return A(P(),`skills/bailian-docs-llm-wiki`)}function Tc(){return x(A(wc(),`models`,`models.jsonl`))}function Ec(){return A(P(),`wiki-sync-state.json`)}function Dc(){try{return JSON.parse(w(Ec(),`utf-8`))}catch{return null}}function Oc(e){try{O(Ec(),JSON.stringify(e))}catch{}}function kc(e){try{Ys($,e)}catch{}}function Ac(e){try{let t=qs().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function jc(){try{return(await uc(3e3)).skills[$]??null}catch{return null}}async function Mc(){let e=Dc(),t=Date.now();if(e&&t-e.lastChecked<432e5&&Tc())return!1;let n=await jc();if(!n?.contentHash)return!1;if(Tc()&&(!e||e.contentHash===n.contentHash)){if(Oc({lastChecked:t,contentHash:n.contentHash}),Ac(n.contentHash)){let e=qs().skills[$]?.links??[];kc(Sc(n,rc($,Z(),e).links))}return!1}try{let e=qs().skills[$]?.links??[];kc((await Cc($,n,Z(),e)).lockEntry)}catch{return!1}return Oc({lastChecked:t,contentHash:n.contentHash}),!0}const Nc=`bailian-cli`,Pc=`install-method`,Fc=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function Ic(e){return e?A(P(),`${Pc}.${e}`):A(P(),Pc)}function Lc(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function Rc(e){if(!e)return null;let t=e.trim().toLowerCase();return Fc.has(t)?t:null}function zc(e){try{return Rc(w(e,`utf-8`).split(`
190
- `)[0])}catch{return null}}function Bc(){let e=Rc(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Lc()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Vc(e){let t=Rc(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=zc(Ic(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=zc(Ic());if(e)return e}return Bc()}return zc(Ic())||Bc()}function Hc(e){let t=Vc(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function Uc(e,t={clientName:Nc}){try{let n=P();x(n)||C(n,{recursive:!0,mode:448}),O(Ic(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&O(Ic(),`${e}\n`,{mode:384})}catch{}}const Wc=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Gc=`https://github.com/modelstudioai/cli/releases`,Kc=`https://bailian.aliyun.com/cli/install.sh`,qc=`https://bailian.aliyun.com/cli/install.ps1`;function Jc(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):Wc}function Yc(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${Jc()}/manifest.json`:`${Jc()}/${t}.json`}function Xc(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${Jc()}/${n}/${t}`}function Zc(){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 Qc(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function $c(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function el(e){return new Promise((t,n)=>{b.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??Error(`Failed to open zip: ${e}`));return}t(i)})})}function tl(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function nl(e,t,n){let r=await el(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=tl(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 ye(k(t),{recursive:!0}),await ge(r,se(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function rl(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new Ae(`--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 Ae(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function il(){let e=X();return x(e)?T(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return le(A(e,t)).isDirectory()}catch{return!1}}):[]}function al(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{Fa as ASYNC_FLAG,Le as BAILIAN_HOST,Ta as BILLING_METHOD,Nc as BINARY_PRODUCT_CLIENT_NAME,N as BailianError,Oo as Budgets,bt as CHANNEL,Da as CHARGE_TYPE,Va as COMMAND_PACK_API_VERSION,Pa as CONCURRENT_FLAG,Re as CONFIG_FILE_KEYS,La as CONSOLE_AUTH_FLAGS,J as Capabilities,sn as Client,K as Complexities,ko as ContextNeeds,Ea as DEFAULT_BILLING_METHOD,Wc as DEFAULT_CLI_CDN_BASE,Ca as DEFAULT_DEPLOY_PLAN,qc as DEFAULT_INSTALL_PS1_URL,Kc as DEFAULT_INSTALL_SCRIPT_URL,Yi as DEFAULT_TRAINING_TYPE,W as DEPLOY_PLAN,Ie as DOCS_HOSTS,M as ExitCode,Ao as Features,Gc as GITHUB_RELEASES_BASE,Na as GLOBAL_FLAGS,ta as INSUFFICIENT_SAMPLES_CODE,Gr as MAX_DATASET_BYTES,Kr as MAX_MEDIA_ZIP_BYTES,Ia as MODEL_AUTH_FLAGS,kr as MODEL_LIST_API,en as McpClient,Do as Modalities,Y as ModelCategories,Ra as OPENAPI_AUTH_FLAGS,Ar as PREDICT_CONFIG_API,q as QualityPreferences,Fe as REGIONS,jo as SEMANTIC_TOP_K,ja as STRATEGIES,Ji as TRAINING_TYPES_CLI,qi as TRAINING_TYPE_MAP,Ae as UsageError,pt as activateConfigProfile,qo as analyzeIntent,xn as appCompletionPath,cc as atomicSwap,Yt as bailianMcpPath,Xt as bailianMcpSsePath,Qc as binaryAssetFileName,$c as binaryInnerFileName,Et as buildAcsCanonicalQuery,_r as buildAsrFlashRequest,gr as buildAsyncAsrLanguageFields,Vs as buildDocLink,gt as buildSettings,Sc as buildSkillLockEntry,ht as buildSources,on as callConsoleGateway,Hi as cancelFineTune,Yc as channelManifestUrl,pn as chatPath,yr as collectAsrTranscriptionItems,sc as computeDirContentHash,al as computeSkillStatuses,$t as connectBailianMcpWithFallback,Er as createBailianControlUser,ga as createDeployment,zi as createFineTune,Sr as createInstrumentedFetch,$a as createTrackingEvent,za as credentialFlagDefs,wa as defaultDeployPlan,Ba as defineCommand,mt as deleteConfigProfile,Wr as deleteDataset,ya as deleteDeployment,Ui as deleteFineTune,Xe as describeAuthState,Zc as detectBinaryPlatform,Bc as detectInstallMethod,Z as detectInstalledAgents,Oi as detectModality,nt as detectOutputFormat,pc as downloadSkillAsset,rn as effectiveConsoleGatewayConfig,Ks as emptySkillLock,Qe as ensureConfigDir,Ki as exportCheckpoint,vr as extractAsrFlashText,oc as extractTarBr,nl as extractZipEntryToFile,rc as fanOutSkillToAgents,ea as fetchModelCapability,Pr as fetchModelDetail,Nr as fetchModelGroups,Mr as fetchModelList,Lr as fetchPredictConfig,uc as fetchSkillsIndex,fo as flushTelemetry,tt as formatErrorJson,Ri as formatIssue,et as formatJson,rt as formatOutput,$e as formatText,dn as generateCLIAccessToken,Ua as generateFilename,Xs as getAgentTargets,Jc as getCliCdnBase,P as getConfigDir,F as getConfigPath,Ze as getCredentialsPath,Ur as getDataset,va as getDeployment,Vi as getFineTune,Wi as getFineTuneLogs,Vc as getInstallMethod,Br as getModelProfilePreset,Eo as getModels,ma as getProfile,Gs as getSkillLockPath,lc as getSkillRegistryBaseUrl,X as getSkillsDir,Hc as getUpdateInstallMethod,vn as image2ImagePath,Ft as imageFileToDataUri,hn as imagePath,gn as imageSyncPath,_n as imageText2ImagePath,hr as inferAudioFormatHint,bc as installSkill,yc as installSkillFromBuffer,Cc as installSkillWithFanout,Lc as isCompiledBinary,nr as isLegacyImage2ImageModel,tr as isLegacyText2ImageModel,Rt as isLocalFile,ac as isSafeEntryName,hc as isSafeSkillName,xs as isSemanticAvailable,Zt as isStreamableHttpUnsupported,Zn as isSyncMultimodalImageModel,Xi as isTrainingTypeCli,Qt as isUrlOverrideSseFallbackCandidate,rr as isWanxFunctionImageEditModel,Mn as knowledgeChatEndpoint,An as knowledgeRetrievePath,jn as knowledgeSearchEndpoint,nc as linkSkillToAgents,Dr as listBailianControlWorkspaces,Gi as listCheckpoints,Hr as listDatasets,ba as listDeployableModels,_a as listDeployments,Bi as listFineTunes,il as listSkillDirsOnDisk,Li as listSupportedFormats,$i as listSupportedTrainingTypes,ha as listTrainingTypes,po as localSink,vt as makeAuthStore,Rr as makeConfigStore,Me as mapApiError,yt as maskToken,Mc as maybeSyncWikiData,Nn as mcpWebSearchPath,Sn as memoryAddPath,wn as memoryListPath,Tn as memoryNodePath,Cn as memorySearchPath,Qi as modelSupportsTrainingType,ot as normalizeConfigName,Ne as normalizeModelBaseUrl,Ya as parseBooleanValue,He as parseConfigFile,Jr as parseDatasetSchemaFlag,Xa as parseOptionalBooleanValue,Ut as parseSSE,rl as parseSkillNames,Ma as pickPlanStrategy,Fi as pickValidator,na as preflightBatchSizeGate,On as profileSchemaPath,Ws as rankModels,R as readConfigFile,ut as readConfigProfiles,qs as readSkillLock,qa as readTextFromPathOrStdin,as as recallCandidates,Ls as recallSemantic,It as redactDataUri,fn as refreshAccessToken,Ii as registerValidator,Xc as releaseAssetUrl,mo as remoteSink,xc as removeSkillDir,Ct as request,Tt as requestJson,Or as resetBailianControlPolicies4Agent,We as resolveApiKey,mr as resolveAsrApi,fc as resolveAssetFileName,Za as resolveBooleanFlag,Ge as resolveConsole,zt as resolveFileUrl,sr as resolveImageEditApi,or as resolveImageGenerateApi,ir as resolveImageSizeProfile,Ue as resolveModelBaseUrl,Ke as resolveOpenApi,Ga as resolveOutputDir,ar as resolvePromptExtendDefault,Qa as resolveWatermark,mn as responsesPath,Ja as runWithConcurrency,mc as sanitizeSkillName,xa as scaleDeployment,Dt as signAcsRequest,xt as sourceConfig,Dn as speechRecognizePath,En as speechSynthesizePath,Ka as stripUndefined,bn as taskPath,vo as trackCommandExecution,B as trackingHeaders,Zi as trainingTypeMethodVariant,ic as unlinkSkillFromAgents,jr as unwrapResponse,Sa as updateDeployment,Vr as uploadDataset,Lt as uploadFile,Ys as upsertSkillLockEntry,kn as userProfilePath,ft as validateConfigProfileActivation,U as validateDataset,_c as validateSkillDir,yn as videoGeneratePath,z as writeConfigFile,Uc as writeInstallMethodSync,Js 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===K.Pipeline?Jo:qo)+e}else l=n.complexity===K.Pipeline?Jo:qo;let u=a?.enableThinking??!1,d=n.complexity===K.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=mn(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Ut(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await e.requestJson({path:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:K.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===K.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=qs(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Js(e,g),{type:K.Pipeline,summary:h.summary??``,steps:e}}let _=qs(h.recommendations??h??[],g,i);return{type:K.Single,recommendations:_}}function X(){return A(P(),`skills`)}function Xs(){return A(X(),`skill-lock.json`)}function Zs(){return{version:1,skills:{}}}function Qs(){let e=Xs();if(!x(e))return Zs();try{let t=JSON.parse(w(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?Zs():t}catch{return Zs()}}function $s(e){C(X(),{recursive:!0}),O(Xs(),JSON.stringify(e,null,2)+`
189
+ `)}function ec(e,t){let n=Qs();n.skills[e]={...n.skills[e],...t},$s(n)}function tc(){let e=pe(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||A(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:A(e,r,`skills`),detectDirs:[A(e,r)]}),i=(t,n)=>t?.trim()||A(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:A(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>A(e,t)),s=o.find(e=>x(e))??o[0],c=[A(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(A(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(A(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:A(e,`.agents`,`skills`),detectDirs:[A(e,`.agents`),A(e,`.cline`),A(e,`.dexto`),A(e,`.firebender`),A(e,`.kimi-code`),A(e,`.kimi`),A(e,`.loaf`),A(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:A(n,`agents`,`skills`),detectDirs:[A(n,`agents`),A(n,`amp`),A(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:A(e,`.astrbot`,`data`,`skills`),detectDirs:[A(t,`data`,`skills`),A(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:A(e,`.codebuddy`,`skills`),detectDirs:[A(t,`.codebuddy`),A(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:A(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:A(e,`.continue`,`skills`),detectDirs:[A(t,`.continue`),A(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:A(e,`.deepagents`,`agent`,`skills`),detectDirs:[A(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:A(n,`devin`,`skills`),detectDirs:[A(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:A(n,`goose`,`skills`),detectDirs:[A(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:A(e,`.jazz`,`skills`),detectDirs:[A(e,`.jazz`),A(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:A(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[A(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:A(e,`.minimax`,`skills`),detectDirs:[A(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:A(n,`opencode`,`skills`),detectDirs:[A(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:A(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:A(e,`.tabnine`,`agent`,`skills`),detectDirs:[A(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:A(e,`.zcode`,`skills`),detectDirs:[A(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Z(){return tc().filter(e=>e.detectDirs.some(e=>x(e)))}function nc(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function rc(e){let t=X();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+fe)}return e===t||e.startsWith(t+fe)}function ic(e){try{if(!S(e).isSymbolicLink())return!1;let t=ce(e);return rc(de(t)?t:j(k(e),t))}catch{return!1}}function ac(e,t){if(!t.some(t=>nc(t,e)))return!1;try{return S(e).isDirectory()}catch{return!1}}const oc=`existing file/dir not managed by bl skill`;function sc(e,t=Z(),n=[]){let r=A(X(),e),i=[];for(let a of t){let t=A(a.skillsDir,e);try{let e=!1;try{S(t),e=!0}catch{}if(e)if(ic(t))D(t);else if(ac(t,n))D(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:oc});continue}C(a.skillsDir,{recursive:!0});try{ue(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{oe(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 cc(e,t=Z(),n=[]){let r=sc(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===oc).map(e=>e.path),s=n.filter(e=>!a.some(t=>nc(t,e))&&!o.some(t=>nc(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function lc(e,t=[]){let n=[],r=new Set(t);for(let t of tc())r.add(A(t.skillsDir,e));for(let e of r)try{let r;try{r=S(e)}catch{continue}r.isSymbolicLink()?ic(e)&&(D(e),n.push(e)):t.some(t=>nc(t,e))&&(D(e,{recursive:!0,force:!0}),n.push(e))}catch{}return n}function uc(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function dc(e,t){let n=ve.extract();n.on(`entry`,(e,r,i)=>{if(!uc(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(Error(`unsafe tar entry: ${e.name}`));return}let a=A(t,e.name);if(e.type===`directory`){C(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}C(k(a),{recursive:!0});let o=se(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await ge(he.from(e),_e(),n)}function fc(e){let t=[],n=r=>{for(let i of T(r?A(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=me(`sha256`);for(let n of t)r.update(n),r.update(w(A(e,n)));return`sha256:${r.digest(`hex`)}`}function pc(e,t){C(k(t),{recursive:!0});let n=`${t}.old-${Date.now()}`;x(t)&&E(t,n);try{E(e,t)}catch(e){throw x(n)&&!x(t)&&E(n,t),e}x(n)&&D(n,{recursive:!0,force:!0})}function mc(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function hc(e=1e4){let t=`${mc()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new N(`Cannot access skill registry: ${t}`,M.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new N(`Skill registry returned HTTP ${n.status}: ${t}`,M.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 N(`Skill index index.json is not valid JSON`,M.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 N(`Skill index index.json has invalid structure`,M.GENERAL,`Retry later or contact the publisher`);return i}const gc=/^sha256-[0-9a-f]{64}\.tar\.br$/;function _c(e){let t=e?.object;return t&&gc.test(t)?t:`skill.tar.br`}async function vc(e,t){let n=`${mc()}/${e}/${_c(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new N(`Failed to download skill ${e}: ${n}`,M.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new N(`Failed to download skill ${e}: HTTP ${r.status}`,M.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 bc(e){return e.length>0&&yc(e)===e}function Q(e,t){throw new N(`Skill ${e} validation failed: ${t}`,M.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function xc(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function Sc(e,t){let n=A(e,`SKILL.md`),r;try{le(n).isFile()||Q(t,`SKILL.md is not a regular file`),r=w(n,`utf-8`)}catch(e){if(e instanceof N)throw e;Q(t,`missing SKILL.md`)}let i=xc(r);i===null&&Q(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{Q(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&Q(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)&&Q(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function Cc(e){if(!bc(e))throw new N(`Invalid skill name: ${e}`,M.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function wc(e,t,n){Cc(e);let r=X(),i=A(r,e),a=A(r,`.tmp-${e}-${process.pid}-${Date.now()}`);try{if(C(a,{recursive:!0}),await dc(t,a),n?.startsWith(`sha256:`)){let t=fc(a);if(t!==n)throw new N(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,M.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let r=Sc(a,e);return pc(a,i),{name:e,path:i,meta:r}}finally{x(a)&&D(a,{recursive:!0,force:!0})}}async function Tc(e,t){if(t.compression&&t.compression!==`tar.br`)throw new N(`Skill ${e} uses unsupported compression format: ${t.compression}`,M.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return wc(e,await vc(e,t),t.contentHash)}function Ec(e){Cc(e);let t=A(X(),e);return x(t)?(D(t,{recursive:!0,force:!0}),!0):!1}function Dc(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 Oc(e,t,n=Z(),r=[]){await Tc(e,t);let i=cc(e,n,r);return{lockEntry:Dc(t,i.links),linkedAgents:i.linkedAgents}}const $=`bailian-docs-llm-wiki`;function kc(){return A(P(),`skills/bailian-docs-llm-wiki`)}function Ac(){return x(A(kc(),`models`,`models.jsonl`))}function jc(){return A(P(),`wiki-sync-state.json`)}function Mc(){try{return JSON.parse(w(jc(),`utf-8`))}catch{return null}}function Nc(e){try{O(jc(),JSON.stringify(e))}catch{}}function Pc(e){try{ec($,e)}catch{}}function Fc(e){try{let t=Qs().skills[$];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function Ic(){try{return(await hc(3e3)).skills[$]??null}catch{return null}}async function Lc(){let e=Mc(),t=Date.now();if(e&&t-e.lastChecked<432e5&&Ac())return!1;let n=await Ic();if(!n?.contentHash)return!1;if(Ac()&&(!e||e.contentHash===n.contentHash)){if(Nc({lastChecked:t,contentHash:n.contentHash}),Fc(n.contentHash)){let e=Qs().skills[$]?.links??[];Pc(Dc(n,cc($,Z(),e).links))}return!1}try{let e=Qs().skills[$]?.links??[];Pc((await Oc($,n,Z(),e)).lockEntry)}catch{return!1}return Nc({lastChecked:t,contentHash:n.contentHash}),!0}const Rc=`bailian-cli`,zc=`install-method`,Bc=new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function Vc(e){return e?A(P(),`${zc}.${e}`):A(P(),zc)}function Hc(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function Uc(e){if(!e)return null;let t=e.trim().toLowerCase();return Bc.has(t)?t:null}function Wc(e){try{return Uc(w(e,`utf-8`).split(`
190
+ `)[0])}catch{return null}}function Gc(){let e=Uc(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Hc()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Kc(e){let t=Uc(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=Wc(Vc(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=Wc(Vc());if(e)return e}return Gc()}return Wc(Vc())||Gc()}function qc(e){let t=Kc(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function Jc(e,t={clientName:Rc}){try{let n=P();x(n)||C(n,{recursive:!0,mode:448}),O(Vc(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&O(Vc(),`${e}\n`,{mode:384})}catch{}}const Yc=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Xc=`https://github.com/modelstudioai/cli/releases`,Zc=`https://bailian.aliyun.com/cli/install.sh`,Qc=`https://bailian.aliyun.com/cli/install.ps1`;function $c(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):Yc}function el(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${$c()}/manifest.json`:`${$c()}/${t}.json`}function tl(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${$c()}/${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 rl(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function il(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function al(e){return new Promise((t,n)=>{b.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??Error(`Failed to open zip: ${e}`));return}t(i)})})}function ol(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function sl(e,t,n){let r=await al(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=ol(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 ye(k(t),{recursive:!0}),await ge(r,se(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function cl(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new Ae(`--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 Ae(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function ll(){let e=X();return x(e)?T(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return le(A(e,t)).isDirectory()}catch{return!1}}):[]}function ul(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{Ba as ASYNC_FLAG,Le as BAILIAN_HOST,Aa as BILLING_METHOD,Rc as BINARY_PRODUCT_CLIENT_NAME,N as BailianError,No as Budgets,bt as CHANNEL,Ma as CHARGE_TYPE,Ka as COMMAND_PACK_API_VERSION,za as CONCURRENT_FLAG,Re as CONFIG_FILE_KEYS,Ha as CONSOLE_AUTH_FLAGS,J as Capabilities,cn as Client,K as Complexities,Po as ContextNeeds,ja as DEFAULT_BILLING_METHOD,Yc as DEFAULT_CLI_CDN_BASE,Oa as DEFAULT_DEPLOY_PLAN,Qc as DEFAULT_INSTALL_PS1_URL,Zc as DEFAULT_INSTALL_SCRIPT_URL,ea as DEFAULT_TRAINING_TYPE,W as DEPLOY_PLAN,Ie as DOCS_HOSTS,M as ExitCode,Fo as Features,Xc as GITHUB_RELEASES_BASE,Ra as GLOBAL_FLAGS,oa as INSUFFICIENT_SAMPLES_CODE,Xr as MAX_DATASET_BYTES,Zr as MAX_MEDIA_ZIP_BYTES,Va as MODEL_AUTH_FLAGS,Mr as MODEL_LIST_API,en as McpClient,Mo as Modalities,Y as ModelCategories,Ua as OPENAPI_AUTH_FLAGS,Nr as PREDICT_CONFIG_API,q as QualityPreferences,Fe as REGIONS,Io as SEMANTIC_TOP_K,Ia as STRATEGIES,$i as TRAINING_TYPES_CLI,Qi as TRAINING_TYPE_MAP,Ae as UsageError,pt as activateConfigProfile,Qo as analyzeIntent,an as anonymousConsoleCall,wn as appCompletionPath,pc as atomicSwap,Yt as bailianMcpPath,Xt as bailianMcpSsePath,rl as binaryAssetFileName,il as binaryInnerFileName,Et as buildAcsCanonicalQuery,br as buildAsrFlashRequest,yr as buildAsyncAsrLanguageFields,Ks as buildDocLink,gt as buildSettings,Dc as buildSkillLockEntry,ht as buildSources,sn as callConsoleGateway,qi as cancelFineTune,el as channelManifestUrl,mn as chatPath,Sr as collectAsrTranscriptionItems,fc as computeDirContentHash,ul as computeSkillStatuses,$t as connectBailianMcpWithFallback,kr as createBailianControlUser,xa as createDeployment,Wi as createFineTune,Tr as createInstrumentedFetch,io as createTrackingEvent,Wa as credentialFlagDefs,ka as defaultDeployPlan,Ga as defineCommand,mt as deleteConfigProfile,Yr as deleteDataset,wa as deleteDeployment,Ji as deleteFineTune,Xe as describeAuthState,nl as detectBinaryPlatform,Gc as detectInstallMethod,Z as detectInstalledAgents,Ni as detectModality,nt as detectOutputFormat,vc as downloadSkillAsset,rn as effectiveConsoleGatewayConfig,Zs as emptySkillLock,Qe as ensureConfigDir,Zi as exportCheckpoint,xr as extractAsrFlashText,dc as extractTarBr,sl as extractZipEntryToFile,cc as fanOutSkillToAgents,aa as fetchModelCapability,zr as fetchModelDetail,Rr as fetchModelGroups,Fr as fetchModelList,Ir as fetchModelListAll,Hr as fetchPredictConfig,hc as fetchSkillsIndex,Lr as findModelByName,_o as flushTelemetry,tt as formatErrorJson,Ui as formatIssue,et as formatJson,rt as formatOutput,$e as formatText,fn as generateCLIAccessToken,Ja as generateFilename,tc as getAgentTargets,$c as getCliCdnBase,P as getConfigDir,F as getConfigPath,Ze as getCredentialsPath,Jr as getDataset,Ca as getDeployment,Ki as getFineTune,Yi as getFineTuneLogs,Kc as getInstallMethod,Gr as getModelProfilePreset,jo as getModels,ya as getProfile,Xs as getSkillLockPath,mc as getSkillRegistryBaseUrl,X as getSkillsDir,qc as getUpdateInstallMethod,yn as image2ImagePath,Ft as imageFileToDataUri,gn as imagePath,_n as imageSyncPath,vn as imageText2ImagePath,vr as inferAudioFormatHint,Tc as installSkill,wc as installSkillFromBuffer,Oc as installSkillWithFanout,Hc as isCompiledBinary,ar as isLegacyImage2ImageModel,ir as isLegacyText2ImageModel,Rt as isLocalFile,uc as isSafeEntryName,bc as isSafeSkillName,Es as isSemanticAvailable,Zt as isStreamableHttpUnsupported,er as isSyncMultimodalImageModel,ta as isTrainingTypeCli,Qt as isUrlOverrideSseFallbackCandidate,or as isWanxFunctionImageEditModel,Fn as knowledgeChatEndpoint,Nn as knowledgeRetrievePath,Pn as knowledgeSearchEndpoint,sc as linkSkillToAgents,Ar as listBailianControlWorkspaces,Xi as listCheckpoints,qr as listDatasets,Ta as listDeployableModels,Sa as listDeployments,Gi as listFineTunes,ll as listSkillDirsOnDisk,Hi as listSupportedFormats,ia as listSupportedTrainingTypes,ba as listTrainingTypes,vo as localSink,vt as makeAuthStore,Ur as makeConfigStore,Me as mapApiError,yt as maskToken,Lc as maybeSyncWikiData,In as mcpWebSearchPath,Tn as memoryAddPath,Dn as memoryListPath,On as memoryNodePath,En as memorySearchPath,ra as modelSupportsTrainingType,Sn as modelsLimitsPath,Cn as modelsPermissionsPath,ot as normalizeConfigName,Ne as normalizeModelBaseUrl,eo as parseBooleanValue,He as parseConfigFile,$r as parseDatasetSchemaFlag,to as parseOptionalBooleanValue,Ut as parseSSE,cl as parseSkillNames,La as pickPlanStrategy,Bi as pickValidator,sa as preflightBatchSizeGate,jn as profileSchemaPath,Ys as rankModels,R as readConfigFile,ut as readConfigProfiles,Qs as readSkillLock,Qa as readTextFromPathOrStdin,us as recallCandidates,Hs as recallSemantic,It as redactDataUri,pn as refreshAccessToken,Vi as registerValidator,tl as releaseAssetUrl,yo as remoteSink,Ec as removeSkillDir,Ct as request,Tt as requestJson,jr as resetBailianControlPolicies4Agent,We as resolveApiKey,_r as resolveAsrApi,_c as resolveAssetFileName,no as resolveBooleanFlag,Ge as resolveConsole,zt as resolveFileUrl,ur as resolveImageEditApi,lr as resolveImageGenerateApi,sr as resolveImageSizeProfile,Ue as resolveModelBaseUrl,Ke as resolveOpenApi,Xa as resolveOutputDir,cr as resolvePromptExtendDefault,ro as resolveWatermark,hn as responsesPath,$a as runWithConcurrency,yc as sanitizeSkillName,Ea as scaleDeployment,Dt as signAcsRequest,xt as sourceConfig,An as speechRecognizePath,kn as speechSynthesizePath,Za as stripUndefined,xn as taskPath,Co as trackCommandExecution,B as trackingHeaders,na as trainingTypeMethodVariant,lc as unlinkSkillFromAgents,Pr as unwrapResponse,Da as updateDeployment,Kr as uploadDataset,Lt as uploadFile,ec as upsertSkillLockEntry,Mn as userProfilePath,ft as validateConfigProfileActivation,U as validateDataset,Sc as validateSkillDir,bn as videoGeneratePath,z as writeConfigFile,Jc as writeInstallMethodSync,$s as writeSkillLock};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.15.0",
3
+ "version": "1.15.1",
4
4
  "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.",
5
5
  "homepage": "https://bailian.console.aliyun.com/cli",
6
6
  "bugs": {