bailian-cli-core 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,203 +1,220 @@
1
- import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{parse as _,stringify as v}from"yaml";import{Dispatcher as y,getGlobalDispatcher as b}from"undici";import{createHash as ee,createHmac as te,randomBytes as ne,randomUUID as re}from"crypto";import{Readable as ie}from"stream";import{createInterface as x}from"readline";import{pipeline as ae}from"stream/promises";import*as oe from"yauzl";import{copyFileSync as se,cpSync as ce,createWriteStream as le,existsSync as S,lstatSync as C,mkdirSync as w,readFileSync as T,readdirSync as E,readlinkSync as ue,realpathSync as de,renameSync as D,rmSync as O,statSync as fe,symlinkSync as k,writeFileSync as A}from"node:fs";import{basename as pe,dirname as j,isAbsolute as me,join as M,relative as he,resolve as ge,sep as _e}from"node:path";import{homedir as ve}from"node:os";import{createHash as ye}from"node:crypto";import{Readable as be}from"node:stream";import{pipeline as xe}from"node:stream/promises";import{createBrotliDecompress as Se}from"node:zlib";import Ce from"tar-stream";import{mkdir as we}from"node:fs/promises";var Te=Object.create,Ee=Object.defineProperty,De=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyNames,ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty,je=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Me=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Oe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ae.call(e,s)&&s!==n&&Ee(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=De(t,s))||r.enumerable});return e},Ne=(e,t,n)=>(n=e==null?{}:Te(ke(e)),Me(t||!e||!e.__esModule||!Ae.call(e,`default`)?Ee(n,`default`,{value:e,enumerable:!0}):n,e)),Pe=/* @__PURE__ */ e(import.meta.url);const N={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10};var P=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=N.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api,this.rawResponse=r?.rawResponse}toJSON(){let e=Fe(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},F=class extends P{constructor(e,t){super(e,N.USAGE,t),this.name=`UsageError`}};function Fe(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 Ie(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.error?.code??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new P(r,N.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function Le(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Re(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Re(e);return n.origin}function Re(e){return new P(`Invalid model base URL "${e}".`,N.USAGE,`Use an absolute http(s) URL.`)}const ze={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},Be={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},Ve=`https://bailian.cn-beijing.aliyuncs.com`,He=[`en-US`,`zh-CN`],Ue=`en-US`,We=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],Ge=/* @__PURE__ */ new Set([`text`,`json`]),Ke=/* @__PURE__ */ new Set([`domestic`,`international`]),qe=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function Je(e){return qe.test(e)}function Ye(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!Je(e))return[];t.includes(e)||t.push(e)}return t}function Xe(e){try{return Le(e)}catch{return}}function Ze(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&He.includes(t.language)&&(n.language=t.language),typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=Xe(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&Ge.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.watermark==`boolean`&&(n.watermark=t.watermark),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=Ye(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&Ke.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function Qe(e,t=ze.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:Le(n||t),baseUrlIsDefault:!n}}function $e(e,t=ze.cn){return Qe(e,t).baseUrl}function et(e){let t=$e(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new P(`No API key found.`,N.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function tt(e){let t=e.file.access_token?.trim();if(!t)throw new P(`No console access token found.`,N.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function nt(e){let t=rt(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=rt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(it(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||it(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=rt(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;throw new P(`No OpenAPI AK/SK credentials found.`,N.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function rt(e,t,n,r,i){if(!r)return;let a=it(t),o=it(n);if(!a||!o)throw new P(`Incomplete OpenAPI AK/SK credentials found.`,N.AUTH,at(e));return{accessKeyId:a,accessKeySecret:o,securityToken:it(i),source:e}}function it(e){return e?.trim()||void 0}function at(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 ot(e){let t={};try{t.apiKey=et(e)}catch{}try{t.console=tt(e)}catch{}try{t.openapi=nt(e)}catch{}return t}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function st(){return g(I(),`config.json`)}function ct(){return g(I(),`credentials.json`)}async function lt(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function ut(e){return v(e).replace(/\n$/,``)}function dt(e){return JSON.stringify(e,null,2)}function ft(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function pt(e){return e===`json`||e===`text`?e:`text`}function mt(e,t){switch(t){case`json`:return dt(e);case`text`:return ut(e)}}const ht={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function gt(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return ht}const _t=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,vt=`active_config`;function yt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function bt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!_t.test(e))throw new P(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,N.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(We.includes(e)||e===vt)throw new P(`Invalid config name "${e}". It conflicts with a config key.`,N.USAGE);return e}}function L(){let e=st();if(!i(e))return{};try{let t=JSON.parse(o(e,`utf-8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}function xt(e,t){let n=bt(e[vt]);if(n&&t&&!yt(e[n]))throw new P(`Active config "${n}" does not exist.`,N.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function St(e,t){if(!t)return e;let n=e[t];return yt(n)?n:{}}function R(e){return Ze(St(L(),e))}async function Ct(e,t,n={}){let r=L();if(t)r[t]=e;else{for(let e of Object.keys(r))We.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[vt]=t??`default`),await wt(r)}async function wt(e){await lt();let t=st(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),s(n,t)}function Tt(){let e=L(),t={};for(let[n,r]of Object.entries(e))We.includes(n)||n===vt||yt(r)&&(t[n]=Ze(r));return{default:Ze(e),named:t,active:xt(e,!0)??`default`}}function Et(e,t){let n=bt(t);if(n&&!yt(e[n]))throw new P(`Config "${n}" does not exist.`,N.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function Dt(e){return Et(L(),e)}async function Ot(e){let t=L(),n=Et(t,e);return t[vt]=n,await wt(t),n}async function kt(e){let t=bt(e);if(!t)throw new P(`Cannot delete the default profile.`,N.USAGE);let n=L();return yt(n[t])?(delete n[t],xt(n,!1)===t&&(n[vt]=`default`),await wt(n),!0):!1}function At(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:R(),configName:void 0},fallbackFrom:e.configName}}function jt(e){let t=L(),n=e.config!==void 0,r=xt(t,!n),i=n?bt(e.config):r;return{flags:e,file:Ze(St(t,i)),env:process.env,configName:i,configPath:st()}}function Mt(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=gt(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=gt(o);if(s)throw new P(s[`en-US`],N.USAGE);return{configPath:e.configPath??st(),configName:e.configName,output:pt(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const Nt={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function Pt(e){return e?Nt[e]:void 0}function Ft(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function It(e,t,n){if(n)return t;let r=Ft(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const Lt={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function Rt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>ot({...e,file:R(t)}),stored(){let e=R(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>$e(e,t),async login(e){let r=e.api_key?It(e.api_key,t,n):t,i=n||r!==t,a=R(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?Le(String(n)):n}await Ct(a,r,{activate:i})},async logout(e){let n=R(t),r=Lt[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await Ct(n,t),!0},get path(){return e.configPath??st()}}}const zt={"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 Bt(e,t){return zt[e]?.[t]??zt[`cn-beijing`][t]}function Vt(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 Ht(e){let t=Vt(e);return(n,r)=>Wt({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function Ut(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function Wt(e,t,{api:n,data:r},i){let a=Bt(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Ut(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new P(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,N.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new P(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?N.AUTH:N.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}function Gt(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const Kt=`bailian-cli`,qt=`BailianCLI`,Jt=`X-Dashscope-Service`;function Yt(e){return JSON.stringify({channel:Kt,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function z(e){return{"x-dashscope-source-config":Yt(e),"x-dashscope-openapisource":qt,[Jt]:Kt}}const Xt=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function Zt(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Qt(e,t){let n=en((t.timeout??e.settings.timeout)*1e3,t.signal);try{return tn(await $t(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function $t(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...z(e.identity),...t.headers};if(!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),Zt(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=i.Authorization;n&&console.error(`> Auth: ${Gt(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${Yt(e.identity)}`)}let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(b(),Xt)}},o=await fetch(t.url,a);if(e.settings.verbose){console.error(`< ${o.status} ${o.statusText}`);let e=o.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!o.ok){let e={};try{e=await o.json()}catch{if(n.aborted)throw n.reason}throw Ie(o.status,e,t.url)}return o}function en(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new P(`Response body idle timeout: no data received for ${e/1e3}s.`,N.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function tn(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function nn(e,t){let n=en((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await $t(e,t,n.signal),i;try{i=await r.json()}catch{if(n.signal.aborted)throw n.signal.reason;let e=r.headers.get(`content-type`)||``;throw new P(`API returned non-JSON response (${e||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${e||`未知类型`}),服务器可能出现问题。`,N.GENERAL)}if(i.code&&typeof i.code==`string`&&i.code!==`200`&&i.code!==`Success`)throw Ie(200,{error:{message:i.message,type:i.code}},t.url);return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function rn(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])=>`${on(e)}=${on(String(t))}`).join(`&`)}function an(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=re(),i=sn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
1
+ import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{parse as _,stringify as v}from"yaml";import{Dispatcher as y,fetch as b,getGlobalDispatcher as ee,setGlobalDispatcher as te}from"undici";import{createHash as ne,createHmac as re,randomBytes as ie,randomUUID as ae}from"crypto";import{Readable as oe}from"stream";import{createInterface as x}from"readline";import{pipeline as se}from"stream/promises";import*as ce from"yauzl";import{copyFileSync as le,cpSync as ue,createReadStream as de,createWriteStream as fe,existsSync as S,lstatSync as C,mkdirSync as w,readFileSync as T,readdirSync as E,readlinkSync as pe,realpathSync as me,renameSync as D,rmSync as O,statSync as he,symlinkSync as ge,writeFileSync as _e}from"node:fs";import{isIP as ve}from"node:net";import{Readable as ye}from"node:stream";import{basename as be,dirname as k,isAbsolute as xe,join as A,relative as Se,resolve as j,sep as Ce}from"node:path";import{parse as we}from"csv-parse";import{stringify as Te}from"csv-stringify/sync";import{link as Ee,mkdir as De,open as Oe,readFile as ke,rename as Ae,unlink as je}from"node:fs/promises";import{createHash as Me,randomUUID as Ne}from"node:crypto";import{createInterface as Pe}from"node:readline/promises";import{homedir as Fe}from"node:os";import{pipeline as Ie}from"node:stream/promises";import{createBrotliDecompress as Le}from"node:zlib";import Re from"tar-stream";var ze=Object.create,Be=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,He=Object.getOwnPropertyNames,Ue=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty,Ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=He(t),a=0,o=i.length,s;a<o;a++)s=i[a],!We.call(e,s)&&s!==n&&Be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ve(t,s))||r.enumerable});return e},qe=(e,t,n)=>(n=e==null?{}:ze(Ue(e)),Ke(t||!e||!e.__esModule||!We.call(e,`default`)?Be(n,`default`,{value:e,enumerable:!0}):n,e)),Je=/* @__PURE__ */ e(import.meta.url);const M={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10,INTERRUPTED:130};var N=class extends Error{exitCode;hint;api;rawResponse;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,this.rawResponse=r?.rawResponse}toJSON(){let e=Ye(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}:{}}}}},P=class extends N{constructor(e,t){super(e,M.USAGE,t),this.name=`UsageError`}};function Ye(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 Xe(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.error?.code??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??t.requestID}})}function Ze(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Qe(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Qe(e);return n.origin}function Qe(e){return new N(`Invalid model base URL "${e}".`,M.USAGE,`Use an absolute http(s) URL.`)}const F={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},$e={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},et=`https://bailian.cn-beijing.aliyuncs.com`,tt=[`en-US`,`zh-CN`],nt=`en-US`,rt=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],it=/* @__PURE__ */ new Set([`text`,`json`]),at=/* @__PURE__ */ new Set([`domestic`,`international`]),ot=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function st(e){return ot.test(e)}function ct(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!st(e))return[];t.includes(e)||t.push(e)}return t}function lt(e){try{return Ze(e)}catch{return}}function ut(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&tt.includes(t.language)&&(n.language=t.language),typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=lt(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&it.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.watermark==`boolean`&&(n.watermark=t.watermark),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=ct(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&at.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 dt(e,t=F.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:Ze(n||t),baseUrlIsDefault:!n}}function ft(e,t=F.cn){return dt(e,t).baseUrl}function pt(e){let t=ft(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 N(`No API key found.`,M.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function mt(e){let t=e.file.access_token?.trim();if(!t)throw new N(`No console access token found.`,M.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 ht(e){let t=gt(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=gt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(_t(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||_t(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=gt(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;throw new N(`No OpenAPI AK/SK credentials found.`,M.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 gt(e,t,n,r,i){if(!r)return;let a=_t(t),o=_t(n);if(!a||!o)throw new N(`Incomplete OpenAPI AK/SK credentials found.`,M.AUTH,vt(e));return{accessKeyId:a,accessKeySecret:o,securityToken:_t(i),source:e}}function _t(e){return e?.trim()||void 0}function vt(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 yt(e){let t={};try{t.apiKey=pt(e)}catch{}try{t.console=mt(e)}catch{}try{t.openapi=ht(e)}catch{}return t}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function bt(){return g(I(),`config.json`)}function xt(){return g(I(),`credentials.json`)}async function St(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Ct(e){return v(e).replace(/\n$/,``)}function wt(e){return JSON.stringify(e,null,2)}function Tt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Et(e){return e===`json`||e===`text`?e:`text`}function Dt(e,t){switch(t){case`json`:return wt(e);case`text`:return Ct(e)}}const Ot={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function kt(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return Ot}const At=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,jt=`active_config`;function Mt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Nt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!At.test(e))throw new N(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,M.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(rt.includes(e)||e===jt)throw new N(`Invalid config name "${e}". It conflicts with a config key.`,M.USAGE);return e}}function Pt(){let e=bt();if(!i(e))return{};try{let t=JSON.parse(o(e,`utf-8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}function Ft(e,t){let n=Nt(e[jt]);if(n&&t&&!Mt(e[n]))throw new N(`Active config "${n}" does not exist.`,M.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function It(e,t){if(!t)return e;let n=e[t];return Mt(n)?n:{}}function L(e){return ut(It(Pt(),e))}async function Lt(e,t,n={}){let r=Pt();if(t)r[t]=e;else{for(let e of Object.keys(r))rt.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[jt]=t??`default`),await Rt(r)}async function Rt(e){await St();let t=bt(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),s(n,t)}function zt(){let e=Pt(),t={};for(let[n,r]of Object.entries(e))rt.includes(n)||n===jt||Mt(r)&&(t[n]=ut(r));return{default:ut(e),named:t,active:Ft(e,!0)??`default`}}function Bt(e,t){let n=Nt(t);if(n&&!Mt(e[n]))throw new N(`Config "${n}" does not exist.`,M.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function Vt(e){return Bt(Pt(),e)}async function Ht(e){let t=Pt(),n=Bt(t,e);return t[jt]=n,await Rt(t),n}async function Ut(e){let t=Nt(e);if(!t)throw new N(`Cannot delete the default profile.`,M.USAGE);let n=Pt();return Mt(n[t])?(delete n[t],Ft(n,!1)===t&&(n[jt]=`default`),await Rt(n),!0):!1}function Wt(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:L(),configName:void 0},fallbackFrom:e.configName}}function Gt(e){let t=Pt(),n=e.config!==void 0,r=Ft(t,!n),i=n?Nt(e.config):r;return{flags:e,file:ut(It(t,i)),env:process.env,configName:i,configPath:bt()}}function Kt(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=kt(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=kt(o);if(s)throw new N(s[`en-US`],M.USAGE);return{configPath:e.configPath??bt(),configName:e.configName,output:Et(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const qt={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function Jt(e){return e?qt[e]:void 0}function Yt(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function Xt(e,t,n){if(n)return t;let r=Yt(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const Zt={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function Qt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>yt({...e,file:L(t)}),stored(){let e=L(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>ft(e,t),async login(e){let r=e.api_key?Xt(e.api_key,t,n):t,i=n||r!==t,a=L(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?Ze(String(n)):n}await Lt(a,r,{activate:i})},async logout(e){let n=L(t),r=Zt[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await Lt(n,t),!0},get path(){return e.configPath??bt()}}}const $t=process.versions.bun?void 0:ee();globalThis.Request,$t&&ee()!==$t&&te($t);const R={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},en={"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 tn(e,t){return en[e]?.[t]??en[`cn-beijing`][t]}function nn(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 rn(e){let t=nn(e);return(n,r)=>on({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function an(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function on(e,t,{api:n,data:r},i){let a=tn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=an(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await R.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,M.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new N(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?M.AUTH:M.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}function sn(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const cn=`bailian-cli`,ln=`BailianCLI`,un=`X-Dashscope-Service`;function dn(e){return JSON.stringify({channel:cn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function z(e){return{"x-dashscope-source-config":dn(e),"x-dashscope-openapisource":ln,[un]:cn}}const fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function pn(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function mn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return _n(await hn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function hn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...z(e.identity),...t.headers};if(!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),pn(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=i.Authorization;n&&console.error(`> Auth: ${sn(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${dn(e.identity)}`)}let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(ee(),fn)}},o=await R.fetch(t.url,a);if(e.settings.verbose){console.error(`< ${o.status} ${o.statusText}`);let e=o.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!o.ok){let e=await o.text(),n;try{let t=JSON.parse(e);n=typeof t==`object`&&t?t:{message:e}}catch{n={message:e}}n.request_id??=o.headers.get(`x-request-id`)??void 0;let r=Xe(o.status,n,t.url);throw new N(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function gn(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new N(`Response body idle timeout: no data received for ${e/1e3}s.`,M.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function _n(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function vn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await hn(e,t,n.signal),i;try{i=await r.json()}catch(e){if(n.signal.aborted)throw n.signal.reason;if(!(e instanceof SyntaxError))throw e;let t=r.headers.get(`content-type`)||``;throw new N(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,M.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=Xe(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new N(e.message,e.exitCode,e.hint,{api:e.api,rawResponse:JSON.stringify(i)})}return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function yn(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])=>`${xn(e)}=${xn(String(t))}`).join(`&`)}function bn(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ae(),i=Sn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
3
3
  `)+`
4
4
  `,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
5
- `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${sn(u)}`,p=cn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function on(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function sn(e){return ee(`sha256`).update(e,`utf8`).digest(`hex`)}function cn(e,t){return te(`sha256`,e).update(t,`utf8`).digest(`hex`)}const ln=`${ze.cn}/api/v1/uploads`;async function un(e,t,n,r){let i=`${ln}?action=getPolicy&model=${encodeURIComponent(t)}`,a=vn(15e3,r),o=await fetch(i,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...z(n)},signal:a.signal}).finally(a.cleanup);if(!o.ok){let e=await o.text().catch(()=>``);throw new P(`Failed to get upload policy (HTTP ${o.status}): ${e}`,N.GENERAL)}return(await o.json()).data}async function dn(e,t,n,r=120){let i=m(t),a=`${e.upload_dir}/${i}`,s=o(t),c=new FormData;c.append(`OSSAccessKeyId`,e.oss_access_key_id),c.append(`Signature`,e.signature),c.append(`policy`,e.policy),c.append(`x-oss-object-acl`,e.x_oss_object_acl),c.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),c.append(`key`,a),c.append(`success_action_status`,`200`),c.append(`file`,new Blob([s]),i);let l=vn(r*1e3,n),u=await fetch(e.upload_host,{method:`POST`,body:c,signal:l.signal}).finally(l.cleanup);if(!u.ok){let e=await u.text().catch(()=>``);throw new P(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,N.GENERAL)}return`oss://${a}`}const fn={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function pn(e){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);if(!l(e).isFile())throw new P(`Not a file: ${e}`,N.USAGE);let t=h(e).toLowerCase(),n=fn[t];if(!n)throw new P(`Unsupported image format "${t||`unknown`}".`,N.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function mn(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function hn(e){let{apiKey:t,model:n,filePath:r,identity:a,signal:o,timeout:s}=e;if(!i(r))throw new P(`File not found: ${r}`,N.USAGE);if(!l(r).isFile())throw new P(`Not a file: ${r}`,N.USAGE);return dn(await un(t,n,a,o),r,o,s)}function gn(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function _n(e,t,n,r){return gn(e)?hn({apiKey:t,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function vn(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 yn(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
5
+ `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Sn(u)}`,p=Cn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function xn(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Sn(e){return ne(`sha256`).update(e,`utf8`).digest(`hex`)}function Cn(e,t){return re(`sha256`,e).update(t,`utf8`).digest(`hex`)}const wn=[`cn-beijing`,`ap-southeast-1`];function Tn(e){return new N(`Local-file temporary upload is supported only in ${wn.join(`, `)}; "${e}" is not supported.`,M.USAGE,`Use a reachable HTTPS media URL instead.`)}function En(e){if(Yt(e)===`token-plan`)throw Tn(`Token Plan`)}function Dn(e,t){let n=Ze(e),r=new URL(n).hostname.toLowerCase();if(/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/.test(r))throw Tn(`Token Plan`);if(r===new URL(F.cn).hostname||r===new URL(F.intl).hostname)return En(t),n;if(r===new URL(F.us).hostname)throw Tn(r);let i=/^[^.]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/.exec(r)?.[1];if(i===`cn-beijing`||i===`ap-southeast-1`)return En(t),n;if(i)throw Tn(i);return n}async function On(e,t,n,r,i){let a=`${Dn(r,e)}/api/v1/uploads`,o=`${a}?action=getPolicy&model=${encodeURIComponent(t)}`,s=In(15e3,i),c=await R.fetch(o,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...z(n)},signal:s.signal}).finally(s.cleanup);if(!c.ok){let e=await c.text().catch(()=>``),t;try{t=JSON.parse(e)}catch{}let n=typeof t?.message==`string`&&t.message?t.message:e||`${c.status} ${c.statusText}`,r=typeof t?.code==`string`?t.code:void 0,i=typeof t?.request_id==`string`?t.request_id:void 0;throw new N(`${[`HTTP ${c.status}`,r?`code=${r}`:void 0,i?`request_id=${i}`:void 0,`upload_endpoint=${a}`].filter(e=>e!==void 0).join(`; `)} - ${n}`,M.GENERAL,void 0,{api:{httpStatus:c.status,apiCode:r,requestId:i},rawResponse:e.slice(0,500)})}return(await c.json()).data}async function kn(e,t,n,r=120){let i=m(t),a=`${e.upload_dir}/${i}`,s=o(t),c=new FormData;c.append(`OSSAccessKeyId`,e.oss_access_key_id),c.append(`Signature`,e.signature),c.append(`policy`,e.policy),c.append(`x-oss-object-acl`,e.x_oss_object_acl),c.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),c.append(`key`,a),c.append(`success_action_status`,`200`),c.append(`file`,new Blob([s]),i);let l=In(r*1e3,n),u=await R.fetch(e.upload_host,{method:`POST`,body:c,signal:l.signal}).finally(l.cleanup);if(!u.ok){let e=await u.text().catch(()=>``);throw new N(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,M.GENERAL)}return`oss://${a}`}const An={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function jn(e){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);if(!l(e).isFile())throw new N(`Not a file: ${e}`,M.USAGE);let t=h(e).toLowerCase(),n=An[t];if(!n)throw new N(`Unsupported image format "${t||`unknown`}".`,M.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function Mn(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function Nn(e){let{apiKey:t,baseUrl:n=F.cn,model:r,filePath:a,identity:o,signal:s,timeout:c}=e;if(!i(a))throw new N(`File not found: ${a}`,M.USAGE);if(!l(a).isFile())throw new N(`Not a file: ${a}`,M.USAGE);return kn(await On(t,r,o,n,s),a,s,c)}function Pn(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Fn(e,t,n,r){return Pn(e)?Nn({apiKey:t,baseUrl:r.baseUrl,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function In(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 Ln(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
6
6
  `).replace(/\r/g,`
7
7
  `);let r=t.split(`
8
- `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function bn(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new P(`SSE event exceeded the maximum buffer size.`,N.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a}return{event:o}}async function*xn(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16777216;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
8
+ `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Rn(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a}return{event:o}}async function*zn(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16777216;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
9
9
  `).replace(/\r/g,`
10
10
  `).split(`
11
- `);r=t.pop()??``;for(let n of t){let t=bn(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new P(`SSE stream exceeded the maximum buffer size.`,N.GENERAL);let{lines:s,rest:c}=yn(r);r=c;for(let t of s){let n=bn(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=bn(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function Sn(e){return String(e)}var Cn=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=/* @__PURE__ */ new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);await this.openSse();let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP SSE] Session initialized`),console.error(`[MCP SSE] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new P(`MCP SSE session closed.`,N.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out waiting for response headers.`,N.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new P(e,N.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof P?e:new P(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,N.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Tn(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of xn(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=wn(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Sn(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new P(`MCP SSE stream ended before endpoint event.`,N.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let n=this.nextId++,r=Sn(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=Tn(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new P(`MCP error (${e.error.code}): ${e.error.message}`,N.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);if(!this.messageUrl)throw new P(`MCP SSE message endpoint is not ready.`,N.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=En(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):n.timedOut?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:t})}throw new P(e,N.GENERAL)}}finally{n.cleanup()}}};function wn(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new P(`MCP SSE endpoint is not a valid URL: ${t}`,N.GENERAL)}if(n.origin!==r.origin)throw new P(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,N.GENERAL);return n.toString()}function Tn(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new P(t,N.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function En(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function Dn(e){return`/api/v1/mcps/${e}/mcp`}function On(e){return`/api/v1/mcps/${e}/sse`}function kn(e){return e instanceof P&&/^MCP request failed:\s*405\b/i.test(e.message)}function An(e){return e instanceof P&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function jn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new Mn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!An(e))throw e}let r=new Cn(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new Mn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!kn(e)||a===`WebSearch`)throw e}let c=new Cn(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var Mn=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new P(`MCP error (${a.error.code}): ${a.error.message}`,N.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of xn(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new P(`MCP SSE response stream ended without a matching JSON-RPC response.`,N.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new P(e,N.GENERAL)}return r}},Nn=class{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new P(`This command needs a model-domain API key.`,N.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new P(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,N.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...z(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return Qt(this.http,this.toOpts(e))}requestJson(e){return nn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return gn(e)?_n(e,this.requireApi().token,t,{...n,identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return gn(e)?this.usesTokenPlanEndpoint()?Promise.resolve(pn(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Mn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),jn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Dn(e)),sseUrl:this.url(On(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new P(`This command needs a console access token.`,N.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await Wt(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof P)||e.exitCode!==N.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await Rn({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await Wt({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?rn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=an({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${Gt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${Gt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...z(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new P(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,N.GENERAL)}if(!s.ok||l.Success===!1)throw new P(`${l.Code||s.status} - ${l.Message||s.statusText}`,N.GENERAL);return l}};const Pn=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function Fn(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Pn.has(n))throw new P(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,N.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function In(e,t){let n=await Wt(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new P(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,N.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function Ln(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Nn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=Fn(n,r),l=Pn.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new P(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,N.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function Rn(e){let t=e.settings.configName,n=R(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
12
- `);let a=(await Ln({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await In({...Fn(e.settings,e.baseUrl),token:a},e.settings);let o=R(t);return o.access_token=a,await Ct(o,t),a}function zn(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new F(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function Bn(){return`/compatible-mode/v1/chat/completions`}function Vn(){return`/compatible-mode/v1/responses`}function Hn(){return`/compatible-mode/v1/systemone`}function Un(){return`/api/v1/services/aigc/image-generation/generation`}function Wn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Gn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Kn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function qn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Jn(){return`/api/v1/services/aigc/image2video/video-synthesis`}function Yn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Xn(){return`/api/v1/models/limits`}function Zn(){return`/api/v1/models/permissions`}function Qn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function $n(e,t){return zn(e,t)}function er(){return`/api/v2/apps/memory/add-async`}function tr(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function nr(){return`/api/v2/apps/memory/memory_nodes/search`}function rr(){return`/api/v2/apps/memory/memory_nodes`}function ir(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function ar(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function or(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function sr(){return`/api/v1/services/audio/asr/transcription`}function cr(){return`/api/v1/services/audio/asr/customization`}function lr(){return`/api/v2/apps/memory/profile_schemas`}function ur(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function dr(e){return`${ur(e)}/user_profile`}function fr(e){return`${ur(e)}/profile_values`}function pr(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function mr(e){return zn(e,`/api/v1/indices/knowledge/search`)}function hr(e){return zn(e,`/api/v2/apps/knowledge/chat`)}function gr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const _r=`/api/v1/agentstudio/security`;function vr(e){return`${e}${_r}/overview`}function yr(e){return`${e}${_r}/agent_logs`}function br(){return`/api/v1/mcps/WebSearch/mcp`}function xr(){return`/compatible-mode/v1/files`}function Sr(){return`/api/v1/files`}function Cr(e){return`/api/v1/files/${encodeURIComponent(e)}`}function wr(){return`/api/v1/fine-tunes`}function Tr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Er(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Dr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Or(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function kr(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Ar(){return`/api/v1/fine-tunes/compress/templates`}function jr(){return`/api/v1/fine-tunes/compress/jobs`}function Mr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function Nr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function Pr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function Fr(){return`/api/v1/deployments`}function Ir(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Lr(e){return`${Ir(e)}/capacity-instances`}function Rr(e,t){return`${Lr(e)}/${encodeURIComponent(t)}`}function zr(e,t){return`${Rr(e,t)}/scale`}function Br(e,t){return`${Rr(e,t)}/renew`}function Vr(e){return`${Ir(e)}/update-overflowstrategy`}function Hr(e,t){return`${Ir(e)}/capacity-operations/${encodeURIComponent(t)}`}function Ur(e){return`${Ir(e)}/scale`}function Wr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function Gr(){return`/api/v1/deployments/models`}function Kr(e,t){return zn(e,t)}function qr(){return`/api/v1/agentstudio/files`}function Jr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function Yr(e){return`/api/v1/agentstudio/sandbox${e}`}function Xr(e,t){return Jr(e)+Yr(t)}const Zr={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function Qr(e){return`${Zr.sandboxes}/${encodeURIComponent(e)}`}function $r(e,t){return`${Qr(e)}/${t}`}function ei(e){return`${Zr.templates}/${encodeURIComponent(e)}`}function ti(e,t){return`${ei(e)}/builds/${encodeURIComponent(t)}/status`}const ni={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},ri=[`qwen-image`,`wan2.7-image`,`z-image`],ii=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function ai(e,t){return t.some(t=>e.startsWith(t))}function oi(e){return ai(e,ri)||e.startsWith(`wan2.6-image`)}function si(e){return ai(e,ri)}function ci(e){return ai(e,ii)}function li(e){return/^wanx-v1(?:-|$)/i.test(e)}function ui(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||si(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||li(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function di(e){return/wan2\.5-i2i/i.test(e)}function fi(e){return/imageedit/i.test(e)}function pi(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:li(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:ui(e)?`wan-legacy`:`wan26`}function mi(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function B(e,t){return{...e,sizeProfile:pi(t),promptExtendDefault:mi(t)}}function hi(e){return si(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):ui(e)?B({kind:`async-text2image`,path:Gn(),useSync:!1,inputStyle:`prompt`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function gi(e){return ci(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):fi(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`function-base-image`},e):di(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`prompt-images`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function _i(e){return/realtime|streaming/i.test(e)}function vi(e){return/filetrans/i.test(e)}function yi(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const bi=[`fun-asr-flash`,`qwen-audio`];function xi(e){return _i(e)||vi(e)?!1:!!(e.startsWith(bi[0])||e.startsWith(bi[1])&&/asr-flash/i.test(e))}function Si(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||vi(e)||_i(e)||xi(e))}function Ci(e){if(_i(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(vi(e)){let t=yi(e);return{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return xi(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`input-audio`}:Si(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function wi(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Ti(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function Ei(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Di(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:wi(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Ti(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Oi(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function ki(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const Ai={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},ji=new Set(Object.values(ze));function Mi(e){return ji.has(e.replace(/\/+$/,``))}function Ni(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function Pi(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function Fi(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new P(`Security API failed: ${r} - ${t??`no message`}${i}`,N.GENERAL,Ai[r],{rawResponse:n.slice(0,500)})}function Ii(e,t){let n;try{n=JSON.parse(e)}catch{throw new P(`Security API returned non-JSON response (${t??`unknown type`}).`,N.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=Ni(n),i=r?Ni(r.data):void 0,a=i?Ni(i.DataV2):void 0;if(a){let t=Ni(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=Pi(i?.errorCode,r?.errorCode),c=Pi(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&Fi(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||Fi(Pi(r.errorCode),Pi(r.errorMsg),e),r.data??null;if(r){let t=Pi(i?.errorCode,r.errorCode),n=Pi(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&Fi(t,n,e)}if(r)return r;Fi(void 0,void 0,e)}async function Li(e,t){let n=await e.request({path:t,method:`GET`});return Ii(await n.text(),n.headers.get(`content-type`))}function Ri(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function zi(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Bi(e){return async(t,n={})=>{let r=zi(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),Ri(r))for(let[t,n]of Object.entries(z(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${Gt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Vi=`2024-08-16`;function Hi(e){return`bailiancontrol.${e}.aliyuncs.com`}function Ui(e){return new Nn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Wi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Vi,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Gi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Vi,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ki(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Vi,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const qi=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ji=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function V(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Yi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=V(await e(qi,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Xi(e,t={}){let n=t.pageSize??50,r=await Yi(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await Yi(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Zi(e,t){return(await Yi(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Qi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=V(await e(qi,{input:u}));return{total:d.total??0,groups:d.list??[]}}function $i(e){return e.flatMap(e=>e.items??[])}async function ea(e,t={}){let n=t.pageSize??50,r=await Qi(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Qi(e,{...t,pageNo:r,pageSize:n})));return $i([r.groups,...o.map(e=>e.groups)].flat())}async function ta(e,t){return(V(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const na=[`name`,`key`,`default`,`tip`,`range`];function ra(e){return e.map(e=>{let t={};for(let n of na)e[n]!==void 0&&(t[n]=e[n]);return t})}async function ia(e,t){let n=V(await e(Ji,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?ra(e):null}catch{return null}return Array.isArray(n)?ra(n):null}function aa(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Le(String(r)):r;await Ct(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await Ct(n,e)},profiles:()=>Tt(),activate:e=>Ot(e),validateActivation:e=>Dt(e),get path(){return st()}}}async function oa(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:xr(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?(/* @__PURE__ */ new Date(f.created_at*1e3)).toISOString():void 0,request_id:f.request_id};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new P(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,N.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new P(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,N.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function sa(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Sr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ca(e,t,n){return e.requestJson({path:Cr(t),method:`GET`,signal:n})}async function la(e,t,n){let r=await e.request({path:Cr(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ua=209715200,da=314572800,fa=314572800,pa=2147483648;function ma(e,t=ua){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);let n=l(e);if(!n.isFile())throw new P(`Not a regular file: ${e}`,N.USAGE);if(n.size===0)throw new P(`File is empty: ${e}`,N.USAGE);if(n.size>t)throw new P(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,N.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ha(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new P(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,N.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function ga(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=/* @__PURE__ */ 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 _a=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),va=.1;function ya(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<va||a>10)&&i.push(H(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${va} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(H(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(H(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function ba(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(H(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(H(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(H(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(H(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(H(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(H(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(H(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...ya(s,Array.isArray(e),t,o))}}}return r}function xa(e,t,n){let r=[];if(!Array.isArray(e))return r.push(H(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(H(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(H(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(H(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(H(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(H(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Sa(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(H(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!_a.has(a))&&r.push(H(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(H(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...ba(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(H(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...xa(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function Ca(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(H(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(H(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Sa(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(H(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(H(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(H(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(H(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(H(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(H(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;wa(a)&&n.push(H(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(H(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(H(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function wa(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const Ta={name:`chatml`,detect:()=>!0,inspect:Ca};function Ea(e,t){let n=[];if(!(`text`in e))return n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Da={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ea};function Oa(e,t){let n=Ca(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(H(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(H(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(H(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Sa(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Sa(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const ka={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Oa},Aa=[`choice`,`noul`,`score`],ja=255,Ma=2,Na=255,Pa=/* @__PURE__ */ new Set([`true`,`false`]);function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){return typeof e==`string`&&e.trim().length>0}function W(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function Ia(e,t=`state`){return Fa(e)||Array.isArray(e)&&e.length>0||U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function La(e,t){let n=`${t}.criteria`;if(!U(e))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!Fa(t)||!Fa(r))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function Ra(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!Fa(e))?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function za(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return U(e)&&Object.entries(e).every(([e,t])=>Pa.has(e)&&typeof t==`string`)?[]:[W(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function Ba(e,t){if(!U(e))return[W(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(W(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...La(e.criteria,t)):e.type===`noul`?n.push(...za(e.criteria,t)):e.type===`score`?n.push(...Ra(e.criteria,t)):n.push(W(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function Va(e,t=`questions`){return U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function Ha(e,t=`questions`){return Fa(e)?[]:[W(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function Ua(e,t=`questions`){let n=Va(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=Ha(n,t);if(e.length>0){r.push(...e);continue}r.push(...Ba(i,`${t}.${n}`))}return r}function G(e,t,n,r){return H(`error`,e,t,{line:n,path:r})}function Wa(e,t){return G(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Ga(e,t,n,r){if(!U(e))return[G(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[G(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[G(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[G(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Ka(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[G(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Ga(e.target,r,t,`${n}.target`)}function qa(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Ga(e.target,[`true`,`false`],t,`${n}.target`):[G(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Ja(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[G(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:Ga(e.target,i,t,`${n}.target`)}function Ya(e,t){let n=Ia(e.state).map(e=>Wa(e,t)),r=e.questions,i=Va(r);if(i.length>0)return n.push(...i.map(e=>Wa(e,t))),n;for(let[e,i]of Object.entries(r)){let r=Ha(e);if(r.length>0){n.push(...r.map(e=>Wa(e,t)));continue}let a=`questions.${e}`,o=Ba(i,a);if(o.length>0){n.push(...o.map(e=>Wa(e,t)));continue}let s=i;s.type===`choice`?n.push(...Ka(s,t,a)):s.type===`noul`?n.push(...qa(s,t,a)):n.push(...Ja(s,t,a))}return n}const Xa={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:Ya};function Za(e,t){let n=[];if(!(`wav_fn`in e))n.push(H(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(H(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(H(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(H(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Qa={name:`tts`,detect:e=>`wav_fn`in e,inspect:Za},$a=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function eo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function to(e){return/^[\x20-\x7E]+$/.test(e)}function no(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(H(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(H(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`img_path`})),to(r)||n.push(H(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(H(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`input_img`})),to(r)||n.push(H(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const ro={name:`image`,detect:e=>`img_path`in e,inspect:no},io=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),ao=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function oo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function so(e){return/^[\x20-\x7E]+$/.test(e)}function co(e,t,n,r,i,a){if(!(n in t)){r&&e.push(H(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(H(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(H(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=oo(o);i.has(s)||e.push(H(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),so(o)||e.push(H(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function lo(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return co(n,e,`first_frame_path`,!0,io,t),co(n,e,`last_frame_path`,!1,io,t),co(n,e,`video_path`,!1,ao,t),n}const uo=[Qa,ro,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:lo},Xa,ka,Da,Ta];function fo(e,t){return t===void 0?uo.find(t=>t.detect(e))??Ta:uo.find(e=>e.name===t)||Ta}async function po(e,t){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(H(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function mo(e,t,r,i,a){let o=r?null:new Set(ga(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=x({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(H(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...ho(n,d,i))}return{sampled:c,issues:s}}function ho(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[H(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return fo(r,n).inspect(r,t)}const go={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await po(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[H(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await mo(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 _o(e,t){return new Promise((n,r)=>{oe.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function vo(e){return new Promise((t,n)=>{oe.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const yo=/^[a-zA-Z0-9_-]+$/;function bo(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function xo(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function So(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||xo(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=bo(n),i=n.slice(e.length);e.length>0&&!yo.test(e)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=bo(i);if(a.length>120&&t.length<10&&t.push(H(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(H(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(H(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Co(e,t,n){let{entry:i,zipfile:a}=await _o(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);ae(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function wo(e,t=100){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const To={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await vo(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(H(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(H(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=So(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(H(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||xo(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return $a.has(n)});e.length<25&&r.push(H(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ne(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Co(e,_,y)}catch(t){return r.push(H(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await go.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await wo(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(H(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Eo(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Do(e);if(t===`.zip`)return Oo(e);throw new P(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,N.USAGE)}async function Do(e){let t=await Ao(e);if(!t)throw new P(`JSONL file is empty or contains only blank lines: ${e}`,N.USAGE);let n=ko(t);return n===`unknown`?`text`:n}async function Oo(e){let t=await jo(e,`data.jsonl`);if(!t)throw new P(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,N.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ko(t);if(n===`unknown`)throw new P(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,N.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ko(e){let t;try{t=JSON.parse(e)}catch{throw new P(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,N.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,N.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Ao(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function jo(e,t){return _o(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new P(`Failed to read "${t}" from ZIP: ${e?.message}`,N.USAGE));return}let o=x({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Mo=[go,To];function No(e){let t=h(e).toLowerCase(),n=Mo.find(e=>e.extensions.includes(t));if(!n){let e=Mo.flatMap(e=>e.extensions).join(`, `);throw new P(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,N.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Po(e){Mo.some(t=>t.format===e.format)||Mo.push(e)}async function K(e,t={}){let{bytes:n}=ma(e,t.maxBytes??209715200),r=await No(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Fo(){return Mo.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Io(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}`}const Lo=`decision-model-preview`,Ro=[`cn-beijing`,`ap-southeast-1`],zo=`cn-beijing`,Bo=[`label`,`target`];function Vo(e){if(!U(e))return e;let t=e.questions;return U(t)&&typeof t.type!=`string`?t:e}function Ho(e){if(!U(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!U(r)){t[n]=r;continue}let e={...r};for(let t of Bo)delete e[t];t[n]=e}return t}async function Uo(e,t,n){return e.requestJson({path:wr(),method:`POST`,body:t,signal:n})}async function Wo(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=wr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Go(e,t,n){return e.requestJson({path:Tr(t),method:`GET`,signal:n})}async function Ko(e,t,n){return e.requestJson({path:Er(t),method:`POST`,signal:n})}async function qo(e,t,n){return e.requestJson({path:Tr(t),method:`DELETE`,signal:n})}async function Jo(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=Dr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Yo(e,t,n){return e.requestJson({path:Or(t),method:`GET`,signal:n})}async function Xo(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${kr(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Zo(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Qo(e,t={}){return e.requestJson({path:Zo(Ar(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function $o(e,t,n){return e.requestJson({path:jr(),method:`POST`,body:t,signal:n})}async function es(e,t={}){let n=Zo(jr(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function ts(e,t,n){return e.requestJson({path:Mr(t),method:`GET`,signal:n})}async function ns(e,t,n={}){return e.requestJson({path:Zo(Pr(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function rs(e,t,n){return e.requestJson({path:Nr(t),method:`POST`,signal:n})}async function is(e,t,n){return e.requestJson({path:Mr(t),method:`DELETE`,signal:n})}const as={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`}},os=Object.keys(as),ss=`sft-lora`;function cs(e){return e in as}function ls(e){let{method:t,variant:n}=as[e];return{method:t,variant:n}}function us(e,t){if(!e)return!1;let{method:n,variant:r}=as[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function ds(e){return e?os.filter(t=>us(e,t)):[]}async function fs(e,t){return await Zi(Ht(e),t)}const ps=`INSUFFICIENT_SAMPLES`;function ms(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ps,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
13
- `)}}function hs(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function gs(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return K(e,{...r,schema:n})},resolveHyperParameters(e,t){return hs(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const _s=gs(`sft`,`sft`,`chatml`),vs={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},ys={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},bs={...ys,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},xs={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Ss(e){return e===`image`||e===`image-i2i`}function Cs(e){return e===`video`||e===`video-kf2v`}function ws(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Ts(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Es=[_s,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return K(e,{...n,schema:`tts`});if(Ss(t))return K(e,{...n,schema:`image`,maxBytes:pa});if(Cs(t)){let r=await K(e,{...n,schema:`video`,maxBytes:pa});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(H(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(H(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return K(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...vs};if(Ss(e)){let n={...e===`image-i2i`?bs:ys};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Cs(e)){let e=t.model??t.baseModel,n={...xs,batch_size:Ts(e)?1:4,max_pixels:Ts(e)?102400:ws(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return hs(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!Ss(t)&&!Cs(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Ss(e)||Cs(e)}},gs(`dpo`,`dpo_full`,`dpo`),gs(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return K(e,{...n,schema:`cpt`,maxBytes:da})},resolveHyperParameters(e,t){return hs(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Ds(e){let t=Es.find(t=>t.clientTrainingType===e);if(!t){let t=Es.map(e=>e.clientTrainingType).join(`, `);throw new P(`Unknown training type "${e}".`,N.USAGE,`Supported training types: ${t}.`)}return t}function Os(){return Es.map(e=>e.clientTrainingType)}const ks=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,As=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,js=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Ms(e,t){return V(await e.console(ks,{query:{type:0,modelId:t}}))}async function Ns(e,t,n){return V(await e.console(As,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Ps(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return V(await e.console(js,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}function Fs(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function Is(e,t,n){return e.requestJson({path:Fr(),method:`POST`,body:t,signal:n})}async function Ls(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.plan!==void 0&&n.set(`plan`,t.plan);let r=Fr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Rs(e,t,n){return e.requestJson({path:Ir(t),method:`GET`,signal:n})}async function zs(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)),n.includeDeleted!==void 0&&r.set(`include_deleted`,String(n.includeDeleted)),n.statuses!==void 0&&r.set(`statuses`,n.statuses.join(`,`)),n.chargeTypes!==void 0&&r.set(`charge_types`,n.chargeTypes.join(`,`));let i=Lr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Bs(e,t,n,r){return e.requestJson({path:Rr(t,n),method:`GET`,signal:r})}async function Vs(e,t,n,r){return e.requestJson({path:Hr(t,n),method:`GET`,signal:r})}async function Hs(e,t,n,r={}){return e.requestJson({path:Lr(t),method:`POST`,body:n,headers:Fs(r.requestId),signal:r.signal})}async function Us(e,t,n,r,i={}){return e.requestJson({path:zr(t,n),method:`PUT`,body:r,headers:Fs(i.requestId),signal:i.signal})}async function Ws(e,t,n,r,i={}){return e.requestJson({path:Br(t,n),method:`PUT`,body:r,headers:Fs(i.requestId),signal:i.signal})}async function Gs(e,t,n,r={}){let i=Rr(t,n),a=new URLSearchParams;return r.reason!==void 0&&a.set(`reason`,r.reason),e.requestJson({path:a.toString()?`${i}?${a.toString()}`:i,method:`DELETE`,headers:Fs(r.requestId),signal:r.signal})}async function Ks(e,t,n,r){return e.requestJson({path:Vr(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function qs(e,t,n){return e.requestJson({path:Ir(t),method:`DELETE`,signal:n})}async function Js(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=Gr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ys(e,t,n,r,i){return e.requestJson({path:Ur(t),method:`PUT`,body:n,headers:Fs(i),signal:r})}async function Xs(e,t,n,r){return e.requestJson({path:Wr(t),method:`PUT`,body:n,signal:r})}const q={LORA:`lora`,PTU:`ptu`,MU:`mu`},Zs=q.LORA;function Qs(e){return e===`audio`?q.MU:Zs}const $s={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},ec=$s.POST_PAY,J={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function tc(e,t){if(t||e.inputTpm!==void 0||e.outputTpm!==void 0){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm must be provided together.
11
+ `);r=t.pop()??``;for(let n of t){let t=Rn(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let{lines:s,rest:c}=Ln(r);r=c;for(let t of s){let n=Rn(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Rn(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function Bn(e){return String(e)}var Vn=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=/* @__PURE__ */ new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);await this.openSse();let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP SSE] Session initialized`),console.error(`[MCP SSE] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new N(`MCP SSE session closed.`,M.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await R.fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out waiting for response headers.`,M.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new N(e,M.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof N?e:new N(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,M.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Un(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of zn(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Hn(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Bn(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new N(`MCP SSE stream ended before endpoint event.`,M.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let n=this.nextId++,r=Bn(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=Un(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new N(`MCP error (${e.error.code}): ${e.error.message}`,M.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);if(!this.messageUrl)throw new N(`MCP SSE message endpoint is not ready.`,M.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=Wn(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await R.fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):n.timedOut?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:t})}throw new N(e,M.GENERAL)}}finally{n.cleanup()}}};function Hn(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new N(`MCP SSE endpoint is not a valid URL: ${t}`,M.GENERAL)}if(n.origin!==r.origin)throw new N(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,M.GENERAL);return n.toString()}function Un(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new N(t,M.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Wn(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function Gn(e){return`/api/v1/mcps/${e}/mcp`}function Kn(e){return`/api/v1/mcps/${e}/sse`}function qn(e){return e instanceof N&&/^MCP request failed:\s*405\b/i.test(e.message)}function Jn(e){return e instanceof N&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function Yn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new Xn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Jn(e))throw e}let r=new Vn(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new Xn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!qn(e)||a===`WebSearch`)throw e}let c=new Vn(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var Xn=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new N(`MCP error (${a.error.code}): ${a.error.message}`,M.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of zn(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new N(`MCP SSE response stream ended without a matching JSON-RPC response.`,M.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await R.fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}},Zn=class{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...z(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return mn(this.http,this.toOpts(e))}requestJson(e){return vn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Pn(e)?Fn(e,this.requireApi().token,t,{signal:n.signal,baseUrl:this.url(``,n.defaultBaseUrl),identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Pn(e)?this.usesTokenPlanEndpoint()?Promise.resolve(jn(e)):this.uploadFile(e,t,n):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Xn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),Yn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Gn(e)),sseUrl:this.url(Kn(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await on(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof N)||e.exitCode!==M.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await nr({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await on({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?yn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=bn({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${sn(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${sn(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await R.fetch(i,{method:e.method,headers:{...a,...z(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new N(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,M.GENERAL)}if(!s.ok||l.Success===!1)throw new N(`${l.Code||s.status} - ${l.Message||s.statusText}`,M.GENERAL);return l}};const Qn=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function $n(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Qn.has(n))throw new N(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,M.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function er(e,t){let n=await on(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new N(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,M.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function tr(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Zn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=$n(n,r),l=Qn.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new N(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,M.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function nr(e){let t=e.settings.configName,n=L(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
12
+ `);let a=(await tr({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await er({...$n(e.settings,e.baseUrl),token:a},e.settings);let o=L(t);return o.access_token=a,await Lt(o,t),a}function rr(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new P(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function ir(){return`/compatible-mode/v1/chat/completions`}function ar(){return`/compatible-mode/v1/batches`}function or(e){return`${ar()}/${encodeURIComponent(e)}`}function sr(e){return`${or(e)}/cancel`}function cr(e){return`/compatible-mode/v1/files/${encodeURIComponent(e)}/content`}function lr(){return`https://batch.dashscope.aliyuncs.com`}function ur(){return`/compatible-mode/v1/responses`}function dr(){return`/compatible-mode/v1/systemone`}function fr(){return`/api/v1/services/aigc/image-generation/generation`}function pr(){return`/api/v1/services/aigc/multimodal-generation/generation`}function mr(){return`/api/v1/services/aigc/text2image/image-synthesis`}function hr(){return`/api/v1/services/aigc/image2image/image-synthesis`}function gr(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function _r(){return`/api/v1/services/aigc/image2video/video-synthesis`}function vr(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function yr(){return`/api/v1/models/limits`}function br(){return`/api/v1/models/permissions`}function xr(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Sr(e,t){return rr(e,t)}function Cr(){return`/api/v2/apps/memory/add-async`}function wr(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function Tr(){return`/api/v2/apps/memory/memory_nodes/search`}function Er(){return`/api/v2/apps/memory/memory_nodes`}function Dr(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Or(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function kr(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Ar(){return`/api/v1/services/audio/asr/transcription`}function jr(){return`/api/v1/services/audio/asr/customization`}function Mr(){return`/api/v2/apps/memory/profile_schemas`}function Nr(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function Pr(e){return`${Nr(e)}/user_profile`}function Fr(e){return`${Nr(e)}/profile_values`}function Ir(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function Lr(e){return rr(e,`/api/v1/indices/knowledge/search`)}function Rr(e){return rr(e,`/api/v2/apps/knowledge/chat`)}function zr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const Br=`/api/v1/agentstudio/security`;function Vr(e){return`${e}${Br}/overview`}function Hr(e){return`${e}${Br}/agent_logs`}function Ur(){return`/api/v1/mcps/WebSearch/mcp`}function Wr(){return`/compatible-mode/v1/files`}function Gr(){return`/api/v1/files`}function Kr(e){return`/api/v1/files/${encodeURIComponent(e)}`}function qr(){return`/api/v1/fine-tunes`}function Jr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Yr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Xr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Zr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Qr(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function $r(){return`/api/v1/fine-tunes/compress/templates`}function ei(){return`/api/v1/fine-tunes/compress/jobs`}function ti(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function ni(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function ri(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function ii(){return`/api/v1/deployments`}function ai(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function oi(e){return`${ai(e)}/capacity-instances`}function si(e,t){return`${oi(e)}/${encodeURIComponent(t)}`}function ci(e,t){return`${si(e,t)}/scale`}function li(e,t){return`${si(e,t)}/renew`}function ui(e){return`${ai(e)}/update-overflowstrategy`}function di(e,t){return`${ai(e)}/capacity-operations/${encodeURIComponent(t)}`}function fi(e){return`${ai(e)}/scale`}function pi(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function mi(){return`/api/v1/deployments/models`}function hi(e,t){return rr(e,t)}function gi(){return`/api/v1/agentstudio/files`}function _i(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function vi(e){return`/api/v1/agentstudio/sandbox${e}`}function yi(e,t){return _i(e)+vi(t)}const bi={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function xi(e){return`${bi.sandboxes}/${encodeURIComponent(e)}`}function Si(e,t){return`${xi(e)}/${t}`}function Ci(e){return`${bi.templates}/${encodeURIComponent(e)}`}function wi(e,t){return`${Ci(e)}/builds/${encodeURIComponent(t)}/status`}const Ti={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},Ei=[`qwen-image`,`wan2.7-image`,`z-image`],Di=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function Oi(e,t){return t.some(t=>e.startsWith(t))}function ki(e){return Oi(e,Ei)||e.startsWith(`wan2.6-image`)}function Ai(e){return Oi(e,Ei)}function ji(e){return Oi(e,Di)}function Mi(e){return/^wanx-v1(?:-|$)/i.test(e)}function Ni(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||Ai(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||Mi(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function Pi(e){return/wan2\.5-i2i/i.test(e)}function Fi(e){return/imageedit/i.test(e)}function Ii(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:Mi(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Ni(e)?`wan-legacy`:`wan26`}function Li(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function Ri(e,t){return{...e,sizeProfile:Ii(t),promptExtendDefault:Li(t)}}function zi(e){return Ai(e)?Ri({kind:`sync-multimodal`,path:pr(),useSync:!0,inputStyle:`messages`},e):Ni(e)?Ri({kind:`async-text2image`,path:mr(),useSync:!1,inputStyle:`prompt`},e):Ri({kind:`async-image-generation`,path:fr(),useSync:!1,inputStyle:`messages`},e)}function Bi(e){return ji(e)?Ri({kind:`sync-multimodal`,path:pr(),useSync:!0,inputStyle:`messages`},e):Fi(e)?Ri({kind:`async-image2image`,path:hr(),useSync:!1,inputStyle:`function-base-image`},e):Pi(e)?Ri({kind:`async-image2image`,path:hr(),useSync:!1,inputStyle:`prompt-images`},e):Ri({kind:`async-image-generation`,path:fr(),useSync:!1,inputStyle:`messages`},e)}function Vi(e){return/realtime|streaming/i.test(e)}function Hi(e){return/filetrans/i.test(e)}function Ui(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const Wi=[`fun-asr-flash`,`qwen-audio`];function Gi(e){return Vi(e)||Hi(e)?!1:!!(e.startsWith(Wi[0])||e.startsWith(Wi[1])&&/asr-flash/i.test(e))}function Ki(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||Hi(e)||Vi(e)||Gi(e))}function qi(e){if(Vi(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(Hi(e)){let t=Ui(e);return{kind:`async-filetrans`,path:Ar(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return Gi(e)?{kind:`sync-flash`,path:pr(),useSync:!0,flashFamily:`input-audio`}:Ki(e)?{kind:`sync-flash`,path:pr(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Ar(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Ji(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Yi(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function Xi(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Zi(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:Ji(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Yi(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Qi(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function $i(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const ea={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},ta=new Set(Object.values(F));function na(e){return ta.has(e.replace(/\/+$/,``))}function ra(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function ia(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function aa(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new N(`Security API failed: ${r} - ${t??`no message`}${i}`,M.GENERAL,ea[r],{rawResponse:n.slice(0,500)})}function oa(e,t){let n;try{n=JSON.parse(e)}catch{throw new N(`Security API returned non-JSON response (${t??`unknown type`}).`,M.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=ra(n),i=r?ra(r.data):void 0,a=i?ra(i.DataV2):void 0;if(a){let t=ra(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=ia(i?.errorCode,r?.errorCode),c=ia(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&aa(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||aa(ia(r.errorCode),ia(r.errorMsg),e),r.data??null;if(r){let t=ia(i?.errorCode,r.errorCode),n=ia(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&aa(t,n,e)}if(r)return r;aa(void 0,void 0,e)}async function sa(e,t){let n=await e.request({path:t,method:`GET`});return oa(await n.text(),n.headers.get(`content-type`))}function ca(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function la(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function ua(e){return async(t,n={})=>{let r=la(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),ca(r))for(let[t,n]of Object.entries(z(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${sn(e.replace(/^Bearer /,``))}`)}let a=await R.fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const da=`2024-08-16`;function fa(e){return`bailiancontrol.${e}.aliyuncs.com`}function pa(e){return new Zn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function ma(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:da,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function ha(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:da,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function ga(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:da,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const _a=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,va=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function B(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function ya(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=B(await e(_a,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function ba(e,t={}){let n=t.pageSize??50,r=await ya(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await ya(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function xa(e,t){return(await ya(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Sa(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=B(await e(_a,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Ca(e){return e.flatMap(e=>e.items??[])}async function wa(e,t={}){let n=t.pageSize??50,r=await Sa(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Sa(e,{...t,pageNo:r,pageSize:n})));return Ca([r.groups,...o.map(e=>e.groups)].flat())}async function Ta(e,t){return(B(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Ea=[`name`,`key`,`default`,`tip`,`range`];function Da(e){return e.map(e=>{let t={};for(let n of Ea)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Oa(e,t){let n=B(await e(va,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Da(e):null}catch{return null}return Array.isArray(n)?Da(n):null}function ka(e){return{read:()=>L(e),async write(t){let n=L(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Ze(String(r)):r;await Lt(n,e)},async unset(t){let n=L(e);for(let e of t)delete n[e];await Lt(n,e)},profiles:()=>zt(),activate:e=>Ht(e),validateActivation:e=>Vt(e),get path(){return bt()}}}async function Aa(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=t.fileBlob?.size??l(r).size,s=m(r),c=t.fileBlob??await new Response(oe.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:Wr(),method:`POST`,body:u,signal:a});if(d.id)return{file_id:d.id,name:d.filename??s,size:d.bytes??o,purpose:d.purpose??i,gmt_create:d.created_at?(/* @__PURE__ */ new Date(d.created_at*1e3)).toISOString():void 0,request_id:d.request_id};let f=d.data?.failed_uploads;if(Array.isArray(f)&&f.length>0){let e=f[0]??{};throw new N(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,M.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new N(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,M.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function ja(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Gr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ma(e,t,n){return e.requestJson({path:Kr(t),method:`GET`,signal:n})}async function Na(e,t,n){let r=await e.request({path:Kr(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Pa=209715200,Fa=314572800,Ia=314572800,La=2147483648;function Ra(e,t=Pa){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);let n=l(e);if(!n.isFile())throw new N(`Not a regular file: ${e}`,M.USAGE);if(n.size===0)throw new N(`File is empty: ${e}`,M.USAGE);if(n.size>t)throw new N(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,M.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function V(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function za(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,M.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function Ba(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=/* @__PURE__ */ 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 Va=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),Ha=.1;function Ua(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<Ha||a>10)&&i.push(V(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${Ha} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(V(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(V(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function Wa(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(V(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(V(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(V(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(V(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(V(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(V(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(V(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(V(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...Ua(s,Array.isArray(e),t,o))}}}return r}function Ga(e,t,n){let r=[];if(!Array.isArray(e))return r.push(V(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(V(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(V(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(V(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(V(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(V(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(V(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Ka(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;return(typeof a!=`string`||!Va.has(a))&&r.push(V(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(V(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...Wa(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(V(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...Ga(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(V(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(V(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function qa(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,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Ka(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(V(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(V(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(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`}));for(let e of c)s.has(e)||n.push(V(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(V(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;Ja(a)&&n.push(V(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(V(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(V(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(V(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function Ja(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const Ya={name:`chatml`,detect:()=>!0,inspect:qa};function Xa(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 Za={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Xa};function Qa(e,t){let n=qa(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(V(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(V(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(V(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Ka(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`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(s){n.push(...Ka(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`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 $a={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Qa},eo=[`choice`,`noul`,`score`],to=255,no=2,ro=255,io=/* @__PURE__ */ new Set([`true`,`false`]);function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ao(e){return typeof e==`string`&&e.trim().length>0}function U(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function oo(e,t=`state`){return ao(e)||Array.isArray(e)&&e.length>0||H(e)&&Object.keys(e).length>0?[]:[U(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function so(e,t){let n=`${t}.criteria`;if(!H(e))return[U(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[U(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!ao(t)||!ao(r))return[U(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function co(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!ao(e))?[U(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[U(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function lo(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return H(e)&&Object.entries(e).every(([e,t])=>io.has(e)&&typeof t==`string`)?[]:[U(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function uo(e,t){if(!H(e))return[U(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(U(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...so(e.criteria,t)):e.type===`noul`?n.push(...lo(e.criteria,t)):e.type===`score`?n.push(...co(e.criteria,t)):n.push(U(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function fo(e,t=`questions`){return H(e)&&Object.keys(e).length>0?[]:[U(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function po(e,t=`questions`){return ao(e)?[]:[U(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function mo(e,t=`questions`){let n=fo(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=po(n,t);if(e.length>0){r.push(...e);continue}r.push(...uo(i,`${t}.${n}`))}return r}function W(e,t,n,r){return V(`error`,e,t,{line:n,path:r})}function ho(e,t){return W(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function go(e,t,n,r){if(!H(e))return[W(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[W(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[W(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[W(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function _o(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[W(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:go(e.target,r,t,`${n}.target`)}function vo(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:go(e.target,[`true`,`false`],t,`${n}.target`):[W(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function yo(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[W(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:go(e.target,i,t,`${n}.target`)}function bo(e,t){let n=oo(e.state).map(e=>ho(e,t)),r=e.questions,i=fo(r);if(i.length>0)return n.push(...i.map(e=>ho(e,t))),n;for(let[e,i]of Object.entries(r)){let r=po(e);if(r.length>0){n.push(...r.map(e=>ho(e,t)));continue}let a=`questions.${e}`,o=uo(i,a);if(o.length>0){n.push(...o.map(e=>ho(e,t)));continue}let s=i;s.type===`choice`?n.push(..._o(s,t,a)):s.type===`noul`?n.push(...vo(s,t,a)):n.push(...yo(s,t,a))}return n}const xo={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:bo};function So(e,t){let n=[];if(!(`wav_fn`in e))n.push(V(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(V(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(V(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(V(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(V(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(V(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Co={name:`tts`,detect:e=>`wav_fn`in e,inspect:So},wo=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function To(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Eo(e){return/^[\x20-\x7E]+$/.test(e)}function Do(e,t){let n=[];if(!(`prompt`in e))n.push(V(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(V(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(V(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(V(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=To(r);wo.has(e)||n.push(V(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...wo].join(`, `)}.`,{line:t,path:`img_path`})),Eo(r)||n.push(V(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(V(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=To(r);wo.has(e)||n.push(V(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...wo].join(`, `)}.`,{line:t,path:`input_img`})),Eo(r)||n.push(V(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const Oo={name:`image`,detect:e=>`img_path`in e,inspect:Do},ko=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Ao=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function jo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Mo(e){return/^[\x20-\x7E]+$/.test(e)}function No(e,t,n,r,i,a){if(!(n in t)){r&&e.push(V(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(V(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(V(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=jo(o);i.has(s)||e.push(V(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Mo(o)||e.push(V(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Po(e,t){let n=[];if(!(`prompt`in e))n.push(V(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(V(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return No(n,e,`first_frame_path`,!0,ko,t),No(n,e,`last_frame_path`,!1,ko,t),No(n,e,`video_path`,!1,Ao,t),n}const Fo=[Co,Oo,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Po},xo,$a,Za,Ya];function Io(e,t){return t===void 0?Fo.find(t=>t.detect(e))??Ya:Fo.find(e=>e.name===t)||Ya}async function Lo(e,t){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.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:o}))}return{totalLines:o,blankLines:s,issues:a}}async function Ro(e,t,r,i,a){let o=r?null:new Set(Ba(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=x({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))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:d}));continue}s.push(...zo(n,d,i))}return{sampled:c,issues:s}}function zo(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 Io(r,n).inspect(r,t)}const Bo={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Lo(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 Ro(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 Vo(e,t){return new Promise((n,r)=>{ce.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function Ho(e){return new Promise((t,n)=>{ce.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const Uo=/^[a-zA-Z0-9_-]+$/;function Wo(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function Go(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function Ko(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||Go(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Wo(n),i=n.slice(e.length);e.length>0&&!Uo.test(e)&&t.length<10&&t.push(V(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(V(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Wo(i);if(a.length>120&&t.length<10&&t.push(V(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(V(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(V(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function qo(e,t,n){let{entry:i,zipfile:a}=await Vo(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);se(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Jo(e,t=100){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const Yo={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Ho(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[V(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[V(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(V(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(V(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=Ko(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(V(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||Go(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return wo.has(n)});e.length<25&&r.push(V(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ie(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await qo(e,_,y)}catch(t){return r.push(V(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await Bo.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Jo(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(V(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Xo(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Zo(e);if(t===`.zip`)return Qo(e);throw new N(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,M.USAGE)}async function Zo(e){let t=await es(e);if(!t)throw new N(`JSONL file is empty or contains only blank lines: ${e}`,M.USAGE);let n=$o(t);return n===`unknown`?`text`:n}async function Qo(e){let t=await ts(e,`data.jsonl`);if(!t)throw new N(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,M.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=$o(t);if(n===`unknown`)throw new N(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,M.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function $o(e){let t;try{t=JSON.parse(e)}catch{throw new N(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,M.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,M.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function es(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function ts(e,t){return Vo(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new N(`Failed to read "${t}" from ZIP: ${e?.message}`,M.USAGE));return}let o=x({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const ns=[Bo,Yo];function rs(e){let t=h(e).toLowerCase(),n=ns.find(e=>e.extensions.includes(t));if(!n){let e=ns.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 is(e){ns.some(t=>t.format===e.format)||ns.push(e)}async function as(e,t={}){let{bytes:n}=Ra(e,t.maxBytes??209715200),r=await rs(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function os(){return ns.map(e=>({format:e.format,extensions:[...e.extensions]}))}function ss(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}`}const cs=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],ls=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],us=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),ds=524288e3,fs=6291456,ps=5e4;function G(e,t){throw new P(`${e}\n${t}`)}function ms(e){if(e instanceof N)return e;let t=e?.code;return new N(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,M.GENERAL,t===`ENOENT`?`Check the file and parent directory paths. / 请检查文件及父目录路径。`:t===`EEXIST`?`Output exists; use --force to replace it. / 输出已存在,使用 --force 覆盖。`:`Check file permissions and available disk space. / 请检查文件权限与磁盘空间。`,{cause:e})}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hs(e){return cs.includes(e)||G(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*gs(e){let t=typeof e==`string`?de(e):e instanceof Blob?ye.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw ms(e)}}async function*_s(e,t=1/0,n=fs){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return G(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of gs(e)){i+=a.byteLength,i>t&&G(`File exceeds ${t} bytes.`,`文件超过 ${t} 字节。`);let e=Buffer.concat([r,a]),s=0,c=e.indexOf(10,s);for(;c!==-1;){let t=c-s;t>n&&G(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`),yield{text:o(e.subarray(s,c)).replace(/\r$/,``),bytes:t+1},s=c+1,c=e.indexOf(10,s)}r=Buffer.from(e.subarray(s)),r.byteLength>n&&G(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function vs(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return G(`Media must use a public HTTP(S) or base64 data URL.`,`媒体必须使用公网 HTTP(S) 或 base64 data URL。`)}let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``),r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(n),i=r?parseInt(r[1],16):0,a=r?parseInt(r[2],16):0,o=r?[i>>8,i&255,a>>8,a&255].join(`.`):n,s=n===`localhost`||n.endsWith(`.localhost`)||ve(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||ve(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&G(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)vs(n,t);else if(K(e))for(let[n,r]of Object.entries(e))vs(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var ys=class{ids=/* @__PURE__ */ new Set;thinking;report={records:0,bytes:0,model:``,endpoint:`/v1/chat/completions`,warnings:[]};warn(e){this.report.warnings.includes(e)||this.report.warnings.push(e)}add(e,t){let n=this.report.records+1,r=e=>G(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);K(e)||r(`JSON object`);let i=e,a=i.custom_id;(typeof a!=`string`||!a.trim()||Array.from(a).length>256||this.ids.has(a))&&r(`custom_id`),i.method!==`POST`&&r(`method=POST`);let o=hs(String(i.url));K(i.body)||r(`body`);let s=i.body;if((typeof s.model!=`string`||!s.model.trim())&&r(`body.model`),s.enable_thinking!==void 0&&typeof s.enable_thinking!=`boolean`&&r(`enable_thinking`),this.report.records&&(this.report.model!==s.model||this.report.endpoint!==o||this.thinking!==s.enable_thinking)&&r(`model/url/enable_thinking`),o===`/v1/embeddings`){let e=e=>typeof e==`string`&&!!e.trim(),t=e=>Array.isArray(e)&&e.length>0&&e.every(e=>Number.isInteger(e)&&e>=0);e(s.input)||t(s.input)||Array.isArray(s.input)&&s.input.length>0&&(s.input.every(e)||s.input.every(t))||r(`body.input`)}else(!Array.isArray(s.messages)||!s.messages.length||s.messages.some(e=>!K(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(K))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(K))))&&r(`body.messages`);vs(s),K(s.extra_body)&&(`enable_thinking`in s.extra_body||`thinking_budget`in s.extra_body)&&this.warn(`Place enable_thinking/thinking_budget at body top level, not extra_body. / enable_thinking/thinking_budget 应放在 body 顶层,而非 extra_body。`),t>6291456&&r(`line <=6 MiB`),t>1048576&&this.warn(`Line exceeds 1 MiB; documentation differs (1/6 MiB), compatibility is not guaranteed. / 单行超过 1 MiB,文档存在 1/6 MiB 差异,不保证兼容。`),this.ids.add(a),this.report.records++,this.report.bytes+=t,this.report.model=s.model,this.report.endpoint=o,this.thinking=s.enable_thinking,(this.report.records>5e4||this.report.bytes>524288e3)&&r(`50000 records / 500 MiB`),s.model===`batch-test-model`&&(this.report.records>100||this.report.bytes>1048576)&&r(`batch-test-model: 100 records / 1 MiB`)}finish(){return this.report.records||G(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function bs(e){let t=new ys,n=0;for await(let r of _s(e,ds)){n++;let e;try{e=JSON.parse(r.text)}catch{G(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function xs(e){let t=[],n=0;for await(let r of gs(e))n+=r.byteLength,n>524288e3&&G(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function Ss(e,t,n){return e.requestJson({path:ar(),method:`POST`,body:t,signal:n})}function Cs(e,t,n){return e.requestJson({path:or(t),signal:n})}function ws(e,t,n){return e.requestJson({path:sr(t),method:`POST`,signal:n})}function Ts(e,t={},n){let r=new URLSearchParams;for(let[e,n]of Object.entries(t))n!==void 0&&r.set(e,Array.isArray(n)?n.join(`,`):String(n));return e.requestJson({path:ar()+(r.size?`?${r.toString()}`:``),signal:n})}function Es(e,t,n){return e.request({path:cr(t),signal:n})}function Ds(e){let t=e.url(ir(),lr),n=new URL(t).hostname.toLowerCase(),r=new URL(e.baseUrl).hostname.toLowerCase();return(e.usesTokenPlanEndpoint()||/^dashscope(?:-intl|-us)?\.aliyuncs\.com$/.test(n)||/^dashscope-(?:intl|us)\.aliyuncs\.com$/.test(r))&&G(`--batch needs the Batch host, not a realtime/international/Token Plan endpoint; configure --base-url explicitly.`,`--batch 不能使用实时、国际站或 Token Plan 端点,请显式配置 Batch --base-url。`),t}async function Os(e,t,n=!1){let r=j(e),i=j(k(r),`.${be(r)}.${Ne()}.tmp`),a,o=e=>{throw ms(e)};try{await De(k(r),{recursive:!0}).catch(o),a=await Oe(i,`wx`,384).catch(o);for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e,n=0;for(;n<t.byteLength;){let e=await a.write(t,n,t.byteLength-n).catch(o);n+=e.bytesWritten}}await a.sync().catch(o),await a.close().catch(o),a=void 0,n?await Ae(i,r).catch(o):await Ee(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await je(i).catch(()=>{})}}async function ks(e){let t=hs(e.endpoint??`/v1/chat/completions`);(j(e.file)===j(e.outputFile)||e.bodyFile&&j(e.bodyFile)===j(e.outputFile))&&G(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||G(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await ke(e.bodyFile,`utf8`)}catch(e){throw ms(e)}try{let e=JSON.parse(t);if(!K(e))throw Error();i=e}catch{G(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&G(`--body-file cannot define model/messages/input.`,`--body-file 不得定义 model/messages/input。`),t===`/v1/embeddings`&&(e.system!==void 0||`enable_thinking`in i||`thinking_budget`in i)&&G(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new ys,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of gs(e.file)){n+=r.byteLength,n>524288e3&&G(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{G(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{G(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=ye.from(l()),d=we({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&G(`CSV requires unique headers and mapped ID/input columns.`,`CSV 表头必须唯一并包含映射的 ID/输入列。`),s=e.filter(e=>e!==n&&e!==r),e)});u.on(`error`,e=>d.destroy(e)),u.pipe(d);let f=0;try{for await(let s of d){f++;let c=s;c[r]?.trim()||G(`Empty CSV input at record ${f}.`,`CSV 第 ${f} 条记录输入为空。`);let l={...i,model:e.model};t===`/v1/embeddings`?(l.input=c[r],l.encoding_format??=`float`):l.messages=[...e.system===void 0?[]:[{role:`system`,content:e.system}],{role:`user`,content:c[r]}];let u={custom_id:c[n],method:`POST`,url:t,body:l},d=JSON.stringify(u)+`
13
+ `;a.add(u,Buffer.byteLength(d)),e.dryRun&&o.length<2&&o.push(u),yield d}c=a.finish()}catch(e){throw e instanceof Error&&e.name===`Error`&&`code`in e&&String(e.code).startsWith(`CSV_`)&&G(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),ms(e)}finally{u.destroy(),d.destroy()}}if(e.dryRun)for await(let e of u());else await Os(e.outputFile,u(),e.force);return{...c,output_file:j(e.outputFile),ignored_columns:s,...e.dryRun?{samples:o}:{}}}const As=[`custom_id`,`model`,`request_id`,`status_code`,`content`,`embedding`,`error_code`,`error_message`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function q(e){return K(e)?e:{}}function js(e){let t=e==null?``:typeof e==`string`?e:JSON.stringify(e);return/^[\s\x00-\x1f]*[=+@-]/.test(t)?`'${t}`:t}function Ms(e){return typeof e==`number`&&Number.isFinite(e)?e:``}function Ns(e){let t=q(e),n=q(t.response),r=q(n.body),i=q(t.error??r.error),a=q(r.usage),o=q(q(Array.isArray(r.choices)?r.choices[0]:void 0).message),s=Array.isArray(r.data)?r.data.map(e=>{let t=q(e);return{index:t.index,embedding:t.embedding}}):void 0;return{recognized:Array.isArray(r.choices)||Array.isArray(r.data)||`code`in i||`message`in i,row:{custom_id:js(t.custom_id),model:js(r.model),request_id:js(n.request_id),status_code:Ms(n.status_code),content:js(o.content),embedding:js(s),error_code:js(i.code),error_message:js(i.message),prompt_tokens:Ms(a.prompt_tokens),completion_tokens:Ms(a.completion_tokens),total_tokens:Ms(a.total_tokens)}}}async function Ps(e,t,n=!1){let r=0,i=0;async function*a(){yield``+Te([],{columns:[...As],header:!0});for(let t of e)for await(let e of _s(t,1/0,1/0)){if(!e.text.trim())continue;let n;try{n=JSON.parse(e.text)}catch{G(`Invalid result JSONL at ${t}:${r+1}.`,`结果 JSONL 格式错误:${t}:${r+1}。`)}let a=Ns(n);r++,a.recognized||i++,yield Te([a.row],{columns:[...As]})}}return await Os(t,a(),n),{records:r,unknown_records:i}}function Fs(e){let t=e===`zh-CN`?`请介绍一下自己`:`Introduce yourself`,n={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-plus`,messages:[{role:`user`,content:t}]}},r={custom_id:`req-001`,method:`POST`,url:`/v1/embeddings`,body:{model:`text-embedding-v4`,input:t,encoding_format:`float`}},i={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-vl-plus`,messages:[{role:`user`,content:[{type:`text`,text:t},{type:`image_url`,image_url:{url:`https://example.com/image.jpg`}}]}]}},a={custom_id:`req-001`,response:{request_id:`request-001`,status_code:200,body:{model:`qwen-plus`,choices:[{message:{role:`assistant`,content:e===`zh-CN`?`你好`:`Hello`}}],usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}}},error:null};return{csv:`custom_id,content\nreq-001,${t}\nreq-002,2+2?`,chat:n,embedding:r,vision:i,defaults:{enable_thinking:!1,max_tokens:1024},success:a,failure:{custom_id:`req-002`,response:null,error:{code:`ExampleError`,message:`Example service error`}}}}function Is(e){let t=t=>{let n=Fs(t);if(e===`prepare`||e===`convert`)return`input.csv:\n${n.csv}\n\ninput.jsonl:\n${JSON.stringify(n.chat)}\n\ndefaults.json (--body-file):\n${JSON.stringify(n.defaults)}`;if(e===`create`)return`Chat JSONL:\n${JSON.stringify(n.chat)}\n\nEmbedding JSONL:\n${JSON.stringify(n.embedding)}\n\nMultimodal JSONL (${t===`zh-CN`?`请替换示例公网图片 URL`:`replace the example public image URL`}):\n${JSON.stringify(n.vision)}`;let r=Te([n.success,n.failure].map(e=>Ns(e).row),{columns:[...As],header:!0});return`result.jsonl:\n${JSON.stringify(n.success)}\n\nerror.jsonl (${t===`zh-CN`?`示意包络,真实服务需联调`:`illustrative envelope; verify with the service`}):\n${JSON.stringify(n.failure)}\n\nresult.csv:\n${r}`};return{"en-US":t(`en-US`),"zh-CN":t(`zh-CN`)}}const Ls=`decision-model-preview`,Rs=[`cn-beijing`,`ap-southeast-1`],zs=`cn-beijing`,Bs=[`label`,`target`];function Vs(e){if(!H(e))return e;let t=e.questions;return H(t)&&typeof t.type!=`string`?t:e}function Hs(e){if(!H(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!H(r)){t[n]=r;continue}let e={...r};for(let t of Bs)delete e[t];t[n]=e}return t}async function Us(e,t,n){return e.requestJson({path:qr(),method:`POST`,body:t,signal:n})}async function Ws(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=qr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Gs(e,t,n){return e.requestJson({path:Jr(t),method:`GET`,signal:n})}async function Ks(e,t,n){return e.requestJson({path:Yr(t),method:`POST`,signal:n})}async function qs(e,t,n){return e.requestJson({path:Jr(t),method:`DELETE`,signal:n})}async function Js(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=Xr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Ys(e,t,n){return e.requestJson({path:Zr(t),method:`GET`,signal:n})}async function Xs(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Qr(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Zs(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Qs(e,t={}){return e.requestJson({path:Zs($r(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function $s(e,t,n){return e.requestJson({path:ei(),method:`POST`,body:t,signal:n})}async function ec(e,t={}){let n=Zs(ei(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function tc(e,t,n){return e.requestJson({path:ti(t),method:`GET`,signal:n})}async function nc(e,t,n={}){return e.requestJson({path:Zs(ri(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function rc(e,t,n){return e.requestJson({path:ni(t),method:`POST`,signal:n})}async function ic(e,t,n){return e.requestJson({path:ti(t),method:`DELETE`,signal:n})}const ac={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`}},oc=Object.keys(ac),sc=`sft-lora`;function cc(e){return e in ac}function lc(e){let{method:t,variant:n}=ac[e];return{method:t,variant:n}}function uc(e,t){if(!e)return!1;let{method:n,variant:r}=ac[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function dc(e){return e?oc.filter(t=>uc(e,t)):[]}async function fc(e,t){return await xa(rn(e),t)}const pc=`INSUFFICIENT_SAMPLES`;function mc(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:pc,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(`
14
+ `)}}function hc(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function gc(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return as(e,{...r,schema:n})},resolveHyperParameters(e,t){return hc(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const _c=gc(`sft`,`sft`,`chatml`),vc={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},yc={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},bc={...yc,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},xc={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Sc(e){return e===`image`||e===`image-i2i`}function Cc(e){return e===`video`||e===`video-kf2v`}function wc(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Tc(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Ec=[_c,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return as(e,{...n,schema:`tts`});if(Sc(t))return as(e,{...n,schema:`image`,maxBytes:La});if(Cc(t)){let r=await as(e,{...n,schema:`video`,maxBytes:La});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(V(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(V(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return as(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...vc};if(Sc(e)){let n={...e===`image-i2i`?bc:yc};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Cc(e)){let e=t.model??t.baseModel,n={...xc,batch_size:Tc(e)?1:4,max_pixels:Tc(e)?102400:wc(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return hc(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!Sc(t)&&!Cc(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Sc(e)||Cc(e)}},gc(`dpo`,`dpo_full`,`dpo`),gc(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return as(e,{...n,schema:`cpt`,maxBytes:Fa})},resolveHyperParameters(e,t){return hc(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Dc(e){let t=Ec.find(t=>t.clientTrainingType===e);if(!t){let t=Ec.map(e=>e.clientTrainingType).join(`, `);throw new N(`Unknown training type "${e}".`,M.USAGE,`Supported training types: ${t}.`)}return t}function Oc(){return Ec.map(e=>e.clientTrainingType)}const kc=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,Ac=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,jc=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Mc(e,t){return B(await e.console(kc,{query:{type:0,modelId:t}}))}async function Nc(e,t,n){return B(await e.console(Ac,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Pc(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return B(await e.console(jc,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}function Fc(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function Ic(e,t,n){return e.requestJson({path:ii(),method:`POST`,body:t,signal:n})}async function Lc(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.plan!==void 0&&n.set(`plan`,t.plan);let r=ii(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Rc(e,t,n){return e.requestJson({path:ai(t),method:`GET`,signal:n})}async function zc(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)),n.includeDeleted!==void 0&&r.set(`include_deleted`,String(n.includeDeleted)),n.statuses!==void 0&&r.set(`statuses`,n.statuses.join(`,`)),n.chargeTypes!==void 0&&r.set(`charge_types`,n.chargeTypes.join(`,`));let i=oi(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Bc(e,t,n,r){return e.requestJson({path:si(t,n),method:`GET`,signal:r})}async function Vc(e,t,n,r){return e.requestJson({path:di(t,n),method:`GET`,signal:r})}async function Hc(e,t,n,r={}){return e.requestJson({path:oi(t),method:`POST`,body:n,headers:Fc(r.requestId),signal:r.signal})}async function Uc(e,t,n,r,i={}){return e.requestJson({path:ci(t,n),method:`PUT`,body:r,headers:Fc(i.requestId),signal:i.signal})}async function Wc(e,t,n,r,i={}){return e.requestJson({path:li(t,n),method:`PUT`,body:r,headers:Fc(i.requestId),signal:i.signal})}async function Gc(e,t,n,r={}){let i=si(t,n),a=new URLSearchParams;return r.reason!==void 0&&a.set(`reason`,r.reason),e.requestJson({path:a.toString()?`${i}?${a.toString()}`:i,method:`DELETE`,headers:Fc(r.requestId),signal:r.signal})}async function Kc(e,t,n,r){return e.requestJson({path:ui(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function qc(e,t,n){return e.requestJson({path:ai(t),method:`DELETE`,signal:n})}async function Jc(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=mi(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Yc(e,t,n,r,i){return e.requestJson({path:fi(t),method:`PUT`,body:n,headers:Fc(i),signal:r})}async function Xc(e,t,n,r){return e.requestJson({path:pi(t),method:`PUT`,body:n,signal:r})}const J={LORA:`lora`,PTU:`ptu`,MU:`mu`},Zc=J.LORA;function Qc(e){return e===`audio`?J.MU:Zc}const $c={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},el=$c.POST_PAY,Y={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function tl(e,t){if(t||e.inputTpm!==void 0||e.outputTpm!==void 0){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm must be provided together.
14
15
  必须同时提供 --input-tpm 和 --output-tpm。`;if(!Number.isSafeInteger(e.inputTpm)||e.inputTpm<0)return`--input-tpm must be a non-negative safe integer in kTPM.
15
16
  --input-tpm 必须是非负安全整数,单位为 kTPM。`;if(!Number.isSafeInteger(e.outputTpm)||e.outputTpm<0)return`--output-tpm must be a non-negative safe integer in kTPM.
16
- --output-tpm 必须是非负安全整数,单位为 kTPM。`}}function nc(e){let t={};return e.inputTpm!==void 0&&(t.input_tpm=e.inputTpm),e.outputTpm!==void 0&&(t.output_tpm=e.outputTpm),t}function rc(e){return e.duration!==void 0||e.autoRenewal!==void 0||e.autoRenewalDuration!==void 0||e.autoRenewalCycle!==void 0}function ic(e,t){if(t||rc(e)){if(e.duration===void 0||!Number.isSafeInteger(e.duration)||e.duration<=0)return`--duration must be a positive safe integer in days.
17
+ --output-tpm 必须是非负安全整数,单位为 kTPM。`}}function nl(e){let t={};return e.inputTpm!==void 0&&(t.input_tpm=e.inputTpm),e.outputTpm!==void 0&&(t.output_tpm=e.outputTpm),t}function rl(e){return e.duration!==void 0||e.autoRenewal!==void 0||e.autoRenewalDuration!==void 0||e.autoRenewalCycle!==void 0}function il(e,t){if(t||rl(e)){if(e.duration===void 0||!Number.isSafeInteger(e.duration)||e.duration<=0)return`--duration must be a positive safe integer in days.
17
18
  --duration 必须是正安全整数,单位为天。`;if(typeof e.autoRenewal!=`boolean`)return`--auto-renewal must explicitly be true or false.
18
19
  必须显式指定 --auto-renewal 为 true 或 false。`;if((e.autoRenewal||e.autoRenewalDuration!==void 0)&&(e.autoRenewalDuration===void 0||!Number.isSafeInteger(e.autoRenewalDuration)||e.autoRenewalDuration<=0))return`--auto-renewal-duration must be a positive safe integer in days; required when --auto-renewal=true.
19
20
  --auto-renewal-duration 必须是正安全整数(天);开启自动续费时必填。`;if(e.autoRenewalCycle!==void 0&&(typeof e.autoRenewalCycle!=`string`||e.autoRenewalCycle.trim()===``))return`--auto-renewal-cycle must be a non-empty string.
20
- --auto-renewal-cycle 必须是非空字符串。`}}function ac(e){if(!rc(e))return;let t={};return e.duration!==void 0&&(t.duration=e.duration),e.autoRenewal!==void 0&&(t.auto_renewal=e.autoRenewal),e.autoRenewalDuration!==void 0&&(t.auto_renewal_duration=e.autoRenewalDuration),e.autoRenewalCycle!==void 0&&(t.auto_renewal_cycle=e.autoRenewalCycle),t}const oc={name:q.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},sc={name:q.PTU,validateFlags(e){return e.capacity!==void 0||e.deploySpec!==void 0||e.billingMethod!==void 0?`--capacity, --deploy-spec and --billing-method are not supported for plan=ptu; use reservation capacity and --charge-type.
21
- plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==J.PRE_PAID&&e.chargeType!==J.POST_PAID?`--charge-type is required for plan=ptu and must be pre_paid or post_paid.
21
+ --auto-renewal-cycle 必须是非空字符串。`}}function al(e){if(!rl(e))return;let t={};return e.duration!==void 0&&(t.duration=e.duration),e.autoRenewal!==void 0&&(t.auto_renewal=e.autoRenewal),e.autoRenewalDuration!==void 0&&(t.auto_renewal_duration=e.autoRenewalDuration),e.autoRenewalCycle!==void 0&&(t.auto_renewal_cycle=e.autoRenewalCycle),t}const ol={name:J.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},sl={name:J.PTU,validateFlags(e){return e.capacity!==void 0||e.deploySpec!==void 0||e.billingMethod!==void 0?`--capacity, --deploy-spec and --billing-method are not supported for plan=ptu; use reservation capacity and --charge-type.
22
+ plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==Y.PRE_PAID&&e.chargeType!==Y.POST_PAID?`--charge-type is required for plan=ptu and must be pre_paid or post_paid.
22
23
  plan=ptu 必须提供 --charge-type,且只能为 pre_paid 或 post_paid。`:e.serviceTier!==void 0&&e.serviceTier!==`ptu_fast`&&e.serviceTier!==`ptu_default`?`--service-tier must be ptu_fast or ptu_default.
23
- --service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===J.POST_PAID?`ptu_default only supports pre_paid.
24
- ptu_default 仅支持 pre_paid。`:e.chargeType===J.POST_PAID&&rc(e)?`Prepaid flags are not allowed with --charge-type post_paid.
25
- --charge-type post_paid 不允许提供预付费参数。`:tc(e,!0)??ic(e,e.chargeType===J.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
26
- 当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:nc(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=ac(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},cc={name:q.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||ec,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new P(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,N.USAGE);try{let a=await Js(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===q.MU)?.templates??[];if(o.length===0)throw i();let s=t===$s.POST_PAY?J.POST_PAID:J.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof P?e:new P(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,N.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},lc={[q.LORA]:oc,[q.PTU]:sc,[q.MU]:cc};function uc(e){let t=lc[e];if(!t)throw new P(`Unsupported plan "${e}". Supported plans: ${Object.keys(lc).join(`, `)}.`,N.USAGE);return t}const dc=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,fc=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,pc=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function mc(e,t){return V(await e.console(dc,{input:{modelServiceId:t}}))}async function hc(e,t){return V(await e.console(fc,{input:{modelServiceId:t}}))}async function gc(e){let t=[],n=1;for(;;){let r=V(await e.console(pc,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function _c(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const vc=`speech-biasing`;function yc(e,t){return{model:vc,input:{action:e,...t}}}async function bc(e,t,n,r){return e.requestJson({path:cr(),method:`POST`,body:yc(t,n),signal:r})}function xc(e,t,n){return bc(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function Sc(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),bc(e,`list_vocabulary`,r,n)}function Cc(e,t,n){return bc(e,`query_vocabulary`,{vocabulary_id:t},n)}function wc(e,t,n,r){return bc(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function Tc(e,t,n){return bc(e,`delete_vocabulary`,{vocabulary_id:t},n)}function Ec(e,t){try{return JSON.parse(e)}catch(e){throw new F(`${t} is not valid JSON — ${e.message}`)}}function Dc(e){let t=Ec(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new F(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new F(`--vocabulary weight for "${e}" must be a number.`);return t}function Oc(e,t){let n=`--words`,r=Ec(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new F(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new F(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new F(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new F(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new F(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new F(`${n} must contain at least one hot word.`);return i}const kc={introspect:{type:`switch`,description:{"en-US":`Print the machine-readable command schema (JSON) and exit`,"zh-CN":`输出机器可读的命令说明(JSON)并退出`}},output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},Ac={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},jc={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},Mc={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},Nc={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Pc={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function Fc(e){return e.auth===`apiKey`?Mc:e.auth===`console`?Nc:e.auth===`openapi`?Pc:{}}function Ic(e){return e}const Lc=1;function Rc(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function zc(e,t){return`${Rc(e||`image`,`image`)}_${Rc((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function Bc(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return Vc(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function Vc(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const Hc=()=>g(f(),`bailian-output`);function Uc(e,t){let n=t?.flagDir||e.outputDir||Hc(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Wc(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Gc(e){return o(e===`-`?0:e,`utf-8`)}async function Kc(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function qc(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new P(`Invalid ${t} value "${String(e)}". Use true or false.`,N.USAGE)}function Jc(e,t=`boolean`){if(e!=null)return qc(e,t)}function Yc(e,t,n=`boolean`){let r=Jc(e,n);return r===void 0?t:r}function Xc(e,t){return Jc(e,`watermark`)??t??!0}const Zc=/^[a-z0-9][a-z0-9.-]{0,63}$/,Qc=/^bailian-[a-z0-9-]{1,64}$/,$c=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function el(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function tl(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return Zc.test(t)?t:`unknown`}function nl(e){let t=el(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=el(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&Qc.test(n)?n:void 0,i=el(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&$c.test(i)?i:void 0;return{callerType:`agent`,callerName:tl(el(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function rl(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function il(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function al(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=il(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let Y;function ol(){return Y||(process.env.NODE_ENV===`development`?(Y=`dev`,Y):process.env.BAILIAN_COMPILED===`1`?(Y=`prod`,Y):(Y=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,Y))}var sl=/* @__PURE__ */ je(((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=Pe(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Pe(`dns`)},function(e,t){e.exports=Pe(`util`)},function(e,t){e.exports=Pe(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},se=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},O=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map;k.set(`Baiduspider-render`,i),k.set(`Baiduspider+`,i),k.set(`Baiduspider-image+`,i),k.set(`360Spider`,a),k.set(`360Spider-Image`,a),k.set(`bingbot`,o),k.set(`Googlebot`,s),k.set(`YandexRenderResourcesBot`,c),k.set(`spider`,l),k.set(`Dataprovider.com`,u),k.set(`AhrefsBot`,d),k.set(`BitSightBot`,f),k.set(`oBot`,p),k.set(`Cincraw`,m),k.set(`DingTalkBot-LinkService`,h),k.set(`YisouSpider`,g),k.set(`Bytespider`,_),k.set(`ev-crawler`,v),k.set(`bitdiscovery`,y),k.set(`Spider`,b),k.set(`Ai2Bot-Dolma`,ee),k.set(`dianjing_ad_spider`,te),A.set(`Baiduspider-render`,ne),A.set(`Baiduspider+`,ne),A.set(`Baiduspider-image+`,ne),A.set(`360Spider`,re),A.set(`360Spider-Image`,re),A.set(`bingbot`,ie),A.set(`Googlebot`,x),A.set(`YandexRenderResourcesBot`,ae),A.set(`spider`,oe),A.set(`Dataprovider.com`,se),A.set(`AhrefsBot`,ce),A.set(`BitSightBot`,le),A.set(`oBot`,S),A.set(`Cincraw`,C),A.set(`DingTalkBot-LinkService`,w),A.set(`YisouSpider`,T),A.set(`Bytespider`,E),A.set(`ev-crawler`,ue),A.set(`bitdiscovery`,de),A.set(`Spider`,D),A.set(`Ai2Bot-Dolma`,O),A.set(`dianjing_ad_spider`,fe);let pe={productHandlerMap:k,commentHandlerMap:A,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,pe),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=/* @__PURE__ */ 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:(/* @__PURE__ */ 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||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),re=n(5),ie=n.n(re);function x(e){return(x=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 ae(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 oe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ae(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=(function(e){var t=(function(e,t){if(x(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(x(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return x(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ce(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=S(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.
27
- 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 le(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)||S(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
28
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function S(e,t){if(e){if(typeof e==`string`)return C(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)?C(e,t):void 0}}function C(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 w(){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=le(r[n],2),o=(a[0],a[1]);if(o){var s,c=ce(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 T,E,ue=(T=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:T,device_id:ie.a.createHash(`md5`).update(w()).digest(`hex`),platform:`node`}),de=(0,ne.promisify)(te.a.resolve);function D(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,oe(oe({},ue),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}D.prototype=((E=function(){}).prototype=b.prototype,new E),D.prototype.constructor=D,D.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,de(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=D}]).default})),cl=/* @__PURE__ */ je(((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})),ll=/* @__PURE__ */ Ne(sl(),1),ul=/* @__PURE__ */ Ne(cl(),1);const dl=()=>g(I(),`telemetry.jsonl`);let fl;const pl=/* @__PURE__ */ new Set;let ml;try{let e=new ll.default({pid:`bailian-cli-node`,env:ol()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;pl.add(e),e.finally(()=>pl.delete(e))}return n},ml=e,fl=e.use(ul.default)}catch{}async function hl(e=1e3){try{if(ml)try{typeof ml._sendAll==`function`&&ml._sendAll()}catch{}if(pl.size===0)return;let t=[...pl].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function gl(e){try{await lt();let n=dl();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
29
- `,{mode:384})}catch{}}async function _l(e){try{if(!fl)return;fl(e.command,al(e))}catch{}}const vl=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),yl=/* @__PURE__ */ new Set(/* @__PURE__ */ `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 bl(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||vl.has(n)||yl.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function xl(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof P?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=rl({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:bl(n),caller:e.caller});gl(u).catch(()=>{}),_l(u).catch(()=>{})}}function Sl(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 Cl=class{settings;name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await Xi(Ht(this.settings))).map(Sl).filter(e=>e!==null)}};function wl(){return M(I(),`skills/bailian-docs-llm-wiki`)}function Tl(){return M(wl(),`models`,`models.jsonl`)}function El(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 Dl(e){let t=T(e,`utf-8`).split(`
30
- `).filter(Boolean),n=[];for(let e of t)try{let t=El(JSON.parse(e));t&&n.push(t)}catch{}return n}var Ol=class{name=`catalog`;constructor(e){}available(){return S(Tl())}async load(){return this.available()?Dl(Tl()):[]}};async function kl(e,t){let n=[new Ol({onPrepareStart:t?.onPrepareStart}),new Cl(e)];for(let e of n)if(e.available()){let t=await e.load();if(t.length>0)return t}let r=await n[0].load();if(r.length>0)return r;throw new P(`No model data available.`,N.GENERAL)}const Al={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},X={Single:`single`,Pipeline:`pipeline`},jl={Low:`low`,Medium:`medium`,High:`high`},Ml={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Z={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`},Nl={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Pl={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Fl=20,Il=/-\d{4}-\d{2}-\d{2}$/,Ll=/* @__PURE__ */ new Set([Q.IG,Q.VG,Q.TTS,Q.RealtimeTTS,Q.ThreeDGeneration]),Rl=/* @__PURE__ */ new Set([Q.TG,Q.Reasoning,Q.ASR,Q.RealtimeASR,Q.RealtimeAudioTranslate,Q.TR,Q.ME]),zl={standard:0,large:32e3,"extra-large":128e3};console.assert(!0,`FUSION_HARD_WEIGHT + FUSION_SOFT_WEIGHT must sum to 1`),console.assert(!0,`HARD_WEIGHT_* sub-weights must sum to 1`);const Bl=`You are a model recommendation advisor for Alibaba Cloud Model Studio. From the candidate models below, select the best recommendations.
24
+ --service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===Y.POST_PAID?`ptu_default only supports pre_paid.
25
+ ptu_default 仅支持 pre_paid。`:e.chargeType===Y.POST_PAID&&rl(e)?`Prepaid flags are not allowed with --charge-type post_paid.
26
+ --charge-type post_paid 不允许提供预付费参数。`:tl(e,!0)??il(e,e.chargeType===Y.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
27
+ 当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:nl(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=al(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},cl={name:J.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||el,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new N(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,M.USAGE);try{let a=await Jc(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===J.MU)?.templates??[];if(o.length===0)throw i();let s=t===$c.POST_PAY?Y.POST_PAID:Y.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof N?e:new N(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,M.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},ll={[J.LORA]:ol,[J.PTU]:sl,[J.MU]:cl};function ul(e){let t=ll[e];if(!t)throw new N(`Unsupported plan "${e}". Supported plans: ${Object.keys(ll).join(`, `)}.`,M.USAGE);return t}const dl=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,fl=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,pl=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function ml(e,t){return B(await e.console(dl,{input:{modelServiceId:t}}))}async function hl(e,t){return B(await e.console(fl,{input:{modelServiceId:t}}))}async function gl(e){let t=[],n=1;for(;;){let r=B(await e.console(pl,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function _l(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const vl=`speech-biasing`;function yl(e,t){return{model:vl,input:{action:e,...t}}}async function bl(e,t,n,r){return e.requestJson({path:jr(),method:`POST`,body:yl(t,n),signal:r})}function xl(e,t,n){return bl(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function Sl(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),bl(e,`list_vocabulary`,r,n)}function Cl(e,t,n){return bl(e,`query_vocabulary`,{vocabulary_id:t},n)}function wl(e,t,n,r){return bl(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function Tl(e,t,n){return bl(e,`delete_vocabulary`,{vocabulary_id:t},n)}function El(e,t){try{return JSON.parse(e)}catch(e){throw new P(`${t} is not valid JSON — ${e.message}`)}}function Dl(e){let t=El(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new P(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new P(`--vocabulary weight for "${e}" must be a number.`);return t}function Ol(e,t){let n=`--words`,r=El(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new P(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new P(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new P(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new P(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new P(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new P(`${n} must contain at least one hot word.`);return i}const kl={introspect:{type:`switch`,description:{"en-US":`Print the machine-readable command schema (JSON) and exit`,"zh-CN":`输出机器可读的命令说明(JSON)并退出`}},output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},Al={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},jl={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},Ml={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},Nl={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Pl={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function Fl(e){return e.auth===`apiKey`?Ml:e.auth===`console`?Nl:e.auth===`openapi`?Pl:{}}function Il(e){return e}const Ll=1;function Rl(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function zl(e,t){return`${Rl(e||`image`,`image`)}_${Rl((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function Bl(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return Vl(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function Vl(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const Hl=()=>g(f(),`bailian-output`);function Ul(e,t){let n=t?.flagDir||e.outputDir||Hl(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Wl(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Gl(e){return o(e===`-`?0:e,`utf-8`)}async function Kl(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function ql(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 Jl(e,t=`boolean`){if(e!=null)return ql(e,t)}function Yl(e,t,n=`boolean`){let r=Jl(e,n);return r===void 0?t:r}function Xl(e,t){return Jl(e,`watermark`)??t??!0}const Zl=/^[a-z0-9][a-z0-9.-]{0,63}$/,Ql=/^bailian-[a-z0-9-]{1,64}$/,$l=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function eu(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function tu(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return Zl.test(t)?t:`unknown`}function nu(e){let t=eu(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=eu(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&Ql.test(n)?n:void 0,i=eu(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&$l.test(i)?i:void 0;return{callerType:`agent`,callerName:tu(eu(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function ru(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function iu(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function au(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=iu(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let ou;function su(){return ou||(process.env.NODE_ENV===`development`?(ou=`dev`,ou):process.env.BAILIAN_COMPILED===`1`?(ou=`prod`,ou):(ou=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,ou))}var cu=/* @__PURE__ */ Ge(((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=Je(`os`)},function(e,t){e.exports=(...e)=>(process.versions.bun?globalThis.fetch:Je(`undici`).fetch)(...e)},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Je(`dns`)},function(e,t){e.exports=Je(`util`)},function(e,t){e.exports=Je(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},se=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},pe=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map;D.set(`Baiduspider-render`,i),D.set(`Baiduspider+`,i),D.set(`Baiduspider-image+`,i),D.set(`360Spider`,a),D.set(`360Spider-Image`,a),D.set(`bingbot`,o),D.set(`Googlebot`,s),D.set(`YandexRenderResourcesBot`,c),D.set(`spider`,l),D.set(`Dataprovider.com`,u),D.set(`AhrefsBot`,d),D.set(`BitSightBot`,f),D.set(`oBot`,p),D.set(`Cincraw`,m),D.set(`DingTalkBot-LinkService`,h),D.set(`YisouSpider`,g),D.set(`Bytespider`,_),D.set(`ev-crawler`,v),D.set(`bitdiscovery`,y),D.set(`Spider`,b),D.set(`Ai2Bot-Dolma`,ee),D.set(`dianjing_ad_spider`,te),O.set(`Baiduspider-render`,ne),O.set(`Baiduspider+`,ne),O.set(`Baiduspider-image+`,ne),O.set(`360Spider`,re),O.set(`360Spider-Image`,re),O.set(`bingbot`,ie),O.set(`Googlebot`,ae),O.set(`YandexRenderResourcesBot`,oe),O.set(`spider`,x),O.set(`Dataprovider.com`,se),O.set(`AhrefsBot`,ce),O.set(`BitSightBot`,le),O.set(`oBot`,ue),O.set(`Cincraw`,de),O.set(`DingTalkBot-LinkService`,fe),O.set(`YisouSpider`,S),O.set(`Bytespider`,C),O.set(`ev-crawler`,w),O.set(`bitdiscovery`,T),O.set(`Spider`,E),O.set(`Ai2Bot-Dolma`,pe),O.set(`dianjing_ad_spider`,me);let he={productHandlerMap:D,commentHandlerMap:O,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,he),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=/* @__PURE__ */ 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:(/* @__PURE__ */ 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||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),re=n(5),ie=n.n(re);function ae(e){return(ae=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function oe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function x(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oe(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=(function(e){var t=(function(e,t){if(ae(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ae(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return ae(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ce(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=ue(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.
28
+ 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 le(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)||ue(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
29
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function ue(e,t){if(e){if(typeof e==`string`)return de(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)?de(e,t):void 0}}function de(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 fe(){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=le(r[n],2),o=(a[0],a[1]);if(o){var s,c=ce(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 S,C,w=(S=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:S,device_id:ie.a.createHash(`md5`).update(fe()).digest(`hex`),platform:`node`}),T=(0,ne.promisify)(te.a.resolve);function E(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,x(x({},w),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}E.prototype=((C=function(){}).prototype=b.prototype,new C),E.prototype.constructor=E,E.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,T(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=E}]).default})),lu=/* @__PURE__ */ Ge(((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})),uu=/* @__PURE__ */ qe(cu(),1),du=/* @__PURE__ */ qe(lu(),1);const fu=()=>g(I(),`telemetry.jsonl`);let pu;const mu=/* @__PURE__ */ new Set;let hu;try{let e=new uu.default({pid:`bailian-cli-node`,env:su()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;mu.add(e),e.finally(()=>mu.delete(e))}return n},hu=e,pu=e.use(du.default)}catch{}async function gu(e=1e3){try{if(hu)try{typeof hu._sendAll==`function`&&hu._sendAll()}catch{}if(mu.size===0)return;let t=[...mu].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function _u(e){try{await St();let n=fu();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
30
+ `,{mode:384})}catch{}}async function vu(e){try{if(!pu)return;pu(e.command,au(e))}catch{}}const yu=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),bu=/* @__PURE__ */ new Set(/* @__PURE__ */ `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 xu(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||yu.has(n)||bu.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function Su(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof N?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=ru({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:xu(n),caller:e.caller});_u(u).catch(()=>{}),vu(u).catch(()=>{})}}const Cu=/* @__PURE__ */ `代码生成.创意写作.客服对话.知识问答.文档理解.数据分析.数学推理.翻译.图像生成.图像编辑.视频生成.视频编辑.语音合成.语音识别.实时对话.Agent编排.深度研究.教育辅导.电商营销.角色扮演.3D生成.向量检索.数字人.音乐生成.人脸人像.虚拟试穿.OCR文字识别.情感分析.意图识别.图像修复.语义重排.播客.有声书`.split(`.`),wu=`You are an intent analyzer for an AI model recommendation system. Given the user's requirement, understand the scenario first, then extract structured information.
31
31
 
32
- 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.
33
-
34
- ## Background
35
- The system has pre-filtered candidate models based on intent analysis. Your job is to rank and pick from these candidates.
36
- The intent includes budget and qualityPreference fields representing the user's actual needs.
37
-
38
- ## Recommendation Strategy
39
-
40
- Recommend 3 models at different tiers, but ordering must reflect the user's true needs:
41
-
42
- - #1 (Best Pick): Based on budget and qualityPreference, pick the best-fitting tier and put its top model first
43
- - #2 (Runner-Up): A worthy consideration from another tier, explaining tradeoffs vs #1
44
- - #3 (Alternative): A third-perspective choice, explaining scenario differences
45
-
46
- Key principles:
47
- - budget:"low" / qualityPreference:"cost-optimized" → #1 should be the best value model, not a flagship
48
- - budget:"high" / qualityPreference:"flagship" → #1 should be the most capable flagship model
49
- - budget:"medium" / qualityPreference:"balanced" → #1 should be the best all-around match
50
-
51
- Each recommendation must explain why the model fits (or as an alternative, why it's worth considering), with reasoning tied to the user's specific needs.
52
-
53
- ## Rules
54
- - Only recommend models from the candidate list — never recommend outside it
55
- - No generic reasons ("powerful", "good performance", "effective"). Each reason must describe how the model solves a specific aspect of the user's task
56
- - All three recommendations must have distinct reasoning angles, not duplicate reasons
57
- - When pricing is available: factor in budget, put the most budget-friendly option first
58
- - When family info is available: avoid recommending multiple models from the same family, prefer stable versions
59
- - When version tags are available: prefer stable/latest versions unless the user explicitly needs a specific version
60
- - Models without enriched fields: rank by capability and description — don't penalize for missing info
61
- - If no model fits, return an empty array
62
- - If you believe the task actually requires multi-model collaboration (pipeline), you may output type:"pipeline" format
63
- - Output strict JSON, no other text
64
-
65
- ## Output Format
66
-
67
- Single task:
68
- {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":["key highlights"]}]}
69
-
70
- Pipeline (only when confident multi-model is needed):
71
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"step description","recommendations":[{"model":"model ID","reason":"reason for choosing","highlights":["highlights"]}]}]}`,Vl=`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.
72
-
73
- 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.
74
-
75
- ## Background
76
- The system has pre-filtered candidate models for each step's requirements.
77
- The intent includes budget and qualityPreference fields representing the user's actual needs.
78
-
79
- ## Recommendation Strategy
80
-
81
- Recommend 3 models at different tiers per step, ordering by user needs:
82
-
83
- - #1 (Best Pick): Based on budget and qualityPreference, pick the best-fitting tier and put its top model first
84
- - #2 (Runner-Up): A worthy consideration from another tier, explaining tradeoffs
85
- - #3 (Alternative): A third-perspective choice
86
-
87
- Key principles:
88
- - budget:"low" / qualityPreference:"cost-optimized" → #1 should be the best value model
89
- - budget:"high" / qualityPreference:"flagship" → #1 should be the most capable flagship model
90
- - budget:"medium" / qualityPreference:"balanced" → #1 should be the best all-around match
91
-
92
- ## Rules
93
- - Only recommend models from the candidate list
94
- - Each step recommends multiple models sorted by priority, each with brief reason and key highlights
95
- - The "step" field must describe the specific problem this step solves in the user's task — no numbered or generic modal labels (e.g. "Output: Text")
96
- - No generic reasons. Each reason must describe how the model solves a specific aspect of the user's task at this step
97
- - When pricing is available: factor in budget, put the most budget-friendly option first
98
- - When family info is available: avoid using different tiers of the same family in adjacent steps unless truly needed
99
- - Models without enriched fields: rank by capability and description — don't penalize for missing info
100
- - Adjacent steps must be modality-compatible: the previous step's output modalities must be supported as input modalities by the next step
101
- - If you believe the task can be done with a single model, output type:"single" format
102
- - Output strict JSON
103
-
104
- ## Output Format
105
-
106
- {"type":"pipeline","summary":"one-line solution description","steps":[{"step":"specific problem this step solves in the user's task","recommendations":[{"model":"model ID","reason":"how this model solves the specific problem at this step","highlights":["highlights"]}]}]}
107
-
108
- Or (if single model suffices):
109
- {"type":"single","recommendations":[{"model":"model ID","reason":"recommendation reason","highlights":
110
- ["key highlights"]}]}`,Hl={complexity:X.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:[],outputModality:[],requiredCapabilities:[Q.TG],requiredFeatures:[],budget:jl.Medium,contextNeed:Ml.Standard,qualityPreference:Z.Balanced,confidence:0},Ul=[`unconstrained`,`scoped`,`comparison`,`alternative`];function Wl(e){if(!e||typeof e!=`object`)return;let t=typeof e.mode==`string`&&Ul.includes(e.mode)?e.mode:`unconstrained`,n=Array.isArray(e.targets)?e.targets.filter(e=>typeof e==`string`):[],r=Array.isArray(e.excludes)?e.excludes.filter(e=>typeof e==`string`):[];return{mode:t,targets:n.length>0?n:void 0,excludes:r.length>0?r:void 0}}async function Gl(e,t){let n=Bn(),r={model:`qwen3.6-flash`,messages:[{role:`system`,content:`You are an intent analyzer. Given the user's requirement, understand the scenario first, then extract structured information.
111
-
112
- 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.
32
+ CRITICAL: Respond with ONLY a valid JSON object. taskSummary must be in English; segments[].step is a short Simplified Chinese label (e.g. "剧本创作", "图生视频").
113
33
 
114
34
  ## Analysis Steps
115
- 1. Summarize the user's core need in one sentence (taskSummary) — be specific about the scenario, not generic
116
- 2. Infer scenario hints (scenarioHints), e.g.: ["low-latency", "consumer-facing", "high-concurrency", "conversational", "offline-batch", "high-precision"]
117
- 3. Infer budget and qualityPreference from scenario hints
118
- - Only deviate from defaults when the user explicitly states or the scenario strongly implies
119
- - User says "low cost", "cheap", "save money" → budget:"low"
120
- - User says "best", "high precision", "cost no object" → qualityPreference:"flagship"
121
- - Infer from scenario constraints only when strong: e.g. "1M requests/day customer service" → budget:"low" (high concurrency = cost-sensitive)
122
- - Otherwise keep budget:"medium", qualityPreference:"balanced"
123
- 4. Extract modalities, capabilities, features etc.
35
+ 1. Identify the FINAL DELIVERABLE the user wants (a finished video? a script? a transcript?) and summarize the need in one sentence (taskSummary) — be specific, not generic. Do not narrow the deliverable: "做一个AI短剧" means a finished short-drama video, NOT just a script
36
+ 2. Decide complexity (single vs pipeline) — see "Complexity detection"
37
+ 3. Infer scenario hints (scenarioHints), e.g.: ["low-latency", "consumer-facing", "high-concurrency"]
38
+ 4. Infer budget and qualityPreference. DEFAULT qualityPreference is "flagship": when the user expresses no price or performance preference, assume they want the strongest model.
39
+ - "low cost", "cheap", "便宜", "便宜点", "便宜一点", "经济实惠" → budget:"low" AND qualityPreference:"cost-optimized" (a budget preference, NOT optimizeDimension)
40
+ - "小模型" / "轻量" / "够用就行" / "不追求性能" → qualityPreference:"cost-optimized"
41
+ - Explicit middle ground ("中档", "均衡", "性价比适中", "不用最贵也不用最便宜") → qualityPreference:"balanced"
42
+ - "best", "high precision", "最好", "最强" → qualityPreference:"flagship"
43
+ - Otherwise keep budget:"medium"
44
+ 5. Extract modalities and capability codes
45
+
46
+ ## Complexity detection
47
+ - complexity:"pipeline" when the final deliverable needs TWO OR MORE different capabilities chained together (one step's output feeds the next) and no single model produces the whole deliverable. Typical signals: producing a finished multimedia work (短剧, MV, 宣传片, 带配音/字幕的视频, 有声绘本) or a convert-then-process flow
48
+ - complexity:"single" when ONE capability delivers the result, even if the task is creative or large. Do NOT split a single-capability task into artificial steps
49
+ - When the deliverable maps directly to one scene label (e.g. 数字人, 播客, 有声书, 虚拟试穿), keep "single" with that scene, and set requiredCapabilities to that scene's ONE core capability only (数字人/播客/有声书 → ["TTS"]; 虚拟试穿/人脸人像 → ["IG"]). Do not add supporting capabilities like TG or realtime codes — the scene label already carries the rest
50
+ - Examples:
51
+ - "做一个AI短剧" → pipeline: script (Text→Text, TG) → character/storyboard images (Text→Image, IG) → video clips (Image→Video, VG) → voice-over (Text→Audio, TTS)
52
+ - "根据天气预报制作MV" → pipeline: lyrics/script (Text→Text, TG) → music video (Text→Video, VG)
53
+ - "把会议录音转成文字并整理成纪要" → pipeline: transcription (Audio→Text, ASR) → minutes (Text→Text, TG)
54
+ - "帮我写一个短剧剧本" → single (Text→Text, TG, 创意写作)
55
+ - "用商品图生成一段展示视频" → single (Image→Video, VG)
56
+ - "做个电商商品主图" → single (Text→Image, IG)
57
+ - "做一个数字人直播" → single (scene 数字人)
58
+ - Pipeline output rules:
59
+ - segments: 2-4 ordered steps; each step uses ONE primary capability; each step's inputModality must be the user's original input or a previous step's output (a valid modality chain)
60
+ - each step has a short Chinese "step" label and a "scene": the ONE scene label (from the scene list below) that best describes that step, or null. Distinguish retrieval steps: 向量检索 for embedding, 语义重排 for reranking
61
+ - each step's modalities must match its capability: TG Text→Text, IG →Image, VG →Video, TTS Text→Audio, ASR Audio→Text. Final assembly (剪辑, 合成, 配音合轨, 加字幕) is NOT a model step — omit it
62
+ - top-level inputModality = first step's input; outputModality = final deliverable's modality; requiredCapabilities = union of step capabilities; matchedScenes = scenes of the core steps (e.g. 视频生成, 语音合成), max 3, no loosely related scenes
63
+ - For single tasks, OMIT segments
64
+
65
+ ## Generic requests and deployment constraints
66
+ - When the user names NO concrete task (only asks for "小模型", "轻量模型", "端侧能用的模型", etc.), DO NOT enumerate scenes or capabilities: matchedScenes:[], sceneConfidence ≤ 0.3, requiredCapabilities:["TG"] unless a modality is explicitly mentioned
67
+ - Deployment constraints (端侧/终端/edge, 离线/offline, 本地/local, ONNX, 私有化部署, 不依赖云端) go into scenarioHints ONLY — they are not scenes or capabilities
68
+ - "小模型" / "轻量" → qualityPreference:"cost-optimized" (this is NOT optimizeDimension)
69
+ - Example: "是否有一些小模型推荐可用于终端推理,不依赖云端" → complexity:"single", requiredCapabilities:["TG"], matchedScenes:[], sceneConfidence:0.2, scenarioHints:["on-device","offline","no-cloud-dependency"], qualityPreference:"cost-optimized", cardinalityHint:null, optimizeDimension:null
70
+ - Hard limits: matchedScenes ≤ 3; for single tasks requiredCapabilities ≤ 2
71
+
72
+ ## Capability codes
73
+ Pick ONLY the capabilities actually needed (at most 2 for a single task — choose the core ones). Use ONLY the codes listed below; never invent new codes (e.g. "Digital-Human" is invalid — express that via the scene label 数字人):
74
+ - TG: text generation (chat, writing, coding, translation, summarization)
75
+ - Reasoning: deep step-by-step thinking — only for math, logic, complex analysis, or explicit "深度思考"; never add it for ordinary writing/chat
76
+ - VU: visual understanding (image/video in → text out)
77
+ - IG: image generation / editing
78
+ - VG: video generation / editing (text/image/video → video)
79
+ - TTS: speech synthesis (text → audio)
80
+ - ASR: speech recognition from audio files (audio → text)
81
+ - Realtime-ASR: streaming speech recognition
82
+ - Realtime-Text-to-Speech: streaming speech synthesis
83
+ - Realtime-Audio-Translate: real-time spoken translation / simultaneous interpretation
84
+ - Realtime-Chatting: real-time spoken conversation
85
+ - Realtime-Omni: real-time omni-modal interaction (audio/video in, speech out)
86
+ - Multimodal-Omni: non-realtime omni-modal understanding + generation
87
+ - ME: multimodal embedding — only when images/videos themselves are embedded or searched; text documents use TR
88
+ - TR: text embedding & rerank — ONLY for retrieval/search/RAG/semantic ranking; NEVER for writing, chat, translation or "text" tasks in general
89
+ - 3D-generation: 3D model generation
90
+
91
+ ## Scene mapping
92
+ Map the user's need to ONE OR MORE of these ${Cu.length} scenes (use exact Chinese labels):
93
+ ${Cu.join(`, `)}
94
+
95
+ - matchedScenes: array of matched scene labels (max 3, ordered by relevance); [] if none match
96
+ - sceneConfidence: 0.0-1.0 (1.0 = exact match, 0.5 = inferred, 0.0 = no match)
124
97
 
125
98
  ## Model preference detection
126
- Analyze whether the user mentioned specific models, model families, or vendors:
127
- - No models/families/vendors mentioned → mode:"unconstrained", no targets
128
- - User scoped the range (e.g. "recommend from the deepseek family", "open-source reasoning models") → mode:"scoped", targets:["deepseek"]
129
- - User wants to compare specific models (e.g. "compare wan2.6 and wan2.7", "is qwen-max good for legal analysis") → mode:"comparison", targets:["wan2.6","wan2.7"]
130
- - Single model evaluation is also comparison with one target
131
- - User wants alternatives to a reference model (e.g. "something like qwen-max but cheaper") → mode:"alternative", targets:["qwen-max"]
132
- - User explicitly excludes certain models/families (e.g. "good models besides qwen") → excludes:["qwen"], mode determined by other signals
133
- - targets should capture the model/family names as the user wrote them
99
+ - No models/families/vendors mentioned → mode:"unconstrained"
100
+ - Scoped range ("deepseek 家族里推荐") → mode:"scoped", targets:["deepseek"]
101
+ - Compare specific models ("对比 A 和 B", "A 适合做 X 吗") → mode:"comparison", targets:[...]
102
+ - Single model evaluation is comparison with one target
103
+ - Alternatives to a reference ("比 A 更便宜的", "A 的替代品") → mode:"alternative", targets:["A"]. "alternative" REQUIRES a reference model the user wants to beat or replace; exclusion alone never makes it "alternative"
104
+ - Explicit exclusion ("除了 qwen", "不要 qwen3.8", "排除 X 系列") → excludes:[...]. This is MANDATORY: whenever the user excludes any model/family/vendor, always populate excludes — even when mode stays "unconstrained"
105
+ - targets/excludes capture the core name the user wrote, stripping modifiers like "系列"/"家族" (e.g. "除了qwen3.8系列" → excludes:["qwen3.8"])
106
+ - Example: "除了qwen3.8系列,推荐个写营销文案的模型" → mode:"unconstrained", excludes:["qwen3.8"] (no targets)
107
+
108
+ ## Cardinality detection
109
+ - "最便宜的" / "哪个最好" (single extreme with superlative) → cardinalityHint:"one". Note: "推荐一个", "给我一个" are quantity words, NOT cardinality triggers — do not set "one" for them
110
+ - Explicit enumeration requests only — "都有哪些" / "列一下" / "列出所有" / "全部模型" → cardinalityHint:"many"
111
+ - Otherwise cardinalityHint MUST be null (the default for the vast majority of requests). These are NOT "many": "用什么模型", "推荐个…", "有没有…推荐", "是否有一些…". These are NOT "one" either: "帮我推荐个写代码的模型", "帮我写一个剧本" ("一个/个" is a quantity word for the task, not a request for a single extreme)
112
+
113
+ ## Optimize dimension
114
+ Set optimizeDimension ONLY when the user explicitly writes a single-dimension superlative
115
+ ("最便宜"/"最快"/"上下文最长"/"最强"/"效果最好"). "便宜点"/"便宜一点"/"cheap" is a budget preference (budget:"low"), NOT optimizeDimension:"price". Never infer optimizeDimension from the task type or from mild words like "好"/"合适"/"专业"/"便宜点". Otherwise optimizeDimension MUST be null.
134
116
 
135
117
  ## Output fields
136
- - taskSummary: one-sentence scenario understanding (must be specific, never generic like "user wants AI")
137
- - scenarioHints: array of inferred scenario features
138
- - complexity: "single" or "pipeline"
139
- - segments: only for pipeline, each with step/inputModality/outputModality/requiredCapabilities
140
- - step must describe the specific problem this step solves in the user's task, no numbered or generic modal labels
141
- - segments must form a modality chain: each step's inputModality should cover the previous step's outputModality
142
- - inputModality: user input modalities ["Text","Image","Video","Audio"]
143
- - outputModality: expected output modalities
144
- - requiredCapabilities: capability codes (use strictly from the list, don't invent):
145
- TG=Text Generation, Reasoning=Reasoning, VU=Vision Understanding, IG=Image Generation, VG=Video Generation,
146
- TTS=Text-to-Speech, ASR=Speech-to-Text, Realtime-ASR=Realtime Speech-to-Text,
147
- Realtime-Text-to-Speech=Realtime Text-to-Speech, Realtime-Audio-Translate=Realtime Audio Translation,
148
- Realtime-Omni=Realtime Omni-modal, Multimodal-Omni=Multimodal Omni, ME=Multimodal Embedding,
149
- TR=Translation, 3D-generation=3D Generation
150
- - requiredFeatures: required features (function-calling, web-search, structured-outputs, prefix-completion)
151
- - budget: "low"/"medium"/"high"
152
- - contextNeed: "standard"/"large"/"extra-large"
153
- - qualityPreference: "flagship"/"balanced"/"cost-optimized"
154
- - 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
155
- - modelPreference: { mode, targets?, excludes? }
156
-
157
- Output only JSON, no other text.`},{role:`user`,content:t}],max_tokens:1024,temperature:0},i;try{i=await e.requestJson({path:n,method:`POST`,body:r,timeout:30})}catch{return{...Hl}}let a=(i.choices?.[0]?.message?.content??``).match(/\{[\s\S]*\}/);if(!a)return{...Hl};let o=JSON.parse(a[0]),s=o.modelPreference,c=Wl(s);return{complexity:o.complexity===X.Pipeline?X.Pipeline:X.Single,taskSummary:typeof o.taskSummary==`string`?o.taskSummary:``,scenarioHints:Array.isArray(o.scenarioHints)?o.scenarioHints:[],semanticQuery:typeof o.semanticQuery==`string`?o.semanticQuery:``,segments:Array.isArray(o.segments)?o.segments.map(e=>({step:e.step??``,inputModality:Array.isArray(e.inputModality)?e.inputModality:[],outputModality:Array.isArray(e.outputModality)?e.outputModality:[],requiredCapabilities:Array.isArray(e.requiredCapabilities)?e.requiredCapabilities:[]})):void 0,inputModality:Array.isArray(o.inputModality)?o.inputModality:[],outputModality:Array.isArray(o.outputModality)?o.outputModality:[],requiredCapabilities:Array.isArray(o.requiredCapabilities)?o.requiredCapabilities:[],requiredFeatures:Array.isArray(o.requiredFeatures)?o.requiredFeatures:[],budget:o.budget??Hl.budget,contextNeed:o.contextNeed??Hl.contextNeed,qualityPreference:o.qualityPreference??Hl.qualityPreference,confidence:1,modelPreference:c}}function Kl(e){let t=!1,n=!1;for(let r of e)Ll.has(r)&&(t=!0),Rl.has(r)&&(n=!0);return t&&n}function ql(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(Il,``);return n===e||!t.has(n)})}function Jl(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 Yl(e,t){if(t.length===0)return!0;let n=e.inferenceMetadata?.request_modality??[];return t.some(e=>n.includes(e))}function Xl(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=zl[i];return d>0&&(c??0)>=d&&(u+=8),a===Z.Flagship&&l===Pl.Flagship||a===Z.CostOptimized&&l===Pl.CostOptimized?u+=15:a===Z.Balanced&&l===Pl.Flagship&&(u+=5),u}function Zl(e,t,n){return e.map(e=>({model:e,score:Xl(e,t)})).sort((e,t)=>t.score-e.score).slice(0,n)}function Ql(e){return new Set(e.map(({model:e})=>e.model))}function $l(e,t){let n=/* @__PURE__ */ 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 eu(e,t){let n=new Set(t);return e.filter(e=>!n.has(e.model.model)&&(n.add(e.model.model),!0))}function tu(e,t,n){return n.size>=10?[]:Zl(e.filter(({model:e})=>!n.has(e)),t,10-n.size)}function nu(e,t,n,r,i){let{inputModality:a,outputModality:o,requiredCapabilities:s}=t,c={complexity:X.Single,taskSummary:``,scenarioHints:[],semanticQuery:``,inputModality:a,outputModality:o,requiredCapabilities:s,requiredFeatures:[],budget:r,contextNeed:Ml.Standard,qualityPreference:i,confidence:1},l=e.filter(e=>Jl(e,a,o)&&Yl(e,n));return l.length<5&&(l=e.filter(e=>Jl(e,a,o))),l.length<5&&(l=e),Zl(l,c,5)}function ru(e,t){e=ql(e);let n;if(t.complexity===X.Pipeline&&t.segments?.length){let r=[];for(let[n,i]of t.segments.entries()){let a=n===0?[]:t.segments[n-1].outputModality,o=eu(nu(e,i,a,t.budget,t.qualityPreference),Ql(r));r=[...r,...o]}let i=tu(e,t,Ql(r));n=[...r,...i]}else if(Kl(t.requiredCapabilities))n=iu(e,t);else{let r=e.filter(e=>Jl(e,t.inputModality,t.outputModality));r.length<5&&(r=e),n=Zl(r,t,50)}return $l(n,3)}function iu(e,t){let n=t.requiredCapabilities.filter(e=>Ll.has(e)),r=t.requiredCapabilities.filter(e=>Rl.has(e)),i=[];if(n.length>0&&(i=Zl(e.filter(e=>n.some(t=>e.capabilities.includes(t))),t,25)),r.length>0){let n=Ql(i),a={...t,requiredCapabilities:r},o=e.filter(e=>!n.has(e.model)&&r.some(t=>e.capabilities.includes(t)));i=[...i,...Zl(o,a,25)]}let a=tu(e,t,Ql(i));return[...i,...a]}const au=`text-embedding-v4`;function ou(){return M(I(),`skills/bailian-docs-llm-wiki`)}function su(){return M(ou(),`models-embeddings.json`)}function cu(){let e=su();if(!S(e))return null;try{return JSON.parse(T(e,`utf-8`)).items}catch{return null}}async function lu(e,t){let n={model:au,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 uu(e,t){let n={model:au,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 du={TG:`Text Generation`,Reasoning:`Reasoning`,VU:`Vision Understanding`,IG:`Image Generation`,VG:`Video Generation`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`},fu={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`};function pu(){let e=M(ou(),`groups`),t=/* @__PURE__ */ new Map;if(!S(e))return t;for(let n of E(e).filter(e=>e.endsWith(`.json`)))try{let r=JSON.parse(T(M(e,n),`utf-8`)),i=r.description??``;if(r.items)for(let e of r.items)t.set(e.model,e.description||i)}catch{}return t}function mu(e,t){let n=(e.capabilities??[]).map(e=>du[e]??e).join(`, `),r=t.get(e.model)||e.shortDescription||e.description||``,i=(e.inferenceMetadata?.request_modality??[]).map(e=>fu[e]??e).join(`, `),a=(e.inferenceMetadata?.response_modality??[]).map(e=>fu[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 hu(e,t){let n=pu(),r=t.map(e=>mu(e,n)),i=[];for(let t=0;t<r.length;t+=10){let n=await uu(e,r.slice(t,t+10));i.push(...n)}let a=t.map((e,t)=>({id:e.model,vector:i[t]})),o={model:au,dimensions:512,count:a.length,items:a},s=su();return w(j(s),{recursive:!0}),A(s,JSON.stringify(o)),a}function gu(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 _u=null;function vu(){return _u===null&&(_u=cu()),_u}function yu(){return vu()!==null}function bu(e){return(e??``).toLowerCase().replace(Il,``).replace(/[\s_-]+/g,``).trim()}function xu(e,t){let n=bu(t);if(!n)return!1;if(bu(e.model)===n||bu(e.name)===n)return!0;let r=e.model,i=r.lastIndexOf(`/`);return i>=0&&bu(r.slice(i+1))===n||[e.family,e.familyName].some(e=>{if(!e)return!1;let t=bu(e);return t.length>0&&n.includes(t)})}function Su(e,t){return t.some(t=>xu(e,t))}function Cu(e,t){return t.length===0?[]:e.filter(e=>Su(e,t))}function wu(e,t){return t.length===0?e:e.filter(({model:e})=>!Su(e,t))}function Tu(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 Eu(e,t){return Tu(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Du(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=zl[i]??0;if(l>0){let t=e.contextWindow??0;c=t>=l?1:t/l}let u=1;return a===Z.Flagship?u=e.category===Pl.Flagship?1:.5:a===Z.CostOptimized&&(u=e.category===Pl.CostOptimized?1:.5),.4*o+.2*s+.2*c+.2*u}function Ou(e,t){if(!t)return new Set(e.map(e=>e.model));let n=e.filter(e=>Eu(e,t)),r=n.length>=5?n:e;return new Set(r.map(e=>e.model))}function ku(e,t){return Tu(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Au(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=gu(t,e.vector),o=a?Du(n,a):0;return[{model:n,score:a?.4*o+.6*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 ju(e){return{model:e,score:1,hardScore:1,softScore:1}}function Mu(e,t,n,r,i,a,o){let s=r.targets??[],c=s.length>0?Cu(e,s):e,l=[];if(c.length<5&&s.length>0){for(let e of c)l.push(ju(e));let r=new Set(l.map(({model:e})=>e.model)),s=Au(t,n,Ou(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 Au(t,n,Ou(c,o),i,a,o)}function Nu(e,t,n,r,i,a,o){let s=r.targets??[],c=[],l=/* @__PURE__ */ new Set;for(let t of e)Su(t,s)&&!l.has(t.model)&&(c.push(ju(t)),l.add(t.model));return c}function Pu(e,t,n,r,i,a,o){let s=Cu(e,r.targets??[]),c=new Set(s.map(e=>e.family).filter(Boolean)),l=[],u=/* @__PURE__ */ new Set;for(let e of s)l.push(ju(e)),u.add(e.model);let d=Math.max(0,i-l.length);if(d>0){let r=Au(t,n,Ou(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 Fu(e,t,n,r,i){let a=vu();if(!a)a=await hu(e,t),_u=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 hu(e,t),_u=a)}let o=await lu(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=Mu(t,a,o,c,r,s,i);break;case`comparison`:e=Nu(t,a,o,c,r,s,i);break;case`alternative`:e=Pu(t,a,o,c,r,s,i);break;default:e=[]}return wu(e,l)}if(i?.complexity===X.Pipeline&&i.segments?.length){let e=/* @__PURE__ */ new Set,n=[],c=Math.max(5,Math.ceil(r/i.segments.length));for(let r of i.segments){let l=t.filter(e=>ku(e,r)),u=new Set(l.filter(t=>!e.has(t.model)).map(e=>e.model));if(u.size===0)continue;let d=Au(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 wu(n,l)}let u=Ou(t,i);return wu(Au(a,o,u,r,s,i),l)}function Iu(e){if(e.prices?.length)return e.prices.map(e=>`${e.type}:${e.price}/${e.unit}`).join(`, `)}function Lu(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=Iu(e);return r&&t.push(`Pricing: ${r}`),e.family&&t.push(`Family: ${e.family}`),t.join(` | `)}).join(`
158
- `)}function Ru(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!==Ml.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(`
159
- `)}function zu(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 Bu(e,t,n){let r=Array.isArray(e)?e:[],i=[],a=/* @__PURE__ */ 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 Vu(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 Hu(e,t,n,r,i,a){let o=Lu(t),s=Ru(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.
160
-
161
- 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.
162
-
163
- ## Background
164
- The user specified models to compare. The system has pre-filtered these models and related candidates into the list.
165
- The intent's modelPreference.targets are the models to compare.
166
-
167
- ## Comparison Strategy
168
- - All user-specified models must appear in the results, sorted by suitability
169
- - Each model's reason must be comparative: describe strengths and weaknesses relative to other models being compared
170
- - If candidates contain better fits than what the user specified, they can be additionally recommended, but user-specified models take priority
171
- - Single-model evaluation (one target): evaluate if the model fits, and recommend better alternatives
172
-
173
- ## Rules
174
- - Only recommend models from the candidate list
175
- - reason must include comparative perspective: how this model is better/worse compared to others
176
- - highlights should emphasize differentiating characteristics
177
- - Output strict JSON
178
-
179
- ## Output Format
180
- {"type":"single","recommendations":[{"model":"model ID","reason":"comparative analysis","highlights":["differentiators"]}]}`;else if(c===`alternative`)l=`You are a model alternative advisor for Alibaba Cloud Model Studio. The user has a reference model and wants to find alternatives.
181
-
182
- 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.
183
-
184
- ## Background
185
- The user has a reference model and wants to find alternatives that are better in specific dimensions (cheaper, faster, more capable).
186
- The intent's modelPreference.targets is the reference model.
187
-
188
- ## Alternative Strategy
189
- - #1: If the reference model is in candidates, first evaluate if it meets the user's needs — give its positioning
190
- - #2~#3: Recommend alternatives. reason must explain the tradeoff vs the reference model in the user's dimensions of interest
191
- - Focus on the user's stated alternative dimension (e.g. "cheaper" → focus on pricing comparison, "better" → focus on capability comparison)
192
-
193
- ## Rules
194
- - Only recommend models from the candidate list
195
- - The reference model must be included in results if it's in the candidate list
196
- - Alternative recommendations must explain concrete differences from the reference model
197
- - Avoid recommending other versions from the same family unless there's a significant difference
198
- - Output strict JSON
199
-
200
- ## Output Format
201
- {"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===X.Pipeline?Vl:Bl)+e}else l=n.complexity===X.Pipeline?Vl:Bl;let u=a?.enableThinking??!1,d=n.complexity===X.Pipeline?`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models for each pipeline step. Respond in English only.`:`Intent Analysis:\n${s}\n\nCandidate Models:\n${o}\n\nUser Request: ${r}\n\nRecommend up to ${i} models. Respond in English only.`,f={model:`qwen-flash`,messages:[{role:`system`,content:l},{role:`user`,content:d}],max_tokens:4096,temperature:0};u&&(f.stream=!0,f.enable_thinking=!0);let p=Bn(),m;if(u){let t=await e.request({path:p,method:`POST`,body:f,stream:!0}),n=``,r=!1;for await(let e of xn(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:X.Single,recommendations:[]}}let g=new Map(t.map(({model:e})=>[e.model,e]));if(h.type===X.Pipeline&&Array.isArray(h.steps)){let e=[];for(let t of h.steps){let n=Bu(t.recommendations??(t.model?[t]:[]),g,i);n.length>0&&e.push({step:t.step??``,recommendations:n})}return Vu(e,g),{type:X.Pipeline,summary:h.summary??``,steps:e}}let _=Bu(h.recommendations??h??[],g,i);return{type:X.Single,recommendations:_}}function $(){return M(I(),`skills`)}function Uu(){return M($(),`skill-lock.json`)}function Wu(){return{version:1,skills:{}}}function Gu(){let e=Uu();if(!S(e))return Wu();try{let t=JSON.parse(T(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?Wu():t}catch{return Wu()}}function Ku(e){w($(),{recursive:!0}),A(Uu(),JSON.stringify(e,null,2)+`
202
- `)}function qu(e,t){let n=Gu();n.skills[e]={...n.skills[e],...t},Ku(n)}const Ju=`BL_SKIP_HOST_AGENTS`,Yu=[`CLAUDE_CONFIG_DIR`,`CODEX_HOME`,`VIBE_HOME`,`HERMES_HOME`,`AUTOHAND_HOME`,`GROK_HOME`,`DSH_HOME`,`OPENCLAW_CONFIG_PATH`,`ZCODE_HOME`,`APPDATA`,`LOCALAPPDATA`,`FLATPAK_XDG_CONFIG_HOME`,`PI_CODING_AGENT_DIR`];function Xu(){let e=ve(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||M(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:M(e,r,`skills`),detectDirs:[M(e,r)]}),i=(t,n)=>t?.trim()||M(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:M(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>M(e,t)),s=o.find(e=>S(e))??o[0],c=[M(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(M(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(M(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:M(e,`.agents`,`skills`),detectDirs:[M(e,`.agents`),M(e,`.cline`),M(e,`.dexto`),M(e,`.firebender`),M(e,`.kimi-code`),M(e,`.kimi`),M(e,`.loaf`),M(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:M(n,`agents`,`skills`),detectDirs:[M(n,`agents`),M(n,`amp`),M(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:M(e,`.astrbot`,`data`,`skills`),detectDirs:[M(t,`data`,`skills`),M(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:M(e,`.codebuddy`,`skills`),detectDirs:[M(t,`.codebuddy`),M(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:M(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:M(e,`.continue`,`skills`),detectDirs:[M(t,`.continue`),M(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:M(e,`.deepagents`,`agent`,`skills`),detectDirs:[M(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:M(n,`devin`,`skills`),detectDirs:[M(n,`devin`)]},r(`droid`,`Droid`,`.factory`),a(`dsh`,`DeepSeek DSH`,i(process.env.DSH_HOME,`.dsh`)),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:M(n,`goose`,`skills`),detectDirs:[M(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,Bc(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:M(e,`.jazz`,`skills`),detectDirs:[M(e,`.jazz`),M(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:M(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[M(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:M(e,`.minimax`,`skills`),detectDirs:[M(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:M(n,`opencode`,`skills`),detectDirs:[M(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:M(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:M(e,`.tabnine`,`agent`,`skills`),detectDirs:[M(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cli`,`Trae CLI`,`.traecli`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),r(`workbuddy`,`Tencent WorkBuddy`,`.workbuddy`),{id:`zcode`,displayName:`ZCode`,skillsDir:M(e,`.zcode`,`skills`),detectDirs:[M(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Zu(e){let t=ge(e);try{return de(t)}catch{let e=[],n=t;for(;n!==j(n);){if(S(n))try{return M(de(n),...e.reverse())}catch{break}e.push(pe(n)),n=j(n)}return t}}function Qu(e,t){let n=Zu(e),r=Zu(t);return n===r||n.startsWith(r+_e)}function $u(e){if(!me(e)||Qu(e,ve()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&Qu(e,t))}function ed(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!$u(e)}function td(){return Xu().filter(e=>e.detectDirs.some(e=>ed(e)&&S(e)))}function nd(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function rd(e){let t=$();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+_e)}return e===t||e.startsWith(t+_e)}function id(e){try{if(!C(e).isSymbolicLink())return!1;let t=ue(e);return rd(me(t)?t:ge(j(e),t))}catch{return!1}}function ad(e,t){if(!t.some(t=>nd(t,e)))return!1;try{return C(e).isDirectory()}catch{return!1}}function od(e){try{return C(e).isDirectory()?S(M(e,`SKILL.md`)):!1}catch{return!1}}const sd=`existing file/dir not managed by bl skill`;function cd(e,t=td(),n=[]){let r=M($(),e),i=[];for(let a of t){let t=M(a.skillsDir,e);try{let e=!1;try{C(t),e=!0}catch{}if(e){if(id(t))O(t);else if(ad(t,n))O(t,{recursive:!0,force:!0});else if(od(t))O(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:sd});continue}}w(a.skillsDir,{recursive:!0});try{k(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{ce(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function ld(e,t=td(),n=[]){let r=cd(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===sd).map(e=>e.path),s=n.filter(e=>!a.some(t=>nd(t,e))&&!o.some(t=>nd(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function ud(e,t=[]){let n=[],r=new Set(t);for(let t of Xu())r.add(M(t.skillsDir,e));for(let e of r)try{let r;try{r=C(e)}catch{continue}r.isSymbolicLink()?id(e)&&n.push(e):t.some(t=>nd(t,e))&&n.push(e)}catch{}return n}function dd(e,t=[]){let n=[];for(let r of ud(e,t))try{if(id(r))O(r);else if(!C(r).isSymbolicLink()&&t.some(e=>nd(e,r)))O(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function fd(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function pd(e,t){let n=Ce.extract();n.on(`entry`,(e,r,i)=>{if(!fd(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=M(t,e.name);if(e.type===`directory`){w(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}w(j(a),{recursive:!0});let o=le(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await xe(be.from(e),Se(),n)}function md(e){let t=[],n=r=>{for(let i of E(r?M(e,r):e,{withFileTypes:!0})){let e=r?`${r}/${i.name}`:i.name;i.isDirectory()?n(e):i.isFile()&&t.push(e)}};n(``),t.sort((e,t)=>e<t?-1:+(e>t));let r=ye(`sha256`);for(let n of t)r.update(n),r.update(T(M(e,n)));return`sha256:${r.digest(`hex`)}`}function hd(e,t,n=259){let r,i=a=>{for(let o of E(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=M(a,o.name),c=he(e,s);for(let e of t){let t=M(e,c).length;t>n&&t>(r?.pathLength??0)&&(r={root:e,relativePath:c,pathLength:t})}o.isDirectory()&&i(s)}};for(let e of t)e.length>n&&e.length>(r?.pathLength??0)&&(r={root:e,relativePath:``,pathLength:e.length});return i(e),r}function gd(e){let t=[],n=r=>{for(let i of E(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=M(r,i.name),o=he(e,a);i.isDirectory()?(t.push({relativePath:o,type:`directory`}),n(a)):i.isFile()&&t.push({relativePath:o,type:`file`})}};return n(e),t}function _d(e,t){let n=gd(e),r=new Set(n.map(e=>e.relativePath));w(t,{recursive:!0});for(let r of n){let n=M(e,r.relativePath),i=M(t,r.relativePath);if(S(i)){let e=C(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&O(i,{recursive:!0,force:!0})}r.type===`directory`?w(i,{recursive:!0}):(w(j(i),{recursive:!0}),se(n,i))}let i=gd(t).filter(e=>!r.has(e.relativePath)).sort((e,t)=>t.relativePath.length-e.relativePath.length);for(let e of i)O(M(t,e.relativePath),{recursive:!0,force:!0})}function vd(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function yd(e){try{S(e)&&O(e,{recursive:!0,force:!0})}catch{}}function bd(e,t,n={}){w(j(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(S(t))try{D(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!vd(i))throw i;try{_d(t,r),_d(e,t),yd(r);return}catch(e){try{S(r)&&_d(r,t)}catch{}throw Error(`Skill directory is in use and could not be updated in place. Close running agent hosts and retry. / Skill 目录正被占用,无法原地更新;请关闭正在运行的 Agent 后重试。 ${e instanceof Error?e.message:String(e)}`,{cause:e})}}try{D(e,t)}catch(e){throw S(r)&&!S(t)&&D(r,t),e}yd(r)}function xd(e){if(e instanceof P){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function Sd(e){return e instanceof P&&e.api?.httpStatus===429}function Cd(e,t){return Math.min(t*2**(e-1),1e4)}function wd(e){return new Promise(t=>setTimeout(t,e))}async function Td(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??xd,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;Sd(e)&&await wd(Cd(t,a))}throw o}function Ed(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function Dd(e=3e4,t=3){return Td(async()=>{let t=`${Ed()}/index.json`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new P(`Cannot access skill registry: ${t}`,N.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new P(`Skill registry returned HTTP ${n.status}: ${t}`,N.NETWORK,n.status===404?`Skill index not yet published or registry URL is incorrect; confirm the publisher has generated index.json`:`Remote error, retry later`);let r;try{r=await n.json()}catch(e){throw new P(`Skill index index.json is not valid JSON`,N.GENERAL,`Remote may be in the middle of publishing, retry later`,{cause:e})}let i=r;if(typeof i!=`object`||!i||typeof i.skills!=`object`||i.skills===null)throw new P(`Skill index index.json has invalid structure`,N.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const Od=/^sha256-[0-9a-f]{64}\.tar\.br$/;function kd(e){let t=e?.object;return t&&Od.test(t)?t:`skill.tar.br`}async function Ad(e,t,n=3){return Td(async()=>{let n=`${Ed()}/${e}/${kd(t)}`,r;try{r=await fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new P(`Failed to download skill ${e}: ${n}`,N.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new P(`Failed to download skill ${e}: HTTP ${r.status}`,N.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())},{attempts:n})}function jd(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function Md(e){return e.length>0&&jd(e)===e}function Nd(e,t){throw new P(`Skill ${e} validation failed: ${t}`,N.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function Pd(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function Fd(e,t){let n=M(e,`SKILL.md`),r;try{fe(n).isFile()||Nd(t,`SKILL.md is not a regular file`),r=T(n,`utf-8`)}catch(e){if(e instanceof P)throw e;Nd(t,`missing SKILL.md`)}let i=Pd(r);i===null&&Nd(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{Nd(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&Nd(t,`frontmatter is not a key-value structure`);let o=a,s=typeof o.name==`string`?o.name.trim():``,c=typeof o.description==`string`?o.description.trim():``;return(!s||!c)&&Nd(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function Id(e){if(!Md(e))throw new P(`Invalid skill name: ${e}`,N.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function Ld(e,t,n,r){Id(e);let i=$(),a=M(i,e),o=M(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{w(o,{recursive:!0}),await pd(t,o);let i=hd(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new P(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,N.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=md(o);if(t!==n)throw new P(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,N.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=Fd(o,e);return bd(o,a),{name:e,path:a,meta:s}}finally{try{S(o)&&O(o,{recursive:!0,force:!0})}catch{}}}async function Rd(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new P(`Skill ${e} uses unsupported compression format: ${t.compression}`,N.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return Ld(e,await Ad(e,t,n),t.contentHash,r)}function zd(e){Id(e);let t=M($(),e);return S(t)?(O(t,{recursive:!0,force:!0}),!0):!1}function Bd(e,t){return{...e.contentHash?{contentHash:e.contentHash}:{},...e.publishedAt?{publishedAt:e.publishedAt}:{},installedAt:(/* @__PURE__ */ new Date()).toISOString(),sourceType:`oss`,...e.description?{description:e.description}:{},links:t}}async function Vd(e,t,n=td(),r=[],i){await Rd(e,t,i,process.platform===`win32`?[M($(),e),...n.map(t=>M(t.skillsDir,e))]:void 0);let a=ld(e,n,r);return{lockEntry:Bd(t,a.links),linkedAgents:a.linkedAgents}}const Hd=`bailian-docs-llm-wiki`;function Ud(){return M(I(),`skills/bailian-docs-llm-wiki`)}function Wd(){return S(M(Ud(),`models`,`models.jsonl`))}function Gd(){return M(I(),`wiki-sync-state.json`)}function Kd(){try{return JSON.parse(T(Gd(),`utf-8`))}catch{return null}}function qd(e){try{A(Gd(),JSON.stringify(e))}catch{}}function Jd(e){try{qu(Hd,e)}catch{}}function Yd(e){try{let t=Gu().skills[Hd];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function Xd(){try{return(await Dd(3e3,1)).skills[Hd]??null}catch{return null}}async function Zd(){let e=Kd(),t=Date.now();if(e&&t-e.lastChecked<432e5&&Wd())return!1;let n=await Xd();if(!n?.contentHash)return!1;if(Wd()&&(!e||e.contentHash===n.contentHash)){if(qd({lastChecked:t,contentHash:n.contentHash}),Yd(n.contentHash)){let e=Gu().skills[Hd]?.links??[];Jd(Bd(n,ld(Hd,td(),e).links))}return!1}try{let e=Gu().skills[Hd]?.links??[];Jd((await Vd(Hd,n,td(),e,1)).lockEntry)}catch{return!1}return qd({lastChecked:t,contentHash:n.contentHash}),!0}const Qd=`bailian-cli`,$d=`install-method`,ef=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function tf(e){return e?M(I(),`${$d}.${e}`):M(I(),$d)}function nf(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function rf(e){if(!e)return null;let t=e.trim().toLowerCase();return ef.has(t)?t:null}function af(e){try{return rf(T(e,`utf-8`).split(`
203
- `)[0])}catch{return null}}function of(){let e=rf(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(nf()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function sf(e){let t=rf(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=af(tf(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=af(tf());if(e)return e}return of()}return af(tf())||of()}function cf(e){let t=sf(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function lf(e,t={clientName:Qd}){try{let n=I();S(n)||w(n,{recursive:!0,mode:448}),A(tf(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&A(tf(),`${e}\n`,{mode:384})}catch{}}const uf=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,df=`https://github.com/modelstudioai/cli/releases`,ff=`https://bailian.aliyun.com/cli/install.sh`,pf=`https://bailian.aliyun.com/cli/install.ps1`;function mf(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):uf}function hf(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${mf()}/manifest.json`:`${mf()}/${t}.json`}function gf(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${mf()}/${n}/${t}`}function _f(){let e=process.platform,t=process.arch,n;if(e===`darwin`)n=`darwin`;else if(e===`linux`)n=`linux`;else if(e===`win32`)n=`windows`;else throw Error(`Unsupported platform for binary updates: ${e}`);let r;if(t===`arm64`)r=`arm64`;else if(t===`x64`)r=`x64`;else throw Error(`Unsupported architecture for binary updates: ${t}`);if(n===`linux`&&r===`arm64`)throw Error(`linux arm64 is not supported for binary updates; use: npm install -g bailian-cli`);if(n===`windows`&&r===`arm64`)throw Error(`windows arm64 is not supported for binary updates; use: npm install -g bailian-cli`);return{os:n,arch:r,fileSuffix:e===`win32`?`.exe`:``}}function vf(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function yf(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function bf(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function xf(e){return new Promise((t,n)=>{oe.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??/* @__PURE__ */ Error(`Failed to open zip: ${e}`));return}t(i)})})}function Sf(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function Cf(e,t,n){let r=await xf(e);return new Promise((i,a)=>{let o=!1,s=e=>{if(!o){o=!0;try{r.close()}catch{}a(e instanceof Error?e:Error(String(e)))}},c=e=>{if(!o){o=!0;try{r.close()}catch{}i(e)}};r.on(`error`,s),r.on(`end`,()=>{o||s(/* @__PURE__ */ Error(n?`Zip entry not found: ${n} in ${e}`:`Zip has no file entries: ${e}`))}),r.on(`entry`,e=>{if(o)return;let i=e.fileName.replace(/\\/g,`/`);if(i.endsWith(`/`)){r.readEntry();return}let a=Sf(i);if(n&&i!==n&&a!==n){r.readEntry();return}r.openReadStream(e,(n,r)=>{if(n||!r){s(n??/* @__PURE__ */ Error(`Failed to read zip entry: ${e.fileName}`));return}(async()=>{try{await we(j(t),{recursive:!0}),await xe(r,le(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function wf(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new F(`--name cannot be empty`,`Use --name all or --name skill-a,skill-b`);let r=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))];if(r.includes(`all`)){if(r.length>1)throw new F(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Tf(){let e=$();return S(e)?E(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return fe(M(e,t)).isDirectory()}catch{return!1}}):[]}function Ef(e,t,n){let r=new Set(n),i=/* @__PURE__ */ new Set,a=[];for(let[n,o]of Object.entries(e.skills)){i.add(n);let e=t.skills[n];if(e){let t=r.has(n)?e.contentHash===o.contentHash?`installed`:`outdated`:`missing`;a.push({name:n,status:t,publishedAt:o.publishedAt,description:o.description})}else r.has(n)?a.push({name:n,status:`untracked`,publishedAt:o.publishedAt,description:o.description}):a.push({name:n,status:`not-installed`,publishedAt:o.publishedAt,description:o.description})}for(let[e,n]of Object.entries(t.skills))i.has(e)||(i.add(e),a.push({name:e,status:r.has(e)?`installed`:`missing`,publishedAt:n.publishedAt,description:n.description}));for(let e of n)i.has(e)||a.push({name:e,status:`untracked`});return a.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}export{Yu as AGENT_ENV_KEYS,qe as API_KEY_CAPABILITY_PATTERN,jc as ASYNC_FLAG,Ve as BAILIAN_HOST,$s as BILLING_METHOD,Qd as BINARY_PRODUCT_CLIENT_NAME,P as BailianError,jl as Budgets,As as CALC_DATASETS_TOKENS_API,Kt as CHANNEL,J as CHARGE_TYPE,Lc as COMMAND_PACK_API_VERSION,Ac as CONCURRENT_FLAG,We as CONFIG_FILE_KEYS,Nc as CONSOLE_AUTH_FLAGS,Q as Capabilities,Nn as Client,X as Complexities,Ml as ContextNeeds,Jt as DASHSCOPE_SERVICE_HEADER,Aa as DECISION_QUESTION_TYPES,Ro as DECISION_REGIONS,ec as DEFAULT_BILLING_METHOD,uf as DEFAULT_CLI_CDN_BASE,Lo as DEFAULT_DECISION_MODEL,zo as DEFAULT_DECISION_REGION,Zs as DEFAULT_DEPLOY_PLAN,pf as DEFAULT_INSTALL_PS1_URL,ff as DEFAULT_INSTALL_SCRIPT_URL,Ue as DEFAULT_LANGUAGE,ss as DEFAULT_TRAINING_TYPE,pc as DEPLOY_LIST_INDEPENDENT_API,q as DEPLOY_PLAN,dc as DEPLOY_START_API,fc as DEPLOY_STOP_API,Be as DOCS_HOSTS,js as ESTIMATE_FINETUNE_TOKENS_API,N as ExitCode,Nl as Features,df as GITHUB_RELEASES_BASE,kc as GLOBAL_FLAGS,ps as INSUFFICIENT_SAMPLES_CODE,da as MAX_CPT_BYTES,ua as MAX_DATASET_BYTES,ja as MAX_DECISION_CHOICE_OPTIONS,fa as MAX_DECISION_DATASET_BYTES,Na as MAX_DECISION_SCORE_LEVELS,pa as MAX_MEDIA_ZIP_BYTES,Ma as MIN_DECISION_SCORE_LEVELS,Mc as MODEL_AUTH_FLAGS,qi as MODEL_LIST_API,Mn as McpClient,Al as Modalities,Pl as ModelCategories,Pc as OPENAPI_AUTH_FLAGS,qt as OPEN_API_SOURCE,Ji as PREDICT_CONFIG_API,Z as QualityPreferences,ni as RAG_PATHS,ze as REGIONS,Zr as SANDBOX_PATHS,Fl as SEMANTIC_TOP_K,Ju as SKIP_HOST_AGENTS_ENV,vc as SPEECH_BIASING_MODEL,lc as STRATEGIES,He as SUPPORTED_LANGUAGES,ks as TRAINING_MODEL_PRICE_API,os as TRAINING_TYPES_CLI,as as TRAINING_TYPE_MAP,F as UsageError,Ot as activateConfigProfile,qr as agentStudioFilesPath,gr as agentStudioHost,Gl as analyzeIntent,Ht as anonymousConsoleCall,Qn as appCompletionPath,bd as atomicSwap,Dn as bailianMcpPath,On as bailianMcpSsePath,vf as binaryAssetFileName,bf as binaryInnerFileName,yf as binaryTarFileName,rn as buildAcsCanonicalQuery,Ti as buildAsrContextMessages,Di as buildAsrFlashRequest,Ei as buildAsyncAsrLanguageFields,zu as buildDocLink,ac as buildPrepaidInfo,nc as buildReservationCapacity,Mt as buildSettings,Bd as buildSkillLockEntry,jt as buildSources,yc as buildVocabularyRequest,Wt as callConsoleGateway,rs as cancelCompressJob,Ko as cancelFineTune,hf as channelManifestUrl,Bn as chatPath,ki as collectAsrTranscriptionItems,md as computeDirContentHash,Ef as computeSkillStatuses,jn as connectBailianMcpWithFallback,Wi as createBailianControlUser,Hs as createCapacityInstance,$o as createCompressJob,Is as createDeployment,Uo as createFineTune,Bi as createInstrumentedFetch,rl as createTrackingEvent,xc as createVocabulary,Fc as credentialFlagDefs,Hn as decisionPath,Qs as defaultDeployPlan,Ic as defineCommand,Gs as deleteCapacityInstance,is as deleteCompressJob,kt as deleteConfigProfile,la as deleteDataset,qs as deleteDeployment,qo as deleteFineTune,Tc as deleteVocabulary,Rr as deploymentCapacityInstancePath,Br as deploymentCapacityInstanceRenewPath,zr as deploymentCapacityInstanceScalePath,Lr as deploymentCapacityInstancesPath,Hr as deploymentCapacityOperationPath,Vr as deploymentOverflowPath,ot as describeAuthState,_f as detectBinaryPlatform,of as detectInstallMethod,td as detectInstalledAgents,Eo as detectModality,pt as detectOutputFormat,Ad as downloadSkillAsset,Vt as effectiveConsoleGatewayConfig,Wu as emptySkillLock,lt as ensureConfigDir,Ps as estimateCptTokens,Ns as estimateSftDpoTokens,Xo as exportCheckpoint,Oi as extractAsrFlashText,pd as extractTarBr,Cf as extractZipEntryToFile,ld as fanOutSkillToAgents,fs as fetchModelCapability,ta as fetchModelDetail,Qi as fetchModelGroups,ea as fetchModelGroupsAll,Yi as fetchModelList,Xi as fetchModelListAll,ia as fetchPredictConfig,Dd as fetchSkillsIndex,Ms as fetchTrainingModelPrice,_c as findDeploymentEntry,Zi as findModelByName,$i as flattenModelGroups,hl as flushTelemetry,ft as formatErrorJson,Io as formatIssue,dt as formatJson,mt as formatOutput,ut as formatText,Ln as generateCLIAccessToken,zc as generateFilename,Xu as getAgentTargets,Ft as getApiKeyLoginKind,Bs as getCapacityInstance,Vs as getCapacityOperation,mf as getCliCdnBase,ts as getCompressJob,ns as getCompressJobLogs,I as getConfigDir,st as getConfigPath,ct as getCredentialsPath,ca as getDataset,Rs as getDeployment,Go as getFineTune,Jo as getFineTuneLogs,Bc as getHermesHome,sf as getInstallMethod,Pt as getModelProfilePreset,kl as getModels,Ds as getProfile,Uu as getSkillLockPath,Ed as getSkillRegistryBaseUrl,$ as getSkillsDir,cf as getUpdateInstallMethod,rc as hasPrepaidFlags,Kn as image2ImagePath,Jn as image2videoPath,pn as imageFileToDataUri,Un as imagePath,Wn as imageSyncPath,Gn as imageText2ImagePath,wi as inferAudioFormatHint,Ba as inspectDecisionQuestion,Ha as inspectDecisionQuestionId,Va as inspectDecisionQuestionTable,Ua as inspectDecisionQuestions,Ia as inspectDecisionState,Rd as installSkill,Ld as installSkillFromBuffer,Vd as installSkillWithFanout,Je as isApiKeyCapability,nf as isCompiledBinary,Mi as isDashScopeGateway,U as isDecisionObject,$u as isHostSystemDetectDir,di as isLegacyImage2ImageModel,ui as isLegacyText2ImageModel,gn as isLocalFile,fd as isSafeEntryName,Md as isSafeSkillName,yu as isSemanticAvailable,kn as isStreamableHttpUnsupported,oi as isSyncMultimodalImageModel,cs as isTrainingTypeCli,An as isUrlOverrideSseFallbackCandidate,fi as isWanxFunctionImageEditModel,hr as knowledgeChatEndpoint,mr as knowledgeSearchEndpoint,cd as linkSkillToAgents,Gi as listBailianControlWorkspaces,zs as listCapacityInstances,Yo as listCheckpoints,es as listCompressJobs,Qo as listCompressTemplates,sa as listDatasets,Js as listDeployableModels,Ls as listDeployments,Wo as listFineTunes,gc as listIndependentDeployedModels,Tf as listSkillDirsOnDisk,Fo as listSupportedFormats,ds as listSupportedTrainingTypes,Os as listTrainingTypes,Sc as listVocabularies,gl as localSink,Rt as makeAuthStore,aa as makeConfigStore,Ie as mapApiError,Gt as maskToken,Zd as maybeSyncWikiData,br as mcpWebSearchPath,er as memoryAddAsyncPath,$n as memoryEndpoint,tr as memoryEventPath,rr as memoryListPath,ir as memoryNodePath,nr as memorySearchPath,ar as memorySkillExportPath,us as modelSupportsTrainingType,Xn as modelsLimitsPath,Zn as modelsPermissionsPath,Ye as normalizeApiKeyCapabilities,bt as normalizeConfigName,Le as normalizeModelBaseUrl,qc as parseBooleanValue,Ze as parseConfigFile,ha as parseDatasetSchemaFlag,Dc as parseInstantVocabulary,Jc as parseOptionalBooleanValue,xn as parseSSE,Ii as parseSecurityBody,wf as parseSkillNames,Oc as parseVocabularyEntries,uc as pickPlanStrategy,No as pickValidator,ud as planUnlinkSkillFromAgents,ms as preflightBatchSizeGate,ur as profileSchemaItemPath,lr as profileSchemaPath,Cc as queryVocabulary,Kr as ragEndpoint,Hu as rankModels,nl as readCaller,R as readConfigFile,Tt as readConfigProfiles,Gu as readSkillLock,Gc as readTextFromPathOrStdin,ru as recallCandidates,Fu as recallSemantic,mn as redactDataUri,Rn as refreshAccessToken,Po as registerValidator,gf as releaseAssetUrl,_l as remoteSink,zd as removeSkillDir,Ws as renewCapacityInstance,Qt as request,nn as requestJson,Ki as resetBailianControlPolicies4Agent,et as resolveApiKey,Ci as resolveAsrApi,kd as resolveAssetFileName,Yc as resolveBooleanFlag,Fn as resolveCLIAccessTokenTarget,tt as resolveConsole,_n as resolveFileUrl,gi as resolveImageEditApi,hi as resolveImageGenerateApi,pi as resolveImageSizeProfile,$e as resolveModelBaseUrl,Qe as resolveModelBaseUrlState,nt as resolveOpenApi,Uc as resolveOutputDir,mi as resolvePromptExtendDefault,Xc as resolveWatermark,Vn as responsesPath,Kc as runWithConcurrency,Yr as sandboxApiPath,Jr as sandboxBaseUrl,Xr as sandboxEndpoint,$r as sandboxInstanceActionPath,Qr as sandboxInstancePath,ti as sandboxTemplateBuildStatusPath,ei as sandboxTemplatePath,jd as sanitizeSkillName,Us as scaleCapacityInstance,Ys as scaleDeployment,yr as securityAgentLogsEndpoint,Li as securityGet,vr as securityOverviewEndpoint,At as selectApiKeyResolutionSources,an as signAcsRequest,Yt as sourceConfig,sr as speechRecognizePath,or as speechSynthesizePath,cr as speechVocabularyPath,mc as startModelService,hc as stopModelService,Ho as stripDecisionTrainingFields,Wc as stripUndefined,Yn as taskPath,xl as trackCommandExecution,z as trackingHeaders,ls as trainingTypeMethodVariant,dd as unlinkSkillFromAgents,Vo as unwrapDecisionQuestions,V as unwrapResponse,Xs as updateDeployment,Ks as updateDeploymentOverflow,wc as updateVocabulary,oa as uploadDataset,hn as uploadFile,qu as upsertSkillLockEntry,dr as userProfilePath,fr as userProfileValuesPath,Dt as validateConfigProfileActivation,In as validateConsoleAccessToken,K as validateDataset,ic as validatePrepaidFlags,tc as validateReservationCapacity,Fd as validateSkillDir,gt as validateTimeout,qn as videoGeneratePath,pr as workspaceMaaSBaseUrl,Ct as writeConfigFile,lf as writeInstallMethodSync,Ku as writeSkillLock};
118
+ {
119
+ "taskSummary": "one-sentence English summary",
120
+ "scenarioHints": ["..."],
121
+ "complexity": "single" | "pipeline",
122
+ "segments": [{ "step": "中文步骤名", "scene": "<scene label>"|null, "inputModality": [...], "outputModality": [...], "requiredCapabilities": [...] }], // pipeline only; steps must form a modality chain
123
+ "inputModality": ["Text"|"Image"|"Video"|"Audio"],
124
+ "outputModality": [...],
125
+ "requiredCapabilities": [...], // strictly from the "Capability codes" list above
126
+ "requiredFeatures": [...], // from: function-calling, web-search, structured-outputs, prefix-completion
127
+ "budget": "low"|"medium"|"high",
128
+ "contextNeed": "standard"|"large"|"extra-large",
129
+ "qualityPreference": "flagship"|"balanced"|"cost-optimized",
130
+ "matchedScenes": [...],
131
+ "sceneConfidence": 0.0-1.0,
132
+ "modelPreference": { "mode": "...", "targets": [...], "excludes": [...] },
133
+ "cardinalityHint": null | "one" | "many", // null unless an explicit trigger word from "Cardinality detection" appears
134
+ "optimizeDimension": null | "price" | "speed" | "context" | "quality" // null unless an explicit superlative appears
135
+ }
136
+
137
+ Output only JSON, no other text.`;var X=class extends Error{kind;status;code;requestId;stage;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.name=`LLMError`,this.kind=e,this.status=n.status,this.code=n.code,this.requestId=n.requestId,this.stage=n.stage}get fatal(){return this.kind===`rate_limit`||this.kind===`auth`||this.kind===`cancelled`}get tag(){return this.status?`${this.status} ${this.kind}`:this.kind}};function Z(e){if(!e?.aborted)return;let t=e.reason;throw new X(`cancelled`,t instanceof Error?t.message:`执行已取消`,{cause:t})}function Tu(e){return e===429?`rate_limit`:e===401||e===403?`auth`:`http`}function Eu(e,t,n){return{stage:e,fallback:t,kind:n.kind,status:n.status,message:n.message}}function Du(e){let t=e.status?`${e.status} ${e.kind}`:e.kind;return`${e.fallback} (${t})`}function Q(e,t){return e instanceof X?(e.stage??=t,e):new X(`parse`,e instanceof Error?e.message:String(e),{stage:t,cause:e})}const Ou=[`unconstrained`,`scoped`,`comparison`,`alternative`],ku=/* @__PURE__ */ new Set([`Text`,`Image`,`Video`,`Audio`]),Au=new Set(Cu),ju=/* @__PURE__ */ new Set([`price`,`speed`,`context`,`quality`]),Mu=/* @__PURE__ */ new Set([`one`,`few`,`many`]);function Nu(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Pu(e){return Nu(e).filter(e=>ku.has(e))}function Fu(e){if(!e||typeof e!=`object`)return;let t=e,n=typeof t.mode==`string`&&Ou.includes(t.mode)?t.mode:`unconstrained`,r=Nu(t.targets),i=Nu(t.excludes);return{mode:n,targets:r.length>0?r:void 0,excludes:i.length>0?i:void 0}}async function Iu(e,t,n){let r;try{r=await e.chatJson([{role:`system`,content:wu},{role:`user`,content:t}],{stage:`intent`,signal:n})}catch(e){throw Q(e,`intent`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new X(`parse`,`Intent response is not a JSON object`,{stage:`intent`});let i=Nu(r.matchedScenes).filter(e=>Au.has(e)),a=typeof r.sceneConfidence==`number`&&r.sceneConfidence>=0&&r.sceneConfidence<=1?r.sceneConfidence:i.length>0?.5:0;return{complexity:r.complexity===`pipeline`?`pipeline`:`single`,segments:Array.isArray(r.segments)?r.segments.map(e=>({step:typeof e.step==`string`?e.step:``,scene:typeof e.scene==`string`&&Au.has(e.scene)?e.scene:void 0,inputModality:Pu(e.inputModality),outputModality:Pu(e.outputModality),requiredCapabilities:Nu(e.requiredCapabilities)})):void 0,taskSummary:typeof r.taskSummary==`string`?r.taskSummary:``,scenarioHints:Nu(r.scenarioHints),inputModality:Pu(r.inputModality),outputModality:Pu(r.outputModality),requiredCapabilities:Nu(r.requiredCapabilities),requiredFeatures:Nu(r.requiredFeatures),budget:r.budget===`low`||r.budget===`high`?r.budget:`medium`,contextNeed:r.contextNeed===`large`||r.contextNeed===`extra-large`?r.contextNeed:`standard`,qualityPreference:r.qualityPreference===`cost-optimized`||r.qualityPreference===`balanced`?r.qualityPreference:`flagship`,confidence:1,modelPreference:Fu(r.modelPreference),matchedScenes:i,sceneConfidence:a,cardinalityHint:typeof r.cardinalityHint==`string`&&Mu.has(r.cardinalityHint)?r.cardinalityHint:void 0,optimizeDimension:typeof r.optimizeDimension==`string`&&ju.has(r.optimizeDimension)?r.optimizeDimension:void 0}}function Lu(e){return!e.offlineInfo}function Ru(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&i.length>0&&!t.some(e=>i.includes(e))||n.length>0&&a.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function zu(e,t){return Ru(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Bu(e,t){let n=[...t.matchedScenes,...t.scenarioHints].filter(Boolean);return n.length===0?e:e.filter(e=>{let t=e.profile?.notSuitableFor;return!t?.length||!t.some(e=>n.some(t=>e.includes(t)))})}function Vu(e,t,n=5){let r=e.filter(e=>zu(e,t));if(r.length>=n)return r;if(t.requiredCapabilities.length>0){let n=e.filter(e=>t.requiredCapabilities.some(t=>e.capabilities.includes(t)));if(n.length>0)return n}return e}const Hu=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`VU`,`IG`,`VG`,`TTS`,`ASR`,`Realtime-ASR`,`Realtime-Text-to-Speech`,`Realtime-Audio-Translate`,`Realtime-Chatting`,`Realtime-Omni`,`Multimodal-Omni`,`ME`,`TR`,`3D-generation`]),Uu=/* @__PURE__ */ new Set([`Reasoning`]),Wu={TG:[`代码生成`,`创意写作`,`客服对话`,`知识问答`,`文档理解`,`数据分析`,`数学推理`,`翻译`,`Agent编排`,`深度研究`,`教育辅导`,`电商营销`,`角色扮演`,`情感分析`,`意图识别`],VU:[`文档理解`,`OCR文字识别`,`数据分析`],IG:[`图像生成`,`图像编辑`,`图像修复`,`人脸人像`,`虚拟试穿`,`电商营销`],VG:[`视频生成`,`视频编辑`,`数字人`],TTS:[`语音合成`,`有声书`,`播客`,`数字人`],ASR:[`语音识别`],"Realtime-ASR":[`语音识别`,`实时对话`],TR:[`向量检索`,`语义重排`,`知识问答`],ME:[`向量检索`],"3D-generation":[`3D生成`]},Gu={IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`},Ku=[[/重排|rerank/i,`语义重排`],[/向量|嵌入|embedding|索引/i,`向量检索`],[/翻译|translat/i,`翻译`],[/代码|编程|code/i,`代码生成`],[/剧本|脚本|文案|歌词|故事|小说|创作|写作|script|lyric/i,`创意写作`],[/纪要|摘要|总结|整理|summar/i,`文档理解`],[/问答|回答|答案|answer/i,`知识问答`],[/转写|识别|听写|transcri/i,`语音识别`],[/配音|旁白|朗读|语音合成|voice/i,`语音合成`],[/数字人|口型|lip/i,`数字人`]],qu=/剪辑|合成剪辑|合轨|混音|拼接|加字幕|字幕合成|后期|导出|assembl|edit(ing)? together|mux/i;function Ju(e,t){let n=t[0];if(n===`Image`)return`IG`;if(n===`Video`)return`VG`;if(n===`Audio`)return e.includes(`Audio`)&&!e.includes(`Text`)?void 0:`TTS`;if(n===`Text`)return e.includes(`Audio`)?`ASR`:e.includes(`Image`)||e.includes(`Video`)?`VU`:`TG`}function Yu(e){return{TG:`文本生成`,VU:`视觉理解`,IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`,TR:`文本检索`,ME:`多模态检索`,"3D-generation":`3D 生成`}[e]??e}function Xu(e){let t=[];for(let n of e??[]){let e=n.requiredCapabilities.filter(e=>Hu.has(e)),r=e.filter(e=>!Uu.has(e)),i=n.step?.trim()??``;if(r.length===0&&qu.test(i))continue;let a=r[0]??Ju(n.inputModality,n.outputModality);if(!a)continue;let o=[a,...e.filter(e=>e!==a)],s=i||Yu(a);if(t.push({index:t.length+1,label:s,inputModality:n.inputModality,outputModality:n.outputModality,primaryCapability:a,capabilities:o,scene:Zu(n.scene,s,a)}),t.length>=5)break}return t.length>=2?t:[]}function Zu(e,t,n){let r=e=>(Wu[n]??[]).includes(e);if(e&&r(e))return e;for(let[e,n]of Ku)if(e.test(t)&&r(n))return n;return Gu[n]}function Qu(e,t){if(e.scene)return[e.scene];let n=new Set(Wu[e.primaryCapability]??[]);return t.matchedScenes.filter(e=>n.has(e))}function $u(e,t){return{...t,complexity:`single`,segments:void 0,inputModality:e.inputModality,outputModality:e.outputModality,requiredCapabilities:[e.primaryCapability],requiredFeatures:e.primaryCapability===`TG`?t.requiredFeatures:[],matchedScenes:Qu(e,t)}}const ed=/* @__PURE__ */ new Set([`IG`,`VG`,`TTS`,`Realtime-Text-to-Speech`,`3D-generation`]),td=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`ASR`,`Realtime-ASR`,`TR`,`ME`]);function nd(e){let t=!1,n=!1;for(let r of e)ed.has(r)&&(t=!0),td.has(r)&&(n=!0);return t&&n}function rd(e){let t=e.modelPreference?.mode;if(t!==`comparison`&&t!==`alternative`){if(e.outputModality.length>0&&e.inputModality.length===0){let t=e.outputModality[0];if(t===`Video`&&e.matchedScenes.length===0)return{question:`你打算从什么素材出发生成视频?`,options:[`纯文字描述(文生视频)`,`已有图片(图生视频)`,`已有视频(视频编辑)`],defaultIfSkip:`纯文字描述(文生视频)`,impact:`text-to-video and image-to-video use completely different models`};if(t===`Audio`&&e.matchedScenes.length===0)return{question:`你需要的是哪类语音能力?`,options:[`文字转语音(TTS)`,`语音转文字(ASR)`,`实时语音对话`],defaultIfSkip:`文字转语音(TTS)`,impact:`TTS and ASR are completely different models`}}if(e.complexity!==`pipeline`&&e.requiredCapabilities.length>=3&&nd(e.requiredCapabilities))return{question:`你的核心需求是哪一类?`,options:e.requiredCapabilities.slice(0,4),defaultIfSkip:e.requiredCapabilities[0],impact:`different capabilities map to completely different model pools`}}}function id(e,t){let n=e.modelPreference?.mode;if(n===`comparison`||n===`alternative`||n===`scoped`||e.matchedScenes.length>0&&e.sceneConfidence>=.5||e.complexity===`pipeline`)return;let r=t.filter(t=>zu(t,e));if(e.matchedScenes.length===0&&e.sceneConfidence<.5){let e=/* @__PURE__ */ new Map;for(let t of r)for(let n of t.profile?.scenes??[])e.set(n,(e.get(n)??0)+1);let t=[...e.entries()].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e])=>e);return t.length===0?void 0:{question:`你想用在什么场景?`,options:t,defaultIfSkip:t[0],impact:`不同场景对应完全不同的模型池`}}if(r.length<=20)return;let i=/* @__PURE__ */ new Map;for(let e of r)for(let t of e.profile?.scenes??[])i.set(t,(i.get(t)??0)+1);let a=[...i.entries()].sort((e,t)=>t[1]-e[1]);if(a.length===0||a[0][1]/r.length>=.5)return;let o=a.slice(0,3).map(([e])=>e);return{question:`你的需求更接近哪个场景?`,options:o,defaultIfSkip:o[0],impact:`different scenes produce completely different recommendations`}}function ad(e){let t=e.modelPreference;return!t||t.mode===`unconstrained`?`none`:t.mode===`comparison`?`existing`:t.mode===`alternative`?`reference`:`scope`}function od(e){return e.modelPreference?.mode===`comparison`?(e.modelPreference?.targets?.length??0)<=1?`evaluate`:`differentiate`:e.optimizeDimension?`optimize`:`match`}function sd(e){return e.cardinalityHint??`few`}function cd(e,t,n){return t===`differentiate`?`compare`:t===`evaluate`?`validate`:n===`many`?`catalog`:`recommend`}function ld(e){return e.matchedScenes.length===0&&e.sceneConfidence<.5&&e.confidence>0}const ud=[{name:`forced-compare`,match:e=>e.anchor===`existing`,plan:{recall:`forced`,score:`none`,rank:`forced-order`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`forced-alternative`,match:e=>e.anchor===`reference`,plan:{recall:`forced`,score:`formula`,rank:`score-sort`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`pipeline-steps`,match:e=>e.pipeline&&e.steps>=2,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:2,stepwise:!0}},{name:`template-fast`,match:e=>e.sceneHit&&e.userIntent===`match`&&!e.pipeline,plan:{recall:`template`,score:`none`,rank:`template-order`,explain:`template-text`,fairness:!0,topN:3}},{name:`holistic-complex`,match:e=>e.pipeline||e.fuzzy,plan:{recall:`holistic-pool`,score:`holistic`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}},{name:`catalog-browse`,match:e=>e.cardinality===`many`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`catalog`,fairness:!0,topN:10}},{name:`optimize-single`,match:e=>e.userIntent===`optimize`&&e.cardinality===`one`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3}}],dd={name:`structured-normal`,match:()=>!0,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}};function fd(e){return{recall:`structured`,score:`none`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3,routingReason:`ambiguity-detected`,clarify:e}}function pd(e,t,n){let r=rd(e);if(r)return fd(r);let i=id(e,t);if(i)return fd(i);let a=ad(e),o=od(e),s=sd(e),c=cd(a,o,s),l={anchor:a,userIntent:o,cardinality:s,output:c,sceneHit:e.matchedScenes.length>0&&e.sceneConfidence>=.8,pipeline:e.complexity===`pipeline`,steps:e.complexity===`pipeline`?Xu(e.segments).length:0,fuzzy:ld(e)},u=ud.find(e=>e.match(l))??dd;return{...u.plan,...n!==void 0&&n>0?{topN:n}:{},routingReason:`${u.name}|${a}/${o}/${s}/${c}`}}const md=/-\d{4}-\d{2}-\d{2}$/;function hd(e){return(e??``).toLowerCase().replace(md,``).replace(/[\s_-]+/g,``).trim()}function gd(e,t){if(hd(e.model)===t||hd(e.name)===t)return!0;let n=e.model.lastIndexOf(`/`);return n>=0&&hd(e.model.slice(n+1))===t}function _d(e,t){return[e.family,e.familyName].some(e=>{if(!e)return!1;let n=hd(e);return n.length>0&&(t.includes(n)||n.includes(t))})}function vd(e,t){if(t.length===0)return[];let n=[],r=/* @__PURE__ */ new Set;for(let i of t){let t=hd(i);if(!t)continue;let a=e.filter(e=>gd(e,t));a.length===0&&(a=e.filter(e=>_d(e,t)));for(let e of a)r.has(e.model)||(r.add(e.model),n.push(e))}return n}function yd(e,t){return t.length===0?e:e.filter(e=>!t.some(t=>{let n=hd(t);return n.length>0&&(gd(e,n)||_d(e,n))}))}function bd(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}const xd={flagship:0,balanced:1,lightweight:2},Sd=/* @__PURE__ */ new Set([`qwen`,`qwen-domain-model`,`wan`]);function Cd(e){return Sd.has(e.provider)}function wd(e){let t=e.model.match(/(\d+(?:\.\d+)?)/);return t?Number.parseFloat(t[1]):-1/0}function Td(e){let t=e.budget===`low`||e.qualityPreference===`cost-optimized`;return(e,n)=>{let r=xd[e.profile?.familyTier??``]??1.5,i=xd[n.profile?.familyTier??``]??1.5,a=t?i-r:r-i;if(a!==0)return a;let o=+!Cd(e),s=+!Cd(n);if(o!==s)return o-s;let c=bd(e),l=bd(n),u=!Number.isFinite(c);if(u!==!Number.isFinite(l))return u?1:-1;if(!u){let e=t?c-l:l-c;if(e!==0)return e}return wd(n)-wd(e)}}function Ed(e,t){return{model:e,hardScore:t,finalScore:t}}function Dd(e,t){let n=e.matchedScenes[0];if(!n)return null;let r=t.filter(e=>e.profile?.scenes?.includes(n));return r.length<3?null:r.sort(Td(e)).map(e=>Ed(e,1))}function Od(e,t){let n=Vu(t,e),r=e.matchedScenes[0],i=Td(e),a=[...n].sort((e,t)=>{if(r){let n=+!e.profile?.scenes?.includes(r),i=+!t.profile?.scenes?.includes(r);if(n!==i)return n-i}return i(e,t)}),o=/* @__PURE__ */ new Map;for(let e of a){let t=e.profile?.familyTier??`unknown`,n=o.get(t)??[];n.push(e),o.set(t,n)}let s=[],c=Math.ceil(20/Math.max(o.size,1));for(let[,e]of o)s.push(...e.slice(0,c));if(s.length<20){let e=new Set(s.map(e=>e.model));for(let t of a){if(s.length>=20)break;e.has(t.model)||s.push(t)}}return s.slice(0,20).map(e=>Ed(e,0))}function kd(e,t,n){let r=vd(t,e.modelPreference?.targets??[]),i=new Set(r.map(e=>e.model)),a=r.map(e=>Ed(e,1));if(e.modelPreference?.mode===`comparison`)return a;let o=Math.max(0,Math.max(n,5)-a.length);if(o>0){let n=Vu(t.filter(e=>!i.has(e.model)),e);for(let t of n.sort(Td(e)).slice(0,o))a.push(Ed(t,0))}return a}function Ad(e,t){let n=t.filter(t=>zu(t,e));return n.length<5&&(n=t),n.sort(Td(e)).slice(0,30).map(e=>Ed(e,0))}function jd(e,t,n,r){let i=n.filter(Lu);i=yd(i,t.modelPreference?.excludes??[]);let a;switch(e){case`template`:a=Dd(t,i)??Od(t,i);break;case`forced`:a=kd(t,i,r);break;case`holistic-pool`:a=Ad(t,i);break;default:a=Od(t,i)}if(e!==`forced`){let e=new Set(Bu(a.map(e=>e.model),t).map(e=>e.model));a=a.filter(t=>e.has(t.model.model))}return a}function Md(e){let t=(e??``).replace(/```(?:json)?\s*([\s\S]*?)```/gi,`$1`).trim();try{return JSON.parse(t)}catch{}let n=t.indexOf(`{`),r=t.lastIndexOf(`}`);if(n!==-1&&r!==-1&&r>n){let e=t.slice(n,r+1);try{return JSON.parse(e)}catch{}let i=e.replace(/,\s*([}\]])/g,`$1`);try{return JSON.parse(i)}catch{}}throw Error(`Failed to extract valid JSON from LLM response`)}function Nd(e,t){return`${e.length?e.join(`/`):`?`} → ${t.length?t.join(`/`):`?`}`}function Pd(e){let t=[];e.taskSummary&&t.push(`Task: ${e.taskSummary}`),t.push(`Complexity: ${e.complexity}`);let n=e.complexity===`pipeline`?e.segments??[]:[];n.length>0&&(t.push(`Steps:`),n.forEach((e,n)=>{let r=e.requiredCapabilities.length?` [${e.requiredCapabilities.join(`, `)}]`:``;t.push(` ${n+1}. ${e.step||`step`}: ${Nd(e.inputModality,e.outputModality)}${r}`)})),t.push(`Modality: ${Nd(e.inputModality,e.outputModality)}`),e.requiredCapabilities.length&&t.push(`Capabilities: ${e.requiredCapabilities.join(`, `)}`),e.requiredFeatures.length&&t.push(`Features: ${e.requiredFeatures.join(`, `)}`),e.matchedScenes.length&&t.push(`Scenes: ${e.matchedScenes.join(`, `)}`),e.scenarioHints.length&&t.push(`Hints: ${e.scenarioHints.join(`, `)}`),t.push(`Budget: ${e.budget}`),t.push(`Quality: ${e.qualityPreference}`),e.contextNeed!==`standard`&&t.push(`Context need: ${e.contextNeed}`);let r=e.modelPreference?.excludes??[];return r.length&&t.push(`Excluded by user: ${r.join(`, `)}`),t.join(`
138
+ `)}const Fd={match:{scene:.4,tier:.2,price:.2,context:.2},optimize:{scene:.1,tier:.1,price:.6,context:.2},evaluate:{scene:.5,tier:.2,price:.1,context:.2},differentiate:{scene:.3,tier:.3,price:.2,context:.2}},Id={price:{scene:0,tier:0,price:1,context:0},context:{scene:0,tier:0,price:0,context:1},quality:{scene:.2,tier:.8,price:0,context:0},speed:{scene:.2,tier:0,price:.4,context:.4}};function Ld(e,t){return e===`optimize`&&t.optimizeDimension?Id[t.optimizeDimension]??Fd.optimize:Fd[e]}const Rd={standard:0,large:32e3,"extra-large":128e3};function zd(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:void 0}function Bd(e,t){if(t.matchedScenes.length===0)return 1;let n=e.profile?.scenes??[];return+!!t.matchedScenes.some(e=>n.includes(e))}function Vd(e,t){let n=e.profile?.familyTier;return n?t.qualityPreference===`flagship`?n===`flagship`?1:.5:t.qualityPreference===`cost-optimized`?n===`lightweight`?1:.5:1:1}function Hd(e,t,n){let r=n.map(e=>zd(e.model)).filter(e=>e!==void 0);if(r.length<2)return 1;let i=Math.min(...r),a=Math.max(...r);if(a===i)return 1;let o=zd(e),s=o===void 0?.5:1-(o-i)/(a-i);return t.budget===`low`?s:t.budget===`high`?1-s*.5:.5+s*.5}function Ud(e,t){let n=Rd[t.contextNeed]??0;if(n===0)return 1;let r=e.contextWindow??0;return r===0||r>=n?1:r/n}function Wd(e,t,n){let r=Ld(n,t);return e.map(n=>{let i=r.scene*Bd(n.model,t)+r.tier*Vd(n.model,t)+r.price*Hd(n.model,t,e)+r.context*Ud(n.model,t);return{...n,hardScore:i,finalScore:i}})}function Gd(e){let t=e.model.profile;return[`ID: ${e.model.model}`,t?.oneLinePositioning?`Positioning: ${t.oneLinePositioning}`:``,t?.scenes?.length?`Scenes: ${t.scenes.join(`, `)}`:``,t?.styleKeywords?.length?`Style: ${t.styleKeywords.join(`, `)}`:``,t?.notSuitableFor?.length?`NotSuitableFor: ${t.notSuitableFor.join(`, `)}`:``].filter(Boolean).join(` | `)}async function Kd(e,t){let n=t.llm,r=e.map(Gd).join(`
139
+ `);t.trace.performance.llmCalls++;let i=Md(await n.chat([{role:`system`,content:`You are a model-fit judge. For each candidate model, rate how well it fits the user's need on a 1-10 scale, considering the FULL user request and the parsed intent against the model's complete profile (positioning, scenes, style, limitations).
140
+
141
+ Rules:
142
+ - Judge holistically; do not decompose into dimensions
143
+ - The parsed intent is the structured reading of the request; use it, but the original request wins if they conflict
144
+ - For a pipeline task (Complexity: pipeline), score each model by how well it serves the step that matches its capability; a model that fits no step must score ≤3
145
+ - A model whose notSuitableFor conflicts with the need must score ≤3
146
+ - Respond with ONLY JSON: {"scores": [{"model": "<id>", "score": <1-10>}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${Pd(t.intent)}\n\nCandidates:\n${r}`}],{maxTokens:2048,stage:`holistic-score`,signal:t.signal})),a=new Map((i.scores??[]).map(e=>[e.model,e.score]));return e.map(e=>{let t=a.get(e.model.model),n=typeof t==`number`&&t>=1&&t<=10?t:5;return{...e,holisticScore:n,finalScore:n/10}})}async function qd(e,t,n,r){switch(e){case`none`:return t;case`holistic`:try{return await Kd(t,n)}catch(e){if(Z(n.signal),Q(e,`holistic-score`).kind===`cancelled`)throw e;return n.trace.degradations.push(Eu(`holistic-score`,`holistic-score→formula`,Q(e,`holistic-score`))),Wd(t,n.intent,r)}default:return Wd(t,n.intent,r)}}function Jd(e,t){if(e.length<=1)return e;let n=/* @__PURE__ */ new Map,r=[],i=[];for(let t of e){let e=t.model.family;if(!e){r.push(t);continue}let a=n.get(e)??0;a<2?(r.push(t),n.set(e,a+1)):i.push(t)}let a=[...r,...i],o=a.slice(0,t),s=new Set(o.map(e=>e.model.family).filter(Boolean));if(t>=3&&s.size===1&&a.length>t){let e=o[0].model.family,n=a.findIndex((n,r)=>r>=t&&n.model.family!==e);if(n>=0){let[e]=a.splice(n,1);a.splice(t-1,0,e)}}return a}function Yd(e){let t=e.model.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}function Xd(e){return e.model.profile?.familyTier??`unknown`}function Zd(e,t){let n=[`primary`,`runner-up`,`exploration`];return e.slice(0,t).map((e,t)=>({...e,rank:t+1,slot:n[Math.min(t,n.length-1)]}))}function Qd(e,t,n){if(t<3||e.length<3)return Zd(e,t);let r=[],i=/* @__PURE__ */ new Set,a=()=>{for(let t of e){if(r.length>=3)break;i.has(t.model.model)||(r.push(t),i.add(t.model.model))}};if(n.budget===`low`||n.qualityPreference===`cost-optimized`){let n=/* @__PURE__ */ new Map;for(let t of e){let e=Xd(t),r=n.get(e)??[];r.push(t),n.set(e,r)}for(let e of[`lightweight`,`balanced`,`flagship`]){let t=n.get(e)?.[0];if(t&&!i.has(t.model.model)&&(r.push(t),i.add(t.model.model)),r.length>=3)break}return a(),Zd(r,t)}let o=/* @__PURE__ */ new Set;for(let t of e){if(r.length>=3)break;Xd(t)===`flagship`&&(o.has(t.model.provider)||(o.add(t.model.provider),r.push(t),i.add(t.model.model)))}return a(),Zd(r,t)}function $d(e,t,n,r,i){let a;switch(e){case`template-order`:case`forced-order`:a=t;break;default:a=[...t].sort((e,t)=>{let n=t.finalScore-e.finalScore;return Math.abs(n)>1e-9?n:Yd(e)-Yd(t)})}return r&&(a=Jd(a,n)),e===`forced-order`?Zd(a,n):Qd(a,n,i)}const ef={input_token:`输入`,output_token:`输出`,input_token_cache:`缓存输入`,input_token_cache_creation_5m:`缓存写入`,input_token_cache_read:`缓存读取`,input_token_batch:`批量输入`,output_token_batch:`批量输出`,input_token_batch_chat:`批量对话输入`,output_token_batch_chat:`批量对话输出`};function tf(e){let t=[];for(let n of e.prices??[]){if(t.length>=3)break;let e=ef[n.type]??n.type;t.push(`${e} ${n.price} / ${n.unit}`)}return{pricing:t,contextWindow:e.contextWindow,maxInputTokens:e.maxInputTokens,maxOutputTokens:e.maxOutputTokens,features:e.features??[]}}function nf(e){let t=e.model,n=t.profile;return[`ID: ${t.model}`,`Name: ${t.name}`,`Slot: ${e.slot}`,n?.oneLinePositioning?`Positioning: ${n.oneLinePositioning}`:`Description: ${t.description.slice(0,120)}`,n?.scenes?.length?`Scenes: ${n.scenes.join(`, `)}`:``,n?.familyTier?`Tier: ${n.familyTier}`:``,t.contextWindow?`Context: ${t.contextWindow}`:``,t.prices?.length?`Price: ${t.prices[0].price}/${t.prices[0].unit}`:``,n?.notSuitableFor?.length?`NotSuitableFor: ${n.notSuitableFor.join(`, `)}`:``].filter(Boolean).join(` | `)}function rf(e){return e.model.profile?.profileCompleteness===`structured-only`?`low`:e.slot===`exploration`||e.slot===`alternative`?`medium`:`high`}function af(e){return e.map(e=>{let t=e.model.profile,n=[];return t?.familyTier&&n.push(t.familyTier),e.model.prices?.length&&n.push(`${e.model.prices[0].price}/${e.model.prices[0].unit}`),t?.styleKeywords?.length&&n.push(...t.styleKeywords.slice(0,2)),{model:e.model.model,name:e.model.name,reason:t?.oneLinePositioning??e.model.description.slice(0,80),highlights:n,confidence:rf(e),slot:e.slot,docUrl:e.model.docUrl,specs:tf(e.model)}})}function of(e){return e.map(e=>({model:e.model.model,name:e.model.name,reason:e.model.profile?.oneLinePositioning??``,highlights:e.model.profile?.familyTier?[e.model.profile.familyTier]:[],confidence:rf(e),slot:e.slot,docUrl:e.model.docUrl,specs:tf(e.model)}))}async function sf(e,t,n){n.trace.performance.llmCalls++;let r=Md(await n.llm.chat([{role:`system`,content:e},{role:`user`,content:`User request: ${n.input}\n\nIntent:\n${Pd(n.intent)}\n\nRanked candidates:\n${t.map(nf).join(`
147
+ `)}`}],{maxTokens:2048,stage:`explain`,signal:n.signal})),i=new Map((r.items??[]).map(e=>[e.model,e]));return t.map(e=>{let t=i.get(e.model.model);return{model:e.model.model,name:e.model.name,reason:t?.reason??e.model.profile?.oneLinePositioning??``,highlights:t?.highlights??[],confidence:rf(e),slot:e.slot,docUrl:e.model.docUrl,specs:tf(e.model)}})}async function cf(e,t,n){switch(e){case`template-text`:return af(t);case`catalog`:return of(t);case`llm-compare`:try{return await sf(`You are a model comparison advisor for Alibaba Cloud Model Studio. Analyze the given models against the user's use case comparatively.
148
+
149
+ Rules:
150
+ - reason and highlights MUST be in Simplified Chinese (简体中文)
151
+ - Each reason must be comparative: strengths/weaknesses relative to the other models, and "choose this if ..."
152
+ - highlights emphasize differentiators
153
+ - Respond with ONLY JSON:
154
+ {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if(Z(n.signal),Q(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(Eu(`explain`,`llm-compare→template-text`,Q(e,`explain`))),af(t)}default:try{return await sf(`You are a model recommendation advisor for Alibaba Cloud Model Studio. The candidates below are ALREADY ranked — do not reorder them. Write a recommendation reason for each.
155
+
156
+ The candidates occupy distinct quality-tier slots. Write each reason from its slot's perspective:
157
+ - primary (Best Pick): why this model is the best fit for the user's budget and quality preference
158
+ - runner-up (Runner-Up): a worthy alternative from a different quality tier — explain the tradeoff vs the best pick
159
+ - exploration (Alternative): a third-perspective choice — explain the scenario difference
160
+
161
+ Rules:
162
+ - reason and highlights MUST be in Simplified Chinese (简体中文)
163
+ - Each reason must explain how the model solves a specific aspect of the user's task — no generic praise ("性能强大", "效果好")
164
+ - The three reasons must take distinct angles
165
+ - If the intent is a pipeline (Complexity: pipeline), name the step each model serves (e.g. "用于第3步图生视频")
166
+ - Respond with ONLY JSON:
167
+ {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if(Z(n.signal),Q(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(Eu(`explain`,`llm-generate→template-text`,Q(e,`explain`))),af(t)}}}function lf(e){let t=e.model,n=t.profile,r=(n?.pipelineRole??[]).map(e=>`${e.from}→${e.to}: ${e.role}`).slice(0,3);return[` - ID: ${t.model}`,`Slot: ${e.slot}`,n?.oneLinePositioning?`Positioning: ${n.oneLinePositioning}`:`Description: ${t.description.slice(0,120)}`,n?.familyTier?`Tier: ${n.familyTier}`:``,t.prices?.length?`Price: ${t.prices[0].price}/${t.prices[0].unit}`:``,r.length?`Roles: ${r.join(`; `)}`:``,n?.notSuitableFor?.length?`NotSuitableFor: ${n.notSuitableFor.slice(0,3).join(`, `)}`:``].filter(Boolean).join(` | `)}function uf({step:e,candidates:t}){let n=`${e.inputModality.join(`/`)||`?`} → ${e.outputModality.join(`/`)||`?`}`;return[`Step ${e.index}: ${e.label} (${n}, ${e.capabilities.join(`+`)})`,...t.map(lf)].join(`
168
+ `)}function df(e){return af(e.candidates).map(t=>({...t,step:e.step.index}))}async function ff(e,t){if(e.every(e=>e.candidates.length===0))return e.map(()=>[]);let n;try{t.trace.performance.llmCalls++,n=Md(await t.llm.chat([{role:`system`,content:`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's task is a multi-step pipeline. For EACH step, the candidates are ALREADY selected — do not reorder, add or drop models. Write a recommendation reason for each candidate.
169
+
170
+ Rules:
171
+ - reason and highlights MUST be in Simplified Chinese (简体中文)
172
+ - primary: why this model fits THIS step of the user's task, and what it hands to / takes from the adjacent steps when relevant
173
+ - alternative: frame it positively — the concrete situation in which the user should pick it instead of the primary (e.g. 预算更紧/追求更高画质/需要更长时长/已有参考视频). Never argue against it or call it unsuitable; it was selected as a valid option
174
+ - Each reason at most 80 Chinese characters; be specific to the user's task; no generic praise ("性能强大", "效果好")
175
+ - highlights: 2-3 short phrases
176
+ - Respond with ONLY JSON:
177
+ {"steps":[{"index":1,"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${Pd(t.intent)}\n\nSelected candidates per step:\n${e.map(uf).join(`
178
+
179
+ `)}`}],{maxTokens:2048,stage:`step-explain`,signal:t.signal}))}catch(n){if(Z(t.signal),Q(n,`explain`).kind===`cancelled`)throw n;return t.trace.degradations.push(Eu(`explain`,`step-explain→template-text`,Q(n,`explain`))),e.map(df)}let r=/* @__PURE__ */ new Map;for(let e of n.steps??[])typeof e.index==`number`&&r.set(e.index,new Map((e.items??[]).map(e=>[e.model,e])));return e.map(e=>{let t=df(e),n=r.get(e.step.index);return t.map(e=>{let t=n?.get(e.model);return t?.reason?{...e,reason:t.reason,highlights:t.highlights?.length?t.highlights:e.highlights}:e})})}function pf(e){return e.inferenceMetadata?.request_modality??[]}function mf(e){return e.inferenceMetadata?.response_modality??[]}function hf(e,t){return t.length===0||e.length===0||t.some(t=>e.includes(t))}function gf(e,t,n){return e.capabilities.includes(t.primaryCapability)?n===`capability-only`?!0:hf(mf(e),t.outputModality)?n===`relaxed-input`||hf(pf(e),t.inputModality):!1:!1}const _f={向量检索:`语义重排`};function vf(e,t){let n=e.filter(t);return n.length>=2?n:e}function yf(e,t,n){let r=$u(e,t);for(let t of[`strict`,`relaxed-input`,`capability-only`]){let i=n.filter(n=>gf(n,e,t));if(i.length<2)continue;let a=e.scene;if(a){i=vf(i,e=>e.profile?.scenes?.includes(a)??!1);let e=_f[a];e&&(i=vf(i,t=>!(t.profile?.scenes?.includes(e)??!1)))}return i=vf(i,e=>Bu([e],r).length>0),{models:i,gate:t}}return{models:n.filter(t=>gf(t,e,`capability-only`)),gate:`capability-only`}}const bf={role:.35,scene:.2,tier:.2,price:.15,extras:.1},xf=/纯文[字本]|无图|仅[用靠]?文字|只有文字|无参考/;function Sf(e,t){if(t.inputModality.length>0&&t.inputModality.every(e=>e===`Text`)&&t.outputModality.some(e=>e===`Image`||e===`Video`)&&(e.profile?.notSuitableFor??[]).some(e=>xf.test(e)))return .25;let n=e.profile?.pipelineRole??[];if(n.length===0)return .5;let r=e=>t.outputModality.length===0||t.outputModality.includes(e),i=e=>t.inputModality.length===0||t.inputModality.includes(e);return n.some(e=>i(e.from)&&r(e.to))?1:n.some(e=>r(e.to))?.5:0}function Cf(e,t){let n=e.profile?.familyTier;return n?{flagship:{flagship:1,balanced:.6,lightweight:.3},"cost-optimized":{lightweight:1,balanced:.7,flagship:.4},balanced:{balanced:1,flagship:.85,lightweight:.7}}[t.qualityPreference]?.[n]??.7:.7}function wf(e){let t=e.prices?.[0],n=t?.price?Number.parseFloat(t.price):NaN;return Number.isFinite(n)?{value:n,unit:t.unit}:void 0}function Tf(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=wf(t);e&&n.set(e.unit,(n.get(e.unit)??0)+1)}let r=[...n.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0],i=e.map(wf).filter(e=>e!==void 0&&e.unit===r).map(e=>e.value),a=Math.min(...i),o=Math.max(...i);return e=>{let n=wf(e);if(!n||n.unit!==r||i.length<2||o===a)return .5;let s=1-(n.value-a)/(o-a);return t.budget===`low`?s:t.budget===`high`?1-s*.5:.5+s*.5}}function Ef(e,t,n){let r=t.capabilities.filter(e=>e!==t.primaryCapability),i=r.length+n.length;return i===0?1:(r.filter(t=>e.capabilities.includes(t)).length+n.filter(t=>e.features.includes(t)).length)/i}function Df(e,t,n){let r=$u(t,n),i=Qu(t,n),a=Tf(e,n);return e.map(e=>{let o=Sf(e,t),s=i.length===0||(e.profile?.scenes??[]).some(e=>i.includes(e))?1:.3,c=bf.role*o+bf.scene*s+bf.tier*Cf(e,n)+bf.price*a(e)+bf.extras*Ef(e,t,r.requiredFeatures);return e.profile?.profileCompleteness===`structured-only`&&(c*=.9),{model:e,score:c,role:o}}).sort((e,t)=>t.score-e.score||(wf(e.model)?.value??1/0)-(wf(t.model)?.value??1/0))}function Of(e){let[t,...n]=e;if(!t)return[];let r=n.filter(e=>e.role>=t.role),i=r.length>0?r:n,a=e=>e.model.profile?.familyTier??`unknown`,o=e=>e.model.family??e.model.provider,s=i.find(e=>a(e)!==a(t))??i.find(e=>o(e)!==o(t))??i[0];return s?[t,s]:[t]}const kf={Text:`文本`,Image:`图片`,Video:`视频`,Audio:`音频`};function Af(e,t){let n=[];for(let r=1;r<e.length;r++){let i=t[r-1],a=t[r];if(!i||!a)continue;let o=mf(i).length?mf(i):e[r-1].outputModality,s=e[r].inputModality.filter(e=>o.includes(e));if(s.length===0)continue;let c=pf(a);if(c.length>0&&!s.some(e=>c.includes(e))){let e=s.map(e=>kf[e]??e).join(`/`);n.push(`第${r}步 ${i.name} 输出${e},但第${r+1}步首选 ${a.name} 不接受${e}输入,衔接时需要转换或换用备选`)}}return n}function jf(e,t){return!t||e.models.length<2||e.gate===`capability-only`?`low`:e.gate===`strict`&&e.models.length>=3&&t.role===1?`high`:`medium`}const Mf=[`low`,`medium`,`high`];function Nf(e){return e.reduce((e,t)=>Mf.indexOf(t)<Mf.indexOf(e)?t:e,`high`)}async function Pf(e){let t=Xu(e.intent.segments),n=yd(e.models.filter(Lu),e.intent.modelPreference?.excludes??[]),r=Date.now(),i=t.map(t=>yf(t,e.intent,n));e.trace.performance.recallMs=Date.now()-r;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} recall] ${t[n].label}: pool=${i[n].models.length} gate=${i[n].gate} scene=${t[n].scene??`-`}`);let a=Date.now(),o=t.map((t,n)=>Df(i[n].models,t,e.intent));e.trace.performance.scoreMs=Date.now()-a;for(let n=0;n<t.length;n++){let r=o[n].slice(0,3).map(e=>`${e.model.model}(${e.score.toFixed(2)},role=${e.role})`).join(`, `);e.decisionLog?.push(`[step ${n+1} score] ${t[n].label}: ${r}`)}let s=Date.now(),c=o.map(t=>Of(t).slice(0,e.topN));e.trace.performance.rankMs=Date.now()-s;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} pick] ${t[n].label}: ${c[n].map(e=>e.model.model).join(` + `)}`);let l=t.map((e,t)=>({step:e,candidates:c[t].map((e,t)=>({model:e.model,hardScore:e.score,finalScore:e.score,rank:t+1,slot:t===0?`primary`:`alternative`}))})),u=Date.now(),d=await ff(l,e);e.trace.performance.explainMs=Date.now()-u;let f=t.map((e,t)=>({index:e.index,step:e.label,inputModality:e.inputModality,outputModality:e.outputModality,capabilities:e.capabilities,recommendations:d[t],candidatePool:i[t].models.length,confidence:jf(i[t],o[t][0]),gate:i[t].gate}));return{steps:f,warnings:Af(t,c.map(e=>e[0]?.model)),candidatePool:i.reduce((e,t)=>e+t.models.length,0),confidence:Nf(f.map(e=>e.confidence))}}function Ff(e,t){let{plan:n,intent:r}=e;if(n.recall===`template`&&r.sceneConfidence>=.8)return`high`;if(t.length<5&&n.recall!==`forced`)return`low`;let i=[...t].sort((e,t)=>t.finalScore-e.finalScore);return(i[0]?i[0].finalScore-(i[1]?.finalScore??0):0)>.2&&(i[0]?.finalScore??0)>.6||n.recall===`forced`?`high`:`medium`}function If(e,t){if(t){process.stderr.write(`[recommend:trace] ${JSON.stringify(e)}\n`);return}let n=[e.failure?`failed at ${e.failure.stage}`:e.routingReason??`?`,`${e.performance.totalMs}ms`,`llm=${e.performance.llmCalls}`];if(e.failure){let{status:t,kind:r}=e.failure;n.push(`error=${t?`${t} ${r}`:r}`)}e.degradations.length&&n.push(`degraded=${e.degradations.map(Du).join(`,`)}`),process.stderr.write(`[recommend] ${n.join(`, `)}\n`)}async function Lf(e,t,n){Z(t.signal);let r=Date.now(),i={timestamp:(/* @__PURE__ */ new Date()).toISOString(),input:e,performance:{llmCalls:0},degradations:[]},a=await t.catalog();Z(t.signal);let o=t.decisionLog??[],s=Date.now(),c;if(n)c=n;else{i.performance.llmCalls++;try{c=await Iu(t.llm,e,t.signal),Z(t.signal)}catch(e){let n=Q(e,`intent`);throw i.performance.intentMs=Date.now()-s,i.performance.totalMs=Date.now()-r,i.failure={stage:`intent`,kind:n.kind,status:n.status,code:n.code,requestId:n.requestId,message:n.message},If(i,t.verbose??!1),n}}i.performance.intentMs=Date.now()-s,i.matchedScenes=c.matchedScenes,i.sceneConfidence=c.sceneConfidence,o.push(`[intent] complexity=${c.complexity} scenes=[${c.matchedScenes.join(`,`)}] conf=${c.sceneConfidence} caps=[${c.requiredCapabilities.join(`,`)}] budget=${c.budget} quality=${c.qualityPreference}`);let l=pd(c,a,t.topN);if(i.routingReason=l.routingReason,o.push(`[route] ${l.routingReason}${l.clarify?` → clarify`:``}`),l.clarify)return i.performance.totalMs=Date.now()-r,If(i,t.verbose??!1),{type:`need_clarify`,...l.clarify,intent:c};let u={input:e,intent:c,models:a,plan:l,topN:l.topN,llm:t.llm,signal:t.signal,trace:i,decisionLog:o};if(l.stepwise){let e=await Pf(u);return Z(t.signal),i.performance.totalMs=Date.now()-r,If(i,t.verbose??!1),{type:`result`,recommendations:e.steps.flatMap(e=>e.recommendations),confidence:e.confidence,routingReason:l.routingReason,candidatePool:e.candidatePool,intent:c,degradations:[...i.degradations],steps:e.steps,warnings:e.warnings}}let d=od(c),f=Date.now(),p=jd(l.recall,c,a,l.topN);i.performance.recallMs=Date.now()-f,o.push(`[recall] strategy=${l.recall} pool=${p.length}`);let m=Date.now(),h=await qd(l.score,p,u,d);Z(t.signal),i.performance.scoreMs=Date.now()-m,o.push(`[score] strategy=${l.score} top=${h.slice(0,3).map(e=>`${e.model.model}(${e.finalScore.toFixed(2)})`).join(`, `)}`);let g=Date.now(),_=$d(l.rank,h,l.topN,l.fairness,c);i.performance.rankMs=Date.now()-g,o.push(`[rank] ${_.map(e=>`${e.model.model}/${e.slot}`).join(`, `)}`);let v=Date.now(),y=await cf(l.explain,_,u);return Z(t.signal),i.performance.explainMs=Date.now()-v,i.performance.totalMs=Date.now()-r,If(i,t.verbose??!1),{type:`result`,recommendations:y,confidence:Ff(u,h),routingReason:l.routingReason,candidatePool:p.length,intent:c,degradations:[...i.degradations]}}const Rf=/* @__PURE__ */ new Set([`bailian-model-recommend`]);function zf(){let e=(process.env.BAILIAN_SKILL_EXCLUDE??``).split(`,`).map(e=>e.trim()).filter(Boolean);return/* @__PURE__ */ new Set([...Rf,...e])}function Bf(){return process.env.BAILIAN_SKILLS_DIR||A(I(),`skills`)}function Vf(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=t[1].split(/\r?\n/),r={},i=``,a=!1;for(let e of n){if(a&&/^\s+/.test(e)){r[i]+=(r[i]?` `:``)+e.trim();continue}a=!1;let t=e.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)/);if(!t)continue;let[,n,o]=t;o===`>-`||o===`|`||o===`>`||o===`|-`?(i=n,r[n]=``,a=!0):r[n]=o.trim()}return r}function Hf(){let e=Bf();if(!S(e))return[];let t=[],n;try{n=E(e)}catch{return[]}let r=zf();for(let i of n){let n=A(e,i),a=A(n,`SKILL.md`);if(!S(a))continue;let o;try{o=T(a,`utf-8`)}catch{continue}let s=Vf(o),c=s.name||i;if(r.has(i)||r.has(c))continue;let l=s.description||``;l&&t.push({name:c,description:l,basePath:n})}return t}function Uf(e){if(e.length===0)return``;let t=[`## Available Skills`,"When the user's request matches a skill's description, call the `use_skill` tool with that skill's name to load its full instructions.",``],n=0;for(let r of e){let e=r.description,i=8e3-n;i<=0?e=`(description truncated)`:e.length>i&&(e=e.slice(0,i)+`…`),n+=e.length,t.push(`- **${r.name}**: ${e}`)}return t.join(`
180
+ `)}const Wf=65536;function Gf(e,t){let n=Kf(Bf());if(!n)return{error:`skills directory not found`};let r=t?Kf(t)??n:n,i=j(r,e);if(!qf(i,n))return{error:`path escapes the skills sandbox: ${e}`};let a=Kf(i);return a&&!qf(a,n)?{error:`symlink escapes the skills sandbox: ${e}`}:{resolved:i}}function Kf(e){try{return me(e)}catch{return}}function qf(e,t){return e===t||e.startsWith(t+Ce)}function Jf(e,t,n){let{resolved:r,error:i}=Gf(e,n);if(i||!r)return{ok:!1,error:i??`resolve failed`};let a=t.toLowerCase();try{let e=he(r);if(!e.isFile())return{ok:!1,error:`not a regular file`};if(e.size>4194304)return{ok:!1,error:`file too large to search (${e.size} bytes)`};let t=T(r,`utf-8`).split(`
181
+ `),n=[],i=0;for(let e=0;e<t.length;e++)t[e].toLowerCase().includes(a)&&(i++,n.length<40&&n.push(`${e+1}: ${t[e]}`));return{ok:!0,matches:n,totalMatches:i}}catch(e){return{ok:!1,error:e.message}}}function Yf(e,t){let{resolved:n,error:r}=Gf(e,t);if(r||!n)return{ok:!1,error:r??`resolve failed`};try{if(!he(n).isFile())return{ok:!1,error:`not a regular file`};let e=T(n),t=e.length>Wf;return{ok:!0,content:e.subarray(0,Wf).toString(`utf-8`),truncated:t}}catch(e){return{ok:!1,error:e.message}}}function Xf(e){return{originalInput:e,clarifications:[]}}function Zf(e){if(e.clarifications.length===0)return e.originalInput;let t=e.clarifications.map(e=>`- ${e.question} → ${e.answer}`);return`${e.originalInput}\n\n补充说明:\n${t.join(`
182
+ `)}`}const Qf=[{type:`function`,function:{name:`recommend`,description:`Recommend models for the user's request. Takes no arguments: the system automatically passes the user's original request plus every answer collected via ask_user. Returns top-N recommendations + decision signals (confidence/candidatePool), or need_clarify (user clarification required). Also covers comparison/alternative requests.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`use_skill`,description:`Load a skill's full instructions (SKILL.md) by name. Use this when the user's request matches a skill in the Available Skills list — e.g. asking about a specific model's usage, API parameters, calling examples, pricing details, or any documentation lookup. Returns the skill's instructions and its base path; then follow those instructions using read_file.`,parameters:{type:`object`,properties:{skill:{type:`string`,description:`The skill name from the Available Skills list`}},required:[`skill`]}}},{type:`function`,function:{name:`search_files`,description:`Search a file inside the loaded skill for a keyword (case-insensitive substring) and return the matching lines. PREFERRED over read_file for large data files like models.jsonl or families.jsonl — those are truncated when read whole, but search scans the full file. Example: search_files(path='models/models.jsonl', pattern='qwen-image').`,parameters:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the skill's base path`},pattern:{type:`string`,description:`Keyword to search for (case-insensitive substring)`}},required:[`path`,`pattern`]}}},{type:`function`,function:{name:`read_file`,description:`Read a file inside the loaded skill's directory (or the skills root). Use relative paths as instructed by the skill's SKILL.md (e.g. 'models/models.jsonl', 'wiki/index.md'). Only use after loading a skill via use_skill.`,parameters:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the skill's base path`}},required:[`path`]}}},{type:`function`,function:{name:`ask_user`,description:`Ask the user a multiple-choice question to resolve ambiguity. Only use when different choices lead to completely different recommendations; max 2 rounds.`,parameters:{type:`object`,properties:{question:{type:`string`},options:{type:`array`,items:{type:`string`},maxItems:4},default_if_skip:{type:`string`}},required:[`question`,`options`,`default_if_skip`]}}}];async function $f(e,t,n){Z(t.signal);let r;try{if(r=e.function.arguments.trim()?JSON.parse(e.function.arguments):{},!r||typeof r!=`object`||Array.isArray(r))throw Error(`参数必须是对象`)}catch{return{result:JSON.stringify({error:`invalid tool arguments`})}}switch(e.function.name){case`recommend`:{t.onProgress?.(`running recommendation engine`);let e=await Lf(Zf(n),t);if(e.type===`need_clarify`)return{recommendResult:e,result:JSON.stringify({type:`need_clarify`,question:e.question,options:e.options,default_if_skip:e.defaultIfSkip,impact:e.impact})};let r=e=>({model:e.model,name:e.name,reason:e.reason,highlights:e.highlights,slot:e.slot}),i=e.steps?{steps:e.steps.map(e=>({index:e.index,step:e.step,io:`${e.inputModality.join(`/`)} → ${e.outputModality.join(`/`)}`,confidence:e.confidence,recommendations:e.recommendations.map(r)})),warnings:e.warnings?.length?e.warnings:void 0}:{recommendations:e.recommendations.map(r)};return{result:JSON.stringify({type:`result`,confidence:e.confidence,routingReason:e.routingReason,candidatePool:e.candidatePool,...i}),recommendResult:e}}case`use_skill`:{let e=typeof r.skill==`string`?r.skill.trim():``;if(!e)return{result:JSON.stringify({error:`missing skill name`})};let i=Hf(),a=i.find(t=>t.name===e);if(!a){let t=i.map(e=>e.name);return{result:JSON.stringify({error:`Skill "${e}" not found. Available skills: ${t.join(`, `)||`(none)`}`})}}t.onProgress?.(`matched skill "${a.name}"`);let o;try{o=T(A(a.basePath,`SKILL.md`),`utf-8`)}catch(e){return{result:JSON.stringify({error:`Failed to read SKILL.md: ${e.message}`})}}return n.activeSkill=a,t.onProgress?.(`loaded skill "${a.name}" (SKILL.md, ${o.length} chars)`),{result:JSON.stringify({type:`skill_loaded`,skill:a.name,basePath:a.basePath,instructions:o})}}case`read_file`:{let e=typeof r.path==`string`?r.path.trim():``;if(!e)return{result:JSON.stringify({error:`missing file path`})};let i=n.activeSkill?.basePath;t.onProgress?.(`reading ${e}`);let a=Yf(e,i);return a.ok?(t.onProgress?.(`read ${e} (${a.content?.length??0} chars${a.truncated?`, truncated`:``})`),{result:JSON.stringify({type:`file_content`,path:e,truncated:a.truncated??!1,content:a.content})}):(t.onProgress?.(`read failed: ${a.error}`),{result:JSON.stringify({error:a.error})})}case`search_files`:{let e=typeof r.path==`string`?r.path.trim():``,i=typeof r.pattern==`string`?r.pattern.trim():``;if(!e||!i)return{result:JSON.stringify({error:`missing path or pattern`})};t.onProgress?.(`searching ${e} for "${i}"`);let a=Jf(e,i,n.activeSkill?.basePath);return a.ok?(t.onProgress?.(`search ${e}: ${a.totalMatches} match(es)`),{result:JSON.stringify({type:`search_results`,path:e,pattern:i,totalMatches:a.totalMatches,returned:a.matches?.length??0,matches:a.matches})}):(t.onProgress?.(`search failed: ${a.error}`),{result:JSON.stringify({error:a.error})})}case`ask_user`:{let e=typeof r.question==`string`?r.question:``;if(!e.trim()||!Array.isArray(r.options)||!r.options.every(e=>typeof e==`string`)||typeof r.default_if_skip!=`string`)return{result:JSON.stringify({error:`invalid clarification question/options/default`})};let i=await t.interaction.ask({signal:t.signal,question:e,options:Array.isArray(r.options)?r.options:[],defaultIfSkip:typeof r.default_if_skip==`string`?r.default_if_skip:``});return Z(t.signal),i.trim()&&n.clarifications.push({question:e,answer:i.trim()}),{result:JSON.stringify({type:`user_answer`,answer:i,note:`Recorded. Call recommend again (no arguments) to apply it.`})}}default:return{result:JSON.stringify({error:`unknown tool: ${e.function.name}`})}}}function ep(){let e=Uf(Hf());return`You are an AI model selection assistant for Alibaba Cloud Model Studio. You help users find the best model via tools.
183
+
184
+ ## Workflow
185
+ 1. FIRST, classify the request type:
186
+ - **Documentation/usage query**: the user mentions a SPECIFIC MODEL NAME (e.g. "qwen-max", "Wan2.0-T2I-Turbo", "cosyvoice-v3-flash", "qwen-image系列") AND asks about that model's info/price/usage/calling examples/API parameters → call use_skill("bailian-docs-llm-wiki"), then use read_file/search_files to find the answer. NEVER call recommend for this type. IMPORTANT: if no specific model name is mentioned, this is NOT a doc query.
187
+ - **Recommendation query** (user describes a need or task, possibly vague, wants model suggestions): 推荐, 选, 有没有, 哪个好, 对比, 更便宜, 做个XX, 帮我XX, 用什么模型 → call recommend. This includes ALL vague/short requests like "推荐一个", "做个视频", "做个电商商品主图" — these are recommendation requests, NOT documentation queries.
188
+ - **CRITICAL**: this agent IS the model-recommendation capability itself. For recommendation-type requests you MUST call the recommend tool — NEVER call use_skill for a skill whose description mentions model recommendation/selection/comparison, even if the user's request matches that skill's description. use_skill is only for documentation/data lookup (see below).
189
+ - If truly ambiguous → prefer recommend
190
+ - CRITICAL: for ANY request that describes a task or need (even extremely short ones like "推荐一个" or "做个视频"), you MUST call recommend as your FIRST action. Do NOT answer directly, do NOT ask the user yourself, do NOT call ask_user before recommend — the recommend tool itself decides whether clarification is needed and returns need_clarify if so. Answering a recommendation request without calling recommend is always wrong.
191
+ 2. Decide next step based on the result:
192
+ - type: "need_clarify" → call ask_user (pass through question/options/default_if_skip), then call recommend again with no arguments; the recorded answer is applied automatically (max 2 clarifications per session)
193
+ - type: "result" → output the final answer directly. Calling recommend again without a new ask_user answer returns the same result, so never re-call it just to retry
194
+ - type: "skill_loaded" → read the instructions carefully, then use read_file to access the referenced data files. Follow the skill's lookup flow step by step
195
+ - type: "file_content" → use the content to answer the user's question
196
+ 3. Final answer: summarize in Simplified Chinese. Do NOT repeat raw tool JSON. If confidence is "low", say so briefly
197
+ - If the result has "steps" (a multi-step plan): present it step by step in order — for each step give the primary model and its alternative with the trade-off, and pass on any "warnings" about hand-offs between steps
198
+
199
+ ## Skill usage rules
200
+ - use_skill is ONLY for documentation/data lookup skills (e.g. bailian-docs-llm-wiki). Never activate skills that overlap with your own capabilities — model recommendation, selection, comparison, or "what model to use" decisions are always handled by the recommend tool, not by a skill
201
+ - After use_skill returns, you MUST follow the skill's instructions to locate information — do NOT guess file paths or fabricate content
202
+ - Use read_file with relative paths as directed by the skill (e.g. "models/models.jsonl", "groups/wan-text-to-image.json")
203
+ - For large data files (models.jsonl, families.jsonl), ALWAYS use search_files with a keyword instead of read_file — read_file truncates large files and will miss entries; search_files scans the full file and returns matching lines
204
+ - NEVER fabricate API code, parameter names, or pricing. Only report what you find in the files
205
+ - If the skill's data doesn't contain the answer, say so honestly and suggest the user check the official docs
206
+
207
+ ${e?e+`
208
+
209
+ `:``}## Discipline
210
+ - Only ask a question if it significantly narrows the candidate pool
211
+ - Ask about business scenarios, NOT technical parameters (e.g. never ask "how many tokens of context do you need")
212
+ - Never fabricate model names not returned by tools
213
+ - If the input is NOT a model request (greetings, jokes, casual chat), do NOT call any tool: respond naturally and briefly in Simplified Chinese, then introduce yourself in one sentence as the Bailian model selection assistant — mention that you can recommend models for any scenario (text/image/video/audio, single model or multi-step pipelines), compare models, look up specific models, and find cheaper alternatives — and guide the user with one concrete example question (e.g. "你可以试试问我:推荐一个写代码的模型")
214
+ - Everything else — including vague requests like "推荐一个", "有什么好模型", "帮我选个模型" — MUST go through the recommend tool`}async function tp(e,t,n){let r=[{role:`system`,content:ep()},{role:`user`,content:e}],i=Xf(e),a=[],o,s=0,c=0,l=e=>{a.push(e),n?.(e)};try{for(let e=0;e<10;e++){c=e,Z(t.signal);let n;try{n=await t.llm.chatWithTools(r,Qf,{stage:`agent`,signal:t.signal}),Z(t.signal)}catch(n){Z(t.signal);let r=Q(n,`agent`);if(r.kind===`cancelled`)throw r;if(r.fatal){if(!o)throw r;let t=Eu(`agent`,`agent-summary→engine-result`,r);return process.stderr.write(`[recommend] agent loop failed (${r.tag}), using the recommendation already computed\n`),l({turn:e,type:`fallback`,reason:`agent_error_existing_result`}),{finalText:``,recommendResult:o,turns:e,degradations:[t],trajectory:a}}process.stderr.write(`[recommend] agent loop failed (${r.tag}), falling back to engine: ${r.message}\n`);let s=await Lf(Zf(i),t);return l({turn:e,type:`fallback`,reason:`agent_error_engine_rerun`}),{finalText:``,recommendResult:s,turns:e,degradations:[Eu(`agent`,`agent→engine-rerun`,r)],trajectory:a}}if(!n.toolCalls.length)return l({turn:e,type:`final_answer`,reason:n.content.trim()?`completed`:`empty_answer`}),{finalText:n.content,recommendResult:o,turns:e+1,degradations:[],trajectory:a};r.push({role:`assistant`,content:n.content,tool_calls:n.toolCalls});for(let t of n.toolCalls){let n;try{n=JSON.parse(t.function.arguments||`{}`)}catch{}l({turn:e,type:`tool_call`,callId:t.id,tool:t.function.name,args:n})}for(let a of n.toolCalls)try{if(Z(t.signal),a.function.name===`ask_user`&&s>=2){let t={error:`clarify budget exhausted; proceed with defaults`};l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:`rejected`,reason:`clarify_budget`,result:t}),r.push({role:`tool`,tool_call_id:a.id,content:JSON.stringify(t)});continue}let n=await $f(a,t,i);Z(t.signal),n.recommendResult&&(o=n.recommendResult);let c=JSON.parse(n.result),u=c.error?`error`:`success`;a.function.name===`ask_user`&&u===`success`&&s++,l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:u,result:c,resultType:typeof c.type==`string`?c.type:void 0,degradations:n.recommendResult?.type===`result`?n.recommendResult.degradations:void 0}),r.push({role:`tool`,tool_call_id:a.id,content:n.result})}catch(n){let r=t.signal?.aborted||Q(n,`agent`).kind===`cancelled`;throw l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:r?`cancelled`:`error`,reason:n instanceof Error?n.message:String(n)}),n}}return c=10,Z(t.signal),l({turn:10,type:`fallback`,reason:`turn_budget`}),o?{finalText:``,recommendResult:o,turns:10,degradations:[],trajectory:a}:{finalText:``,recommendResult:await Lf(Zf(i),t),turns:10,degradations:[],trajectory:a}}catch(e){let n=t.signal?.aborted||Q(e,`agent`).kind===`cancelled`,r=new Set(a.filter(e=>e.type===`tool_result`).map(e=>`${e.turn}:${e.callId}`));for(let e of a.filter(e=>e.type===`tool_call`&&!r.has(`${e.turn}:${e.callId}`)))l({turn:e.turn,type:`tool_result`,tool:e.tool,callId:e.callId,status:n?`cancelled`:`rejected`,reason:`run_terminated`});throw l({turn:c,type:n?`cancelled`:`error`,reason:e instanceof Error?e.message:String(e)}),Z(t.signal),e}}const np=`qwen-flash-2025-07-28`;function rp(e){let{baseUrl:t,apiKey:n,defaultModel:r=np,timeoutMs:i=6e4,enableThinking:a,thinkingStages:o,thinkingLog:s,onThinking:c}=e,l=`${t.replace(/\/$/,``)}/compatible-mode/v1/chat/completions`;async function u(t,r,a){Z(r.signal);let o=new AbortController,s=setTimeout(()=>o.abort(),i),c=r.signal?AbortSignal.any([r.signal,o.signal]):o.signal;try{e.onRequest?.(r.stage??`llm`);let i=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:c});if(!i.ok){let e=await i.text(),t={message:e.slice(0,200)};try{t=JSON.parse(e)}catch{}throw ip(t,i.status,i.headers.get(`x-request-id`)??void 0)}let o=await a(i,c);return Z(r.signal),o}catch(e){throw Z(r.signal),o.signal.aborted?new X(`timeout`,`LLM request timed out after ${i}ms`,{cause:e}):e instanceof X?e:e instanceof SyntaxError?new X(`parse`,`LLM 响应不是有效 JSON`,{cause:e}):new X(`network`,`LLM request failed: ${e?.cause?.code??e?.message}`,{cause:e})}finally{clearTimeout(s)}}async function d(e,t={}){return u(e,t,async e=>{let n=await e.json();if(n.error)throw ip(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.[0];if(ap(r?.finish_reason),!r?.message)throw new X(`parse`,`LLM 响应缺少 message`);if(op(r.message.tool_calls??[]),!r.message.content?.trim()&&!r.message.tool_calls?.length)throw new X(`parse`,`LLM 返回空响应`);let i=r.message.reasoning_content;return s&&i&&s.push({stage:t.stage??`llm`,content:i}),n})}async function f(e,t,n={}){let i=n.stage??(t?`agent`:`llm`);return u({model:n.model??r,messages:e.map(sp),...t?{tools:t}:{},temperature:n.temperature??0,max_tokens:n.maxTokens??4096,stream:!0,enable_thinking:!0},{...n,stage:i},async(e,t)=>{if(!e.body)throw new X(`parse`,`SSE 响应缺少正文`);let n=e.body.getReader(),r=new TextDecoder,a=``,o=``,l=``,u=!1,d=``,f=[],p=/* @__PURE__ */ new Map,m=()=>{if(!f.length)return;let t=f.join(`
215
+ `);if(f=[],t.trim()===`[DONE]`){u=!0;return}let n=JSON.parse(t);if(n.error||d===`error`)throw ip(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.find(e=>e.index===0||e.index===void 0);ap(r?.finish_reason);let a=r?.delta;if(a){a.reasoning_content&&(l+=a.reasoning_content,c?.(i,a.reasoning_content)),o+=a.content??``;for(let e of a.tool_calls??[]){let t=e.index;if(t===void 0||!Number.isInteger(t)||t<0)throw new X(`parse`,`工具片段缺少有效 index`);let n=p.get(t)??{id:``,name:``,arguments:``};if(e.id){if(n.id&&n.id!==e.id)throw new X(`parse`,`同一工具 index 返回不同 id`);n.id=e.id}n.name+=e.function?.name??``,n.arguments+=e.function?.arguments??``,p.set(t,n)}}},h=e=>{let t=e.replace(/\r$/,``);t?t.startsWith(`data:`)?f.push(t.slice(5).replace(/^ /,``)):t.startsWith(`event:`)&&(d=t.slice(6).trim()):(m(),d=``)},g=()=>{n.cancel().catch(()=>{})};t.addEventListener(`abort`,g,{once:!0});try{for(;!u;){t.throwIfAborted();let{done:e,value:i}=await n.read();t.throwIfAborted(),a+=e?r.decode():r.decode(i,{stream:!0});let o=a.split(`
216
+ `);a=o.pop()??``;for(let e of o)if(h(e),u)break;if(e&&(!u&&a&&h(a),u||m(),!u))throw new X(`parse`,`SSE 在完成标记前断流`)}let e=[...p.entries()].sort(([e],[t])=>e-t).map(([,e])=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.arguments}}));if(op(e),!o.trim()&&!e.length)throw new X(`parse`,`SSE 返回空响应`);return s&&l&&s.push({stage:i,content:l}),{content:o,toolCalls:e}}finally{t.removeEventListener(`abort`,g),await n.cancel().catch(()=>{}),n.releaseLock()}})}let p=e=>e?.stage!==void 0&&o?.includes(e.stage)||a===!0;return{async chat(e,t){return p(t)?(await f(e,void 0,t)).content:(await d({model:t?.model??r,messages:e,temperature:t?.temperature??0,max_tokens:t?.maxTokens??4096},{...t})).choices?.[0]?.message?.content??``},async chatJson(e,t){let n=await this.chat(e,t);try{return Md(n)}catch{let r=await this.chat([...e,{role:`assistant`,content:n},{role:`user`,content:`IMPORTANT: Your previous response was not valid JSON. Respond with ONLY a valid JSON object, no other text.`}],t);try{return Md(r)}catch(e){throw new X(`parse`,`LLM returned invalid JSON twice: ${r.slice(0,120)}`,{cause:e})}}},async chatWithTools(e,t,n){if(p(n))return f(e,t,n);let i=(await d({model:n?.model??r,messages:e.map(sp),tools:t,temperature:0,max_tokens:4096},{...n,stage:n?.stage??`agent`})).choices?.[0]?.message;return{content:i?.content??``,toolCalls:i?.tool_calls??[]}}}}function ip(e,t,n){let r=e&&typeof e==`object`?e:{},i=r.error&&typeof r.error==`object`?r.error:r,a=typeof i.code==`string`?i.code:void 0;return new X(t?Tu(t):/invalid.?api.?key|unauthorized|accessdenied|forbidden/i.test(a??``)?`auth`:/quota|throttl|rate.?limit/i.test(a??``)?`rate_limit`:`http`,`LLM request failed: ${typeof i.message==`string`?i.message:typeof r.error==`string`?r.error:`服务端错误`}`,{status:t,code:a,requestId:typeof r.request_id==`string`?r.request_id:n})}function ap(e){if(e&&e!==`stop`&&e!==`tool_calls`)throw new X(`parse`,`LLM 响应未完整结束: ${e}`)}function op(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(!n.id||t.has(n.id)||!n.function?.name||n.type!==`function`)throw new X(`parse`,`工具调用缺少标识或标识重复`);t.add(n.id);let e;try{e=JSON.parse(n.function.arguments)}catch(e){throw new X(`parse`,`工具参数不完整`,{cause:e})}if(!e||typeof e!=`object`||Array.isArray(e))throw new X(`parse`,`工具参数必须是 JSON 对象`)}}function sp(e){let t={role:e.role,content:e.content};return e.tool_call_id&&(t.tool_call_id=e.tool_call_id),e.tool_calls&&(t.tool_calls=e.tool_calls),t}function cp(){return A(I(),`skills/bailian-docs-llm-wiki`,`models`)}const lp=/-\d{4}-\d{2}-\d{2}$/;let up=null,dp=null;function fp(e){if(!S(e))return[];let t=[];for(let n of T(e,`utf-8`).split(`
217
+ `))if(n.trim())try{t.push(JSON.parse(n))}catch{}return t}function pp(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(lp,``);return n===e||!t.has(n)})}async function mp(e=cp()){if(up)return up;let t=fp(A(e,`models.jsonl`));if(t.length===0)throw Error(`No model catalog found at ${A(e,`models.jsonl`)}. Run any bl advisor/agent command once to sync wiki data.`);return up=pp(t),up}async function hp(e=cp()){if(dp)return dp;let t=fp(A(e,`families.jsonl`));return dp=new Map(t.map(e=>[e.slug,e])),dp}function gp(){up=null,dp=null}function _p(){return{async ask({question:e,options:t,defaultIfSkip:n,signal:r}){Z(r);let i=Pe({input:process.stdin,output:process.stderr});try{for(process.stderr.write(`\n${e}\n`),t.forEach((e,t)=>{let r=e===n;process.stderr.write(` ${t+1}. ${e}${r?` (default)`:``}\n`)}),process.stderr.write(` 输入序号选择,回车使用默认,或直接输入文字描述你的需求
218
+ `);;){let e=(await i.question(`Select: `,{signal:r})).trim();if(Z(r),!e)return n;if(/^\d+$/.test(e)){let n=Number.parseInt(e,10)-1;if(n>=0&&n<t.length)return t[n];process.stderr.write(` 请输入 1-${t.length} 之间的序号,或直接输入文字描述\n`);continue}return e}}finally{i.close()}}}}function vp(){return{async ask({question:e,defaultIfSkip:t,signal:n}){return Z(n),process.stderr.write(`[recommend] non-interactive, "${e}" → default: ${t}\n`),t}}}function $(){return A(I(),`skills`)}function yp(){return A($(),`skill-lock.json`)}function bp(){return{version:1,skills:{}}}function xp(){let e=yp();if(!S(e))return bp();try{let t=JSON.parse(T(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?bp():t}catch{return bp()}}function Sp(e){w($(),{recursive:!0}),_e(yp(),JSON.stringify(e,null,2)+`
219
+ `)}function Cp(e,t){let n=xp();n.skills[e]={...n.skills[e],...t},Sp(n)}const wp=`BL_SKIP_HOST_AGENTS`,Tp=[`CLAUDE_CONFIG_DIR`,`CODEX_HOME`,`VIBE_HOME`,`HERMES_HOME`,`AUTOHAND_HOME`,`GROK_HOME`,`DSH_HOME`,`OPENCLAW_CONFIG_PATH`,`ZCODE_HOME`,`APPDATA`,`LOCALAPPDATA`,`FLATPAK_XDG_CONFIG_HOME`,`PI_CODING_AGENT_DIR`];function Ep(){let e=Fe(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||A(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:A(e,r,`skills`),detectDirs:[A(e,r)]}),i=(t,n)=>t?.trim()||A(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:A(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>A(e,t)),s=o.find(e=>S(e))??o[0],c=[A(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(A(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(A(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:A(e,`.agents`,`skills`),detectDirs:[A(e,`.agents`),A(e,`.cline`),A(e,`.dexto`),A(e,`.firebender`),A(e,`.kimi-code`),A(e,`.kimi`),A(e,`.loaf`),A(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:A(n,`agents`,`skills`),detectDirs:[A(n,`agents`),A(n,`amp`),A(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:A(e,`.astrbot`,`data`,`skills`),detectDirs:[A(t,`data`,`skills`),A(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:A(e,`.codebuddy`,`skills`),detectDirs:[A(t,`.codebuddy`),A(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:A(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:A(e,`.continue`,`skills`),detectDirs:[A(t,`.continue`),A(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:A(e,`.deepagents`,`agent`,`skills`),detectDirs:[A(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:A(n,`devin`,`skills`),detectDirs:[A(n,`devin`)]},r(`droid`,`Droid`,`.factory`),a(`dsh`,`DeepSeek DSH`,i(process.env.DSH_HOME,`.dsh`)),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:A(n,`goose`,`skills`),detectDirs:[A(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,Bl(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:A(e,`.jazz`,`skills`),detectDirs:[A(e,`.jazz`),A(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:A(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[A(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:A(e,`.minimax`,`skills`),detectDirs:[A(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:A(n,`opencode`,`skills`),detectDirs:[A(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:A(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:A(e,`.tabnine`,`agent`,`skills`),detectDirs:[A(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cli`,`Trae CLI`,`.traecli`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),r(`workbuddy`,`Tencent WorkBuddy`,`.workbuddy`),{id:`zcode`,displayName:`ZCode`,skillsDir:A(e,`.zcode`,`skills`),detectDirs:[A(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function Dp(e){let t=j(e);try{return me(t)}catch{let e=[],n=t;for(;n!==k(n);){if(S(n))try{return A(me(n),...e.reverse())}catch{break}e.push(be(n)),n=k(n)}return t}}function Op(e,t){let n=Dp(e),r=Dp(t);return n===r||n.startsWith(r+Ce)}function kp(e){if(!xe(e)||Op(e,Fe()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&Op(e,t))}function Ap(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!kp(e)}function jp(){return Ep().filter(e=>e.detectDirs.some(e=>Ap(e)&&S(e)))}function Mp(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function Np(e){let t=$();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+Ce)}return e===t||e.startsWith(t+Ce)}function Pp(e){try{if(!C(e).isSymbolicLink())return!1;let t=pe(e);return Np(xe(t)?t:j(k(e),t))}catch{return!1}}function Fp(e,t){if(!t.some(t=>Mp(t,e)))return!1;try{return C(e).isDirectory()}catch{return!1}}function Ip(e){try{return C(e).isDirectory()?S(A(e,`SKILL.md`)):!1}catch{return!1}}const Lp=`existing file/dir not managed by bl skill`;function Rp(e,t=jp(),n=[]){let r=A($(),e),i=[];for(let a of t){let t=A(a.skillsDir,e);try{let e=!1;try{C(t),e=!0}catch{}if(e){if(Pp(t))O(t);else if(Fp(t,n))O(t,{recursive:!0,force:!0});else if(Ip(t))O(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:Lp});continue}}w(a.skillsDir,{recursive:!0});try{ge(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{ue(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function zp(e,t=jp(),n=[]){let r=Rp(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===Lp).map(e=>e.path),s=n.filter(e=>!a.some(t=>Mp(t,e))&&!o.some(t=>Mp(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function Bp(e,t=[]){let n=[],r=new Set(t);for(let t of Ep())r.add(A(t.skillsDir,e));for(let e of r)try{let r;try{r=C(e)}catch{continue}r.isSymbolicLink()?Pp(e)&&n.push(e):t.some(t=>Mp(t,e))&&n.push(e)}catch{}return n}function Vp(e,t=[]){let n=[];for(let r of Bp(e,t))try{if(Pp(r))O(r);else if(!C(r).isSymbolicLink()&&t.some(e=>Mp(e,r)))O(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function Hp(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function Up(e,t){let n=Re.extract();n.on(`entry`,(e,r,i)=>{if(!Hp(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=A(t,e.name);if(e.type===`directory`){w(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}w(k(a),{recursive:!0});let o=fe(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await Ie(ye.from(e),Le(),n)}function Wp(e){let t=[],n=r=>{for(let i of E(r?A(e,r):e,{withFileTypes:!0})){let e=r?`${r}/${i.name}`:i.name;i.isDirectory()?n(e):i.isFile()&&t.push(e)}};n(``),t.sort((e,t)=>e<t?-1:+(e>t));let r=Me(`sha256`);for(let n of t)r.update(n),r.update(T(A(e,n)));return`sha256:${r.digest(`hex`)}`}function Gp(e,t,n=259){let r,i=a=>{for(let o of E(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=A(a,o.name),c=Se(e,s);for(let e of t){let t=A(e,c).length;t>n&&t>(r?.pathLength??0)&&(r={root:e,relativePath:c,pathLength:t})}o.isDirectory()&&i(s)}};for(let e of t)e.length>n&&e.length>(r?.pathLength??0)&&(r={root:e,relativePath:``,pathLength:e.length});return i(e),r}function Kp(e){let t=[],n=r=>{for(let i of E(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=A(r,i.name),o=Se(e,a);i.isDirectory()?(t.push({relativePath:o,type:`directory`}),n(a)):i.isFile()&&t.push({relativePath:o,type:`file`})}};return n(e),t}function qp(e,t){let n=Kp(e),r=new Set(n.map(e=>e.relativePath));w(t,{recursive:!0});for(let r of n){let n=A(e,r.relativePath),i=A(t,r.relativePath);if(S(i)){let e=C(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&O(i,{recursive:!0,force:!0})}r.type===`directory`?w(i,{recursive:!0}):(w(k(i),{recursive:!0}),le(n,i))}let i=Kp(t).filter(e=>!r.has(e.relativePath)).sort((e,t)=>t.relativePath.length-e.relativePath.length);for(let e of i)O(A(t,e.relativePath),{recursive:!0,force:!0})}function Jp(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function Yp(e){try{S(e)&&O(e,{recursive:!0,force:!0})}catch{}}function Xp(e,t,n={}){w(k(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(S(t))try{D(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!Jp(i))throw i;try{qp(t,r),qp(e,t),Yp(r);return}catch(e){try{S(r)&&qp(r,t)}catch{}throw Error(`Skill directory is in use and could not be updated in place. Close running agent hosts and retry. / Skill 目录正被占用,无法原地更新;请关闭正在运行的 Agent 后重试。 ${e instanceof Error?e.message:String(e)}`,{cause:e})}}try{D(e,t)}catch(e){throw S(r)&&!S(t)&&D(r,t),e}Yp(r)}function Zp(e){if(e instanceof N){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function Qp(e){return e instanceof N&&e.api?.httpStatus===429}function $p(e,t){return Math.min(t*2**(e-1),1e4)}function em(e){return new Promise(t=>setTimeout(t,e))}async function tm(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??Zp,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;Qp(e)&&await em($p(t,a))}throw o}function nm(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function rm(e=3e4,t=3){return tm(async()=>{let t=`${nm()}/index.json`,n;try{n=await R.fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new N(`Cannot access skill registry: ${t}`,M.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new N(`Skill registry returned HTTP ${n.status}: ${t}`,M.NETWORK,n.status===404?`Skill index not yet published or registry URL is incorrect; confirm the publisher has generated index.json`:`Remote error, retry later`);let r;try{r=await n.json()}catch(e){throw new N(`Skill index index.json is not valid JSON`,M.GENERAL,`Remote may be in the middle of publishing, retry later`,{cause:e})}let i=r;if(typeof i!=`object`||!i||typeof i.skills!=`object`||i.skills===null)throw new N(`Skill index index.json has invalid structure`,M.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const im=/^sha256-[0-9a-f]{64}\.tar\.br$/;function am(e){let t=e?.object;return t&&im.test(t)?t:`skill.tar.br`}async function om(e,t,n=3){return tm(async()=>{let n=`${nm()}/${e}/${am(t)}`,r;try{r=await R.fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new N(`Failed to download skill ${e}: ${n}`,M.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new N(`Failed to download skill ${e}: HTTP ${r.status}`,M.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())},{attempts:n})}function sm(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function cm(e){return e.length>0&&sm(e)===e}function lm(e,t){throw new N(`Skill ${e} validation failed: ${t}`,M.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function um(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function dm(e,t){let n=A(e,`SKILL.md`),r;try{he(n).isFile()||lm(t,`SKILL.md is not a regular file`),r=T(n,`utf-8`)}catch(e){if(e instanceof N)throw e;lm(t,`missing SKILL.md`)}let i=um(r);i===null&&lm(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{lm(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&lm(t,`frontmatter is not a key-value structure`);let o=a,s=typeof o.name==`string`?o.name.trim():``,c=typeof o.description==`string`?o.description.trim():``;return(!s||!c)&&lm(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function fm(e){if(!cm(e))throw new N(`Invalid skill name: ${e}`,M.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function pm(e,t,n,r){fm(e);let i=$(),a=A(i,e),o=A(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{w(o,{recursive:!0}),await Up(t,o);let i=Gp(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new N(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,M.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=Wp(o);if(t!==n)throw new N(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,M.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=dm(o,e);return Xp(o,a),{name:e,path:a,meta:s}}finally{try{S(o)&&O(o,{recursive:!0,force:!0})}catch{}}}async function mm(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new N(`Skill ${e} uses unsupported compression format: ${t.compression}`,M.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return pm(e,await om(e,t,n),t.contentHash,r)}function hm(e){fm(e);let t=A($(),e);return S(t)?(O(t,{recursive:!0,force:!0}),!0):!1}function gm(e,t){return{...e.contentHash?{contentHash:e.contentHash}:{},...e.publishedAt?{publishedAt:e.publishedAt}:{},installedAt:(/* @__PURE__ */ new Date()).toISOString(),sourceType:`oss`,...e.description?{description:e.description}:{},links:t}}async function _m(e,t,n=jp(),r=[],i){await mm(e,t,i,process.platform===`win32`?[A($(),e),...n.map(t=>A(t.skillsDir,e))]:void 0);let a=zp(e,n,r);return{lockEntry:gm(t,a.links),linkedAgents:a.linkedAgents}}const vm=`bailian-docs-llm-wiki`;function ym(){return A(I(),`skills/bailian-docs-llm-wiki`)}function bm(){return S(A(ym(),`models`,`models.jsonl`))}function xm(){return A(I(),`wiki-sync-state.json`)}function Sm(){try{return JSON.parse(T(xm(),`utf-8`))}catch{return null}}function Cm(e){try{_e(xm(),JSON.stringify(e))}catch{}}function wm(e){try{Cp(vm,e)}catch{}}function Tm(e){try{let t=xp().skills[vm];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function Em(){try{return(await rm(3e3,1)).skills[vm]??null}catch{return null}}async function Dm(){let e=Sm(),t=Date.now();if(e&&t-e.lastChecked<432e5&&bm())return!1;let n=await Em();if(!n?.contentHash)return!1;if(bm()&&(!e||e.contentHash===n.contentHash)){if(Cm({lastChecked:t,contentHash:n.contentHash}),Tm(n.contentHash)){let e=xp().skills[vm]?.links??[];wm(gm(n,zp(vm,jp(),e).links))}return!1}try{let e=xp().skills[vm]?.links??[];wm((await _m(vm,n,jp(),e,1)).lockEntry)}catch{return!1}return Cm({lastChecked:t,contentHash:n.contentHash}),!0}const Om={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},km={Single:`single`,Pipeline:`pipeline`},Am={Low:`low`,Medium:`medium`,High:`high`},jm={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},Mm={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},Nm={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`},Pm={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},Fm={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},Im=`bailian-cli`,Lm=`install-method`,Rm=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function zm(e){return e?A(I(),`${Lm}.${e}`):A(I(),Lm)}function Bm(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function Vm(e){if(!e)return null;let t=e.trim().toLowerCase();return Rm.has(t)?t:null}function Hm(e){try{return Vm(T(e,`utf-8`).split(`
220
+ `)[0])}catch{return null}}function Um(){let e=Vm(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(Bm()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function Wm(e){let t=Vm(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=Hm(zm(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=Hm(zm());if(e)return e}return Um()}return Hm(zm())||Um()}function Gm(e){let t=Wm(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function Km(e,t={clientName:Im}){try{let n=I();S(n)||w(n,{recursive:!0,mode:448}),_e(zm(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&_e(zm(),`${e}\n`,{mode:384})}catch{}}const qm=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Jm=`https://github.com/modelstudioai/cli/releases`,Ym=`https://bailian.aliyun.com/cli/install.sh`,Xm=`https://bailian.aliyun.com/cli/install.ps1`;function Zm(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):qm}function Qm(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${Zm()}/manifest.json`:`${Zm()}/${t}.json`}function $m(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${Zm()}/${n}/${t}`}function eh(){let e=process.platform,t=process.arch,n;if(e===`darwin`)n=`darwin`;else if(e===`linux`)n=`linux`;else if(e===`win32`)n=`windows`;else throw Error(`Unsupported platform for binary updates: ${e}`);let r;if(t===`arm64`)r=`arm64`;else if(t===`x64`)r=`x64`;else throw Error(`Unsupported architecture for binary updates: ${t}`);if(n===`linux`&&r===`arm64`)throw Error(`linux arm64 is not supported for binary updates; use: npm install -g bailian-cli`);if(n===`windows`&&r===`arm64`)throw Error(`windows arm64 is not supported for binary updates; use: npm install -g bailian-cli`);return{os:n,arch:r,fileSuffix:e===`win32`?`.exe`:``}}function th(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function nh(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function rh(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function ih(e){return new Promise((t,n)=>{ce.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??/* @__PURE__ */ Error(`Failed to open zip: ${e}`));return}t(i)})})}function ah(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function oh(e,t,n){let r=await ih(e);return new Promise((i,a)=>{let o=!1,s=e=>{if(!o){o=!0;try{r.close()}catch{}a(e instanceof Error?e:Error(String(e)))}},c=e=>{if(!o){o=!0;try{r.close()}catch{}i(e)}};r.on(`error`,s),r.on(`end`,()=>{o||s(/* @__PURE__ */ Error(n?`Zip entry not found: ${n} in ${e}`:`Zip has no file entries: ${e}`))}),r.on(`entry`,e=>{if(o)return;let i=e.fileName.replace(/\\/g,`/`);if(i.endsWith(`/`)){r.readEntry();return}let a=ah(i);if(n&&i!==n&&a!==n){r.readEntry();return}r.openReadStream(e,(n,r)=>{if(n||!r){s(n??/* @__PURE__ */ Error(`Failed to read zip entry: ${e.fileName}`));return}(async()=>{try{await De(k(t),{recursive:!0}),await Ie(r,fe(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function sh(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new P(`--name cannot be empty`,`Use --name all or --name skill-a,skill-b`);let r=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))];if(r.includes(`all`)){if(r.length>1)throw new P(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function ch(){let e=$();return S(e)?E(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return he(A(e,t)).isDirectory()}catch{return!1}}):[]}function lh(e,t,n){let r=new Set(n),i=/* @__PURE__ */ new Set,a=[];for(let[n,o]of Object.entries(e.skills)){i.add(n);let e=t.skills[n];if(e){let t=r.has(n)?e.contentHash===o.contentHash?`installed`:`outdated`:`missing`;a.push({name:n,status:t,publishedAt:o.publishedAt,description:o.description})}else r.has(n)?a.push({name:n,status:`untracked`,publishedAt:o.publishedAt,description:o.description}):a.push({name:n,status:`not-installed`,publishedAt:o.publishedAt,description:o.description})}for(let[e,n]of Object.entries(t.skills))i.has(e)||(i.add(e),a.push({name:e,status:r.has(e)?`installed`:`missing`,publishedAt:n.publishedAt,description:n.description}));for(let e of n)i.has(e)||a.push({name:e,status:`untracked`});return a.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}export{Tp as AGENT_ENV_KEYS,ot as API_KEY_CAPABILITY_PATTERN,jl as ASYNC_FLAG,et as BAILIAN_HOST,As as BATCH_CSV_COLUMNS,cs as BATCH_ENDPOINTS,ls as BATCH_STATUSES,us as BATCH_TERMINAL,$c as BILLING_METHOD,Im as BINARY_PRODUCT_CLIENT_NAME,N as BailianError,ys as BatchValidator,Am as Budgets,Ac as CALC_DATASETS_TOKENS_API,cn as CHANNEL,Y as CHARGE_TYPE,Ll as COMMAND_PACK_API_VERSION,Al as CONCURRENT_FLAG,rt as CONFIG_FILE_KEYS,Nl as CONSOLE_AUTH_FLAGS,Nm as Capabilities,Zn as Client,km as Complexities,jm as ContextNeeds,un as DASHSCOPE_SERVICE_HEADER,eo as DECISION_QUESTION_TYPES,Rs as DECISION_REGIONS,el as DEFAULT_BILLING_METHOD,qm as DEFAULT_CLI_CDN_BASE,Ls as DEFAULT_DECISION_MODEL,zs as DEFAULT_DECISION_REGION,Zc as DEFAULT_DEPLOY_PLAN,Xm as DEFAULT_INSTALL_PS1_URL,Ym as DEFAULT_INSTALL_SCRIPT_URL,nt as DEFAULT_LANGUAGE,np as DEFAULT_LLM_MODEL,sc as DEFAULT_TRAINING_TYPE,pl as DEPLOY_LIST_INDEPENDENT_API,J as DEPLOY_PLAN,dl as DEPLOY_START_API,fl as DEPLOY_STOP_API,$e as DOCS_HOSTS,jc as ESTIMATE_FINETUNE_TOKENS_API,M as ExitCode,Pm as Features,Jm as GITHUB_RELEASES_BASE,kl as GLOBAL_FLAGS,pc as INSUFFICIENT_SAMPLES_CODE,X as LLMError,ds as MAX_BATCH_BYTES,fs as MAX_BATCH_LINE_BYTES,ps as MAX_BATCH_RECORDS,Fa as MAX_CPT_BYTES,Pa as MAX_DATASET_BYTES,to as MAX_DECISION_CHOICE_OPTIONS,Ia as MAX_DECISION_DATASET_BYTES,ro as MAX_DECISION_SCORE_LEVELS,La as MAX_MEDIA_ZIP_BYTES,no as MIN_DECISION_SCORE_LEVELS,Ml as MODEL_AUTH_FLAGS,_a as MODEL_LIST_API,Xn as McpClient,Om as Modalities,Fm as ModelCategories,Pl as OPENAPI_AUTH_FLAGS,ln as OPEN_API_SOURCE,va as PREDICT_CONFIG_API,Mm as QualityPreferences,Ti as RAG_PATHS,Qf as RECOMMEND_TOOLS,F as REGIONS,bi as SANDBOX_PATHS,wp as SKIP_HOST_AGENTS_ENV,vl as SPEECH_BIASING_MODEL,ll as STRATEGIES,tt as SUPPORTED_LANGUAGES,kc as TRAINING_MODEL_PRICE_API,oc as TRAINING_TYPES_CLI,ac as TRAINING_TYPE_MAP,P as UsageError,Ht as activateConfigProfile,tp as agentLoop,gi as agentStudioFilesPath,zr as agentStudioHost,Iu as analyzeEngineIntent,rn as anonymousConsoleCall,xr as appCompletionPath,Xp as atomicSwap,Gn as bailianMcpPath,Kn as bailianMcpSsePath,gs as batchChunks,Is as batchDataNotes,Fs as batchExamples,ms as batchIoError,_s as batchLines,K as batchObject,G as batchUsage,th as binaryAssetFileName,rh as binaryInnerFileName,nh as binaryTarFileName,yn as buildAcsCanonicalQuery,Yi as buildAsrContextMessages,Zi as buildAsrFlashRequest,Xi as buildAsyncAsrLanguageFields,Zf as buildEngineInput,al as buildPrepaidInfo,nl as buildReservationCapacity,Kt as buildSettings,gm as buildSkillLockEntry,Gt as buildSources,yl as buildVocabularyRequest,on as callConsoleGateway,ws as cancelBatch,rc as cancelCompressJob,Ks as cancelFineTune,Qm as channelManifestUrl,ir as chatPath,$i as collectAsrTranscriptionItems,Wp as computeDirContentHash,lh as computeSkillStatuses,Yn as connectBailianMcpWithFallback,ma as createBailianControlUser,Ss as createBatch,Hc as createCapacityInstance,$s as createCompressJob,Ic as createDeployment,Us as createFineTune,ua as createInstrumentedFetch,rp as createLLMClient,vp as createNonInteractive,_p as createReadlineInteraction,Xf as createSession,ru as createTrackingEvent,xl as createVocabulary,Fl as credentialFlagDefs,dr as decisionPath,Qc as defaultDeployPlan,Il as defineCommand,Gc as deleteCapacityInstance,ic as deleteCompressJob,Ut as deleteConfigProfile,Na as deleteDataset,qc as deleteDeployment,qs as deleteFineTune,Tl as deleteVocabulary,si as deploymentCapacityInstancePath,li as deploymentCapacityInstanceRenewPath,ci as deploymentCapacityInstanceScalePath,oi as deploymentCapacityInstancesPath,di as deploymentCapacityOperationPath,ui as deploymentOverflowPath,yt as describeAuthState,eh as detectBinaryPlatform,Um as detectInstallMethod,jp as detectInstalledAgents,Xo as detectModality,Et as detectOutputFormat,$f as dispatchTool,om as downloadSkillAsset,nn as effectiveConsoleGatewayConfig,bp as emptySkillLock,St as ensureConfigDir,Pc as estimateCptTokens,Nc as estimateSftDpoTokens,Ps as exportBatchCsv,Xs as exportCheckpoint,Qi as extractAsrFlashText,Up as extractTarBr,oh as extractZipEntryToFile,zp as fanOutSkillToAgents,fc as fetchModelCapability,Ta as fetchModelDetail,Sa as fetchModelGroups,wa as fetchModelGroupsAll,ya as fetchModelList,ba as fetchModelListAll,Oa as fetchPredictConfig,rm as fetchSkillsIndex,Mc as fetchTrainingModelPrice,_l as findDeploymentEntry,xa as findModelByName,Ca as flattenModelGroups,gu as flushTelemetry,Du as formatDegradation,Tt as formatErrorJson,ss as formatIssue,wt as formatJson,Dt as formatOutput,Ct as formatText,tr as generateCLIAccessToken,zl as generateFilename,Ep as getAgentTargets,Yt as getApiKeyLoginKind,Cs as getBatch,Es as getBatchFileContent,Bc as getCapacityInstance,Vc as getCapacityOperation,Zm as getCliCdnBase,tc as getCompressJob,nc as getCompressJobLogs,I as getConfigDir,bt as getConfigPath,xt as getCredentialsPath,Ma as getDataset,Rc as getDeployment,Gs as getFineTune,Js as getFineTuneLogs,Bl as getHermesHome,Wm as getInstallMethod,Jt as getModelProfilePreset,Dc as getProfile,yp as getSkillLockPath,nm as getSkillRegistryBaseUrl,$ as getSkillsDir,Gm as getUpdateInstallMethod,rl as hasPrepaidFlags,R as httpTransport,hr as image2ImagePath,_r as image2videoPath,jn as imageFileToDataUri,fr as imagePath,pr as imageSyncPath,mr as imageText2ImagePath,Ji as inferAudioFormatHint,uo as inspectDecisionQuestion,po as inspectDecisionQuestionId,fo as inspectDecisionQuestionTable,mo as inspectDecisionQuestions,oo as inspectDecisionState,mm as installSkill,pm as installSkillFromBuffer,_m as installSkillWithFanout,st as isApiKeyCapability,Bm as isCompiledBinary,na as isDashScopeGateway,H as isDecisionObject,kp as isHostSystemDetectDir,Pi as isLegacyImage2ImageModel,Ni as isLegacyText2ImageModel,Pn as isLocalFile,Hp as isSafeEntryName,cm as isSafeSkillName,qn as isStreamableHttpUnsupported,ki as isSyncMultimodalImageModel,cc as isTrainingTypeCli,Jn as isUrlOverrideSseFallbackCandidate,Fi as isWanxFunctionImageEditModel,Rr as knowledgeChatEndpoint,Lr as knowledgeSearchEndpoint,Rp as linkSkillToAgents,ha as listBailianControlWorkspaces,Ts as listBatches,zc as listCapacityInstances,Ys as listCheckpoints,ec as listCompressJobs,Qs as listCompressTemplates,ja as listDatasets,Jc as listDeployableModels,Lc as listDeployments,Ws as listFineTunes,gl as listIndependentDeployedModels,ch as listSkillDirsOnDisk,os as listSupportedFormats,dc as listSupportedTrainingTypes,Oc as listTrainingTypes,Sl as listVocabularies,mp as loadCatalog,hp as loadFamilies,_u as localSink,Qt as makeAuthStore,ka as makeConfigStore,Xe as mapApiError,sn as maskToken,Dm as maybeSyncWikiData,Ur as mcpWebSearchPath,Cr as memoryAddAsyncPath,Sr as memoryEndpoint,wr as memoryEventPath,Er as memoryListPath,Dr as memoryNodePath,Tr as memorySearchPath,Or as memorySkillExportPath,uc as modelSupportsTrainingType,yr as modelsLimitsPath,br as modelsPermissionsPath,ct as normalizeApiKeyCapabilities,Nt as normalizeConfigName,Ze as normalizeModelBaseUrl,hs as parseBatchEndpoint,ql as parseBooleanValue,ut as parseConfigFile,za as parseDatasetSchemaFlag,Dl as parseInstantVocabulary,Jl as parseOptionalBooleanValue,zn as parseSSE,oa as parseSecurityBody,sh as parseSkillNames,Ol as parseVocabularyEntries,ul as pickPlanStrategy,rs as pickValidator,Bp as planUnlinkSkillFromAgents,mc as preflightBatchSizeGate,ks as prepareBatch,Nr as profileSchemaItemPath,Mr as profileSchemaPath,Ns as projectBatchCsv,Cl as queryVocabulary,hi as ragEndpoint,xs as readBatchBlob,nu as readCaller,L as readConfigFile,zt as readConfigProfiles,xp as readSkillLock,Gl as readTextFromPathOrStdin,Lf as recommendEngine,Mn as redactDataUri,nr as refreshAccessToken,is as registerValidator,$m as releaseAssetUrl,vu as remoteSink,hm as removeSkillDir,Wc as renewCapacityInstance,mn as request,vn as requestJson,ga as resetBailianControlPolicies4Agent,gp as resetCatalogCache,pt as resolveApiKey,qi as resolveAsrApi,am as resolveAssetFileName,Ds as resolveBatchChatEndpoint,Yl as resolveBooleanFlag,$n as resolveCLIAccessTokenTarget,mt as resolveConsole,Fn as resolveFileUrl,Bi as resolveImageEditApi,zi as resolveImageGenerateApi,Ii as resolveImageSizeProfile,ft as resolveModelBaseUrl,dt as resolveModelBaseUrlState,ht as resolveOpenApi,Ul as resolveOutputDir,Li as resolvePromptExtendDefault,Xl as resolveWatermark,ur as responsesPath,pd as routeEngine,Kl as runWithConcurrency,vi as sandboxApiPath,_i as sandboxBaseUrl,yi as sandboxEndpoint,Si as sandboxInstanceActionPath,xi as sandboxInstancePath,wi as sandboxTemplateBuildStatusPath,Ci as sandboxTemplatePath,sm as sanitizeSkillName,Uc as scaleCapacityInstance,Yc as scaleDeployment,Hr as securityAgentLogsEndpoint,sa as securityGet,Vr as securityOverviewEndpoint,Wt as selectApiKeyResolutionSources,bn as signAcsRequest,dn as sourceConfig,Ar as speechRecognizePath,kr as speechSynthesizePath,jr as speechVocabularyPath,ml as startModelService,hl as stopModelService,Hs as stripDecisionTrainingFields,Wl as stripUndefined,vr as taskPath,Su as trackCommandExecution,z as trackingHeaders,lc as trainingTypeMethodVariant,Vp as unlinkSkillFromAgents,Vs as unwrapDecisionQuestions,B as unwrapResponse,Xc as updateDeployment,Kc as updateDeploymentOverflow,wl as updateVocabulary,Aa as uploadDataset,Nn as uploadFile,Cp as upsertSkillLockEntry,Pr as userProfilePath,Fr as userProfileValuesPath,bs as validateBatch,Vt as validateConfigProfileActivation,er as validateConsoleAccessToken,as as validateDataset,il as validatePrepaidFlags,tl as validateReservationCapacity,dm as validateSkillDir,kt as validateTimeout,gr as videoGeneratePath,Ir as workspaceMaaSBaseUrl,Os as writeBatchFile,Lt as writeConfigFile,Km as writeInstallMethodSync,Sp as writeSkillLock};