bailian-cli-core 2.8.5 → 2.8.6

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,5 +1,5 @@
1
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 x,setGlobalDispatcher as ee}from"undici";import{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie}from"crypto";import{Readable as ae}from"stream";import{createInterface as oe}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 pe,mkdirSync as me,readFileSync as he,readdirSync as ge,readlinkSync as _e,realpathSync as ve,renameSync as C,rmSync as w,statSync as ye,symlinkSync as be,writeFileSync as xe}from"node:fs";import{isIP as Se}from"node:net";import{Readable as Ce}from"node:stream";import{basename as we,dirname as Te,isAbsolute as Ee,join as T,relative as De,resolve as Oe,sep as ke}from"node:path";import{parse as Ae}from"csv-parse";import{stringify as je}from"csv-stringify/sync";import{link as Me,mkdir as Ne,open as Pe,readFile as Fe,rename as Ie,unlink as Le}from"node:fs/promises";import{createHash as Re,randomUUID as ze}from"node:crypto";import{setTimeout as Be}from"node:timers/promises";import{createInterface as Ve}from"node:readline/promises";import{homedir as He}from"node:os";import{pipeline as Ue}from"node:stream/promises";import{createBrotliDecompress as We}from"node:zlib";import Ge from"tar-stream";var Ke=Object.create,qe=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyNames,Xe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty,E=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ye(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ze.call(e,s)&&s!==n&&qe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Je(t,s))||r.enumerable});return e},$e=(e,t,n)=>(n=e==null?{}:Ke(Xe(e)),Qe(t||!e||!e.__esModule||!Ze.call(e,`default`)?qe(n,`default`,{value:e,enumerable:!0}):n,e)),et=/* @__PURE__ */ e(import.meta.url);const tt=/(?:authorization|cookie|apikey|accesskey(?:id)?|privatekey|credentials?|token|password|secret)$/i;function nt(e,t=/* @__PURE__ */ new Set,n=0){if(typeof e==`bigint`)return e.toString();if(typeof e==`function`)return`[Function]`;if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(n>=8)return`[Truncated]`;t.add(e);try{let r=Object.getOwnPropertyDescriptors(e),i=e=>{if(e)return`value`in e?nt(e.value,t,n+1):`[Accessor]`};if(Array.isArray(e)){let e=r.length?.value;return Array.from({length:e},(e,t)=>i(r[String(t)]))}return Object.fromEntries(Object.entries(r).filter(([,e])=>e.enumerable).map(([e,t])=>[e,tt.test(e.replaceAll(/[-_]/g,``))?`[REDACTED]`:i(t)]))}catch{return`[Unserializable]`}finally{t.delete(e)}}const D={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10,INTERRUPTED:130};var O=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=D.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=it(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}:{}}}}},rt=class extends O{constructor(e,t){super(e,D.USAGE,t),this.name=`UsageError`}};function it(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(nt(e))}}catch{return}}}var at=class extends O{reason;constructor(e,t,n,r){super(t,D.AUTH,n,r),this.reason=e}};function ot(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 O(r,D.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function st(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw ct(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw ct(e);return n.origin}function ct(e){return new O(`Invalid model base URL "${e}".`,D.USAGE,`Use an absolute http(s) URL.`)}const lt={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},ut={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},dt=`https://bailian.cn-beijing.aliyuncs.com`,ft=[`en-US`,`zh-CN`],pt=`en-US`,mt=[`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`],ht=/* @__PURE__ */ new Set([`text`,`json`]),gt=/* @__PURE__ */ new Set([`domestic`,`international`]),_t=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function vt(e){return _t.test(e)}function yt(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(!vt(e))return[];t.includes(e)||t.push(e)}return t}function bt(e){try{return st(e)}catch{return}}function xt(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&ft.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=bt(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&ht.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=yt(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`&&gt.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 St(e){if(e.flags.apiKey)return`flag`;if(e.env.DASHSCOPE_API_KEY?.trim())return`env`;if(e.file.api_key)return`config`}function Ct(e){if(e.flags.baseUrl)return`flag`;if(e.env.DASHSCOPE_BASE_URL?.trim())return`env`;if(e.file.base_url)return`config`}function wt(e){return{apiKeySource:St(e),baseUrlSource:Ct(e)}}function Tt(e){let{apiKeySource:t,baseUrlSource:n}=e;return!!(t&&n&&t!==n)}function Et(e,t=lt.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:st(n||t),baseUrlIsDefault:!n}}function Dt(e,t=lt.cn){return Et(e,t).baseUrl}function Ot(e){let t=Dt(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 at(`missing-api-key`,`No API key found.`,`Set DASHSCOPE_API_KEY or pass --api-key.`)}function kt(e){let t=e.file.access_token?.trim();if(!t)throw new at(`missing-console-token`,`No console access token found.`);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 At(e){let t=jt(`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=jt(`env`,e.env.BAILIAN_ACCESS_KEY_ID,e.env.BAILIAN_ACCESS_KEY_SECRET,!!(Mt(e.env.BAILIAN_ACCESS_KEY_ID)||Mt(e.env.BAILIAN_ACCESS_KEY_SECRET)),e.env.BAILIAN_SECURITY_TOKEN,`BAILIAN`);if(n)return n;let r=jt(`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;let i=jt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Mt(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Mt(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(i)return i;throw new at(`missing-openapi-pair`,`No OpenAPI AK/SK credentials found.`,`Set BAILIAN_ACCESS_KEY_ID and BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET), or pass --access-key-id and --access-key-secret.`)}function jt(e,t,n,r,i,a=`ALIBABA_CLOUD`){if(!r)return;let o=Mt(t),s=Mt(n);if(!o||!s)throw new at(`incomplete-openapi-${e}`,`Incomplete OpenAPI AK/SK credentials found.`,Nt(e,a));return{accessKeyId:o,accessKeySecret:s,securityToken:Mt(i),source:e}}function Mt(e){return e?.trim()||void 0}function Nt(e,t){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 ${t}_ACCESS_KEY_ID and ${t}_ACCESS_KEY_SECRET, or unset the partial env vars.`:`Save a complete AccessKey ID and secret pair in the selected configuration.`}function Pt(e){let t={};try{t.apiKey=Ot(e)}catch{}try{t.console=kt(e)}catch{}try{t.openapi=At(e)}catch{}return t}function Ft(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function It(){return g(Ft(),`config.json`)}function Lt(){return g(Ft(),`credentials.json`)}async function Rt(){let e=Ft(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function zt(e){return v(e).replace(/\n$/,``)}function Bt(e){return JSON.stringify(e,null,2)}function Vt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Ht(e){return e===`json`||e===`text`?e:`text`}function Ut(e,t){switch(t){case`json`:return Bt(e);case`text`:return zt(e)}}const Wt={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function Gt(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return Wt}const Kt=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,qt=`active_config`;function Jt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Yt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!Kt.test(e))throw new O(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,D.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(mt.includes(e)||e===qt)throw new O(`Invalid config name "${e}". It conflicts with a config key.`,D.USAGE);return e}}function Xt(e){let t=It();if(!i(t))return{};try{let e=JSON.parse(o(t,`utf-8`));return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(t){let n=t;return(n instanceof SyntaxError||n.message.includes(`JSON`))&&e?.({code:`CONFIG_CORRUPTED`,message:{"en-US":`Config file is corrupted; using defaults.`,"zh-CN":`配置文件已损坏,将使用默认配置。`}}),{}}}function Zt(e,t){let n=Yt(e[qt]);if(n&&t&&!Jt(e[n]))throw new O(`Active config "${n}" does not exist.`,D.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function Qt(e,t){if(!t)return e;let n=e[t];return Jt(n)?n:{}}function $t(e){return xt(Qt(Xt(),e))}async function en(e,t,n={}){let r=Xt();if(t)r[t]=e;else{for(let e of Object.keys(r))mt.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[qt]=t??`default`),await tn(r)}async function tn(e){await Rt();let t=It(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384}),s(n,t)}function nn(){let e=Xt(),t={};for(let[n,r]of Object.entries(e))mt.includes(n)||n===qt||Jt(r)&&(t[n]=xt(r));return{default:xt(e),named:t,active:Zt(e,!0)??`default`}}function rn(e,t){let n=Yt(t);if(n&&!Jt(e[n]))throw new O(`Config "${n}" does not exist.`,D.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function an(e){return rn(Xt(),e)}async function on(e){let t=Xt(),n=rn(t,e);return t[qt]=n,await tn(t),n}async function sn(e){let t=Yt(e);if(!t)throw new O(`Cannot delete the default profile.`,D.USAGE);let n=Xt();return Jt(n[t])?(delete n[t],Zt(n,!1)===t&&(n[qt]=`default`),await tn(n),!0):!1}function cn(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:$t(),configName:void 0},fallbackFrom:e.configName}}function ln(e,t){let n=Xt(t),r=e.config!==void 0,i=Zt(n,!r),a=r?Yt(e.config):i;return{flags:e,file:xt(Qt(n,a)),env:process.env,configName:a,configPath:It()}}function un({flags:e,env:t,file:n={}}){let r=e.output||t.DASHSCOPE_OUTPUT||n.output;return{output:Ht(r),outputExplicit:!!r,outputSource:e.output?`flag`:t.DASHSCOPE_OUTPUT?`env`:n.output?`file`:`default`,quiet:e.quiet||t.DASHSCOPE_QUIET===`1`,verbose:e.verbose||t.DASHSCOPE_VERBOSE===`1`}}function dn(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 O(s[`en-US`],D.USAGE);return{configPath:e.configPath??It(),configName:e.configName,...un(e),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,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const fn={"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 pn(e){return e?fn[e]:void 0}function mn(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function hn(e,t,n){if(n)return t;let r=mn(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const gn={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 _n(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Pt({...e,file:$t(t)}),stored(){let e=$t(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=>Dt(e,t),async login(e){let r=e.api_key?hn(e.api_key,t,n):t,i=n||r!==t,a=$t(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`?st(String(n)):n}await en(a,r,{activate:i})},async logout(e){let n=$t(t),r=gn[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await en(n,t),!0},get path(){return e.configPath??It()}}}function vn(e){try{let t=new URL(e);t.username=``,t.password=``;for(let e of t.searchParams.keys())t.searchParams.set(e,`[REDACTED]`);return t.hash=``,t.toString()}catch{return`[Invalid URL]`}}function yn(e,t,n,r){e.debug?.({message:{"en-US":`HTTP request`,"zh-CN":`HTTP 请求`},details:{method:t,url:vn(n),...r}})}function bn(e,t){e.debug?.({message:{"en-US":`HTTP response`,"zh-CN":`HTTP 响应`},details:{status:t.status,status_text:t.statusText,request_id:t.headers.get(`x-request-id`)??void 0}})}const xn=process.versions.bun?void 0:x();globalThis.Request,xn&&x()!==xn&&ee(xn);const Sn={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},Cn={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function wn(e,t){return Cn[e]?.[t]??Cn[`cn-beijing`][t]}function Tn(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 En(e,t={}){let n=Tn(e);return(r,i)=>On({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:r,data:i},t)}function Dn(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=wn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Dn(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)}`;yn(i,`POST`,f,{api:n,region:e.region});let p=await Sn.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(bn(i,p),!p.ok){let e=await p.text().catch(()=>``);throw new O(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,D.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);throw n.includes(`NotLogined`)?new at(`expired-console-session`,`Console session is not logged in or has expired.`,i.recoveryHint,{rawResponse:e}):new O(`Console gateway error: ${n}`,D.GENERAL,void 0,{rawResponse:e})}return m}const kn=`bailian-cli`,An=`bailian-cli-call`,jn=`BailianCLI`,Mn=`X-Dashscope-Service`;function Nn(e){return JSON.stringify({channel:kn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function Pn(e,t=kn){return{"x-dashscope-source-config":Nn(e),"x-dashscope-openapisource":jn,[Mn]:t}}const Fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function In(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Ln(e,t){let n=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return Bn(await Rn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function Rn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...Pn(e.identity),...t.headers};!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),In(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),yn(e,t.method??`GET`,t.url);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(x(),Fn)}},o=await Sn.fetch(t.url,a);if(bn(e,o),!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=ot(o.status,n,t.url);throw new O(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function zn(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 O(`Response body idle timeout: no data received for ${e/1e3}s.`,D.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function Bn(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=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await Rn(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 O(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,D.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=ot(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new O(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 Hn(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])=>`${Wn(e)}=${Wn(String(t))}`).join(`&`)}function Un(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ie(),i=Gn(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(`
2
+ `,{mode:384}),s(n,t)}function nn(){let e=Xt(),t={};for(let[n,r]of Object.entries(e))mt.includes(n)||n===qt||Jt(r)&&(t[n]=xt(r));return{default:xt(e),named:t,active:Zt(e,!0)??`default`}}function rn(e,t){let n=Yt(t);if(n&&!Jt(e[n]))throw new O(`Config "${n}" does not exist.`,D.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function an(e){return rn(Xt(),e)}async function on(e){let t=Xt(),n=rn(t,e);return t[qt]=n,await tn(t),n}async function sn(e){let t=Yt(e);if(!t)throw new O(`Cannot delete the default profile.`,D.USAGE);let n=Xt();return Jt(n[t])?(delete n[t],Zt(n,!1)===t&&(n[qt]=`default`),await tn(n),!0):!1}function cn(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:$t(),configName:void 0},fallbackFrom:e.configName}}function ln(e,t){let n=Xt(t),r=e.config!==void 0,i=Zt(n,!r),a=r?Yt(e.config):i;return{flags:e,file:xt(Qt(n,a)),env:process.env,configName:a,configPath:It()}}function un({flags:e,env:t,file:n={}}){let r=e.output||t.DASHSCOPE_OUTPUT||n.output;return{output:Ht(r),outputExplicit:!!r,outputSource:e.output?`flag`:t.DASHSCOPE_OUTPUT?`env`:n.output?`file`:`default`,quiet:e.quiet||t.DASHSCOPE_QUIET===`1`,verbose:e.verbose||t.DASHSCOPE_VERBOSE===`1`}}function dn(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 O(s[`en-US`],D.USAGE);return{configPath:e.configPath??It(),configName:e.configName,...un(e),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,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const fn={"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 pn(e){return e?fn[e]:void 0}function mn(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function hn(e,t,n){if(n)return t;let r=mn(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const gn={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 _n(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Pt({...e,file:$t(t)}),stored(){let e=$t(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=>Dt(e,t),async login(e){let r=e.api_key?hn(e.api_key,t,n):t,i=n||r!==t,a=$t(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`?st(String(n)):n}await en(a,r,{activate:i})},async logout(e){let n=$t(t),r=gn[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await en(n,t),!0},get path(){return e.configPath??It()}}}function vn(e){try{let t=new URL(e);t.username=``,t.password=``;for(let e of t.searchParams.keys())t.searchParams.set(e,`[REDACTED]`);return t.hash=``,t.toString()}catch{return`[Invalid URL]`}}function yn(e,t,n,r){e.debug?.({message:{"en-US":`HTTP request`,"zh-CN":`HTTP 请求`},details:{method:t,url:vn(n),...r}})}function bn(e,t){e.debug?.({message:{"en-US":`HTTP response`,"zh-CN":`HTTP 响应`},details:{status:t.status,status_text:t.statusText,request_id:t.headers.get(`x-request-id`)??void 0}})}const xn=process.versions.bun?void 0:x();globalThis.Request,xn&&x()!==xn&&ee(xn);const Sn={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},Cn={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function wn(e,t){return Cn[e]?.[t]??Cn[`cn-beijing`][t]}function Tn(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 En(e,t={}){let n=Tn(e);return(r,i)=>On({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:r,data:i},t)}function Dn(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=wn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Dn(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)}`;yn(i,`POST`,f,{api:n,region:e.region});let p=await Sn.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(bn(i,p),!p.ok){let e=await p.text().catch(()=>``);throw new O(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,D.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);if(n.includes(`NotLogined`))throw new at(`expired-console-session`,`Console session is not logged in or has expired.`,i.recoveryHint,{rawResponse:e});let r=typeof h.errorMsg==`string`&&h.errorMsg?h.errorMsg:typeof h.message==`string`&&h.message?h.message:n,a=[m.requestId,m.request_id,h.requestId,h.request_id].find(e=>typeof e==`string`&&e.length>0);throw new O(`${r} (HTTP ${p.status}; code=${n})`,D.GENERAL,void 0,{api:{httpStatus:p.status,apiCode:n,requestId:a},rawResponse:e})}return m}const kn=`bailian-cli`,An=`bailian-cli-call`,jn=`BailianCLI`,Mn=`X-Dashscope-Service`;function Nn(e){return JSON.stringify({channel:kn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function Pn(e,t=kn){return{"x-dashscope-source-config":Nn(e),"x-dashscope-openapisource":jn,[Mn]:t}}const Fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function In(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Ln(e,t){let n=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return Bn(await Rn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function Rn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...Pn(e.identity),...t.headers};!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),In(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),yn(e,t.method??`GET`,t.url);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(x(),Fn)}},o=await Sn.fetch(t.url,a);if(bn(e,o),!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=ot(o.status,n,t.url);throw new O(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function zn(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 O(`Response body idle timeout: no data received for ${e/1e3}s.`,D.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function Bn(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=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await Rn(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 O(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,D.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=ot(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new O(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 Hn(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])=>`${Wn(e)}=${Wn(String(t))}`).join(`&`)}function Un(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ie(),i=Gn(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
5
  `),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Gn(u)}`,p=Kn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function Wn(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Gn(e){return te(`sha256`).update(e,`utf8`).digest(`hex`)}function Kn(e,t){return ne(`sha256`,e).update(t,`utf8`).digest(`hex`)}const qn=[`cn-beijing`,`ap-southeast-1`];function Jn(e){return new O(`Local-file temporary upload is supported only in ${qn.join(`, `)}; "${e}" is not supported.`,D.USAGE,`Use a reachable HTTPS media URL instead.`)}function Yn(e){if(mn(e)===`token-plan`)throw Jn(`Token Plan`)}function Xn(e,t){let n=st(e),r=new URL(n).hostname.toLowerCase();if(/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/.test(r))throw Jn(`Token Plan`);if(r===new URL(lt.cn).hostname||r===new URL(lt.intl).hostname)return Yn(t),n;if(r===new URL(lt.us).hostname)throw Jn(r);let i=/^[^.]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/.exec(r)?.[1];if(i===`cn-beijing`||i===`ap-southeast-1`)return Yn(t),n;if(i)throw Jn(i);return n}async function Zn(e,t,n,r,i){let a=`${Xn(r,e)}/api/v1/uploads`,o=`${a}?action=getPolicy&model=${encodeURIComponent(t)}`,s=cr(15e3,i),c=await Sn.fetch(o,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...Pn(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 O(`${[`HTTP ${c.status}`,r?`code=${r}`:void 0,i?`request_id=${i}`:void 0,`upload_endpoint=${a}`].filter(e=>e!==void 0).join(`; `)} - ${n}`,D.GENERAL,void 0,{api:{httpStatus:c.status,apiCode:r,requestId:i},rawResponse:e.slice(0,500)})}return(await c.json()).data}async function Qn(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=cr(r*1e3,n),u=await Sn.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 O(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,D.GENERAL)}return`oss://${a}`}const $n={".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`},er={".aac":`audio/aac`,".amr":`audio/amr`,".flac":`audio/flac`,".m4a":`audio/mp4`,".mp3":`audio/mpeg`,".oga":`audio/ogg`,".ogg":`audio/ogg`,".opus":`audio/opus`,".wav":`audio/wav`,".weba":`audio/webm`,".wma":`audio/x-ms-wma`};function tr(e,t,n){if(!i(e))throw new O(`File not found: ${e}`,D.USAGE);if(!l(e).isFile())throw new O(`Not a file: ${e}`,D.USAGE);let r=h(e).toLowerCase(),a=t[r];if(!a)throw new O(`Unsupported ${n} format "${r||`unknown`}".`,D.USAGE,`Use an ${n} file with a recognized extension.`);return`data:${a};base64,${o(e).toString(`base64`)}`}function nr(e){return tr(e,$n,`image`)}function rr(e){return tr(e,er,`audio`)}function ir(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function ar(e){let{apiKey:t,baseUrl:n=lt.cn,model:r,filePath:a,identity:o,signal:s,timeout:c}=e;if(!i(a))throw new O(`File not found: ${a}`,D.USAGE);if(!l(a).isFile())throw new O(`Not a file: ${a}`,D.USAGE);return Qn(await Zn(t,r,o,n,s),a,s,c)}function or(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function sr(e,t,n,r){return or(e)?ar({apiKey:t,baseUrl:r.baseUrl,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function cr(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}}const lr=Object.freeze({status:`aborted`});function k(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=/* @__PURE__ */ new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var ur=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};const dr={};function fr(e){return e&&Object.assign(dr,e),dr}function pr(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function mr(e,t){return typeof t==`bigint`?t.toString():t}function hr(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function gr(e){return e==null}function _r(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function vr(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function A(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function br(e){return JSON.stringify(e)}const xr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Sr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Cr=hr(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function wr(e){if(Sr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return Sr(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const Tr=/* @__PURE__ */ new Set([`string`,`number`,`symbol`]);function Er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Dr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Or(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const kr={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ar(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return Dr(e,{...e._zod.def,shape:n,checks:[]})}function jr(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return Dr(e,{...e._zod.def,shape:n,checks:[]})}function Mr(e,t){if(!wr(t))throw Error(`Invalid input to extend: expected a plain object`);return Dr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return yr(this,`shape`,n),n},checks:[]})}function Nr(e,t){return Dr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return yr(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function Pr(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Dr(t,{...t._zod.def,shape:i,checks:[]})}function Fr(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Dr(t,{...t._zod.def,shape:i,checks:[]})}function Ir(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Lr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Rr(e){return typeof e==`string`?e:e?.message}function zr(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=Rr(e.inst?._zod.def?.error?.(e))??Rr(t?.error?.(e))??Rr(n.customError?.(e))??Rr(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Br(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Vr(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Hr=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,mr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ur=k(`$ZodError`,Hr),Wr=k(`$ZodError`,Hr,{Parent:Error});function Gr(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Kr(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const qr=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new ur;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>zr(e,a,fr())));throw xr(t,i?.callee),t}return o.value},Jr=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>zr(e,a,fr())));throw xr(t,i?.callee),t}return o.value},Yr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ur;return a.issues.length?{success:!1,error:new(e??Ur)(a.issues.map(e=>zr(e,i,fr())))}:{success:!0,data:a.value}},Xr=/* @__PURE__*/ Yr(Wr),Zr=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>zr(e,i,fr())))}:{success:!0,data:a.value}},Qr=/* @__PURE__*/ Zr(Wr),$r=/^[cC][^\s-]{8,}$/,ei=/^[0-9a-z]+$/,ti=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ni=/^[0-9a-vA-V]{20}$/,ri=/^[A-Za-z0-9]{27}$/,ii=/^[a-zA-Z0-9_-]{21}$/,ai=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,si=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,ci=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function li(){return/* @__PURE__ */ RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ui=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,di=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,fi=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,pi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hi=/^[A-Za-z0-9_-]*$/,gi=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,_i=/^\+(?:[0-9]){6,14}[0-9]$/,vi=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,yi=/*@__PURE__*/ RegExp(`^${vi}$`);function bi(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xi(e){return RegExp(`^${bi(e)}$`)}function Si(e){let t=bi({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${vi}T(?:${r})$`)}const Ci=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},wi=/^\d+$/,Ti=/^-?\d+(?:\.\d+)?/i,Ei=/true|false/i,Di=/null/i,Oi=/^[^A-Z]*$/,ki=/^[^a-z]*$/,Ai=/*@__PURE__*/ k(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ji={number:`number`,bigint:`bigint`,object:`date`},Mi=/*@__PURE__*/ k(`$ZodCheckLessThan`,(e,t)=>{Ai.init(e,t);let n=ji[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ni=/*@__PURE__*/ k(`$ZodCheckGreaterThan`,(e,t)=>{Ai.init(e,t);let n=ji[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Pi=/*@__PURE__*/ k(`$ZodCheckMultipleOf`,(e,t)=>{Ai.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):vr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Fi=/*@__PURE__*/ k(`$ZodCheckNumberFormat`,(e,t)=>{Ai.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=kr[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=wi)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),Ii=/*@__PURE__*/ k(`$ZodCheckMaxLength`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Br(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Li=/*@__PURE__*/ k(`$ZodCheckMinLength`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Br(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ri=/*@__PURE__*/ k(`$ZodCheckLengthEquals`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Br(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),zi=/*@__PURE__*/ k(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Ai.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=/* @__PURE__ */ new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Bi=/*@__PURE__*/ k(`$ZodCheckRegex`,(e,t)=>{zi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vi=/*@__PURE__*/ k(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Oi,zi.init(e,t)}),Hi=/*@__PURE__*/ k(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ki,zi.init(e,t)}),Ui=/*@__PURE__*/ k(`$ZodCheckIncludes`,(e,t)=>{Ai.init(e,t);let n=Er(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Wi=/*@__PURE__*/ k(`$ZodCheckStartsWith`,(e,t)=>{Ai.init(e,t);let n=RegExp(`^${Er(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gi=/*@__PURE__*/ k(`$ZodCheckEndsWith`,(e,t)=>{Ai.init(e,t);let n=RegExp(`.*${Er(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ki=/*@__PURE__*/ k(`$ZodCheckOverwrite`,(e,t)=>{Ai.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var qi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
@@ -74,25 +74,25 @@ ${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(
74
74
  `),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Iv(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 O(`SSE event exceeded the maximum buffer size.`,D.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a}return{event:o}}async function*Lv(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,`
75
75
  `).replace(/\r/g,`
76
76
  `).split(`
77
- `);r=t.pop()??``;for(let n of t){let t=Iv(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new O(`SSE stream exceeded the maximum buffer size.`,D.GENERAL);let{lines:s,rest:c}=Fv(r);r=c;for(let t of s){let n=Iv(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Iv(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()}}const Rv=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,zv=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Bv(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 Vv(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Bv(await e(Rv,{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 Hv(e,t={}){let n=t.pageSize??50,r=await Vv(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 Vv(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Uv(e,t){return(await Vv(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Wv(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=Bv(await e(Rv,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Gv(e){return e.flatMap(e=>e.items??[])}async function Kv(e,t={}){let n=t.pageSize??50,r=await Wv(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=>Wv(e,{...t,pageNo:r,pageSize:n})));return Gv([r.groups,...o.map(e=>e.groups)].flat())}async function qv(e,t){return(Bv(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 Jv=[`name`,`key`,`default`,`tip`,`range`];function Yv(e){return e.map(e=>{let t={};for(let n of Jv)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Xv(e,t){let n=Bv(await e(zv,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Yv(e):null}catch{return null}return Array.isArray(n)?Yv(n):null}function Zv(e){return{read:()=>$t(e),async write(t){let n=$t(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?st(String(r)):r;await en(n,e)},async unset(t){let n=$t(e);for(let e of t)delete n[e];await en(n,e)},profiles:()=>nn(),activate:e=>on(e),validateActivation:e=>an(e),get path(){return It()}}}const Qv=`{{commandPrefix}}`;function $v(e,t=[],n=[]){return{bin:e.commandInvocation?.bin??e.binName,path:[...e.commandInvocation?.path??[],...t],args:[...n]}}function ey(e,t=``){let n=typeof e==`string`?e:[e.commandInvocation?.bin??e.binName,...e.commandInvocation?.path??[]].join(` `);return t?`${n} ${t}`:n}function ty(e=``){return ey(Qv,e)}function ny(e,t){return e.split(Qv).join(ey(t))}async function ry(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(ae.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:Lg(),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 O(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,D.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new O(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,D.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function iy(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=Rg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ay(e,t,n){return e.requestJson({path:zg(t),method:`GET`,signal:n})}async function oy(e,t,n){let r=await e.request({path:zg(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const sy=209715200,cy=314572800,ly=314572800,uy=2147483648;function dy(e,t=sy){if(!i(e))throw new O(`File not found: ${e}`,D.USAGE);let n=l(e);if(!n.isFile())throw new O(`Not a regular file: ${e}`,D.USAGE);if(n.size===0)throw new O(`File is empty: ${e}`,D.USAGE);if(n.size>t)throw new O(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,D.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function Z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function fy(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 O(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,D.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 py(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 my=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),hy=.1;function gy(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<hy||a>10)&&i.push(Z(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${hy} 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(Z(`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(Z(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function _y(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(Z(`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(Z(`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(Z(`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(Z(`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(Z(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(Z(`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(Z(`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(Z(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...gy(s,Array.isArray(e),t,o))}}}return r}function vy(e,t,n){let r=[];if(!Array.isArray(e))return r.push(Z(`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(Z(`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(Z(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(Z(`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(Z(`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(Z(`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(Z(`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 yy(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(Z(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!my.has(a))&&r.push(Z(`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(Z(`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(..._y(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(Z(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...vy(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(Z(`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(Z(`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 by(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(Z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(Z(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,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(...yy(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(Z(`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(Z(`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(Z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(Z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(Z(`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(Z(`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;xy(a)&&n.push(Z(`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(Z(`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(Z(`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(Z(`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 xy(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 Sy={name:`chatml`,detect:()=>!0,inspect:by};function Cy(e,t){let n=[];if(!(`text`in e))return n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const wy={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Cy};function Ty(e,t){let n=by(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(Z(`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(Z(`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(Z(`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(Z(`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(Z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(Z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...yy(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...yy(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Ey={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Ty},Dy=[`choice`,`noul`,`score`],Oy=255,ky=2,Ay=255,jy=/* @__PURE__ */ new Set([`true`,`false`]);function My(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ny(e){return typeof e==`string`&&e.trim().length>0}function Py(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function Fy(e,t=`state`){return Ny(e)||Array.isArray(e)&&e.length>0||My(e)&&Object.keys(e).length>0?[]:[Py(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function Iy(e,t){let n=`${t}.criteria`;if(!My(e))return[Py(`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[Py(`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(!Ny(t)||!Ny(r))return[Py(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function Ly(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!Ny(e))?[Py(`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?[Py(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function Ry(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return My(e)&&Object.entries(e).every(([e,t])=>jy.has(e)&&typeof t==`string`)?[]:[Py(`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 zy(e,t){if(!My(e))return[Py(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(Py(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...Iy(e.criteria,t)):e.type===`noul`?n.push(...Ry(e.criteria,t)):e.type===`score`?n.push(...Ly(e.criteria,t)):n.push(Py(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function By(e,t=`questions`){return My(e)&&Object.keys(e).length>0?[]:[Py(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function Vy(e,t=`questions`){return Ny(e)?[]:[Py(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function Hy(e,t=`questions`){let n=By(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=Vy(n,t);if(e.length>0){r.push(...e);continue}r.push(...zy(i,`${t}.${n}`))}return r}function Uy(e,t,n,r){return Z(`error`,e,t,{line:n,path:r})}function Wy(e,t){return Uy(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Gy(e,t,n,r){if(!My(e))return[Uy(`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[Uy(`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[Uy(`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?[Uy(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Ky(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[Uy(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Gy(e.target,r,t,`${n}.target`)}function qy(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Gy(e.target,[`true`,`false`],t,`${n}.target`):[Uy(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Jy(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[Uy(`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?[]:Gy(e.target,i,t,`${n}.target`)}function Yy(e,t){let n=Fy(e.state).map(e=>Wy(e,t)),r=e.questions,i=By(r);if(i.length>0)return n.push(...i.map(e=>Wy(e,t))),n;for(let[e,i]of Object.entries(r)){let r=Vy(e);if(r.length>0){n.push(...r.map(e=>Wy(e,t)));continue}let a=`questions.${e}`,o=zy(i,a);if(o.length>0){n.push(...o.map(e=>Wy(e,t)));continue}let s=i;s.type===`choice`?n.push(...Ky(s,t,a)):s.type===`noul`?n.push(...qy(s,t,a)):n.push(...Jy(s,t,a))}return n}const Xy={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:Yy};function Zy(e,t){let n=[];if(!(`wav_fn`in e))n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(Z(`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(Z(`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(Z(`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(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Qy={name:`tts`,detect:e=>`wav_fn`in e,inspect:Zy},$y=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function eb(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function tb(e){return/^[\x20-\x7E]+$/.test(e)}function nb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`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(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=eb(r);$y.has(e)||n.push(Z(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$y].join(`, `)}.`,{line:t,path:`img_path`})),tb(r)||n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=eb(r);$y.has(e)||n.push(Z(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$y].join(`, `)}.`,{line:t,path:`input_img`})),tb(r)||n.push(Z(`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 rb={name:`image`,detect:e=>`img_path`in e,inspect:nb},ib=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),ab=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function ob(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function sb(e){return/^[\x20-\x7E]+$/.test(e)}function cb(e,t,n,r,i,a){if(!(n in t)){r&&e.push(Z(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(Z(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(Z(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=ob(o);i.has(s)||e.push(Z(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),sb(o)||e.push(Z(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function lb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`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(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return cb(n,e,`first_frame_path`,!0,ib,t),cb(n,e,`last_frame_path`,!1,ib,t),cb(n,e,`video_path`,!1,ab,t),n}const ub=[Qy,rb,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:lb},Xy,Ey,wy,Sy];function db(e,t){return t===void 0?ub.find(t=>t.detect(e))??Sy:ub.find(e=>e.name===t)||Sy}async function fb(e,t){let r=n(e,{encoding:`utf8`}),i=oe({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(Z(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function pb(e,t,r,i,a){let o=r?null:new Set(py(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=oe({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(Z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...mb(n,d,i))}return{sampled:c,issues:s}}function mb(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[Z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return db(r,n).inspect(r,t)}const hb={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await fb(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[Z(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await pb(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 gb(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 _b(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 vb=/^[a-zA-Z0-9_-]+$/;function yb(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function bb(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 xb(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||bb(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=yb(n),i=n.slice(e.length);e.length>0&&!vb.test(e)&&t.length<10&&t.push(Z(`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(Z(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=yb(i);if(a.length>120&&t.length<10&&t.push(Z(`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(Z(`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(Z(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Sb(e,t,n){let{entry:i,zipfile:a}=await gb(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 Cb(e,t=100){let r=n(e,{encoding:`utf8`}),i=oe({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 wb={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await _b(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[Z(`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:[Z(`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(Z(`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(Z(`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=xb(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(Z(`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(`/`)||bb(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return $y.has(n)});e.length<25&&r.push(Z(`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-${re(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Sb(e,_,y)}catch(t){return r.push(Z(`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 hb.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Cb(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(Z(`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 Tb(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Eb(e);if(t===`.zip`)return Db(e);throw new O(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,D.USAGE)}async function Eb(e){let t=await kb(e);if(!t)throw new O(`JSONL file is empty or contains only blank lines: ${e}`,D.USAGE);let n=Ob(t);return n===`unknown`?`text`:n}async function Db(e){let t=await Ab(e,`data.jsonl`);if(!t)throw new O(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,D.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Ob(t);if(n===`unknown`)throw new O(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,D.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Ob(e){let t;try{t=JSON.parse(e)}catch{throw new O(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,D.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new O(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,D.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 kb(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=oe({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 Ab(e,t){return gb(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new O(`Failed to read "${t}" from ZIP: ${e?.message}`,D.USAGE));return}let o=oe({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 jb=[hb,wb];function Mb(e){let t=h(e).toLowerCase(),n=jb.find(e=>e.extensions.includes(t));if(!n){let e=jb.flatMap(e=>e.extensions).join(`, `);throw new O(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,D.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Nb(e){jb.some(t=>t.format===e.format)||jb.push(e)}async function Pb(e,t={}){let{bytes:n}=dy(e,t.maxBytes??209715200),r=await Mb(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Fb(){return jb.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Ib(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 Lb=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],Rb=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],zb=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),Bb=524288e3,Vb=6291456,Hb=5e4;function Q(e,t){throw new rt(`${e}\n${t}`)}function Ub(e){if(e instanceof O)return e;let t=e?.code;return new O(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,D.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 Wb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gb(e){return Lb.includes(e)||Q(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*Kb(e){let t=typeof e==`string`?de(e):e instanceof Blob?Ce.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw Ub(e)}}async function*qb(e,t=1/0,n=Vb){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return Q(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of Kb(e)){i+=a.byteLength,i>t&&Q(`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&&Q(`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&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function Jb(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return Q(`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`)||Se(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||Se(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&Q(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)Jb(n,t);else if(Wb(e))for(let[n,r]of Object.entries(e))Jb(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var Yb=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=>Q(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);Wb(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=Gb(String(i.url));Wb(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=>!Wb(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(Wb))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(Wb))))&&r(`body.messages`);Jb(s),Wb(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||Q(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function Xb(e){let t=new Yb,n=0;for await(let r of qb(e,Bb)){n++;let e;try{e=JSON.parse(r.text)}catch{Q(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function Zb(e){let t=[],n=0;for await(let r of Kb(e))n+=r.byteLength,n>524288e3&&Q(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function Qb(e,t,n){return e.requestJson({path:Qh(),method:`POST`,body:t,signal:n})}function $b(e,t,n){return e.requestJson({path:$h(t),signal:n})}function ex(e,t,n){return e.requestJson({path:eg(t),method:`POST`,signal:n})}function tx(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:Qh()+(r.size?`?${r.toString()}`:``),signal:n})}function nx(e,t,n){return e.request({path:tg(t),signal:n})}function rx(e){let t=e.url(Zh(),ng),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))&&Q(`--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 ix(e,t,n=!1){let r=Oe(e),i=Oe(Te(r),`.${we(r)}.${ze()}.tmp`),a,o=e=>{throw Ub(e)};try{await Ne(Te(r),{recursive:!0}).catch(o),a=await Pe(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 Ie(i,r).catch(o):await Me(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await Le(i).catch(()=>{})}}async function ax(e){let t=Gb(e.endpoint??`/v1/chat/completions`);(Oe(e.file)===Oe(e.outputFile)||e.bodyFile&&Oe(e.bodyFile)===Oe(e.outputFile))&&Q(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||Q(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await Fe(e.bodyFile,`utf8`)}catch(e){throw Ub(e)}try{let e=JSON.parse(t);if(!Wb(e))throw Error();i=e}catch{Q(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&Q(`--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)&&Q(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new Yb,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of Kb(e.file)){n+=r.byteLength,n>524288e3&&Q(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=Ce.from(l()),d=Ae({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&Q(`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()||Q(`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)+`
78
- `;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_`)&&Q(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),Ub(e)}finally{u.destroy(),d.destroy()}}if(e.dryRun)for await(let e of u());else await ix(e.outputFile,u(),e.force);return{...c,output_file:Oe(e.outputFile),ignored_columns:s,...e.dryRun?{samples:o}:{}}}const ox=[`custom_id`,`model`,`request_id`,`status_code`,`content`,`embedding`,`error_code`,`error_message`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function sx(e){return Wb(e)?e:{}}function cx(e){let t=e==null?``:typeof e==`string`?e:JSON.stringify(e);return/^[\s\x00-\x1f]*[=+@-]/.test(t)?`'${t}`:t}function lx(e){return typeof e==`number`&&Number.isFinite(e)?e:``}function ux(e){let t=sx(e),n=sx(t.response),r=sx(n.body),i=sx(t.error??r.error),a=sx(r.usage),o=sx(sx(Array.isArray(r.choices)?r.choices[0]:void 0).message),s=Array.isArray(r.data)?r.data.map(e=>{let t=sx(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:cx(t.custom_id),model:cx(r.model),request_id:cx(n.request_id),status_code:lx(n.status_code),content:cx(o.content),embedding:cx(s),error_code:cx(i.code),error_message:cx(i.message),prompt_tokens:lx(a.prompt_tokens),completion_tokens:lx(a.completion_tokens),total_tokens:lx(a.total_tokens)}}}async function dx(e,t,n=!1){let r=0,i=0;async function*a(){yield``+je([],{columns:[...ox],header:!0});for(let t of e)for await(let e of qb(t,1/0,1/0)){if(!e.text.trim())continue;let n;try{n=JSON.parse(e.text)}catch{Q(`Invalid result JSONL at ${t}:${r+1}.`,`结果 JSONL 格式错误:${t}:${r+1}。`)}let a=ux(n);r++,a.recognized||i++,yield je([a.row],{columns:[...ox]})}}return await ix(t,a(),n),{records:r,unknown_records:i}}function fx(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 px(e){let t=t=>{let n=fx(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=je([n.success,n.failure].map(e=>ux(e).row),{columns:[...ox],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 mx=`decision-model-preview`,hx=[`cn-beijing`,`ap-southeast-1`],gx=`cn-beijing`,_x=[`label`,`target`];function vx(e){if(!My(e))return e;let t=e.questions;return My(t)&&typeof t.type!=`string`?t:e}function yx(e){if(!My(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!My(r)){t[n]=r;continue}let e={...r};for(let t of _x)delete e[t];t[n]=e}return t}async function bx(e,t,n,r){let i=await e.requestJson({path:Xh(t,n,`submit`),method:`POST`,body:r});if(typeof i?.data?.biz_id!=`string`||!i.data.biz_id.trim())throw new O(`ParseX response is missing data.biz_id; submission may have succeeded. / ParseX 响应缺少 data.biz_id,任务可能已提交成功。`,void 0,`Check the task before submitting again. / 请核对任务后再决定是否重新提交。`,{api:{requestId:i?.request_id}});return i}async function xx(e,t,n,r,i){let a=await e.requestJson({path:Xh(t,n,`result`),method:`POST`,body:r,signal:i});if(typeof a?.data?.status!=`string`||!a.data.status.trim())throw new O(`ParseX response is missing data.status. / ParseX 响应缺少 data.status。`,void 0,void 0,{api:{requestId:a?.request_id}});return a}async function Sx(e,t,n,r,i){let a=new AbortController,o=()=>a.abort(i.signal?.reason);i.signal?.aborted?o():i.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>a.abort(new O(`ParseX polling timed out. / ParseX 轮询超时。`,D.TIMEOUT,`The remote task was not cancelled; query the same biz_id: ${r.biz_id}. / 未取消远端任务,请使用同一 biz_id 继续查询。`)),i.pollTimeout*1e3);try{for(;;){a.signal.throwIfAborted();try{let o=await xx(e,t,n,r,a.signal);if(a.signal.throwIfAborted(),i.progress?.(o),o.data.status===`success`||o.data.status===`failed`)return o}catch(e){if(a.signal.aborted||!(e instanceof O)||e.api?.apiCode!==`ResultNotReady`)throw e}await Be(i.interval*1e3,void 0,{signal:a.signal})}}catch(e){throw a.signal.aborted?a.signal.reason:e}finally{clearTimeout(s),i.signal?.removeEventListener(`abort`,o)}}async function Cx(e,t,n){return e.requestJson({path:Bg(),method:`POST`,body:t,signal:n})}async function wx(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=Bg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Tx(e,t,n){return e.requestJson({path:Vg(t),method:`GET`,signal:n})}async function Ex(e,t,n){return e.requestJson({path:Hg(t),method:`POST`,signal:n})}async function Dx(e,t,n){return e.requestJson({path:Vg(t),method:`DELETE`,signal:n})}async function Ox(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=Ug(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function kx(e,t){let n=new URLSearchParams;n.set(`input_model`,t.inputModel),n.set(`training_type`,t.trainingType),t.mtuSpecCode&&n.set(`mtu_spec_code`,t.mtuSpecCode),t.paramType&&n.set(`param_type`,t.paramType),t.trainOptions&&Object.keys(t.trainOptions).length>0&&n.set(`hyper_parameters`,JSON.stringify(t.trainOptions)),t.lang&&n.set(`lang`,t.lang);let r=`${Wg()}?${n.toString()}`;return e.requestJson({path:r,method:`GET`,headers:t.workspaceId?{"X-DashScope-WorkSpace":t.workspaceId}:void 0,signal:t.signal})}async function Ax(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=Gg(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,headers:n.workspaceId?{"X-DashScope-WorkSpace":n.workspaceId}:void 0,signal:n.signal})}async function jx(e,t,n){return e.requestJson({path:Kg(t),method:`GET`,signal:n})}async function Mx(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Xg(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Nx(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 Px(e,t={}){return e.requestJson({path:Nx(Zg(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function Fx(e,t,n){return e.requestJson({path:Qg(),method:`POST`,body:t,signal:n})}async function Ix(e,t={}){let n=Nx(Qg(),{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 Lx(e,t,n){return e.requestJson({path:$g(t),method:`GET`,signal:n})}async function Rx(e,t,n={}){return e.requestJson({path:Nx(t_(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function zx(e,t,n){return e.requestJson({path:e_(t),method:`POST`,signal:n})}async function Bx(e,t,n){return e.requestJson({path:$g(t),method:`DELETE`,signal:n})}const Vx={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`}},Hx=Object.keys(Vx),Ux=`sft-lora`;function Wx(e){return e in Vx}function Gx(e){let{method:t,variant:n}=Vx[e];return{method:t,variant:n}}function Kx(e,t){if(!e)return!1;let{method:n,variant:r}=Vx[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function qx(e){return e?Hx.filter(t=>Kx(e,t)):[]}async function Jx(e,t,n={}){return await Uv(En(e,n),t)}const Yx=`INSUFFICIENT_SAMPLES`;function Xx(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Yx,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 within the range published for this model and training type.`].join(`
79
- `)}}function Zx(e){if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Qx(e,t,n){let r=(e-t)/n;return Math.abs(r-Math.round(r))<1e-9}function $x(e,t){let n=new Map(e.flatMap(e=>e.name?[[e.name,e]]:[])),r=[];for(let[e,i]of Object.entries(t)){let t=n.get(e);if(!t){r.push({parameter:e,value:i,code:`unsupported`});continue}if(t.editable===!1){r.push({parameter:e,value:i,code:`not_editable`});continue}let a=String(i),o=t.support_values??[];if(o.length>0&&!o.includes(a)){r.push({parameter:e,value:i,code:`not_supported`,expected:o.join(`, `)});continue}let s=t.data_range??[];if(t.type===`number`||t.type===`intInputNumber`||t.type===`floatInputNumber`||s.length===2||t.step!==void 0){let n=Zx(i);if(n===void 0||t.type===`intInputNumber`&&!Number.isInteger(n)){r.push({parameter:e,value:i,code:`invalid_type`,expected:t.type===`intInputNumber`?`integer`:`number`});continue}let a=Zx(s[0]),o=Zx(s[1]),c=a!==void 0&&(t.left_range===`exclude`?n<=a:n<a),l=o!==void 0&&(t.right_range===`exclude`?n>=o:n>o);if(c||l){let n=t.left_range===`exclude`?`(`:`[`,a=t.right_range===`exclude`?`)`:`]`;r.push({parameter:e,value:i,code:`out_of_range`,expected:`${n}${s[0]}, ${s[1]}${a}`});continue}t.step!==void 0&&t.step>0&&!Qx(n,a??0,t.step)&&r.push({parameter:e,value:i,code:`invalid_step`,expected:`step ${t.step} from ${a??0}`});continue}(i===null||typeof i==`object`||t.type===`input`&&a.trim()===``)&&r.push({parameter:e,value:i,code:`invalid_type`,expected:t.type??`scalar`})}return r}function eS(e,t){let n=e.find(e=>e.name===t);return Zx(n?.defaultValue??n?.recommend_value)}function tS(e){let t={};return e.nEpochs!==void 0&&(t.n_epochs=e.nEpochs),e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0&&(t.batch_size=e.batchSize),t}function nS(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return Pb(e,{...r,schema:n})},resolveHyperParameters(e,t){return tS(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const rS=nS(`sft`,`sft`,`chatml`),iS={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},aS={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},oS={...aS,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},sS={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 cS(e){return e===`image`||e===`image-i2i`}function lS(e){return e===`video`||e===`video-kf2v`}function uS(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function dS(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const fS=[rS,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return Pb(e,{...n,schema:`tts`});if(cS(t))return Pb(e,{...n,schema:`image`,maxBytes:uy});if(lS(t)){let r=await Pb(e,{...n,schema:`video`,maxBytes:uy});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(Z(`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(Z(`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 Pb(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...iS};if(cS(e)){let n={...e===`image-i2i`?oS:aS};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(lS(e)){let e=t.model??t.baseModel,n={...sS,batch_size:dS(e)?1:4,max_pixels:dS(e)?102400:uS(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 tS(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!cS(t)&&!lS(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||cS(e)||lS(e)}},nS(`dpo`,`dpo_full`,`dpo`),nS(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return Pb(e,{...n,schema:`cpt`,maxBytes:cy})},resolveHyperParameters(e,t){return tS(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function pS(e){let t=fS.find(t=>t.clientTrainingType===e);if(!t){let t=fS.map(e=>e.clientTrainingType).join(`, `);throw new O(`Unknown training type "${e}".`,D.USAGE,`Supported training types: ${t}.`)}return t}function mS(){return fS.map(e=>e.clientTrainingType)}const hS=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,gS=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,_S=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function vS(e,t){return Bv(await e.console(hS,{query:{type:0,modelId:t}}))}async function yS(e,t,n){return Bv(await e.console(gS,{input:{trainDatasetIds:t,hyperParams:n}}))}async function bS(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 Bv(await e.console(_S,{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 xS(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function SS(e,t,n){return e.requestJson({path:n_(),method:`POST`,body:t,signal:n})}async function CS(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=n_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function wS(e,t,n){return e.requestJson({path:r_(t),method:`GET`,signal:n})}async function TS(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=i_(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ES(e,t,n,r){return e.requestJson({path:a_(t,n),method:`GET`,signal:r})}async function DS(e,t,n,r){return e.requestJson({path:l_(t,n),method:`GET`,signal:r})}async function OS(e,t,n,r={}){return e.requestJson({path:i_(t),method:`POST`,body:n,headers:xS(r.requestId),signal:r.signal})}async function kS(e,t,n,r,i={}){return e.requestJson({path:o_(t,n),method:`PUT`,body:r,headers:xS(i.requestId),signal:i.signal})}async function AS(e,t,n,r,i={}){return e.requestJson({path:s_(t,n),method:`PUT`,body:r,headers:xS(i.requestId),signal:i.signal})}async function jS(e,t,n,r={}){let i=a_(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:xS(r.requestId),signal:r.signal})}async function MS(e,t,n,r){return e.requestJson({path:c_(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function NS(e,t,n){return e.requestJson({path:r_(t),method:`DELETE`,signal:n})}async function PS(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=f_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function FS(e,t,n,r,i){return e.requestJson({path:u_(t),method:`PUT`,body:n,headers:xS(i),signal:r})}async function IS(e,t,n,r){return e.requestJson({path:d_(t),method:`PUT`,body:n,signal:r})}const LS={LORA:`lora`,PTU:`ptu`,MU:`mu`},RS=LS.LORA;function zS(e){return e===`audio`?LS.MU:RS}const BS={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},VS=BS.POST_PAY,HS={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function US(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.
77
+ `);r=t.pop()??``;for(let n of t){let t=Iv(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new O(`SSE stream exceeded the maximum buffer size.`,D.GENERAL);let{lines:s,rest:c}=Fv(r);r=c;for(let t of s){let n=Iv(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Iv(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 Rv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const zv=/* @__PURE__ */ new Set([`data`,`DataV2`,`success`,`successResponse`,`failed`,`code`,`errorCode`,`errorMsg`,`message`,`requestId`,`request_id`,`traceId`,`httpStatusCode`,`httpStatus`,`api`,`ret`]);function Bv(e,t=!1){return t&&(typeof e.success==`boolean`||typeof e.failed==`boolean`||Array.isArray(e.ret))||Object.hasOwn(e,`DataV2`)||typeof e.successResponse==`boolean`||Object.keys(e).every(e=>zv.has(e))&&(Object.hasOwn(e,`data`)||Object.hasOwn(e,`errorCode`)||Array.isArray(e.ret)||typeof e.success==`boolean`||typeof e.failed==`boolean`)}function Vv(e){if(typeof e==`string`&&e.trim())return e;if(typeof e==`number`)return String(e)}function Hv(e){let t=[],n=e,r;for(;Rv(n)&&Bv(n,r!==void 0);){if(t.push(n),t.length>6)throw new O(`Invalid Console response envelope. / Console 响应信封无效。`,D.GENERAL);if(Object.hasOwn(n,`DataV2`))n=n.DataV2,r=`dataV2`;else if(Object.hasOwn(n,`data`))r=r===`dataV2`?`result`:void 0,n=n.data;else break}let i=t.flatMap(e=>Array.isArray(e.ret)?e.ret.filter(e=>typeof e==`string`&&!e.startsWith(`SUCCESS::`)):[]),a=t.filter(e=>{let t=Vv(e.errorCode);return e.success===!1||e.successResponse===!1||e.failed===!0||e.success!==!0&&e.successResponse!==!0&&t!==void 0&&t!==`0`&&t!==`200`});if(a.length>0||i.length>0){let n=[...a].reverse(),r=n.map(e=>Vv(e.errorMsg)??Vv(e.message)).find(Boolean)??(i.join(`; `)||`Console service failed without a message. / Console 服务失败,未提供错误消息。`),o=n.map(e=>Vv(e.errorCode)??(e.success===!1||e.failed===!0?Vv(e.code):void 0)).find(Boolean),s=t.map(e=>Vv(e.requestId)??Vv(e.request_id)).find(Boolean);throw new O(`${r} (${[`HTTP 200`,o?`code=${o}`:``,s?`request_id=${s}`:``].filter(Boolean).join(`; `)})`,D.GENERAL,void 0,{api:{httpStatus:200,apiCode:o,requestId:s},rawResponse:JSON.stringify(e)})}return n}const Uv=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Wv=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Gv(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 Kv(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Gv(await e(Uv,{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 qv(e,t={}){let n=t.pageSize??50,r=await Kv(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 Kv(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Jv(e,t){return(await Kv(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Yv(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=Gv(await e(Uv,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Xv(e){return e.flatMap(e=>e.items??[])}async function Zv(e,t={}){let n=t.pageSize??50,r=await Yv(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=>Yv(e,{...t,pageNo:r,pageSize:n})));return Xv([r.groups,...o.map(e=>e.groups)].flat())}async function Qv(e,t){return(Gv(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 $v=[`name`,`key`,`default`,`tip`,`range`];function ey(e){return e.map(e=>{let t={};for(let n of $v)e[n]!==void 0&&(t[n]=e[n]);return t})}async function ty(e,t){let n=Gv(await e(Wv,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?ey(e):null}catch{return null}return Array.isArray(n)?ey(n):null}function ny(e){return{read:()=>$t(e),async write(t){let n=$t(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?st(String(r)):r;await en(n,e)},async unset(t){let n=$t(e);for(let e of t)delete n[e];await en(n,e)},profiles:()=>nn(),activate:e=>on(e),validateActivation:e=>an(e),get path(){return It()}}}const ry=`{{commandPrefix}}`;function iy(e,t=[],n=[]){return{bin:e.commandInvocation?.bin??e.binName,path:[...e.commandInvocation?.path??[],...t],args:[...n]}}function ay(e,t=``){let n=typeof e==`string`?e:[e.commandInvocation?.bin??e.binName,...e.commandInvocation?.path??[]].join(` `);return t?`${n} ${t}`:n}function oy(e=``){return ay(ry,e)}function sy(e,t){return e.split(ry).join(ay(t))}const cy=`zeldaEasy.bmp.ossRpcService.download`;function ly(e){if(typeof e!=`string`||!/^https?:\/\//i.test(e))return!1;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}async function uy(e,t){let n=Hv(await e.console(cy,{fileKey:t}));if(typeof n!=`object`||!n||Array.isArray(n)||!(`url`in n)||!ly(n.url))throw new O(`Console file URL response must be an object with a valid HTTP(S) URL. / Console 文件地址响应必须是包含有效 HTTP(S) URL 的对象。`,D.GENERAL);return n}async function dy(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(ae.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:Lg(),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 O(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,D.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new O(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,D.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function fy(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=Rg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function py(e,t,n){return e.requestJson({path:zg(t),method:`GET`,signal:n})}async function my(e,t,n){let r=await e.request({path:zg(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const hy=`zeldaEasy.broadscope-platform.dataset.queryByDatasetId.m_efm`,gy=`zeldaEasy.broadscope-platform.dataset.query.m_efm`,_y=`zeldaEasy.broadscope-platform.datasetGroup.query.m_efm`;function vy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yy(e){return typeof e==`string`&&e.trim().length>0}function by(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=t}function xy(e={}){return{input:{datasetGroupPageNo:e.page??1,datasetGroupPageSize:e.pageSize??10,...e.name===void 0?{}:{name:e.name},datasetPageSize:1,datasetTaskTypeList:[0],datasetTaskPageSize:1}}}async function Sy(e,t={}){let n=Hv(await e.console(_y,xy(t)));if(!vy(n)||!Array.isArray(n.records)||!n.records.every(e=>vy(e)&&yy(e.datasetGroupId))||!by(n.page,1)||!by(n.itemsPerPage,1)||!by(n.items,0)||n.pageCount!==void 0&&!by(n.pageCount,0))throw new O(`Invalid Console dataset groups page: expected records with datasetGroupId and valid page/itemsPerPage/items. / Console 数据集组分页响应无效:需要包含 datasetGroupId 的 records 以及有效的 page/itemsPerPage/items。`,D.GENERAL);return n}function Cy(e){return{input:{datasetGroupId:e,datasetTaskTypeList:[0],datasetTaskPageSize:1}}}function wy(e){let t=Array.isArray(e)?{result:e}:e;if(!vy(t)||!Array.isArray(t.result)||!t.result.every(vy))throw new O(`Console dataset version response must be an object array or contain a result array of objects. / Console 数据集版本响应必须为对象数组或包含对象数组 result。`,D.GENERAL);return t}async function Ty(e,t){let n=wy(Hv(await e.console(gy,Cy(t))));if(!n.result.every(e=>yy(e.datasetId)&&(e.datasetGroupId===void 0||e.datasetGroupId===t)))throw new O(`Console dataset versions have missing version IDs or belong to another dataset group. / Console 数据集版本缺少版本 ID 或属于其他数据集组。`,D.GENERAL);return n}async function Ey(e,t){let n=Hv(await e.console(hy,{input:{datasetId:t}}));if(!vy(n)||![n.datasetId,n.datasetGroupId,n.datasetName].some(e=>typeof e==`string`&&e.trim()))throw new O(`Console dataset query returned no usable metadata. / Console 数据集查询未返回可用元信息。`,D.GENERAL);if(n.datasetId!==void 0&&n.datasetId!==t)throw new O(`Console dataset response does not match the requested version ID. / Console 数据集响应与请求的版本 ID 不匹配。`,D.GENERAL);return n}function Dy(e,t){return{input:{datasetId:e,datasetGroupId:t,page:1,itemsPerPage:1,datasetTaskTypeList:[0],datasetTaskPageSize:1}}}async function Oy(e,t,n){let r=wy(Hv(await e.console(gy,Dy(t,n)))).result.filter(e=>e.datasetId===t);if(r.length>1)throw new O(`Console dataset query returned multiple matches for one version ID. / Console 数据集查询为同一版本 ID 返回了多个匹配项。`,D.GENERAL);let i=r[0]??null;if(i&&i.datasetGroupId!==void 0&&i.datasetGroupId!==n)throw new O(`Console dataset version belongs to a different dataset group. / Console 数据集版本所属组与查询目标不匹配。`,D.GENERAL);return i}function ky(e){let t=e&&vy(e.datasetTaskDTO)?e.datasetTaskDTO:void 0;return{release_status:e?.releaseStatus==null?`missing`:`returned`,import_status:t?.taskStatus==null?`missing`:`returned`}}const Ay=209715200,jy=314572800,My=314572800,Ny=2147483648;function Py(e,t=Ay){if(!i(e))throw new O(`File not found: ${e}`,D.USAGE);let n=l(e);if(!n.isFile())throw new O(`Not a regular file: ${e}`,D.USAGE);if(n.size===0)throw new O(`File is empty: ${e}`,D.USAGE);if(n.size>t)throw new O(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,D.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function Z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function Fy(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 O(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,D.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 Iy(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 Ly=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),Ry=.1;function zy(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<Ry||a>10)&&i.push(Z(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${Ry} 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(Z(`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(Z(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function By(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(Z(`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(Z(`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(Z(`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(Z(`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(Z(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(Z(`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(Z(`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(Z(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...zy(s,Array.isArray(e),t,o))}}}return r}function Vy(e,t,n){let r=[];if(!Array.isArray(e))return r.push(Z(`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(Z(`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(Z(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(Z(`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(Z(`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(Z(`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(Z(`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 Hy(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(Z(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!Ly.has(a))&&r.push(Z(`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(Z(`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(...By(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(Z(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...Vy(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(Z(`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(Z(`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 Uy(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(Z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(Z(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,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(...Hy(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(Z(`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(Z(`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(Z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(Z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(Z(`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(Z(`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;Wy(a)&&n.push(Z(`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(Z(`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(Z(`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(Z(`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 Wy(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 Gy={name:`chatml`,detect:()=>!0,inspect:Uy};function Ky(e,t){let n=[];if(!(`text`in e))return n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const qy={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ky};function Jy(e,t){let n=Uy(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(Z(`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(Z(`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(Z(`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(Z(`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(Z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(Z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Hy(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Hy(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const Yy={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Jy},Xy=[`choice`,`noul`,`score`],Zy=255,Qy=2,$y=255,eb=/* @__PURE__ */ new Set([`true`,`false`]);function tb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nb(e){return typeof e==`string`&&e.trim().length>0}function rb(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function ib(e,t=`state`){return nb(e)||Array.isArray(e)&&e.length>0||tb(e)&&Object.keys(e).length>0?[]:[rb(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function ab(e,t){let n=`${t}.criteria`;if(!tb(e))return[rb(`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[rb(`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(!nb(t)||!nb(r))return[rb(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function ob(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!nb(e))?[rb(`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?[rb(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function sb(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return tb(e)&&Object.entries(e).every(([e,t])=>eb.has(e)&&typeof t==`string`)?[]:[rb(`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 cb(e,t){if(!tb(e))return[rb(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(rb(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...ab(e.criteria,t)):e.type===`noul`?n.push(...sb(e.criteria,t)):e.type===`score`?n.push(...ob(e.criteria,t)):n.push(rb(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function lb(e,t=`questions`){return tb(e)&&Object.keys(e).length>0?[]:[rb(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function ub(e,t=`questions`){return nb(e)?[]:[rb(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function db(e,t=`questions`){let n=lb(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=ub(n,t);if(e.length>0){r.push(...e);continue}r.push(...cb(i,`${t}.${n}`))}return r}function fb(e,t,n,r){return Z(`error`,e,t,{line:n,path:r})}function pb(e,t){return fb(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function mb(e,t,n,r){if(!tb(e))return[fb(`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[fb(`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[fb(`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?[fb(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function hb(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[fb(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:mb(e.target,r,t,`${n}.target`)}function gb(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:mb(e.target,[`true`,`false`],t,`${n}.target`):[fb(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function _b(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[fb(`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?[]:mb(e.target,i,t,`${n}.target`)}function vb(e,t){let n=ib(e.state).map(e=>pb(e,t)),r=e.questions,i=lb(r);if(i.length>0)return n.push(...i.map(e=>pb(e,t))),n;for(let[e,i]of Object.entries(r)){let r=ub(e);if(r.length>0){n.push(...r.map(e=>pb(e,t)));continue}let a=`questions.${e}`,o=cb(i,a);if(o.length>0){n.push(...o.map(e=>pb(e,t)));continue}let s=i;s.type===`choice`?n.push(...hb(s,t,a)):s.type===`noul`?n.push(...gb(s,t,a)):n.push(..._b(s,t,a))}return n}const yb={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:vb};function bb(e,t){let n=[];if(!(`wav_fn`in e))n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(Z(`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(Z(`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(Z(`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(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const xb={name:`tts`,detect:e=>`wav_fn`in e,inspect:bb},Sb=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Cb(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function wb(e){return/^[\x20-\x7E]+$/.test(e)}function Tb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`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(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Cb(r);Sb.has(e)||n.push(Z(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Sb].join(`, `)}.`,{line:t,path:`img_path`})),wb(r)||n.push(Z(`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(Z(`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(Z(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Cb(r);Sb.has(e)||n.push(Z(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Sb].join(`, `)}.`,{line:t,path:`input_img`})),wb(r)||n.push(Z(`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 Eb={name:`image`,detect:e=>`img_path`in e,inspect:Tb},Db=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Ob=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function kb(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Ab(e){return/^[\x20-\x7E]+$/.test(e)}function jb(e,t,n,r,i,a){if(!(n in t)){r&&e.push(Z(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(Z(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(Z(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=kb(o);i.has(s)||e.push(Z(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Ab(o)||e.push(Z(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Mb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`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(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return jb(n,e,`first_frame_path`,!0,Db,t),jb(n,e,`last_frame_path`,!1,Db,t),jb(n,e,`video_path`,!1,Ob,t),n}const Nb=[xb,Eb,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Mb},yb,Yy,qy,Gy];function Pb(e,t){return t===void 0?Nb.find(t=>t.detect(e))??Gy:Nb.find(e=>e.name===t)||Gy}async function Fb(e,t){let r=n(e,{encoding:`utf8`}),i=oe({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(Z(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function Ib(e,t,r,i,a){let o=r?null:new Set(Iy(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=oe({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(Z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...Lb(n,d,i))}return{sampled:c,issues:s}}function Lb(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[Z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Pb(r,n).inspect(r,t)}const Rb={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Fb(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[Z(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Ib(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 zb(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 Bb(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 Vb=/^[a-zA-Z0-9_-]+$/;function Hb(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function Ub(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 Wb(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||Ub(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Hb(n),i=n.slice(e.length);e.length>0&&!Vb.test(e)&&t.length<10&&t.push(Z(`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(Z(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Hb(i);if(a.length>120&&t.length<10&&t.push(Z(`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(Z(`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(Z(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Gb(e,t,n){let{entry:i,zipfile:a}=await zb(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 Kb(e,t=100){let r=n(e,{encoding:`utf8`}),i=oe({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 qb={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Bb(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[Z(`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:[Z(`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(Z(`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(Z(`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=Wb(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(Z(`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(`/`)||Ub(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Sb.has(n)});e.length<25&&r.push(Z(`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-${re(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Gb(e,_,y)}catch(t){return r.push(Z(`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 Rb.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Kb(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(Z(`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 Jb(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Yb(e);if(t===`.zip`)return Xb(e);throw new O(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,D.USAGE)}async function Yb(e){let t=await Qb(e);if(!t)throw new O(`JSONL file is empty or contains only blank lines: ${e}`,D.USAGE);let n=Zb(t);return n===`unknown`?`text`:n}async function Xb(e){let t=await $b(e,`data.jsonl`);if(!t)throw new O(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,D.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Zb(t);if(n===`unknown`)throw new O(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,D.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Zb(e){let t;try{t=JSON.parse(e)}catch{throw new O(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,D.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new O(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,D.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 Qb(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=oe({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 $b(e,t){return zb(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new O(`Failed to read "${t}" from ZIP: ${e?.message}`,D.USAGE));return}let o=oe({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 ex=[Rb,qb];function tx(e){let t=h(e).toLowerCase(),n=ex.find(e=>e.extensions.includes(t));if(!n){let e=ex.flatMap(e=>e.extensions).join(`, `);throw new O(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,D.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function nx(e){ex.some(t=>t.format===e.format)||ex.push(e)}async function rx(e,t={}){let{bytes:n}=Py(e,t.maxBytes??209715200),r=await tx(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function ix(){return ex.map(e=>({format:e.format,extensions:[...e.extensions]}))}function ax(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 ox=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],sx=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],cx=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),lx=524288e3,ux=6291456,dx=5e4;function Q(e,t){throw new rt(`${e}\n${t}`)}function fx(e){if(e instanceof O)return e;let t=e?.code;return new O(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,D.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 px(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mx(e){return ox.includes(e)||Q(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*hx(e){let t=typeof e==`string`?de(e):e instanceof Blob?Ce.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw fx(e)}}async function*gx(e,t=1/0,n=ux){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return Q(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of hx(e)){i+=a.byteLength,i>t&&Q(`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&&Q(`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&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function _x(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return Q(`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`)||Se(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||Se(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&Q(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)_x(n,t);else if(px(e))for(let[n,r]of Object.entries(e))_x(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var vx=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=>Q(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);px(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=mx(String(i.url));px(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=>!px(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(px))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(px))))&&r(`body.messages`);_x(s),px(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||Q(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function yx(e){let t=new vx,n=0;for await(let r of gx(e,lx)){n++;let e;try{e=JSON.parse(r.text)}catch{Q(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function bx(e){let t=[],n=0;for await(let r of hx(e))n+=r.byteLength,n>524288e3&&Q(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function xx(e,t,n){return e.requestJson({path:Qh(),method:`POST`,body:t,signal:n})}function Sx(e,t,n){return e.requestJson({path:$h(t),signal:n})}function Cx(e,t,n){return e.requestJson({path:eg(t),method:`POST`,signal:n})}function wx(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:Qh()+(r.size?`?${r.toString()}`:``),signal:n})}function Tx(e,t,n){return e.request({path:tg(t),signal:n})}function Ex(e){let t=e.url(Zh(),ng),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))&&Q(`--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 Dx(e,t,n=!1){let r=Oe(e),i=Oe(Te(r),`.${we(r)}.${ze()}.tmp`),a,o=e=>{throw fx(e)};try{await Ne(Te(r),{recursive:!0}).catch(o),a=await Pe(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 Ie(i,r).catch(o):await Me(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await Le(i).catch(()=>{})}}async function Ox(e){let t=mx(e.endpoint??`/v1/chat/completions`);(Oe(e.file)===Oe(e.outputFile)||e.bodyFile&&Oe(e.bodyFile)===Oe(e.outputFile))&&Q(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||Q(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await Fe(e.bodyFile,`utf8`)}catch(e){throw fx(e)}try{let e=JSON.parse(t);if(!px(e))throw Error();i=e}catch{Q(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&Q(`--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)&&Q(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new vx,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of hx(e.file)){n+=r.byteLength,n>524288e3&&Q(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=Ce.from(l()),d=Ae({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&Q(`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()||Q(`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)+`
78
+ `;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_`)&&Q(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),fx(e)}finally{u.destroy(),d.destroy()}}if(e.dryRun)for await(let e of u());else await Dx(e.outputFile,u(),e.force);return{...c,output_file:Oe(e.outputFile),ignored_columns:s,...e.dryRun?{samples:o}:{}}}const kx=[`custom_id`,`model`,`request_id`,`status_code`,`content`,`embedding`,`error_code`,`error_message`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function Ax(e){return px(e)?e:{}}function jx(e){let t=e==null?``:typeof e==`string`?e:JSON.stringify(e);return/^[\s\x00-\x1f]*[=+@-]/.test(t)?`'${t}`:t}function Mx(e){return typeof e==`number`&&Number.isFinite(e)?e:``}function Nx(e){let t=Ax(e),n=Ax(t.response),r=Ax(n.body),i=Ax(t.error??r.error),a=Ax(r.usage),o=Ax(Ax(Array.isArray(r.choices)?r.choices[0]:void 0).message),s=Array.isArray(r.data)?r.data.map(e=>{let t=Ax(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:jx(t.custom_id),model:jx(r.model),request_id:jx(n.request_id),status_code:Mx(n.status_code),content:jx(o.content),embedding:jx(s),error_code:jx(i.code),error_message:jx(i.message),prompt_tokens:Mx(a.prompt_tokens),completion_tokens:Mx(a.completion_tokens),total_tokens:Mx(a.total_tokens)}}}async function Px(e,t,n=!1){let r=0,i=0;async function*a(){yield``+je([],{columns:[...kx],header:!0});for(let t of e)for await(let e of gx(t,1/0,1/0)){if(!e.text.trim())continue;let n;try{n=JSON.parse(e.text)}catch{Q(`Invalid result JSONL at ${t}:${r+1}.`,`结果 JSONL 格式错误:${t}:${r+1}。`)}let a=Nx(n);r++,a.recognized||i++,yield je([a.row],{columns:[...kx]})}}return await Dx(t,a(),n),{records:r,unknown_records:i}}function Fx(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 Ix(e){let t=t=>{let n=Fx(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=je([n.success,n.failure].map(e=>Nx(e).row),{columns:[...kx],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 Lx=`decision-model-preview`,Rx=[`cn-beijing`,`ap-southeast-1`],zx=`cn-beijing`,Bx=[`label`,`target`];function Vx(e){if(!tb(e))return e;let t=e.questions;return tb(t)&&typeof t.type!=`string`?t:e}function Hx(e){if(!tb(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!tb(r)){t[n]=r;continue}let e={...r};for(let t of Bx)delete e[t];t[n]=e}return t}async function Ux(e,t,n,r){let i=await e.requestJson({path:Xh(t,n,`submit`),method:`POST`,body:r});if(typeof i?.data?.biz_id!=`string`||!i.data.biz_id.trim())throw new O(`ParseX response is missing data.biz_id; submission may have succeeded. / ParseX 响应缺少 data.biz_id,任务可能已提交成功。`,void 0,`Check the task before submitting again. / 请核对任务后再决定是否重新提交。`,{api:{requestId:i?.request_id}});return i}async function Wx(e,t,n,r,i){let a=await e.requestJson({path:Xh(t,n,`result`),method:`POST`,body:r,signal:i});if(typeof a?.data?.status!=`string`||!a.data.status.trim())throw new O(`ParseX response is missing data.status. / ParseX 响应缺少 data.status。`,void 0,void 0,{api:{requestId:a?.request_id}});return a}async function Gx(e,t,n,r,i){let a=new AbortController,o=()=>a.abort(i.signal?.reason);i.signal?.aborted?o():i.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>a.abort(new O(`ParseX polling timed out. / ParseX 轮询超时。`,D.TIMEOUT,`The remote task was not cancelled; query the same biz_id: ${r.biz_id}. / 未取消远端任务,请使用同一 biz_id 继续查询。`)),i.pollTimeout*1e3);try{for(;;){a.signal.throwIfAborted();try{let o=await Wx(e,t,n,r,a.signal);if(a.signal.throwIfAborted(),i.progress?.(o),o.data.status===`success`||o.data.status===`failed`)return o}catch(e){if(a.signal.aborted||!(e instanceof O)||e.api?.apiCode!==`ResultNotReady`)throw e}await Be(i.interval*1e3,void 0,{signal:a.signal})}}catch(e){throw a.signal.aborted?a.signal.reason:e}finally{clearTimeout(s),i.signal?.removeEventListener(`abort`,o)}}async function Kx(e,t,n){return e.requestJson({path:Bg(),method:`POST`,body:t,signal:n})}async function qx(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=Bg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Jx(e,t,n){return e.requestJson({path:Vg(t),method:`GET`,signal:n})}async function Yx(e,t,n){return e.requestJson({path:Hg(t),method:`POST`,signal:n})}async function Xx(e,t,n){return e.requestJson({path:Vg(t),method:`DELETE`,signal:n})}async function Zx(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=Ug(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Qx(e,t){let n=new URLSearchParams;n.set(`input_model`,t.inputModel),n.set(`training_type`,t.trainingType),t.mtuSpecCode&&n.set(`mtu_spec_code`,t.mtuSpecCode),t.paramType&&n.set(`param_type`,t.paramType),t.trainOptions&&Object.keys(t.trainOptions).length>0&&n.set(`hyper_parameters`,JSON.stringify(t.trainOptions)),t.lang&&n.set(`lang`,t.lang);let r=`${Wg()}?${n.toString()}`;return e.requestJson({path:r,method:`GET`,headers:t.workspaceId?{"X-DashScope-WorkSpace":t.workspaceId}:void 0,signal:t.signal})}async function $x(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=Gg(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,headers:n.workspaceId?{"X-DashScope-WorkSpace":n.workspaceId}:void 0,signal:n.signal})}async function eS(e,t,n){return e.requestJson({path:Kg(t),method:`GET`,signal:n})}async function tS(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Xg(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function nS(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 rS(e,t={}){return e.requestJson({path:nS(Zg(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function iS(e,t,n){return e.requestJson({path:Qg(),method:`POST`,body:t,signal:n})}async function aS(e,t={}){let n=nS(Qg(),{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 oS(e,t,n){return e.requestJson({path:$g(t),method:`GET`,signal:n})}async function sS(e,t,n={}){return e.requestJson({path:nS(t_(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function cS(e,t,n){return e.requestJson({path:e_(t),method:`POST`,signal:n})}async function lS(e,t,n){return e.requestJson({path:$g(t),method:`DELETE`,signal:n})}const uS={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`}},dS=Object.keys(uS),fS=`sft-lora`;function pS(e){return e in uS}function mS(e){let{method:t,variant:n}=uS[e];return{method:t,variant:n}}function hS(e,t){if(!e)return!1;let{method:n,variant:r}=uS[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function gS(e){return e?dS.filter(t=>hS(e,t)):[]}async function _S(e,t,n={}){return await Jv(En(e,n),t)}const vS=`INSUFFICIENT_SAMPLES`;function yS(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:vS,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 within the range published for this model and training type.`].join(`
79
+ `)}}function bS(e){if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.trim()===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function xS(e,t,n){let r=(e-t)/n;return Math.abs(r-Math.round(r))<1e-9}function SS(e,t){let n=new Map(e.flatMap(e=>e.name?[[e.name,e]]:[])),r=[];for(let[e,i]of Object.entries(t)){let t=n.get(e);if(!t){r.push({parameter:e,value:i,code:`unsupported`});continue}if(t.editable===!1){r.push({parameter:e,value:i,code:`not_editable`});continue}let a=String(i),o=t.support_values??[];if(o.length>0&&!o.includes(a)){r.push({parameter:e,value:i,code:`not_supported`,expected:o.join(`, `)});continue}let s=t.data_range??[];if(t.type===`number`||t.type===`intInputNumber`||t.type===`floatInputNumber`||s.length===2||t.step!==void 0){let n=bS(i);if(n===void 0||t.type===`intInputNumber`&&!Number.isInteger(n)){r.push({parameter:e,value:i,code:`invalid_type`,expected:t.type===`intInputNumber`?`integer`:`number`});continue}let a=bS(s[0]),o=bS(s[1]),c=a!==void 0&&(t.left_range===`exclude`?n<=a:n<a),l=o!==void 0&&(t.right_range===`exclude`?n>=o:n>o);if(c||l){let n=t.left_range===`exclude`?`(`:`[`,a=t.right_range===`exclude`?`)`:`]`;r.push({parameter:e,value:i,code:`out_of_range`,expected:`${n}${s[0]}, ${s[1]}${a}`});continue}t.step!==void 0&&t.step>0&&!xS(n,a??0,t.step)&&r.push({parameter:e,value:i,code:`invalid_step`,expected:`step ${t.step} from ${a??0}`});continue}(i===null||typeof i==`object`||t.type===`input`&&a.trim()===``)&&r.push({parameter:e,value:i,code:`invalid_type`,expected:t.type??`scalar`})}return r}function CS(e,t){let n=e.find(e=>e.name===t);return bS(n?.defaultValue??n?.recommend_value)}function wS(e){let t={};return e.nEpochs!==void 0&&(t.n_epochs=e.nEpochs),e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0&&(t.batch_size=e.batchSize),t}function TS(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return rx(e,{...r,schema:n})},resolveHyperParameters(e,t){return wS(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const ES=TS(`sft`,`sft`,`chatml`),DS={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},OS={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},kS={...OS,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},AS={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 jS(e){return e===`image`||e===`image-i2i`}function MS(e){return e===`video`||e===`video-kf2v`}function NS(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function PS(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const FS=[ES,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return rx(e,{...n,schema:`tts`});if(jS(t))return rx(e,{...n,schema:`image`,maxBytes:Ny});if(MS(t)){let r=await rx(e,{...n,schema:`video`,maxBytes:Ny});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(Z(`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(Z(`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 rx(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...DS};if(jS(e)){let n={...e===`image-i2i`?kS:OS};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(MS(e)){let e=t.model??t.baseModel,n={...AS,batch_size:PS(e)?1:4,max_pixels:PS(e)?102400:NS(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 wS(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!jS(t)&&!MS(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||jS(e)||MS(e)}},TS(`dpo`,`dpo_full`,`dpo`),TS(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return rx(e,{...n,schema:`cpt`,maxBytes:jy})},resolveHyperParameters(e,t){return wS(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function IS(e){let t=FS.find(t=>t.clientTrainingType===e);if(!t){let t=FS.map(e=>e.clientTrainingType).join(`, `);throw new O(`Unknown training type "${e}".`,D.USAGE,`Supported training types: ${t}.`)}return t}function LS(){return FS.map(e=>e.clientTrainingType)}const RS=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,zS=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,BS=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function VS(e,t){return Gv(await e.console(RS,{query:{type:0,modelId:t}}))}async function HS(e,t,n){return Gv(await e.console(zS,{input:{trainDatasetIds:t,hyperParams:n}}))}async function US(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 Gv(await e.console(BS,{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 WS(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function GS(e,t,n){return e.requestJson({path:n_(),method:`POST`,body:t,signal:n})}async function KS(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=n_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function qS(e,t,n){return e.requestJson({path:r_(t),method:`GET`,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)),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=i_(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function YS(e,t,n,r){return e.requestJson({path:a_(t,n),method:`GET`,signal:r})}async function XS(e,t,n,r){return e.requestJson({path:l_(t,n),method:`GET`,signal:r})}async function ZS(e,t,n,r={}){return e.requestJson({path:i_(t),method:`POST`,body:n,headers:WS(r.requestId),signal:r.signal})}async function QS(e,t,n,r,i={}){return e.requestJson({path:o_(t,n),method:`PUT`,body:r,headers:WS(i.requestId),signal:i.signal})}async function $S(e,t,n,r,i={}){return e.requestJson({path:s_(t,n),method:`PUT`,body:r,headers:WS(i.requestId),signal:i.signal})}async function eC(e,t,n,r={}){let i=a_(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:WS(r.requestId),signal:r.signal})}async function tC(e,t,n,r){return e.requestJson({path:c_(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function nC(e,t,n){return e.requestJson({path:r_(t),method:`DELETE`,signal:n})}async function rC(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=f_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function iC(e,t,n,r,i){return e.requestJson({path:u_(t),method:`PUT`,body:n,headers:WS(i),signal:r})}async function aC(e,t,n,r){return e.requestJson({path:d_(t),method:`PUT`,body:n,signal:r})}const oC={LORA:`lora`,PTU:`ptu`,MU:`mu`},sC=oC.LORA;function cC(e){return e===`audio`?oC.MU:sC}const lC={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},uC=lC.POST_PAY,dC={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function fC(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.
80
80
  必须同时提供 --input-tpm 和 --output-tpm。`;if(!Number.isSafeInteger(e.inputTpm)||e.inputTpm<0)return`--input-tpm must be a non-negative safe integer in kTPM.
81
81
  --input-tpm 必须是非负安全整数,单位为 kTPM。`;if(!Number.isSafeInteger(e.outputTpm)||e.outputTpm<0)return`--output-tpm must be a non-negative safe integer in kTPM.
82
- --output-tpm 必须是非负安全整数,单位为 kTPM。`}}function WS(e){let t={};return e.inputTpm!==void 0&&(t.input_tpm=e.inputTpm),e.outputTpm!==void 0&&(t.output_tpm=e.outputTpm),t}function GS(e){return e.duration!==void 0||e.autoRenewal!==void 0||e.autoRenewalDuration!==void 0||e.autoRenewalCycle!==void 0}function KS(e,t){if(t||GS(e)){if(e.duration===void 0||!Number.isSafeInteger(e.duration)||e.duration<=0)return`--duration must be a positive safe integer in days.
82
+ --output-tpm 必须是非负安全整数,单位为 kTPM。`}}function pC(e){let t={};return e.inputTpm!==void 0&&(t.input_tpm=e.inputTpm),e.outputTpm!==void 0&&(t.output_tpm=e.outputTpm),t}function mC(e){return e.duration!==void 0||e.autoRenewal!==void 0||e.autoRenewalDuration!==void 0||e.autoRenewalCycle!==void 0}function hC(e,t){if(t||mC(e)){if(e.duration===void 0||!Number.isSafeInteger(e.duration)||e.duration<=0)return`--duration must be a positive safe integer in days.
83
83
  --duration 必须是正安全整数,单位为天。`;if(typeof e.autoRenewal!=`boolean`)return`--auto-renewal must explicitly be true or false.
84
84
  必须显式指定 --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.
85
85
  --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.
86
- --auto-renewal-cycle 必须是非空字符串。`}}function qS(e){if(!GS(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 JS={name:LS.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},YS={name:LS.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.
87
- plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==HS.PRE_PAID&&e.chargeType!==HS.POST_PAID?`--charge-type is required for plan=ptu and must be pre_paid or post_paid.
86
+ --auto-renewal-cycle 必须是非空字符串。`}}function gC(e){if(!mC(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 _C={name:oC.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},vC={name:oC.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.
87
+ plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==dC.PRE_PAID&&e.chargeType!==dC.POST_PAID?`--charge-type is required for plan=ptu and must be pre_paid or post_paid.
88
88
  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.
89
- --service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===HS.POST_PAID?`ptu_default only supports pre_paid.
90
- ptu_default 仅支持 pre_paid。`:e.chargeType===HS.POST_PAID&&GS(e)?`Prepaid flags are not allowed with --charge-type post_paid.
91
- --charge-type post_paid 不允许提供预付费参数。`:US(e,!0)??KS(e,e.chargeType===HS.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
92
- 当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:WS(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=qS(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},XS={name:LS.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||VS,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new O(`No mu-plan template found for model "${e.model}". `+(e.modelUnavailableHint??`Pass --deploy-spec explicitly.`),D.USAGE);try{let a=await PS(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===LS.MU)?.templates??[];if(o.length===0)throw i();let s=t===BS.POST_PAY?HS.POST_PAID:HS.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 O?e:new O(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,D.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},ZS={[LS.LORA]:JS,[LS.PTU]:YS,[LS.MU]:XS};function QS(e){let t=ZS[e];if(!t)throw new O(`Unsupported plan "${e}". Supported plans: ${Object.keys(ZS).join(`, `)}.`,D.USAGE);return t}const $S=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,eC=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,tC=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function nC(e,t){return Bv(await e.console($S,{input:{modelServiceId:t}}))}async function rC(e,t){return Bv(await e.console(eC,{input:{modelServiceId:t}}))}async function iC(e){let t=[],n=1;for(;;){let r=Bv(await e.console(tC,{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 aC(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}async function oC(e,t,n){return e.requestJson({path:Jg(),method:`POST`,body:t,signal:n})}async function sC(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.modelName&&n.set(`model_name`,t.modelName);let r=Jg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function cC(e,t,n){return e.requestJson({path:Yg(t),method:`GET`,signal:n})}async function lC(e,t,n){return e.requestJson({path:Yg(t),method:`DELETE`,signal:n})}const uC=`zeldaEasy.broadscope-platform.customModel.listSupportImportModels`;async function dC(e){let t=Bv(await e.console(uC,{}));return{total:t.total,pageNo:t.pageNo,pageSize:t.pageSize,list:t.list??[]}}function fC(e,t){let n=t.trim().toLowerCase();return e.find(e=>String(e.model??``).toLowerCase()===n)}function pC(e){return e===`lora`?`efficient_sft`:`sft`}const mC=`speech-biasing`;function hC(e,t){return{model:mC,input:{action:e,...t}}}async function gC(e,t,n,r){return e.requestJson({path:wg(),method:`POST`,body:hC(t,n),signal:r})}function _C(e,t,n){return gC(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function vC(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),gC(e,`list_vocabulary`,r,n)}function yC(e,t,n){return gC(e,`query_vocabulary`,{vocabulary_id:t},n)}function bC(e,t,n,r){return gC(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function xC(e,t,n){return gC(e,`delete_vocabulary`,{vocabulary_id:t},n)}function SC(e,t){try{return JSON.parse(e)}catch(e){throw new rt(`${t} is not valid JSON — ${e.message}`)}}function CC(e){let t=SC(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new rt(`--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 rt(`--vocabulary weight for "${e}" must be a number.`);return t}function wC(e,t){let n=`--words`,r=SC(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new rt(`${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 rt(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new rt(`${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 rt(`${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 rt(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new rt(`${n} must contain at least one hot word.`);return i}const TC={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":`显示版本信息`}}},EC={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},DC={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},OC={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`}}},kC={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)`}}},AC={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 jC(e){return e.auth===`apiKey`?e.optionalConsole?{...OC,...kC}:OC:e.auth===`console`?kC:e.auth===`openapi`?AC:{}}function MC(e){return e}const NC=1;function PC(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function FC(e,t){return`${PC(e||`image`,`image`)}_${PC((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function IC(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return LC(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 LC(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const RC=()=>g(f(),`bailian-output`);function zC(e,t){let n=t?.flagDir||e.outputDir||RC(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function BC(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function VC(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function HC(e){return o(e===`-`?0:e,`utf-8`)}async function UC(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 WC(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 O(`Invalid ${t} value "${String(e)}". Use true or false.`,D.USAGE)}function GC(e,t=`boolean`){if(e!=null)return WC(e,t)}function KC(e,t,n=`boolean`){let r=GC(e,n);return r===void 0?t:r}function qC(e,t){return GC(e,`watermark`)??t??!0}const JC=`BAILIAN_CALLER_NAME`,YC=/^[a-z0-9][a-z0-9.-]{0,63}$/,XC=/^bailian-[a-z0-9-]{1,64}$/,ZC=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function QC(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function $C(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return YC.test(t)?t:`unknown`}function ew(e){let t=QC(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t===`agent`||t===`ai_agent`){let t=QC(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),n=t!==void 0&&XC.test(t)?t:void 0,r=QC(e,`BAILIAN_SKILL_VERSION`),i=n!==void 0&&r!==void 0&&ZC.test(r)?r:void 0;return{callerType:`agent`,callerName:$C(QC(e,JC)),...n===void 0?{}:{skillName:n},...i===void 0?{}:{skillVersion:i}}}return t===`script`?{callerType:`script`,callerName:$C(QC(e,JC))}:{callerType:`unknown`}}function tw(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.identity.version,commandPrefix:ey(e.identity),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.caller.callerType===`script`&&(t.callerName=e.caller.callerName),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 nw(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function rw(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=nw(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let iw;function aw(){return iw||(process.env.NODE_ENV===`development`?(iw=`dev`,iw):process.env.BAILIAN_COMPILED===`1`?(iw=`prod`,iw):(iw=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,iw))}var ow=/* @__PURE__ */ E(((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=et(`os`)},function(e,t){e.exports=(...e)=>(process.versions.bun?globalThis.fetch:et(`undici`).fetch)(...e)},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=et(`dns`)},function(e,t){e.exports=et(`util`)},function(e,t){e.exports=et(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},ie=(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`},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`},pe=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},he=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ge=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},_e=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ve=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map;C.set(`Baiduspider-render`,i),C.set(`Baiduspider+`,i),C.set(`Baiduspider-image+`,i),C.set(`360Spider`,a),C.set(`360Spider-Image`,a),C.set(`bingbot`,o),C.set(`Googlebot`,s),C.set(`YandexRenderResourcesBot`,c),C.set(`spider`,l),C.set(`Dataprovider.com`,u),C.set(`AhrefsBot`,d),C.set(`BitSightBot`,f),C.set(`oBot`,p),C.set(`Cincraw`,m),C.set(`DingTalkBot-LinkService`,h),C.set(`YisouSpider`,g),C.set(`Bytespider`,_),C.set(`ev-crawler`,v),C.set(`bitdiscovery`,y),C.set(`Spider`,b),C.set(`Ai2Bot-Dolma`,x),C.set(`dianjing_ad_spider`,ee),w.set(`Baiduspider-render`,te),w.set(`Baiduspider+`,te),w.set(`Baiduspider-image+`,te),w.set(`360Spider`,ne),w.set(`360Spider-Image`,ne),w.set(`bingbot`,re),w.set(`Googlebot`,ie),w.set(`YandexRenderResourcesBot`,ae),w.set(`spider`,oe),w.set(`Dataprovider.com`,se),w.set(`AhrefsBot`,ce),w.set(`BitSightBot`,le),w.set(`oBot`,ue),w.set(`Cincraw`,de),w.set(`DingTalkBot-LinkService`,fe),w.set(`YisouSpider`,S),w.set(`Bytespider`,pe),w.set(`ev-crawler`,me),w.set(`bitdiscovery`,he),w.set(`Spider`,ge),w.set(`Ai2Bot-Dolma`,_e),w.set(`dianjing_ad_spider`,ve);let ye={productHandlerMap:C,commentHandlerMap:w,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ye),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,x=n(5),ee=n.n(x);function te(e){return(te=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 ne(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 re(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ne(Object(n),!0).forEach(function(t){ie(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ne(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ie(e,t,n){return(t=(function(e){var t=(function(e,t){if(te(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(te(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return te(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ae(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=se(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.
89
+ --service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===dC.POST_PAID?`ptu_default only supports pre_paid.
90
+ ptu_default 仅支持 pre_paid。`:e.chargeType===dC.POST_PAID&&mC(e)?`Prepaid flags are not allowed with --charge-type post_paid.
91
+ --charge-type post_paid 不允许提供预付费参数。`:fC(e,!0)??hC(e,e.chargeType===dC.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
92
+ 当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:pC(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=gC(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},yC={name:oC.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||uC,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new O(`No mu-plan template found for model "${e.model}". `+(e.modelUnavailableHint??`Pass --deploy-spec explicitly.`),D.USAGE);try{let a=await rC(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===oC.MU)?.templates??[];if(o.length===0)throw i();let s=t===lC.POST_PAY?dC.POST_PAID:dC.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 O?e:new O(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,D.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},bC={[oC.LORA]:_C,[oC.PTU]:vC,[oC.MU]:yC};function xC(e){let t=bC[e];if(!t)throw new O(`Unsupported plan "${e}". Supported plans: ${Object.keys(bC).join(`, `)}.`,D.USAGE);return t}const SC=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,CC=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,wC=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function TC(e,t){return Gv(await e.console(SC,{input:{modelServiceId:t}}))}async function EC(e,t){return Gv(await e.console(CC,{input:{modelServiceId:t}}))}async function DC(e){let t=[],n=1;for(;;){let r=Gv(await e.console(wC,{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 OC(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const kC=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel.m_efm`;function AC(e={}){return{input:{page:e.page??1,itemsPerPage:e.pageSize??10,...e.keyword===void 0?{}:{searchNameKeyword:e.keyword},...e.modelServiceId===void 0?{}:{modelServiceId:e.modelServiceId}}}}function jC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MC(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=t}function NC(e){return jC(e)&&Array.isArray(e.records)&&e.records.every(jC)&&MC(e.items,0)&&MC(e.itemsPerPage,1)&&MC(e.page,1)&&MC(e.pageCount,0)}async function PC(e,t={}){let n=Hv(await e.console(kC,AC(t)));if(!NC(n))throw new O(`Invalid Console deployment instances page: records must be an array of objects; items and pageCount must be non-negative safe integers; page and itemsPerPage must be positive safe integers. / Console 部署实例分页响应无效:records 必须为对象数组;items 和 pageCount 必须为非负安全整数;page 和 itemsPerPage 必须为正安全整数。`,D.GENERAL);return n}async function FC(e,t,n){return e.requestJson({path:Jg(),method:`POST`,body:t,signal:n})}async function IC(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.modelName&&n.set(`model_name`,t.modelName);let r=Jg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function LC(e,t,n){return e.requestJson({path:Yg(t),method:`GET`,signal:n})}async function RC(e,t,n){return e.requestJson({path:Yg(t),method:`DELETE`,signal:n})}const zC=`zeldaEasy.broadscope-platform.customModel.listSupportImportModels`;async function BC(e){let t=Gv(await e.console(zC,{}));return{total:t.total,pageNo:t.pageNo,pageSize:t.pageSize,list:t.list??[]}}function VC(e,t){let n=t.trim().toLowerCase();return e.find(e=>String(e.model??``).toLowerCase()===n)}function HC(e){return e===`lora`?`efficient_sft`:`sft`}const UC=`speech-biasing`;function WC(e,t){return{model:UC,input:{action:e,...t}}}async function GC(e,t,n,r){return e.requestJson({path:wg(),method:`POST`,body:WC(t,n),signal:r})}function KC(e,t,n){return GC(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function qC(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),GC(e,`list_vocabulary`,r,n)}function JC(e,t,n){return GC(e,`query_vocabulary`,{vocabulary_id:t},n)}function YC(e,t,n,r){return GC(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function XC(e,t,n){return GC(e,`delete_vocabulary`,{vocabulary_id:t},n)}function ZC(e,t){try{return JSON.parse(e)}catch(e){throw new rt(`${t} is not valid JSON — ${e.message}`)}}function QC(e){let t=ZC(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new rt(`--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 rt(`--vocabulary weight for "${e}" must be a number.`);return t}function $C(e,t){let n=`--words`,r=ZC(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new rt(`${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 rt(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new rt(`${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 rt(`${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 rt(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new rt(`${n} must contain at least one hot word.`);return i}const ew={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":`显示版本信息`}}},tw={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},nw={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},rw={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`}}},iw={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)`}}},aw={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 ow(e){return e.auth===`apiKey`?e.optionalConsole?{...rw,...iw}:rw:e.auth===`console`?iw:e.auth===`openapi`?aw:{}}function sw(e){return e}const cw=1;function lw(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function uw(e,t){return`${lw(e||`image`,`image`)}_${lw((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function dw(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return fw(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 fw(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const pw=()=>g(f(),`bailian-output`);function mw(e,t){let n=t?.flagDir||e.outputDir||pw(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function hw(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function gw(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function _w(e){return o(e===`-`?0:e,`utf-8`)}async function vw(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 yw(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 O(`Invalid ${t} value "${String(e)}". Use true or false.`,D.USAGE)}function bw(e,t=`boolean`){if(e!=null)return yw(e,t)}function xw(e,t,n=`boolean`){let r=bw(e,n);return r===void 0?t:r}function Sw(e,t){return bw(e,`watermark`)??t??!0}const Cw=`BAILIAN_CALLER_NAME`,ww=/^[a-z0-9][a-z0-9.-]{0,63}$/,Tw=/^bailian-[a-z0-9-]{1,64}$/,Ew=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function Dw(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function Ow(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return ww.test(t)?t:`unknown`}function kw(e){let t=Dw(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t===`agent`||t===`ai_agent`){let t=Dw(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),n=t!==void 0&&Tw.test(t)?t:void 0,r=Dw(e,`BAILIAN_SKILL_VERSION`),i=n!==void 0&&r!==void 0&&Ew.test(r)?r:void 0;return{callerType:`agent`,callerName:Ow(Dw(e,Cw)),...n===void 0?{}:{skillName:n},...i===void 0?{}:{skillVersion:i}}}return t===`script`?{callerType:`script`,callerName:Ow(Dw(e,Cw))}:{callerType:`unknown`}}function Aw(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.identity.version,commandPrefix:ay(e.identity),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.caller.callerType===`script`&&(t.callerName=e.caller.callerName),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 jw(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function Mw(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=jw(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let Nw;function Pw(){return Nw||(process.env.NODE_ENV===`development`?(Nw=`dev`,Nw):process.env.BAILIAN_COMPILED===`1`?(Nw=`prod`,Nw):(Nw=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,Nw))}var Fw=/* @__PURE__ */ E(((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=et(`os`)},function(e,t){e.exports=(...e)=>(process.versions.bun?globalThis.fetch:et(`undici`).fetch)(...e)},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=et(`dns`)},function(e,t){e.exports=et(`util`)},function(e,t){e.exports=et(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},ie=(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`},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`},pe=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},he=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ge=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},_e=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ve=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map;C.set(`Baiduspider-render`,i),C.set(`Baiduspider+`,i),C.set(`Baiduspider-image+`,i),C.set(`360Spider`,a),C.set(`360Spider-Image`,a),C.set(`bingbot`,o),C.set(`Googlebot`,s),C.set(`YandexRenderResourcesBot`,c),C.set(`spider`,l),C.set(`Dataprovider.com`,u),C.set(`AhrefsBot`,d),C.set(`BitSightBot`,f),C.set(`oBot`,p),C.set(`Cincraw`,m),C.set(`DingTalkBot-LinkService`,h),C.set(`YisouSpider`,g),C.set(`Bytespider`,_),C.set(`ev-crawler`,v),C.set(`bitdiscovery`,y),C.set(`Spider`,b),C.set(`Ai2Bot-Dolma`,x),C.set(`dianjing_ad_spider`,ee),w.set(`Baiduspider-render`,te),w.set(`Baiduspider+`,te),w.set(`Baiduspider-image+`,te),w.set(`360Spider`,ne),w.set(`360Spider-Image`,ne),w.set(`bingbot`,re),w.set(`Googlebot`,ie),w.set(`YandexRenderResourcesBot`,ae),w.set(`spider`,oe),w.set(`Dataprovider.com`,se),w.set(`AhrefsBot`,ce),w.set(`BitSightBot`,le),w.set(`oBot`,ue),w.set(`Cincraw`,de),w.set(`DingTalkBot-LinkService`,fe),w.set(`YisouSpider`,S),w.set(`Bytespider`,pe),w.set(`ev-crawler`,me),w.set(`bitdiscovery`,he),w.set(`Spider`,ge),w.set(`Ai2Bot-Dolma`,_e),w.set(`dianjing_ad_spider`,ve);let ye={productHandlerMap:C,commentHandlerMap:w,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ye),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,x=n(5),ee=n.n(x);function te(e){return(te=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 ne(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 re(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ne(Object(n),!0).forEach(function(t){ie(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ne(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ie(e,t,n){return(t=(function(e){var t=(function(e,t){if(te(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(te(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return te(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ae(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=se(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.
93
93
  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 oe(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)||se(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
94
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function se(e,t){if(e){if(typeof e==`string`)return ce(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)?ce(e,t):void 0}}function ce(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 le(){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=oe(r[n],2),o=(a[0],a[1]);if(o){var s,c=ae(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 ue,de,fe=(ue=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:ue,device_id:ee.a.createHash(`md5`).update(le()).digest(`hex`),platform:`node`});function S(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,re(re({},fe),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}S.prototype=((de=function(){}).prototype=b.prototype,new de),S.prototype.constructor=S,S.prototype.send=async function(e,t={}){let n=t.signal;if(n?.aborted)return;let r;if(!process.versions.bun){let{Agent:e,EnvHttpProxyAgent:t}=et(`undici`),i={signal:n,timeout:1e3},a=process.env.HTTP_PROXY?.trim()||void 0,o=process.env.HTTPS_PROXY?.trim()||void 0;r=a||o?new t({httpProxy:a,httpsProxy:o,noProxy:process.env.NO_PROXY?.trim()||void 0,connect:i,requestTls:i,proxyTls:i}):new e({connect:i})}let i=[...this._offlineQueue.splice(0),e];try{await Promise.all(i.map(async e=>{if(!n?.aborted)try{this._print(`send`,e),await(await o()(this._config.endpoint_url,{method:`POST`,keepalive:!0,signal:n,...r?{dispatcher:r}:{},body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})})).body?.cancel().catch(()=>{})}catch{n?.aborted||(this._offlineQueue.length>500&&this._offlineQueue.shift(),this._offlineQueue.push(e))}}))}finally{await r?.destroy().catch(()=>{})}},t.default=S}]).default})),sw=/* @__PURE__ */ E(((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})),cw=/* @__PURE__ */ $e(ow(),1),lw=/* @__PURE__ */ $e(sw(),1);const uw=()=>g(Ft(),`telemetry.jsonl`);let dw;const fw=/* @__PURE__ */ new Set;let pw;try{let e=new cw.default({pid:`bailian-cli-node`,env:aw()}),t=e.send.bind(e);e.send=function(e){let n=new AbortController,r=setTimeout(()=>n.abort(),1e3);r.unref?.();let i={controller:n,promise:Promise.resolve().then(()=>t(e,{signal:n.signal})).catch(()=>{}).finally(()=>{n.abort(),clearTimeout(r),fw.delete(i)})};return fw.add(i),i.promise},pw=e,dw=e.use(lw.default)}catch{}async function mw(e=1e3){let t;try{if(pw)try{typeof pw._sendAll==`function`&&pw._sendAll()}catch{}if(fw.size===0)return;await Promise.race([Promise.allSettled([...fw].map(e=>e.promise)),new Promise(n=>{t=setTimeout(()=>{for(let e of fw)e.controller.abort();n()},e),t.unref?.()})])}catch{}finally{clearTimeout(t)}}async function hw(e){try{await Rt();let n=uw();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
95
- `,{mode:384})}catch{}}async function gw(e){try{if(!dw)return;dw(e.command,rw(e))}catch{}}const _w=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),vw=/* @__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 yw(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||_w.has(n)||vw.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function bw(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 O?(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=tw({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},identity:e.identity,authMethod:e.authMethod,params:yw(n),caller:e.caller});hw(u).catch(()=>{}),gw(u).catch(()=>{})}}const xw=/* @__PURE__ */ `代码生成.创意写作.客服对话.知识问答.文档理解.数据分析.数学推理.翻译.图像生成.图像编辑.视频生成.视频编辑.语音合成.语音识别.实时对话.Agent编排.深度研究.教育辅导.电商营销.角色扮演.3D生成.向量检索.数字人.音乐生成.人脸人像.虚拟试穿.OCR文字识别.情感分析.意图识别.图像修复.语义重排.播客.有声书`.split(`.`),Sw=`You are an intent analyzer for an AI model recommendation system. Given the user's requirement, understand the scenario first, then extract structured information.
94
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function se(e,t){if(e){if(typeof e==`string`)return ce(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)?ce(e,t):void 0}}function ce(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 le(){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=oe(r[n],2),o=(a[0],a[1]);if(o){var s,c=ae(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 ue,de,fe=(ue=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:ue,device_id:ee.a.createHash(`md5`).update(le()).digest(`hex`),platform:`node`});function S(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,re(re({},fe),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}S.prototype=((de=function(){}).prototype=b.prototype,new de),S.prototype.constructor=S,S.prototype.send=async function(e,t={}){let n=t.signal;if(n?.aborted)return;let r;if(!process.versions.bun){let{Agent:e,EnvHttpProxyAgent:t}=et(`undici`),i={signal:n,timeout:1e3},a=process.env.HTTP_PROXY?.trim()||void 0,o=process.env.HTTPS_PROXY?.trim()||void 0;r=a||o?new t({httpProxy:a,httpsProxy:o,noProxy:process.env.NO_PROXY?.trim()||void 0,connect:i,requestTls:i,proxyTls:i}):new e({connect:i})}let i=[...this._offlineQueue.splice(0),e];try{await Promise.all(i.map(async e=>{if(!n?.aborted)try{this._print(`send`,e),await(await o()(this._config.endpoint_url,{method:`POST`,keepalive:!0,signal:n,...r?{dispatcher:r}:{},body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})})).body?.cancel().catch(()=>{})}catch{n?.aborted||(this._offlineQueue.length>500&&this._offlineQueue.shift(),this._offlineQueue.push(e))}}))}finally{await r?.destroy().catch(()=>{})}},t.default=S}]).default})),Iw=/* @__PURE__ */ E(((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})),Lw=/* @__PURE__ */ $e(Fw(),1),Rw=/* @__PURE__ */ $e(Iw(),1);const zw=()=>g(Ft(),`telemetry.jsonl`);let Bw;const Vw=/* @__PURE__ */ new Set;let Hw;try{let e=new Lw.default({pid:`bailian-cli-node`,env:Pw()}),t=e.send.bind(e);e.send=function(e){let n=new AbortController,r=setTimeout(()=>n.abort(),1e3);r.unref?.();let i={controller:n,promise:Promise.resolve().then(()=>t(e,{signal:n.signal})).catch(()=>{}).finally(()=>{n.abort(),clearTimeout(r),Vw.delete(i)})};return Vw.add(i),i.promise},Hw=e,Bw=e.use(Rw.default)}catch{}async function Uw(e=1e3){let t;try{if(Hw)try{typeof Hw._sendAll==`function`&&Hw._sendAll()}catch{}if(Vw.size===0)return;await Promise.race([Promise.allSettled([...Vw].map(e=>e.promise)),new Promise(n=>{t=setTimeout(()=>{for(let e of Vw)e.controller.abort();n()},e),t.unref?.()})])}catch{}finally{clearTimeout(t)}}async function Ww(e){try{await Rt();let n=zw();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
95
+ `,{mode:384})}catch{}}async function Gw(e){try{if(!Bw)return;Bw(e.command,Mw(e))}catch{}}const Kw=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),qw=/* @__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 Jw(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||Kw.has(n)||qw.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function Yw(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 O?(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=Aw({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},identity:e.identity,authMethod:e.authMethod,params:Jw(n),caller:e.caller});Ww(u).catch(()=>{}),Gw(u).catch(()=>{})}}const Xw=/* @__PURE__ */ `代码生成.创意写作.客服对话.知识问答.文档理解.数据分析.数学推理.翻译.图像生成.图像编辑.视频生成.视频编辑.语音合成.语音识别.实时对话.Agent编排.深度研究.教育辅导.电商营销.角色扮演.3D生成.向量检索.数字人.音乐生成.人脸人像.虚拟试穿.OCR文字识别.情感分析.意图识别.图像修复.语义重排.播客.有声书`.split(`.`),Zw=`You are an intent analyzer for an AI model recommendation system. Given the user's requirement, understand the scenario first, then extract structured information.
96
96
 
97
97
  CRITICAL: Respond with ONLY a valid JSON object. taskSummary must be in English; segments[].step is a short Simplified Chinese label (e.g. "剧本创作", "图生视频").
98
98
 
@@ -154,8 +154,8 @@ Pick ONLY the capabilities actually needed (at most 2 for a single task — choo
154
154
  - 3D-generation: 3D model generation
155
155
 
156
156
  ## Scene mapping
157
- Map the user's need to ONE OR MORE of these ${xw.length} scenes (use exact Chinese labels):
158
- ${xw.join(`, `)}
157
+ Map the user's need to ONE OR MORE of these ${Xw.length} scenes (use exact Chinese labels):
158
+ ${Xw.join(`, `)}
159
159
 
160
160
  - matchedScenes: array of matched scene labels (max 3, ordered by relevance); [] if none match
161
161
  - sceneConfidence: 0.0-1.0 (1.0 = exact match, 0.5 = inferred, 0.0 = no match)
@@ -199,24 +199,24 @@ Set optimizeDimension ONLY when the user explicitly writes a single-dimension su
199
199
  "optimizeDimension": null | "price" | "speed" | "context" | "quality" // null unless an explicit superlative appears
200
200
  }
201
201
 
202
- Output only JSON, no other text.`;var Cw=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 $(e){if(!e?.aborted)return;let t=e.reason;throw new Cw(`cancelled`,t instanceof Error?t.message:`执行已取消`,{cause:t})}function ww(e){return e===429?`rate_limit`:e===401||e===403?`auth`:`http`}function Tw(e,t,n){return{stage:e,fallback:t,kind:n.kind,status:n.status,message:n.message}}function Ew(e){let t=e.status?`${e.status} ${e.kind}`:e.kind;return`${e.fallback} (${t})`}function Dw(e,t){return e instanceof Cw?(e.stage??=t,e):new Cw(`parse`,e instanceof Error?e.message:String(e),{stage:t,cause:e})}const Ow=[`unconstrained`,`scoped`,`comparison`,`alternative`],kw=/* @__PURE__ */ new Set([`Text`,`Image`,`Video`,`Audio`]),Aw=new Set(xw),jw=/* @__PURE__ */ new Set([`price`,`speed`,`context`,`quality`]),Mw=/* @__PURE__ */ new Set([`one`,`few`,`many`]);function Nw(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Pw(e){return Nw(e).filter(e=>kw.has(e))}function Fw(e){if(!e||typeof e!=`object`)return;let t=e,n=typeof t.mode==`string`&&Ow.includes(t.mode)?t.mode:`unconstrained`,r=Nw(t.targets),i=Nw(t.excludes);return{mode:n,targets:r.length>0?r:void 0,excludes:i.length>0?i:void 0}}async function Iw(e,t,n){let r;try{r=await e.chatJson([{role:`system`,content:Sw},{role:`user`,content:t}],{stage:`intent`,signal:n})}catch(e){throw Dw(e,`intent`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new Cw(`parse`,`Intent response is not a JSON object`,{stage:`intent`});let i=Nw(r.matchedScenes).filter(e=>Aw.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`&&Aw.has(e.scene)?e.scene:void 0,inputModality:Pw(e.inputModality),outputModality:Pw(e.outputModality),requiredCapabilities:Nw(e.requiredCapabilities)})):void 0,taskSummary:typeof r.taskSummary==`string`?r.taskSummary:``,scenarioHints:Nw(r.scenarioHints),inputModality:Pw(r.inputModality),outputModality:Pw(r.outputModality),requiredCapabilities:Nw(r.requiredCapabilities),requiredFeatures:Nw(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:Fw(r.modelPreference),matchedScenes:i,sceneConfidence:a,cardinalityHint:typeof r.cardinalityHint==`string`&&Mw.has(r.cardinalityHint)?r.cardinalityHint:void 0,optimizeDimension:typeof r.optimizeDimension==`string`&&jw.has(r.optimizeDimension)?r.optimizeDimension:void 0}}function Lw(e){return!e.offlineInfo}function Rw(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 zw(e,t){return Rw(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function Bw(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 Vw(e,t,n=5){let r=e.filter(e=>zw(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 Hw=/* @__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`]),Uw=/* @__PURE__ */ new Set([`Reasoning`]),Ww={TG:[`代码生成`,`创意写作`,`客服对话`,`知识问答`,`文档理解`,`数据分析`,`数学推理`,`翻译`,`Agent编排`,`深度研究`,`教育辅导`,`电商营销`,`角色扮演`,`情感分析`,`意图识别`],VU:[`文档理解`,`OCR文字识别`,`数据分析`],IG:[`图像生成`,`图像编辑`,`图像修复`,`人脸人像`,`虚拟试穿`,`电商营销`],VG:[`视频生成`,`视频编辑`,`数字人`],TTS:[`语音合成`,`有声书`,`播客`,`数字人`],ASR:[`语音识别`],"Realtime-ASR":[`语音识别`,`实时对话`],TR:[`向量检索`,`语义重排`,`知识问答`],ME:[`向量检索`],"3D-generation":[`3D生成`]},Gw={IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`},Kw=[[/重排|rerank/i,`语义重排`],[/向量|嵌入|embedding|索引/i,`向量检索`],[/翻译|translat/i,`翻译`],[/代码|编程|code/i,`代码生成`],[/剧本|脚本|文案|歌词|故事|小说|创作|写作|script|lyric/i,`创意写作`],[/纪要|摘要|总结|整理|summar/i,`文档理解`],[/问答|回答|答案|answer/i,`知识问答`],[/转写|识别|听写|transcri/i,`语音识别`],[/配音|旁白|朗读|语音合成|voice/i,`语音合成`],[/数字人|口型|lip/i,`数字人`]],qw=/剪辑|合成剪辑|合轨|混音|拼接|加字幕|字幕合成|后期|导出|assembl|edit(ing)? together|mux/i;function Jw(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 Yw(e){return{TG:`文本生成`,VU:`视觉理解`,IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`,TR:`文本检索`,ME:`多模态检索`,"3D-generation":`3D 生成`}[e]??e}function Xw(e){let t=[];for(let n of e??[]){let e=n.requiredCapabilities.filter(e=>Hw.has(e)),r=e.filter(e=>!Uw.has(e)),i=n.step?.trim()??``;if(r.length===0&&qw.test(i))continue;let a=r[0]??Jw(n.inputModality,n.outputModality);if(!a)continue;let o=[a,...e.filter(e=>e!==a)],s=i||Yw(a);if(t.push({index:t.length+1,label:s,inputModality:n.inputModality,outputModality:n.outputModality,primaryCapability:a,capabilities:o,scene:Zw(n.scene,s,a)}),t.length>=5)break}return t.length>=2?t:[]}function Zw(e,t,n){let r=e=>(Ww[n]??[]).includes(e);if(e&&r(e))return e;for(let[e,n]of Kw)if(e.test(t)&&r(n))return n;return Gw[n]}function Qw(e,t){if(e.scene)return[e.scene];let n=new Set(Ww[e.primaryCapability]??[]);return t.matchedScenes.filter(e=>n.has(e))}function $w(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:Qw(e,t)}}const eT=/* @__PURE__ */ new Set([`IG`,`VG`,`TTS`,`Realtime-Text-to-Speech`,`3D-generation`]),tT=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`ASR`,`Realtime-ASR`,`TR`,`ME`]);function nT(e){let t=!1,n=!1;for(let r of e)eT.has(r)&&(t=!0),tT.has(r)&&(n=!0);return t&&n}function rT(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&&nT(e.requiredCapabilities))return{question:`你的核心需求是哪一类?`,options:e.requiredCapabilities.slice(0,4),defaultIfSkip:e.requiredCapabilities[0],impact:`different capabilities map to completely different model pools`}}}function iT(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=>zw(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 aT(e){let t=e.modelPreference;return!t||t.mode===`unconstrained`?`none`:t.mode===`comparison`?`existing`:t.mode===`alternative`?`reference`:`scope`}function oT(e){return e.modelPreference?.mode===`comparison`?(e.modelPreference?.targets?.length??0)<=1?`evaluate`:`differentiate`:e.optimizeDimension?`optimize`:`match`}function sT(e){return e.cardinalityHint??`few`}function cT(e,t,n){return t===`differentiate`?`compare`:t===`evaluate`?`validate`:n===`many`?`catalog`:`recommend`}function lT(e){return e.matchedScenes.length===0&&e.sceneConfidence<.5&&e.confidence>0}const uT=[{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}}],dT={name:`structured-normal`,match:()=>!0,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}};function fT(e){return{recall:`structured`,score:`none`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3,routingReason:`ambiguity-detected`,clarify:e}}function pT(e,t,n){let r=rT(e);if(r)return fT(r);let i=iT(e,t);if(i)return fT(i);let a=aT(e),o=oT(e),s=sT(e),c=cT(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`?Xw(e.segments).length:0,fuzzy:lT(e)},u=uT.find(e=>e.match(l))??dT;return{...u.plan,...n!==void 0&&n>0?{topN:n}:{},routingReason:`${u.name}|${a}/${o}/${s}/${c}`}}const mT=/-\d{4}-\d{2}-\d{2}$/;function hT(e){return(e??``).toLowerCase().replace(mT,``).replace(/[\s_-]+/g,``).trim()}function gT(e,t){if(hT(e.model)===t||hT(e.name)===t)return!0;let n=e.model.lastIndexOf(`/`);return n>=0&&hT(e.model.slice(n+1))===t}function _T(e,t){return[e.family,e.familyName].some(e=>{if(!e)return!1;let n=hT(e);return n.length>0&&(t.includes(n)||n.includes(t))})}function vT(e,t){if(t.length===0)return[];let n=[],r=/* @__PURE__ */ new Set;for(let i of t){let t=hT(i);if(!t)continue;let a=e.filter(e=>gT(e,t));a.length===0&&(a=e.filter(e=>_T(e,t)));for(let e of a)r.has(e.model)||(r.add(e.model),n.push(e))}return n}function yT(e,t){return t.length===0?e:e.filter(e=>!t.some(t=>{let n=hT(t);return n.length>0&&(gT(e,n)||_T(e,n))}))}function bT(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}const xT={flagship:0,balanced:1,lightweight:2},ST=/* @__PURE__ */ new Set([`qwen`,`qwen-domain-model`,`wan`]);function CT(e){return ST.has(e.provider)}function wT(e){let t=e.model.match(/(\d+(?:\.\d+)?)/);return t?Number.parseFloat(t[1]):-1/0}function TT(e){let t=e.budget===`low`||e.qualityPreference===`cost-optimized`;return(e,n)=>{let r=xT[e.profile?.familyTier??``]??1.5,i=xT[n.profile?.familyTier??``]??1.5,a=t?i-r:r-i;if(a!==0)return a;let o=+!CT(e),s=+!CT(n);if(o!==s)return o-s;let c=bT(e),l=bT(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 wT(n)-wT(e)}}function ET(e,t){return{model:e,hardScore:t,finalScore:t}}function DT(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(TT(e)).map(e=>ET(e,1))}function OT(e,t){let n=Vw(t,e),r=e.matchedScenes[0],i=TT(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=>ET(e,0))}function kT(e,t,n){let r=vT(t,e.modelPreference?.targets??[]),i=new Set(r.map(e=>e.model)),a=r.map(e=>ET(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=Vw(t.filter(e=>!i.has(e.model)),e);for(let t of n.sort(TT(e)).slice(0,o))a.push(ET(t,0))}return a}function AT(e,t){let n=t.filter(t=>zw(t,e));return n.length<5&&(n=t),n.sort(TT(e)).slice(0,30).map(e=>ET(e,0))}function jT(e,t,n,r){let i=n.filter(Lw);i=yT(i,t.modelPreference?.excludes??[]);let a;switch(e){case`template`:a=DT(t,i)??OT(t,i);break;case`forced`:a=kT(t,i,r);break;case`holistic-pool`:a=AT(t,i);break;default:a=OT(t,i)}if(e!==`forced`){let e=new Set(Bw(a.map(e=>e.model),t).map(e=>e.model));a=a.filter(t=>e.has(t.model.model))}return a}function MT(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 NT(e,t){return`${e.length?e.join(`/`):`?`} → ${t.length?t.join(`/`):`?`}`}function PT(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`}: ${NT(e.inputModality,e.outputModality)}${r}`)})),t.push(`Modality: ${NT(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(`
203
- `)}const FT={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}},IT={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 LT(e,t){return e===`optimize`&&t.optimizeDimension?IT[t.optimizeDimension]??FT.optimize:FT[e]}const RT={standard:0,large:32e3,"extra-large":128e3};function zT(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:void 0}function BT(e,t){if(t.matchedScenes.length===0)return 1;let n=e.profile?.scenes??[];return+!!t.matchedScenes.some(e=>n.includes(e))}function VT(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 HT(e,t,n){let r=n.map(e=>zT(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=zT(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 UT(e,t){let n=RT[t.contextNeed]??0;if(n===0)return 1;let r=e.contextWindow??0;return r===0||r>=n?1:r/n}function WT(e,t,n){let r=LT(n,t);return e.map(n=>{let i=r.scene*BT(n.model,t)+r.tier*VT(n.model,t)+r.price*HT(n.model,t,e)+r.context*UT(n.model,t);return{...n,hardScore:i,finalScore:i}})}function GT(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 KT(e,t){let n=t.llm,r=e.map(GT).join(`
204
- `);t.trace.performance.llmCalls++;let i=MT(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).
202
+ Output only JSON, no other text.`;var Qw=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 $(e){if(!e?.aborted)return;let t=e.reason;throw new Qw(`cancelled`,t instanceof Error?t.message:`执行已取消`,{cause:t})}function $w(e){return e===429?`rate_limit`:e===401||e===403?`auth`:`http`}function eT(e,t,n){return{stage:e,fallback:t,kind:n.kind,status:n.status,message:n.message}}function tT(e){let t=e.status?`${e.status} ${e.kind}`:e.kind;return`${e.fallback} (${t})`}function nT(e,t){return e instanceof Qw?(e.stage??=t,e):new Qw(`parse`,e instanceof Error?e.message:String(e),{stage:t,cause:e})}const rT=[`unconstrained`,`scoped`,`comparison`,`alternative`],iT=/* @__PURE__ */ new Set([`Text`,`Image`,`Video`,`Audio`]),aT=new Set(Xw),oT=/* @__PURE__ */ new Set([`price`,`speed`,`context`,`quality`]),sT=/* @__PURE__ */ new Set([`one`,`few`,`many`]);function cT(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function lT(e){return cT(e).filter(e=>iT.has(e))}function uT(e){if(!e||typeof e!=`object`)return;let t=e,n=typeof t.mode==`string`&&rT.includes(t.mode)?t.mode:`unconstrained`,r=cT(t.targets),i=cT(t.excludes);return{mode:n,targets:r.length>0?r:void 0,excludes:i.length>0?i:void 0}}async function dT(e,t,n){let r;try{r=await e.chatJson([{role:`system`,content:Zw},{role:`user`,content:t}],{stage:`intent`,signal:n})}catch(e){throw nT(e,`intent`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new Qw(`parse`,`Intent response is not a JSON object`,{stage:`intent`});let i=cT(r.matchedScenes).filter(e=>aT.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`&&aT.has(e.scene)?e.scene:void 0,inputModality:lT(e.inputModality),outputModality:lT(e.outputModality),requiredCapabilities:cT(e.requiredCapabilities)})):void 0,taskSummary:typeof r.taskSummary==`string`?r.taskSummary:``,scenarioHints:cT(r.scenarioHints),inputModality:lT(r.inputModality),outputModality:lT(r.outputModality),requiredCapabilities:cT(r.requiredCapabilities),requiredFeatures:cT(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:uT(r.modelPreference),matchedScenes:i,sceneConfidence:a,cardinalityHint:typeof r.cardinalityHint==`string`&&sT.has(r.cardinalityHint)?r.cardinalityHint:void 0,optimizeDimension:typeof r.optimizeDimension==`string`&&oT.has(r.optimizeDimension)?r.optimizeDimension:void 0}}function fT(e){return!e.offlineInfo}function pT(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 mT(e,t){return pT(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function hT(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 gT(e,t,n=5){let r=e.filter(e=>mT(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 _T=/* @__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`]),vT=/* @__PURE__ */ new Set([`Reasoning`]),yT={TG:[`代码生成`,`创意写作`,`客服对话`,`知识问答`,`文档理解`,`数据分析`,`数学推理`,`翻译`,`Agent编排`,`深度研究`,`教育辅导`,`电商营销`,`角色扮演`,`情感分析`,`意图识别`],VU:[`文档理解`,`OCR文字识别`,`数据分析`],IG:[`图像生成`,`图像编辑`,`图像修复`,`人脸人像`,`虚拟试穿`,`电商营销`],VG:[`视频生成`,`视频编辑`,`数字人`],TTS:[`语音合成`,`有声书`,`播客`,`数字人`],ASR:[`语音识别`],"Realtime-ASR":[`语音识别`,`实时对话`],TR:[`向量检索`,`语义重排`,`知识问答`],ME:[`向量检索`],"3D-generation":[`3D生成`]},bT={IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`},xT=[[/重排|rerank/i,`语义重排`],[/向量|嵌入|embedding|索引/i,`向量检索`],[/翻译|translat/i,`翻译`],[/代码|编程|code/i,`代码生成`],[/剧本|脚本|文案|歌词|故事|小说|创作|写作|script|lyric/i,`创意写作`],[/纪要|摘要|总结|整理|summar/i,`文档理解`],[/问答|回答|答案|answer/i,`知识问答`],[/转写|识别|听写|transcri/i,`语音识别`],[/配音|旁白|朗读|语音合成|voice/i,`语音合成`],[/数字人|口型|lip/i,`数字人`]],ST=/剪辑|合成剪辑|合轨|混音|拼接|加字幕|字幕合成|后期|导出|assembl|edit(ing)? together|mux/i;function CT(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 wT(e){return{TG:`文本生成`,VU:`视觉理解`,IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`,TR:`文本检索`,ME:`多模态检索`,"3D-generation":`3D 生成`}[e]??e}function TT(e){let t=[];for(let n of e??[]){let e=n.requiredCapabilities.filter(e=>_T.has(e)),r=e.filter(e=>!vT.has(e)),i=n.step?.trim()??``;if(r.length===0&&ST.test(i))continue;let a=r[0]??CT(n.inputModality,n.outputModality);if(!a)continue;let o=[a,...e.filter(e=>e!==a)],s=i||wT(a);if(t.push({index:t.length+1,label:s,inputModality:n.inputModality,outputModality:n.outputModality,primaryCapability:a,capabilities:o,scene:ET(n.scene,s,a)}),t.length>=5)break}return t.length>=2?t:[]}function ET(e,t,n){let r=e=>(yT[n]??[]).includes(e);if(e&&r(e))return e;for(let[e,n]of xT)if(e.test(t)&&r(n))return n;return bT[n]}function DT(e,t){if(e.scene)return[e.scene];let n=new Set(yT[e.primaryCapability]??[]);return t.matchedScenes.filter(e=>n.has(e))}function OT(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:DT(e,t)}}const kT=/* @__PURE__ */ new Set([`IG`,`VG`,`TTS`,`Realtime-Text-to-Speech`,`3D-generation`]),AT=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`ASR`,`Realtime-ASR`,`TR`,`ME`]);function jT(e){let t=!1,n=!1;for(let r of e)kT.has(r)&&(t=!0),AT.has(r)&&(n=!0);return t&&n}function MT(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&&jT(e.requiredCapabilities))return{question:`你的核心需求是哪一类?`,options:e.requiredCapabilities.slice(0,4),defaultIfSkip:e.requiredCapabilities[0],impact:`different capabilities map to completely different model pools`}}}function NT(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=>mT(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 PT(e){let t=e.modelPreference;return!t||t.mode===`unconstrained`?`none`:t.mode===`comparison`?`existing`:t.mode===`alternative`?`reference`:`scope`}function FT(e){return e.modelPreference?.mode===`comparison`?(e.modelPreference?.targets?.length??0)<=1?`evaluate`:`differentiate`:e.optimizeDimension?`optimize`:`match`}function IT(e){return e.cardinalityHint??`few`}function LT(e,t,n){return t===`differentiate`?`compare`:t===`evaluate`?`validate`:n===`many`?`catalog`:`recommend`}function RT(e){return e.matchedScenes.length===0&&e.sceneConfidence<.5&&e.confidence>0}const zT=[{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}}],BT={name:`structured-normal`,match:()=>!0,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}};function VT(e){return{recall:`structured`,score:`none`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3,routingReason:`ambiguity-detected`,clarify:e}}function HT(e,t,n){let r=MT(e);if(r)return VT(r);let i=NT(e,t);if(i)return VT(i);let a=PT(e),o=FT(e),s=IT(e),c=LT(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`?TT(e.segments).length:0,fuzzy:RT(e)},u=zT.find(e=>e.match(l))??BT;return{...u.plan,...n!==void 0&&n>0?{topN:n}:{},routingReason:`${u.name}|${a}/${o}/${s}/${c}`}}const UT=/-\d{4}-\d{2}-\d{2}$/;function WT(e){return(e??``).toLowerCase().replace(UT,``).replace(/[\s_-]+/g,``).trim()}function GT(e,t){if(WT(e.model)===t||WT(e.name)===t)return!0;let n=e.model.lastIndexOf(`/`);return n>=0&&WT(e.model.slice(n+1))===t}function KT(e,t){return[e.family,e.familyName].some(e=>{if(!e)return!1;let n=WT(e);return n.length>0&&(t.includes(n)||n.includes(t))})}function qT(e,t){if(t.length===0)return[];let n=[],r=/* @__PURE__ */ new Set;for(let i of t){let t=WT(i);if(!t)continue;let a=e.filter(e=>GT(e,t));a.length===0&&(a=e.filter(e=>KT(e,t)));for(let e of a)r.has(e.model)||(r.add(e.model),n.push(e))}return n}function JT(e,t){return t.length===0?e:e.filter(e=>!t.some(t=>{let n=WT(t);return n.length>0&&(GT(e,n)||KT(e,n))}))}function YT(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}const XT={flagship:0,balanced:1,lightweight:2},ZT=/* @__PURE__ */ new Set([`qwen`,`qwen-domain-model`,`wan`]);function QT(e){return ZT.has(e.provider)}function $T(e){let t=e.model.match(/(\d+(?:\.\d+)?)/);return t?Number.parseFloat(t[1]):-1/0}function eE(e){let t=e.budget===`low`||e.qualityPreference===`cost-optimized`;return(e,n)=>{let r=XT[e.profile?.familyTier??``]??1.5,i=XT[n.profile?.familyTier??``]??1.5,a=t?i-r:r-i;if(a!==0)return a;let o=+!QT(e),s=+!QT(n);if(o!==s)return o-s;let c=YT(e),l=YT(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 $T(n)-$T(e)}}function tE(e,t){return{model:e,hardScore:t,finalScore:t}}function nE(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(eE(e)).map(e=>tE(e,1))}function rE(e,t){let n=gT(t,e),r=e.matchedScenes[0],i=eE(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=>tE(e,0))}function iE(e,t,n){let r=qT(t,e.modelPreference?.targets??[]),i=new Set(r.map(e=>e.model)),a=r.map(e=>tE(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=gT(t.filter(e=>!i.has(e.model)),e);for(let t of n.sort(eE(e)).slice(0,o))a.push(tE(t,0))}return a}function aE(e,t){let n=t.filter(t=>mT(t,e));return n.length<5&&(n=t),n.sort(eE(e)).slice(0,30).map(e=>tE(e,0))}function oE(e,t,n,r){let i=n.filter(fT);i=JT(i,t.modelPreference?.excludes??[]);let a;switch(e){case`template`:a=nE(t,i)??rE(t,i);break;case`forced`:a=iE(t,i,r);break;case`holistic-pool`:a=aE(t,i);break;default:a=rE(t,i)}if(e!==`forced`){let e=new Set(hT(a.map(e=>e.model),t).map(e=>e.model));a=a.filter(t=>e.has(t.model.model))}return a}function sE(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 cE(e,t){return`${e.length?e.join(`/`):`?`} → ${t.length?t.join(`/`):`?`}`}function lE(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`}: ${cE(e.inputModality,e.outputModality)}${r}`)})),t.push(`Modality: ${cE(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(`
203
+ `)}const uE={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}},dE={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 fE(e,t){return e===`optimize`&&t.optimizeDimension?dE[t.optimizeDimension]??uE.optimize:uE[e]}const pE={standard:0,large:32e3,"extra-large":128e3};function mE(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:void 0}function hE(e,t){if(t.matchedScenes.length===0)return 1;let n=e.profile?.scenes??[];return+!!t.matchedScenes.some(e=>n.includes(e))}function gE(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 _E(e,t,n){let r=n.map(e=>mE(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=mE(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 vE(e,t){let n=pE[t.contextNeed]??0;if(n===0)return 1;let r=e.contextWindow??0;return r===0||r>=n?1:r/n}function yE(e,t,n){let r=fE(n,t);return e.map(n=>{let i=r.scene*hE(n.model,t)+r.tier*gE(n.model,t)+r.price*_E(n.model,t,e)+r.context*vE(n.model,t);return{...n,hardScore:i,finalScore:i}})}function bE(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 xE(e,t){let n=t.llm,r=e.map(bE).join(`
204
+ `);t.trace.performance.llmCalls++;let i=sE(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).
205
205
 
206
206
  Rules:
207
207
  - Judge holistically; do not decompose into dimensions
208
208
  - The parsed intent is the structured reading of the request; use it, but the original request wins if they conflict
209
209
  - 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
210
210
  - A model whose notSuitableFor conflicts with the need must score ≤3
211
- - Respond with ONLY JSON: {"scores": [{"model": "<id>", "score": <1-10>}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${PT(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 qT(e,t,n,r){switch(e){case`none`:return t;case`holistic`:try{return await KT(t,n)}catch(e){if($(n.signal),Dw(e,`holistic-score`).kind===`cancelled`)throw e;return n.trace.degradations.push(Tw(`holistic-score`,`holistic-score→formula`,Dw(e,`holistic-score`))),WT(t,n.intent,r)}default:return WT(t,n.intent,r)}}function JT(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 YT(e){let t=e.model.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}function XT(e){return e.model.profile?.familyTier??`unknown`}function ZT(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 QT(e,t,n){if(t<3||e.length<3)return ZT(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=XT(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(),ZT(r,t)}let o=/* @__PURE__ */ new Set;for(let t of e){if(r.length>=3)break;XT(t)===`flagship`&&(o.has(t.model.provider)||(o.add(t.model.provider),r.push(t),i.add(t.model.model)))}return a(),ZT(r,t)}function $T(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:YT(e)-YT(t)})}return r&&(a=JT(a,n)),e===`forced-order`?ZT(a,n):QT(a,n,i)}const eE={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 tE(e){let t=[];for(let n of e.prices??[]){if(t.length>=3)break;let e=eE[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 nE(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 rE(e){return e.model.profile?.profileCompleteness===`structured-only`?`low`:e.slot===`exploration`||e.slot===`alternative`?`medium`:`high`}function iE(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:rE(e),slot:e.slot,docUrl:e.model.docUrl,specs:tE(e.model)}})}function aE(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:rE(e),slot:e.slot,docUrl:e.model.docUrl,specs:tE(e.model)}))}async function oE(e,t,n){n.trace.performance.llmCalls++;let r=MT(await n.llm.chat([{role:`system`,content:e},{role:`user`,content:`User request: ${n.input}\n\nIntent:\n${PT(n.intent)}\n\nRanked candidates:\n${t.map(nE).join(`
212
- `)}`}],{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:rE(e),slot:e.slot,docUrl:e.model.docUrl,specs:tE(e.model)}})}async function sE(e,t,n){switch(e){case`template-text`:return iE(t);case`catalog`:return aE(t);case`llm-compare`:try{return await oE(`You are a model comparison advisor for Alibaba Cloud Model Studio. Analyze the given models against the user's use case comparatively.
211
+ - Respond with ONLY JSON: {"scores": [{"model": "<id>", "score": <1-10>}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${lE(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 SE(e,t,n,r){switch(e){case`none`:return t;case`holistic`:try{return await xE(t,n)}catch(e){if($(n.signal),nT(e,`holistic-score`).kind===`cancelled`)throw e;return n.trace.degradations.push(eT(`holistic-score`,`holistic-score→formula`,nT(e,`holistic-score`))),yE(t,n.intent,r)}default:return yE(t,n.intent,r)}}function CE(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 wE(e){let t=e.model.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}function TE(e){return e.model.profile?.familyTier??`unknown`}function EE(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 DE(e,t,n){if(t<3||e.length<3)return EE(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=TE(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(),EE(r,t)}let o=/* @__PURE__ */ new Set;for(let t of e){if(r.length>=3)break;TE(t)===`flagship`&&(o.has(t.model.provider)||(o.add(t.model.provider),r.push(t),i.add(t.model.model)))}return a(),EE(r,t)}function OE(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:wE(e)-wE(t)})}return r&&(a=CE(a,n)),e===`forced-order`?EE(a,n):DE(a,n,i)}const kE={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 AE(e){let t=[];for(let n of e.prices??[]){if(t.length>=3)break;let e=kE[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 jE(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 ME(e){return e.model.profile?.profileCompleteness===`structured-only`?`low`:e.slot===`exploration`||e.slot===`alternative`?`medium`:`high`}function NE(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:ME(e),slot:e.slot,docUrl:e.model.docUrl,specs:AE(e.model)}})}function PE(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:ME(e),slot:e.slot,docUrl:e.model.docUrl,specs:AE(e.model)}))}async function FE(e,t,n){n.trace.performance.llmCalls++;let r=sE(await n.llm.chat([{role:`system`,content:e},{role:`user`,content:`User request: ${n.input}\n\nIntent:\n${lE(n.intent)}\n\nRanked candidates:\n${t.map(jE).join(`
212
+ `)}`}],{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:ME(e),slot:e.slot,docUrl:e.model.docUrl,specs:AE(e.model)}})}async function IE(e,t,n){switch(e){case`template-text`:return NE(t);case`catalog`:return PE(t);case`llm-compare`:try{return await FE(`You are a model comparison advisor for Alibaba Cloud Model Studio. Analyze the given models against the user's use case comparatively.
213
213
 
214
214
  Rules:
215
215
  - reason and highlights MUST be in Simplified Chinese (简体中文)
216
216
  - Each reason must be comparative: strengths/weaknesses relative to the other models, and "choose this if ..."
217
217
  - highlights emphasize differentiators
218
218
  - Respond with ONLY JSON:
219
- {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),Dw(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(Tw(`explain`,`llm-compare→template-text`,Dw(e,`explain`))),iE(t)}default:try{return await oE(`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.
219
+ {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),nT(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(eT(`explain`,`llm-compare→template-text`,nT(e,`explain`))),NE(t)}default:try{return await FE(`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.
220
220
 
221
221
  The candidates occupy distinct quality-tier slots. Write each reason from its slot's perspective:
222
222
  - primary (Best Pick): why this model is the best fit for the user's budget and quality preference
@@ -229,8 +229,8 @@ Rules:
229
229
  - The three reasons must take distinct angles
230
230
  - If the intent is a pipeline (Complexity: pipeline), name the step each model serves (e.g. "用于第3步图生视频")
231
231
  - Respond with ONLY JSON:
232
- {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),Dw(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(Tw(`explain`,`llm-generate→template-text`,Dw(e,`explain`))),iE(t)}}}function cE(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 lE({step:e,candidates:t}){let n=`${e.inputModality.join(`/`)||`?`} → ${e.outputModality.join(`/`)||`?`}`;return[`Step ${e.index}: ${e.label} (${n}, ${e.capabilities.join(`+`)})`,...t.map(cE)].join(`
233
- `)}function uE(e){return iE(e.candidates).map(t=>({...t,step:e.step.index}))}async function dE(e,t){if(e.every(e=>e.candidates.length===0))return e.map(()=>[]);let n;try{t.trace.performance.llmCalls++,n=MT(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.
232
+ {"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),nT(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(eT(`explain`,`llm-generate→template-text`,nT(e,`explain`))),NE(t)}}}function LE(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 RE({step:e,candidates:t}){let n=`${e.inputModality.join(`/`)||`?`} → ${e.outputModality.join(`/`)||`?`}`;return[`Step ${e.index}: ${e.label} (${n}, ${e.capabilities.join(`+`)})`,...t.map(LE)].join(`
233
+ `)}function zE(e){return NE(e.candidates).map(t=>({...t,step:e.step.index}))}async function BE(e,t){if(e.every(e=>e.candidates.length===0))return e.map(()=>[]);let n;try{t.trace.performance.llmCalls++,n=sE(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.
234
234
 
235
235
  Rules:
236
236
  - reason and highlights MUST be in Simplified Chinese (简体中文)
@@ -239,12 +239,12 @@ Rules:
239
239
  - Each reason at most 80 Chinese characters; be specific to the user's task; no generic praise ("性能强大", "效果好")
240
240
  - highlights: 2-3 short phrases
241
241
  - Respond with ONLY JSON:
242
- {"steps":[{"index":1,"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${PT(t.intent)}\n\nSelected candidates per step:\n${e.map(lE).join(`
242
+ {"steps":[{"index":1,"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${lE(t.intent)}\n\nSelected candidates per step:\n${e.map(RE).join(`
243
243
 
244
- `)}`}],{maxTokens:2048,stage:`step-explain`,signal:t.signal}))}catch(n){if($(t.signal),Dw(n,`explain`).kind===`cancelled`)throw n;return t.trace.degradations.push(Tw(`explain`,`step-explain→template-text`,Dw(n,`explain`))),e.map(uE)}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=uE(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 fE(e){return e.inferenceMetadata?.request_modality??[]}function pE(e){return e.inferenceMetadata?.response_modality??[]}function mE(e,t){return t.length===0||e.length===0||t.some(t=>e.includes(t))}function hE(e,t,n){return e.capabilities.includes(t.primaryCapability)?n===`capability-only`?!0:mE(pE(e),t.outputModality)?n===`relaxed-input`||mE(fE(e),t.inputModality):!1:!1}const gE={向量检索:`语义重排`};function _E(e,t){let n=e.filter(t);return n.length>=2?n:e}function vE(e,t,n){let r=$w(e,t);for(let t of[`strict`,`relaxed-input`,`capability-only`]){let i=n.filter(n=>hE(n,e,t));if(i.length<2)continue;let a=e.scene;if(a){i=_E(i,e=>e.profile?.scenes?.includes(a)??!1);let e=gE[a];e&&(i=_E(i,t=>!(t.profile?.scenes?.includes(e)??!1)))}return i=_E(i,e=>Bw([e],r).length>0),{models:i,gate:t}}return{models:n.filter(t=>hE(t,e,`capability-only`)),gate:`capability-only`}}const yE={role:.35,scene:.2,tier:.2,price:.15,extras:.1},bE=/纯文[字本]|无图|仅[用靠]?文字|只有文字|无参考/;function xE(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=>bE.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 SE(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 CE(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 wE(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=CE(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(CE).filter(e=>e!==void 0&&e.unit===r).map(e=>e.value),a=Math.min(...i),o=Math.max(...i);return e=>{let n=CE(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 TE(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 EE(e,t,n){let r=$w(t,n),i=Qw(t,n),a=wE(e,n);return e.map(e=>{let o=xE(e,t),s=i.length===0||(e.profile?.scenes??[]).some(e=>i.includes(e))?1:.3,c=yE.role*o+yE.scene*s+yE.tier*SE(e,n)+yE.price*a(e)+yE.extras*TE(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||(CE(e.model)?.value??1/0)-(CE(t.model)?.value??1/0))}function DE(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 OE={Text:`文本`,Image:`图片`,Video:`视频`,Audio:`音频`};function kE(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=pE(i).length?pE(i):e[r-1].outputModality,s=e[r].inputModality.filter(e=>o.includes(e));if(s.length===0)continue;let c=fE(a);if(c.length>0&&!s.some(e=>c.includes(e))){let e=s.map(e=>OE[e]??e).join(`/`);n.push(`第${r}步 ${i.name} 输出${e},但第${r+1}步首选 ${a.name} 不接受${e}输入,衔接时需要转换或换用备选`)}}return n}function AE(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 jE=[`low`,`medium`,`high`];function ME(e){return e.reduce((e,t)=>jE.indexOf(t)<jE.indexOf(e)?t:e,`high`)}async function NE(e){let t=Xw(e.intent.segments),n=yT(e.models.filter(Lw),e.intent.modelPreference?.excludes??[]),r=Date.now(),i=t.map(t=>vE(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)=>EE(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=>DE(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 dE(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:AE(i[t],o[t][0]),gate:i[t].gate}));return{steps:f,warnings:kE(t,c.map(e=>e[0]?.model)),candidatePool:i.reduce((e,t)=>e+t.models.length,0),confidence:ME(f.map(e=>e.confidence))}}function PE(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`}async function FE(e,t,n){$(t.signal);let r=Date.now(),i={timestamp:(/* @__PURE__ */ new Date()).toISOString(),input:e,performance:{llmCalls:0},degradations:[]},a=await t.catalog();$(t.signal);let o=t.decisionLog??[],s=Date.now(),c;if(n)c=n;else{i.performance.llmCalls++;try{c=await Iw(t.llm,e,t.signal),$(t.signal)}catch(e){let n=Dw(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},t.onTrace?.(i),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=pT(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,t.onTrace?.(i),{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 NE(u);return $(t.signal),i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{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=oT(c),f=Date.now(),p=jT(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 qT(l.score,p,u,d);$(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(),_=$T(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 sE(l.explain,_,u);return $(t.signal),i.performance.explainMs=Date.now()-v,i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{type:`result`,recommendations:y,confidence:PE(u,h),routingReason:l.routingReason,candidatePool:p.length,intent:c,degradations:[...i.degradations]}}const IE=/* @__PURE__ */ new Set([`bailian-model-recommend`]);function LE(){let e=(process.env.BAILIAN_SKILL_EXCLUDE??``).split(`,`).map(e=>e.trim()).filter(Boolean);return/* @__PURE__ */ new Set([...IE,...e])}function RE(){return process.env.BAILIAN_SKILLS_DIR||T(Ft(),`skills`)}function zE(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 BE(){let e=RE();if(!S(e))return[];let t=[],n;try{n=ge(e)}catch{return[]}let r=LE();for(let i of n){let n=T(e,i),a=T(n,`SKILL.md`);if(!S(a))continue;let o;try{o=he(a,`utf-8`)}catch{continue}let s=zE(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 VE(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(`
245
- `)}const HE=65536;function UE(e,t){let n=WE(RE());if(!n)return{error:`skills directory not found`};let r=t?WE(t)??n:n,i=Oe(r,e);if(!GE(i,n))return{error:`path escapes the skills sandbox: ${e}`};let a=WE(i);return a&&!GE(a,n)?{error:`symlink escapes the skills sandbox: ${e}`}:{resolved:i}}function WE(e){try{return ve(e)}catch{return}}function GE(e,t){return e===t||e.startsWith(t+ke)}function KE(e,t,n){let{resolved:r,error:i}=UE(e,n);if(i||!r)return{ok:!1,error:i??`resolve failed`};let a=t.toLowerCase();try{let e=ye(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=he(r,`utf-8`).split(`
246
- `),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 qE(e,t){let{resolved:n,error:r}=UE(e,t);if(r||!n)return{ok:!1,error:r??`resolve failed`};try{if(!ye(n).isFile())return{ok:!1,error:`not a regular file`};let e=he(n),t=e.length>HE;return{ok:!0,content:e.subarray(0,HE).toString(`utf-8`),truncated:t}}catch(e){return{ok:!1,error:e.message}}}function JE(e){return{originalInput:e,clarifications:[]}}function YE(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(`
247
- `)}`}const XE=[{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 ZE(e,t,n){$(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 FE(YE(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=BE(),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=he(T(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=qE(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=KE(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 $(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 QE(){let e=VE(BE());return`You are an AI model selection assistant for Alibaba Cloud Model Studio. You help users find the best model via tools.
244
+ `)}`}],{maxTokens:2048,stage:`step-explain`,signal:t.signal}))}catch(n){if($(t.signal),nT(n,`explain`).kind===`cancelled`)throw n;return t.trace.degradations.push(eT(`explain`,`step-explain→template-text`,nT(n,`explain`))),e.map(zE)}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=zE(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 VE(e){return e.inferenceMetadata?.request_modality??[]}function HE(e){return e.inferenceMetadata?.response_modality??[]}function UE(e,t){return t.length===0||e.length===0||t.some(t=>e.includes(t))}function WE(e,t,n){return e.capabilities.includes(t.primaryCapability)?n===`capability-only`?!0:UE(HE(e),t.outputModality)?n===`relaxed-input`||UE(VE(e),t.inputModality):!1:!1}const GE={向量检索:`语义重排`};function KE(e,t){let n=e.filter(t);return n.length>=2?n:e}function qE(e,t,n){let r=OT(e,t);for(let t of[`strict`,`relaxed-input`,`capability-only`]){let i=n.filter(n=>WE(n,e,t));if(i.length<2)continue;let a=e.scene;if(a){i=KE(i,e=>e.profile?.scenes?.includes(a)??!1);let e=GE[a];e&&(i=KE(i,t=>!(t.profile?.scenes?.includes(e)??!1)))}return i=KE(i,e=>hT([e],r).length>0),{models:i,gate:t}}return{models:n.filter(t=>WE(t,e,`capability-only`)),gate:`capability-only`}}const JE={role:.35,scene:.2,tier:.2,price:.15,extras:.1},YE=/纯文[字本]|无图|仅[用靠]?文字|只有文字|无参考/;function XE(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=>YE.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 ZE(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 QE(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 $E(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=QE(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(QE).filter(e=>e!==void 0&&e.unit===r).map(e=>e.value),a=Math.min(...i),o=Math.max(...i);return e=>{let n=QE(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 eD(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 tD(e,t,n){let r=OT(t,n),i=DT(t,n),a=$E(e,n);return e.map(e=>{let o=XE(e,t),s=i.length===0||(e.profile?.scenes??[]).some(e=>i.includes(e))?1:.3,c=JE.role*o+JE.scene*s+JE.tier*ZE(e,n)+JE.price*a(e)+JE.extras*eD(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||(QE(e.model)?.value??1/0)-(QE(t.model)?.value??1/0))}function nD(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 rD={Text:`文本`,Image:`图片`,Video:`视频`,Audio:`音频`};function iD(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=HE(i).length?HE(i):e[r-1].outputModality,s=e[r].inputModality.filter(e=>o.includes(e));if(s.length===0)continue;let c=VE(a);if(c.length>0&&!s.some(e=>c.includes(e))){let e=s.map(e=>rD[e]??e).join(`/`);n.push(`第${r}步 ${i.name} 输出${e},但第${r+1}步首选 ${a.name} 不接受${e}输入,衔接时需要转换或换用备选`)}}return n}function aD(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 oD=[`low`,`medium`,`high`];function sD(e){return e.reduce((e,t)=>oD.indexOf(t)<oD.indexOf(e)?t:e,`high`)}async function cD(e){let t=TT(e.intent.segments),n=JT(e.models.filter(fT),e.intent.modelPreference?.excludes??[]),r=Date.now(),i=t.map(t=>qE(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)=>tD(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=>nD(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 BE(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:aD(i[t],o[t][0]),gate:i[t].gate}));return{steps:f,warnings:iD(t,c.map(e=>e[0]?.model)),candidatePool:i.reduce((e,t)=>e+t.models.length,0),confidence:sD(f.map(e=>e.confidence))}}function lD(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`}async function uD(e,t,n){$(t.signal);let r=Date.now(),i={timestamp:(/* @__PURE__ */ new Date()).toISOString(),input:e,performance:{llmCalls:0},degradations:[]},a=await t.catalog();$(t.signal);let o=t.decisionLog??[],s=Date.now(),c;if(n)c=n;else{i.performance.llmCalls++;try{c=await dT(t.llm,e,t.signal),$(t.signal)}catch(e){let n=nT(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},t.onTrace?.(i),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=HT(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,t.onTrace?.(i),{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 cD(u);return $(t.signal),i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{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=FT(c),f=Date.now(),p=oE(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 SE(l.score,p,u,d);$(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(),_=OE(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 IE(l.explain,_,u);return $(t.signal),i.performance.explainMs=Date.now()-v,i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{type:`result`,recommendations:y,confidence:lD(u,h),routingReason:l.routingReason,candidatePool:p.length,intent:c,degradations:[...i.degradations]}}const dD=/* @__PURE__ */ new Set([`bailian-model-recommend`]);function fD(){let e=(process.env.BAILIAN_SKILL_EXCLUDE??``).split(`,`).map(e=>e.trim()).filter(Boolean);return/* @__PURE__ */ new Set([...dD,...e])}function pD(){return process.env.BAILIAN_SKILLS_DIR||T(Ft(),`skills`)}function mD(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 hD(){let e=pD();if(!S(e))return[];let t=[],n;try{n=ge(e)}catch{return[]}let r=fD();for(let i of n){let n=T(e,i),a=T(n,`SKILL.md`);if(!S(a))continue;let o;try{o=he(a,`utf-8`)}catch{continue}let s=mD(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 gD(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(`
245
+ `)}const _D=65536;function vD(e,t){let n=yD(pD());if(!n)return{error:`skills directory not found`};let r=t?yD(t)??n:n,i=Oe(r,e);if(!bD(i,n))return{error:`path escapes the skills sandbox: ${e}`};let a=yD(i);return a&&!bD(a,n)?{error:`symlink escapes the skills sandbox: ${e}`}:{resolved:i}}function yD(e){try{return ve(e)}catch{return}}function bD(e,t){return e===t||e.startsWith(t+ke)}function xD(e,t,n){let{resolved:r,error:i}=vD(e,n);if(i||!r)return{ok:!1,error:i??`resolve failed`};let a=t.toLowerCase();try{let e=ye(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=he(r,`utf-8`).split(`
246
+ `),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 SD(e,t){let{resolved:n,error:r}=vD(e,t);if(r||!n)return{ok:!1,error:r??`resolve failed`};try{if(!ye(n).isFile())return{ok:!1,error:`not a regular file`};let e=he(n),t=e.length>_D;return{ok:!0,content:e.subarray(0,_D).toString(`utf-8`),truncated:t}}catch(e){return{ok:!1,error:e.message}}}function CD(e){return{originalInput:e,clarifications:[]}}function wD(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(`
247
+ `)}`}const TD=[{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 ED(e,t,n){$(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 uD(wD(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=hD(),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=he(T(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=SD(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=xD(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 $(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 DD(){let e=gD(hD());return`You are an AI model selection assistant for Alibaba Cloud Model Studio. You help users find the best model via tools.
248
248
 
249
249
  ## Workflow
250
250
  1. FIRST, classify the request type:
@@ -276,10 +276,10 @@ ${e?e+`
276
276
  - Ask about business scenarios, NOT technical parameters (e.g. never ask "how many tokens of context do you need")
277
277
  - Never fabricate model names not returned by tools
278
278
  - 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. "你可以试试问我:推荐一个写代码的模型")
279
- - Everything else — including vague requests like "推荐一个", "有什么好模型", "帮我选个模型" — MUST go through the recommend tool`}async function $E(e,t,n){let r=[{role:`system`,content:QE()},{role:`user`,content:e}],i=JE(e),a=[],o,s=0,c=0,l=e=>{a.push(e),n?.(e)};try{for(let e=0;e<10;e++){c=e,$(t.signal);let n;try{n=await t.llm.chatWithTools(r,XE,{stage:`agent`,signal:t.signal}),$(t.signal)}catch(n){$(t.signal);let r=Dw(n,`agent`);if(r.kind===`cancelled`)throw r;if(r.fatal){if(!o)throw r;let n=Tw(`agent`,`agent-summary→engine-result`,r);return t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), using the recommendation already computed`),l({turn:e,type:`fallback`,reason:`agent_error_existing_result`}),{finalText:``,recommendResult:o,turns:e,degradations:[n],trajectory:a}}t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), falling back to engine: ${r.message}`);let s=await FE(YE(i),t);return l({turn:e,type:`fallback`,reason:`agent_error_engine_rerun`}),{finalText:``,recommendResult:s,turns:e,degradations:[Tw(`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($(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 ZE(a,t,i);$(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||Dw(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,$(t.signal),l({turn:10,type:`fallback`,reason:`turn_budget`}),o?{finalText:``,recommendResult:o,turns:10,degradations:[],trajectory:a}:{finalText:``,recommendResult:await FE(YE(i),t),turns:10,degradations:[],trajectory:a}}catch(e){let n=t.signal?.aborted||Dw(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)}),$(t.signal),e}}const eD=`qwen-flash-2025-07-28`;function tD(e){let{baseUrl:t,apiKey:n,defaultModel:r=eD,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){$(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(e.fetch??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 nD(t,i.status,i.headers.get(`x-request-id`)??void 0)}let o=await a(i,c);return $(r.signal),o}catch(e){throw $(r.signal),o.signal.aborted?new Cw(`timeout`,`LLM request timed out after ${i}ms`,{cause:e}):e instanceof Cw?e:e instanceof SyntaxError?new Cw(`parse`,`LLM 响应不是有效 JSON`,{cause:e}):new Cw(`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 nD(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.[0];if(rD(r?.finish_reason),!r?.message)throw new Cw(`parse`,`LLM 响应缺少 message`);if(iD(r.message.tool_calls??[]),!r.message.content?.trim()&&!r.message.tool_calls?.length)throw new Cw(`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(aD),...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 Cw(`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(`
280
- `);if(f=[],t.trim()===`[DONE]`){u=!0;return}let n=JSON.parse(t);if(n.error||d===`error`)throw nD(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.find(e=>e.index===0||e.index===void 0);rD(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 Cw(`parse`,`工具片段缺少有效 index`);let n=p.get(t)??{id:``,name:``,arguments:``};if(e.id){if(n.id&&n.id!==e.id)throw new Cw(`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(`
281
- `);a=o.pop()??``;for(let e of o)if(h(e),u)break;if(e&&(!u&&a&&h(a),u||m(),!u))throw new Cw(`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(iD(e),!o.trim()&&!e.length)throw new Cw(`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 MT(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 MT(r)}catch(e){throw new Cw(`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(aD),tools:t,temperature:0,max_tokens:4096},{...n,stage:n?.stage??`agent`})).choices?.[0]?.message;return{content:i?.content??``,toolCalls:i?.tool_calls??[]}}}}function nD(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 Cw(t?ww(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 rD(e){if(e&&e!==`stop`&&e!==`tool_calls`)throw new Cw(`parse`,`LLM 响应未完整结束: ${e}`)}function iD(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 Cw(`parse`,`工具调用缺少标识或标识重复`);t.add(n.id);let e;try{e=JSON.parse(n.function.arguments)}catch(e){throw new Cw(`parse`,`工具参数不完整`,{cause:e})}if(!e||typeof e!=`object`||Array.isArray(e))throw new Cw(`parse`,`工具参数必须是 JSON 对象`)}}function aD(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 oD(){return T(Ft(),`skills/bailian-docs-llm-wiki`,`models`)}const sD=/-\d{4}-\d{2}-\d{2}$/;let cD=null,lD=null;function uD(e){if(!S(e))return[];let t=[];for(let n of he(e,`utf-8`).split(`
282
- `))if(n.trim())try{t.push(JSON.parse(n))}catch{}return t}function dD(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(sD,``);return n===e||!t.has(n)})}async function fD(e=oD()){if(cD)return cD;let t=uD(T(e,`models.jsonl`));if(t.length===0)throw Error(`No model catalog found at ${T(e,`models.jsonl`)}. Run any bl advisor/agent command once to sync wiki data.`);return cD=dD(t),cD}async function pD(e=oD()){if(lD)return lD;let t=uD(T(e,`families.jsonl`));return lD=new Map(t.map(e=>[e.slug,e])),lD}function mD(){cD=null,lD=null}function hD(){return{async ask({question:e,options:t,defaultIfSkip:n,signal:r}){$(r);let i=Ve({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(` 输入序号选择,回车使用默认,或直接输入文字描述你的需求
283
- `);;){let e=(await i.question(`Select: `,{signal:r})).trim();if($(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 gD(){return{async ask({question:e,defaultIfSkip:t,signal:n}){return $(n),process.stderr.write(`[recommend] non-interactive, "${e}" → default: ${t}\n`),t}}}function _D(){return T(Ft(),`skills`)}function vD(){return T(_D(),`skill-lock.json`)}function yD(){return{version:1,skills:{}}}function bD(){let e=vD();if(!S(e))return yD();try{let t=JSON.parse(he(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?yD():t}catch{return yD()}}function xD(e){me(_D(),{recursive:!0}),xe(vD(),JSON.stringify(e,null,2)+`
284
- `)}function SD(e,t){let n=bD();n.skills[e]={...n.skills[e],...t},xD(n)}const CD=`BL_SKIP_HOST_AGENTS`,wD=[`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 TD(){let e=He(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||T(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:T(e,r,`skills`),detectDirs:[T(e,r)]}),i=(t,n)=>t?.trim()||T(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:T(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>T(e,t)),s=o.find(e=>S(e))??o[0],c=[T(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(T(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(T(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:T(e,`.agents`,`skills`),detectDirs:[T(e,`.agents`),T(e,`.cline`),T(e,`.dexto`),T(e,`.firebender`),T(e,`.kimi-code`),T(e,`.kimi`),T(e,`.loaf`),T(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:T(n,`agents`,`skills`),detectDirs:[T(n,`agents`),T(n,`amp`),T(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:T(e,`.astrbot`,`data`,`skills`),detectDirs:[T(t,`data`,`skills`),T(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:T(e,`.codebuddy`,`skills`),detectDirs:[T(t,`.codebuddy`),T(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:T(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:T(e,`.continue`,`skills`),detectDirs:[T(t,`.continue`),T(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:T(e,`.deepagents`,`agent`,`skills`),detectDirs:[T(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:T(n,`devin`,`skills`),detectDirs:[T(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:T(n,`goose`,`skills`),detectDirs:[T(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,IC(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:T(e,`.jazz`,`skills`),detectDirs:[T(e,`.jazz`),T(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:T(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[T(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:T(e,`.minimax`,`skills`),detectDirs:[T(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:T(n,`opencode`,`skills`),detectDirs:[T(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:T(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:T(e,`.tabnine`,`agent`,`skills`),detectDirs:[T(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:T(e,`.zcode`,`skills`),detectDirs:[T(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function ED(e){let t=Oe(e);try{return ve(t)}catch{let e=[],n=t;for(;n!==Te(n);){if(S(n))try{return T(ve(n),...e.reverse())}catch{break}e.push(we(n)),n=Te(n)}return t}}function DD(e,t){let n=ED(e),r=ED(t);return n===r||n.startsWith(r+ke)}function OD(e){if(!Ee(e)||DD(e,He()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&DD(e,t))}function kD(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!OD(e)}function AD(){return TD().filter(e=>e.detectDirs.some(e=>kD(e)&&S(e)))}function jD(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function MD(e){let t=_D();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+ke)}return e===t||e.startsWith(t+ke)}function ND(e){try{if(!pe(e).isSymbolicLink())return!1;let t=_e(e);return MD(Ee(t)?t:Oe(Te(e),t))}catch{return!1}}function PD(e,t){if(!t.some(t=>jD(t,e)))return!1;try{return pe(e).isDirectory()}catch{return!1}}function FD(e){try{return pe(e).isDirectory()?S(T(e,`SKILL.md`)):!1}catch{return!1}}const ID=`existing file/dir not managed by bl skill`;function LD(e,t=AD(),n=[]){let r=T(_D(),e),i=[];for(let a of t){let t=T(a.skillsDir,e);try{let e=!1;try{pe(t),e=!0}catch{}if(e){if(ND(t))w(t);else if(PD(t,n))w(t,{recursive:!0,force:!0});else if(FD(t))w(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:ID});continue}}me(a.skillsDir,{recursive:!0});try{be(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 RD(e,t=AD(),n=[]){let r=LD(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===ID).map(e=>e.path),s=n.filter(e=>!a.some(t=>jD(t,e))&&!o.some(t=>jD(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function zD(e,t=[]){let n=[],r=new Set(t);for(let t of TD())r.add(T(t.skillsDir,e));for(let e of r)try{let r;try{r=pe(e)}catch{continue}r.isSymbolicLink()?ND(e)&&n.push(e):t.some(t=>jD(t,e))&&n.push(e)}catch{}return n}function BD(e,t=[]){let n=[];for(let r of zD(e,t))try{if(ND(r))w(r);else if(!pe(r).isSymbolicLink()&&t.some(e=>jD(e,r)))w(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function VD(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function HD(e,t){let n=Ge.extract();n.on(`entry`,(e,r,i)=>{if(!VD(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=T(t,e.name);if(e.type===`directory`){me(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}me(Te(a),{recursive:!0});let o=fe(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await Ue(Ce.from(e),We(),n)}function UD(e){let t=[],n=r=>{for(let i of ge(r?T(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=Re(`sha256`);for(let n of t)r.update(n),r.update(he(T(e,n)));return`sha256:${r.digest(`hex`)}`}function WD(e,t,n=259){let r,i=a=>{for(let o of ge(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=T(a,o.name),c=De(e,s);for(let e of t){let t=T(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 ge(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=T(r,i.name),o=De(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 KD(e,t){let n=GD(e),r=new Set(n.map(e=>e.relativePath));me(t,{recursive:!0});for(let r of n){let n=T(e,r.relativePath),i=T(t,r.relativePath);if(S(i)){let e=pe(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&w(i,{recursive:!0,force:!0})}r.type===`directory`?me(i,{recursive:!0}):(me(Te(i),{recursive:!0}),le(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)w(T(t,e.relativePath),{recursive:!0,force:!0})}function qD(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function JD(e){try{S(e)&&w(e,{recursive:!0,force:!0})}catch{}}function YD(e,t,n={}){me(Te(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(S(t))try{C(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!qD(i))throw i;try{KD(t,r),KD(e,t),JD(r);return}catch(e){try{S(r)&&KD(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{C(e,t)}catch(e){throw S(r)&&!S(t)&&C(r,t),e}JD(r)}function XD(e){if(e instanceof O){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 ZD(e){return e instanceof O&&e.api?.httpStatus===429}function QD(e,t){return Math.min(t*2**(e-1),1e4)}function $D(e){return new Promise(t=>setTimeout(t,e))}async function eO(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;ZD(e)&&await $D(QD(t,a))}throw o}function tO(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function nO(e=3e4,t=3){return eO(async()=>{let t=`${tO()}/index.json`,n;try{n=await Sn.fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new O(`Cannot access skill registry: ${t}`,D.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new O(`Skill registry returned HTTP ${n.status}: ${t}`,D.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 O(`Skill index index.json is not valid JSON`,D.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 O(`Skill index index.json has invalid structure`,D.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const rO=/^sha256-[0-9a-f]{64}\.tar\.br$/;function iO(e){let t=e?.object;return t&&rO.test(t)?t:`skill.tar.br`}async function aO(e,t,n=3){return eO(async()=>{let n=`${tO()}/${e}/${iO(t)}`,r;try{r=await Sn.fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new O(`Failed to download skill ${e}: ${n}`,D.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new O(`Failed to download skill ${e}: HTTP ${r.status}`,D.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 oO(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function sO(e){return e.length>0&&oO(e)===e}function cO(e,t){throw new O(`Skill ${e} validation failed: ${t}`,D.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function lO(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function uO(e,t){let n=T(e,`SKILL.md`),r;try{ye(n).isFile()||cO(t,`SKILL.md is not a regular file`),r=he(n,`utf-8`)}catch(e){if(e instanceof O)throw e;cO(t,`missing SKILL.md`)}let i=lO(r);i===null&&cO(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{cO(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&cO(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)&&cO(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function dO(e){if(!sO(e))throw new O(`Invalid skill name: ${e}`,D.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function fO(e,t,n,r){dO(e);let i=_D(),a=T(i,e),o=T(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{me(o,{recursive:!0}),await HD(t,o);let i=WD(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new O(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,D.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=UD(o);if(t!==n)throw new O(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,D.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=uO(o,e);return YD(o,a),{name:e,path:a,meta:s}}finally{try{S(o)&&w(o,{recursive:!0,force:!0})}catch{}}}async function pO(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new O(`Skill ${e} uses unsupported compression format: ${t.compression}`,D.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return fO(e,await aO(e,t,n),t.contentHash,r)}function mO(e){dO(e);let t=T(_D(),e);return S(t)?(w(t,{recursive:!0,force:!0}),!0):!1}function hO(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 gO(e,t,n=AD(),r=[],i){await pO(e,t,i,process.platform===`win32`?[T(_D(),e),...n.map(t=>T(t.skillsDir,e))]:void 0);let a=RD(e,n,r);return{lockEntry:hO(t,a.links),linkedAgents:a.linkedAgents}}const _O=`bailian-docs-llm-wiki`;function vO(){return T(Ft(),`skills/bailian-docs-llm-wiki`)}function yO(){return S(T(vO(),`models`,`models.jsonl`))}function bO(){return T(Ft(),`wiki-sync-state.json`)}function xO(){try{return JSON.parse(he(bO(),`utf-8`))}catch{return null}}function SO(e){try{xe(bO(),JSON.stringify(e))}catch{}}function CO(e){try{SD(_O,e)}catch{}}function wO(e){try{let t=bD().skills[_O];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function TO(){try{return(await nO(3e3,1)).skills[_O]??null}catch{return null}}async function EO(){let e=xO(),t=Date.now();if(e&&t-e.lastChecked<432e5&&yO())return!1;let n=await TO();if(!n?.contentHash)return!1;if(yO()&&(!e||e.contentHash===n.contentHash)){if(SO({lastChecked:t,contentHash:n.contentHash}),wO(n.contentHash)){let e=bD().skills[_O]?.links??[];CO(hO(n,RD(_O,AD(),e).links))}return!1}try{let e=bD().skills[_O]?.links??[];CO((await gO(_O,n,AD(),e,1)).lockEntry)}catch{return!1}return SO({lastChecked:t,contentHash:n.contentHash}),!0}const DO={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},OO={Single:`single`,Pipeline:`pipeline`},kO={Low:`low`,Medium:`medium`,High:`high`},AO={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},jO={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},MO={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`},NO={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},PO={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},FO=`bailian-cli`,IO=`install-method`,LO=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function RO(e){return e?T(Ft(),`${IO}.${e}`):T(Ft(),IO)}function zO(){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 BO(e){if(!e)return null;let t=e.trim().toLowerCase();return LO.has(t)?t:null}function VO(e){try{return BO(he(e,`utf-8`).split(`
285
- `)[0])}catch{return null}}function HO(){let e=BO(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(zO()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function UO(e){let t=BO(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=VO(RO(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=VO(RO());if(e)return e}return HO()}return VO(RO())||HO()}function WO(e){let t=UO(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function GO(e,t={clientName:FO}){try{let n=Ft();S(n)||me(n,{recursive:!0,mode:448}),xe(RO(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&xe(RO(),`${e}\n`,{mode:384})}catch{}}const KO=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,qO=`https://github.com/modelstudioai/cli/releases`,JO=`https://bailian.aliyun.com/cli/install.sh`,YO=`https://bailian.aliyun.com/cli/install.ps1`;function XO(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):KO}function ZO(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${XO()}/manifest.json`:`${XO()}/${t}.json`}function QO(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${XO()}/${n}/${t}`}function $O(){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===`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 ek(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function tk(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function nk(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function rk(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 ik(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function ak(e,t,n){let r=await rk(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=ik(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 Ne(Te(t),{recursive:!0}),await Ue(r,fe(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function ok(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new rt(`--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 rt(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function sk(){let e=_D();return S(e)?ge(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return ye(T(e,t)).isDirectory()}catch{return!1}}):[]}function ck(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{wD as AGENT_ENV_KEYS,hv as AIGC_MCP_SERVER,gv as AIGC_MCP_TOOL,_t as API_KEY_CAPABILITY_PATTERN,DC as ASYNC_FLAG,dt as BAILIAN_HOST,ox as BATCH_CSV_COLUMNS,Lb as BATCH_ENDPOINTS,Rb as BATCH_STATUSES,zb as BATCH_TERMINAL,BS as BILLING_METHOD,FO as BINARY_PRODUCT_CLIENT_NAME,O as BailianError,Yb as BatchValidator,kO as Budgets,gS as CALC_DATASETS_TOKENS_API,kn as CHANNEL,HS as CHARGE_TYPE,NC as COMMAND_PACK_API_VERSION,EC as CONCURRENT_FLAG,mt as CONFIG_FILE_KEYS,kC as CONSOLE_AUTH_FLAGS,MO as Capabilities,Vh as Client,OO as Complexities,AO as ContextNeeds,at as CredentialError,Mn as DASHSCOPE_SERVICE_HEADER,Dy as DECISION_QUESTION_TYPES,hx as DECISION_REGIONS,VS as DEFAULT_BILLING_METHOD,KO as DEFAULT_CLI_CDN_BASE,mx as DEFAULT_DECISION_MODEL,gx as DEFAULT_DECISION_REGION,RS as DEFAULT_DEPLOY_PLAN,YO as DEFAULT_INSTALL_PS1_URL,JO as DEFAULT_INSTALL_SCRIPT_URL,pt as DEFAULT_LANGUAGE,eD as DEFAULT_LLM_MODEL,Ux as DEFAULT_TRAINING_TYPE,tC as DEPLOY_LIST_INDEPENDENT_API,LS as DEPLOY_PLAN,$S as DEPLOY_START_API,eC as DEPLOY_STOP_API,ut as DOCS_HOSTS,_S as ESTIMATE_FINETUNE_TOKENS_API,D as ExitCode,NO as Features,qO as GITHUB_RELEASES_BASE,TC as GLOBAL_FLAGS,Yx as INSUFFICIENT_SAMPLES_CODE,uC as LIST_SUPPORT_IMPORT_MODELS_API,Cw as LLMError,Bb as MAX_BATCH_BYTES,Vb as MAX_BATCH_LINE_BYTES,Hb as MAX_BATCH_RECORDS,cy as MAX_CPT_BYTES,sy as MAX_DATASET_BYTES,Oy as MAX_DECISION_CHOICE_OPTIONS,ly as MAX_DECISION_DATASET_BYTES,Ay as MAX_DECISION_SCORE_LEVELS,uy as MAX_MEDIA_ZIP_BYTES,An as MCP_CALL_SERVICE,Tv as MCP_IMAGE_GEN_RATIO_SIZES,Dv as MCP_TTS_VOICES,ky as MIN_DECISION_SCORE_LEVELS,OC as MODEL_AUTH_FLAGS,Rv as MODEL_LIST_API,kh as McpClient,DO as Modalities,PO as ModelCategories,AC as OPENAPI_AUTH_FLAGS,jn as OPEN_API_SOURCE,zv as PREDICT_CONFIG_API,jO as QualityPreferences,C_ as RAG_PATHS,XE as RECOMMEND_TOOLS,lt as REGIONS,v_ as SANDBOX_PATHS,CD as SKIP_HOST_AGENTS_ENV,mC as SPEECH_BIASING_MODEL,ZS as STRATEGIES,ft as SUPPORTED_LANGUAGES,hS as TRAINING_MODEL_PRICE_API,Hx as TRAINING_TYPES_CLI,Vx as TRAINING_TYPE_MAP,rt as UsageError,on as activateConfigProfile,$E as agentLoop,m_ as agentStudioFilesPath,Mg as agentStudioHost,Iw as analyzeEngineIntent,En as anonymousConsoleCall,mg as appCompletionPath,YD as atomicSwap,rr as audioFileToDataUri,Fh as bailianMcpPath,Ih as bailianMcpSsePath,Kb as batchChunks,px as batchDataNotes,fx as batchExamples,Ub as batchIoError,qb as batchLines,Wb as batchObject,Q as batchUsage,ek as binaryAssetFileName,nk as binaryInnerFileName,tk as binaryTarFileName,Hn as buildAcsCanonicalQuery,q_ as buildAsrContextMessages,Y_ as buildAsrFlashRequest,J_ as buildAsyncAsrLanguageFields,$v as buildCommandInvocation,YE as buildEngineInput,yv as buildImageEditArgs,vv as buildImageGenArgs,xv as buildImageToVideoArgs,un as buildOutputSettings,qS as buildPrepaidInfo,WS as buildReservationCapacity,dn as buildSettings,hO as buildSkillLockEntry,ln as buildSources,wv as buildSpeechToTextArgs,bv as buildTextToVideoArgs,Cv as buildTtsArgs,Sv as buildVideoFetchArgs,hC as buildVocabularyRequest,On as callConsoleGateway,ex as cancelBatch,zx as cancelCompressJob,Ex as cancelFineTune,ZO as channelManifestUrl,Zh as chatPath,Z_ as collectAsrTranscriptionItems,ty as commandRef,UD as computeDirContentHash,ck as computeSkillStatuses,zh as connectBailianMcpWithFallback,fv as createBailianControlUser,Qb as createBatch,OS as createCapacityInstance,Fx as createCompressJob,oC as createCustomModelImport,SS as createDeployment,Cx as createFineTune,cv as createInstrumentedFetch,tD as createLLMClient,gD as createNonInteractive,hD as createReadlineInteraction,JE as createSession,tw as createTrackingEvent,_C as createVocabulary,jC as credentialFlagDefs,ig as decisionPath,zS as defaultDeployPlan,MC as defineCommand,jS as deleteCapacityInstance,Bx as deleteCompressJob,sn as deleteConfigProfile,lC as deleteCustomModelImport,oy as deleteDataset,NS as deleteDeployment,Dx as deleteFineTune,xC as deleteVocabulary,a_ as deploymentCapacityInstancePath,s_ as deploymentCapacityInstanceRenewPath,o_ as deploymentCapacityInstanceScalePath,i_ as deploymentCapacityInstancesPath,l_ as deploymentCapacityOperationPath,c_ as deploymentOverflowPath,Pt as describeAuthState,$O as detectBinaryPlatform,HO as detectInstallMethod,AD as detectInstalledAgents,Tb as detectModality,Ht as detectOutputFormat,ZE as dispatchTool,aO as downloadSkillAsset,Tn as effectiveConsoleGatewayConfig,yD as emptySkillLock,Rt as ensureConfigDir,bS as estimateCptTokens,yS as estimateSftDpoTokens,dx as exportBatchCsv,Mx as exportCheckpoint,X_ as extractAsrFlashText,HD as extractTarBr,ak as extractZipEntryToFile,RD as fanOutSkillToAgents,Jx as fetchModelCapability,qv as fetchModelDetail,Wv as fetchModelGroups,Kv as fetchModelGroupsAll,Vv as fetchModelList,Hv as fetchModelListAll,Xv as fetchPredictConfig,nO as fetchSkillsIndex,vS as fetchTrainingModelPrice,aC as findDeploymentEntry,Uv as findModelByName,fC as findSupportImportModel,Gv as flattenModelGroups,mw as flushTelemetry,Sx as followParsexResult,ey as formatCommand,Ew as formatDegradation,Vt as formatErrorJson,Ib as formatIssue,Bt as formatJson,Ut as formatOutput,zt as formatText,Gh as generateCLIAccessToken,FC as generateFilename,TD as getAgentTargets,mn as getApiKeyLoginKind,$b as getBatch,nx as getBatchFileContent,ES as getCapacityInstance,DS as getCapacityOperation,XO as getCliCdnBase,Lx as getCompressJob,Rx as getCompressJobLogs,Ft as getConfigDir,It as getConfigPath,Lt as getCredentialsPath,cC as getCustomModelImport,ay as getDataset,wS as getDeployment,Tx as getFineTune,eS as getFineTuneHyperParameterDefaultNumber,Ox as getFineTuneLogs,kx as getFineTuneParams,IC as getHermesHome,UO as getInstallMethod,pn as getModelProfilePreset,xx as getParsexResult,pS as getProfile,vD as getSkillLockPath,tO as getSkillRegistryBaseUrl,_D as getSkillsDir,WO as getUpdateInstallMethod,GS as hasPrepaidFlags,Sn as httpTransport,cg as image2ImagePath,ug as image2videoPath,nr as imageFileToDataUri,ag as imagePath,og as imageSyncPath,sg as imageText2ImagePath,K_ as inferAudioFormatHint,zy as inspectDecisionQuestion,Vy as inspectDecisionQuestionId,By as inspectDecisionQuestionTable,Hy as inspectDecisionQuestions,Fy as inspectDecisionState,pO as installSkill,fO as installSkillFromBuffer,gO as installSkillWithFanout,vt as isApiKeyCapability,zO as isCompiledBinary,ev as isDashScopeGateway,My as isDecisionObject,OD as isHostSystemDetectDir,M_ as isLegacyImage2ImageModel,j_ as isLegacyText2ImageModel,or as isLocalFile,Ov as isMcpTtsVoice,Tt as isModelConnectionSourceMismatch,VD as isSafeEntryName,sO as isSafeSkillName,Lh as isStreamableHttpUnsupported,D_ as isSyncMultimodalImageModel,Wx as isTrainingTypeCli,Rh as isUrlOverrideSseFallbackCandidate,N_ as isWanxFunctionImageEditModel,jg as knowledgeChatEndpoint,Ag as knowledgeSearchEndpoint,LD as linkSkillToAgents,pv as listBailianControlWorkspaces,Ax as listBasicMetrics,tx as listBatches,TS as listCapacityInstances,jx as listCheckpoints,Ix as listCompressJobs,Px as listCompressTemplates,sC as listCustomModelImports,iy as listDatasets,PS as listDeployableModels,CS as listDeployments,wx as listFineTunes,iC as listIndependentDeployedModels,sk as listSkillDirsOnDisk,dC as listSupportImportModels,Fb as listSupportedFormats,qx as listSupportedTrainingTypes,mS as listTrainingTypes,vC as listVocabularies,fD as loadCatalog,pD as loadFamilies,hw as localSink,_n as makeAuthStore,Zv as makeConfigStore,ot as mapApiError,BC as maskToken,EO as maybeSyncWikiData,Ig as mcpWebSearchPath,gg as memoryAddAsyncPath,hg as memoryEndpoint,_g as memoryEventPath,yg as memoryListPath,bg as memoryNodePath,vg as memorySearchPath,xg as memorySkillExportPath,Kx as modelSupportsTrainingType,fg as modelsLimitsPath,pg as modelsPermissionsPath,yt as normalizeApiKeyCapabilities,Yt as normalizeConfigName,st as normalizeModelBaseUrl,Pv as parseAigcAsrTexts,Av as parseAigcImageResults,_v as parseAigcToolResult,jv as parseAigcTtsResult,Mv as parseAigcVideoTaskId,Nv as parseAigcVideoTaskResult,Gb as parseBatchEndpoint,WC as parseBooleanValue,xt as parseConfigFile,fy as parseDatasetSchemaFlag,CC as parseInstantVocabulary,GC as parseOptionalBooleanValue,Lv as parseSSE,iv as parseSecurityBody,ok as parseSkillNames,wC as parseVocabularyEntries,Yh as parsexBaseUrl,Xh as parsexEndpoint,QS as pickPlanStrategy,Mb as pickValidator,zD as planUnlinkSkillFromAgents,Xx as preflightBatchSizeGate,ax as prepareBatch,Eg as profileSchemaItemPath,Tg as profileSchemaPath,ux as projectBatchCsv,yC as queryVocabulary,p_ as ragEndpoint,Zb as readBatchBlob,ew as readCaller,$t as readConfigFile,nn as readConfigProfiles,bD as readSkillLock,HC as readTextFromPathOrStdin,FE as recommendEngine,ir as redactDataUri,Kh as refreshAccessToken,Nb as registerValidator,QO as releaseAssetUrl,gw as remoteSink,mO as removeSkillDir,ny as renderCommandText,AS as renewCapacityInstance,Ln as request,Vn as requestJson,pC as requiredTrainTypeForWeightType,mv as resetBailianControlPolicies4Agent,mD as resetCatalogCache,Ot as resolveApiKey,St as resolveApiKeySource,G_ as resolveAsrApi,iO as resolveAssetFileName,rx as resolveBatchChatEndpoint,KC as resolveBooleanFlag,Uh as resolveCLIAccessTokenTarget,kt as resolveConsole,sr as resolveFileUrl,R_ as resolveImageEditApi,L_ as resolveImageGenerateApi,P_ as resolveImageSizeProfile,Ev as resolveMcpImageSize,Dt as resolveModelBaseUrl,Ct as resolveModelBaseUrlSource,Et as resolveModelBaseUrlState,wt as resolveModelConnectionProvenance,At as resolveOpenApi,zC as resolveOutputDir,F_ as resolvePromptExtendDefault,qC as resolveWatermark,rg as responsesPath,pT as routeEngine,UC as runWithConcurrency,g_ as sandboxApiPath,h_ as sandboxBaseUrl,__ as sandboxEndpoint,b_ as sandboxInstanceActionPath,y_ as sandboxInstancePath,S_ as sandboxTemplateBuildStatusPath,x_ as sandboxTemplatePath,nt as sanitizeDiagnosticDetails,oO as sanitizeSkillName,kS as scaleCapacityInstance,FS as scaleDeployment,Fg as securityAgentLogsEndpoint,av as securityGet,Pg as securityOverviewEndpoint,cn as selectApiKeyResolutionSources,Un as signAcsRequest,Nn as sourceConfig,Cg as speechRecognizePath,Sg as speechSynthesizePath,wg as speechVocabularyPath,nC as startModelService,rC as stopModelService,yx as stripDecisionTrainingFields,VC as stripUndefined,bx as submitParsexTask,dg as taskPath,bw as trackCommandExecution,Pn as trackingHeaders,Gx as trainingTypeMethodVariant,BD as unlinkSkillFromAgents,vx as unwrapDecisionQuestions,Bv as unwrapResponse,IS as updateDeployment,MS as updateDeploymentOverflow,bC as updateVocabulary,ry as uploadDataset,ar as uploadFile,SD as upsertSkillLockEntry,Dg as userProfilePath,Og as userProfileValuesPath,Xb as validateBatch,an as validateConfigProfileActivation,Wh as validateConsoleAccessToken,Pb as validateDataset,$x as validateFineTuneHyperParameterOverrides,KS as validatePrepaidFlags,US as validateReservationCapacity,uO as validateSkillDir,Gt as validateTimeout,lg as videoGeneratePath,kg as workspaceMaaSBaseUrl,ix as writeBatchFile,en as writeConfigFile,GO as writeInstallMethodSync,xD as writeSkillLock};
279
+ - Everything else — including vague requests like "推荐一个", "有什么好模型", "帮我选个模型" — MUST go through the recommend tool`}async function OD(e,t,n){let r=[{role:`system`,content:DD()},{role:`user`,content:e}],i=CD(e),a=[],o,s=0,c=0,l=e=>{a.push(e),n?.(e)};try{for(let e=0;e<10;e++){c=e,$(t.signal);let n;try{n=await t.llm.chatWithTools(r,TD,{stage:`agent`,signal:t.signal}),$(t.signal)}catch(n){$(t.signal);let r=nT(n,`agent`);if(r.kind===`cancelled`)throw r;if(r.fatal){if(!o)throw r;let n=eT(`agent`,`agent-summary→engine-result`,r);return t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), using the recommendation already computed`),l({turn:e,type:`fallback`,reason:`agent_error_existing_result`}),{finalText:``,recommendResult:o,turns:e,degradations:[n],trajectory:a}}t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), falling back to engine: ${r.message}`);let s=await uD(wD(i),t);return l({turn:e,type:`fallback`,reason:`agent_error_engine_rerun`}),{finalText:``,recommendResult:s,turns:e,degradations:[eT(`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($(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 ED(a,t,i);$(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||nT(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,$(t.signal),l({turn:10,type:`fallback`,reason:`turn_budget`}),o?{finalText:``,recommendResult:o,turns:10,degradations:[],trajectory:a}:{finalText:``,recommendResult:await uD(wD(i),t),turns:10,degradations:[],trajectory:a}}catch(e){let n=t.signal?.aborted||nT(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)}),$(t.signal),e}}const kD=`qwen-flash-2025-07-28`;function AD(e){let{baseUrl:t,apiKey:n,defaultModel:r=kD,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){$(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(e.fetch??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 jD(t,i.status,i.headers.get(`x-request-id`)??void 0)}let o=await a(i,c);return $(r.signal),o}catch(e){throw $(r.signal),o.signal.aborted?new Qw(`timeout`,`LLM request timed out after ${i}ms`,{cause:e}):e instanceof Qw?e:e instanceof SyntaxError?new Qw(`parse`,`LLM 响应不是有效 JSON`,{cause:e}):new Qw(`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 jD(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.[0];if(MD(r?.finish_reason),!r?.message)throw new Qw(`parse`,`LLM 响应缺少 message`);if(ND(r.message.tool_calls??[]),!r.message.content?.trim()&&!r.message.tool_calls?.length)throw new Qw(`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(PD),...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 Qw(`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(`
280
+ `);if(f=[],t.trim()===`[DONE]`){u=!0;return}let n=JSON.parse(t);if(n.error||d===`error`)throw jD(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.find(e=>e.index===0||e.index===void 0);MD(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 Qw(`parse`,`工具片段缺少有效 index`);let n=p.get(t)??{id:``,name:``,arguments:``};if(e.id){if(n.id&&n.id!==e.id)throw new Qw(`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(`
281
+ `);a=o.pop()??``;for(let e of o)if(h(e),u)break;if(e&&(!u&&a&&h(a),u||m(),!u))throw new Qw(`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(ND(e),!o.trim()&&!e.length)throw new Qw(`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 sE(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 sE(r)}catch(e){throw new Qw(`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(PD),tools:t,temperature:0,max_tokens:4096},{...n,stage:n?.stage??`agent`})).choices?.[0]?.message;return{content:i?.content??``,toolCalls:i?.tool_calls??[]}}}}function jD(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 Qw(t?$w(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 MD(e){if(e&&e!==`stop`&&e!==`tool_calls`)throw new Qw(`parse`,`LLM 响应未完整结束: ${e}`)}function ND(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 Qw(`parse`,`工具调用缺少标识或标识重复`);t.add(n.id);let e;try{e=JSON.parse(n.function.arguments)}catch(e){throw new Qw(`parse`,`工具参数不完整`,{cause:e})}if(!e||typeof e!=`object`||Array.isArray(e))throw new Qw(`parse`,`工具参数必须是 JSON 对象`)}}function PD(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 FD(){return T(Ft(),`skills/bailian-docs-llm-wiki`,`models`)}const ID=/-\d{4}-\d{2}-\d{2}$/;let LD=null,RD=null;function zD(e){if(!S(e))return[];let t=[];for(let n of he(e,`utf-8`).split(`
282
+ `))if(n.trim())try{t.push(JSON.parse(n))}catch{}return t}function BD(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(ID,``);return n===e||!t.has(n)})}async function VD(e=FD()){if(LD)return LD;let t=zD(T(e,`models.jsonl`));if(t.length===0)throw Error(`No model catalog found at ${T(e,`models.jsonl`)}. Run any bl advisor/agent command once to sync wiki data.`);return LD=BD(t),LD}async function HD(e=FD()){if(RD)return RD;let t=zD(T(e,`families.jsonl`));return RD=new Map(t.map(e=>[e.slug,e])),RD}function UD(){LD=null,RD=null}function WD(){return{async ask({question:e,options:t,defaultIfSkip:n,signal:r}){$(r);let i=Ve({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(` 输入序号选择,回车使用默认,或直接输入文字描述你的需求
283
+ `);;){let e=(await i.question(`Select: `,{signal:r})).trim();if($(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 GD(){return{async ask({question:e,defaultIfSkip:t,signal:n}){return $(n),process.stderr.write(`[recommend] non-interactive, "${e}" → default: ${t}\n`),t}}}function KD(){return T(Ft(),`skills`)}function qD(){return T(KD(),`skill-lock.json`)}function JD(){return{version:1,skills:{}}}function YD(){let e=qD();if(!S(e))return JD();try{let t=JSON.parse(he(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?JD():t}catch{return JD()}}function XD(e){me(KD(),{recursive:!0}),xe(qD(),JSON.stringify(e,null,2)+`
284
+ `)}function ZD(e,t){let n=YD();n.skills[e]={...n.skills[e],...t},XD(n)}const QD=`BL_SKIP_HOST_AGENTS`,$D=[`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 eO(){let e=He(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||T(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:T(e,r,`skills`),detectDirs:[T(e,r)]}),i=(t,n)=>t?.trim()||T(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:T(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>T(e,t)),s=o.find(e=>S(e))??o[0],c=[T(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(T(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(T(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:T(e,`.agents`,`skills`),detectDirs:[T(e,`.agents`),T(e,`.cline`),T(e,`.dexto`),T(e,`.firebender`),T(e,`.kimi-code`),T(e,`.kimi`),T(e,`.loaf`),T(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:T(n,`agents`,`skills`),detectDirs:[T(n,`agents`),T(n,`amp`),T(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:T(e,`.astrbot`,`data`,`skills`),detectDirs:[T(t,`data`,`skills`),T(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:T(e,`.codebuddy`,`skills`),detectDirs:[T(t,`.codebuddy`),T(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:T(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:T(e,`.continue`,`skills`),detectDirs:[T(t,`.continue`),T(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:T(e,`.deepagents`,`agent`,`skills`),detectDirs:[T(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:T(n,`devin`,`skills`),detectDirs:[T(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:T(n,`goose`,`skills`),detectDirs:[T(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,dw(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:T(e,`.jazz`,`skills`),detectDirs:[T(e,`.jazz`),T(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:T(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[T(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:T(e,`.minimax`,`skills`),detectDirs:[T(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:T(n,`opencode`,`skills`),detectDirs:[T(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:T(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:T(e,`.tabnine`,`agent`,`skills`),detectDirs:[T(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:T(e,`.zcode`,`skills`),detectDirs:[T(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function tO(e){let t=Oe(e);try{return ve(t)}catch{let e=[],n=t;for(;n!==Te(n);){if(S(n))try{return T(ve(n),...e.reverse())}catch{break}e.push(we(n)),n=Te(n)}return t}}function nO(e,t){let n=tO(e),r=tO(t);return n===r||n.startsWith(r+ke)}function rO(e){if(!Ee(e)||nO(e,He()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&nO(e,t))}function iO(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!rO(e)}function aO(){return eO().filter(e=>e.detectDirs.some(e=>iO(e)&&S(e)))}function oO(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function sO(e){let t=KD();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+ke)}return e===t||e.startsWith(t+ke)}function cO(e){try{if(!pe(e).isSymbolicLink())return!1;let t=_e(e);return sO(Ee(t)?t:Oe(Te(e),t))}catch{return!1}}function lO(e,t){if(!t.some(t=>oO(t,e)))return!1;try{return pe(e).isDirectory()}catch{return!1}}function uO(e){try{return pe(e).isDirectory()?S(T(e,`SKILL.md`)):!1}catch{return!1}}const dO=`existing file/dir not managed by bl skill`;function fO(e,t=aO(),n=[]){let r=T(KD(),e),i=[];for(let a of t){let t=T(a.skillsDir,e);try{let e=!1;try{pe(t),e=!0}catch{}if(e){if(cO(t))w(t);else if(lO(t,n))w(t,{recursive:!0,force:!0});else if(uO(t))w(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:dO});continue}}me(a.skillsDir,{recursive:!0});try{be(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 pO(e,t=aO(),n=[]){let r=fO(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===dO).map(e=>e.path),s=n.filter(e=>!a.some(t=>oO(t,e))&&!o.some(t=>oO(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function mO(e,t=[]){let n=[],r=new Set(t);for(let t of eO())r.add(T(t.skillsDir,e));for(let e of r)try{let r;try{r=pe(e)}catch{continue}r.isSymbolicLink()?cO(e)&&n.push(e):t.some(t=>oO(t,e))&&n.push(e)}catch{}return n}function hO(e,t=[]){let n=[];for(let r of mO(e,t))try{if(cO(r))w(r);else if(!pe(r).isSymbolicLink()&&t.some(e=>oO(e,r)))w(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function gO(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function _O(e,t){let n=Ge.extract();n.on(`entry`,(e,r,i)=>{if(!gO(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=T(t,e.name);if(e.type===`directory`){me(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}me(Te(a),{recursive:!0});let o=fe(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await Ue(Ce.from(e),We(),n)}function vO(e){let t=[],n=r=>{for(let i of ge(r?T(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=Re(`sha256`);for(let n of t)r.update(n),r.update(he(T(e,n)));return`sha256:${r.digest(`hex`)}`}function yO(e,t,n=259){let r,i=a=>{for(let o of ge(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=T(a,o.name),c=De(e,s);for(let e of t){let t=T(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 bO(e){let t=[],n=r=>{for(let i of ge(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=T(r,i.name),o=De(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 xO(e,t){let n=bO(e),r=new Set(n.map(e=>e.relativePath));me(t,{recursive:!0});for(let r of n){let n=T(e,r.relativePath),i=T(t,r.relativePath);if(S(i)){let e=pe(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&w(i,{recursive:!0,force:!0})}r.type===`directory`?me(i,{recursive:!0}):(me(Te(i),{recursive:!0}),le(n,i))}let i=bO(t).filter(e=>!r.has(e.relativePath)).sort((e,t)=>t.relativePath.length-e.relativePath.length);for(let e of i)w(T(t,e.relativePath),{recursive:!0,force:!0})}function SO(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function CO(e){try{S(e)&&w(e,{recursive:!0,force:!0})}catch{}}function wO(e,t,n={}){me(Te(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(S(t))try{C(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!SO(i))throw i;try{xO(t,r),xO(e,t),CO(r);return}catch(e){try{S(r)&&xO(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{C(e,t)}catch(e){throw S(r)&&!S(t)&&C(r,t),e}CO(r)}function TO(e){if(e instanceof O){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 EO(e){return e instanceof O&&e.api?.httpStatus===429}function DO(e,t){return Math.min(t*2**(e-1),1e4)}function OO(e){return new Promise(t=>setTimeout(t,e))}async function kO(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??TO,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;EO(e)&&await OO(DO(t,a))}throw o}function AO(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function jO(e=3e4,t=3){return kO(async()=>{let t=`${AO()}/index.json`,n;try{n=await Sn.fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new O(`Cannot access skill registry: ${t}`,D.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new O(`Skill registry returned HTTP ${n.status}: ${t}`,D.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 O(`Skill index index.json is not valid JSON`,D.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 O(`Skill index index.json has invalid structure`,D.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const MO=/^sha256-[0-9a-f]{64}\.tar\.br$/;function NO(e){let t=e?.object;return t&&MO.test(t)?t:`skill.tar.br`}async function PO(e,t,n=3){return kO(async()=>{let n=`${AO()}/${e}/${NO(t)}`,r;try{r=await Sn.fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new O(`Failed to download skill ${e}: ${n}`,D.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new O(`Failed to download skill ${e}: HTTP ${r.status}`,D.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 FO(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function IO(e){return e.length>0&&FO(e)===e}function LO(e,t){throw new O(`Skill ${e} validation failed: ${t}`,D.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function RO(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function zO(e,t){let n=T(e,`SKILL.md`),r;try{ye(n).isFile()||LO(t,`SKILL.md is not a regular file`),r=he(n,`utf-8`)}catch(e){if(e instanceof O)throw e;LO(t,`missing SKILL.md`)}let i=RO(r);i===null&&LO(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{LO(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&LO(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)&&LO(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function BO(e){if(!IO(e))throw new O(`Invalid skill name: ${e}`,D.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function VO(e,t,n,r){BO(e);let i=KD(),a=T(i,e),o=T(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{me(o,{recursive:!0}),await _O(t,o);let i=yO(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new O(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,D.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=vO(o);if(t!==n)throw new O(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,D.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=zO(o,e);return wO(o,a),{name:e,path:a,meta:s}}finally{try{S(o)&&w(o,{recursive:!0,force:!0})}catch{}}}async function HO(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new O(`Skill ${e} uses unsupported compression format: ${t.compression}`,D.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return VO(e,await PO(e,t,n),t.contentHash,r)}function UO(e){BO(e);let t=T(KD(),e);return S(t)?(w(t,{recursive:!0,force:!0}),!0):!1}function WO(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 GO(e,t,n=aO(),r=[],i){await HO(e,t,i,process.platform===`win32`?[T(KD(),e),...n.map(t=>T(t.skillsDir,e))]:void 0);let a=pO(e,n,r);return{lockEntry:WO(t,a.links),linkedAgents:a.linkedAgents}}const KO=`bailian-docs-llm-wiki`;function qO(){return T(Ft(),`skills/bailian-docs-llm-wiki`)}function JO(){return S(T(qO(),`models`,`models.jsonl`))}function YO(){return T(Ft(),`wiki-sync-state.json`)}function XO(){try{return JSON.parse(he(YO(),`utf-8`))}catch{return null}}function ZO(e){try{xe(YO(),JSON.stringify(e))}catch{}}function QO(e){try{ZD(KO,e)}catch{}}function $O(e){try{let t=YD().skills[KO];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function ek(){try{return(await jO(3e3,1)).skills[KO]??null}catch{return null}}async function tk(){let e=XO(),t=Date.now();if(e&&t-e.lastChecked<432e5&&JO())return!1;let n=await ek();if(!n?.contentHash)return!1;if(JO()&&(!e||e.contentHash===n.contentHash)){if(ZO({lastChecked:t,contentHash:n.contentHash}),$O(n.contentHash)){let e=YD().skills[KO]?.links??[];QO(WO(n,pO(KO,aO(),e).links))}return!1}try{let e=YD().skills[KO]?.links??[];QO((await GO(KO,n,aO(),e,1)).lockEntry)}catch{return!1}return ZO({lastChecked:t,contentHash:n.contentHash}),!0}const nk={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},rk={Single:`single`,Pipeline:`pipeline`},ik={Low:`low`,Medium:`medium`,High:`high`},ak={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},ok={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},sk={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`},ck={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},lk={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},uk=`bailian-cli`,dk=`install-method`,fk=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function pk(e){return e?T(Ft(),`${dk}.${e}`):T(Ft(),dk)}function mk(){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 hk(e){if(!e)return null;let t=e.trim().toLowerCase();return fk.has(t)?t:null}function gk(e){try{return hk(he(e,`utf-8`).split(`
285
+ `)[0])}catch{return null}}function _k(){let e=hk(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(mk()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function vk(e){let t=hk(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=gk(pk(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=gk(pk());if(e)return e}return _k()}return gk(pk())||_k()}function yk(e){let t=vk(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function bk(e,t={clientName:uk}){try{let n=Ft();S(n)||me(n,{recursive:!0,mode:448}),xe(pk(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&xe(pk(),`${e}\n`,{mode:384})}catch{}}const xk=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,Sk=`https://github.com/modelstudioai/cli/releases`,Ck=`https://bailian.aliyun.com/cli/install.sh`,wk=`https://bailian.aliyun.com/cli/install.ps1`;function Tk(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):xk}function Ek(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${Tk()}/manifest.json`:`${Tk()}/${t}.json`}function Dk(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${Tk()}/${n}/${t}`}function Ok(){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===`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 kk(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function Ak(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function jk(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function Mk(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 Nk(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function Pk(e,t,n){let r=await Mk(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=Nk(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 Ne(Te(t),{recursive:!0}),await Ue(r,fe(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function Fk(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new rt(`--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 rt(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function Ik(){let e=KD();return S(e)?ge(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return ye(T(e,t)).isDirectory()}catch{return!1}}):[]}function Lk(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{$D as AGENT_ENV_KEYS,hv as AIGC_MCP_SERVER,gv as AIGC_MCP_TOOL,_t as API_KEY_CAPABILITY_PATTERN,nw as ASYNC_FLAG,dt as BAILIAN_HOST,kx as BATCH_CSV_COLUMNS,ox as BATCH_ENDPOINTS,sx as BATCH_STATUSES,cx as BATCH_TERMINAL,lC as BILLING_METHOD,uk as BINARY_PRODUCT_CLIENT_NAME,O as BailianError,vx as BatchValidator,ik as Budgets,zS as CALC_DATASETS_TOKENS_API,kn as CHANNEL,dC as CHARGE_TYPE,cw as COMMAND_PACK_API_VERSION,tw as CONCURRENT_FLAG,mt as CONFIG_FILE_KEYS,iw as CONSOLE_AUTH_FLAGS,hy as CONSOLE_DATASET_BY_ID_API,_y as CONSOLE_DATASET_GROUPS_API,gy as CONSOLE_DATASET_VERSIONS_API,kC as CONSOLE_DEPLOY_INSTANCES_API,cy as CONSOLE_FILE_URL_API,sk as Capabilities,Vh as Client,rk as Complexities,ak as ContextNeeds,at as CredentialError,Mn as DASHSCOPE_SERVICE_HEADER,Xy as DECISION_QUESTION_TYPES,Rx as DECISION_REGIONS,uC as DEFAULT_BILLING_METHOD,xk as DEFAULT_CLI_CDN_BASE,Lx as DEFAULT_DECISION_MODEL,zx as DEFAULT_DECISION_REGION,sC as DEFAULT_DEPLOY_PLAN,wk as DEFAULT_INSTALL_PS1_URL,Ck as DEFAULT_INSTALL_SCRIPT_URL,pt as DEFAULT_LANGUAGE,kD as DEFAULT_LLM_MODEL,fS as DEFAULT_TRAINING_TYPE,wC as DEPLOY_LIST_INDEPENDENT_API,oC as DEPLOY_PLAN,SC as DEPLOY_START_API,CC as DEPLOY_STOP_API,ut as DOCS_HOSTS,BS as ESTIMATE_FINETUNE_TOKENS_API,D as ExitCode,ck as Features,Sk as GITHUB_RELEASES_BASE,ew as GLOBAL_FLAGS,vS as INSUFFICIENT_SAMPLES_CODE,zC as LIST_SUPPORT_IMPORT_MODELS_API,Qw as LLMError,lx as MAX_BATCH_BYTES,ux as MAX_BATCH_LINE_BYTES,dx as MAX_BATCH_RECORDS,jy as MAX_CPT_BYTES,Ay as MAX_DATASET_BYTES,Zy as MAX_DECISION_CHOICE_OPTIONS,My as MAX_DECISION_DATASET_BYTES,$y as MAX_DECISION_SCORE_LEVELS,Ny as MAX_MEDIA_ZIP_BYTES,An as MCP_CALL_SERVICE,Tv as MCP_IMAGE_GEN_RATIO_SIZES,Dv as MCP_TTS_VOICES,Qy as MIN_DECISION_SCORE_LEVELS,rw as MODEL_AUTH_FLAGS,Uv as MODEL_LIST_API,kh as McpClient,nk as Modalities,lk as ModelCategories,aw as OPENAPI_AUTH_FLAGS,jn as OPEN_API_SOURCE,Wv as PREDICT_CONFIG_API,ok as QualityPreferences,C_ as RAG_PATHS,TD as RECOMMEND_TOOLS,lt as REGIONS,v_ as SANDBOX_PATHS,QD as SKIP_HOST_AGENTS_ENV,UC as SPEECH_BIASING_MODEL,bC as STRATEGIES,ft as SUPPORTED_LANGUAGES,RS as TRAINING_MODEL_PRICE_API,dS as TRAINING_TYPES_CLI,uS as TRAINING_TYPE_MAP,rt as UsageError,on as activateConfigProfile,OD as agentLoop,m_ as agentStudioFilesPath,Mg as agentStudioHost,dT as analyzeEngineIntent,En as anonymousConsoleCall,mg as appCompletionPath,wO as atomicSwap,rr as audioFileToDataUri,Fh as bailianMcpPath,Ih as bailianMcpSsePath,hx as batchChunks,Ix as batchDataNotes,Fx as batchExamples,fx as batchIoError,gx as batchLines,px as batchObject,Q as batchUsage,kk as binaryAssetFileName,jk as binaryInnerFileName,Ak as binaryTarFileName,Hn as buildAcsCanonicalQuery,q_ as buildAsrContextMessages,Y_ as buildAsrFlashRequest,J_ as buildAsyncAsrLanguageFields,iy as buildCommandInvocation,xy as buildConsoleDatasetGroupsRequest,Dy as buildConsoleDatasetVersionRequest,Cy as buildConsoleDatasetVersionsRequest,AC as buildConsoleDeploymentInstancesRequest,wD as buildEngineInput,yv as buildImageEditArgs,vv as buildImageGenArgs,xv as buildImageToVideoArgs,un as buildOutputSettings,gC as buildPrepaidInfo,pC as buildReservationCapacity,dn as buildSettings,WO as buildSkillLockEntry,ln as buildSources,wv as buildSpeechToTextArgs,bv as buildTextToVideoArgs,Cv as buildTtsArgs,Sv as buildVideoFetchArgs,WC as buildVocabularyRequest,On as callConsoleGateway,Cx as cancelBatch,cS as cancelCompressJob,Yx as cancelFineTune,Ek as channelManifestUrl,Zh as chatPath,Z_ as collectAsrTranscriptionItems,oy as commandRef,vO as computeDirContentHash,Lk as computeSkillStatuses,zh as connectBailianMcpWithFallback,ky as consoleDatasetStatusAvailability,fv as createBailianControlUser,xx as createBatch,ZS as createCapacityInstance,iS as createCompressJob,FC as createCustomModelImport,GS as createDeployment,Kx as createFineTune,cv as createInstrumentedFetch,AD as createLLMClient,GD as createNonInteractive,WD as createReadlineInteraction,CD as createSession,Aw as createTrackingEvent,KC as createVocabulary,ow as credentialFlagDefs,ig as decisionPath,cC as defaultDeployPlan,sw as defineCommand,eC as deleteCapacityInstance,lS as deleteCompressJob,sn as deleteConfigProfile,RC as deleteCustomModelImport,my as deleteDataset,nC as deleteDeployment,Xx as deleteFineTune,XC as deleteVocabulary,a_ as deploymentCapacityInstancePath,s_ as deploymentCapacityInstanceRenewPath,o_ as deploymentCapacityInstanceScalePath,i_ as deploymentCapacityInstancesPath,l_ as deploymentCapacityOperationPath,c_ as deploymentOverflowPath,Pt as describeAuthState,Ok as detectBinaryPlatform,_k as detectInstallMethod,aO as detectInstalledAgents,Jb as detectModality,Ht as detectOutputFormat,ED as dispatchTool,PO as downloadSkillAsset,Tn as effectiveConsoleGatewayConfig,JD as emptySkillLock,Rt as ensureConfigDir,US as estimateCptTokens,HS as estimateSftDpoTokens,Px as exportBatchCsv,tS as exportCheckpoint,X_ as extractAsrFlashText,_O as extractTarBr,Pk as extractZipEntryToFile,pO as fanOutSkillToAgents,_S as fetchModelCapability,Qv as fetchModelDetail,Yv as fetchModelGroups,Zv as fetchModelGroupsAll,Kv as fetchModelList,qv as fetchModelListAll,ty as fetchPredictConfig,jO as fetchSkillsIndex,VS as fetchTrainingModelPrice,OC as findDeploymentEntry,Jv as findModelByName,VC as findSupportImportModel,Xv as flattenModelGroups,Uw as flushTelemetry,Gx as followParsexResult,ay as formatCommand,tT as formatDegradation,Vt as formatErrorJson,ax as formatIssue,Bt as formatJson,Ut as formatOutput,zt as formatText,Gh as generateCLIAccessToken,uw as generateFilename,eO as getAgentTargets,mn as getApiKeyLoginKind,Sx as getBatch,Tx as getBatchFileContent,YS as getCapacityInstance,XS as getCapacityOperation,Tk as getCliCdnBase,oS as getCompressJob,sS as getCompressJobLogs,Ft as getConfigDir,It as getConfigPath,Ey as getConsoleDatasetById,uy as getConsoleFileUrl,Lt as getCredentialsPath,LC as getCustomModelImport,py as getDataset,qS as getDeployment,Jx as getFineTune,CS as getFineTuneHyperParameterDefaultNumber,Zx as getFineTuneLogs,Qx as getFineTuneParams,dw as getHermesHome,vk as getInstallMethod,pn as getModelProfilePreset,Wx as getParsexResult,IS as getProfile,qD as getSkillLockPath,AO as getSkillRegistryBaseUrl,KD as getSkillsDir,yk as getUpdateInstallMethod,mC as hasPrepaidFlags,Sn as httpTransport,cg as image2ImagePath,ug as image2videoPath,nr as imageFileToDataUri,ag as imagePath,og as imageSyncPath,sg as imageText2ImagePath,K_ as inferAudioFormatHint,cb as inspectDecisionQuestion,ub as inspectDecisionQuestionId,lb as inspectDecisionQuestionTable,db as inspectDecisionQuestions,ib as inspectDecisionState,HO as installSkill,VO as installSkillFromBuffer,GO as installSkillWithFanout,vt as isApiKeyCapability,mk as isCompiledBinary,ev as isDashScopeGateway,tb as isDecisionObject,rO as isHostSystemDetectDir,M_ as isLegacyImage2ImageModel,j_ as isLegacyText2ImageModel,or as isLocalFile,Ov as isMcpTtsVoice,Tt as isModelConnectionSourceMismatch,gO as isSafeEntryName,IO as isSafeSkillName,Lh as isStreamableHttpUnsupported,D_ as isSyncMultimodalImageModel,pS as isTrainingTypeCli,Rh as isUrlOverrideSseFallbackCandidate,N_ as isWanxFunctionImageEditModel,jg as knowledgeChatEndpoint,Ag as knowledgeSearchEndpoint,fO as linkSkillToAgents,pv as listBailianControlWorkspaces,$x as listBasicMetrics,wx as listBatches,JS as listCapacityInstances,eS as listCheckpoints,aS as listCompressJobs,rS as listCompressTemplates,Sy as listConsoleDatasetGroups,Ty as listConsoleDatasetVersions,PC as listConsoleDeploymentInstances,IC as listCustomModelImports,fy as listDatasets,rC as listDeployableModels,KS as listDeployments,qx as listFineTunes,DC as listIndependentDeployedModels,Ik as listSkillDirsOnDisk,BC as listSupportImportModels,ix as listSupportedFormats,gS as listSupportedTrainingTypes,LS as listTrainingTypes,qC as listVocabularies,VD as loadCatalog,HD as loadFamilies,Ww as localSink,_n as makeAuthStore,ny as makeConfigStore,ot as mapApiError,hw as maskToken,tk as maybeSyncWikiData,Ig as mcpWebSearchPath,gg as memoryAddAsyncPath,hg as memoryEndpoint,_g as memoryEventPath,yg as memoryListPath,bg as memoryNodePath,vg as memorySearchPath,xg as memorySkillExportPath,hS as modelSupportsTrainingType,fg as modelsLimitsPath,pg as modelsPermissionsPath,yt as normalizeApiKeyCapabilities,Yt as normalizeConfigName,st as normalizeModelBaseUrl,Pv as parseAigcAsrTexts,Av as parseAigcImageResults,_v as parseAigcToolResult,jv as parseAigcTtsResult,Mv as parseAigcVideoTaskId,Nv as parseAigcVideoTaskResult,mx as parseBatchEndpoint,yw as parseBooleanValue,xt as parseConfigFile,Fy as parseDatasetSchemaFlag,QC as parseInstantVocabulary,bw as parseOptionalBooleanValue,Lv as parseSSE,iv as parseSecurityBody,Fk as parseSkillNames,$C as parseVocabularyEntries,Yh as parsexBaseUrl,Xh as parsexEndpoint,xC as pickPlanStrategy,tx as pickValidator,mO as planUnlinkSkillFromAgents,yS as preflightBatchSizeGate,Ox as prepareBatch,Eg as profileSchemaItemPath,Tg as profileSchemaPath,Nx as projectBatchCsv,Oy as queryConsoleDatasetVersion,JC as queryVocabulary,p_ as ragEndpoint,bx as readBatchBlob,kw as readCaller,$t as readConfigFile,nn as readConfigProfiles,YD as readSkillLock,_w as readTextFromPathOrStdin,uD as recommendEngine,ir as redactDataUri,Kh as refreshAccessToken,nx as registerValidator,Dk as releaseAssetUrl,Gw as remoteSink,UO as removeSkillDir,sy as renderCommandText,$S as renewCapacityInstance,Ln as request,Vn as requestJson,HC as requiredTrainTypeForWeightType,mv as resetBailianControlPolicies4Agent,UD as resetCatalogCache,Ot as resolveApiKey,St as resolveApiKeySource,G_ as resolveAsrApi,NO as resolveAssetFileName,Ex as resolveBatchChatEndpoint,xw as resolveBooleanFlag,Uh as resolveCLIAccessTokenTarget,kt as resolveConsole,sr as resolveFileUrl,R_ as resolveImageEditApi,L_ as resolveImageGenerateApi,P_ as resolveImageSizeProfile,Ev as resolveMcpImageSize,Dt as resolveModelBaseUrl,Ct as resolveModelBaseUrlSource,Et as resolveModelBaseUrlState,wt as resolveModelConnectionProvenance,At as resolveOpenApi,mw as resolveOutputDir,F_ as resolvePromptExtendDefault,Sw as resolveWatermark,rg as responsesPath,HT as routeEngine,vw as runWithConcurrency,g_ as sandboxApiPath,h_ as sandboxBaseUrl,__ as sandboxEndpoint,b_ as sandboxInstanceActionPath,y_ as sandboxInstancePath,S_ as sandboxTemplateBuildStatusPath,x_ as sandboxTemplatePath,nt as sanitizeDiagnosticDetails,FO as sanitizeSkillName,QS as scaleCapacityInstance,iC as scaleDeployment,Fg as securityAgentLogsEndpoint,av as securityGet,Pg as securityOverviewEndpoint,cn as selectApiKeyResolutionSources,Un as signAcsRequest,Nn as sourceConfig,Cg as speechRecognizePath,Sg as speechSynthesizePath,wg as speechVocabularyPath,TC as startModelService,EC as stopModelService,Hx as stripDecisionTrainingFields,gw as stripUndefined,Ux as submitParsexTask,dg as taskPath,Yw as trackCommandExecution,Pn as trackingHeaders,mS as trainingTypeMethodVariant,hO as unlinkSkillFromAgents,Hv as unwrapConsoleResponse,Vx as unwrapDecisionQuestions,Gv as unwrapResponse,aC as updateDeployment,tC as updateDeploymentOverflow,YC as updateVocabulary,dy as uploadDataset,ar as uploadFile,ZD as upsertSkillLockEntry,Dg as userProfilePath,Og as userProfileValuesPath,yx as validateBatch,an as validateConfigProfileActivation,Wh as validateConsoleAccessToken,rx as validateDataset,SS as validateFineTuneHyperParameterOverrides,hC as validatePrepaidFlags,fC as validateReservationCapacity,zO as validateSkillDir,Gt as validateTimeout,lg as videoGeneratePath,kg as workspaceMaaSBaseUrl,Dx as writeBatchFile,en as writeConfigFile,bk as writeInstallMethodSync,XD as writeSkillLock};