bailian-cli-core 1.6.0 → 1.7.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.mjs CHANGED
@@ -1,16 +1,14 @@
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(`
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 ee,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 E}from"node:url";var ne=Object.create,re=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,ae=Object.getOwnPropertyNames,oe=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ae(t),a=0,o=i.length,s;a<o;a++)s=i[a],!se.call(e,s)&&s!==n&&re(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ie(t,s))||r.enumerable});return e},le=(e,t,n)=>(n=e==null?{}:ne(oe(e)),ce(t||!e||!e.__esModule?re(n,`default`,{value:e,enumerable:!0}):n,e)),O=e(import.meta.url);const k={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONTENT_FILTER:10};var A=class extends Error{exitCode;hint;api;constructor(e,t=k.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api}toJSON(){let e=j(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}:{}}}}},ue=class extends A{constructor(e,t){super(e,k.USAGE,t),this.name=`UsageError`}};function j(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 M(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new A(r,k.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id}})}const de={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},fe={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},pe=`https://bailian.cn-beijing.aliyuncs.com`,me=new Set([`text`,`json`]),he=new Set([`domestic`,`international`]);function ge(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function _e(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.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.base_url==`string`&&ge(t.base_url)&&(n.base_url=t.base_url),typeof t.intent_detect_base_url==`string`&&ge(t.intent_detect_base_url)&&(n.intent_detect_base_url=t.intent_detect_base_url),typeof t.output==`string`&&me.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.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&he.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 ve(e){return e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url||de.cn}function ye(e){let t=ve(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new A(`No API key found.`,k.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function be(e){let t=e.file.access_token?.trim();if(!t)throw new A(`No console access token found.`,k.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function xe(e){let t=Se(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0);if(t)return t;let n=Se(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Ce(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Ce(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)));if(n)return n;let r=Se(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret));if(r)return r;throw new A(`No OpenAPI AK/SK credentials found.`,k.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function Se(e,t,n,r){if(!r)return;let i=Ce(t),a=Ce(n);if(!i||!a)throw new A(`Incomplete OpenAPI AK/SK credentials found.`,k.AUTH,we(e));return{accessKeyId:i,accessKeySecret:a,source:e}}function Ce(e){return e?.trim()||void 0}function we(e){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars to use config credentials.`:"Run `bl auth login --open-api --access-key-id <id> --access-key-secret <secret>` again to save a complete pair."}function Te(e){let t={};try{t.apiKey=ye(e)}catch{}try{t.console=be(e)}catch{}try{t.openapi=xe(e)}catch{}return t}function N(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:p(u(),`.bailian`)}function P(){return p(N(),`config.json`)}function Ee(){return p(N(),`credentials.json`)}async function De(){let e=N(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Oe(e){return m(e).replace(/\n$/,``)}function ke(e){return JSON.stringify(e,null,2)}function Ae(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function je(e){return e===`json`||e===`text`?e:`text`}function Me(e,t){switch(t){case`json`:return ke(e);case`text`:return Oe(e)}}function F(){let e=P();if(!r(e))return{};try{return _e(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 I(e){await De();let t=P(),n=t+`.tmp`;l(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),o(n,t)}function Ne(e){return{flags:e,file:F(),env:process.env}}function Pe(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=i!==void 0&&Number.isFinite(i)&&i>0?i:void 0,o=t.timeout??a??n.timeout??300;if(!Number.isFinite(o)||o<=0)throw new A(`Timeout must be a positive finite number.`,k.USAGE);return{configPath:P(),intentDetectBaseUrl:n.intent_detect_base_url||r.DASHSCOPE_INTENT_DETECT_BASE_URL||void 0,output:je(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const Fe={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`],all:[`api_key`,`access_token`,`access_key_id`,`access_key_secret`]};function Ie(e){return{describe:()=>Te(e),stored(){let e=F();return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret)}},resolveBaseUrl:()=>ve(e),async login(e){let t=F();for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);await I(t)},async logout(e){let t=F(),n=Fe[e];if(!n.some(e=>t[e]!==void 0))return!1;for(let e of n)delete t[e];return await I(t),!0}}}function Le(){return`/compatible-mode/v1/chat/completions`}function Re(e){return`${e}/api/v1/services/aigc/text-generation/generation`}function ze(){return`/api/v1/services/aigc/image-generation/generation`}function Be(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Ve(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function He(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Ue(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function We(){return`/api/v2/apps/memory/add`}function Ge(){return`/api/v2/apps/memory/memory_nodes/search`}function Ke(){return`/api/v2/apps/memory/memory_nodes`}function qe(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Je(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Ye(){return`/api/v1/services/audio/asr/transcription`}function Xe(){return`/api/v2/apps/memory/profile_schemas`}function Ze(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Qe(){return`/api/v1/indices/rag/index/retrieve`}function $e(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function et(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function tt(){return`/api/v1/mcps/WebSearch/mcp`}function nt(){return`/compatible-mode/v1/files`}function rt(){return`/api/v1/files`}function it(e){return`/api/v1/files/${encodeURIComponent(e)}`}function at(){return`/api/v1/fine-tunes`}function ot(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function st(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function ct(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function lt(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function ut(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function dt(){return`/api/v1/deployments`}function ft(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function pt(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function mt(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function ht(){return`/api/v1/deployments/models`}const gt=`bailian-cli`,_t={t1:`public`,t2:``},vt=JSON.stringify({channel:gt,tags:_t});function L(){return{"x-dashscope-source-config":vt}}function yt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function bt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function xt(e,t){let n=typeof FormData<`u`&&t.body instanceof FormData,r={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...L(),...t.headers};if(!n&&!r[`Content-Type`]&&(r[`Content-Type`]=`application/json`),t.async&&(r[`X-DashScope-Async`]=`enable`),bt(t.body)&&(r[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let e=r.Authorization;e&&console.error(`> Auth: ${yt(e.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${vt}`)}let i=St((t.timeout??e.settings.timeout)*1e3,t.signal),a=await fetch(t.url,{method:t.method??`GET`,headers:r,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:i.signal}).finally(i.cleanup);if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!a.ok){let e={};try{e=await a.json()}catch{}throw M(a.status,e,t.url)}return a}function St(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 Ct(e,t){let n=await xt(e,t),r;try{r=await n.json()}catch{throw new A(`API returned non-JSON response (${n.headers.get(`content-type`)||`unknown type`}). Server may be experiencing issues.`,k.GENERAL)}if(r.code&&typeof r.code==`string`&&r.code!==`200`&&r.code!==`Success`)throw M(200,{error:{message:r.message,type:r.code}},t.url);return r}function wt(e){let t=[];for(let[n,r]of Object.entries(e))if(!(r===void 0||r===``))if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r]);return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${Et(e)}=${Et(t)}`).join(`&`)}function Tt(e){let t=e.method??`POST`,n=new Date().toISOString().replace(/\.\d{3}Z$/,`Z`),r=_(),i=Dt(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
3
  `)+`
6
- `,c=o.join(`;`),l=[t,e.pathname,``,s,c,i].join(`
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.
4
+ `,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
5
+ `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Dt(u)}`,p=Ot(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function Et(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Dt(e){return h(`sha256`).update(e,`utf8`).digest(`hex`)}function Ot(e,t){return g(`sha256`,e).update(t,`utf8`).digest(`hex`)}const kt=`${de.cn}/api/v1/uploads`;async function At(e,t,n){let r=`${kt}?action=getPolicy&model=${encodeURIComponent(t)}`,i=Ft(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...L()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new A(`Failed to get upload policy (HTTP ${a.status}): ${e}`,k.GENERAL)}return(await a.json()).data}async function jt(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=Ft(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...L()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new A(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,k.GENERAL)}return`oss://${i}`}async function Mt(e){let{apiKey:t,model:n,filePath:i,signal:a}=e;if(!r(i))throw new A(`File not found: ${i}`,k.USAGE);if(!s(i).isFile())throw new A(`Not a file: ${i}`,k.USAGE);return jt(await At(t,n,a),i,a)}function Nt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:r(e)}async function Pt(e,t,n,r={}){return Nt(e)?Mt({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function Ft(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}function It(e){return`/api/v1/mcps/${e}/mcp`}var Lt=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new A(`This command needs a model-domain API key.`,k.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new A(`MCP error (${r.error.code}): ${r.error.message}`,k.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...L()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new A(e,k.GENERAL)}return r}};const Rt={"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 zt(e,t){return Rt[e]?.[t]??Rt[`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 Vt(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 R(e,t,{api:n,data:r}){let i=zt(e.region,e.site),a=`https://${i.csGateway}`,o=i.action,s=Vt(n,r,e.switchAgent),c=new URLSearchParams({params:s,region:e.region}),l=t*1e3,u={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(u.Authorization=`Bearer ${e.token}`);let d=await fetch(`${a}/cli/api.json?action=${o}&product=sfm_bailian&api=${encodeURIComponent(n)}`,{method:`POST`,headers:u,body:c.toString(),signal:AbortSignal.timeout(l)});if(!d.ok){let e=await d.text().catch(()=>``);throw new A(`Console CLI gateway failed: HTTP ${d.status} ${d.statusText}`,k.GENERAL,e.slice(0,500))}let f=await d.json(),p=f.data;if(p?.success===!1&&p.errorCode){let e=p.errorCode,t=typeof e==`string`?e:JSON.stringify(e),n=t.includes(`NotLogined`),r=typeof p.errorMsg==`string`?p.errorMsg:void 0;throw new A(n?`Console session is not logged in or has expired.`:`Console gateway error: ${t}`,n?k.AUTH:k.GENERAL,n?"Run `bl auth login --console` to sign in or refresh your console session.":r&&r!==t?r:void 0)}return f}var Ht=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new A(`This command needs a model-domain API key.`,k.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new A(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,k.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}url(e){return this.baseUrl+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return xt(this.http,this.toOpts(e))}requestJson(e){return Ct(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Nt(e)?Pt(e,this.requireApi().token,t,n):Promise.resolve(e)}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Lt(this.http,t,this.deps.apiCred?.token)}console(e,t){if(!this.deps.consoleCred)throw new A(`This command needs a console access token.`,k.AUTH);return R(this.deps.consoleCred,this.deps.settings.timeout,{api:e,data:t})}async openApiQueryJson(e){let t=this.requireOpenApi(),n=wt(e.queryParams),r=`https://${e.host}${e.path}${n?`?${n}`:``}`,i=Tt({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,action:e.action,version:e.version,body:``,host:e.host,pathname:e.path,method:e.method,queryString:n});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${r}\n`),process.stderr.write(`> AK: ${yt(t.accessKeyId)}\n`));let a=this.deps.settings.timeout*1e3,o=await fetch(r,{method:e.method,headers:{...i,...L()},signal:AbortSignal.timeout(a)});this.deps.settings.verbose&&process.stderr.write(`< ${o.status} ${o.statusText}\n`);let s=await o.json();if(!o.ok||s.Success===!1)throw new A(`${s.Code||o.status} - ${s.Message||o.statusText}`,k.GENERAL);return s}};async function*Ut(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new A(`SSE stream exceeded the maximum buffer size.`,k.GENERAL);let o=r.split(`
6
+ `);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new A(`SSE event exceeded the maximum buffer size.`,k.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}async function Wt(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}}),c=s?.data?.DataV2?.data??s?.data??{},l=c?.data?.total??c?.total??0,u=c?.data?.list??c?.list??[],d=[];for(let e of u)if(e.items?.length)for(let t of e.items)d.push(t);else d.push(e);return{total:l,models:d}}function Gt(){return{read:()=>F(),async write(e){let t=F();for(let[n,r]of Object.entries(e))r===void 0?delete t[n]:t[n]=r;await I(t)},async unset(e){let t=F();for(let n of e)delete t[n];await I(t)},get path(){return P()}}}async function Kt(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 e.requestJson({path:nt(),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 A(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,k.GENERAL,`Server reported failure for ${c}. Re-run with --verbose to see the raw response.`)}throw new A(`Dataset upload of ${c} returned no file_id (HTTP 200 with empty payload).`,k.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function qt(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=rt(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Jt(e,t,n){return e.requestJson({path:it(t),method:`GET`,signal:n})}async function Yt(e,t,n){let r=await e.request({path:it(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Xt=300*1024*1024;function Zt(e,t=Xt){if(!r(e))throw new A(`File not found: ${e}`,k.USAGE);let n=s(e);if(!n.isFile())throw new A(`Not a regular file: ${e}`,k.USAGE);if(n.size===0)throw new A(`File is empty: ${e}`,k.USAGE);if(n.size>t)throw new A(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,k.USAGE);return{bytes:n.size,ext:f(e).toLowerCase()}}function z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function Qt(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`)return t;throw new A(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt.`,k.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, else ChatML).`)}function $t(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 en=new Set([`system`,`user`,`assistant`]);function tn(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(z(`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`||!en.has(a))&&r.push(z(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(z(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function nn(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(z(`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(...tn(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(z(`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(z(`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(z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const rn={name:`chatml`,detect:()=>!0,inspect:nn};function an(e,t){let n=[];if(!(`text`in e))return n.push(z(`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(z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const on={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:an};function sn(e,t){let n=nn(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(z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...tn(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...tn(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const cn=[{name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:sn},on,rn];function ln(e,t){return t===void 0?cn.find(t=>t.detect(e))??rn:cn.find(e=>e.name===t)||rn}async function un(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(z(`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 dn(e,t,r,i,a){let o=r?null:new Set($t(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(z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...fn(n,u,i))}return{sampled:c,issues:s}}function fn(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return ln(r,n).inspect(r,t)}const B=[{format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await un(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[z(`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 dn(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 pn(e){let t=f(e).toLowerCase(),n=B.find(e=>e.extensions.includes(t));if(!n){let e=B.flatMap(e=>e.extensions).join(`, `);throw new A(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,k.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function mn(e){B.some(t=>t.format===e.format)||B.push(e)}async function hn(e,t={}){let{bytes:n}=Zt(e,t.maxBytes??314572800),r=await pn(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function gn(){return B.map(e=>({format:e.format,extensions:[...e.extensions]}))}function _n(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 vn(e,t,n){return e.requestJson({path:at(),method:`POST`,body:t,signal:n})}async function yn(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(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function bn(e,t,n){return e.requestJson({path:ot(t),method:`GET`,signal:n})}async function xn(e,t,n){return e.requestJson({path:st(t),method:`POST`,signal:n})}async function Sn(e,t,n){return e.requestJson({path:ot(t),method:`DELETE`,signal:n})}async function Cn(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=ct(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function wn(e,t,n){return e.requestJson({path:lt(t),method:`GET`,signal:n})}async function Tn(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${ut(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const V={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`}},En=Object.keys(V),Dn=`sft-lora`;function On(e){return e in V}function kn(e){return V[e].server}function An(e){let{method:t,variant:n}=V[e];return{method:t,variant:n}}function jn(e,t){if(!e)return!1;let{method:n,variant:r}=V[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Mn(e){return e?En.filter(t=>jn(e,t)):[]}async function Nn(e,t){let n=Bt(e);return(await Wt((t,r)=>R({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const Pn=`INSUFFICIENT_SAMPLES`;function Fn(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Pn,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(`
7
+ `)}}async function In(e,t,n){return e.requestJson({path:dt(),method:`POST`,body:t,signal:n})}async function Ln(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=dt(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Rn(e,t,n){return e.requestJson({path:ft(t),method:`GET`,signal:n})}async function zn(e,t,n){return e.requestJson({path:ft(t),method:`DELETE`,signal:n})}async function Bn(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=ht(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Vn(e,t,n,r){return e.requestJson({path:pt(t),method:`PUT`,body:n,signal:r})}async function Hn(e,t,n,r){return e.requestJson({path:mt(t),method:`PUT`,body:n,signal:r})}const Un={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},Wn={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Gn={async:{type:`switch`,description:`Return async task id without waiting`}},Kn={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},qn={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},Jn={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}};function Yn(e){return e.auth===`apiKey`?Kn:e.auth===`console`?qn:e.auth===`openapi`?Jn:{}}function Xn(e){return e}function Zn(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function Qn(e,t){return`${Zn(e||`image`,`image`)}_${Zn((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const $n=()=>p(u(),`bailian-output`);function er(e,t){let n=t?.flagDir||e.outputDir||$n(),a=t?.subDir?p(n,t.subDir):n;return r(a)||i(a,{recursive:!0}),a}function tr(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function nr(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new A(`Invalid ${t} value "${String(e)}". Use true or false.`,k.USAGE)}function rr(e,t=`boolean`){if(e!=null)return nr(e,t)}function ir(e,t,n=`boolean`){let r=rr(e,n);return r===void 0?t:r}function ar(e){return rr(e,`watermark`)??!0}function or(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 sr(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function cr(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=sr(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let H;function lr(){return H||(process.env.NODE_ENV===`development`?(H=`dev`,H):(H=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,H))}var ur=D(((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=O(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=O(`dns`)},function(e,t){e.exports=O(`util`)},function(e,t){e.exports=O(`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`},ee=(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`},E=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},ne=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},O=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},k=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},A=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},j=new Map,M=new Map;j.set(`Baiduspider-render`,i),j.set(`Baiduspider+`,i),j.set(`Baiduspider-image+`,i),j.set(`360Spider`,a),j.set(`360Spider-Image`,a),j.set(`bingbot`,o),j.set(`Googlebot`,s),j.set(`YandexRenderResourcesBot`,c),j.set(`spider`,l),j.set(`Dataprovider.com`,u),j.set(`AhrefsBot`,d),j.set(`BitSightBot`,f),j.set(`oBot`,p),j.set(`Cincraw`,m),j.set(`DingTalkBot-LinkService`,h),j.set(`YisouSpider`,g),j.set(`Bytespider`,_),j.set(`ev-crawler`,v),j.set(`bitdiscovery`,y),j.set(`Spider`,b),j.set(`Ai2Bot-Dolma`,x),j.set(`dianjing_ad_spider`,ee),M.set(`Baiduspider-render`,S),M.set(`Baiduspider+`,S),M.set(`Baiduspider-image+`,S),M.set(`360Spider`,C),M.set(`360Spider-Image`,C),M.set(`bingbot`,te),M.set(`Googlebot`,w),M.set(`YandexRenderResourcesBot`,T),M.set(`spider`,E),M.set(`Dataprovider.com`,ne),M.set(`AhrefsBot`,re),M.set(`BitSightBot`,ie),M.set(`oBot`,ae),M.set(`Cincraw`,oe),M.set(`DingTalkBot-LinkService`,se),M.set(`YisouSpider`,D),M.set(`Bytespider`,ce),M.set(`ev-crawler`,le),M.set(`bitdiscovery`,O),M.set(`Spider`,k),M.set(`Ai2Bot-Dolma`,A),M.set(`dianjing_ad_spider`,ue);let de={productHandlerMap:j,commentHandlerMap:M,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,de),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,x=n(3),ee=n.n(x),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 E(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){ne(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 ne(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 re(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=ae(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.
8
+ 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 ie(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)||ae(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
9
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function ae(e,t){if(e){if(typeof e==`string`)return oe(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)?oe(e,t):void 0}}function oe(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 se(){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=ie(r[n],2),o=(a[0],a[1]);if(o){var s,c=re(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 D,ce,le=(D=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:D,device_id:te.a.createHash(`md5`).update(se()).digest(`hex`),platform:`node`}),O=(0,S.promisify)(ee.a.resolve);function k(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,E(E({},le),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}k.prototype=((ce=function(){}).prototype=b.prototype,new ce),k.prototype.constructor=k,k.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,O(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=k}]).default})),dr=D(((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})),fr=le(ur(),1),pr=le(dr(),1);const mr=()=>p(N(),`telemetry.jsonl`);let hr;const U=new Set;let W;try{let e=new fr.default({pid:`bailian-cli-node`,env:lr()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;U.add(e),e.finally(()=>U.delete(e))}return n},W=e,hr=e.use(pr.default)}catch{}async function gr(e=1e3){try{if(W)try{typeof W._sendAll==`function`&&W._sendAll()}catch{}if(U.size===0)return;let t=[...U].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function _r(e){try{await De();let n=mr();try{s(n).size>5242880&&c(n)}catch{}t(n,JSON.stringify(e)+`
10
+ `,{mode:384})}catch{}}async function vr(e){try{if(!hr)return;hr(e.command,cr(e))}catch{}}const yr=new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),br=new Set(`page.pageSize.n.count.model.voice.language.provider.capability.temperature.topP.topK.maxTokens.seed.stream.size.resolution.ratio.duration.format.audioFormat.sampleRate.pitch.rate.volume.api.mode.download.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function xr(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||yr.has(n)||br.has(n)&&(r===void 0||r===!1||(t[n]=r));return t}async function Sr(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c;try{await r()}catch(e){throw a=!1,e instanceof A?(o=e.message,s=e.api?.httpStatus,c=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),l=or({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,httpStatus:s,requestId:c},cliVersion:e.identity.version,authMethod:e.authMethod,params:xr(n)});_r(l).catch(()=>{}),vr(l).catch(()=>{})}}function Cr(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 wr=class{name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){let e=Bt(this.settings),t=(t,n)=>R({region:e.consoleRegion,site:e.consoleSite,switchAgent:e.consoleSwitchAgent},this.settings.timeout,{api:t,data:n}),n=await Wt(t,{pageNo:1,pageSize:50}),r=[...n.models],i=Math.ceil(n.total/50);for(let e=2;e<=i;e++){let n=await Wt(t,{pageNo:e,pageSize:50});r.push(...n.models)}return r.map(Cr).filter(e=>e!==null)}};const Tr=`models.jsonl`;function Er(){return T(N(),`skills/bailian-docs-llm-wiki`)}function Dr(){return T(Er(),Tr)}function Or(){return T(w(E(import.meta.url)),`../../../../../skills/bailian-docs-llm-wiki/models`)}function kr(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 Ar(e){let t=S(e,`utf-8`).split(`
11
+ `).filter(Boolean),n=[];for(let e of t)try{let t=kr(JSON.parse(e));t&&n.push(t)}catch{}return n}function jr(){let e=Or();if(!x(T(e,Tr)))return!1;let t=Er();try{return ee(t,{recursive:!0}),b(e,t,{recursive:!0}),!0}catch{return!1}}var Mr=class{name=`catalog`;options;constructor(e){this.options=e??{}}available(){return x(Dr())}async load(){return!this.available()&&(this.options.onPrepareStart?.(),!jr())?[]:Ar(Dr())}};async function Nr(e,t){let n=[new Mr({onPrepareStart:t?.onPrepareStart}),new wr(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new A(`No model data available.`,k.GENERAL)}const Pr={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},G={Single:`single`,Pipeline:`pipeline`},Fr={Low:`low`,Medium:`medium`,High:`high`},Ir={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},K={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},q={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`},Lr={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},J={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Rr=20,zr=/-\d{4}-\d{2}-\d{2}$/,Br=new Set([q.IG,q.VG,q.TTS,q.RealtimeTTS,q.ThreeDGeneration]),Vr=new Set([q.TG,q.Reasoning,q.ASR,q.RealtimeASR,q.RealtimeAudioTranslate,q.TR,q.ME]),Hr={standard:0,large:32e3,"extra-large":128e3},Ur=.4,Wr=.6,Gr=.4,Kr=.2,qr=.2,Jr=.2;console.assert(Math.abs(Ur+Wr-1)<1e-9,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(Math.abs(Gr+Kr+qr+Jr-1)<1e-9,`HARD_WEIGHT_* sub-weights must sum to 1`);const Yr=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
14
12
 
15
13
  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
14
 
@@ -51,7 +49,7 @@ Single task:
51
49
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
52
50
 
53
51
  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"]}]}]}`,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.
52
+ {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Xr=`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
53
 
56
54
  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
55
 
@@ -90,7 +88,9 @@ Key principles:
90
88
 
91
89
  Or (if single model suffices):
92
90
  {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
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.
91
+ ["key highlights"]}]}`,Zr={name:`classify_intent`,description:`Classify the user's model recommendation intent. Extract the mode and any model/family names mentioned.`,parameters:{type:`object`,properties:{mode:{type:`string`,enum:[`unconstrained`,`scoped`,`comparison`,`alternative`],description:`The detected intent mode.`},targets:{type:`array`,items:{type:`string`},description:`Model or family names the user mentioned or wants to evaluate. Empty for unconstrained.`},excludes:{type:`array`,items:{type:`string`},description:`Model or family names the user explicitly wants to exclude. Empty if none mentioned.`},complexity:{type:`string`,enum:[`single`,`pipeline`],description:`Whether the task needs a single model or a multi-step pipeline. Default to single unless the user clearly describes chained steps.`}},required:[`mode`]}};function Qr(){return`You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. The tools you can use are as follows:
92
+ ${JSON.stringify([Zr],null,2)}
93
+ Response in INTENT_MODE.`}const Y={complexity:G.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[q.TG],requiredFeatures:[],budget:Fr.Medium,contextNeed:Ir.Standard,qualityPreference:K.Balanced,confidence:0},$r=[`unconstrained`,`scoped`,`comparison`,`alternative`];function ei(e){let t=e.match(/<tags>\s*([\s\S]*?)\s*<\/tags>/i);return t?t[1].trim():``}function ti(e){let t=e.match(/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/i);if(!t)return null;try{let e=JSON.parse(t[1]);return Array.isArray(e)&&e.length>0&&e[0].arguments?e[0].arguments:e&&typeof e==`object`&&`arguments`in e?e.arguments:null}catch{return null}}function ni(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function ri(e,t,n){let r=Re(n??e.baseUrl),i={model:`tongyi-intent-detect-v3`,input:{messages:[{role:`system`,content:Qr()},{role:`user`,content:t}]},parameters:{result_format:`message`,max_tokens:512,temperature:0}};try{let t=(await e.requestJson({path:r,method:`POST`,body:i,timeout:10})).output?.choices?.[0]?.message?.content??``,n=ei(t),a=$r.includes(n)?n:`unconstrained`,o=ti(t);return{mode:a,targets:o?ni(o.targets):[],excludes:o?ni(o.excludes):[],complexity:o?.complexity===`pipeline`?`pipeline`:`single`}}catch{return null}}function ii(e,t){if(e)return{mode:e.mode,targets:e.targets.length>0?e.targets:void 0,excludes:e.excludes.length>0?e.excludes:void 0};if(t)return{mode:t.mode,targets:t.targets.length>0?t.targets:void 0,excludes:t.excludes.length>0?t.excludes:void 0}}async function ai(e,t,n){let r=ri(e,t,n?.intentDetectBaseUrl),i=Le(),a={model:`qwen3.6-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
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
 
@@ -134,11 +134,12 @@ Analyze whether the user mentioned specific models, model families, or vendors:
134
134
  - budget: "low"/"medium"/"high"
135
135
  - contextNeed: "standard"/"large"/"extra-large"
136
136
  - qualityPreference: "flagship"/"balanced"/"cost-optimized"
137
+ - semanticQuery: a self-contained English phrase (15-30 words) describing the need in a form optimized for semantic matching against model descriptions — fold in scenario, modalities, and key constraints; do not just copy the user's wording
137
138
  - modelPreference: { mode, targets?, excludes? }
138
139
 
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.
140
+ Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0},o=e.requestJson({path:i,method:`POST`,body:a,timeout:30}),[s,c]=await Promise.all([r,o.catch(()=>null)]);if(!c)return{...Y,modelPreference:ii(s),complexity:s?.complexity===`pipeline`?G.Pipeline:G.Single};let l=(c.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!l)return{...Y,confidence:+!!s,modelPreference:ii(s),complexity:s?.complexity===`pipeline`?G.Pipeline:G.Single};let u=JSON.parse(l[0]),d=u.modelPreference,f=ii(s,{mode:d&&typeof d==`object`&&typeof d.mode==`string`&&$r.includes(d.mode)?d.mode:`unconstrained`,targets:d&&typeof d==`object`&&Array.isArray(d.targets)?d.targets:[],excludes:d&&typeof d==`object`&&Array.isArray(d.excludes)?d.excludes:[]}),p=u.complexity===G.Pipeline?G.Pipeline:G.Single;return{complexity:s?.complexity===`pipeline`?G.Pipeline:p,taskSummary:typeof u.taskSummary==`string`?u.taskSummary:``,scenarioHints:Array.isArray(u.scenarioHints)?u.scenarioHints:[],semanticQuery:typeof u.semanticQuery==`string`?u.semanticQuery:``,segments:Array.isArray(u.segments)?u.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(u.inputModality)?u.inputModality:[],outputModality:Array.isArray(u.outputModality)?u.outputModality:[],requiredCapabilities:Array.isArray(u.requiredCapabilities)?u.requiredCapabilities:[],requiredFeatures:Array.isArray(u.requiredFeatures)?u.requiredFeatures:[],budget:u.budget??Y.budget,contextNeed:u.contextNeed??Y.contextNeed,qualityPreference:u.qualityPreference??Y.qualityPreference,confidence:1,modelPreference:f}}function oi(e){let t=!1,n=!1;for(let r of e)Br.has(r)&&(t=!0),Vr.has(r)&&(n=!0);return t&&n}function si(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(zr,``);return n===e?!0:!t.has(n)})}function ci(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 li(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function ui(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=Hr[i];return d>0&&(c??0)>=d&&(u+=8),a===K.Flagship&&l===J.Flagship||a===K.CostOptimized&&l===J.CostOptimized?u+=15:a===K.Balanced&&l===J.Flagship&&(u+=5),u}function X(e,t,n){return e.map(e=>({model:e,score:ui(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function di(e){return new Set(e.map(({model:e})=>e.model))}function fi(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 pi(e,t){let n=new Set(t);return e.filter(e=>n.has(e.model.model)?!1:(n.add(e.model.model),!0))}function mi(e,t,n){return n.size>=10?[]:X(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function hi(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:G.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:Ir.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>ci(e,a,o)&&li(e,n));return l.length<5&&(l=e.filter(e=>ci(e,a,o))),l.length<5&&(l=e),X(l,c,5)}function gi(e,t){e=si(e);let n;if(t.complexity===G.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=pi(hi(e,i,a,t.budget,t.qualityPreference),di(r));r=[...r,...o]}let i=mi(e,t,di(r));n=[...r,...i]}else if(oi(t.requiredCapabilities))n=_i(e,t);else{let r=e.filter(e=>ci(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=X(r,t,50)}return fi(n,3)}function _i(e,t){let n=t.requiredCapabilities.filter(e=>Br.has(e)),r=t.requiredCapabilities.filter(e=>Vr.has(e)),i=[];if(n.length>0&&(i=X(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=di(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...X(o,a,25)]}let a=mi(e,t,di(i));return[...i,...a]}const vi=`text-embedding-v4`;function yi(){return T(N(),`skills/bailian-docs-llm-wiki`)}function bi(){return T(yi(),`models-embeddings.json`)}function xi(){let e=bi();if(!x(e))return null;try{return JSON.parse(S(e,`utf-8`)).items}catch{return null}}async function Si(e,t){let n={model:vi,input:[t],dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:1e4})).data[0].embedding}async function Ci(e,t){let n={model:vi,input:t,dimensions:512,encoding_format:`float`};return(await e.requestJson({path:`/compatible-mode/v1/embeddings`,method:`POST`,body:n,timeout:3e4})).data.sort((e,t)=>e.index-t.index).map(e=>e.embedding)}const wi={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},Ti={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function Ei(){let e=T(yi(),`groups`),t=new Map;if(!x(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 Di(e,t){let n=(e.capabilities??[]).map(e=>wi[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>Ti[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>Ti[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 Oi(e,t){let n=Ei(),r=t.map(e=>Di(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await Ci(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:vi,dimensions:512,count:a.length,items:a},s=bi();return ee(w(s),{recursive:!0}),te(s,JSON.stringify(o)),a}function ki(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}let Z=null;function Ai(){return Z===null&&(Z=xi()),Z}function ji(){return Ai()!==null}function Mi(e){return(e??``).toLowerCase().replace(zr,``).replace(/[\s_-]+/g,``).trim()}function Ni(e,t){let n=Mi(t);return n?Mi(e.model)===n||Mi(e.name)===n?!0:[e.model,e.name,e.family,e.familyName,e.provider].some(e=>e?Mi(e).includes(n):!1):!1}function Pi(e,t){return t.some(t=>Ni(e,t))}function Fi(e,t){return t.length===0?[]:e.filter(e=>Pi(e,t))}function Ii(e,t){return t.length===0?e:e.filter(({model:e})=>!Pi(e,t))}function Li(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&!t.some(e=>i.includes(e))||n.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function Ri(e,t){return Li(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function zi(e,t){let{requiredCapabilities:n,requiredFeatures:r,contextNeed:i,qualityPreference:a}=t,o=1;n.length>0&&(o=n.filter(t=>e.capabilities.includes(t)).length/n.length);let s=1;r.length>0&&(s=r.filter(t=>e.features.includes(t)).length/r.length);let c=1,l=Hr[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===K.Flagship?u=e.category===J.Flagship?1:.5:a===K.CostOptimized&&(u=e.category===J.CostOptimized?1:.5),Gr*o+Kr*s+qr*c+Jr*u}function Q(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Ri(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function Bi(e,t){return Li(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function $(e,t,n,r,i,a){let o=e.filter(e=>n.has(e.id)).flatMap(e=>{let n=i.get(e.id);if(!n)return[];let r=ki(t,e.vector),o=a?zi(n,a):0;return[{model:n,score:a?Ur*o+Wr*r:r,hardScore:a?o:void 0,softScore:r}]}),s=o.filter(e=>(e.softScore??0)>=.3);return(s.length>=10?s:o).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,r))}function Vi(e){return{model:e,score:1,hardScore:1,softScore:1}}function Hi(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?Fi(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(Vi(e));let r=new Set(l.map(({model:e})=>e.model)),s=$(t,n,Q(e,o),i,a,o);for(let e of s)if(!r.has(e.model.model)&&(l.push(e),l.length>=i))break;return l}return $(t,n,Q(c,o),i,a,o)}function Ui(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=new Set;for(let t of e)Pi(t,s)&&!l.has(t.model)&&(c.push(Vi(t)),l.add(t.model));let u=Math.max(0,i-c.length);if(u>0){let r=$(t,n,Q(e.filter(e=>!l.has(e.model)),o),u,a,o);for(let e of r)c.push(e)}return c.slice(0,Math.max(0,i))}function Wi(e,t,n,r,i,a,o){let s=Fi(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=new Set;for(let e of s)l.push(Vi(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=$(t,n,Q(e.filter(e=>!u.has(e.model)&&(!e.family||!c.has(e.family))),o),d,a,o);for(let e of r)l.push(e)}return l}async function Gi(e,t,n,r,i){let a=Ai();if(!a)a=await Oi(e,t),Z=a;else{let n=new Set(a.map(e=>e.id)),r=new Set(t.map(e=>e.model)),i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}i&&(a=await Oi(e,t),Z=a)}let o=await Si(e,i?.semanticQuery?.trim()||n),s=new Map(t.map(e=>[e.model,e])),c=i?.modelPreference,l=c?.excludes??[];if(c&&c.mode!==`unconstrained`){let e;switch(c.mode){case`scoped`:e=Hi(t,a,o,c,r,s,i);break;case`comparison`:e=Ui(t,a,o,c,r,s,i);break;case`alternative`:e=Wi(t,a,o,c,r,s,i);break;default:e=[]}return Ii(e,l)}if(i?.complexity===G.Pipeline&&i.segments?.length){let e=new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>Bi(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=$(a,o,u,c,s,i);for(let t of d)e.has(t.model.model)||(n.push(t),e.add(t.model.model))}return Ii(n,l)}let u=Q(t,i);return Ii($(a,o,u,r,s,i),l)}function Ki(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function qi(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=Ki(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
141
+ `)}function Ji(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!==Ir.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(`
142
+ `)}function Yi(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 Xi(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 Zi(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 Qi(e,t,n,r,i,a){let o=qi(t),s=Ji(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
143
 
143
144
  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
145
 
@@ -180,4 +181,4 @@ The intent's modelPreference.targets is the reference model.
180
181
  - Output strict JSON
181
182
 
182
183
  ## 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===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};
184
+ {"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===G.Pipeline?Xr:Yr)+e}else l=n.complexity===G.Pipeline?Xr:Yr;let u=a?.enableThinking??!1,d=n.complexity===G.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=Le(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of Ut(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&a?.onThinking&&a.onThinking(t.reasoning_content),t.content&&(r||(r=!0,a?.onContentStart?.()),n+=t.content)}}catch{}}m=n||`{}`}else m=(await e.requestJson({path:p,method:`POST`,body:f})).choices?.[0]?.message?.content??`{}`;let h;try{let e=m.match(/\{[\s\S]*\}/);h=JSON.parse(e?.[0]??`{}`)}catch{return{type:G.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===G.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=Xi(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Zi(e,g),{type:G.Pipeline,summary:h.summary??``,steps:e}}let _=Xi(h.recommendations??h??[],g,i);return{type:G.Single,recommendations:_}}export{Gn as ASYNC_FLAG,pe as BAILIAN_HOST,A as BailianError,Fr as Budgets,gt as CHANNEL,Wn as CONCURRENT_FLAG,qn as CONSOLE_AUTH_FLAGS,q as Capabilities,Ht as Client,G as Complexities,Ir as ContextNeeds,Dn as DEFAULT_TRAINING_TYPE,fe as DOCS_HOSTS,k as ExitCode,Lr as Features,Un as GLOBAL_FLAGS,Pn as INSUFFICIENT_SAMPLES_CODE,Xt as MAX_DATASET_BYTES,Kn as MODEL_AUTH_FLAGS,Lt as McpClient,Pr as Modalities,J as ModelCategories,Jn as OPENAPI_AUTH_FLAGS,K as QualityPreferences,de as REGIONS,Rr as SEMANTIC_TOP_K,vt as SOURCE_CONFIG,_t as TAGS,En as TRAINING_TYPES_CLI,V as TRAINING_TYPE_MAP,ue as UsageError,ai as analyzeIntent,Ue as appCompletionPath,It as bailianMcpPath,wt as buildAcsCanonicalQuery,Yi as buildDocLink,Pe as buildSettings,Ne as buildSources,R as callConsoleGateway,xn as cancelFineTune,Le as chatPath,In as createDeployment,vn as createFineTune,or as createTrackingEvent,Yn as credentialFlagDefs,Xn as defineCommand,Yt as deleteDataset,zn as deleteDeployment,Sn as deleteFineTune,Te as describeAuthState,je as detectOutputFormat,Bt as effectiveConsoleGatewayConfig,De as ensureConfigDir,Tn as exportCheckpoint,Nn as fetchModelCapability,Wt as fetchModelList,gr as flushTelemetry,Ae as formatErrorJson,_n as formatIssue,ke as formatJson,Me as formatOutput,Oe as formatText,Qn as generateFilename,N as getConfigDir,P as getConfigPath,Ee as getCredentialsPath,Jt as getDataset,Rn as getDeployment,bn as getFineTune,Cn as getFineTuneLogs,Nr as getModels,ze as imagePath,Be as imageSyncPath,Nt as isLocalFile,ji as isSemanticAvailable,On as isTrainingTypeCli,et as knowledgeChatEndpoint,Qe as knowledgeRetrievePath,$e as knowledgeSearchEndpoint,wn as listCheckpoints,qt as listDatasets,Bn as listDeployableModels,Ln as listDeployments,yn as listFineTunes,gn as listSupportedFormats,Mn as listSupportedTrainingTypes,_r as localSink,Ie as makeAuthStore,Gt as makeConfigStore,M as mapApiError,yt as maskToken,tt as mcpWebSearchPath,We as memoryAddPath,Ke as memoryListPath,qe as memoryNodePath,Ge as memorySearchPath,jn as modelSupportsTrainingType,nr as parseBooleanValue,_e as parseConfigFile,Qt as parseDatasetSchemaFlag,rr as parseOptionalBooleanValue,Ut as parseSSE,pn as pickValidator,Fn as preflightBatchSizeGate,Xe as profileSchemaPath,Qi as rankModels,F as readConfigFile,gi as recallCandidates,Gi as recallSemantic,mn as registerValidator,vr as remoteSink,xt as request,Ct as requestJson,ye as resolveApiKey,ir as resolveBooleanFlag,be as resolveConsole,Pt as resolveFileUrl,ve as resolveModelBaseUrl,xe as resolveOpenApi,er as resolveOutputDir,ar as resolveWatermark,Vn as scaleDeployment,Tt as signAcsRequest,Ye as speechRecognizePath,Je as speechSynthesizePath,tr as stripUndefined,He as taskPath,kn as toServerTrainingType,Sr as trackCommandExecution,L as trackingHeaders,An as trainingTypeMethodVariant,Hn as updateDeployment,Kt as uploadDataset,Mt as uploadFile,Ze as userProfilePath,hn as validateDataset,Ve as videoGeneratePath,I as writeConfigFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-core",
3
- "version": "1.6.0",
3
+ "version": "1.7.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": {