bailian-cli-core 2.6.1 → 2.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1363,6 +1363,8 @@ interface Settings {
|
|
|
1363
1363
|
* (e.g. `advisor recommend` defaults to json) branch on this.
|
|
1364
1364
|
*/
|
|
1365
1365
|
outputExplicit: boolean;
|
|
1366
|
+
/** 输出来源;命令默认格式可覆盖 Profile 默认值,保留 flag/env 的显式选择。 */
|
|
1367
|
+
outputSource?: "flag" | "env" | "file" | "default";
|
|
1366
1368
|
outputDir?: string;
|
|
1367
1369
|
timeout: number;
|
|
1368
1370
|
watermark: boolean;
|
|
@@ -1690,6 +1692,8 @@ export declare class Client {
|
|
|
1690
1692
|
client: McpConnectedClient;
|
|
1691
1693
|
url: string;
|
|
1692
1694
|
}>;
|
|
1695
|
+
/** 创建仅本次调用链使用的 Console 身份;不修改原 Client、Settings 或持久化配置。 */
|
|
1696
|
+
withConsoleSwitchAgent(switchAgent: number): Client;
|
|
1693
1697
|
console<T>(api: string, data: Record<string, unknown>): Promise<T>;
|
|
1694
1698
|
openApiQueryJson<T extends OpenApiResponse>(opts: ClientOpenApiQueryOpts): Promise<T>;
|
|
1695
1699
|
openApiJson<T extends OpenApiResponse>(opts: ClientOpenApiJsonOpts): Promise<T>;
|
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 ee,setGlobalDispatcher as te}from"undici";import{createHash as ne,createHmac as re,randomBytes as ie,randomUUID as ae}from"crypto";import{Readable as oe}from"stream";import{createInterface as x}from"readline";import{pipeline as se}from"stream/promises";import*as ce from"yauzl";import{copyFileSync as le,cpSync as ue,createReadStream as de,createWriteStream as fe,existsSync as S,lstatSync as C,mkdirSync as w,readFileSync as T,readdirSync as E,readlinkSync as pe,realpathSync as me,renameSync as D,rmSync as O,statSync as he,symlinkSync as ge,writeFileSync as _e}from"node:fs";import{isIP as ve}from"node:net";import{Readable as ye}from"node:stream";import{basename as be,dirname as k,isAbsolute as xe,join as A,relative as Se,resolve as j,sep as Ce}from"node:path";import{parse as we}from"csv-parse";import{stringify as Te}from"csv-stringify/sync";import{link as Ee,mkdir as De,open as Oe,readFile as ke,rename as Ae,unlink as je}from"node:fs/promises";import{createHash as Me,randomUUID as Ne}from"node:crypto";import{createInterface as Pe}from"node:readline/promises";import{homedir as Fe}from"node:os";import{pipeline as Ie}from"node:stream/promises";import{createBrotliDecompress as Le}from"node:zlib";import Re from"tar-stream";var ze=Object.create,Be=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,He=Object.getOwnPropertyNames,Ue=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty,Ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=He(t),a=0,o=i.length,s;a<o;a++)s=i[a],!We.call(e,s)&&s!==n&&Be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ve(t,s))||r.enumerable});return e},qe=(e,t,n)=>(n=e==null?{}:ze(Ue(e)),Ke(t||!e||!e.__esModule||!We.call(e,`default`)?Be(n,`default`,{value:e,enumerable:!0}):n,e)),Je=/* @__PURE__ */ e(import.meta.url);const M={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10,INTERRUPTED:130};var N=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=M.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api,this.rawResponse=r?.rawResponse}toJSON(){let e=Ye(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},P=class extends N{constructor(e,t){super(e,M.USAGE,t),this.name=`UsageError`}};function Ye(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function Xe(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.error?.code??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new N(r,M.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function Ze(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw Qe(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Qe(e);return n.origin}function Qe(e){return new N(`Invalid model base URL "${e}".`,M.USAGE,`Use an absolute http(s) URL.`)}const F={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},$e={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},et=`https://bailian.cn-beijing.aliyuncs.com`,tt=[`en-US`,`zh-CN`],nt=`en-US`,rt=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],it=/* @__PURE__ */ new Set([`text`,`json`]),at=/* @__PURE__ */ new Set([`domestic`,`international`]),ot=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function st(e){return ot.test(e)}function ct(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!st(e))return[];t.includes(e)||t.push(e)}return t}function lt(e){try{return Ze(e)}catch{return}}function ut(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&tt.includes(t.language)&&(n.language=t.language),typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=lt(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&it.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.watermark==`boolean`&&(n.watermark=t.watermark),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=ct(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&at.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function dt(e,t=F.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:Ze(n||t),baseUrlIsDefault:!n}}function ft(e,t=F.cn){return dt(e,t).baseUrl}function pt(e){let t=ft(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new N(`No API key found.`,M.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function mt(e){let t=e.file.access_token?.trim();if(!t)throw new N(`No console access token found.`,M.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function ht(e){let t=gt(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=gt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(_t(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||_t(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=gt(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;throw new N(`No OpenAPI AK/SK credentials found.`,M.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function gt(e,t,n,r,i){if(!r)return;let a=_t(t),o=_t(n);if(!a||!o)throw new N(`Incomplete OpenAPI AK/SK credentials found.`,M.AUTH,vt(e));return{accessKeyId:a,accessKeySecret:o,securityToken:_t(i),source:e}}function _t(e){return e?.trim()||void 0}function vt(e){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars to use config credentials.`:"Run `bl auth login --open-api --access-key-id <id> --access-key-secret <secret>` again to save a complete pair."}function yt(e){let t={};try{t.apiKey=pt(e)}catch{}try{t.console=mt(e)}catch{}try{t.openapi=ht(e)}catch{}return t}function I(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function bt(){return g(I(),`config.json`)}function xt(){return g(I(),`credentials.json`)}async function St(){let e=I(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Ct(e){return v(e).replace(/\n$/,``)}function wt(e){return JSON.stringify(e,null,2)}function Tt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Et(e){return e===`json`||e===`text`?e:`text`}function Dt(e,t){switch(t){case`json`:return wt(e);case`text`:return Ct(e)}}const Ot={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function kt(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return Ot}const At=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,jt=`active_config`;function Mt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Nt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!At.test(e))throw new N(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,M.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(rt.includes(e)||e===jt)throw new N(`Invalid config name "${e}". It conflicts with a config key.`,M.USAGE);return e}}function Pt(){let e=bt();if(!i(e))return{};try{let t=JSON.parse(o(e,`utf-8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}function Ft(e,t){let n=Nt(e[jt]);if(n&&t&&!Mt(e[n]))throw new N(`Active config "${n}" does not exist.`,M.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function It(e,t){if(!t)return e;let n=e[t];return Mt(n)?n:{}}function L(e){return ut(It(Pt(),e))}async function Lt(e,t,n={}){let r=Pt();if(t)r[t]=e;else{for(let e of Object.keys(r))rt.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[jt]=t??`default`),await Rt(r)}async function Rt(e){await St();let t=bt(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
|
|
2
|
-
`,{mode:384}),s(n,t)}function zt(){let e=Pt(),t={};for(let[n,r]of Object.entries(e))rt.includes(n)||n===jt||Mt(r)&&(t[n]=ut(r));return{default:ut(e),named:t,active:Ft(e,!0)??`default`}}function Bt(e,t){let n=Nt(t);if(n&&!Mt(e[n]))throw new N(`Config "${n}" does not exist.`,M.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function Vt(e){return Bt(Pt(),e)}async function Ht(e){let t=Pt(),n=Bt(t,e);return t[jt]=n,await Rt(t),n}async function Ut(e){let t=Nt(e);if(!t)throw new N(`Cannot delete the default profile.`,M.USAGE);let n=Pt();return Mt(n[t])?(delete n[t],Ft(n,!1)===t&&(n[jt]=`default`),await Rt(n),!0):!1}function Wt(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:L(),configName:void 0},fallbackFrom:e.configName}}function Gt(e){let t=Pt(),n=e.config!==void 0,r=Ft(t,!n),i=n?Nt(e.config):r;return{flags:e,file:ut(It(t,i)),env:process.env,configName:i,configPath:bt()}}function Kt(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=kt(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=kt(o);if(s)throw new N(s[`en-US`],M.USAGE);return{configPath:e.configPath??bt(),configName:e.configName,output:Et(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const qt={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function Jt(e){return e?qt[e]:void 0}function Yt(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function Xt(e,t,n){if(n)return t;let r=Yt(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const Zt={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function Qt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>yt({...e,file:L(t)}),stored(){let e=L(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>ft(e,t),async login(e){let r=e.api_key?Xt(e.api_key,t,n):t,i=n||r!==t,a=L(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?Ze(String(n)):n}await Lt(a,r,{activate:i})},async logout(e){let n=L(t),r=Zt[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await Lt(n,t),!0},get path(){return e.configPath??bt()}}}const $t=process.versions.bun?void 0:ee();globalThis.Request,$t&&ee()!==$t&&te($t);const R={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},en={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function tn(e,t){return en[e]?.[t]??en[`cn-beijing`][t]}function nn(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function rn(e){let t=nn(e);return(n,r)=>on({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function an(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function on(e,t,{api:n,data:r},i){let a=tn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=an(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await R.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,M.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new N(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?M.AUTH:M.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}function sn(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const cn=`bailian-cli`,ln=`BailianCLI`,un=`X-Dashscope-Service`;function dn(e){return JSON.stringify({channel:cn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function z(e){return{"x-dashscope-source-config":dn(e),"x-dashscope-openapisource":ln,[un]:cn}}const fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function pn(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function mn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return _n(await hn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function hn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...z(e.identity),...t.headers};if(!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),pn(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=i.Authorization;n&&console.error(`> Auth: ${sn(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${dn(e.identity)}`)}let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(ee(),fn)}},o=await R.fetch(t.url,a);if(e.settings.verbose){console.error(`< ${o.status} ${o.statusText}`);let e=o.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!o.ok){let e=await o.text(),n;try{let t=JSON.parse(e);n=typeof t==`object`&&t?t:{message:e}}catch{n={message:e}}n.request_id??=o.headers.get(`x-request-id`)??void 0;let r=Xe(o.status,n,t.url);throw new N(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function gn(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new N(`Response body idle timeout: no data received for ${e/1e3}s.`,M.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function _n(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function vn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await hn(e,t,n.signal),i;try{i=await r.json()}catch(e){if(n.signal.aborted)throw n.signal.reason;if(!(e instanceof SyntaxError))throw e;let t=r.headers.get(`content-type`)||``;throw new N(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,M.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=Xe(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new N(e.message,e.exitCode,e.hint,{api:e.api,rawResponse:JSON.stringify(i)})}return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function yn(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0&&r!==``){if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r])}return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${xn(e)}=${xn(String(t))}`).join(`&`)}function bn(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ae(),i=Sn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
|
|
2
|
+
`,{mode:384}),s(n,t)}function zt(){let e=Pt(),t={};for(let[n,r]of Object.entries(e))rt.includes(n)||n===jt||Mt(r)&&(t[n]=ut(r));return{default:ut(e),named:t,active:Ft(e,!0)??`default`}}function Bt(e,t){let n=Nt(t);if(n&&!Mt(e[n]))throw new N(`Config "${n}" does not exist.`,M.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function Vt(e){return Bt(Pt(),e)}async function Ht(e){let t=Pt(),n=Bt(t,e);return t[jt]=n,await Rt(t),n}async function Ut(e){let t=Nt(e);if(!t)throw new N(`Cannot delete the default profile.`,M.USAGE);let n=Pt();return Mt(n[t])?(delete n[t],Ft(n,!1)===t&&(n[jt]=`default`),await Rt(n),!0):!1}function Wt(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:L(),configName:void 0},fallbackFrom:e.configName}}function Gt(e){let t=Pt(),n=e.config!==void 0,r=Ft(t,!n),i=n?Nt(e.config):r;return{flags:e,file:ut(It(t,i)),env:process.env,configName:i,configPath:bt()}}function Kt(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=kt(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=kt(o);if(s)throw new N(s[`en-US`],M.USAGE);return{configPath:e.configPath??bt(),configName:e.configName,output:Et(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputSource:t.output?`flag`:r.DASHSCOPE_OUTPUT?`env`:n.output?`file`:`default`,outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const qt={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function Jt(e){return e?qt[e]:void 0}function Yt(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function Xt(e,t,n){if(n)return t;let r=Yt(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const Zt={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function Qt(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>yt({...e,file:L(t)}),stored(){let e=L(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>ft(e,t),async login(e){let r=e.api_key?Xt(e.api_key,t,n):t,i=n||r!==t,a=L(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?Ze(String(n)):n}await Lt(a,r,{activate:i})},async logout(e){let n=L(t),r=Zt[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await Lt(n,t),!0},get path(){return e.configPath??bt()}}}const $t=process.versions.bun?void 0:ee();globalThis.Request,$t&&ee()!==$t&&te($t);const R={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},en={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function tn(e,t){return en[e]?.[t]??en[`cn-beijing`][t]}function nn(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function rn(e){let t=nn(e);return(n,r)=>on({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function an(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function on(e,t,{api:n,data:r},i){let a=tn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=an(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await R.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new N(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,M.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new N(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?M.AUTH:M.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}function sn(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const cn=`bailian-cli`,ln=`BailianCLI`,un=`X-Dashscope-Service`;function dn(e){return JSON.stringify({channel:cn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function z(e){return{"x-dashscope-source-config":dn(e),"x-dashscope-openapisource":ln,[un]:cn}}const fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function pn(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function mn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return _n(await hn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function hn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...z(e.identity),...t.headers};if(!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),pn(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=i.Authorization;n&&console.error(`> Auth: ${sn(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${dn(e.identity)}`)}let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(ee(),fn)}},o=await R.fetch(t.url,a);if(e.settings.verbose){console.error(`< ${o.status} ${o.statusText}`);let e=o.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!o.ok){let e=await o.text(),n;try{let t=JSON.parse(e);n=typeof t==`object`&&t?t:{message:e}}catch{n={message:e}}n.request_id??=o.headers.get(`x-request-id`)??void 0;let r=Xe(o.status,n,t.url);throw new N(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function gn(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new N(`Response body idle timeout: no data received for ${e/1e3}s.`,M.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function _n(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function vn(e,t){let n=gn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await hn(e,t,n.signal),i;try{i=await r.json()}catch(e){if(n.signal.aborted)throw n.signal.reason;if(!(e instanceof SyntaxError))throw e;let t=r.headers.get(`content-type`)||``;throw new N(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,M.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=Xe(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new N(e.message,e.exitCode,e.hint,{api:e.api,rawResponse:JSON.stringify(i)})}return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function yn(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0&&r!==``){if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r])}return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${xn(e)}=${xn(String(t))}`).join(`&`)}function bn(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ae(),i=Sn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
|
|
5
5
|
`),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Sn(u)}`,p=Cn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function xn(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Sn(e){return ne(`sha256`).update(e,`utf8`).digest(`hex`)}function Cn(e,t){return re(`sha256`,e).update(t,`utf8`).digest(`hex`)}const wn=[`cn-beijing`,`ap-southeast-1`];function Tn(e){return new N(`Local-file temporary upload is supported only in ${wn.join(`, `)}; "${e}" is not supported.`,M.USAGE,`Use a reachable HTTPS media URL instead.`)}function En(e){if(Yt(e)===`token-plan`)throw Tn(`Token Plan`)}function Dn(e,t){let n=Ze(e),r=new URL(n).hostname.toLowerCase();if(/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/.test(r))throw Tn(`Token Plan`);if(r===new URL(F.cn).hostname||r===new URL(F.intl).hostname)return En(t),n;if(r===new URL(F.us).hostname)throw Tn(r);let i=/^[^.]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/.exec(r)?.[1];if(i===`cn-beijing`||i===`ap-southeast-1`)return En(t),n;if(i)throw Tn(i);return n}async function On(e,t,n,r,i){let a=`${Dn(r,e)}/api/v1/uploads`,o=`${a}?action=getPolicy&model=${encodeURIComponent(t)}`,s=In(15e3,i),c=await R.fetch(o,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...z(n)},signal:s.signal}).finally(s.cleanup);if(!c.ok){let e=await c.text().catch(()=>``),t;try{t=JSON.parse(e)}catch{}let n=typeof t?.message==`string`&&t.message?t.message:e||`${c.status} ${c.statusText}`,r=typeof t?.code==`string`?t.code:void 0,i=typeof t?.request_id==`string`?t.request_id:void 0;throw new N(`${[`HTTP ${c.status}`,r?`code=${r}`:void 0,i?`request_id=${i}`:void 0,`upload_endpoint=${a}`].filter(e=>e!==void 0).join(`; `)} - ${n}`,M.GENERAL,void 0,{api:{httpStatus:c.status,apiCode:r,requestId:i},rawResponse:e.slice(0,500)})}return(await c.json()).data}async function kn(e,t,n,r=120){let i=m(t),a=`${e.upload_dir}/${i}`,s=o(t),c=new FormData;c.append(`OSSAccessKeyId`,e.oss_access_key_id),c.append(`Signature`,e.signature),c.append(`policy`,e.policy),c.append(`x-oss-object-acl`,e.x_oss_object_acl),c.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),c.append(`key`,a),c.append(`success_action_status`,`200`),c.append(`file`,new Blob([s]),i);let l=In(r*1e3,n),u=await R.fetch(e.upload_host,{method:`POST`,body:c,signal:l.signal}).finally(l.cleanup);if(!u.ok){let e=await u.text().catch(()=>``);throw new N(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,M.GENERAL)}return`oss://${a}`}const An={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function jn(e){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);if(!l(e).isFile())throw new N(`Not a file: ${e}`,M.USAGE);let t=h(e).toLowerCase(),n=An[t];if(!n)throw new N(`Unsupported image format "${t||`unknown`}".`,M.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function Mn(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function Nn(e){let{apiKey:t,baseUrl:n=F.cn,model:r,filePath:a,identity:o,signal:s,timeout:c}=e;if(!i(a))throw new N(`File not found: ${a}`,M.USAGE);if(!l(a).isFile())throw new N(`Not a file: ${a}`,M.USAGE);return kn(await On(t,r,o,n,s),a,s,c)}function Pn(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function Fn(e,t,n,r){return Pn(e)?Nn({apiKey:t,baseUrl:r.baseUrl,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function In(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}function Ln(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
|
|
@@ -8,7 +8,7 @@ import{createRequire as e}from"node:module";import{appendFileSync as t,createRea
|
|
|
8
8
|
`),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Rn(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new N(`SSE event exceeded the maximum buffer size.`,M.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a}return{event:o}}async function*zn(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16777216;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
|
|
9
9
|
`).replace(/\r/g,`
|
|
10
10
|
`).split(`
|
|
11
|
-
`);r=t.pop()??``;for(let n of t){let t=Rn(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let{lines:s,rest:c}=Ln(r);r=c;for(let t of s){let n=Rn(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Rn(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function Bn(e){return String(e)}var Vn=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=/* @__PURE__ */ new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);await this.openSse();let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP SSE] Session initialized`),console.error(`[MCP SSE] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new N(`MCP SSE session closed.`,M.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await R.fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out waiting for response headers.`,M.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new N(e,M.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof N?e:new N(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,M.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Un(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of zn(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Hn(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Bn(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new N(`MCP SSE stream ended before endpoint event.`,M.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let n=this.nextId++,r=Bn(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=Un(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new N(`MCP error (${e.error.code}): ${e.error.message}`,M.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);if(!this.messageUrl)throw new N(`MCP SSE message endpoint is not ready.`,M.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=Wn(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await R.fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):n.timedOut?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:t})}throw new N(e,M.GENERAL)}}finally{n.cleanup()}}};function Hn(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new N(`MCP SSE endpoint is not a valid URL: ${t}`,M.GENERAL)}if(n.origin!==r.origin)throw new N(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,M.GENERAL);return n.toString()}function Un(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new N(t,M.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Wn(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function Gn(e){return`/api/v1/mcps/${e}/mcp`}function Kn(e){return`/api/v1/mcps/${e}/sse`}function qn(e){return e instanceof N&&/^MCP request failed:\s*405\b/i.test(e.message)}function Jn(e){return e instanceof N&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function Yn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new Xn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Jn(e))throw e}let r=new Vn(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new Xn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!qn(e)||a===`WebSearch`)throw e}let c=new Vn(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var Xn=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new N(`MCP error (${a.error.code}): ${a.error.message}`,M.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of zn(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new N(`MCP SSE response stream ended without a matching JSON-RPC response.`,M.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await R.fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}},Zn=class{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...z(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return mn(this.http,this.toOpts(e))}requestJson(e){return vn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Pn(e)?Fn(e,this.requireApi().token,t,{signal:n.signal,baseUrl:this.url(``,n.defaultBaseUrl),identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Pn(e)?this.usesTokenPlanEndpoint()?Promise.resolve(jn(e)):this.uploadFile(e,t,n):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Xn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),Yn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Gn(e)),sseUrl:this.url(Kn(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await on(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof N)||e.exitCode!==M.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await nr({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await on({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?yn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=bn({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${sn(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${sn(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await R.fetch(i,{method:e.method,headers:{...a,...z(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new N(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,M.GENERAL)}if(!s.ok||l.Success===!1)throw new N(`${l.Code||s.status} - ${l.Message||s.statusText}`,M.GENERAL);return l}};const Qn=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function $n(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Qn.has(n))throw new N(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,M.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function er(e,t){let n=await on(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new N(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,M.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function tr(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Zn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=$n(n,r),l=Qn.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new N(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,M.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function nr(e){let t=e.settings.configName,n=L(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
|
|
11
|
+
`);r=t.pop()??``;for(let n of t){let t=Rn(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new N(`SSE stream exceeded the maximum buffer size.`,M.GENERAL);let{lines:s,rest:c}=Ln(r);r=c;for(let t of s){let n=Rn(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Rn(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function Bn(e){return String(e)}var Vn=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=/* @__PURE__ */ new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);await this.openSse();let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP SSE] Session initialized`),console.error(`[MCP SSE] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new N(`MCP SSE session closed.`,M.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await R.fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out waiting for response headers.`,M.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new N(`MCP SSE session closed.`,M.GENERAL):t?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new N(e,M.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof N?e:new N(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,M.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Un(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of zn(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=Hn(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Bn(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new N(`MCP SSE stream ended before endpoint event.`,M.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let n=this.nextId++,r=Bn(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=Un(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new N(`MCP error (${e.error.code}): ${e.error.message}`,M.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new N(`MCP SSE stream ended unexpectedly.`,M.GENERAL);if(!this.messageUrl)throw new N(`MCP SSE message endpoint is not ready.`,M.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=Wn(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await R.fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new N(`MCP SSE session closed.`,M.GENERAL):n.timedOut?new N(`MCP SSE timed out reading error response body.`,M.TIMEOUT):new N(e,M.GENERAL,void 0,{cause:t})}throw new N(e,M.GENERAL)}}finally{n.cleanup()}}};function Hn(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new N(`MCP SSE endpoint is not a valid URL: ${t}`,M.GENERAL)}if(n.origin!==r.origin)throw new N(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,M.GENERAL);return n.toString()}function Un(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new N(t,M.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function Wn(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function Gn(e){return`/api/v1/mcps/${e}/mcp`}function Kn(e){return`/api/v1/mcps/${e}/sse`}function qn(e){return e instanceof N&&/^MCP request failed:\s*405\b/i.test(e.message)}function Jn(e){return e instanceof N&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function Yn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new Xn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Jn(e))throw e}let r=new Vn(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new Xn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!qn(e)||a===`WebSearch`)throw e}let c=new Vn(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var Xn=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new N(`This command needs a model-domain API key.`,M.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new N(`MCP error (${a.error.code}): ${a.error.message}`,M.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of zn(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new N(`MCP SSE response stream ended without a matching JSON-RPC response.`,M.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await R.fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new N(e,M.GENERAL)}return r}},Zn=class e{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new N(`This command needs a model-domain API key.`,M.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new N(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,M.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...z(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return mn(this.http,this.toOpts(e))}requestJson(e){return vn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return Pn(e)?Fn(e,this.requireApi().token,t,{signal:n.signal,baseUrl:this.url(``,n.defaultBaseUrl),identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return Pn(e)?this.usesTokenPlanEndpoint()?Promise.resolve(jn(e)):this.uploadFile(e,t,n):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Xn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),Yn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Gn(e)),sseUrl:this.url(Kn(e)),serverCode:e,urlOverride:t})}withConsoleSwitchAgent(t){return new e({...this.deps,settings:{...this.deps.settings,consoleSwitchAgent:t},consoleCred:this.deps.consoleCred?{...this.deps.consoleCred,switchAgent:t}:void 0})}async console(e,t){if(!this.deps.consoleCred)throw new N(`This command needs a console access token.`,M.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await on(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof N)||e.exitCode!==M.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await nr({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await on({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?yn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=bn({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${sn(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${sn(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await R.fetch(i,{method:e.method,headers:{...a,...z(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new N(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,M.GENERAL)}if(!s.ok||l.Success===!1)throw new N(`${l.Code||s.status} - ${l.Message||s.statusText}`,M.GENERAL);return l}};const Qn=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function $n(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Qn.has(n))throw new N(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,M.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function er(e,t){let n=await on(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new N(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,M.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function tr(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Zn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=$n(n,r),l=Qn.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new N(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,M.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function nr(e){let t=e.settings.configName,n=L(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
|
|
12
12
|
`);let a=(await tr({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await er({...$n(e.settings,e.baseUrl),token:a},e.settings);let o=L(t);return o.access_token=a,await Lt(o,t),a}function rr(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new P(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function ir(){return`/compatible-mode/v1/chat/completions`}function ar(){return`/compatible-mode/v1/batches`}function or(e){return`${ar()}/${encodeURIComponent(e)}`}function sr(e){return`${or(e)}/cancel`}function cr(e){return`/compatible-mode/v1/files/${encodeURIComponent(e)}/content`}function lr(){return`https://batch.dashscope.aliyuncs.com`}function ur(){return`/compatible-mode/v1/responses`}function dr(){return`/compatible-mode/v1/systemone`}function fr(){return`/api/v1/services/aigc/image-generation/generation`}function pr(){return`/api/v1/services/aigc/multimodal-generation/generation`}function mr(){return`/api/v1/services/aigc/text2image/image-synthesis`}function hr(){return`/api/v1/services/aigc/image2image/image-synthesis`}function gr(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function _r(){return`/api/v1/services/aigc/image2video/video-synthesis`}function vr(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function yr(){return`/api/v1/models/limits`}function br(){return`/api/v1/models/permissions`}function xr(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Sr(e,t){return rr(e,t)}function Cr(){return`/api/v2/apps/memory/add-async`}function wr(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function Tr(){return`/api/v2/apps/memory/memory_nodes/search`}function Er(){return`/api/v2/apps/memory/memory_nodes`}function Dr(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Or(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function kr(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Ar(){return`/api/v1/services/audio/asr/transcription`}function jr(){return`/api/v1/services/audio/asr/customization`}function Mr(){return`/api/v2/apps/memory/profile_schemas`}function Nr(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function Pr(e){return`${Nr(e)}/user_profile`}function Fr(e){return`${Nr(e)}/profile_values`}function Ir(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function Lr(e){return rr(e,`/api/v1/indices/knowledge/search`)}function Rr(e){return rr(e,`/api/v2/apps/knowledge/chat`)}function zr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const Br=`/api/v1/agentstudio/security`;function Vr(e){return`${e}${Br}/overview`}function Hr(e){return`${e}${Br}/agent_logs`}function Ur(){return`/api/v1/mcps/WebSearch/mcp`}function Wr(){return`/compatible-mode/v1/files`}function Gr(){return`/api/v1/files`}function Kr(e){return`/api/v1/files/${encodeURIComponent(e)}`}function qr(){return`/api/v1/fine-tunes`}function Jr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Yr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Xr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Zr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Qr(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function $r(){return`/api/v1/fine-tunes/compress/templates`}function ei(){return`/api/v1/fine-tunes/compress/jobs`}function ti(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function ni(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function ri(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function ii(){return`/api/v1/deployments`}function ai(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function oi(e){return`${ai(e)}/capacity-instances`}function si(e,t){return`${oi(e)}/${encodeURIComponent(t)}`}function ci(e,t){return`${si(e,t)}/scale`}function li(e,t){return`${si(e,t)}/renew`}function ui(e){return`${ai(e)}/update-overflowstrategy`}function di(e,t){return`${ai(e)}/capacity-operations/${encodeURIComponent(t)}`}function fi(e){return`${ai(e)}/scale`}function pi(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function mi(){return`/api/v1/deployments/models`}function hi(e,t){return rr(e,t)}function gi(){return`/api/v1/agentstudio/files`}function _i(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function vi(e){return`/api/v1/agentstudio/sandbox${e}`}function yi(e,t){return _i(e)+vi(t)}const bi={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function xi(e){return`${bi.sandboxes}/${encodeURIComponent(e)}`}function Si(e,t){return`${xi(e)}/${t}`}function Ci(e){return`${bi.templates}/${encodeURIComponent(e)}`}function wi(e,t){return`${Ci(e)}/builds/${encodeURIComponent(t)}/status`}const Ti={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},Ei=[`qwen-image`,`wan2.7-image`,`z-image`],Di=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function Oi(e,t){return t.some(t=>e.startsWith(t))}function ki(e){return Oi(e,Ei)||e.startsWith(`wan2.6-image`)}function Ai(e){return Oi(e,Ei)}function ji(e){return Oi(e,Di)}function Mi(e){return/^wanx-v1(?:-|$)/i.test(e)}function Ni(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||Ai(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||Mi(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function Pi(e){return/wan2\.5-i2i/i.test(e)}function Fi(e){return/imageedit/i.test(e)}function Ii(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:Mi(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Ni(e)?`wan-legacy`:`wan26`}function Li(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function Ri(e,t){return{...e,sizeProfile:Ii(t),promptExtendDefault:Li(t)}}function zi(e){return Ai(e)?Ri({kind:`sync-multimodal`,path:pr(),useSync:!0,inputStyle:`messages`},e):Ni(e)?Ri({kind:`async-text2image`,path:mr(),useSync:!1,inputStyle:`prompt`},e):Ri({kind:`async-image-generation`,path:fr(),useSync:!1,inputStyle:`messages`},e)}function Bi(e){return ji(e)?Ri({kind:`sync-multimodal`,path:pr(),useSync:!0,inputStyle:`messages`},e):Fi(e)?Ri({kind:`async-image2image`,path:hr(),useSync:!1,inputStyle:`function-base-image`},e):Pi(e)?Ri({kind:`async-image2image`,path:hr(),useSync:!1,inputStyle:`prompt-images`},e):Ri({kind:`async-image-generation`,path:fr(),useSync:!1,inputStyle:`messages`},e)}function Vi(e){return/realtime|streaming/i.test(e)}function Hi(e){return/filetrans/i.test(e)}function Ui(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const Wi=[`fun-asr-flash`,`qwen-audio`];function Gi(e){return Vi(e)||Hi(e)?!1:!!(e.startsWith(Wi[0])||e.startsWith(Wi[1])&&/asr-flash/i.test(e))}function Ki(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||Hi(e)||Vi(e)||Gi(e))}function qi(e){if(Vi(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(Hi(e)){let t=Ui(e);return{kind:`async-filetrans`,path:Ar(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return Gi(e)?{kind:`sync-flash`,path:pr(),useSync:!0,flashFamily:`input-audio`}:Ki(e)?{kind:`sync-flash`,path:pr(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Ar(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function Ji(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Yi(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function Xi(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Zi(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:Ji(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Yi(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Qi(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function $i(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const ea={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},ta=new Set(Object.values(F));function na(e){return ta.has(e.replace(/\/+$/,``))}function ra(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function ia(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function aa(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new N(`Security API failed: ${r} - ${t??`no message`}${i}`,M.GENERAL,ea[r],{rawResponse:n.slice(0,500)})}function oa(e,t){let n;try{n=JSON.parse(e)}catch{throw new N(`Security API returned non-JSON response (${t??`unknown type`}).`,M.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=ra(n),i=r?ra(r.data):void 0,a=i?ra(i.DataV2):void 0;if(a){let t=ra(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=ia(i?.errorCode,r?.errorCode),c=ia(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&aa(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||aa(ia(r.errorCode),ia(r.errorMsg),e),r.data??null;if(r){let t=ia(i?.errorCode,r.errorCode),n=ia(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&aa(t,n,e)}if(r)return r;aa(void 0,void 0,e)}async function sa(e,t){let n=await e.request({path:t,method:`GET`});return oa(await n.text(),n.headers.get(`content-type`))}function ca(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function la(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function ua(e){return async(t,n={})=>{let r=la(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),ca(r))for(let[t,n]of Object.entries(z(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${sn(e.replace(/^Bearer /,``))}`)}let a=await R.fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const da=`2024-08-16`;function fa(e){return`bailiancontrol.${e}.aliyuncs.com`}function pa(e){return new Zn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function ma(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:da,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function ha(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:da,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function ga(e){return pa(e).openApiJson({host:fa(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:da,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const _a=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,va=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function B(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function ya(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=B(await e(_a,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function ba(e,t={}){let n=t.pageSize??50,r=await ya(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await ya(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function xa(e,t){return(await ya(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Sa(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=B(await e(_a,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Ca(e){return e.flatMap(e=>e.items??[])}async function wa(e,t={}){let n=t.pageSize??50,r=await Sa(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Sa(e,{...t,pageNo:r,pageSize:n})));return Ca([r.groups,...o.map(e=>e.groups)].flat())}async function Ta(e,t){return(B(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Ea=[`name`,`key`,`default`,`tip`,`range`];function Da(e){return e.map(e=>{let t={};for(let n of Ea)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Oa(e,t){let n=B(await e(va,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Da(e):null}catch{return null}return Array.isArray(n)?Da(n):null}function ka(e){return{read:()=>L(e),async write(t){let n=L(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Ze(String(r)):r;await Lt(n,e)},async unset(t){let n=L(e);for(let e of t)delete n[e];await Lt(n,e)},profiles:()=>zt(),activate:e=>Ht(e),validateActivation:e=>Vt(e),get path(){return bt()}}}async function Aa(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=t.fileBlob?.size??l(r).size,s=m(r),c=t.fileBlob??await new Response(oe.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:Wr(),method:`POST`,body:u,signal:a});if(d.id)return{file_id:d.id,name:d.filename??s,size:d.bytes??o,purpose:d.purpose??i,gmt_create:d.created_at?(/* @__PURE__ */ new Date(d.created_at*1e3)).toISOString():void 0,request_id:d.request_id};let f=d.data?.failed_uploads;if(Array.isArray(f)&&f.length>0){let e=f[0]??{};throw new N(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,M.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new N(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,M.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function ja(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Gr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ma(e,t,n){return e.requestJson({path:Kr(t),method:`GET`,signal:n})}async function Na(e,t,n){let r=await e.request({path:Kr(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Pa=209715200,Fa=314572800,Ia=314572800,La=2147483648;function Ra(e,t=Pa){if(!i(e))throw new N(`File not found: ${e}`,M.USAGE);let n=l(e);if(!n.isFile())throw new N(`Not a regular file: ${e}`,M.USAGE);if(n.size===0)throw new N(`File is empty: ${e}`,M.USAGE);if(n.size>t)throw new N(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,M.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function V(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function za(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new N(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,M.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function Ba(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=/* @__PURE__ */ new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const Va=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),Ha=.1;function Ua(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<Ha||a>10)&&i.push(V(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${Ha} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(V(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(V(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function Wa(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(V(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(V(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(V(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(V(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(V(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(V(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(V(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(V(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...Ua(s,Array.isArray(e),t,o))}}}return r}function Ga(e,t,n){let r=[];if(!Array.isArray(e))return r.push(V(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(V(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(V(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(V(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(V(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(V(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(V(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Ka(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(V(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!Va.has(a))&&r.push(V(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(V(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...Wa(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(V(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...Ga(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(V(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(V(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function qa(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(V(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(V(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Ka(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(V(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(V(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(V(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(V(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(V(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(V(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;Ja(a)&&n.push(V(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(V(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(V(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(V(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function Ja(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const Ya={name:`chatml`,detect:()=>!0,inspect:qa};function Xa(e,t){let n=[];if(!(`text`in e))return n.push(V(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(V(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(V(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Za={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Xa};function Qa(e,t){let n=qa(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(V(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(V(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(V(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(V(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Ka(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(V(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Ka(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(V(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const $a={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Qa},eo=[`choice`,`noul`,`score`],to=255,no=2,ro=255,io=/* @__PURE__ */ new Set([`true`,`false`]);function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ao(e){return typeof e==`string`&&e.trim().length>0}function U(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function oo(e,t=`state`){return ao(e)||Array.isArray(e)&&e.length>0||H(e)&&Object.keys(e).length>0?[]:[U(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function so(e,t){let n=`${t}.criteria`;if(!H(e))return[U(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[U(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!ao(t)||!ao(r))return[U(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function co(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!ao(e))?[U(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[U(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function lo(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return H(e)&&Object.entries(e).every(([e,t])=>io.has(e)&&typeof t==`string`)?[]:[U(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function uo(e,t){if(!H(e))return[U(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(U(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...so(e.criteria,t)):e.type===`noul`?n.push(...lo(e.criteria,t)):e.type===`score`?n.push(...co(e.criteria,t)):n.push(U(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function fo(e,t=`questions`){return H(e)&&Object.keys(e).length>0?[]:[U(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function po(e,t=`questions`){return ao(e)?[]:[U(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function mo(e,t=`questions`){let n=fo(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=po(n,t);if(e.length>0){r.push(...e);continue}r.push(...uo(i,`${t}.${n}`))}return r}function W(e,t,n,r){return V(`error`,e,t,{line:n,path:r})}function ho(e,t){return W(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function go(e,t,n,r){if(!H(e))return[W(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[W(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[W(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[W(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function _o(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[W(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:go(e.target,r,t,`${n}.target`)}function vo(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:go(e.target,[`true`,`false`],t,`${n}.target`):[W(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function yo(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[W(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:go(e.target,i,t,`${n}.target`)}function bo(e,t){let n=oo(e.state).map(e=>ho(e,t)),r=e.questions,i=fo(r);if(i.length>0)return n.push(...i.map(e=>ho(e,t))),n;for(let[e,i]of Object.entries(r)){let r=po(e);if(r.length>0){n.push(...r.map(e=>ho(e,t)));continue}let a=`questions.${e}`,o=uo(i,a);if(o.length>0){n.push(...o.map(e=>ho(e,t)));continue}let s=i;s.type===`choice`?n.push(..._o(s,t,a)):s.type===`noul`?n.push(...vo(s,t,a)):n.push(...yo(s,t,a))}return n}const xo={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:bo};function So(e,t){let n=[];if(!(`wav_fn`in e))n.push(V(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(V(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(V(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(V(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(V(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(V(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Co={name:`tts`,detect:e=>`wav_fn`in e,inspect:So},wo=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function To(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Eo(e){return/^[\x20-\x7E]+$/.test(e)}function Do(e,t){let n=[];if(!(`prompt`in e))n.push(V(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(V(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(V(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(V(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=To(r);wo.has(e)||n.push(V(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...wo].join(`, `)}.`,{line:t,path:`img_path`})),Eo(r)||n.push(V(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(V(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(V(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=To(r);wo.has(e)||n.push(V(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...wo].join(`, `)}.`,{line:t,path:`input_img`})),Eo(r)||n.push(V(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const Oo={name:`image`,detect:e=>`img_path`in e,inspect:Do},ko=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Ao=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function jo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Mo(e){return/^[\x20-\x7E]+$/.test(e)}function No(e,t,n,r,i,a){if(!(n in t)){r&&e.push(V(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(V(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(V(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=jo(o);i.has(s)||e.push(V(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Mo(o)||e.push(V(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Po(e,t){let n=[];if(!(`prompt`in e))n.push(V(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(V(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(V(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return No(n,e,`first_frame_path`,!0,ko,t),No(n,e,`last_frame_path`,!1,ko,t),No(n,e,`video_path`,!1,Ao,t),n}const Fo=[Co,Oo,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Po},xo,$a,Za,Ya];function Io(e,t){return t===void 0?Fo.find(t=>t.detect(e))??Ya:Fo.find(e=>e.name===t)||Ya}async function Lo(e,t){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(V(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function Ro(e,t,r,i,a){let o=r?null:new Set(Ba(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=x({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(V(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...zo(n,d,i))}return{sampled:c,issues:s}}function zo(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[V(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Io(r,n).inspect(r,t)}const Bo={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Lo(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[V(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Ro(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Vo(e,t){return new Promise((n,r)=>{ce.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function Ho(e){return new Promise((t,n)=>{ce.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const Uo=/^[a-zA-Z0-9_-]+$/;function Wo(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function Go(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function Ko(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||Go(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=Wo(n),i=n.slice(e.length);e.length>0&&!Uo.test(e)&&t.length<10&&t.push(V(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(V(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=Wo(i);if(a.length>120&&t.length<10&&t.push(V(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(V(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(V(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function qo(e,t,n){let{entry:i,zipfile:a}=await Vo(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);se(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Jo(e,t=100){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const Yo={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Ho(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[V(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[V(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(V(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(V(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=Ko(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(V(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||Go(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return wo.has(n)});e.length<25&&r.push(V(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ie(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await qo(e,_,y)}catch(t){return r.push(V(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await Bo.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await Jo(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(V(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Xo(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Zo(e);if(t===`.zip`)return Qo(e);throw new N(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,M.USAGE)}async function Zo(e){let t=await es(e);if(!t)throw new N(`JSONL file is empty or contains only blank lines: ${e}`,M.USAGE);let n=$o(t);return n===`unknown`?`text`:n}async function Qo(e){let t=await ts(e,`data.jsonl`);if(!t)throw new N(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,M.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=$o(t);if(n===`unknown`)throw new N(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,M.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function $o(e){let t;try{t=JSON.parse(e)}catch{throw new N(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,M.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new N(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,M.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function es(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function ts(e,t){return Vo(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new N(`Failed to read "${t}" from ZIP: ${e?.message}`,M.USAGE));return}let o=x({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const ns=[Bo,Yo];function rs(e){let t=h(e).toLowerCase(),n=ns.find(e=>e.extensions.includes(t));if(!n){let e=ns.flatMap(e=>e.extensions).join(`, `);throw new N(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,M.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function is(e){ns.some(t=>t.format===e.format)||ns.push(e)}async function as(e,t={}){let{bytes:n}=Ra(e,t.maxBytes??209715200),r=await rs(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function os(){return ns.map(e=>({format:e.format,extensions:[...e.extensions]}))}function ss(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}const cs=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],ls=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],us=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),ds=524288e3,fs=6291456,ps=5e4;function G(e,t){throw new P(`${e}\n${t}`)}function ms(e){if(e instanceof N)return e;let t=e?.code;return new N(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,M.GENERAL,t===`ENOENT`?`Check the file and parent directory paths. / 请检查文件及父目录路径。`:t===`EEXIST`?`Output exists; use --force to replace it. / 输出已存在,使用 --force 覆盖。`:`Check file permissions and available disk space. / 请检查文件权限与磁盘空间。`,{cause:e})}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hs(e){return cs.includes(e)||G(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*gs(e){let t=typeof e==`string`?de(e):e instanceof Blob?ye.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw ms(e)}}async function*_s(e,t=1/0,n=fs){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return G(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of gs(e)){i+=a.byteLength,i>t&&G(`File exceeds ${t} bytes.`,`文件超过 ${t} 字节。`);let e=Buffer.concat([r,a]),s=0,c=e.indexOf(10,s);for(;c!==-1;){let t=c-s;t>n&&G(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`),yield{text:o(e.subarray(s,c)).replace(/\r$/,``),bytes:t+1},s=c+1,c=e.indexOf(10,s)}r=Buffer.from(e.subarray(s)),r.byteLength>n&&G(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function vs(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return G(`Media must use a public HTTP(S) or base64 data URL.`,`媒体必须使用公网 HTTP(S) 或 base64 data URL。`)}let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``),r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(n),i=r?parseInt(r[1],16):0,a=r?parseInt(r[2],16):0,o=r?[i>>8,i&255,a>>8,a&255].join(`.`):n,s=n===`localhost`||n.endsWith(`.localhost`)||ve(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||ve(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&G(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)vs(n,t);else if(K(e))for(let[n,r]of Object.entries(e))vs(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var ys=class{ids=/* @__PURE__ */ new Set;thinking;report={records:0,bytes:0,model:``,endpoint:`/v1/chat/completions`,warnings:[]};warn(e){this.report.warnings.includes(e)||this.report.warnings.push(e)}add(e,t){let n=this.report.records+1,r=e=>G(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);K(e)||r(`JSON object`);let i=e,a=i.custom_id;(typeof a!=`string`||!a.trim()||Array.from(a).length>256||this.ids.has(a))&&r(`custom_id`),i.method!==`POST`&&r(`method=POST`);let o=hs(String(i.url));K(i.body)||r(`body`);let s=i.body;if((typeof s.model!=`string`||!s.model.trim())&&r(`body.model`),s.enable_thinking!==void 0&&typeof s.enable_thinking!=`boolean`&&r(`enable_thinking`),this.report.records&&(this.report.model!==s.model||this.report.endpoint!==o||this.thinking!==s.enable_thinking)&&r(`model/url/enable_thinking`),o===`/v1/embeddings`){let e=e=>typeof e==`string`&&!!e.trim(),t=e=>Array.isArray(e)&&e.length>0&&e.every(e=>Number.isInteger(e)&&e>=0);e(s.input)||t(s.input)||Array.isArray(s.input)&&s.input.length>0&&(s.input.every(e)||s.input.every(t))||r(`body.input`)}else(!Array.isArray(s.messages)||!s.messages.length||s.messages.some(e=>!K(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(K))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(K))))&&r(`body.messages`);vs(s),K(s.extra_body)&&(`enable_thinking`in s.extra_body||`thinking_budget`in s.extra_body)&&this.warn(`Place enable_thinking/thinking_budget at body top level, not extra_body. / enable_thinking/thinking_budget 应放在 body 顶层,而非 extra_body。`),t>6291456&&r(`line <=6 MiB`),t>1048576&&this.warn(`Line exceeds 1 MiB; documentation differs (1/6 MiB), compatibility is not guaranteed. / 单行超过 1 MiB,文档存在 1/6 MiB 差异,不保证兼容。`),this.ids.add(a),this.report.records++,this.report.bytes+=t,this.report.model=s.model,this.report.endpoint=o,this.thinking=s.enable_thinking,(this.report.records>5e4||this.report.bytes>524288e3)&&r(`50000 records / 500 MiB`),s.model===`batch-test-model`&&(this.report.records>100||this.report.bytes>1048576)&&r(`batch-test-model: 100 records / 1 MiB`)}finish(){return this.report.records||G(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function bs(e){let t=new ys,n=0;for await(let r of _s(e,ds)){n++;let e;try{e=JSON.parse(r.text)}catch{G(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function xs(e){let t=[],n=0;for await(let r of gs(e))n+=r.byteLength,n>524288e3&&G(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function Ss(e,t,n){return e.requestJson({path:ar(),method:`POST`,body:t,signal:n})}function Cs(e,t,n){return e.requestJson({path:or(t),signal:n})}function ws(e,t,n){return e.requestJson({path:sr(t),method:`POST`,signal:n})}function Ts(e,t={},n){let r=new URLSearchParams;for(let[e,n]of Object.entries(t))n!==void 0&&r.set(e,Array.isArray(n)?n.join(`,`):String(n));return e.requestJson({path:ar()+(r.size?`?${r.toString()}`:``),signal:n})}function Es(e,t,n){return e.request({path:cr(t),signal:n})}function Ds(e){let t=e.url(ir(),lr),n=new URL(t).hostname.toLowerCase(),r=new URL(e.baseUrl).hostname.toLowerCase();return(e.usesTokenPlanEndpoint()||/^dashscope(?:-intl|-us)?\.aliyuncs\.com$/.test(n)||/^dashscope-(?:intl|us)\.aliyuncs\.com$/.test(r))&&G(`--batch needs the Batch host, not a realtime/international/Token Plan endpoint; configure --base-url explicitly.`,`--batch 不能使用实时、国际站或 Token Plan 端点,请显式配置 Batch --base-url。`),t}async function Os(e,t,n=!1){let r=j(e),i=j(k(r),`.${be(r)}.${Ne()}.tmp`),a,o=e=>{throw ms(e)};try{await De(k(r),{recursive:!0}).catch(o),a=await Oe(i,`wx`,384).catch(o);for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e,n=0;for(;n<t.byteLength;){let e=await a.write(t,n,t.byteLength-n).catch(o);n+=e.bytesWritten}}await a.sync().catch(o),await a.close().catch(o),a=void 0,n?await Ae(i,r).catch(o):await Ee(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await je(i).catch(()=>{})}}async function ks(e){let t=hs(e.endpoint??`/v1/chat/completions`);(j(e.file)===j(e.outputFile)||e.bodyFile&&j(e.bodyFile)===j(e.outputFile))&&G(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||G(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await ke(e.bodyFile,`utf8`)}catch(e){throw ms(e)}try{let e=JSON.parse(t);if(!K(e))throw Error();i=e}catch{G(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&G(`--body-file cannot define model/messages/input.`,`--body-file 不得定义 model/messages/input。`),t===`/v1/embeddings`&&(e.system!==void 0||`enable_thinking`in i||`thinking_budget`in i)&&G(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new ys,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of gs(e.file)){n+=r.byteLength,n>524288e3&&G(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{G(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{G(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=ye.from(l()),d=we({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&G(`CSV requires unique headers and mapped ID/input columns.`,`CSV 表头必须唯一并包含映射的 ID/输入列。`),s=e.filter(e=>e!==n&&e!==r),e)});u.on(`error`,e=>d.destroy(e)),u.pipe(d);let f=0;try{for await(let s of d){f++;let c=s;c[r]?.trim()||G(`Empty CSV input at record ${f}.`,`CSV 第 ${f} 条记录输入为空。`);let l={...i,model:e.model};t===`/v1/embeddings`?(l.input=c[r],l.encoding_format??=`float`):l.messages=[...e.system===void 0?[]:[{role:`system`,content:e.system}],{role:`user`,content:c[r]}];let u={custom_id:c[n],method:`POST`,url:t,body:l},d=JSON.stringify(u)+`
|
|
13
13
|
`;a.add(u,Buffer.byteLength(d)),e.dryRun&&o.length<2&&o.push(u),yield d}c=a.finish()}catch(e){throw e instanceof Error&&e.name===`Error`&&`code`in e&&String(e.code).startsWith(`CSV_`)&&G(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),ms(e)}finally{u.destroy(),d.destroy()}}if(e.dryRun)for await(let e of u());else await Os(e.outputFile,u(),e.force);return{...c,output_file:j(e.outputFile),ignored_columns:s,...e.dryRun?{samples:o}:{}}}const As=[`custom_id`,`model`,`request_id`,`status_code`,`content`,`embedding`,`error_code`,`error_message`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function q(e){return K(e)?e:{}}function js(e){let t=e==null?``:typeof e==`string`?e:JSON.stringify(e);return/^[\s\x00-\x1f]*[=+@-]/.test(t)?`'${t}`:t}function Ms(e){return typeof e==`number`&&Number.isFinite(e)?e:``}function Ns(e){let t=q(e),n=q(t.response),r=q(n.body),i=q(t.error??r.error),a=q(r.usage),o=q(q(Array.isArray(r.choices)?r.choices[0]:void 0).message),s=Array.isArray(r.data)?r.data.map(e=>{let t=q(e);return{index:t.index,embedding:t.embedding}}):void 0;return{recognized:Array.isArray(r.choices)||Array.isArray(r.data)||`code`in i||`message`in i,row:{custom_id:js(t.custom_id),model:js(r.model),request_id:js(n.request_id),status_code:Ms(n.status_code),content:js(o.content),embedding:js(s),error_code:js(i.code),error_message:js(i.message),prompt_tokens:Ms(a.prompt_tokens),completion_tokens:Ms(a.completion_tokens),total_tokens:Ms(a.total_tokens)}}}async function Ps(e,t,n=!1){let r=0,i=0;async function*a(){yield``+Te([],{columns:[...As],header:!0});for(let t of e)for await(let e of _s(t,1/0,1/0)){if(!e.text.trim())continue;let n;try{n=JSON.parse(e.text)}catch{G(`Invalid result JSONL at ${t}:${r+1}.`,`结果 JSONL 格式错误:${t}:${r+1}。`)}let a=Ns(n);r++,a.recognized||i++,yield Te([a.row],{columns:[...As]})}}return await Os(t,a(),n),{records:r,unknown_records:i}}function Fs(e){let t=e===`zh-CN`?`请介绍一下自己`:`Introduce yourself`,n={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-plus`,messages:[{role:`user`,content:t}]}},r={custom_id:`req-001`,method:`POST`,url:`/v1/embeddings`,body:{model:`text-embedding-v4`,input:t,encoding_format:`float`}},i={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-vl-plus`,messages:[{role:`user`,content:[{type:`text`,text:t},{type:`image_url`,image_url:{url:`https://example.com/image.jpg`}}]}]}},a={custom_id:`req-001`,response:{request_id:`request-001`,status_code:200,body:{model:`qwen-plus`,choices:[{message:{role:`assistant`,content:e===`zh-CN`?`你好`:`Hello`}}],usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}}},error:null};return{csv:`custom_id,content\nreq-001,${t}\nreq-002,2+2?`,chat:n,embedding:r,vision:i,defaults:{enable_thinking:!1,max_tokens:1024},success:a,failure:{custom_id:`req-002`,response:null,error:{code:`ExampleError`,message:`Example service error`}}}}function Is(e){let t=t=>{let n=Fs(t);if(e===`prepare`||e===`convert`)return`input.csv:\n${n.csv}\n\ninput.jsonl:\n${JSON.stringify(n.chat)}\n\ndefaults.json (--body-file):\n${JSON.stringify(n.defaults)}`;if(e===`create`)return`Chat JSONL:\n${JSON.stringify(n.chat)}\n\nEmbedding JSONL:\n${JSON.stringify(n.embedding)}\n\nMultimodal JSONL (${t===`zh-CN`?`请替换示例公网图片 URL`:`replace the example public image URL`}):\n${JSON.stringify(n.vision)}`;let r=Te([n.success,n.failure].map(e=>Ns(e).row),{columns:[...As],header:!0});return`result.jsonl:\n${JSON.stringify(n.success)}\n\nerror.jsonl (${t===`zh-CN`?`示意包络,真实服务需联调`:`illustrative envelope; verify with the service`}):\n${JSON.stringify(n.failure)}\n\nresult.csv:\n${r}`};return{"en-US":t(`en-US`),"zh-CN":t(`zh-CN`)}}const Ls=`decision-model-preview`,Rs=[`cn-beijing`,`ap-southeast-1`],zs=`cn-beijing`,Bs=[`label`,`target`];function Vs(e){if(!H(e))return e;let t=e.questions;return H(t)&&typeof t.type!=`string`?t:e}function Hs(e){if(!H(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!H(r)){t[n]=r;continue}let e={...r};for(let t of Bs)delete e[t];t[n]=e}return t}async function Us(e,t,n){return e.requestJson({path:qr(),method:`POST`,body:t,signal:n})}async function Ws(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=qr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Gs(e,t,n){return e.requestJson({path:Jr(t),method:`GET`,signal:n})}async function Ks(e,t,n){return e.requestJson({path:Yr(t),method:`POST`,signal:n})}async function qs(e,t,n){return e.requestJson({path:Jr(t),method:`DELETE`,signal:n})}async function Js(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=Xr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Ys(e,t,n){return e.requestJson({path:Zr(t),method:`GET`,signal:n})}async function Xs(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Qr(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Zs(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Qs(e,t={}){return e.requestJson({path:Zs($r(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function $s(e,t,n){return e.requestJson({path:ei(),method:`POST`,body:t,signal:n})}async function ec(e,t={}){let n=Zs(ei(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function tc(e,t,n){return e.requestJson({path:ti(t),method:`GET`,signal:n})}async function nc(e,t,n={}){return e.requestJson({path:Zs(ri(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function rc(e,t,n){return e.requestJson({path:ni(t),method:`POST`,signal:n})}async function ic(e,t,n){return e.requestJson({path:ti(t),method:`DELETE`,signal:n})}const ac={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},oc=Object.keys(ac),sc=`sft-lora`;function cc(e){return e in ac}function lc(e){let{method:t,variant:n}=ac[e];return{method:t,variant:n}}function uc(e,t){if(!e)return!1;let{method:n,variant:r}=ac[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function dc(e){return e?oc.filter(t=>uc(e,t)):[]}async function fc(e,t){return await xa(rn(e),t)}const pc=`INSUFFICIENT_SAMPLES`;function mc(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:pc,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
14
14
|
`)}}function hc(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function gc(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return as(e,{...r,schema:n})},resolveHyperParameters(e,t){return hc(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const _c=gc(`sft`,`sft`,`chatml`),vc={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},yc={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},bc={...yc,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},xc={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Sc(e){return e===`image`||e===`image-i2i`}function Cc(e){return e===`video`||e===`video-kf2v`}function wc(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Tc(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Ec=[_c,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return as(e,{...n,schema:`tts`});if(Sc(t))return as(e,{...n,schema:`image`,maxBytes:La});if(Cc(t)){let r=await as(e,{...n,schema:`video`,maxBytes:La});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(V(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(V(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return as(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...vc};if(Sc(e)){let n={...e===`image-i2i`?bc:yc};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Cc(e)){let e=t.model??t.baseModel,n={...xc,batch_size:Tc(e)?1:4,max_pixels:Tc(e)?102400:wc(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return hc(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!Sc(t)&&!Cc(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Sc(e)||Cc(e)}},gc(`dpo`,`dpo_full`,`dpo`),gc(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return as(e,{...n,schema:`cpt`,maxBytes:Fa})},resolveHyperParameters(e,t){return hc(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Dc(e){let t=Ec.find(t=>t.clientTrainingType===e);if(!t){let t=Ec.map(e=>e.clientTrainingType).join(`, `);throw new N(`Unknown training type "${e}".`,M.USAGE,`Supported training types: ${t}.`)}return t}function Oc(){return Ec.map(e=>e.clientTrainingType)}const kc=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,Ac=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,jc=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Mc(e,t){return B(await e.console(kc,{query:{type:0,modelId:t}}))}async function Nc(e,t,n){return B(await e.console(Ac,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Pc(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return B(await e.console(jc,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}function Fc(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function Ic(e,t,n){return e.requestJson({path:ii(),method:`POST`,body:t,signal:n})}async function Lc(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.plan!==void 0&&n.set(`plan`,t.plan);let r=ii(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Rc(e,t,n){return e.requestJson({path:ai(t),method:`GET`,signal:n})}async function zc(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize)),n.includeDeleted!==void 0&&r.set(`include_deleted`,String(n.includeDeleted)),n.statuses!==void 0&&r.set(`statuses`,n.statuses.join(`,`)),n.chargeTypes!==void 0&&r.set(`charge_types`,n.chargeTypes.join(`,`));let i=oi(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Bc(e,t,n,r){return e.requestJson({path:si(t,n),method:`GET`,signal:r})}async function Vc(e,t,n,r){return e.requestJson({path:di(t,n),method:`GET`,signal:r})}async function Hc(e,t,n,r={}){return e.requestJson({path:oi(t),method:`POST`,body:n,headers:Fc(r.requestId),signal:r.signal})}async function Uc(e,t,n,r,i={}){return e.requestJson({path:ci(t,n),method:`PUT`,body:r,headers:Fc(i.requestId),signal:i.signal})}async function Wc(e,t,n,r,i={}){return e.requestJson({path:li(t,n),method:`PUT`,body:r,headers:Fc(i.requestId),signal:i.signal})}async function Gc(e,t,n,r={}){let i=si(t,n),a=new URLSearchParams;return r.reason!==void 0&&a.set(`reason`,r.reason),e.requestJson({path:a.toString()?`${i}?${a.toString()}`:i,method:`DELETE`,headers:Fc(r.requestId),signal:r.signal})}async function Kc(e,t,n,r){return e.requestJson({path:ui(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function qc(e,t,n){return e.requestJson({path:ai(t),method:`DELETE`,signal:n})}async function Jc(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=mi(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Yc(e,t,n,r,i){return e.requestJson({path:fi(t),method:`PUT`,body:n,headers:Fc(i),signal:r})}async function Xc(e,t,n,r){return e.requestJson({path:pi(t),method:`PUT`,body:n,signal:r})}const J={LORA:`lora`,PTU:`ptu`,MU:`mu`},Zc=J.LORA;function Qc(e){return e===`audio`?J.MU:Zc}const $c={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},el=$c.POST_PAY,Y={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function tl(e,t){if(t||e.inputTpm!==void 0||e.outputTpm!==void 0){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm must be provided together.
|
package/package.json
CHANGED