bailian-cli-core 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -469,6 +469,90 @@ interface DashScopeKnowledgeRetrieveResponse {
469
469
  }>;
470
470
  };
471
471
  }
472
+ interface KnowledgeSearchRequest {
473
+ query: string;
474
+ agent_id: string;
475
+ images?: string[];
476
+ query_history?: Array<{
477
+ role: "user" | "assistant";
478
+ content: string;
479
+ }>;
480
+ }
481
+ interface KnowledgeSearchResponse {
482
+ code: string;
483
+ status_code: number;
484
+ request_id: string;
485
+ data: {
486
+ total: number;
487
+ cost_time: number;
488
+ nodes: Array<{
489
+ score: number;
490
+ text: string;
491
+ metadata: {
492
+ content?: string;
493
+ title?: string;
494
+ doc_id?: string;
495
+ doc_name?: string;
496
+ doc_url?: string;
497
+ pipeline_id?: string;
498
+ workspace_id?: string;
499
+ page_number?: number;
500
+ image_url?: string;
501
+ _knowledge_type?: string;
502
+ _citation_index?: number;
503
+ _score?: number;
504
+ };
505
+ }>;
506
+ };
507
+ }
508
+ type KnowledgeChatContentPart = {
509
+ type: "text";
510
+ text: string;
511
+ } | {
512
+ type: "image_url";
513
+ image_url: {
514
+ url: string;
515
+ };
516
+ };
517
+ interface KnowledgeChatMessage {
518
+ role: "user" | "assistant";
519
+ content: string | KnowledgeChatContentPart[];
520
+ }
521
+ interface KnowledgeChatRequest {
522
+ input: {
523
+ messages: KnowledgeChatMessage[];
524
+ };
525
+ parameters: {
526
+ agent_options: {
527
+ agent_id: string;
528
+ user?: {
529
+ user_id?: string;
530
+ workspace_id?: string;
531
+ };
532
+ };
533
+ };
534
+ stream: boolean;
535
+ }
536
+ interface KnowledgeChatStreamChunk {
537
+ output: {
538
+ choices: Array<{
539
+ message: {
540
+ role: string;
541
+ content: string;
542
+ tool_calls?: unknown[];
543
+ extra?: {
544
+ group?: string;
545
+ step_change?: string;
546
+ step?: string;
547
+ };
548
+ };
549
+ finish_reason: string;
550
+ }>;
551
+ };
552
+ code: string;
553
+ message: string;
554
+ request_id: string;
555
+ }
472
556
  interface DashScopeTTSRequest {
473
557
  model: string;
474
558
  input: {
@@ -717,6 +801,8 @@ declare function speechRecognizeEndpoint(baseUrl: string): string;
717
801
  declare function profileSchemaEndpoint(baseUrl: string): string;
718
802
  declare function userProfileEndpoint(baseUrl: string, schemaId: string): string;
719
803
  declare function knowledgeRetrieveEndpoint(baseUrl: string): string;
804
+ declare function knowledgeSearchEndpoint(workspaceId: string): string;
805
+ declare function knowledgeChatEndpoint(workspaceId: string): string;
720
806
  declare function mcpWebSearchEndpoint(baseUrl: string): string;
721
807
  //#endregion
722
808
  //#region src/client/headers.d.ts
@@ -2143,4 +2229,4 @@ interface ModelSource {
2143
2229
  load(): Promise<ModelProfile[]>;
2144
2230
  }
2145
2231
  //#endregion
2146
- export { AkSignConfig, type ApiErrorBody, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AuthMethod, BAILIAN_HOST, BailianError, BatchSizeGateInput, BatchSizeGateResult, Budget, Budgets, CHANNEL, CONSOLE_GATEWAY_NO_TOKEN_MESSAGE, CancelFineTuneResponse, Capabilities, Capability, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatTool, Command, CommandSpec, Complexities, Complexity, Config, ConfigFile, ConsoleGatewayRequest, ConsoleSite, ContextNeed, ContextNeeds, CreateDeploymentRequest, CreateDeploymentResponse, CreateFineTuneRequest, CreateFineTuneResponse, DEFAULT_TRAINING_TYPE, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, DashScopeKnowledgeRetrieveRequest, DashScopeKnowledgeRetrieveResponse, DashScopeTTSRequest, DashScopeTTSResponse, DashScopeTTSStreamChunk, DashScopeTaskResponse, DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, DatasetDeleteResponse, DatasetFile, DatasetGetResponse, DatasetListParams, DatasetListResponse, DatasetSchema, DatasetUploadParams, DatasetUploadResponse, DeleteDeploymentResponse, DeleteFineTuneResponse, DeployableModel, DeployableTemplate, Deployment, ExitCode, ExportCheckpointResponse, Feature, Features, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, GLOBAL_OPTIONS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, GlobalFlags, INSUFFICIENT_SAMPLES_CODE, IntentProfile, IntentSegment, KnowledgeRetrieveRequest, KnowledgeRetrieveResponse, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, MAX_DATASET_BYTES, McpClient, McpTool, McpToolResult, MemoryAddRequest, MemoryAddResponse, MemoryMessage, MemoryNode, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemorySearchRequest, MemorySearchResponse, Modalities, Modality, ModelCapability, ModelCategories, ModelCategory, ModelListParams, ModelListResult, ModelPreference, ModelPrice, ModelProfile, ModelSource, OptionDef, OutputFormat, PipelineResult, PipelineStep, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolvedCredential, SOURCE_CONFIG, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, SingleResult, StreamChoice, StreamChunk, TAGS, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, analyzeIntent, appCompletionEndpoint, bailianMcpUrl, buildDocLink, callConsoleGateway, cancelFineTune, chatEndpoint, clearApiKey, createDeployment, createFineTune, createTrackingEvent, defineCommand, deleteDataset, deleteDeployment, deleteFineTune, detectOutputFormat, effectiveConsoleGatewayConfig, ensureConfigDir, exportCheckpoint, fetchModelCapability, fetchModelList, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateFilename, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getModels, imageEndpoint, imageSyncEndpoint, isCI, isInteractive, isLocalFile, isSemanticAvailable, isTrainingTypeCli, knowledgeRetrieveEndpoint, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listSupportedFormats, listSupportedTrainingTypes, loadApiKeyFromConfig, loadConfig, localSink, mapApiError, maskToken, mcpWebSearchEndpoint, memoryAddEndpoint, memoryListEndpoint, memoryNodeEndpoint, memorySearchEndpoint, modelSupportsTrainingType, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, pickValidator, preflightBatchSizeGate, profileSchemaEndpoint, rankModels, readConfigFile, recallCandidates, recallSemantic, registerValidator, remoteSink, request, requestJson, resolveBooleanFlag, resolveConsoleGatewayCredential, resolveCredential, resolveFileUrl, resolveOutputDir, resolveWatermark, saveApiKeyToConfig, scaleDeployment, signRequest, speechRecognizeEndpoint, speechSynthesizeEndpoint, stripUndefined, taskEndpoint, toServerTrainingType, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, updateDeployment, uploadDataset, uploadFile, userProfileEndpoint, validateDataset, videoGenerateEndpoint, writeConfigFile };
2232
+ export { AkSignConfig, type ApiErrorBody, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AuthMethod, BAILIAN_HOST, BailianError, BatchSizeGateInput, BatchSizeGateResult, Budget, Budgets, CHANNEL, CONSOLE_GATEWAY_NO_TOKEN_MESSAGE, CancelFineTuneResponse, Capabilities, Capability, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatTool, Command, CommandSpec, Complexities, Complexity, Config, ConfigFile, ConsoleGatewayRequest, ConsoleSite, ContextNeed, ContextNeeds, CreateDeploymentRequest, CreateDeploymentResponse, CreateFineTuneRequest, CreateFineTuneResponse, DEFAULT_TRAINING_TYPE, DOCS_HOSTS, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, DashScopeKnowledgeRetrieveRequest, DashScopeKnowledgeRetrieveResponse, DashScopeTTSRequest, DashScopeTTSResponse, DashScopeTTSStreamChunk, DashScopeTaskResponse, DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, DatasetDeleteResponse, DatasetFile, DatasetGetResponse, DatasetListParams, DatasetListResponse, DatasetSchema, DatasetUploadParams, DatasetUploadResponse, DeleteDeploymentResponse, DeleteFineTuneResponse, DeployableModel, DeployableTemplate, Deployment, ExitCode, ExportCheckpointResponse, Feature, Features, FineTuneCheckpoint, FineTuneHyperParameters, FineTuneJob, FineTuneLogEntry, GLOBAL_OPTIONS, GetDeploymentResponse, GetFineTuneLogsParams, GetFineTuneLogsResponse, GetFineTuneResponse, GetModelsOptions, GlobalFlags, INSUFFICIENT_SAMPLES_CODE, IntentProfile, IntentSegment, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, KnowledgeChatStreamChunk, KnowledgeRetrieveRequest, KnowledgeRetrieveResponse, KnowledgeSearchRequest, KnowledgeSearchResponse, ListCheckpointsResponse, ListDeployableModelsParams, ListDeployableModelsResponse, ListDeploymentsParams, ListDeploymentsResponse, ListFineTunesParams, ListFineTunesResponse, MAX_DATASET_BYTES, McpClient, McpTool, McpToolResult, MemoryAddRequest, MemoryAddResponse, MemoryMessage, MemoryNode, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemorySearchRequest, MemorySearchResponse, Modalities, Modality, ModelCapability, ModelCategories, ModelCategory, ModelListParams, ModelListResult, ModelPreference, ModelPrice, ModelProfile, ModelSource, OptionDef, OutputFormat, PipelineResult, PipelineStep, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, PtuCapacity, QpmLimit, QualityPreference, QualityPreferences, REGIONS, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolvedCredential, SOURCE_CONFIG, ScaleDeploymentRequest, ScaleDeploymentResponse, ScoredCandidate, ServerSentEvent, SingleResult, StreamChoice, StreamChunk, TAGS, TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, TrackingEvent, TrainingTypeCli, UpdateDeploymentRequest, UpdateDeploymentResponse, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, analyzeIntent, appCompletionEndpoint, bailianMcpUrl, buildDocLink, callConsoleGateway, cancelFineTune, chatEndpoint, clearApiKey, createDeployment, createFineTune, createTrackingEvent, defineCommand, deleteDataset, deleteDeployment, deleteFineTune, detectOutputFormat, effectiveConsoleGatewayConfig, ensureConfigDir, exportCheckpoint, fetchModelCapability, fetchModelList, flushTelemetry, formatErrorJson, formatIssue, formatJson, formatOutput, formatText, generateFilename, getConfigDir, getConfigPath, getCredentialsPath, getDataset, getDeployment, getFineTune, getFineTuneLogs, getModels, imageEndpoint, imageSyncEndpoint, isCI, isInteractive, isLocalFile, isSemanticAvailable, isTrainingTypeCli, knowledgeChatEndpoint, knowledgeRetrieveEndpoint, knowledgeSearchEndpoint, listCheckpoints, listDatasets, listDeployableModels, listDeployments, listFineTunes, listSupportedFormats, listSupportedTrainingTypes, loadApiKeyFromConfig, loadConfig, localSink, mapApiError, maskToken, mcpWebSearchEndpoint, memoryAddEndpoint, memoryListEndpoint, memoryNodeEndpoint, memorySearchEndpoint, modelSupportsTrainingType, parseBooleanValue, parseConfigFile, parseDatasetSchemaFlag, parseOptionalBooleanValue, parseSSE, pickValidator, preflightBatchSizeGate, profileSchemaEndpoint, rankModels, readConfigFile, recallCandidates, recallSemantic, registerValidator, remoteSink, request, requestJson, resolveBooleanFlag, resolveConsoleGatewayCredential, resolveCredential, resolveFileUrl, resolveOutputDir, resolveWatermark, saveApiKeyToConfig, scaleDeployment, signRequest, speechRecognizeEndpoint, speechSynthesizeEndpoint, stripUndefined, taskEndpoint, toServerTrainingType, trackCommandExecution, trackingHeaders, trainingTypeMethodVariant, updateDeployment, uploadDataset, uploadFile, userProfileEndpoint, validateDataset, videoGenerateEndpoint, writeConfigFile };
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
- import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,existsSync as r,mkdirSync as i,readFileSync as a,renameSync as o,statSync as s,unlinkSync as c,writeFileSync as l}from"fs";import{homedir as u}from"os";import{basename as d,extname as f,join as p}from"path";import{stringify as m}from"yaml";import{createHash as h,createHmac as g,randomUUID as _}from"crypto";import{Readable as v}from"stream";import{createInterface as y}from"readline";import{cpSync as b,existsSync as x,mkdirSync as S,readFileSync as C,readdirSync as w,writeFileSync as ee}from"node:fs";import{dirname as T,join as E}from"node:path";import{fileURLToPath as D}from"node:url";var te=Object.create,ne=Object.defineProperty,re=Object.getOwnPropertyDescriptor,O=Object.getOwnPropertyNames,k=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty,A=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=O(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ie.call(e,s)&&s!==n&&ne(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=re(t,s))||r.enumerable});return e},oe=(e,t,n)=>(n=e==null?{}:te(k(e)),ae(t||!e||!e.__esModule?ne(n,`default`,{value:e,enumerable:!0}):n,e)),j=e(import.meta.url);const M={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var N=class extends Error{exitCode;hint;api;constructor(e,t=M.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api}toJSON(){let e=se(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}};function se(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function P(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new N(r,M.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}const F={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},ce={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},le=`https://bailian.cn-beijing.aliyuncs.com`,ue=new Set([`text`,`json`]),de=new Set([`domestic`,`international`]);function fe(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function pe(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};return typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.base_url==`string`&&fe(t.base_url)&&(n.base_url=t.base_url),typeof t.output==`string`&&ue.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model),typeof t.access_key_id==`string`&&t.access_key_id.length>0&&(n.access_key_id=t.access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0&&(n.access_key_secret=t.access_key_secret),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&de.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:p(u(),`.bailian`)}function L(){return p(I(),`config.json`)}function me(){return p(I(),`credentials.json`)}async function he(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function ge(e){return m(e).replace(/\n$/,``)}function _e(e){return JSON.stringify(e,null,2)}function ve(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function ye(e){return e===`json`||e===`text`?e:process.stdout.isTTY?`text`:`json`}function be(e,t){switch(t){case`json`:return _e(e);case`text`:return ge(e)}}function xe(){let e=L();if(!r(e))return{};try{return pe(JSON.parse(a(e,`utf-8`)))}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}async function Se(e){await he();let t=L(),n=t+`.tmp`;l(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),o(n,t)}function Ce(e){let t=xe(),n=e.apiKey||void 0,r=t.api_key,i=process.env.DASHSCOPE_ACCESS_TOKEN?.trim()||void 0,a=t.access_token?.trim()||void 0,o=e.baseUrl||t.base_url||process.env.DASHSCOPE_BASE_URL||F.cn,s=ye(e.output||process.env.DASHSCOPE_OUTPUT||t.output),c=process.env.DASHSCOPE_TIMEOUT?Number(process.env.DASHSCOPE_TIMEOUT):void 0,l=c!==void 0&&Number.isFinite(c)&&c>0?c:void 0,u=e.timeout??l??t.timeout??300;if(!Number.isFinite(u)||u<=0)throw new N(`Timeout must be a positive finite number.`,M.USAGE);return{apiKey:n,accessTokenEnv:i,fileAccessToken:a,fileApiKey:r,configPath:L(),baseUrl:o,output:s,outputDir:t.output_dir||void 0,timeout:u,defaultTextModel:t.default_text_model,defaultVideoModel:t.default_video_model,defaultImageModel:t.default_image_model,defaultSpeechModel:t.default_speech_model,defaultOmniModel:t.default_omni_model,accessKeyId:process.env.ALIBABA_CLOUD_ACCESS_KEY_ID||t.access_key_id||void 0,accessKeySecret:process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET||t.access_key_secret||void 0,workspaceId:process.env.BAILIAN_WORKSPACE_ID||t.workspace_id||void 0,consoleSite:e.consoleSite||t.console_site||void 0,consoleRegion:e.consoleRegion||t.console_region||void 0,consoleSwitchAgent:e.consoleSwitchAgent||t.console_switch_agent||void 0,verbose:e.verbose||process.env.DASHSCOPE_VERBOSE===`1`,quiet:e.quiet||!1,noColor:e.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,yes:e.yes||!1,dryRun:e.dryRun||!1,nonInteractive:e.nonInteractive||!1,async:e.async||!1,telemetry:process.env.DO_NOT_TRACK===`1`?!1:t.telemetry??!0}}function we(){let e=L();if(!r(e))return null;try{let t=a(e,`utf-8`),n=JSON.parse(t);return typeof n.api_key==`string`&&n.api_key.length>0?n.api_key:null}catch{return null}}async function Te(e){await he();let t=L(),n={};try{n=JSON.parse(a(t,`utf-8`))}catch{}n.api_key=e;let r=t+`.tmp`;l(r,JSON.stringify(n,null,2)+`
3
- `,{mode:384}),o(r,t)}async function Ee(){let e=L();if(r(e))try{let t=JSON.parse(a(e,`utf-8`));delete t.api_key,delete t.access_token;let n=e+`.tmp`;l(n,JSON.stringify(t,null,2)+`
4
- `,{mode:384}),o(n,e)}catch{}}async function De(e){if(e.apiKey)return{token:e.apiKey,method:`api-key`,source:`flag`};if(e.fileApiKey)return{token:e.fileApiKey,method:`api-key`,source:`config.json`};if(e.accessTokenEnv)return{token:e.accessTokenEnv,method:`access-token`,source:`DASHSCOPE_ACCESS_TOKEN`};if(e.fileAccessToken)return{token:e.fileAccessToken,method:`access-token`,source:`config.json`};if(process.env.DASHSCOPE_API_KEY)return{token:process.env.DASHSCOPE_API_KEY,method:`api-key`,source:`DASHSCOPE_API_KEY`};throw new N(`No credentials found.`,M.AUTH,`Set DASHSCOPE_API_KEY environment variable, pass --api-key, or configure a key.`)}const Oe=`No console access token found.`;async function ke(e){if(e.accessTokenEnv)return{token:e.accessTokenEnv,method:`access-token`,source:`DASHSCOPE_ACCESS_TOKEN`};if(e.fileAccessToken)return{token:e.fileAccessToken,method:`access-token`,source:`config.json`};throw new N(Oe,M.AUTH,"Run `bl auth login --console` or set DASHSCOPE_ACCESS_TOKEN.")}function Ae(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=_(),i=je(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`},o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
1
+ import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,existsSync as r,mkdirSync as i,readFileSync as a,renameSync as o,statSync as s,unlinkSync as c,writeFileSync as l}from"fs";import{homedir as u}from"os";import{basename as d,extname as f,join as p}from"path";import{stringify as m}from"yaml";import{createHash as h,createHmac as g,randomUUID as _}from"crypto";import{Readable as v}from"stream";import{createInterface as y}from"readline";import{cpSync as ee,existsSync as b,mkdirSync as x,readFileSync as S,readdirSync as C,writeFileSync as te}from"node:fs";import{dirname as w,join as T}from"node:path";import{fileURLToPath as ne}from"node:url";var re=Object.create,ie=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,D=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!oe.call(e,s)&&s!==n&&ie(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ae(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:re(D(e)),k(t||!e||!e.__esModule?ie(n,`default`,{value:e,enumerable:!0}):n,e)),j=e(import.meta.url);const M={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var N=class extends Error{exitCode;hint;api;constructor(e,t=M.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api}toJSON(){let e=se(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}};function se(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function P(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new N(r,M.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}const F={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},ce={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},le=`https://bailian.cn-beijing.aliyuncs.com`,ue=new Set([`text`,`json`]),de=new Set([`domestic`,`international`]);function fe(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function pe(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};return typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.base_url==`string`&&fe(t.base_url)&&(n.base_url=t.base_url),typeof t.output==`string`&&ue.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model),typeof t.access_key_id==`string`&&t.access_key_id.length>0&&(n.access_key_id=t.access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0&&(n.access_key_secret=t.access_key_secret),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&de.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:p(u(),`.bailian`)}function L(){return p(I(),`config.json`)}function me(){return p(I(),`credentials.json`)}async function R(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function he(e){return m(e).replace(/\n$/,``)}function ge(e){return JSON.stringify(e,null,2)}function _e(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function ve(e){return e===`json`||e===`text`?e:process.stdout.isTTY?`text`:`json`}function ye(e,t){switch(t){case`json`:return ge(e);case`text`:return he(e)}}function be(){let e=L();if(!r(e))return{};try{return pe(JSON.parse(a(e,`utf-8`)))}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}async function xe(e){await R();let t=L(),n=t+`.tmp`;l(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),o(n,t)}function Se(e){let t=be(),n=e.apiKey||void 0,r=t.api_key,i=process.env.DASHSCOPE_ACCESS_TOKEN?.trim()||void 0,a=t.access_token?.trim()||void 0,o=e.baseUrl||t.base_url||process.env.DASHSCOPE_BASE_URL||F.cn,s=ve(e.output||process.env.DASHSCOPE_OUTPUT||t.output),c=process.env.DASHSCOPE_TIMEOUT?Number(process.env.DASHSCOPE_TIMEOUT):void 0,l=c!==void 0&&Number.isFinite(c)&&c>0?c:void 0,u=e.timeout??l??t.timeout??300;if(!Number.isFinite(u)||u<=0)throw new N(`Timeout must be a positive finite number.`,M.USAGE);return{apiKey:n,accessTokenEnv:i,fileAccessToken:a,fileApiKey:r,configPath:L(),baseUrl:o,output:s,outputDir:t.output_dir||void 0,timeout:u,defaultTextModel:t.default_text_model,defaultVideoModel:t.default_video_model,defaultImageModel:t.default_image_model,defaultSpeechModel:t.default_speech_model,defaultOmniModel:t.default_omni_model,accessKeyId:process.env.ALIBABA_CLOUD_ACCESS_KEY_ID||t.access_key_id||void 0,accessKeySecret:process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET||t.access_key_secret||void 0,workspaceId:process.env.BAILIAN_WORKSPACE_ID||t.workspace_id||void 0,consoleSite:e.consoleSite||t.console_site||void 0,consoleRegion:e.consoleRegion||t.console_region||void 0,consoleSwitchAgent:e.consoleSwitchAgent||t.console_switch_agent||void 0,verbose:e.verbose||process.env.DASHSCOPE_VERBOSE===`1`,quiet:e.quiet||!1,noColor:e.noColor||process.env.NO_COLOR!==void 0||!process.stdout.isTTY,yes:e.yes||!1,dryRun:e.dryRun||!1,nonInteractive:e.nonInteractive||!1,async:e.async||!1,telemetry:process.env.DO_NOT_TRACK===`1`?!1:t.telemetry??!0}}function Ce(){let e=L();if(!r(e))return null;try{let t=a(e,`utf-8`),n=JSON.parse(t);return typeof n.api_key==`string`&&n.api_key.length>0?n.api_key:null}catch{return null}}async function we(e){await R();let t=L(),n={};try{n=JSON.parse(a(t,`utf-8`))}catch{}n.api_key=e;let r=t+`.tmp`;l(r,JSON.stringify(n,null,2)+`
3
+ `,{mode:384}),o(r,t)}async function Te(){let e=L();if(r(e))try{let t=JSON.parse(a(e,`utf-8`));delete t.api_key,delete t.access_token;let n=e+`.tmp`;l(n,JSON.stringify(t,null,2)+`
4
+ `,{mode:384}),o(n,e)}catch{}}async function Ee(e){if(e.apiKey)return{token:e.apiKey,method:`api-key`,source:`flag`};if(e.fileApiKey)return{token:e.fileApiKey,method:`api-key`,source:`config.json`};if(e.accessTokenEnv)return{token:e.accessTokenEnv,method:`access-token`,source:`DASHSCOPE_ACCESS_TOKEN`};if(e.fileAccessToken)return{token:e.fileAccessToken,method:`access-token`,source:`config.json`};if(process.env.DASHSCOPE_API_KEY)return{token:process.env.DASHSCOPE_API_KEY,method:`api-key`,source:`DASHSCOPE_API_KEY`};throw new N(`No credentials found.`,M.AUTH,`Set DASHSCOPE_API_KEY environment variable, pass --api-key, or configure a key.`)}const De=`No console access token found.`;async function Oe(e){if(e.accessTokenEnv)return{token:e.accessTokenEnv,method:`access-token`,source:`DASHSCOPE_ACCESS_TOKEN`};if(e.fileAccessToken)return{token:e.fileAccessToken,method:`access-token`,source:`config.json`};throw new N(De,M.AUTH,"Run `bl auth login --console` or set DASHSCOPE_ACCESS_TOKEN.")}function ke(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=_(),i=Ae(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`},o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
5
5
  `)+`
6
6
  `,c=o.join(`;`),l=[t,e.pathname,``,s,c,i].join(`
7
- `),u=`ACS3-HMAC-SHA256`,d=`${u}\n${je(l)}`,f=Me(e.accessKeySecret,d);return a.authorization=`${u} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${f}`,a}function je(e){return h(`sha256`).update(e,`utf8`).digest(`hex`)}function Me(e,t){return g(`sha256`,e).update(t,`utf8`).digest(`hex`)}function Ne(e){return`${e}/compatible-mode/v1/chat/completions`}function Pe(e){return`${e}/api/v1/services/aigc/image-generation/generation`}function Fe(e){return`${e}/api/v1/services/aigc/multimodal-generation/generation`}function Ie(e){return`${e}/api/v1/services/aigc/video-generation/video-synthesis`}function Le(e,t){return`${e}/api/v1/tasks/${encodeURIComponent(t)}`}function Re(e,t){return`${e}/api/v1/apps/${encodeURIComponent(t)}/completion`}function ze(e){return`${e}/api/v2/apps/memory/add`}function Be(e){return`${e}/api/v2/apps/memory/memory_nodes/search`}function Ve(e){return`${e}/api/v2/apps/memory/memory_nodes`}function He(e,t){return`${e}/api/v2/apps/memory/memory_nodes/${encodeURIComponent(t)}`}function Ue(e){return`${e}/api/v1/services/audio/tts/SpeechSynthesizer`}function We(e){return`${e}/api/v1/services/audio/asr/transcription`}function Ge(e){return`${e}/api/v2/apps/memory/profile_schemas`}function Ke(e,t){return`${e}/api/v2/apps/memory/profile_schemas/${encodeURIComponent(t)}/profiles`}function qe(e){return`${e}/api/v1/indices/rag/index/retrieve`}function Je(e){return`${e}/api/v1/mcps/WebSearch/mcp`}function Ye(e){return`${e}/compatible-mode/v1/files`}function Xe(e){return`${e}/api/v1/files`}function Ze(e,t){return`${e}/api/v1/files/${encodeURIComponent(t)}`}function Qe(e){return`${e}/api/v1/fine-tunes`}function $e(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}`}function et(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/cancel`}function tt(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/logs`}function nt(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/checkpoints`}function rt(e,t,n){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/export/${encodeURIComponent(n)}`}function it(e){return`${e}/api/v1/deployments`}function at(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}`}function ot(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}/scale`}function st(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}/update`}function ct(e){return`${e}/api/v1/deployments/models`}const lt=`bailian-cli`,ut={t1:`public`,t2:``},dt=JSON.stringify({channel:lt,tags:ut});function R(){return{"x-dashscope-source-config":dt}}function ft(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function pt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function z(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.clientName??`bailian-cli-core`}/${e.clientVersion??`0.0.0-dev`}`,...R(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),pt(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),!t.noAuth){let n=await De(e);r.Authorization=`Bearer ${n.token}`,e.verbose&&(console.error(`> ${t.method??`GET`} ${t.url}`),console.error(`> Auth: ${ft(n.token)}`),console.error(`> x-dashscope-source-config: ${dt}`))}let i=mt((t.timeout??e.timeout)*1e3,t.signal),a=await fetch(t.url,{method:t.method??`GET`,headers:r,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:i.signal}).finally(i.cleanup);if(e.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!a.ok){let e={};try{e=await a.json()}catch{}throw P(a.status,e,t.url)}return a}function mt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function B(e,t){let n=await z(e,t),r;try{r=await n.json()}catch{throw new N(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,M.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw P(200,{error:{message:r.message,type:r.code}},t.url);return r}function ht(e,t){return`${e.replace(/\/$/,``)}/api/v1/mcps/${t}/mcp`}var gt=class{url;sessionId;nextId=1;config;authToken;constructor(e,t){this.config=e,this.url=t}async initialize(){let e=await De(this.config);this.authToken=e.token;let t=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.config.clientName??`bailian-cli-core`,version:this.config.clientVersion??`0.0.0-dev`}});this.config.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(t)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new N(`MCP error (${r.error.code}): ${r.error.message}`,M.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.config.clientName??`bailian-cli-core`}/${this.config.clientVersion??`0.0.0-dev`}`,...R()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.config.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.config.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.config.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}};async function*_t(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let o=r.split(`
8
- `);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const vt={"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 yt(e,t){return vt[e]?.[t]??vt[`cn-beijing`][t]}function bt(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 xt(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function St(e,t,{api:n,data:r}){let{consoleRegion:i,consoleSite:a,consoleSwitchAgent:o}=bt(e),s=yt(i,a),c=`https://${s.csGateway}`,l=s.action,u=xt(n,r,o),d=new URLSearchParams({params:u,region:i}),f=e.timeout*1e3,p={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};t&&(p.Authorization=`Bearer ${t}`);let m=await fetch(`${c}/cli/api.json?action=${l}&product=sfm_bailian&api=${encodeURIComponent(n)}`,{method:`POST`,headers:p,body:d.toString(),signal:AbortSignal.timeout(f)});if(!m.ok){let e=await m.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${m.status} ${m.statusText}`,M.GENERAL,e.slice(0,500))}let h=await m.json(),g=h.data;if(g?.success===!1&&g.errorCode){let e=g.errorCode,t=typeof e==`string`?e:JSON.stringify(e),n=t.includes(`NotLogined`),r=typeof g.errorMsg==`string`?g.errorMsg:void 0;throw new N(n?`Console session is not logged in or has expired.`:`Console gateway error: ${t}`,n?M.AUTH:M.GENERAL,n?"Run `bl auth login --console` to sign in or refresh your console session.":r&&r!==t?r:void 0)}return h}async function V(e,t,n={}){let{pageNo:r=1,pageSize:i=50,name:a=``,providers:o=[],capabilities:s=[]}=n,c=await St(e,t,{api:`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,data:{input:{pageNo:r,pageSize:i,name:a,providers:o,inferenceProviders:[],features:[],group:!0,capabilities:s,contextWindows:[]}}}),l=c?.data?.DataV2?.data??c?.data??{},u=l?.data?.total??l?.total??0,d=l?.data?.list??l?.list??[],f=[];for(let e of d)if(e.items?.length)for(let t of e.items)f.push(t);else f.push(e);return{total:u,models:f}}const Ct=`${F.cn}/api/v1/uploads`;async function wt(e,t,n){let r=`${Ct}?action=getPolicy&model=${encodeURIComponent(t)}`,i=kt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...R()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new N(`Failed to get upload policy (HTTP ${a.status}): ${e}`,M.GENERAL)}return(await a.json()).data}async function Tt(e,t,n){let r=d(t),i=`${e.upload_dir}/${r}`,o=a(t),s=new FormData;s.append(`OSSAccessKeyId`,e.oss_access_key_id),s.append(`Signature`,e.signature),s.append(`policy`,e.policy),s.append(`x-oss-object-acl`,e.x_oss_object_acl),s.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),s.append(`key`,i),s.append(`success_action_status`,`200`),s.append(`file`,new Blob([o]),r);let c=kt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...R()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new N(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,M.GENERAL)}return`oss://${i}`}async function Et(e){let{apiKey:t,model:n,filePath:i,signal:a}=e;if(!r(i))throw new N(`File not found: ${i}`,M.USAGE);if(!s(i).isFile())throw new N(`Not a file: ${i}`,M.USAGE);return Tt(await wt(t,n,a),i,a)}function Dt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:r(e)}async function Ot(e,t,n,r={}){return Dt(e)?Et({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function kt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function At(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=s(r),c=d(r),l=v.toWeb(n(r)),u=await new Response(l).blob(),f=new FormData;f.append(`file`,u,c),f.append(`purpose`,i);let p=await B(e,{url:Ye(e.baseUrl),method:`POST`,body:f,signal:a});if(p.id)return{file_id:p.id,name:p.filename??c,size:p.bytes??o.size,purpose:p.purpose??i,gmt_create:p.created_at?new Date(p.created_at*1e3).toISOString():void 0};let m=p.data?.failed_uploads;if(Array.isArray(m)&&m.length>0){let e=m[0]??{};throw new N(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,M.GENERAL,`Server reported failure for ${c}. Re-run with --verbose to see the raw response.`)}throw new N(`Dataset upload of ${c} 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 jt(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=Xe(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function Mt(e,t,n){return B(e,{url:Ze(e.baseUrl,t),method:`GET`,signal:n})}async function Nt(e,t,n){let r=await z(e,{url:Ze(e.baseUrl,t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Pt=300*1024*1024;function Ft(e,t=Pt){if(!r(e))throw new N(`File not found: ${e}`,M.USAGE);let n=s(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:f(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function It(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt.`,M.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, else ChatML).`)}function Lt(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 Rt=new Set([`system`,`user`,`assistant`]);function zt(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`||!Rt.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 Bt(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(...zt(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 Vt={name:`chatml`,detect:()=>!0,inspect:Bt};function Ht(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 Ut={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ht};function Wt(e,t){let n=Bt(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(...zt(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(...zt(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 Gt=[{name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Wt},Ut,Vt];function Kt(e,t){return t===void 0?Gt.find(t=>t.detect(e))??Vt:Gt.find(e=>e.name===t)||Vt}async function qt(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 Jt(e,t,r,i,a){let o=r?null:new Set(Lt(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(...Yt(n,u,i))}return{sampled:c,issues:s}}function Yt(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 Kt(r,n).inspect(r,t)}const U=[{format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await qt(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 Jt(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 Xt(e){let t=f(e).toLowerCase(),n=U.find(e=>e.extensions.includes(t));if(!n){let e=U.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 Zt(e){U.some(t=>t.format===e.format)||U.push(e)}async function Qt(e,t={}){let{bytes:n}=Ft(e,t.maxBytes??314572800),r=await Xt(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function $t(){return U.map(e=>({format:e.format,extensions:[...e.extensions]}))}function en(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 tn(e,t,n){return B(e,{url:Qe(e.baseUrl),method:`POST`,body:t,signal:n})}async function nn(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=Qe(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function rn(e,t,n){return B(e,{url:$e(e.baseUrl,t),method:`GET`,signal:n})}async function an(e,t,n){return B(e,{url:et(e.baseUrl,t),method:`POST`,signal:n})}async function on(e,t,n){return B(e,{url:$e(e.baseUrl,t),method:`DELETE`,signal:n})}async function sn(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=tt(e.baseUrl,t);return B(e,{url:r.toString()?`${i}?${r.toString()}`:i,method:`GET`,signal:n.signal})}async function cn(e,t,n){return B(e,{url:nt(e.baseUrl,t),method:`GET`,signal:n})}async function ln(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),B(e,{url:`${rt(e.baseUrl,t,n)}?${a.toString()}`,method:`GET`,signal:i})}const W={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`}},un=Object.keys(W),dn=`sft-lora`;function fn(e){return e in W}function pn(e){return W[e].server}function mn(e){let{method:t,variant:n}=W[e];return{method:t,variant:n}}function hn(e,t){if(!e)return!1;let{method:n,variant:r}=W[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function gn(e){return e?un.filter(t=>hn(e,t)):[]}async function _n(e,t){return(await V(e,``,{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const vn=`INSUFFICIENT_SAMPLES`;function yn(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:vn,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(`
9
- `)}}async function bn(e,t,n){return B(e,{url:it(e.baseUrl),method:`POST`,body:t,signal:n})}async function xn(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=it(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function Sn(e,t,n){return B(e,{url:at(e.baseUrl,t),method:`GET`,signal:n})}async function Cn(e,t,n){return B(e,{url:at(e.baseUrl,t),method:`DELETE`,signal:n})}async function wn(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=ct(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function Tn(e,t,n,r){return B(e,{url:ot(e.baseUrl,t),method:`PUT`,body:n,signal:r})}async function En(e,t,n,r){return B(e,{url:st(e.baseUrl,t),method:`PUT`,body:n,signal:r})}function Dn(e){return{description:e.description,usageArgs:e.usageArgs,options:e.options,exampleArgs:e.exampleArgs,skipDefaultApiKeySetup:e.skipDefaultApiKeySetup,notes:e.notes,execute:(t,n)=>e.run(t,n)}}const On=[{flag:`--api-key <key>`,description:`API key`},{flag:`--base-url <url>`,description:`API base URL`},{flag:`--output <format>`,description:`Output format: text, json`},{flag:`--timeout <seconds>`,description:`Request timeout`,type:`number`},{flag:`--quiet`,description:`Suppress non-essential output`},{flag:`--verbose`,description:`Print HTTP request/response details`},{flag:`--no-color`,description:`Disable ANSI colors`},{flag:`--dry-run`,description:`Dry run mode`},{flag:`--non-interactive`,description:`Disable interactive prompts`},{flag:`--concurrent <n>`,description:`Run N parallel requests (default: 1)`,type:`number`},{flag:`--console-region <region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID for delegated access`,type:`number`},{flag:`--help`,description:`Show help`},{flag:`--version`,description:`Print version`}];function kn(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function An(e,t){return`${kn(e||`image`,`image`)}_${kn((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const jn=()=>p(u(),`bailian-output`);function Mn(e,t){let n=t?.flagDir||e.outputDir||jn(),a=t?.subDir?p(n,t.subDir):n;return r(a)||i(a,{recursive:!0}),a}function Nn(e){return e?.nonInteractive===!0||process.env.CI?!1:process.stdout.isTTY===!0&&process.stdin.isTTY===!0}function Pn(){return!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.TRAVIS||process.env.CIRCLECI)}function Fn(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function In(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 Ln(e,t=`boolean`){if(e!=null)return In(e,t)}function Rn(e,t,n=`boolean`){let r=Ln(e,n);return r===void 0?t:r}function zn(e){return Ln(e,`watermark`)??!0}function Bn(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 Vn(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Hn(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=Vn(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let G;function Un(){return G||(process.env.NODE_ENV===`development`?(G=`dev`,G):(G=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,G))}var Wn=A(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=j(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=j(`dns`)},function(e,t){e.exports=j(`util`)},function(e,t){e.exports=j(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},te=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},k=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},A=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},j=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},M=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},N=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},P=new Map,F=new Map;P.set(`Baiduspider-render`,i),P.set(`Baiduspider+`,i),P.set(`Baiduspider-image+`,i),P.set(`360Spider`,a),P.set(`360Spider-Image`,a),P.set(`bingbot`,o),P.set(`Googlebot`,s),P.set(`YandexRenderResourcesBot`,c),P.set(`spider`,l),P.set(`Dataprovider.com`,u),P.set(`AhrefsBot`,d),P.set(`BitSightBot`,f),P.set(`oBot`,p),P.set(`Cincraw`,m),P.set(`DingTalkBot-LinkService`,h),P.set(`YisouSpider`,g),P.set(`Bytespider`,_),P.set(`ev-crawler`,v),P.set(`bitdiscovery`,y),P.set(`Spider`,b),P.set(`Ai2Bot-Dolma`,x),P.set(`dianjing_ad_spider`,S),F.set(`Baiduspider-render`,C),F.set(`Baiduspider+`,C),F.set(`Baiduspider-image+`,C),F.set(`360Spider`,w),F.set(`360Spider-Image`,w),F.set(`bingbot`,ee),F.set(`Googlebot`,T),F.set(`YandexRenderResourcesBot`,E),F.set(`spider`,D),F.set(`Dataprovider.com`,te),F.set(`AhrefsBot`,ne),F.set(`BitSightBot`,re),F.set(`oBot`,O),F.set(`Cincraw`,k),F.set(`DingTalkBot-LinkService`,ie),F.set(`YisouSpider`,A),F.set(`Bytespider`,ae),F.set(`ev-crawler`,oe),F.set(`bitdiscovery`,j),F.set(`Spider`,M),F.set(`Ai2Bot-Dolma`,N),F.set(`dianjing_ad_spider`,se);let ce={productHandlerMap:P,commentHandlerMap:F,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ce),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,x=n(3),S=n.n(x),C=n(4),w=n(5),ee=n.n(w);function T(e){return(T=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 E(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 D(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?E(Object(n),!0).forEach(function(t){te(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):E(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function te(e,t,n){return(t=(function(e){var t=(function(e,t){if(T(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(T(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return T(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ne(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=O(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.
10
- 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 re(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)||O(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
11
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function O(e,t){if(e){if(typeof e==`string`)return k(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)?k(e,t):void 0}}function k(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 ie(){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=re(r[n],2),o=(a[0],a[1]);if(o){var s,c=ne(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 A,ae,oe=(A=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:A,device_id:ee.a.createHash(`md5`).update(ie()).digest(`hex`),platform:`node`}),j=(0,C.promisify)(S.a.resolve);function M(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,D(D({},oe),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}M.prototype=((ae=function(){}).prototype=b.prototype,new ae),M.prototype.constructor=M,M.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,j(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=M}]).default})),Gn=A(((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})),Kn=oe(Wn(),1),qn=oe(Gn(),1);const Jn=()=>p(I(),`telemetry.jsonl`);let Yn;const K=new Set;let q;try{let e=new Kn.default({pid:`bailian-cli-node`,env:Un()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;K.add(e),e.finally(()=>K.delete(e))}return n},q=e,Yn=e.use(qn.default)}catch{}async function Xn(e=1e3){try{if(q)try{typeof q._sendAll==`function`&&q._sendAll()}catch{}if(K.size===0)return;let t=[...K].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Zn(e){try{await he();let n=Jn();try{s(n).size>5242880&&c(n)}catch{}t(n,JSON.stringify(e)+`
12
- `,{mode:384})}catch{}}async function Qn(e){try{if(!Yn)return;Yn(e.command,Hn(e))}catch{}}const $n=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`noColor`,`yes`,`dryRun`,`help`,`nonInteractive`,`async`,`console`]),er=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.noWait.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function tr(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||$n.has(n)||er.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function nr(e,t,n,r){if(!e.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;e.apiKey||e.fileApiKey?l=`api-key`:(e.accessTokenEnv||e.fileAccessToken)&&(l=`access-token`);let u=Bn({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.clientVersion??`unknown`,authMethod:l,params:tr(n)});Zn(u).catch(()=>{}),Qn(u).catch(()=>{})}}function rr(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 ir=class{name=`api`;constructor(e){this.config=e}available(){return!0}async load(){let e=await V(this.config,``,{pageNo:1,pageSize:50}),t=[...e.models],n=Math.ceil(e.total/50);for(let e=2;e<=n;e++){let n=await V(this.config,``,{pageNo:e,pageSize:50});t.push(...n.models)}return t.map(rr).filter(e=>e!==null)}};const ar=`models.jsonl`;function or(){return E(I(),`skills/bailian-docs-llm-wiki`)}function sr(){return E(or(),ar)}function cr(){return E(T(D(import.meta.url)),`../../../../../skills/bailian-docs-llm-wiki/models`)}function lr(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 ur(e){let t=C(e,`utf-8`).split(`
13
- `).filter(Boolean),n=[];for(let e of t)try{let t=lr(JSON.parse(e));t&&n.push(t)}catch{}return n}function dr(){let e=cr();if(!x(E(e,ar)))return!1;let t=or();try{return S(t,{recursive:!0}),b(e,t,{recursive:!0}),!0}catch{return!1}}var fr=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return x(sr())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!dr())?[]:ur(sr())}};async function pr(e,t){let n=[new fr({onPrepareStart:t?.onPrepareStart}),new ir(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 mr={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},J={Single:`single`,Pipeline:`pipeline`},hr={Low:`low`,Medium:`medium`,High:`high`},gr={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Y={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},X={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},_r={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},vr={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},yr=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
7
+ `),u=`ACS3-HMAC-SHA256`,d=`${u}\n${Ae(l)}`,f=je(e.accessKeySecret,d);return a.authorization=`${u} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${f}`,a}function Ae(e){return h(`sha256`).update(e,`utf8`).digest(`hex`)}function je(e,t){return g(`sha256`,e).update(t,`utf8`).digest(`hex`)}function Me(e){return`${e}/compatible-mode/v1/chat/completions`}function Ne(e){return`${e}/api/v1/services/aigc/image-generation/generation`}function Pe(e){return`${e}/api/v1/services/aigc/multimodal-generation/generation`}function Fe(e){return`${e}/api/v1/services/aigc/video-generation/video-synthesis`}function Ie(e,t){return`${e}/api/v1/tasks/${encodeURIComponent(t)}`}function Le(e,t){return`${e}/api/v1/apps/${encodeURIComponent(t)}/completion`}function Re(e){return`${e}/api/v2/apps/memory/add`}function ze(e){return`${e}/api/v2/apps/memory/memory_nodes/search`}function Be(e){return`${e}/api/v2/apps/memory/memory_nodes`}function Ve(e,t){return`${e}/api/v2/apps/memory/memory_nodes/${encodeURIComponent(t)}`}function He(e){return`${e}/api/v1/services/audio/tts/SpeechSynthesizer`}function Ue(e){return`${e}/api/v1/services/audio/asr/transcription`}function We(e){return`${e}/api/v2/apps/memory/profile_schemas`}function Ge(e,t){return`${e}/api/v2/apps/memory/profile_schemas/${encodeURIComponent(t)}/profiles`}function Ke(e){return`${e}/api/v1/indices/rag/index/retrieve`}function qe(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Je(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function Ye(e){return`${e}/api/v1/mcps/WebSearch/mcp`}function Xe(e){return`${e}/compatible-mode/v1/files`}function Ze(e){return`${e}/api/v1/files`}function Qe(e,t){return`${e}/api/v1/files/${encodeURIComponent(t)}`}function $e(e){return`${e}/api/v1/fine-tunes`}function et(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}`}function tt(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/cancel`}function nt(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/logs`}function rt(e,t){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/checkpoints`}function it(e,t,n){return`${e}/api/v1/fine-tunes/${encodeURIComponent(t)}/export/${encodeURIComponent(n)}`}function at(e){return`${e}/api/v1/deployments`}function ot(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}`}function st(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}/scale`}function ct(e,t){return`${e}/api/v1/deployments/${encodeURIComponent(t)}/update`}function lt(e){return`${e}/api/v1/deployments/models`}const ut=`bailian-cli`,dt={t1:`public`,t2:``},ft=JSON.stringify({channel:ut,tags:dt});function z(){return{"x-dashscope-source-config":ft}}function pt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function mt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function ht(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.clientName??`bailian-cli-core`}/${e.clientVersion??`0.0.0-dev`}`,...z(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),mt(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),!t.noAuth){let n=await Ee(e);r.Authorization=`Bearer ${n.token}`,e.verbose&&(console.error(`> ${t.method??`GET`} ${t.url}`),console.error(`> Auth: ${pt(n.token)}`),console.error(`> x-dashscope-source-config: ${ft}`))}let i=gt((t.timeout??e.timeout)*1e3,t.signal),a=await fetch(t.url,{method:t.method??`GET`,headers:r,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:i.signal}).finally(i.cleanup);if(e.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!a.ok){let e={};try{e=await a.json()}catch{}throw P(a.status,e,t.url)}return a}function gt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function B(e,t){let n=await ht(e,t),r;try{r=await n.json()}catch{throw new N(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,M.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw P(200,{error:{message:r.message,type:r.code}},t.url);return r}function _t(e,t){return`${e.replace(/\/$/,``)}/api/v1/mcps/${t}/mcp`}var vt=class{url;sessionId;nextId=1;config;authToken;constructor(e,t){this.config=e,this.url=t}async initialize(){let e=await Ee(this.config);this.authToken=e.token;let t=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.config.clientName??`bailian-cli-core`,version:this.config.clientVersion??`0.0.0-dev`}});this.config.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(t)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new N(`MCP error (${r.error.code}): ${r.error.message}`,M.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.config.clientName??`bailian-cli-core`}/${this.config.clientVersion??`0.0.0-dev`}`,...z()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.config.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.config.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.config.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}};async function*yt(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let o=r.split(`
8
+ `);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const bt={"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 xt(e,t){return bt[e]?.[t]??bt[`cn-beijing`][t]}function St(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 Ct(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function wt(e,t,{api:n,data:r}){let{consoleRegion:i,consoleSite:a,consoleSwitchAgent:o}=St(e),s=xt(i,a),c=`https://${s.csGateway}`,l=s.action,u=Ct(n,r,o),d=new URLSearchParams({params:u,region:i}),f=e.timeout*1e3,p={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};t&&(p.Authorization=`Bearer ${t}`);let m=await fetch(`${c}/cli/api.json?action=${l}&product=sfm_bailian&api=${encodeURIComponent(n)}`,{method:`POST`,headers:p,body:d.toString(),signal:AbortSignal.timeout(f)});if(!m.ok){let e=await m.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${m.status} ${m.statusText}`,M.GENERAL,e.slice(0,500))}let h=await m.json(),g=h.data;if(g?.success===!1&&g.errorCode){let e=g.errorCode,t=typeof e==`string`?e:JSON.stringify(e),n=t.includes(`NotLogined`),r=typeof g.errorMsg==`string`?g.errorMsg:void 0;throw new N(n?`Console session is not logged in or has expired.`:`Console gateway error: ${t}`,n?M.AUTH:M.GENERAL,n?"Run `bl auth login --console` to sign in or refresh your console session.":r&&r!==t?r:void 0)}return h}async function Tt(e,t,n={}){let{pageNo:r=1,pageSize:i=50,name:a=``,providers:o=[],capabilities:s=[]}=n,c=await wt(e,t,{api:`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,data:{input:{pageNo:r,pageSize:i,name:a,providers:o,inferenceProviders:[],features:[],group:!0,capabilities:s,contextWindows:[]}}}),l=c?.data?.DataV2?.data??c?.data??{},u=l?.data?.total??l?.total??0,d=l?.data?.list??l?.list??[],f=[];for(let e of d)if(e.items?.length)for(let t of e.items)f.push(t);else f.push(e);return{total:u,models:f}}const Et=`${F.cn}/api/v1/uploads`;async function Dt(e,t,n){let r=`${Et}?action=getPolicy&model=${encodeURIComponent(t)}`,i=Mt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...z()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new N(`Failed to get upload policy (HTTP ${a.status}): ${e}`,M.GENERAL)}return(await a.json()).data}async function Ot(e,t,n){let r=d(t),i=`${e.upload_dir}/${r}`,o=a(t),s=new FormData;s.append(`OSSAccessKeyId`,e.oss_access_key_id),s.append(`Signature`,e.signature),s.append(`policy`,e.policy),s.append(`x-oss-object-acl`,e.x_oss_object_acl),s.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),s.append(`key`,i),s.append(`success_action_status`,`200`),s.append(`file`,new Blob([o]),r);let c=Mt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...z()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new N(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,M.GENERAL)}return`oss://${i}`}async function kt(e){let{apiKey:t,model:n,filePath:i,signal:a}=e;if(!r(i))throw new N(`File not found: ${i}`,M.USAGE);if(!s(i).isFile())throw new N(`Not a file: ${i}`,M.USAGE);return Ot(await Dt(t,n,a),i,a)}function At(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:r(e)}async function jt(e,t,n,r={}){return At(e)?kt({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function Mt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}async function Nt(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=s(r),c=d(r),l=v.toWeb(n(r)),u=await new Response(l).blob(),f=new FormData;f.append(`file`,u,c),f.append(`purpose`,i);let p=await B(e,{url:Xe(e.baseUrl),method:`POST`,body:f,signal:a});if(p.id)return{file_id:p.id,name:p.filename??c,size:p.bytes??o.size,purpose:p.purpose??i,gmt_create:p.created_at?new Date(p.created_at*1e3).toISOString():void 0};let m=p.data?.failed_uploads;if(Array.isArray(m)&&m.length>0){let e=m[0]??{};throw new N(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,M.GENERAL,`Server reported failure for ${c}. Re-run with --verbose to see the raw response.`)}throw new N(`Dataset upload of ${c} 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 Pt(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=Ze(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function Ft(e,t,n){return B(e,{url:Qe(e.baseUrl,t),method:`GET`,signal:n})}async function It(e,t,n){let r=await ht(e,{url:Qe(e.baseUrl,t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Lt=300*1024*1024;function Rt(e,t=Lt){if(!r(e))throw new N(`File not found: ${e}`,M.USAGE);let n=s(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:f(e).toLowerCase()}}function V(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function zt(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt.`,M.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, else ChatML).`)}function Bt(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 Vt=new Set([`system`,`user`,`assistant`]);function Ht(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(V(`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`||!Vt.has(a))&&r.push(V(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(V(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function Ut(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(V(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(V(`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(...Ht(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(V(`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(V(`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(V(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(V(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const Wt={name:`chatml`,detect:()=>!0,inspect:Ut};function Gt(e,t){let n=[];if(!(`text`in e))return n.push(V(`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(V(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(V(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Kt={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Gt};function qt(e,t){let n=Ut(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(V(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(V(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...Ht(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(V(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...Ht(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(V(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Jt=[{name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:qt},Kt,Wt];function Yt(e,t){return t===void 0?Jt.find(t=>t.detect(e))??Wt:Jt.find(e=>e.name===t)||Wt}async function Xt(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(V(`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 Zt(e,t,r,i,a){let o=r?null:new Set(Bt(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(V(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...Qt(n,u,i))}return{sampled:c,issues:s}}function Qt(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[V(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Yt(r,n).inspect(r,t)}const H=[{format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Xt(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[V(`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 Zt(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 $t(e){let t=f(e).toLowerCase(),n=H.find(e=>e.extensions.includes(t));if(!n){let e=H.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 en(e){H.some(t=>t.format===e.format)||H.push(e)}async function tn(e,t={}){let{bytes:n}=Rt(e,t.maxBytes??314572800),r=await $t(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function nn(){return H.map(e=>({format:e.format,extensions:[...e.extensions]}))}function rn(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 an(e,t,n){return B(e,{url:$e(e.baseUrl),method:`POST`,body:t,signal:n})}async function on(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=$e(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function sn(e,t,n){return B(e,{url:et(e.baseUrl,t),method:`GET`,signal:n})}async function cn(e,t,n){return B(e,{url:tt(e.baseUrl,t),method:`POST`,signal:n})}async function ln(e,t,n){return B(e,{url:et(e.baseUrl,t),method:`DELETE`,signal:n})}async function un(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=nt(e.baseUrl,t);return B(e,{url:r.toString()?`${i}?${r.toString()}`:i,method:`GET`,signal:n.signal})}async function dn(e,t,n){return B(e,{url:rt(e.baseUrl,t),method:`GET`,signal:n})}async function fn(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),B(e,{url:`${it(e.baseUrl,t,n)}?${a.toString()}`,method:`GET`,signal:i})}const U={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},pn=Object.keys(U),mn=`sft-lora`;function hn(e){return e in U}function gn(e){return U[e].server}function _n(e){let{method:t,variant:n}=U[e];return{method:t,variant:n}}function vn(e,t){if(!e)return!1;let{method:n,variant:r}=U[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function yn(e){return e?pn.filter(t=>vn(e,t)):[]}async function bn(e,t){return(await Tt(e,``,{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const xn=`INSUFFICIENT_SAMPLES`;function Sn(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:xn,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(`
9
+ `)}}async function Cn(e,t,n){return B(e,{url:at(e.baseUrl),method:`POST`,body:t,signal:n})}async function wn(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=at(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function Tn(e,t,n){return B(e,{url:ot(e.baseUrl,t),method:`GET`,signal:n})}async function En(e,t,n){return B(e,{url:ot(e.baseUrl,t),method:`DELETE`,signal:n})}async function Dn(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=lt(e.baseUrl);return B(e,{url:n.toString()?`${r}?${n.toString()}`:r,method:`GET`,signal:t.signal})}async function On(e,t,n,r){return B(e,{url:st(e.baseUrl,t),method:`PUT`,body:n,signal:r})}async function kn(e,t,n,r){return B(e,{url:ct(e.baseUrl,t),method:`PUT`,body:n,signal:r})}function An(e){return{description:e.description,usageArgs:e.usageArgs,options:e.options,exampleArgs:e.exampleArgs,skipDefaultApiKeySetup:e.skipDefaultApiKeySetup,notes:e.notes,execute:(t,n)=>e.run(t,n)}}const jn=[{flag:`--api-key <key>`,description:`API key`},{flag:`--base-url <url>`,description:`API base URL`},{flag:`--output <format>`,description:`Output format: text, json`},{flag:`--timeout <seconds>`,description:`Request timeout`,type:`number`},{flag:`--quiet`,description:`Suppress non-essential output`},{flag:`--verbose`,description:`Print HTTP request/response details`},{flag:`--no-color`,description:`Disable ANSI colors`},{flag:`--dry-run`,description:`Dry run mode`},{flag:`--non-interactive`,description:`Disable interactive prompts`},{flag:`--concurrent <n>`,description:`Run N parallel requests (default: 1)`,type:`number`},{flag:`--console-region <region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID for delegated access`,type:`number`},{flag:`--help`,description:`Show help`},{flag:`--version`,description:`Print version`}];function Mn(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Nn(e,t){return`${Mn(e||`image`,`image`)}_${Mn((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const Pn=()=>p(u(),`bailian-output`);function Fn(e,t){let n=t?.flagDir||e.outputDir||Pn(),a=t?.subDir?p(n,t.subDir):n;return r(a)||i(a,{recursive:!0}),a}function In(e){return e?.nonInteractive===!0||process.env.CI?!1:process.stdout.isTTY===!0&&process.stdin.isTTY===!0}function Ln(){return!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.TRAVIS||process.env.CIRCLECI)}function Rn(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function zn(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 Bn(e,t=`boolean`){if(e!=null)return zn(e,t)}function Vn(e,t,n=`boolean`){let r=Bn(e,n);return r===void 0?t:r}function Hn(e){return Bn(e,`watermark`)??!0}function Un(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 Wn(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Gn(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=Wn(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let W;function Kn(){return W||(process.env.NODE_ENV===`development`?(W=`dev`,W):(W=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,W))}var qn=O(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=j(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=j(`dns`)},function(e,t){e.exports=j(`util`)},function(e,t){e.exports=j(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},b=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},re=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},k=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},A=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},j=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},M=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},N=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},P=new Map,F=new Map;P.set(`Baiduspider-render`,i),P.set(`Baiduspider+`,i),P.set(`Baiduspider-image+`,i),P.set(`360Spider`,a),P.set(`360Spider-Image`,a),P.set(`bingbot`,o),P.set(`Googlebot`,s),P.set(`YandexRenderResourcesBot`,c),P.set(`spider`,l),P.set(`Dataprovider.com`,u),P.set(`AhrefsBot`,d),P.set(`BitSightBot`,f),P.set(`oBot`,p),P.set(`Cincraw`,m),P.set(`DingTalkBot-LinkService`,h),P.set(`YisouSpider`,g),P.set(`Bytespider`,_),P.set(`ev-crawler`,v),P.set(`bitdiscovery`,y),P.set(`Spider`,ee),P.set(`Ai2Bot-Dolma`,b),P.set(`dianjing_ad_spider`,x),F.set(`Baiduspider-render`,S),F.set(`Baiduspider+`,S),F.set(`Baiduspider-image+`,S),F.set(`360Spider`,C),F.set(`360Spider-Image`,C),F.set(`bingbot`,te),F.set(`Googlebot`,w),F.set(`YandexRenderResourcesBot`,T),F.set(`spider`,ne),F.set(`Dataprovider.com`,re),F.set(`AhrefsBot`,ie),F.set(`BitSightBot`,ae),F.set(`oBot`,E),F.set(`Cincraw`,D),F.set(`DingTalkBot-LinkService`,oe),F.set(`YisouSpider`,O),F.set(`Bytespider`,k),F.set(`ev-crawler`,A),F.set(`bitdiscovery`,j),F.set(`Spider`,M),F.set(`Ai2Bot-Dolma`,N),F.set(`dianjing_ad_spider`,se);let ce={productHandlerMap:P,commentHandlerMap:F,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ce),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var ee=y,b=n(3),x=n.n(b),S=n(4),C=n(5),te=n.n(C);function w(e){return(w=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 T(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 ne(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?T(Object(n),!0).forEach(function(t){re(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function re(e,t,n){return(t=(function(e){var t=(function(e,t){if(w(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(w(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return w(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ie(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=E(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
10
+ 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 ae(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||E(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
11
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function E(e,t){if(e){if(typeof e==`string`)return D(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D(e,t):void 0}}function D(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function oe(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=ae(r[n],2),o=(a[0],a[1]);if(o){var s,c=ie(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var O,k,A=(O=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:O,device_id:te.a.createHash(`md5`).update(oe()).digest(`hex`),platform:`node`}),j=(0,S.promisify)(x.a.resolve);function M(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,ee.call(this,ne(ne({},A),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}M.prototype=((k=function(){}).prototype=ee.prototype,new k),M.prototype.constructor=M,M.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,j(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=M}]).default})),Jn=O(((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})),Yn=A(qn(),1),Xn=A(Jn(),1);const Zn=()=>p(I(),`telemetry.jsonl`);let Qn;const G=new Set;let K;try{let e=new Yn.default({pid:`bailian-cli-node`,env:Kn()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;G.add(e),e.finally(()=>G.delete(e))}return n},K=e,Qn=e.use(Xn.default)}catch{}async function $n(e=1e3){try{if(K)try{typeof K._sendAll==`function`&&K._sendAll()}catch{}if(G.size===0)return;let t=[...G].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function er(e){try{await R();let n=Zn();try{s(n).size>5242880&&c(n)}catch{}t(n,JSON.stringify(e)+`
12
+ `,{mode:384})}catch{}}async function tr(e){try{if(!Qn)return;Qn(e.command,Gn(e))}catch{}}const nr=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`noColor`,`yes`,`dryRun`,`help`,`nonInteractive`,`async`,`console`]),rr=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.noWait.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function ir(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||nr.has(n)||rr.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function ar(e,t,n,r){if(!e.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;e.apiKey||e.fileApiKey?l=`api-key`:(e.accessTokenEnv||e.fileAccessToken)&&(l=`access-token`);let u=Un({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.clientVersion??`unknown`,authMethod:l,params:ir(n)});er(u).catch(()=>{}),tr(u).catch(()=>{})}}function or(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 sr=class{name=`api`;constructor(e){this.config=e}available(){return!0}async load(){let e=await Tt(this.config,``,{pageNo:1,pageSize:50}),t=[...e.models],n=Math.ceil(e.total/50);for(let e=2;e<=n;e++){let n=await Tt(this.config,``,{pageNo:e,pageSize:50});t.push(...n.models)}return t.map(or).filter(e=>e!==null)}};const cr=`models.jsonl`;function lr(){return T(I(),`skills/bailian-docs-llm-wiki`)}function ur(){return T(lr(),cr)}function dr(){return T(w(ne(import.meta.url)),`../../../../../skills/bailian-docs-llm-wiki/models`)}function fr(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 pr(e){let t=S(e,`utf-8`).split(`
13
+ `).filter(Boolean),n=[];for(let e of t)try{let t=fr(JSON.parse(e));t&&n.push(t)}catch{}return n}function mr(){let e=dr();if(!b(T(e,cr)))return!1;let t=lr();try{return x(t,{recursive:!0}),ee(e,t,{recursive:!0}),!0}catch{return!1}}var hr=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return b(ur())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!mr())?[]:pr(ur())}};async function gr(e,t){let n=[new hr({onPrepareStart:t?.onPrepareStart}),new sr(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 _r={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},q={Single:`single`,Pipeline:`pipeline`},vr={Low:`low`,Medium:`medium`,High:`high`},J={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Y={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},X={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},yr={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},br={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},xr=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
14
14
 
15
15
  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.
16
16
 
@@ -51,7 +51,7 @@ Single task:
51
51
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
52
52
 
53
53
  Pipeline (only when confident multi-model is needed):
54
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,br=`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's need has been decomposed into multi-step pipeline. Select the best model for each step.
54
+ {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Sr=`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.
55
55
 
56
56
  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.
57
57
 
@@ -90,7 +90,7 @@ Key principles:
90
90
 
91
91
  Or (if single model suffices):
92
92
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
93
- ["key highlights"]}]}`,Z={complexity:J.Single,taskSummary:``,scenarioHints:[],inputModality:[],outputModality:[],requiredCapabilities:[X.TG],requiredFeatures:[],budget:hr.Medium,contextNeed:gr.Standard,qualityPreference:Y.Balanced,confidence:0};async function xr(e,t){let n=Ne(e.baseUrl),r={model:`qwen-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
93
+ ["key highlights"]}]}`,Z={complexity:q.Single,taskSummary:``,scenarioHints:[],inputModality:[],outputModality:[],requiredCapabilities:[X.TG],requiredFeatures:[],budget:vr.Medium,contextNeed:J.Standard,qualityPreference:Y.Balanced,confidence:0};async function Cr(e,t){let n=Me(e.baseUrl),r={model:`qwen-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
94
94
 
95
95
  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.
96
96
 
@@ -136,9 +136,9 @@ Analyze whether the user mentioned specific models, model families, or vendors:
136
136
  - qualityPreference: "flagship"/"balanced"/"cost-optimized"
137
137
  - modelPreference: { mode, targets?, excludes? }
138
138
 
139
- Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0};try{let t=((await B(e,{url:n,method:`POST`,body:r,timeout:5e3})).choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!t)return Z;let i=JSON.parse(t[0]),a=[`scoped`,`comparison`,`alternative`],o=i.modelPreference,s=o&&typeof o==`object`?{mode:a.includes(o.mode)?o.mode:`unconstrained`,targets:Array.isArray(o.targets)?o.targets:void 0,excludes:Array.isArray(o.excludes)?o.excludes:void 0}:void 0;return{complexity:i.complexity===J.Pipeline?J.Pipeline:J.Single,taskSummary:typeof i.taskSummary==`string`?i.taskSummary:``,scenarioHints:Array.isArray(i.scenarioHints)?i.scenarioHints:[],segments:Array.isArray(i.segments)?i.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(i.inputModality)?i.inputModality:[],outputModality:Array.isArray(i.outputModality)?i.outputModality:[],requiredCapabilities:Array.isArray(i.requiredCapabilities)?i.requiredCapabilities:[],requiredFeatures:Array.isArray(i.requiredFeatures)?i.requiredFeatures:[],budget:i.budget??Z.budget,contextNeed:i.contextNeed??Z.contextNeed,qualityPreference:i.qualityPreference??Z.qualityPreference,confidence:1,modelPreference:s}}catch{return Z}}const Sr=/-\d{4}-\d{2}-\d{2}$/,Cr=new Set([X.IG,X.VG,X.TTS,X.RealtimeTTS,X.ThreeDGeneration]),wr=new Set([X.TG,X.Reasoning,X.ASR,X.RealtimeASR,X.RealtimeAudioTranslate,X.TR,X.ME]),Tr={standard:0,large:32e3,"extra-large":128e3};function Er(e){let t=!1,n=!1;for(let r of e)Cr.has(r)&&(t=!0),wr.has(r)&&(n=!0);return t&&n}function Dr(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Sr,``);return n===e?!0:!t.has(n)})}function Or(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 kr(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Ar(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=Tr[i];return d>0&&(c??0)>=d&&(u+=8),a===Y.Flagship&&l===vr.Flagship||a===Y.CostOptimized&&l===vr.CostOptimized?u+=15:a===Y.Balanced&&l===vr.Flagship&&(u+=5),u}function Q(e,t,n){return e.map(e=>({model:e,score:Ar(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function jr(e){return new Set(e.map(({model:e})=>e.model))}function Mr(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 Nr(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function Pr(e,t,n){return n.size>=10?[]:Q(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Fr(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:J.Single,taskSummary:``,scenarioHints:[],inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:gr.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Or(e,a,o)&&kr(e,n));return l.length<5&&(l=e.filter(e=>Or(e,a,o))),l.length<5&&(l=e),Q(l,c,5)}function Ir(e,t){e=Dr(e);let n;if(t.complexity===J.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=Nr(Fr(e,i,a,t.budget,t.qualityPreference),jr(r));r=[...r,...o]}let i=Pr(e,t,jr(r));n=[...r,...i]}else if(Er(t.requiredCapabilities))n=Lr(e,t);else{let r=e.filter(e=>Or(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Q(r,t,50)}return Mr(n,3)}function Lr(e,t){let n=t.requiredCapabilities.filter(e=>Cr.has(e)),r=t.requiredCapabilities.filter(e=>wr.has(e)),i=[];if(n.length>0&&(i=Q(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=jr(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Q(o,a,25)]}let a=Pr(e,t,jr(i));return[...i,...a]}const Rr=`text-embedding-v4`;function zr(){return E(I(),`skills/bailian-docs-llm-wiki`)}function Br(){return E(zr(),`models-embeddings.json`)}function Vr(){let e=Br();if(!x(e))return null;try{return JSON.parse(C(e,`utf-8`)).items}catch{return null}}async function Hr(e,t){return(await B(e,{url:`${e.baseUrl}/compatible-mode/v1/embeddings`,method:`POST`,body:{model:Rr,input:[t],dimensions:512,encoding_format:`float`},timeout:1e4})).data[0].embedding}async function Ur(e,t){return(await B(e,{url:`${e.baseUrl}/compatible-mode/v1/embeddings`,method:`POST`,body:{model:Rr,input:t,dimensions:512,encoding_format:`float`},timeout:3e4})).data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}const Wr={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Gr={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Kr(){let e=E(zr(),`groups`),t=new Map;if(!x(e))return t;for(let n of w(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(C(E(e,n),`utf-8`)),i=r.description??``;if(r.items)for(let e of r.items)t.set(e.model,e.description||i)}catch{}return t}function qr(e,t){let n=(e.capabilities??[]).map(e=>Wr[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Gr[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Gr[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 Jr(e,t){let n=Kr(),r=t.map(e=>qr(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Ur(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Rr,dimensions:512,count:a.length,items:a},s=Br();return S(T(s),{recursive:!0}),ee(s,JSON.stringify(o)),a}function Yr(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 Xr=null;function Zr(){return Xr===null&&(Xr=Vr()),Xr}function Qr(){return Zr()!==null}function $r(e,t){let n=t.toLowerCase();return[e.model,e.name,e.family,e.familyName,e.provider].some(e=>e?.toLowerCase().includes(n))}function ei(e,t){return t.some(t=>$r(e,t))}function ti(e,t){return t.length===0?e:e.filter(({model:e})=>!ei(e,t))}function ni(e,t){let n=e.inferenceMetadata?.request_modality??[],r=e.inferenceMetadata?.response_modality??[],i=t.inputModality.length===0||t.inputModality.some(e=>n.includes(e)),a=t.outputModality.length===0||t.outputModality.some(e=>r.includes(e));return!i||!a?!1:t.requiredCapabilities.length===0?!0:t.requiredCapabilities.some(t=>e.capabilities.includes(t))}function $(e,t,n,r){return e.filter(e=>n.has(e.id)).map(e=>({id:e.id,similarity:Yr(t,e.vector)})).sort((e,t)=>t.similarity-e.similarity).slice(0,r)}function ri(e,t,n,r,i){let a=r.targets??[],o=a.length>0?e.filter(e=>ei(e,a)):e,s=o.length>=5?o:e,c=$(t,n,new Set(s.map(e=>e.model)),i),l=new Map(e.map(e=>[e.model,e])),u=[];if(o.length<5&&a.length>0){for(let e of o)u.push({model:e,score:1});let e=new Set(u.map(({model:e})=>e.model));for(let{id:t,similarity:n}of c){if(e.has(t))continue;let r=l.get(t);if(r&&u.push({model:r,score:n}),u.length>=i)break}return u}for(let{id:e,similarity:t}of c){let n=l.get(e);n&&u.push({model:n,score:t})}return u}function ii(e,t,n,r,i){let a=r.targets??[],o=new Map(e.map(e=>[e.model,e])),s=[],c=new Set;for(let t of e)ei(t,a)&&!c.has(t.model)&&(s.push({model:t,score:1}),c.add(t.model));let l=i-s.length;if(l>0){let r=$(t,n,new Set(e.filter(e=>!c.has(e.model)).map(e=>e.model)),l);for(let{id:e,similarity:t}of r){let n=o.get(e);n&&s.push({model:n,score:t})}}return s}function ai(e,t,n,r,i){let a=r.targets??[],o=new Map(e.map(e=>[e.model,e])),s=e.filter(e=>ei(e,a)),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push({model:e,score:1}),u.add(e.model);let d=e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),f=$(t,n,new Set(d.map(e=>e.model)),i-l.length);for(let{id:e,similarity:t}of f){let n=o.get(e);n&&l.push({model:n,score:t})}return l}async function oi(e,t,n,r,i){let a=Zr();a||(a=await Jr(e,t),Xr=a);let o=await Hr(e,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=ri(t,a,o,c,r);break;case`comparison`:e=ii(t,a,o,c,r);break;case`alternative`:e=ai(t,a,o,c,r);break;default:e=[]}return ti(e,l)}if(i?.complexity===J.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let i=t.filter(e=>ni(e,r)),l=new Set(i.filter(t=>!e.has(t.model)).map(e=>e.model));if(l.size===0)continue;let u=$(a,o,l,c);for(let{id:t,similarity:r}of u){let i=s.get(t);i&&!e.has(t)&&(n.push({model:i,score:r}),e.add(t))}}return ti(n,l)}let u=new Set(t.map(e=>e.model)),d=$(a,o,u,r),f=[];for(let{id:e,similarity:t}of d){let n=s.get(e);n&&f.push({model:n,score:t})}return ti(f,l)}function si(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function ci(e){if(!e.qpmInfo)return;let t=Object.entries(e.qpmInfo);if(t.length!==0)return t.map(([e,t])=>`${e}:${t.count_limit}/${t.count_limit_period}s`).join(`, `)}function li(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=si(e);r&&t.push(`Pricing: ${r}`);let i=ci(e);return i&&t.push(`QPM: ${i}`),e.versionTag&&t.push(`Version: ${e.versionTag}`),e.openSource!==void 0&&t.push(`Open Source: ${e.openSource?`Yes`:`No`}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
140
- `)}function ui(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!==gr.Standard&&f.push(`Context: ${l}`),d&&d.mode!==`unconstrained`&&(f.push(`Mode: ${d.mode}`),d.targets?.length&&f.push(`Targets: ${d.targets.join(`, `)}`),d.excludes?.length&&f.push(`Excludes: ${d.excludes.join(`, `)}`)),u?.length){f.push(`Pipeline Steps:`);for(let e of u){let t=e.inputModality.join(`,`)||`none`,n=e.outputModality.join(`,`)||`none`,r=e.requiredCapabilities.join(`,`)||`none`;f.push(` - ${e.step} (Input: ${t} → Output: ${n}, Capabilities: ${r})`)}}return f.join(`
141
- `)}function di(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 fi(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 pi(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 mi(e,t,n,r,i,a){let o=li(t),s=ui(n),c=n.modelPreference?.mode,l;if(c===`comparison`)l=`You are a model comparison advisor for Alibaba Cloud Model Studio. The user wants to compare specific models — analyze them against the use case.
139
+ Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0};try{let t=((await B(e,{url:n,method:`POST`,body:r,timeout:5e3})).choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!t)return Z;let i=JSON.parse(t[0]),a=[`scoped`,`comparison`,`alternative`],o=i.modelPreference,s=o&&typeof o==`object`?{mode:a.includes(o.mode)?o.mode:`unconstrained`,targets:Array.isArray(o.targets)?o.targets:void 0,excludes:Array.isArray(o.excludes)?o.excludes:void 0}:void 0;return{complexity:i.complexity===q.Pipeline?q.Pipeline:q.Single,taskSummary:typeof i.taskSummary==`string`?i.taskSummary:``,scenarioHints:Array.isArray(i.scenarioHints)?i.scenarioHints:[],segments:Array.isArray(i.segments)?i.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(i.inputModality)?i.inputModality:[],outputModality:Array.isArray(i.outputModality)?i.outputModality:[],requiredCapabilities:Array.isArray(i.requiredCapabilities)?i.requiredCapabilities:[],requiredFeatures:Array.isArray(i.requiredFeatures)?i.requiredFeatures:[],budget:i.budget??Z.budget,contextNeed:i.contextNeed??Z.contextNeed,qualityPreference:i.qualityPreference??Z.qualityPreference,confidence:1,modelPreference:s}}catch{return Z}}const wr=/-\d{4}-\d{2}-\d{2}$/,Tr=new Set([X.IG,X.VG,X.TTS,X.RealtimeTTS,X.ThreeDGeneration]),Er=new Set([X.TG,X.Reasoning,X.ASR,X.RealtimeASR,X.RealtimeAudioTranslate,X.TR,X.ME]),Dr={standard:0,large:32e3,"extra-large":128e3};function Or(e){let t=!1,n=!1;for(let r of e)Tr.has(r)&&(t=!0),Er.has(r)&&(n=!0);return t&&n}function kr(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(wr,``);return n===e?!0:!t.has(n)})}function Ar(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 jr(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Mr(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=Dr[i];return d>0&&(c??0)>=d&&(u+=8),a===Y.Flagship&&l===br.Flagship||a===Y.CostOptimized&&l===br.CostOptimized?u+=15:a===Y.Balanced&&l===br.Flagship&&(u+=5),u}function Q(e,t,n){return e.map(e=>({model:e,score:Mr(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Nr(e){return new Set(e.map(({model:e})=>e.model))}function Pr(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 Fr(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function Ir(e,t,n){return n.size>=10?[]:Q(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function Lr(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:q.Single,taskSummary:``,scenarioHints:[],inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:J.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Ar(e,a,o)&&jr(e,n));return l.length<5&&(l=e.filter(e=>Ar(e,a,o))),l.length<5&&(l=e),Q(l,c,5)}function Rr(e,t){e=kr(e);let n;if(t.complexity===q.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=Fr(Lr(e,i,a,t.budget,t.qualityPreference),Nr(r));r=[...r,...o]}let i=Ir(e,t,Nr(r));n=[...r,...i]}else if(Or(t.requiredCapabilities))n=zr(e,t);else{let r=e.filter(e=>Ar(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Q(r,t,50)}return Pr(n,3)}function zr(e,t){let n=t.requiredCapabilities.filter(e=>Tr.has(e)),r=t.requiredCapabilities.filter(e=>Er.has(e)),i=[];if(n.length>0&&(i=Q(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Nr(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Q(o,a,25)]}let a=Ir(e,t,Nr(i));return[...i,...a]}const Br=`text-embedding-v4`;function Vr(){return T(I(),`skills/bailian-docs-llm-wiki`)}function Hr(){return T(Vr(),`models-embeddings.json`)}function Ur(){let e=Hr();if(!b(e))return null;try{return JSON.parse(S(e,`utf-8`)).items}catch{return null}}async function Wr(e,t){return(await B(e,{url:`${e.baseUrl}/compatible-mode/v1/embeddings`,method:`POST`,body:{model:Br,input:[t],dimensions:512,encoding_format:`float`},timeout:1e4})).data[0].embedding}async function Gr(e,t){return(await B(e,{url:`${e.baseUrl}/compatible-mode/v1/embeddings`,method:`POST`,body:{model:Br,input:t,dimensions:512,encoding_format:`float`},timeout:3e4})).data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}const Kr={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},qr={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Jr(){let e=T(Vr(),`groups`),t=new Map;if(!b(e))return t;for(let n of C(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(S(T(e,n),`utf-8`)),i=r.description??``;if(r.items)for(let e of r.items)t.set(e.model,e.description||i)}catch{}return t}function Yr(e,t){let n=(e.capabilities??[]).map(e=>Kr[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>qr[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>qr[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 Xr(e,t){let n=Jr(),r=t.map(e=>Yr(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Gr(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:Br,dimensions:512,count:a.length,items:a},s=Hr();return x(w(s),{recursive:!0}),te(s,JSON.stringify(o)),a}function Zr(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 Qr=null;function $r(){return Qr===null&&(Qr=Ur()),Qr}function ei(){return $r()!==null}function ti(e,t){let n=t.toLowerCase();return[e.model,e.name,e.family,e.familyName,e.provider].some(e=>e?.toLowerCase().includes(n))}function ni(e,t){return t.some(t=>ti(e,t))}function ri(e,t){return t.length===0?e:e.filter(({model:e})=>!ni(e,t))}function ii(e,t){let n=e.inferenceMetadata?.request_modality??[],r=e.inferenceMetadata?.response_modality??[],i=t.inputModality.length===0||t.inputModality.some(e=>n.includes(e)),a=t.outputModality.length===0||t.outputModality.some(e=>r.includes(e));return!i||!a?!1:t.requiredCapabilities.length===0?!0:t.requiredCapabilities.some(t=>e.capabilities.includes(t))}function $(e,t,n,r){return e.filter(e=>n.has(e.id)).map(e=>({id:e.id,similarity:Zr(t,e.vector)})).sort((e,t)=>t.similarity-e.similarity).slice(0,r)}function ai(e,t,n,r,i){let a=r.targets??[],o=a.length>0?e.filter(e=>ni(e,a)):e,s=o.length>=5?o:e,c=$(t,n,new Set(s.map(e=>e.model)),i),l=new Map(e.map(e=>[e.model,e])),u=[];if(o.length<5&&a.length>0){for(let e of o)u.push({model:e,score:1});let e=new Set(u.map(({model:e})=>e.model));for(let{id:t,similarity:n}of c){if(e.has(t))continue;let r=l.get(t);if(r&&u.push({model:r,score:n}),u.length>=i)break}return u}for(let{id:e,similarity:t}of c){let n=l.get(e);n&&u.push({model:n,score:t})}return u}function oi(e,t,n,r,i){let a=r.targets??[],o=new Map(e.map(e=>[e.model,e])),s=[],c=new Set;for(let t of e)ni(t,a)&&!c.has(t.model)&&(s.push({model:t,score:1}),c.add(t.model));let l=i-s.length;if(l>0){let r=$(t,n,new Set(e.filter(e=>!c.has(e.model)).map(e=>e.model)),l);for(let{id:e,similarity:t}of r){let n=o.get(e);n&&s.push({model:n,score:t})}}return s}function si(e,t,n,r,i){let a=r.targets??[],o=new Map(e.map(e=>[e.model,e])),s=e.filter(e=>ni(e,a)),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push({model:e,score:1}),u.add(e.model);let d=e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),f=$(t,n,new Set(d.map(e=>e.model)),i-l.length);for(let{id:e,similarity:t}of f){let n=o.get(e);n&&l.push({model:n,score:t})}return l}async function ci(e,t,n,r,i){let a=$r();a||(a=await Xr(e,t),Qr=a);let o=await Wr(e,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=ai(t,a,o,c,r);break;case`comparison`:e=oi(t,a,o,c,r);break;case`alternative`:e=si(t,a,o,c,r);break;default:e=[]}return ri(e,l)}if(i?.complexity===q.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let i=t.filter(e=>ii(e,r)),l=new Set(i.filter(t=>!e.has(t.model)).map(e=>e.model));if(l.size===0)continue;let u=$(a,o,l,c);for(let{id:t,similarity:r}of u){let i=s.get(t);i&&!e.has(t)&&(n.push({model:i,score:r}),e.add(t))}}return ri(n,l)}let u=new Set(t.map(e=>e.model)),d=$(a,o,u,r),f=[];for(let{id:e,similarity:t}of d){let n=s.get(e);n&&f.push({model:n,score:t})}return ri(f,l)}function li(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function ui(e){if(!e.qpmInfo)return;let t=Object.entries(e.qpmInfo);if(t.length!==0)return t.map(([e,t])=>`${e}:${t.count_limit}/${t.count_limit_period}s`).join(`, `)}function di(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=li(e);r&&t.push(`Pricing: ${r}`);let i=ui(e);return i&&t.push(`QPM: ${i}`),e.versionTag&&t.push(`Version: ${e.versionTag}`),e.openSource!==void 0&&t.push(`Open Source: ${e.openSource?`Yes`:`No`}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
140
+ `)}function fi(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!==J.Standard&&f.push(`Context: ${l}`),d&&d.mode!==`unconstrained`&&(f.push(`Mode: ${d.mode}`),d.targets?.length&&f.push(`Targets: ${d.targets.join(`, `)}`),d.excludes?.length&&f.push(`Excludes: ${d.excludes.join(`, `)}`)),u?.length){f.push(`Pipeline Steps:`);for(let e of u){let t=e.inputModality.join(`,`)||`none`,n=e.outputModality.join(`,`)||`none`,r=e.requiredCapabilities.join(`,`)||`none`;f.push(` - ${e.step} (Input: ${t} → Output: ${n}, Capabilities: ${r})`)}}return f.join(`
141
+ `)}function pi(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 mi(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 hi(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 gi(e,t,n,r,i,a){let o=di(t),s=fi(n),c=n.modelPreference?.mode,l;if(c===`comparison`)l=`You are a model comparison advisor for Alibaba Cloud Model Studio. The user wants to compare specific models — analyze them against the use case.
142
142
 
143
143
  CRITICAL: You MUST respond entirely in English. Do not use any Chinese characters anywhere in your response. Every field — reason, highlights — must be written in English.
144
144
 
@@ -180,4 +180,4 @@ The intent's modelPreference.targets is the reference model.
180
180
  - Output strict JSON
181
181
 
182
182
  ## Output Format
183
- {"type":"single","recommendations":[{"model":"model ID","reason":"alternative analysis","highlights":["differentiators"]}]}`;else if(c===`scoped`){let e=n.modelPreference?.targets?.length?`\n\n## Scope Restriction\nThe user explicitly requested recommendations from: ${n.modelPreference.targets.join(`, `)}. Prioritize models within this scope.`:``;l=(n.complexity===J.Pipeline?br:yr)+e}else l=n.complexity===J.Pipeline?br:yr;let u=a?.enableThinking??!1,d=n.complexity===J.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:u?`qwen3.6-flash`:`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=Ne(e.baseUrl),m;if(u){let t=await z(e,{url:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of _t(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 B(e,{url:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:J.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===J.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=fi(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return pi(e,g),{type:J.Pipeline,summary:h.summary??``,steps:e}}let _=fi(h.recommendations??h??[],g,i);return{type:J.Single,recommendations:_}}export{le as BAILIAN_HOST,N as BailianError,hr as Budgets,lt as CHANNEL,Oe as CONSOLE_GATEWAY_NO_TOKEN_MESSAGE,X as Capabilities,J as Complexities,gr as ContextNeeds,dn as DEFAULT_TRAINING_TYPE,ce as DOCS_HOSTS,M as ExitCode,_r as Features,On as GLOBAL_OPTIONS,vn as INSUFFICIENT_SAMPLES_CODE,Pt as MAX_DATASET_BYTES,gt as McpClient,mr as Modalities,vr as ModelCategories,Y as QualityPreferences,F as REGIONS,dt as SOURCE_CONFIG,ut as TAGS,un as TRAINING_TYPES_CLI,W as TRAINING_TYPE_MAP,xr as analyzeIntent,Re as appCompletionEndpoint,ht as bailianMcpUrl,di as buildDocLink,St as callConsoleGateway,an as cancelFineTune,Ne as chatEndpoint,Ee as clearApiKey,bn as createDeployment,tn as createFineTune,Bn as createTrackingEvent,Dn as defineCommand,Nt as deleteDataset,Cn as deleteDeployment,on as deleteFineTune,ye as detectOutputFormat,bt as effectiveConsoleGatewayConfig,he as ensureConfigDir,ln as exportCheckpoint,_n as fetchModelCapability,V as fetchModelList,Xn as flushTelemetry,ve as formatErrorJson,en as formatIssue,_e as formatJson,be as formatOutput,ge as formatText,An as generateFilename,I as getConfigDir,L as getConfigPath,me as getCredentialsPath,Mt as getDataset,Sn as getDeployment,rn as getFineTune,sn as getFineTuneLogs,pr as getModels,Pe as imageEndpoint,Fe as imageSyncEndpoint,Pn as isCI,Nn as isInteractive,Dt as isLocalFile,Qr as isSemanticAvailable,fn as isTrainingTypeCli,qe as knowledgeRetrieveEndpoint,cn as listCheckpoints,jt as listDatasets,wn as listDeployableModels,xn as listDeployments,nn as listFineTunes,$t as listSupportedFormats,gn as listSupportedTrainingTypes,we as loadApiKeyFromConfig,Ce as loadConfig,Zn as localSink,P as mapApiError,ft as maskToken,Je as mcpWebSearchEndpoint,ze as memoryAddEndpoint,Ve as memoryListEndpoint,He as memoryNodeEndpoint,Be as memorySearchEndpoint,hn as modelSupportsTrainingType,In as parseBooleanValue,pe as parseConfigFile,It as parseDatasetSchemaFlag,Ln as parseOptionalBooleanValue,_t as parseSSE,Xt as pickValidator,yn as preflightBatchSizeGate,Ge as profileSchemaEndpoint,mi as rankModels,xe as readConfigFile,Ir as recallCandidates,oi as recallSemantic,Zt as registerValidator,Qn as remoteSink,z as request,B as requestJson,Rn as resolveBooleanFlag,ke as resolveConsoleGatewayCredential,De as resolveCredential,Ot as resolveFileUrl,Mn as resolveOutputDir,zn as resolveWatermark,Te as saveApiKeyToConfig,Tn as scaleDeployment,Ae as signRequest,We as speechRecognizeEndpoint,Ue as speechSynthesizeEndpoint,Fn as stripUndefined,Le as taskEndpoint,pn as toServerTrainingType,nr as trackCommandExecution,R as trackingHeaders,mn as trainingTypeMethodVariant,En as updateDeployment,At as uploadDataset,Et as uploadFile,Ke as userProfileEndpoint,Qt as validateDataset,Ie as videoGenerateEndpoint,Se as writeConfigFile};
183
+ {"type":"single","recommendations":[{"model":"model ID","reason":"alternative analysis","highlights":["differentiators"]}]}`;else if(c===`scoped`){let e=n.modelPreference?.targets?.length?`\n\n## Scope Restriction\nThe user explicitly requested recommendations from: ${n.modelPreference.targets.join(`, `)}. Prioritize models within this scope.`:``;l=(n.complexity===q.Pipeline?Sr:xr)+e}else l=n.complexity===q.Pipeline?Sr:xr;let u=a?.enableThinking??!1,d=n.complexity===q.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:u?`qwen3.6-flash`:`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=Me(e.baseUrl),m;if(u){let t=await ht(e,{url:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of yt(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await B(e,{url:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:q.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===q.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=mi(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return hi(e,g),{type:q.Pipeline,summary:h.summary??``,steps:e}}let _=mi(h.recommendations??h??[],g,i);return{type:q.Single,recommendations:_}}export{le as BAILIAN_HOST,N as BailianError,vr as Budgets,ut as CHANNEL,De as CONSOLE_GATEWAY_NO_TOKEN_MESSAGE,X as Capabilities,q as Complexities,J as ContextNeeds,mn as DEFAULT_TRAINING_TYPE,ce as DOCS_HOSTS,M as ExitCode,yr as Features,jn as GLOBAL_OPTIONS,xn as INSUFFICIENT_SAMPLES_CODE,Lt as MAX_DATASET_BYTES,vt as McpClient,_r as Modalities,br as ModelCategories,Y as QualityPreferences,F as REGIONS,ft as SOURCE_CONFIG,dt as TAGS,pn as TRAINING_TYPES_CLI,U as TRAINING_TYPE_MAP,Cr as analyzeIntent,Le as appCompletionEndpoint,_t as bailianMcpUrl,pi as buildDocLink,wt as callConsoleGateway,cn as cancelFineTune,Me as chatEndpoint,Te as clearApiKey,Cn as createDeployment,an as createFineTune,Un as createTrackingEvent,An as defineCommand,It as deleteDataset,En as deleteDeployment,ln as deleteFineTune,ve as detectOutputFormat,St as effectiveConsoleGatewayConfig,R as ensureConfigDir,fn as exportCheckpoint,bn as fetchModelCapability,Tt as fetchModelList,$n as flushTelemetry,_e as formatErrorJson,rn as formatIssue,ge as formatJson,ye as formatOutput,he as formatText,Nn as generateFilename,I as getConfigDir,L as getConfigPath,me as getCredentialsPath,Ft as getDataset,Tn as getDeployment,sn as getFineTune,un as getFineTuneLogs,gr as getModels,Ne as imageEndpoint,Pe as imageSyncEndpoint,Ln as isCI,In as isInteractive,At as isLocalFile,ei as isSemanticAvailable,hn as isTrainingTypeCli,Je as knowledgeChatEndpoint,Ke as knowledgeRetrieveEndpoint,qe as knowledgeSearchEndpoint,dn as listCheckpoints,Pt as listDatasets,Dn as listDeployableModels,wn as listDeployments,on as listFineTunes,nn as listSupportedFormats,yn as listSupportedTrainingTypes,Ce as loadApiKeyFromConfig,Se as loadConfig,er as localSink,P as mapApiError,pt as maskToken,Ye as mcpWebSearchEndpoint,Re as memoryAddEndpoint,Be as memoryListEndpoint,Ve as memoryNodeEndpoint,ze as memorySearchEndpoint,vn as modelSupportsTrainingType,zn as parseBooleanValue,pe as parseConfigFile,zt as parseDatasetSchemaFlag,Bn as parseOptionalBooleanValue,yt as parseSSE,$t as pickValidator,Sn as preflightBatchSizeGate,We as profileSchemaEndpoint,gi as rankModels,be as readConfigFile,Rr as recallCandidates,ci as recallSemantic,en as registerValidator,tr as remoteSink,ht as request,B as requestJson,Vn as resolveBooleanFlag,Oe as resolveConsoleGatewayCredential,Ee as resolveCredential,jt as resolveFileUrl,Fn as resolveOutputDir,Hn as resolveWatermark,we as saveApiKeyToConfig,On as scaleDeployment,ke as signRequest,Ue as speechRecognizeEndpoint,He as speechSynthesizeEndpoint,Rn as stripUndefined,Ie as taskEndpoint,gn as toServerTrainingType,ar as trackCommandExecution,z as trackingHeaders,_n as trainingTypeMethodVariant,kn as updateDeployment,Nt as uploadDataset,kt as uploadFile,Ge as userProfileEndpoint,tn as validateDataset,Fe as videoGenerateEndpoint,xe as writeConfigFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.",
5
5
  "homepage": "https://bailian.console.aliyun.com/cli",
6
6
  "bugs": {