bailian-cli-runtime 2.8.1 → 2.8.3

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.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -2
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -39,7 +39,7 @@ ${l?`${l}\n\n`:``}${i(this.localize(z.gettingHelp))}
39
39
  `}function en(e,t){if(typeof e==`string`)return{message:t(e)};try{let n=Object.getOwnPropertyDescriptors(e),r=e=>{if(e)return`value`in e?De(e.value):`[Accessor]`};if(Object.hasOwn(n,`message`)){let e=r(n.message),i=r(n.code),a=r(n.details);return{message:t(e),...typeof i==`string`?{code:i}:{},...a===void 0?{}:{details:a}}}return{message:t(De(e))}}catch{return{message:`[Unserializable]`}}}const tn=`https://bailian.console.aliyun.com`,nn=`${tn}/cn-beijing`,rn=`${nn}/?tab=app#/api-key`,an=`https://help.aliyun.com/zh/model-studio/billing-for-knowledge-base`,on=`${tn}/cn-beijing?tab=plan#/efm/subscription/overview`;function sn(e){return`${nn}?tab=mcp#/mcp-market/detail/${e}`}const cn=sn(`WebSearch`),ln=`https://help.aliyun.com/zh/model-studio/cosyvoice-voice-list`;function un(e){return`https://billing-cost.console.aliyun.com/refund/refund?instanceId=${encodeURIComponent(e)}`}function dn(e,t){process.exit(t.error(e))}function fn(e,n,r){if(e instanceof t)return e;if(e instanceof Error)return gn(e,n,r)??new t(e.message,l.GENERAL,void 0,{cause:e});let i=typeof e==`object`&&e?JSON.stringify(Oe(e)):String(e);return new t(i,l.GENERAL)}function pn(e){return`Run \`${O(e,`auth login --console`)}\` to sign in or refresh your console session.`}function mn(e,t,n){let r=e.hint;if(e instanceof a)switch(e.reason){case`missing-api-key`:r=`Set DASHSCOPE_API_KEY, pass --api-key, or run \`${O(t,`auth login`)}\`.`;break;case`missing-console-token`:return`Run \`${O(t,`auth login --console`)}\`.`;case`expired-console-session`:return pn(t);case`missing-openapi-pair`:return`Set BAILIAN_ACCESS_KEY_ID and BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET), pass --access-key-id and --access-key-secret, or run \`${O(t,`auth login --open-api`)}\`.`;case`incomplete-openapi-config`:return`Run \`${O(t,`auth login --open-api --access-key-id <id> --access-key-secret <secret>`)}\` again to save a complete pair.`;case`incomplete-openapi-flag`:case`incomplete-openapi-env`:return r}return e.exitCode!==l.AUTH||r&&[`auth login --console`,`auth login --open-api`,`--access-key-id`,`ALIBABA_CLOUD_ACCESS_KEY_`].some(e=>r.includes(e))?r:[r,`${O(t,`auth login --api-key <your-key>`)}`,`${O(t,`auth status`)}`,n({"en-US":`Get API Key: ${rn}`,"zh-CN":`获取 API Key:${rn}`})].filter(e=>e!==void 0).join(`
40
40
  `)}const hn=e=>typeof e==`string`?e:e[`en-US`];function gn(e,n,r=hn){if(e instanceof t)return e;let i=r({"en-US":`If the DashScope host is wrong, check baseUrl (--base-url, ${O(n,`config show`)}, or DASHSCOPE_BASE_URL).`,"zh-CN":`如果 DashScope 主机地址有误,请检查 baseUrl(--base-url、${O(n,`config show`)} 或 DASHSCOPE_BASE_URL)。`});if(e.name===`AbortError`||e.name===`TimeoutError`||e.message.includes(`timed out`))return new t(r({"en-US":`Request timed out.`,"zh-CN":`请求超时。`}),l.TIMEOUT,r({"en-US":`Try increasing --timeout (e.g. --timeout 60).\n${i}\nRun: ${O(n,`auth status`)} — to check credentials.`,"zh-CN":`请尝试增大 --timeout(例如 --timeout 60)。\n${i}\n运行 ${O(n,`auth status`)} 检查凭证。`}),{cause:e});if(e instanceof TypeError&&e.message===`fetch failed`){let a=e.cause,o=[a?.code,a?.message===a?.code?void 0:a?.message].filter(Boolean),s=o.length?o.join(`: `):r({"en-US":`unknown cause`,"zh-CN":`未知原因`});return new t(r({"en-US":`Network request failed: ${s}`,"zh-CN":`网络请求失败:${s}`}),l.NETWORK,_n(a?.code,n,i,r),{cause:a??e})}let a=e.code;if(typeof a==`string`&&a.startsWith(`E`)){let n={"en-US":`Check the file path and permissions.`,"zh-CN":`请检查文件路径和权限。`};return a===`ENOENT`?n={"en-US":`File or directory not found.`,"zh-CN":`文件或目录不存在。`}:a===`EACCES`||a===`EPERM`?n={"en-US":`Permission denied — check file or directory permissions.`,"zh-CN":`权限不足,请检查文件或目录权限。`}:a===`ENOSPC`&&(n={"en-US":`Disk full — free up space and try again.`,"zh-CN":`磁盘已满,请释放空间后重试。`}),new t(r({"en-US":`File system error: ${e.message}`,"zh-CN":`文件系统错误:${e.message}`}),l.GENERAL,r(n),{cause:e})}}function _n(e,t,n,r){switch(e){case`ENOTFOUND`:case`EAI_AGAIN`:return r({"en-US":`DNS resolution failed. Check DNS / network. ${n}`,"zh-CN":`DNS 解析失败,请检查 DNS 和网络。${n}`});case`ECONNREFUSED`:return r({"en-US":`Connection refused. Check the target host/port and proxy settings.`,"zh-CN":`连接被拒绝,请检查目标主机、端口和代理配置。`});case`ECONNRESET`:return r({"en-US":`Connection reset by peer. Retry, or check proxy / firewall.\nIf you are behind a VPN or corporate proxy, route ${t} through it:\nexport HTTPS_PROXY=http://127.0.0.1:<proxy-port>`,"zh-CN":`连接被对端重置,请重试或检查代理和防火墙。\n如果使用 VPN 或企业代理,请为 ${t} 配置代理:\nexport HTTPS_PROXY=http://127.0.0.1:<proxy-port>`});case`ETIMEDOUT`:return r({"en-US":`Connection timed out. Check your network. ${n}`,"zh-CN":`连接超时,请检查网络。${n}`});case`CERT_HAS_EXPIRED`:case`UNABLE_TO_VERIFY_LEAF_SIGNATURE`:case`DEPTH_ZERO_SELF_SIGNED_CERT`:return r({"en-US":`TLS certificate error. Check system clock and CA bundle.`,"zh-CN":`TLS 证书错误,请检查系统时间和 CA 证书。`});default:return r({"en-US":`Check network and proxy (HTTP_PROXY / HTTPS_PROXY). ${n}`,"zh-CN":`请检查网络和代理(HTTP_PROXY / HTTPS_PROXY)。${n}`})}}function vn(e,t,n,r){if(!Nt(process.stderr))return;let i=e.configPath?.replace(Re(),`~`)??`~/.bailian/config.json`,a=fe(t);r.info({"en-US":`BAILIAN ${i} | Auth: ${a} ${n.source} · api-key`,"zh-CN":`BAILIAN ${i} | 鉴权:${a} ${n.source} · api-key`})}const yn=`https://registry.npmjs.org`,bn=`bailian-cli`,xn=()=>Be(ae(),`update-state.json`),Sn=3e3;function Cn(e){let t=String(e).split(`+`)[0].split(`-`)[0].trim().split(`.`).map(e=>{let t=Number(e);return Number.isFinite(t)?t:0});return[t[0]??0,t[1]??0,t[2]??0]}function wn(e){let t=String(e).split(`+`)[0],n=t.indexOf(`-`);return n>=0?t.slice(n+1):``}function Tn(e){return wn(e)!==``}function En(e){return e.length>0&&/^[0-9]+$/.test(e)}function Dn(e,t){let n=e?e.split(`.`):[],r=t?t.split(`.`):[];if(n.length===0&&r.length===0)return 0;if(n.length===0)return 1;if(r.length===0)return-1;let i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e],i=r[e];if(t===void 0)return-1;if(i===void 0)return 1;let a=En(t),o=En(i);if(a&&o){let e=Number(t)-Number(i);if(e!==0)return e>0?1:-1}else if(a!==o)return a?-1:1;else if(t!==i)return t>i?1:-1}return 0}function On(e,t){let[n,r,i]=Cn(e),[a,o,s]=Cn(t);return n===a?r===o?i===s?Dn(wn(e),wn(t)):i>s?1:-1:r>o?1:-1:n>a?1:-1}function kn(e,t){return On(e,t)>0}function An(e,t){return In(e,t)&&!Tn(e)}function jn(){try{let e=Ue(xn(),`utf-8`);return JSON.parse(e)}catch{return null}}function Mn(e){try{Ge(xn(),JSON.stringify(e))}catch{}}async function Nn(e=Sn,t=bn){try{let n=t.replace(`/`,`%2f`),r=await A.fetch(`${yn}/${n}/latest`,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(e)});return r.ok?(await r.json()).version??null:null}catch{return null}}let Pn=null;function Fn(){return Pn}function In(e,t){let[n,r]=Cn(e),[i,a]=Cn(t);return n>i||n===i&&r-a>3}function Ln(e){return e instanceof Error?e.message:String(e)}async function Rn(e,t){try{e.info({"en-US":`Syncing agent skills...`,"zh-CN":`正在同步 Agent 技能……`});let{execSync:t}=await import(`child_process`);t(`bl skill update`,{stdio:`pipe`}),e.info({"en-US":`Agent skills updated.`,"zh-CN":`Agent 技能已更新。`})}catch(n){e.warning({code:`SKILL_SYNC_FAILED`,message:{"en-US":`Agent skill sync failed: ${Ln(n)}. Run ${O(t,`skill update`)} manually.`,"zh-CN":`Agent 技能同步失败:${Ln(n)}。请手动运行 ${O(t,`skill update`)}。`}})}}async function zn(e,n,r=bn,i=bn,a){let{output:c,binName:l,commandPrefix:u}=a,d=u??l,f=oe({clientName:i,npmPackage:r});if(f===`brew`||f===`winget`)return!1;c.info({"en-US":`Auto-updating: ${e} → ${n}`,"zh-CN":`正在自动更新:${e} → ${n}`});let p=`npm install -g ${r}@latest`;try{let t=null;if(f===`binary`){let{performBinaryUpdate:e}=await Promise.resolve().then(()=>Ci);t=await e(n)}else{let{execSync:e}=await import(`child_process`);e(p,{stdio:`pipe`});try{let n=e(`npm root -g`,{encoding:`utf-8`,stdio:`pipe`}).trim();t=JSON.parse(Ue(Be(n,r,`package.json`),`utf-8`)).version??null}catch(e){c.warning({code:`UPDATE_VERSION_UNVERIFIED`,message:{"en-US":`Could not verify installed version: ${Ln(e)}`,"zh-CN":`无法验证已安装版本:${Ln(e)}`}})}}return Mn({lastChecked:Date.now(),latestVersion:t??n}),c.info({"en-US":`Update complete: ${e} → ${t??n}. Run ${O(d,`--version`)} to verify.`,"zh-CN":`更新完成:${e} → ${t??n}。运行 ${O(d,`--version`)} 验证。`}),await Rn(c,u??`bl`),Pn=null,!0}catch(e){let n=f===`binary`?e instanceof t&&e.hint?e.hint.replace(/^Re-run:\s*/i,``):process.platform===`win32`?`irm ${o} | iex`:`curl -fsSL ${s} | bash`:p;return c.warning({code:`AUTO_UPDATE_FAILED`,message:{"en-US":`Auto-update failed: ${Ln(e)}. Run manually: ${n}`,"zh-CN":`自动更新失败:${Ln(e)}。请手动运行:${n}`}}),!1}}async function Bn(e,t=bn,n=bn){let r=jn(),i=Date.now();if(r&&i-r.lastChecked<864e5){Pn=kn(r.latestVersion,e)?r.latestVersion:null;return}let a=oe({clientName:n,npmPackage:t}),o=null;if(a===`binary`){try{let{fetchBinaryChannelVersion:e}=await Promise.resolve().then(()=>Ci);o=await e(`latest`,Sn)}catch{o=null}o||=await Nn(Sn,t)}else o=await Nn(Sn,t);o&&(Mn({lastChecked:i,latestVersion:o}),o&&kn(o,e)&&(Pn=o))}async function Vn(e){if(!e.command.prepare)return!0;let t=await e.command.prepare({...e,prepared:void 0}),n=t.notices.map(t=>({...t,message:e.localize(t.message)}));if(e.settings.dryRun)return e.output.result({plan:t.preview,risk:t.risk,notices:n}),!1;if(t.risk&&!e.confirmed)throw new Ut({message:e.localize(t.risk.message),hint:e.localize(Ht()),plan:t.preview,notices:n});for(let t of n)e.output.warning({code:t.code,message:t.message,...t.url?{details:{url:t.url}}:{}});return e.prepared=t.data,!0}function Hn(e,t,n){return I(e.sources.file.language??c).localize({"en-US":`Profile "${t}" does not support command "${n}"; API Key settings will be read from Profile "default" for this run.`,"zh-CN":`Profile "${t}" 不支持命令 "${n}",本次将从 Profile "default" 读取 API Key 配置。`})}function Un(e,t){let n=Hn(e,t,e.path.join(` `));e.output.warning({code:`PROFILE_API_KEY_FALLBACK`,message:n,details:{profile:t,command_path:e.path,fallback_profile:`default`,credential_fields:[`api_key`,`base_url`]}})}function Wn(e,t,n,r){if(t===`flag`)return e===`api_key`?`--api-key`:`--base-url`;if(t===`env`){let t=e===`api_key`?`DASHSCOPE_API_KEY`:`DASHSCOPE_BASE_URL`;return r===`zh-CN`?`环境变量 (${t})`:`env (${t})`}return r===`zh-CN`?`配置文件 (${n})`:`config (${n})`}function Gn(e,t,n){let r=e.sources.file.language??c,i=I(r),a=e.sources.configPath??e.settings.configPath??`~/.bailian/config.json`,o=Wn(`api_key`,t,a,r),s=Wn(`base_url`,n,a,r);return i.localize({"en-US":[`api_key and base_url are resolved from different sources.`,`api_key ← ${o}`,`base_url ← ${s}`,`These may not match. The request will continue.`,`Set both from the same source, or run ${O(e.identity,`config show`)} to view effective configuration.`].join(`
41
41
  `),"zh-CN":[`api_key 和 base_url 来自不同配置源。`,`api_key ← ${o}`,`base_url ← ${s}`,`两者可能不匹配,请求仍会继续。`,`建议设为同一来源,或运行 ${O(e.identity,`config show`)} 查看生效配置。`].join(`
42
- `)})}function Kn(e,t,n){e.output.warning({code:`API_KEY_BASE_URL_SOURCE_MISMATCH`,message:Gn(e,t,n),details:{api_key_source:t,base_url_source:n}})}function qn(e){return t=>{let n=r=>{let i=e[r];return i?i(t,()=>n(r+1)):Promise.resolve()};return n(0)}}const Jn=async(e,t)=>{let{command:n,settings:r,sources:o}=e,s={identity:e.identity,settings:r,consoleRecoveryHint:pn(O(e.identity)),debug:t=>e.output.debug(t),...Ce(o)};if(n.auth===`apiKey`){let t=e.path.join(`.`),a=ke(o,t),c=a.sources;a.fallbackFrom&&Un(e,a.fallbackFrom);let l=we(c);le(l)&&l.apiKeySource&&l.baseUrlSource&&Kn(e,l.apiKeySource,l.baseUrlSource);let u;try{u=ge(c)}catch(e){if(!r.dryRun||n.prepare)throw e}if(e.client=new i({...s,...Ce(c),apiCred:u}),n.optionalConsole)try{let t=ye(o);e.client=new i({...s,...Ce(c),apiCred:u,consoleCred:t})}catch{}u&&!n.prepare&&vn(r,u.token,u,e.output)}else if(n.auth===`console`){let t,c;try{t=ye(o)}catch(e){try{c=Te(o)}catch(t){if(!r.dryRun||n.prepare)throw t instanceof a&&t.reason===`missing-openapi-pair`?e:t}}e.client=new i({...s,consoleCred:t,resolveConsoleOpenApiCredential:()=>c??Te(o)})}else if(n.auth===`openapi`){let t;try{t=Te(o)}catch(e){if(!r.dryRun||n.prepare)throw e}e.client=new i({...s,openApiCred:t})}await t()},Yn=(e,t)=>Pe({identity:e.identity,settings:e.settings,authMethod:e.command.auth,caller:pe(process.env)},e.path,e.flags,t),Xn=async(e,t)=>{if(e.command.prepare||process.env.NO_UPDATE_NOTIFIER===`1`){await t();return}let n=Bn(e.identity.version,e.identity.npmPackage,e.identity.clientName).catch(()=>{});await t(),await n;let r=e.path.length===1&&e.path[0]===`update`,i=Fn();i&&!r&&(An(i,e.identity.version)?await zn(e.identity.version,i,e.identity.npmPackage,e.identity.clientName,{output:e.output,binName:e.identity.binName,...e.identity.commandInvocation?{commandPrefix:O(e.identity)}:{}}):e.output.warning({code:`UPDATE_AVAILABLE`,message:{"en-US":`Update available: ${e.identity.version} → ${i}. Run ${O(e.identity,`update`)} to upgrade.`,"zh-CN":`发现新版本:${e.identity.version} → ${i}。运行 ${O(e.identity,`update`)} 升级。`},details:{current_version:e.identity.version,latest_version:i,upgrade_command:`${O(e.identity,`update`)}`}}))},Zn=async(e,t)=>{if(e.command.prepare||e.command.risk===void 0||e.confirmed||e.settings.dryRun){await t();return}throw new Ut({message:e.localize(e.command.risk.message),hint:e.localize(Ht())})},Qn=async e=>{await Vn(e)&&await e.command.run(e)};function $n(e,t){return e[t]?.trim()||void 0}function er(e=process.env){return{httpProxy:$n(e,`HTTP_PROXY`),httpsProxy:$n(e,`HTTPS_PROXY`),noProxy:$n(e,`NO_PROXY`)}}function tr(){let{httpProxy:e,httpsProxy:n,noProxy:r}=er();if(e||n)try{qe(new Ke({httpProxy:e,httpsProxy:n,noProxy:r}))}catch(e){throw new t(`Invalid proxy configuration: ${e instanceof Error?e.message:String(e)}`,l.USAGE,`Check HTTP_PROXY / HTTPS_PROXY values, e.g. export HTTPS_PROXY=http://127.0.0.1:7890`,{cause:e})}}function nr(e){let{output:n,quiet:r,verbose:i}=e.settings,a=e.stdout??process.stdout,o=e.stderr??process.stderr,s=I(`en-US`),c=e.localize??(e=>s.localize(e)),l=!1,u;function d(e,t){let r=en(t,c);if(n===`json`)o.write(JSON.stringify({[e]:r})+`
42
+ `)})}function Kn(e,t,n){e.output.warning({code:`API_KEY_BASE_URL_SOURCE_MISMATCH`,message:Gn(e,t,n),details:{api_key_source:t,base_url_source:n}})}function qn(e){return t=>{let n=r=>{let i=e[r];return i?i(t,()=>n(r+1)):Promise.resolve()};return n(0)}}const Jn=async(e,t)=>{let{command:n,settings:r,sources:o}=e,s={identity:e.identity,settings:r,consoleRecoveryHint:pn(O(e.identity)),debug:t=>e.output.debug(t),...Ce(o)};if(n.auth===`apiKey`){let t=n.authCapability?n.authCapability(e.flags):e.path.join(`.`),a=ke(o,t),c=a.sources;a.fallbackFrom&&Un(e,a.fallbackFrom);let l=we(c);le(l)&&l.apiKeySource&&l.baseUrlSource&&Kn(e,l.apiKeySource,l.baseUrlSource);let u;try{u=ge(c)}catch(e){if(!r.dryRun||n.prepare)throw e}if(e.client=new i({...s,...Ce(c),apiCred:u}),n.optionalConsole)try{let t=ye(o);e.client=new i({...s,...Ce(c),apiCred:u,consoleCred:t})}catch{}u&&!n.prepare&&vn(r,u.token,u,e.output)}else if(n.auth===`console`){let t,c;try{t=ye(o)}catch(e){try{c=Te(o)}catch(t){if(!r.dryRun||n.prepare)throw t instanceof a&&t.reason===`missing-openapi-pair`?e:t}}e.client=new i({...s,consoleCred:t,resolveConsoleOpenApiCredential:()=>c??Te(o)})}else if(n.auth===`openapi`){let t;try{t=Te(o)}catch(e){if(!r.dryRun||n.prepare)throw e}e.client=new i({...s,openApiCred:t})}await t()},Yn=(e,t)=>Pe({identity:e.identity,settings:e.settings,authMethod:e.command.auth,caller:pe(process.env)},e.path,e.flags,t),Xn=async(e,t)=>{if(e.command.prepare||process.env.NO_UPDATE_NOTIFIER===`1`){await t();return}let n=Bn(e.identity.version,e.identity.npmPackage,e.identity.clientName).catch(()=>{});await t(),await n;let r=e.path.length===1&&e.path[0]===`update`,i=Fn();i&&!r&&(An(i,e.identity.version)?await zn(e.identity.version,i,e.identity.npmPackage,e.identity.clientName,{output:e.output,binName:e.identity.binName,...e.identity.commandInvocation?{commandPrefix:O(e.identity)}:{}}):e.output.warning({code:`UPDATE_AVAILABLE`,message:{"en-US":`Update available: ${e.identity.version} → ${i}. Run ${O(e.identity,`update`)} to upgrade.`,"zh-CN":`发现新版本:${e.identity.version} → ${i}。运行 ${O(e.identity,`update`)} 升级。`},details:{current_version:e.identity.version,latest_version:i,upgrade_command:`${O(e.identity,`update`)}`}}))},Zn=async(e,t)=>{if(e.command.prepare||e.command.risk===void 0||e.confirmed||e.settings.dryRun){await t();return}throw new Ut({message:e.localize(e.command.risk.message),hint:e.localize(Ht())})},Qn=async e=>{await Vn(e)&&await e.command.run(e)};function $n(e,t){return e[t]?.trim()||void 0}function er(e=process.env){return{httpProxy:$n(e,`HTTP_PROXY`),httpsProxy:$n(e,`HTTPS_PROXY`),noProxy:$n(e,`NO_PROXY`)}}function tr(){let{httpProxy:e,httpsProxy:n,noProxy:r}=er();if(e||n)try{qe(new Ke({httpProxy:e,httpsProxy:n,noProxy:r}))}catch(e){throw new t(`Invalid proxy configuration: ${e instanceof Error?e.message:String(e)}`,l.USAGE,`Check HTTP_PROXY / HTTPS_PROXY values, e.g. export HTTPS_PROXY=http://127.0.0.1:7890`,{cause:e})}}function nr(e){let{output:n,quiet:r,verbose:i}=e.settings,a=e.stdout??process.stdout,o=e.stderr??process.stderr,s=I(`en-US`),c=e.localize??(e=>s.localize(e)),l=!1,u;function d(e,t){let r=en(t,c);if(n===`json`)o.write(JSON.stringify({[e]:r})+`
43
43
  `);else{let t=e===`warning`?c({"en-US":`Warning`,"zh-CN":`警告`}):`debug`,n=r.details===void 0?``:` ${JSON.stringify(r.details)}`;o.write(Je(`${t}: ${r.message}${n}`)+`
44
44
  `)}}function f(e){n===`text`&&!r&&o.write(Je(en(e,c).message)+`
45
45
  `)}return{output:{result(e,r){if(l)throw new t(c({"en-US":`A final result has already been written.`,"zh-CN":`最终结果已经输出,不能重复输出。`}));let i=n===`text`&&r?.text!==void 0?r.text:k(e,n);if(typeof i!=`string`)throw new t(c({"en-US":`The final result is not serializable.`,"zh-CN":`最终结果无法序列化。`}));a.write(i+`
@@ -47,7 +47,7 @@ ${l?`${l}\n\n`:``}${i(this.localize(z.gettingHelp))}
47
47
  `)}else{let e=[];if(a instanceof Ut){let t=a.toJSON().error;t.plan!==void 0&&e.push(JSON.stringify({plan:t.plan,notices:t.notices??[]},null,2))}let t=(t,n)=>e.push(`${c(t)}: ${n}`);if(t({"en-US":`Error`,"zh-CN":`错误`},a.message),s&&t({"en-US":`Hint`,"zh-CN":`提示`},s),a.api?.httpStatus!==void 0){let e=a.api.apiCode?` (${a.api.apiCode})`:``;t({"en-US":`Status`,"zh-CN":`状态`},`HTTP ${a.api.httpStatus}${e}`)}else a.api?.apiCode&&t({"en-US":`Code`,"zh-CN":`错误码`},a.api.apiCode);a.api?.requestId&&t({"en-US":`Request ID`,"zh-CN":`请求 ID`},a.api.requestId);let n=a.cause,i=/* @__PURE__ */ new Set;for(;n instanceof Error&&i.size<5&&!i.has(n);){i.add(n);let e=n.code;if(a===r||n!==r||n.message!==a.message||e){let r=n.message;t({"en-US":`Caused by`,"zh-CN":`原因`},e?`${e}: ${r}`:r)}n=n.cause}t({"en-US":`Exit code`,"zh-CN":`退出码`},a.exitCode),o.write(Je(e.join(`
48
48
  `))+`
49
49
  `)}return u=a.exitCode,u}}}function rr(e){return P(ae(),`plugins`,e.npmPackage)}function ir(e){return P(rr(e),`package.json`)}function ar(e,t){return P(rr(e),`node_modules`,...t.split(`/`))}async function or(e){try{return JSON.parse(await tt(e,`utf8`))}catch(n){throw new t(`Could not parse JSON file: ${e}`,l.GENERAL,`Repair or remove the invalid file and try again.`,{cause:n})}}async function sr(e){let t=ir(e);return Ye(t)?or(t):{dependencies:{}}}async function cr(e,t){return lr(ar(e,t))}async function lr(e){return or(P(e,`package.json`))}const ur=/* @__PURE__ */ new Set([`none`,`apiKey`,`console`,`openapi`]),dr=/^[a-z0-9][a-z0-9-]*$/;function fr(e,t,r){if(t.name!==e)throw Error(`Package name mismatch: expected "${e}", received "${t.name??``}".`);let i=t.bailianCli;if(!i||i.type!==`command-pack`)throw Error(`Package "${e}" is missing bailianCli.type="command-pack".`);if(i.apiVersion!==n)throw Error(`Command Pack API ${i.apiVersion} is not supported; this CLI supports API ${n}.`);if(i.minCliVersion&&On(r.version,i.minCliVersion)<0)throw Error(`Command Pack requires ${r.npmPackage} ${i.minCliVersion} or newer; current version is ${r.version}.`);if(!i.entry||lt(i.entry))throw Error(`Command Pack "${e}" must declare a relative bailianCli.entry.`);return i}function pr(e,t){let n=e.split(/\s+/).filter(Boolean).join(` `);if(!e||e!==n||!e.split(` `).every(e=>dr.test(e)))throw Error(`Invalid command path "${e}".`);if(!t.commandPrefixes.some(t=>e===t||e.startsWith(`${t} `)))throw Error(`Command "${e}" is outside the allowed prefixes: ${t.commandPrefixes.join(`, `)}.`)}function mr(e){if(typeof e==`string`)return e.length>0;if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return p.every(e=>typeof t[e]==`string`&&t[e].length>0)}function hr(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.level===`high`&&mr(t.message)}function gr(e,t){if(!t||typeof t!=`object`)throw Error(`Command "${e}" must export an object.`);let n=t;if(!mr(n.description))throw Error(`Command "${e}" is missing a description.`);if(!n.auth||!ur.has(n.auth))throw Error(`Command "${e}" has an invalid auth requirement.`);if(n.risk!==void 0&&!hr(n.risk))throw Error(`Command "${e}" has invalid risk metadata.`);if(typeof n.run!=`function`)throw Error(`Command "${e}" is missing run(ctx).`)}function _r(e,n,r){return Object.fromEntries(Object.entries(n).map(([n,i])=>[n,{description:i.description,auth:i.auth,risk:i.risk,usageArgs:i.usageArgs,exampleArgs:i.exampleArgs,notes:i.notes,flags:i.flags,validate:i.validate,run:async a=>{let o=!1,s=!1,c,u=[],d={identity:a.identity,settings:a.settings,flags:a.flags,client:a.client,output:{result(e,n){if(o)throw s=!0,new t(a.localize({"en-US":`A Command Pack submitted more than one final result.`,"zh-CN":`Command Pack 提交了多个最终结果。`}));let r=a.settings.output===`json`?k(e,`json`):void 0;if(a.settings.output===`json`&&typeof r!=`string`)throw new t(a.localize({"en-US":`The final result is not serializable.`,"zh-CN":`最终结果无法序列化。`}));let i=a.settings.output===`text`?n?.text??k(e,`text`):``;o=!0,c=r===void 0?e:JSON.parse(r),u.push(`${i}\n`)},line(e){u.push(`${e}\n`)},write(e){u.push(e)}},errors:{general(e,n){return new t(e,l.GENERAL,n?.hint,{cause:n?.cause})},usage(e,t){return new m(e,t)},timeout(e=`Request timed out.`,n){return new t(e,l.TIMEOUT,n?.hint,{cause:n?.cause})}},credentials:{apiKey(){if(!r.credentialAccess?.includes(`apiKey`))throw new t(`Command Pack "${e}" is not allowed to access API-key credentials.`,l.GENERAL);if(i.auth!==`apiKey`)throw new t(`Command "${n}" must declare auth="apiKey" before accessing API-key credentials.`,l.GENERAL);let o=a.client.exportApiCredential();if(!o)throw new t(`No API key available to the Command Pack.`,l.AUTH);return o}}};try{await i.run(d)}finally{if(!s&&(o||u.length>0)){let e=u.join(``);a.output.result(o?c:e,{text:e.endsWith(`
50
- `)?e.slice(0,-1):e})}}}}]))}async function vr(e,t,n,r,i=ar(r,e)){let a=fr(e,t,r),o=await it(i),s=await it(dt(o,a.entry)),c=ut(o,s);if(!c||c.startsWith(`..`)||lt(c))throw Error(`Command Pack entry must stay inside the package root: ${a.entry}`);let l=(await import(ft(s).href)).default;if(!l||typeof l!=`object`||Array.isArray(l))throw Error(`Command Pack "${e}" must default-export a command map.`);let u=Object.entries(l);if(u.length===0)throw Error(`Command Pack "${e}" does not export any commands.`);for(let[e,t]of u)pr(e,n),gr(e,t);let d=_r(e,l,n);return new qt(d,r.binName),d}function yr(e){return e.startsWith(`file:`)?`linked`:`installed`}async function br(e,t,n){let r={...e},i=[],a;try{a=await sr(t)}catch(e){return{commands:r,reports:[{name:`(plugin sandbox)`,source:`installed`,status:`failed`,commands:[],error:e instanceof Error?e.message:String(e)}]}}for(let[e,o]of Object.entries(a.dependencies??{}).sort(([e],[t])=>e.localeCompare(t))){let a=yr(o),s=n.supported[e];if(!s){i.push({name:e,source:a,status:`failed`,commands:[],error:`Command Pack "${e}" is not supported by ${t.binName}.`});continue}try{let n=await cr(t,e),o=await vr(e,n,s,t),c=Object.keys(o).filter(e=>e in r);if(c.length>0)throw Error(`Command conflicts: ${c.join(`, `)}.`);Object.assign(r,o),i.push({name:e,version:n.version,source:a,status:`loaded`,commands:Object.keys(o).sort()})}catch(t){i.push({name:e,source:a,status:`failed`,commands:[],error:t instanceof Error?t.message:String(t)})}}return{commands:r,reports:i}}const xr={name:`bailian-cli-command-packs`,private:!0,dependencies:{}},Sr=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.HOME.USER.LOGNAME.SHELL.TMPDIR.TEMP.TMP.LANG.TERM.NODE.NODE_PATH.NODE_OPTIONS.FORCE_COLOR.NO_COLOR.NPM_TOKEN.NODE_AUTH_TOKEN.HTTP_PROXY.HTTPS_PROXY.NO_PROXY.http_proxy.https_proxy.no_proxy.SystemRoot.ComSpec.APPDATA.PATHEXT`.split(`.`)),Cr=/* @__PURE__ */ new Set([`registry`,`userconfig`,`globalconfig`,`cache`,`proxy`,`https_proxy`,`noproxy`,`strict_ssl`,`ca`,`cafile`]);function wr(e){let t=/^(?:npm_config_|NPM_CONFIG_)(.+)$/.exec(e);return!!t&&Cr.has(t[1].toLowerCase())}function Tr(e,t){let n=Object.keys(t.supported);return n.length>0?`Allowed packages: ${n.join(`, `)}`:`${e.binName} does not currently support any Command Packs.`}function Er(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(Sr.has(n)||n.startsWith(`LC_`)||wr(n))&&(t[n]=r);return t}async function Dr(e){await j(e,{recursive:!0,mode:448});let t=P(e,`package.json`);Ye(t)||await st(t,`${JSON.stringify(xr,null,2)}\n`,{mode:384})}async function Or(e,n,r){if(ht(`npm`,[`--version`],{encoding:`utf-8`}).status!==0){let e=se()?"Command Packs need a local npm. Install Node.js, or use `npm install -g bailian-cli` instead of the binary install.":`Install Node.js / npm and retry.`;throw new t(`npm is required to install, link, or remove Command Packs, but was not found on PATH.`,l.GENERAL,e)}await new Promise((i,a)=>{let o=mt(`npm`,e,{cwd:n,env:Er(),stdio:[`inherit`,`pipe`,`pipe`]}),s=kr(r),c=kr(r);o.stdout.on(`data`,e=>s.write(e)),o.stderr.on(`data`,e=>c.write(e)),o.once(`error`,a),o.once(`close`,(n,r)=>{if(s.end(),c.end(),n===0){i();return}a(new t(`npm ${e[0]} failed${r?` with signal ${r}`:` with exit code ${n}`}.`,l.GENERAL))})})}function kr(e){let t=new pt(`utf8`),n=``,r=t=>{/^npm\s+(?:warn(?:ing)?|err(?:or)?)\b/i.test(t)?e.warning({code:`COMMAND_PACK_NPM`,message:t}):t&&e.info(t)};return{write(e){n+=t.write(e);let i=n.split(/\r?\n/);n=i.pop()??``;for(let e of i)r(e)},end(){n+=t.end(),n&&r(n),n=``}}}async function Ar(e){let n=rr(e);await Dr(n);let r=P(n,`.lock`);for(let e=0;e<2;e++)try{let e=await et(r,`wx`,384);return await e.writeFile(`${process.pid} ${Date.now()}\n`),await e.close(),async()=>{try{await N(r)}catch{}}}catch(e){if(e.code!==`EEXIST`)throw e;try{let e=await ot(r);if(Date.now()-e.mtimeMs>6e5){await N(r);continue}}catch{continue}throw new t(`Another Command Pack install, link, or remove operation is already running.`,l.GENERAL,`Wait for it to finish and try again.`)}throw new t(`Could not acquire the Command Pack operation lock.`,l.GENERAL)}async function jr(e,t){let n=await Ar(e);try{return await t()}finally{await n()}}function Mr(e,n,r){let i=e.trim(),a=/^(@[^/\s]+\/[^@/\s]+)(?:@([a-zA-Z0-9][a-zA-Z0-9._-]*))?$/.exec(i);if(!a)throw new t(`Unsupported Command Pack package spec: "${e}".`,l.USAGE,`Use an allowlisted scoped package name with an optional version or tag.`);let o=a[1];if(!r.supported[o])throw new t(`Command Pack "${o}" is not allowlisted for ${n.binName}.`,l.USAGE,Tr(n,r));return{name:o,requested:i}}async function Nr(e,t,n,r){let i=r.supported[e],a=await lr(t);return{pjson:a,commands:await vr(e,a,i,n,t)}}function Pr(e,t){return t.startsWith(`file:`)?t:`${e}@${t}`}async function Fr(e,t,n,r){if(t){await Or([`install`,Pr(e,t),`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],n,r);return}await Or([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],n,r)}async function Ir(e,n,r,i){let{name:a,requested:o}=Mr(e,n,r);return jr(n,async()=>{let e=rr(n),s=(await sr(n)).dependencies?.[a];try{await Or([`install`,o,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],e,i);let s=await Nr(a,ar(n,a),n,r);if(!s.pjson.version)throw new t(`Command Pack "${a}" has no package version.`,l.USAGE);return{name:a,version:s.pjson.version,commands:Object.keys(s.commands).sort()}}catch(t){try{await Fr(a,s,e,i)}catch{}throw t}})}async function Lr(e,n,r,i){let a=dt(e);if(!Ye(P(a,`package.json`)))throw new t(`Command Pack path does not exist: ${a}`,l.USAGE);let o=(await lr(a)).name;if(!o||!r.supported[o])throw new t(`Local package "${o??`(unnamed)`}" is not an allowlisted Command Pack for ${n.binName}.`,l.USAGE,Tr(n,r));let s=await Nr(o,a,n,r);return jr(n,async()=>{await Or([`install`,`file:${a}`,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],rr(n),i);let e=await Nr(o,ar(n,o),n,r);return{name:o,version:e.pjson.version??s.pjson.version,commands:Object.keys(e.commands).sort()}})}async function Rr(e,n,r,i){if(!r.supported[e])throw new t(`Command Pack "${e}" is not allowlisted for ${n.binName}.`,l.USAGE,Tr(n,r));if(!(e in((await sr(n)).dependencies??{})))throw new t(`Command Pack "${e}" is not installed.`,l.USAGE);await jr(n,()=>Or([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],rr(n),i))}async function zr(e,t){return(await br({},e,t)).reports}function Br(e,t,n){return{install:r=>Ir(r,e,t,n),link:r=>Lr(r,e,t,n),list:()=>zr(e,t),remove:r=>Rr(r,e,t,n)}}function Vr(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Hr(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)break;if(r===`--quiet`)t.quiet=!0;else if(r===`--verbose`)t.verbose=!0;else for(let i of[`output`,`config`])if(r.startsWith(`--${i}=`))t[i]=r.slice(i.length+3);else if(r===`--${i}`){let r=e[n+1];r!==void 0&&!r.startsWith(`--`)&&(t[i]=r,n++)}}return t}const Ur=/* @__PURE__ */ new Set,Wr=/* @__PURE__ */ new Set;function Gr(e){let t=()=>e();return Wr.add(t),process.on(`SIGINT`,t),()=>{Wr.delete(t),process.removeListener(`SIGINT`,t)}}function Kr(){if(Wr.size>0)return;let e=Ur.values().next().value;e&&(e.getReporter().error(new t(e.localize({"en-US":`Interrupted. Exiting.`,"zh-CN":`操作已中断,正在退出。`}),130)),ie(500).finally(()=>process.exit(130)))}function qr(e){e.code===`EPIPE`&&process.exit(0);let t=Ur.values().next().value;if(t&&process.exit(t.getReporter().error(e)),process.stdout.listenerCount(`error`)===1)throw e}function Jr(e,t){process.stdout.listeners(`error`).includes(qr)||process.stdout.on(`error`,qr),Ur.size===0&&process.on(`SIGINT`,Kr);let n={getReporter:e,localize:t};return Ur.add(n),()=>{Ur.delete(n),Ur.size===0&&process.removeListener(`SIGINT`,Kr)}}function Yr(e,t){let{binName:n,version:r,npmPackage:a,clientName:o}=t,s={binName:n,version:r,npmPackage:a,clientName:o,...t.commandInvocation?{commandInvocation:t.commandInvocation}:{}},l=O(s),d=t.commandPacks??{supported:{}},f,p=qn([Yn,Zn,Xn,Jn,Qn]);function h(){return f||=br(e,s,d),f}async function g(e){return new qt((await h()).commands,l,e)}function _(e,n,r){if(e.printHelp(n,process.stderr),n.length>0)return;let i=!1;try{let e=te(r);i=!!(e.apiKey||e.console)}catch{}i?t.quickStartTasks?.length&&e.printQuickStart(t.quickStartTasks):e.printWelcome()}async function v(e,t,n,a,o){let c=Jt(t,e,n),f=c.kind===`run`||c.kind===`usageError`?c.command:void 0,h=x({...a,flags:c.kind===`run`?c.parsedFlags:a.flags});f?.defaultOutput!==void 0&&((h.outputSource==="default"||h.outputSource===`file`&&f.defaultOutputOverridesProfile)&&(h.output=h.outputSource==="default"&&process.stdout.isTTY?f.defaultInteractiveOutput??f.defaultOutput:f.defaultOutput),h.outputExplicit=!0),c.kind===`run`&&f?.verboseFlags?.some(e=>!!c.parsedFlags[e])&&(h.verbose=!0);let g=o(h);switch(c.kind){case`introspect`:process.stdout.write($t(Qt(e,s,c.path)));return;case`version`:process.stdout.write(`${l} ${r}\n`);return;case`help`:_(e,c.path,{...a,flags:c.parsedFlags});return;case`usageError`:throw c.error;case`run`:try{let t=E(c.command),r=c.parsedFlags,o=Vr(r,[...Object.keys(u),...Object.keys(t)]),l=Vr(r,Object.keys(c.command.flags??{})),f=await c.command.validate?.(l);if(f)throw new m(n(f));let _={...a,flags:o},v={...S(_),...h},y={commandPath:t=>e.commandPath(t),identity:s,output:g.output,path:c.path,command:c.command,flags:l,confirmed:r.yes===!0,localize:n,settings:v,sources:_,configStore:de(_.configName),authStore:ue(_),commandPacks:Br(s,d,g.output),client:new i({identity:s,settings:v,debug:e=>g.output.debug(e),...Ce(_)})};await p(y),await ie(1e3)}catch(t){if(t instanceof m&&c.rest.length===0){e.printHelp(c.path,process.stderr);return}throw t}return}}return{async run(e=process.argv.slice(2)){let t=Hr(e),n=I(c),r=e=>n.localize(e),i=nr({settings:x({flags:t,env:process.env}),localize:r,commandPrefix:l}),a=[],o=Jr(()=>i,r);try{let o=C(t,e=>a.push(e));n=I(o.file.language??c),i=nr({settings:x(o),localize:r,commandPrefix:l}),tr(),await v(await g(n),e,r,o,e=>{i=nr({settings:e,localize:r,commandPrefix:l});for(let e of a.splice(0))i.output.warning(e);return i})}catch(e){for(let e of a.splice(0))i.output.warning(e);await ie(1e3),dn(e,i)}finally{o()}}}}const Xr=`2.8.1`;function Zr(e,t,{gap:n=2}={}){let r=e.map((e,n)=>{let r=e.length;for(let e of t){let t=e[n]??``;t.length>r&&(r=t.length)}return r}),i=` `.repeat(n),a=e=>e.map((e,t)=>(e??``).padEnd(r[t])).join(i),o=[];o.push(a(e));for(let e of t)o.push(a(e));return o}function Qr(e){return e>=11904&&e<=40959||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=195103}function B(e){let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=Qr(e)?2:1}return t}function $r(e,t){let n=t-B(e);return n>0?e+` `.repeat(n):e}const ei=` │ `,ti=[0,150,160],ni=[176,205,250],ri=[160,160,170];function ii(e){if(`NO_COLOR`in process.env)return 0;let t=process.env.FORCE_COLOR;if(t!=null){if(t===`0`||t===`false`)return 0;if(t===`3`||t===`truecolor`)return 3;if(t===`2`)return 2;if(t===`1`||t===`true`||t===``)return 1}if(!Nt(e))return 0;let n=process.env.COLORTERM;if(n===`truecolor`||n===`24bit`)return 3;let r=process.env.TERM??``;return r===`dumb`?1:/-256(color)?$/i.test(r)?2:1}function ai(e,t,n){return e===t&&t===n?e<8?16:e>248?231:232+Math.round((e-8)/247*24):16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)}function oi(e,t,n,r){let i=Math.max(e,t,n)>127,a=i?128:64;return(r===48?i?100:40:i?90:30)+(e>=a|(t>=a?2:0)|(n>=a?4:0))}function si(e,t,n,r,i=38){return e>=3?`${i};2;${t};${n};${r}`:e===2?`${i};5;${ai(t,n,r)}`:String(oi(t,n,r,i))}function ci(e,[t,n,r],i){return e<=0?i:`\x1b[${si(e,t,n,r)}m${i}\x1b[0m`}function li(e,t,n){return t<=0?e:`\x1b[1;${si(t,255,255,255,38)};${si(t,n[0],n[1],n[2],48)}m${e}\x1b[0m`}function ui(e,t){let n=t-B(e);return n>0?` `.repeat(n)+e:e}function di(e,t,n=20,r=process.stdout){return fi(e,t,n,ii(r))}function fi(e,t,n,r){let i=e==null?0:Math.max(0,Math.min(100,e)),a=e!=null,o=a?Math.round(i/100*n):0,s=``,c=``;for(let e=0;e<n;e++)a&&e<o?(s+=`█`,c+=ci(r,ti,`█`)):(s+=` `,c+=` `);let l=a?ni:ri;return s+=` ${t}`,c+=` ${ci(r,l,t)}`,{plain:s,colored:c}}function pi(e){let t=ii(e.out??process.stdout),n=e.align??[],r=e.barColumns??[],i=e.headers.length,a={};for(let n of r){let r=n.width??20,i=[];for(let a=0;a<e.rows.length;a++){let e=n.percents[a]??null,o=n.labels?.[a]??(e==null?`-`:`${Number.isInteger(e)?e:e.toFixed(1)}%`);i.push(fi(e,o,r,t))}a[n.index]=i}let o=(t,n)=>a[n]?a[n][t].plain:e.rows[t][n]??``,s=e.headers.map((t,n)=>{let r=B(t);for(let t=0;t<e.rows.length;t++){let e=B(o(t,n));e>r&&(r=e)}return r}),c=[],l=e.headers.map((e,t)=>n[t]===`right`?ui(e,s[t]):$r(e,s[t])).join(ei),u=Math.max(B(l),...e.rows.map((e,t)=>B(Array.from({length:i},(e,n)=>o(t,n)).join(ei))));c.push(li(` ${$r(l,u)} `,t,ti));let d=` ${ci(t,ti,`│`)} `;for(let t=0;t<e.rows.length;t++){let r=[];for(let o=0;o<i;o++){let i=s[o];if(a[o]){let e=a[o][t],n=i-B(e.plain);r.push(n>0?e.colored+` `.repeat(n):e.colored);continue}let c=e.rows[t][o]??``,l=e.cellColor?.(t,o,c),u=n[o]===`right`?ui(c,i):$r(c,i);l?r.push(n[o]===`right`?u.slice(0,u.length-c.length)+l:l+u.slice(c.length)):r.push(u)}let o=` `;for(let e=0;e<i;e++)o+=r[e],e<i-1&&(o+=d);c.push(o)}return c}function mi(e,t=``){let n=process.stderr.isTTY;return{update(r){if(!n)return;let i=Math.min(1,r/e),a=Math.round(30*i),o=30-a,s=`█`.repeat(a)+`░`.repeat(o),c=`${Math.round(i*100)}%`;process.stderr.write(`\r${t} ${s} ${c}`)},finish(){n&&process.stderr.write(`
50
+ `)?e.slice(0,-1):e})}}}}]))}async function vr(e,t,n,r,i=ar(r,e)){let a=fr(e,t,r),o=await it(i),s=await it(dt(o,a.entry)),c=ut(o,s);if(!c||c.startsWith(`..`)||lt(c))throw Error(`Command Pack entry must stay inside the package root: ${a.entry}`);let l=(await import(ft(s).href)).default;if(!l||typeof l!=`object`||Array.isArray(l))throw Error(`Command Pack "${e}" must default-export a command map.`);let u=Object.entries(l);if(u.length===0)throw Error(`Command Pack "${e}" does not export any commands.`);for(let[e,t]of u)pr(e,n),gr(e,t);let d=_r(e,l,n);return new qt(d,r.binName),d}function yr(e){return e.startsWith(`file:`)?`linked`:`installed`}async function br(e,t,n){let r={...e},i=[],a;try{a=await sr(t)}catch(e){return{commands:r,reports:[{name:`(plugin sandbox)`,source:`installed`,status:`failed`,commands:[],error:e instanceof Error?e.message:String(e)}]}}for(let[e,o]of Object.entries(a.dependencies??{}).sort(([e],[t])=>e.localeCompare(t))){let a=yr(o),s=n.supported[e];if(!s){i.push({name:e,source:a,status:`failed`,commands:[],error:`Command Pack "${e}" is not supported by ${t.binName}.`});continue}try{let n=await cr(t,e),o=await vr(e,n,s,t),c=Object.keys(o).filter(e=>e in r);if(c.length>0)throw Error(`Command conflicts: ${c.join(`, `)}.`);Object.assign(r,o),i.push({name:e,version:n.version,source:a,status:`loaded`,commands:Object.keys(o).sort()})}catch(t){i.push({name:e,source:a,status:`failed`,commands:[],error:t instanceof Error?t.message:String(t)})}}return{commands:r,reports:i}}const xr={name:`bailian-cli-command-packs`,private:!0,dependencies:{}},Sr=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.HOME.USER.LOGNAME.SHELL.TMPDIR.TEMP.TMP.LANG.TERM.NODE.NODE_PATH.NODE_OPTIONS.FORCE_COLOR.NO_COLOR.NPM_TOKEN.NODE_AUTH_TOKEN.HTTP_PROXY.HTTPS_PROXY.NO_PROXY.http_proxy.https_proxy.no_proxy.SystemRoot.ComSpec.APPDATA.PATHEXT`.split(`.`)),Cr=/* @__PURE__ */ new Set([`registry`,`userconfig`,`globalconfig`,`cache`,`proxy`,`https_proxy`,`noproxy`,`strict_ssl`,`ca`,`cafile`]);function wr(e){let t=/^(?:npm_config_|NPM_CONFIG_)(.+)$/.exec(e);return!!t&&Cr.has(t[1].toLowerCase())}function Tr(e,t){let n=Object.keys(t.supported);return n.length>0?`Allowed packages: ${n.join(`, `)}`:`${e.binName} does not currently support any Command Packs.`}function Er(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(Sr.has(n)||n.startsWith(`LC_`)||wr(n))&&(t[n]=r);return t}async function Dr(e){await j(e,{recursive:!0,mode:448});let t=P(e,`package.json`);Ye(t)||await st(t,`${JSON.stringify(xr,null,2)}\n`,{mode:384})}async function Or(e,n,r){if(ht(`npm`,[`--version`],{encoding:`utf-8`}).status!==0){let e=se()?"Command Packs need a local npm. Install Node.js, or use `npm install -g bailian-cli` instead of the binary install.":`Install Node.js / npm and retry.`;throw new t(`npm is required to install, link, or remove Command Packs, but was not found on PATH.`,l.GENERAL,e)}await new Promise((i,a)=>{let o=mt(`npm`,e,{cwd:n,env:Er(),stdio:[`inherit`,`pipe`,`pipe`]}),s=kr(r),c=kr(r);o.stdout.on(`data`,e=>s.write(e)),o.stderr.on(`data`,e=>c.write(e)),o.once(`error`,a),o.once(`close`,(n,r)=>{if(s.end(),c.end(),n===0){i();return}a(new t(`npm ${e[0]} failed${r?` with signal ${r}`:` with exit code ${n}`}.`,l.GENERAL))})})}function kr(e){let t=new pt(`utf8`),n=``,r=t=>{/^npm\s+(?:warn(?:ing)?|err(?:or)?)\b/i.test(t)?e.warning({code:`COMMAND_PACK_NPM`,message:t}):t&&e.info(t)};return{write(e){n+=t.write(e);let i=n.split(/\r?\n/);n=i.pop()??``;for(let e of i)r(e)},end(){n+=t.end(),n&&r(n),n=``}}}async function Ar(e){let n=rr(e);await Dr(n);let r=P(n,`.lock`);for(let e=0;e<2;e++)try{let e=await et(r,`wx`,384);return await e.writeFile(`${process.pid} ${Date.now()}\n`),await e.close(),async()=>{try{await N(r)}catch{}}}catch(e){if(e.code!==`EEXIST`)throw e;try{let e=await ot(r);if(Date.now()-e.mtimeMs>6e5){await N(r);continue}}catch{continue}throw new t(`Another Command Pack install, link, or remove operation is already running.`,l.GENERAL,`Wait for it to finish and try again.`)}throw new t(`Could not acquire the Command Pack operation lock.`,l.GENERAL)}async function jr(e,t){let n=await Ar(e);try{return await t()}finally{await n()}}function Mr(e,n,r){let i=e.trim(),a=/^(@[^/\s]+\/[^@/\s]+)(?:@([a-zA-Z0-9][a-zA-Z0-9._-]*))?$/.exec(i);if(!a)throw new t(`Unsupported Command Pack package spec: "${e}".`,l.USAGE,`Use an allowlisted scoped package name with an optional version or tag.`);let o=a[1];if(!r.supported[o])throw new t(`Command Pack "${o}" is not allowlisted for ${n.binName}.`,l.USAGE,Tr(n,r));return{name:o,requested:i}}async function Nr(e,t,n,r){let i=r.supported[e],a=await lr(t);return{pjson:a,commands:await vr(e,a,i,n,t)}}function Pr(e,t){return t.startsWith(`file:`)?t:`${e}@${t}`}async function Fr(e,t,n,r){if(t){await Or([`install`,Pr(e,t),`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],n,r);return}await Or([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],n,r)}async function Ir(e,n,r,i){let{name:a,requested:o}=Mr(e,n,r);return jr(n,async()=>{let e=rr(n),s=(await sr(n)).dependencies?.[a];try{await Or([`install`,o,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],e,i);let s=await Nr(a,ar(n,a),n,r);if(!s.pjson.version)throw new t(`Command Pack "${a}" has no package version.`,l.USAGE);return{name:a,version:s.pjson.version,commands:Object.keys(s.commands).sort()}}catch(t){try{await Fr(a,s,e,i)}catch{}throw t}})}async function Lr(e,n,r,i){let a=dt(e);if(!Ye(P(a,`package.json`)))throw new t(`Command Pack path does not exist: ${a}`,l.USAGE);let o=(await lr(a)).name;if(!o||!r.supported[o])throw new t(`Local package "${o??`(unnamed)`}" is not an allowlisted Command Pack for ${n.binName}.`,l.USAGE,Tr(n,r));let s=await Nr(o,a,n,r);return jr(n,async()=>{await Or([`install`,`file:${a}`,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],rr(n),i);let e=await Nr(o,ar(n,o),n,r);return{name:o,version:e.pjson.version??s.pjson.version,commands:Object.keys(e.commands).sort()}})}async function Rr(e,n,r,i){if(!r.supported[e])throw new t(`Command Pack "${e}" is not allowlisted for ${n.binName}.`,l.USAGE,Tr(n,r));if(!(e in((await sr(n)).dependencies??{})))throw new t(`Command Pack "${e}" is not installed.`,l.USAGE);await jr(n,()=>Or([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],rr(n),i))}async function zr(e,t){return(await br({},e,t)).reports}function Br(e,t,n){return{install:r=>Ir(r,e,t,n),link:r=>Lr(r,e,t,n),list:()=>zr(e,t),remove:r=>Rr(r,e,t,n)}}function Vr(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Hr(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)break;if(r===`--quiet`)t.quiet=!0;else if(r===`--verbose`)t.verbose=!0;else for(let i of[`output`,`config`])if(r.startsWith(`--${i}=`))t[i]=r.slice(i.length+3);else if(r===`--${i}`){let r=e[n+1];r!==void 0&&!r.startsWith(`--`)&&(t[i]=r,n++)}}return t}const Ur=/* @__PURE__ */ new Set,Wr=/* @__PURE__ */ new Set;function Gr(e){let t=()=>e();return Wr.add(t),process.on(`SIGINT`,t),()=>{Wr.delete(t),process.removeListener(`SIGINT`,t)}}function Kr(){if(Wr.size>0)return;let e=Ur.values().next().value;e&&(e.getReporter().error(new t(e.localize({"en-US":`Interrupted. Exiting.`,"zh-CN":`操作已中断,正在退出。`}),130)),ie(500).finally(()=>process.exit(130)))}function qr(e){e.code===`EPIPE`&&process.exit(0);let t=Ur.values().next().value;if(t&&process.exit(t.getReporter().error(e)),process.stdout.listenerCount(`error`)===1)throw e}function Jr(e,t){process.stdout.listeners(`error`).includes(qr)||process.stdout.on(`error`,qr),Ur.size===0&&process.on(`SIGINT`,Kr);let n={getReporter:e,localize:t};return Ur.add(n),()=>{Ur.delete(n),Ur.size===0&&process.removeListener(`SIGINT`,Kr)}}function Yr(e,t){let{binName:n,version:r,npmPackage:a,clientName:o}=t,s={binName:n,version:r,npmPackage:a,clientName:o,...t.commandInvocation?{commandInvocation:t.commandInvocation}:{}},l=O(s),d=t.commandPacks??{supported:{}},f,p=qn([Yn,Zn,Xn,Jn,Qn]);function h(){return f||=br(e,s,d),f}async function g(e){return new qt((await h()).commands,l,e)}function _(e,n,r){if(e.printHelp(n,process.stderr),n.length>0)return;let i=!1;try{let e=te(r);i=!!(e.apiKey||e.console)}catch{}i?t.quickStartTasks?.length&&e.printQuickStart(t.quickStartTasks):e.printWelcome()}async function v(e,t,n,a,o){let c=Jt(t,e,n),f=c.kind===`run`||c.kind===`usageError`?c.command:void 0,h=x({...a,flags:c.kind===`run`?c.parsedFlags:a.flags});f?.defaultOutput!==void 0&&((h.outputSource==="default"||h.outputSource===`file`&&f.defaultOutputOverridesProfile)&&(h.output=h.outputSource==="default"&&process.stdout.isTTY?f.defaultInteractiveOutput??f.defaultOutput:f.defaultOutput),h.outputExplicit=!0),c.kind===`run`&&f?.verboseFlags?.some(e=>!!c.parsedFlags[e])&&(h.verbose=!0);let g=o(h);switch(c.kind){case`introspect`:process.stdout.write($t(Qt(e,s,c.path)));return;case`version`:process.stdout.write(`${l} ${r}\n`);return;case`help`:_(e,c.path,{...a,flags:c.parsedFlags});return;case`usageError`:throw c.error;case`run`:try{let t=E(c.command),r=c.parsedFlags,o=Vr(r,[...Object.keys(u),...Object.keys(t)]),l=Vr(r,Object.keys(c.command.flags??{})),f=await c.command.validate?.(l);if(f)throw new m(n(f));let _={...a,flags:o},v={...S(_),...h},y={commandPath:t=>e.commandPath(t),identity:s,output:g.output,path:c.path,command:c.command,flags:l,confirmed:r.yes===!0,localize:n,settings:v,sources:_,configStore:de(_.configName),authStore:ue(_),commandPacks:Br(s,d,g.output),client:new i({identity:s,settings:v,debug:e=>g.output.debug(e),...Ce(_)})};await p(y),await ie(1e3)}catch(t){if(t instanceof m&&c.rest.length===0){e.printHelp(c.path,process.stderr);return}throw t}return}}return{async run(e=process.argv.slice(2)){let t=Hr(e),n=I(c),r=e=>n.localize(e),i=nr({settings:x({flags:t,env:process.env}),localize:r,commandPrefix:l}),a=[],o=Jr(()=>i,r);try{let o=C(t,e=>a.push(e));n=I(o.file.language??c),i=nr({settings:x(o),localize:r,commandPrefix:l}),tr(),await v(await g(n),e,r,o,e=>{i=nr({settings:e,localize:r,commandPrefix:l});for(let e of a.splice(0))i.output.warning(e);return i})}catch(e){for(let e of a.splice(0))i.output.warning(e);await ie(1e3),dn(e,i)}finally{o()}}}}const Xr=`2.8.3`;function Zr(e,t,{gap:n=2}={}){let r=e.map((e,n)=>{let r=e.length;for(let e of t){let t=e[n]??``;t.length>r&&(r=t.length)}return r}),i=` `.repeat(n),a=e=>e.map((e,t)=>(e??``).padEnd(r[t])).join(i),o=[];o.push(a(e));for(let e of t)o.push(a(e));return o}function Qr(e){return e>=11904&&e<=40959||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=195103}function B(e){let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=Qr(e)?2:1}return t}function $r(e,t){let n=t-B(e);return n>0?e+` `.repeat(n):e}const ei=` │ `,ti=[0,150,160],ni=[176,205,250],ri=[160,160,170];function ii(e){if(`NO_COLOR`in process.env)return 0;let t=process.env.FORCE_COLOR;if(t!=null){if(t===`0`||t===`false`)return 0;if(t===`3`||t===`truecolor`)return 3;if(t===`2`)return 2;if(t===`1`||t===`true`||t===``)return 1}if(!Nt(e))return 0;let n=process.env.COLORTERM;if(n===`truecolor`||n===`24bit`)return 3;let r=process.env.TERM??``;return r===`dumb`?1:/-256(color)?$/i.test(r)?2:1}function ai(e,t,n){return e===t&&t===n?e<8?16:e>248?231:232+Math.round((e-8)/247*24):16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)}function oi(e,t,n,r){let i=Math.max(e,t,n)>127,a=i?128:64;return(r===48?i?100:40:i?90:30)+(e>=a|(t>=a?2:0)|(n>=a?4:0))}function si(e,t,n,r,i=38){return e>=3?`${i};2;${t};${n};${r}`:e===2?`${i};5;${ai(t,n,r)}`:String(oi(t,n,r,i))}function ci(e,[t,n,r],i){return e<=0?i:`\x1b[${si(e,t,n,r)}m${i}\x1b[0m`}function li(e,t,n){return t<=0?e:`\x1b[1;${si(t,255,255,255,38)};${si(t,n[0],n[1],n[2],48)}m${e}\x1b[0m`}function ui(e,t){let n=t-B(e);return n>0?` `.repeat(n)+e:e}function di(e,t,n=20,r=process.stdout){return fi(e,t,n,ii(r))}function fi(e,t,n,r){let i=e==null?0:Math.max(0,Math.min(100,e)),a=e!=null,o=a?Math.round(i/100*n):0,s=``,c=``;for(let e=0;e<n;e++)a&&e<o?(s+=`█`,c+=ci(r,ti,`█`)):(s+=` `,c+=` `);let l=a?ni:ri;return s+=` ${t}`,c+=` ${ci(r,l,t)}`,{plain:s,colored:c}}function pi(e){let t=ii(e.out??process.stdout),n=e.align??[],r=e.barColumns??[],i=e.headers.length,a={};for(let n of r){let r=n.width??20,i=[];for(let a=0;a<e.rows.length;a++){let e=n.percents[a]??null,o=n.labels?.[a]??(e==null?`-`:`${Number.isInteger(e)?e:e.toFixed(1)}%`);i.push(fi(e,o,r,t))}a[n.index]=i}let o=(t,n)=>a[n]?a[n][t].plain:e.rows[t][n]??``,s=e.headers.map((t,n)=>{let r=B(t);for(let t=0;t<e.rows.length;t++){let e=B(o(t,n));e>r&&(r=e)}return r}),c=[],l=e.headers.map((e,t)=>n[t]===`right`?ui(e,s[t]):$r(e,s[t])).join(ei),u=Math.max(B(l),...e.rows.map((e,t)=>B(Array.from({length:i},(e,n)=>o(t,n)).join(ei))));c.push(li(` ${$r(l,u)} `,t,ti));let d=` ${ci(t,ti,`│`)} `;for(let t=0;t<e.rows.length;t++){let r=[];for(let o=0;o<i;o++){let i=s[o];if(a[o]){let e=a[o][t],n=i-B(e.plain);r.push(n>0?e.colored+` `.repeat(n):e.colored);continue}let c=e.rows[t][o]??``,l=e.cellColor?.(t,o,c),u=n[o]===`right`?ui(c,i):$r(c,i);l?r.push(n[o]===`right`?u.slice(0,u.length-c.length)+l:l+u.slice(c.length)):r.push(u)}let o=` `;for(let e=0;e<i;e++)o+=r[e],e<i-1&&(o+=d);c.push(o)}return c}function mi(e,t=``){let n=process.stderr.isTTY;return{update(r){if(!n)return;let i=Math.min(1,r/e),a=Math.round(30*i),o=30-a,s=`█`.repeat(a)+`░`.repeat(o),c=`${Math.round(i*100)}%`;process.stderr.write(`\r${t} ${s} ${c}`)},finish(){n&&process.stderr.write(`
51
51
  `)}}}async function hi(e,n){let r=Date.now()+n.timeoutSec*1e3,{output:i}=n;for(i.progress({"en-US":`Polling...`,"zh-CN":`正在查询任务状态……`});Date.now()<r;){let r=n.load?await n.load():await e.requestJson({path:n.url});if(n.getStatus){let e=n.getStatus(r);i.progress({"en-US":`Status: ${e}`,"zh-CN":`状态:${e}`})}if(n.isComplete(r))return i.progress({"en-US":`Done.`,"zh-CN":`已完成。`}),r;if(n.isFailed(r)){i.progress({"en-US":`Failed.`,"zh-CN":`任务失败。`}),i.debug({message:{"en-US":`Task response`,"zh-CN":`任务响应`},details:r});let e=n.getErrorMessage?.(r);throw new t(e?`Task failed: ${e}`:`Task failed.`,l.GENERAL,e?void 0:`Use --verbose to see full API response details.`)}await new Promise(e=>setTimeout(e,n.intervalSec*1e3))}throw new t(`Polling timed out.`,l.TIMEOUT,`Try increasing --timeout or check task status manually.`)}async function gi(e,n,r){let i=await A.fetch(e);if(!i.ok)throw new t(`Download failed: HTTP ${i.status}`,l.GENERAL);let a=Number(i.headers.get(`content-length`)||0),o=i.body?.getReader();if(!o)throw new t(`No response body`,l.GENERAL);He(ze(n),{recursive:!0});let s=Ve(n),c=a>0&&!r?.quiet?mi(a,`Downloading`):null,u=0,d=!1;try{let e=new Promise((e,t)=>{s.on(`error`,t)});for(;;){let{done:t,value:n}=await Promise.race([o.read(),e]);if(t)break;s.write(n)||await new Promise(e=>s.once(`drain`,()=>e())),u+=n.byteLength,c?.update(u)}d=!0}finally{if(o.releaseLock(),c?.finish(),await new Promise((e,t)=>{s.on(`finish`,e),s.on(`error`,t),s.end()}),!d)try{We(n)}catch{}}return{size:u}}function _i(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(1)} GB`}function vi(e){return Math.max(1,e.concurrent??1)}async function yi(e,t,n,r=`requests`){if(e<=1)return[await n(0)];t.info({"en-US":`[Concurrent: ${e} ${r}]`,"zh-CN":`[并发:${e} ${r===`tasks`?`个任务`:`个请求`}]`});let i=Array.from({length:e},(e,t)=>n(t));return Promise.all(i)}async function bi(e,t,n){return Promise.all(e.map(({url:e,destPath:r})=>t(e,r,n).then(()=>r)))}const xi={"qwen-image-2.0":{"16:9":`2688*1536`,"9:16":`1536*2688`,"1:1":`2048*2048`,"4:3":`2368*1728`,"3:4":`1728*2368`},"qwen-image-fixed":{"16:9":`1664*928`,"4:3":`1472*1104`,"1:1":`1328*1328`,"3:4":`1104*1472`,"9:16":`928*1664`},wan27:{"16:9":`2688*1536`,"9:16":`1536*2688`,"1:1":`2048*2048`,"4:3":`2368*1728`,"3:4":`1728*2368`},"z-image":{"1:1":`1024*1024`,"16:9":`1280*720`,"9:16":`720*1280`,"4:3":`1152*864`,"3:4":`864*1152`,"3:2":`1248*832`,"2:3":`832*1248`},wan26:{"1:1":`1280*1280`,"16:9":`1696*960`,"9:16":`960*1696`,"4:3":`1472*1104`,"3:4":`1104*1472`},"wan-legacy":{"1:1":`1024*1024`,"16:9":`1280*720`,"9:16":`720*1280`,"3:4":`768*1152`,"4:3":`1152*768`},"wanx-v1":{"1:1":`1024*1024`,"9:16":`720*1280`,"3:4":`768*1152`,"16:9":`1280*720`},"wan25-i2i":{"1:1":`1280*1280`,"16:9":`1280*720`,"9:16":`720*1280`,"4:3":`1152*864`,"3:4":`864*1152`}};function Si(e,t){if(e)return xi[typeof t==`boolean`?t?`qwen-image-2.0`:`qwen-image-fixed`:t][e]??e}var Ci=/* @__PURE__ */ wt({ensureBinaryPathEntries:()=>Bi,ensureWindowsBinJunction:()=>Hi,fetchBinaryChannelManifest:()=>Di,fetchBinaryChannelVersion:()=>Ei,getBinaryBinRoot:()=>wi,getBinaryCurrentPath:()=>Ti,getBinaryShareRoot:()=>V,getBinaryVersionsDir:()=>H,isValidUpdateTargetVersion:()=>Ai,normalizeBinaryVersion:()=>Oi,performBinaryUpdate:()=>Wi,pruneBinaryVersions:()=>Ui,readCurrentVersionDir:()=>Li,resolveBinaryDownloadSpec:()=>Mi,switchCurrentToVersion:()=>zi});function V(){return process.env.BAILIAN_SHARE_DIR?process.env.BAILIAN_SHARE_DIR:process.platform===`win32`?P(process.env.LOCALAPPDATA||P(gt(),`AppData`,`Local`),`bailian-cli`):P(gt(),`.local`,`share`,`bailian-cli`)}function wi(){return process.env.BAILIAN_BIN_DIR?process.env.BAILIAN_BIN_DIR:process.platform===`win32`?P(V(),`bin`):P(gt(),`.local`,`bin`)}function H(){return P(V(),`versions`)}function Ti(){return P(V(),`current`)}async function Ei(e=`latest`,t=5e3){try{let n=await A.fetch(w(e),{signal:AbortSignal.timeout(t)});return n.ok?(await n.json()).version??null:null}catch{return null}}async function Di(e=`latest`,t=8e3){try{let n=await A.fetch(w(e),{signal:AbortSignal.timeout(t)});return n.ok?await n.json():null}catch{return null}}function Oi(e){let t=e.trim();return/^v\d/i.test(t)?t.slice(1):t}const ki=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function Ai(e){let t=e.trim();return t?ki.test(t):!1}async function ji(e,t,n=8e3){try{let r=await A.fetch(me(e,`SHA256SUMS`),{signal:AbortSignal.timeout(n)});if(!r.ok)return;let i=await r.text();for(let e of i.split(`
52
52
  `)){let n=e.trim().match(/^([a-fA-F0-9]{64})\s+(\S+)$/);if(n?.[2]===t)return n[1].toLowerCase()}}catch{}}async function Mi(e){let t=Oi(e),{os:n,arch:r,fileSuffix:i}=D(),a=i===`.exe`,o=h(t,n,r,a),s=g(t,n,r,a),c=me(t,o),l=await ji(t,o);if(!l){let e=await Di(`latest`);e?.version===t&&(l=e.assets?.[`${n}-${r}`]?.sha256)}return{zipName:o,innerName:s,url:c,expectedSha:l}}async function Ni(e,t){let n=await A.fetch(e,{signal:AbortSignal.timeout(12e4)});if(!n.ok||!n.body)throw Error(`Download failed (${n.status}): ${e}`);let r=await n.arrayBuffer(),i=Buffer.from(r);return await j(ct(t),{recursive:!0}),await st(t,i),i}function Pi(e){return _t(`sha256`).update(e).digest(`hex`)}function Fi(){return process.platform===`win32`?`bl.exe`:`bl`}function Ii(){return process.platform===`win32`?`bailian.exe`:`bailian`}async function Li(){let e=Ti();try{let t=await rt(e);return t.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(t)?t:P(ct(e),t)}catch{return null}}function Ri(e){let t=H(),n=e.replaceAll(`\\`,`/`),r=t.replaceAll(`\\`,`/`).replace(/\/$/,``);if(!n.startsWith(`${r}/`)&&n!==r){let t=e.replaceAll(`\\`,`/`).split(`/`).pop();return t&&t!==`versions`?t:null}return n.slice(r.length+1).split(`/`)[0]??null}async function zi(e){let t=P(H(),e),n=Ti();await j(V(),{recursive:!0});try{await N(n)}catch{try{await M(n,{recursive:!0,force:!0})}catch{}}let{symlink:r}=await import(`node:fs/promises`);return process.platform===`win32`?await r(t,n,`junction`):await r(t,n),t}async function Bi(e){let t=P(H(),e),n=Fi(),r=P(Ti(),n),i=wi();if(process.platform===`win32`){await Hi(i);let e=P(t,n),r=P(t,Ii());try{await $e(r)}catch{try{let{link:t}=await import(`node:fs/promises`);await t(e,r)}catch{await Qe(e,r)}}return}await j(i,{recursive:!0});let{symlink:a}=await import(`node:fs/promises`);for(let e of[`bl`,`bailian`]){let t=P(i,e);try{await N(t)}catch{}await a(r,t)}}function Vi(e){return e&&typeof e==`object`&&`code`in e?String(e.code??``):``}async function Hi(e){let t=Ti(),{symlink:n,rename:r}=await import(`node:fs/promises`),i=null;try{let n=await $e(e);if(n.isSymbolicLink()){let n=await rt(e);if((n.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(n)?n:P(ct(e),n)).replaceAll(`\\`,`/`).toLowerCase()===t.replaceAll(`\\`,`/`).toLowerCase())return;await N(e)}else if(n.isDirectory()){i=`${e}.migrating.${process.pid}`;try{await r(e,i)}catch(t){try{await M(e,{recursive:!0,force:!0}),i=null}catch(n){let r=Vi(t)||Vi(n)||`EACCES`;throw Error(`Failed to migrate ${e} to a junction pointing at current (${r}). Close other bl sessions and re-run update, or re-run the install script once.`,{cause:n})}}}else await N(e).catch(()=>M(e,{recursive:!0,force:!0}))}catch(t){let n=Vi(t);if(n&&n!==`ENOENT`)throw t instanceof Error&&t.message.includes(`Failed to migrate`)?t:Error(`Failed to migrate ${e} to a junction pointing at current (${n}). Close other bl sessions and re-run update, or re-run the install script once.`,{cause:t})}await j(ct(e),{recursive:!0}),await n(t,e,`junction`),i&&await M(i,{recursive:!0,force:!0}).catch(()=>{})}async function Ui(e){let t=H(),n=new Set(e.filter(Boolean)),r=await Li(),i=r?Ri(r):null;i&&n.add(i);let a;try{a=await nt(t)}catch{return}for(let e of a){if(e.startsWith(`.`)){await M(P(t,e),{recursive:!0,force:!0}).catch(()=>{});continue}n.has(e)||await M(P(t,e),{recursive:!0,force:!0}).catch(()=>{})}}async function Wi(t){let n=Oi(t),{zipName:r,innerName:i,url:a,expectedSha:o}=await Mi(n),s=V(),c=H();await j(P(s,`.tmp`),{recursive:!0}),await j(c,{recursive:!0});let l=await Li(),u=l?Ri(l):null,d=P(s,`.tmp`,r),f=Pi(await Ni(a,d));if(o&&o!==f)throw await N(d).catch(()=>{}),Error(`Checksum mismatch for ${r}`);let p=P(c,`.staging.${n}.${process.pid}`);await M(p,{recursive:!0,force:!0}).catch(()=>{}),await j(p,{recursive:!0});let m=Fi(),h=P(p,m),g=P(s,`.tmp`,`${m}.${process.pid}`);if(await re(d,g,i),await N(d).catch(()=>{}),await at(g,h),process.platform!==`win32`)await Ze(h,493);else{let e=P(p,Ii());try{let{link:t}=await import(`node:fs/promises`);await t(h,e)}catch{await Qe(h,e)}}let _=P(c,n);await M(_,{recursive:!0,force:!0}).catch(()=>{}),await at(p,_),await zi(n),await Bi(n);let v=[n];return u&&u!==n&&v.push(u),await Ui(v),Le(`binary`,{clientName:e}),await j(ae(),{recursive:!0}),n}const Gi={"en-US":`Enable watermark (true/false). Omit flag to use the Profile setting or CLI default (true).`,"zh-CN":`是否启用水印(true/false)。不传时使用 Profile 配置或 CLI 默认值 true。`},Ki={"en-US":`Enable prompt extend (true/false). Omit flag to use CLI default (true).`,"zh-CN":`是否启用提示词扩展(true/false)。不传时使用 CLI 默认值 true。`},qi={"en-US":`Enable prompt extend (true/false). Omit flag: true for qwen-image sync; parameter omitted on async models (API default).`,"zh-CN":`是否启用提示词扩展(true/false)。不传时:qwen-image 同步调用默认为 true;异步模型不传该参数(使用 API 默认值)。`},Ji={"en-US":`Enable prompt extend (true/false). Omit flag to omit the parameter (DashScope default).`,"zh-CN":`是否启用提示词扩展(true/false)。不传时省略该参数(使用 DashScope 默认值)。`};var U=class extends Error{code;step;details;constructor(e,t,n){super(t),this.name=`PipelineError`,this.code=e,this.step=n?.step,this.details=n?.details}toJSON(){return{code:this.code,message:this.message,...this.step?{step:this.step}:{},...this.details?{details:this.details}:{}}}};function Yi(e,t){return e instanceof U?e:new U(`step_execution_error`,e instanceof Error?e.message:String(e),{step:t})}var Xi=class{handlers=/* @__PURE__ */ new Map;outputSchemas=/* @__PURE__ */ new Map;registerStep(e,t,n){this.handlers.set(e,t),n&&this.outputSchemas.set(e,n)}executeStep(e,t,n){let r=this.handlers.get(e);if(!r)throw new U(`unknown_step`,`Unknown step type: ${e}`,{details:{available:this.listSteps()}});return r(t,n)}hasStep(e){return this.handlers.has(e)}listSteps(){return Array.from(this.handlers.keys()).sort()}getOutputSchema(e){return this.outputSchemas.get(e)}};const Zi=new Xi;function Qi(){return Zi}function $i(e,t,n,r){let i,a;n instanceof Xi?(i=n,a=r):(i=Zi,a=n??r),i.registerStep(e,t,a)}const ea=/* @__PURE__ */ new Set([`image/generate`,`image/edit`,`video/generate`]);function ta(e,t,n){return!ea.has(e)||t.watermark!==void 0?t:{...t,watermark:n.watermark}}function na(e){let t=C({}),n={...S(t),output:`json`,outputExplicit:!0,quiet:!0},r={binName:`bl`,version:`0.0.0-dev`,npmPackage:`bailian-cli`,clientName:`bailian-cli`},a;try{a=ge(t)}catch{}return{client:new i({identity:r,settings:n,baseUrl:Se(t),apiCred:a,debug:e?t=>e.debug(t):void 0}),settings:n}}const ra=[`download`,`out-dir`,`output`];function ia(e){return e.startsWith(`./`)||e.startsWith(`../`)}function aa(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))typeof a==`string`&&ia(a)?(n[i]=dt(t,a),r.push(i)):n[i]=a;return{input:n,resolvedKeys:r}}async function oa(e,t,n){let r=[];for(let i of t){let t=e[i];typeof t==`string`&&(await Xe(t).then(()=>!0,()=>!1)||r.push(`Step "${n}" input "${i}" references file that does not exist: ${t}`))}return r}function sa(e){if(e===void 0)return;if(typeof e==`number`)return Number.isFinite(e)&&e>0?e:void 0;let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m)?$/);if(!t)return;let n=Number(t[1]);if(!Number.isFinite(n)||n<=0)return;let r=t[2]??`s`;return r===`ms`?n/1e3:r===`m`?n*60:n}function W(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ca(e,t){if(Array.isArray(e)){e.forEach(e=>ca(e,t));return}if(W(e)){`$from`in e&&typeof e.$from==`string`&&t.add(e.$from);for(let n of Object.values(e))ca(n,t)}}async function la(e,t){let n=[];for(let r of e)for(let[e,i]of Object.entries(r.input)){if(ra.includes(e)||typeof i!=`string`||!ia(i))continue;let a=dt(t,i);await Xe(a).then(()=>!0,()=>!1)||n.push(`Step "${r.id}" input "${e}" references file that does not exist: ${a}`)}return n}async function ua(e,t,n){if(!t.message)throw new U(`missing_input`,`text/chat requires 'message' input`,{step:`text/chat`});let r=t.model||`qwen3.8-max`,i=[];t.system&&i.push({role:`system`,content:t.system}),i.push({role:`user`,content:t.message});let a={model:r,messages:i,max_tokens:t[`max-tokens`]??4096,stream:!1};t.temperature!==void 0&&(a.temperature=t.temperature),t[`top-p`]!==void 0&&(a.top_p=t[`top-p`]),t[`enable-thinking`]&&(a.enable_thinking=!0,t[`thinking-budget`]!==void 0&&(a.thinking_budget=t[`thinking-budget`]));let o=T();return await e.client.requestJson({path:o,method:`POST`,body:a,timeout:n.blRequestTimeoutSeconds,signal:n.signal})}async function da(e,t,n){let r=t.model||`qwen3-vl-plus`,i=Array.isArray(t.image)?t.image:t.image?[t.image]:[],a=t.video?`Describe the video.`:`Describe the image.`,o=t.prompt||a,s=[];if(t.video){let i=t.video;ce(i)&&(i=await e.client.uploadFile(i,r,{signal:n.signal})),s.push({type:`video_url`,video_url:{url:i}})}for(let t of i){let i=t;ce(t)&&(i=await e.client.uploadFile(t,r,{signal:n.signal})),s.push({type:`image_url`,image_url:{url:i}})}s.push({type:`text`,text:o});let c={model:r,messages:[{role:`user`,content:s}]},l=T();return await e.client.requestJson({path:l,method:`POST`,body:c,signal:n.signal})}async function fa(e,t,n){if(!t.prompt)throw new U(`missing_input`,`image/generate requires 'prompt' input`,{step:`image/generate`});let r=t.model||`qwen-image-3.0`,i=xe(r),a=t.n??1,o=ve(t[`prompt-extend`],i.promptExtendDefault,`prompt-extend`),s={size:Si(t.size,i.sizeProfile),n:a,seed:t.seed,prompt_extend:o,watermark:Ee(t.watermark,e.settings.watermark)},c=i.inputStyle===`prompt`?{model:r,input:{prompt:t.prompt,negative_prompt:t[`negative-prompt`]||void 0},parameters:s}:{model:r,input:{messages:[{role:`user`,content:[{text:t.prompt}]}]},parameters:{...s,negative_prompt:t[`negative-prompt`]||void 0}};if(i.useSync){let r=await e.client.requestJson({path:i.path,method:`POST`,body:c,signal:n.signal}),a=r.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean),o=await ma(a,t[`out-dir`],t[`out-prefix`]);return{urls:a,request_id:r.request_id,...o?{saved:o}:{}}}let l=(await e.client.requestJson({path:i.path,method:`POST`,body:c,async:!0,signal:n.signal})).output.task_id,u=await ya(e,l,n),d=await ma(Array.isArray(u.urls)?u.urls:[],t[`out-dir`],t[`out-prefix`]);return d&&(u.saved=d),u}async function pa(e,t,n){if(!t.prompt)throw new U(`missing_input`,`image/edit requires 'prompt' input`,{step:`image/edit`});let r=Array.isArray(t.image)?t.image:t.image?[t.image]:[],i=t.model||`qwen-image-3.0`,a=be(i),o=t.n??1,s=ve(t[`prompt-extend`],a.promptExtendDefault,`prompt-extend`),c=[];for(let t of r){let r=t;ce(t)&&(r=await e.client.uploadFile(t,i,{signal:n.signal})),c.push(r)}let l={size:Si(t.size,a.sizeProfile),n:o,seed:t.seed,prompt_extend:s,watermark:Ee(t.watermark,e.settings.watermark)},u;if(a.inputStyle===`function-base-image`){let e=c[0];if(!e)throw new U(`missing_input`,`image/edit with wanx*-imageedit requires at least one image`,{step:`image/edit`});u={model:i,input:{function:t.function||`description_edit`,prompt:t.prompt,base_image_url:e},parameters:l}}else if(a.inputStyle===`prompt-images`)u={model:i,input:{prompt:t.prompt,images:c,negative_prompt:t[`negative-prompt`]||void 0},parameters:l};else{let e=c.map(e=>({image:e}));e.push({text:t.prompt}),u={model:i,input:{messages:[{role:`user`,content:e}]},parameters:{...l,negative_prompt:t[`negative-prompt`]||void 0}}}if(a.useSync){let r=await e.client.requestJson({path:a.path,method:`POST`,body:u,signal:n.signal}),i=r.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean),o=await ma(i,t[`out-dir`],t[`out-prefix`]);return{urls:i,request_id:r.request_id,...o?{saved:o}:{}}}let d=(await e.client.requestJson({path:a.path,method:`POST`,body:u,async:!0,signal:n.signal})).output.task_id,f=await ya(e,d,n),p=await ma(Array.isArray(f.urls)?f.urls:[],t[`out-dir`],t[`out-prefix`]);return p&&(f.saved=p),f}async function ma(e,t,n){if(!t||e.length===0)return;await j(t,{recursive:!0});let r=n&&n.length>0?n:`image`,i=e.length===1?[{url:e[0],destPath:P(t,`${r}.png`)}]:e.map((e,n)=>({url:e,destPath:P(t,`${r}_${String(n+1).padStart(3,`0`)}.png`)})),a=[];for(let{url:e,destPath:t}of i)await gi(e,t,{quiet:!0}),a.push(t);return a}async function ha(e,t,n){if(!t.prompt)throw new U(`missing_input`,`video/generate requires 'prompt' input`,{step:`video/generate`});let r=t.model||`wan3.0-video`,i;t.image&&(i=ce(t.image)?await e.client.uploadFile(t.image,r,{signal:n.signal}):t.image);let a={model:r,input:{prompt:t.prompt,negative_prompt:t[`negative-prompt`]||void 0,...i?{media:[{type:`first_frame`,url:i}]}:{}},parameters:{resolution:t.resolution||void 0,ratio:t.ratio||void 0,duration:t.duration,prompt_extend:ve(t[`prompt-extend`],void 0,`prompt-extend`),watermark:Ee(t.watermark,e.settings.watermark),seed:t.seed}};Me(a.parameters);let o=Ie(),s=(await e.client.requestJson({path:o,method:`POST`,body:a,async:!0,signal:n.signal})).output.task_id;return await xa(e,s,(t[`poll-interval`]??10)*1e3,(n.timeoutSeconds??900)*1e3,n)}async function ga(e,t,n){let r=t.text;if(!r&&t[`text-file`]){let{readFileSync:e}=await import(`node:fs`);r=e(t[`text-file`],`utf-8`).trim()}if(!r)throw new U(`missing_input`,`speech/synthesize requires 'text' input`,{step:`speech/synthesize`});let i=t.model||`cosyvoice-v3-flash`,a={model:i,input:{text:r,voice:t.voice,format:t.format,sample_rate:t[`sample-rate`],volume:t.volume,rate:t.rate,pitch:t.pitch,seed:t.seed,language_hints:t.language?[t.language]:void 0,instruction:t.instruction,enable_ssml:t[`enable-ssml`]}};Me(a.input);let o=je(),s=await e.client.requestJson({path:o,method:`POST`,body:a,signal:n.signal});return{audio_url:s.output.audio.url,url_expires_at:s.output.audio.expires_at,model:i,voice:t.voice,request_id:s.request_id}}async function _a(e,t,n){let r=Array.isArray(t.url)?t.url:t.url?[t.url]:[];if(r.length===0)throw new U(`missing_input`,`speech/recognize requires 'url' input`,{step:`speech/recognize`});let i=t.model||`fun-asr`,a=_e(i);if(a.kind===`unsupported`)throw new U(`invalid_input`,a.unsupportedReason??`Unsupported ASR model: ${i}`,{step:`speech/recognize`});if(a.kind===`sync-flash`){if(r.length!==1)throw new U(`invalid_input`,`Model "${i}" is a sync Flash ASR model and accepts exactly one url (got ${r.length})`,{step:`speech/recognize`});let e=[];if(t.diarization&&e.push(`diarization`),t[`speaker-count`]!==void 0&&e.push(`speaker-count`),a.flashFamily===`qwen3`&&(t[`vocabulary-id`]!==void 0&&e.push(`vocabulary-id`),t.vocabulary!==void 0&&e.push(`vocabulary`),t.context!==void 0&&e.push(`context`)),t[`channel-id`]!==void 0&&e.push(`channel-id`),e.length>0)throw new U(`invalid_input`,`Model "${i}" uses sync Flash ASR and does not support: ${e.join(`, `)}`,{step:`speech/recognize`})}if(a.kind===`async-filetrans`&&a.asyncInputStyle===`file_url`&&r.length!==1)throw new U(`invalid_input`,`Model "${i}" accepts exactly one url (got ${r.length})`,{step:`speech/recognize`});let o=[];for(let t of r)ce(t)?o.push(await e.client.uploadFile(t,i,{signal:n.signal})):o.push(t);if(a.kind===`sync-flash`){let r=a.flashFamily,s=v({model:i,audioUrl:o[0],language:t.language,vocabularyId:t[`vocabulary-id`],vocabulary:t.vocabulary,context:t.context,flashFamily:r}),c=await e.client.requestJson({path:a.path,method:`POST`,headers:{"X-DashScope-SSE":`disable`},body:s,signal:n.signal});return{text:ne(c,r),model:i,mode:`sync`,raw:c}}let s=y(a.asyncLanguageStyle??`language_hints`,t.language),c={model:i,input:{...a.asyncInputStyle===`file_url`?{file_url:o[0]}:{file_urls:o},...t.context?{context:_(t.context)}:{}},parameters:{channel_id:t[`channel-id`]===void 0?void 0:[t[`channel-id`]],...s,diarization_enabled:t.diarization,speaker_count:t[`speaker-count`],vocabulary_id:t[`vocabulary-id`],vocabulary:t.vocabulary}};Me(c.parameters);let l=(await e.client.requestJson({path:Ae(),method:`POST`,body:c,async:!0,signal:n.signal})).output.task_id,u=await Sa(e,l,(t[`poll-interval`]??2)*1e3,(n.timeoutSeconds??300)*1e3,n),d=ee(u.output),f={task_id:u.output.task_id,task_status:u.output.task_status,request_id:u.request_id,mode:`async`,model:i};if(u.output.results&&(f.results=u.output.results),u.output.result&&(f.result=u.output.result,typeof u.output.result.transcription_url==`string`&&(f.transcription_url=u.output.result.transcription_url)),u.output.task_metrics&&(f.task_metrics=u.output.task_metrics),u.usage&&(f.usage=u.usage),d.length===0)return f;let p=[],m=[];for(let e of d){if(!e.transcription_url)continue;let t=await A.fetch(e.transcription_url,{signal:n.signal});if(!t.ok)throw new U(`async_task_failed`,`Failed to download transcription: HTTP ${t.status}`,{step:`speech/recognize`,details:{taskId:l,url:e.transcription_url}});let r=await t.json();m.push(r);let i=r.transcripts;if(i?.length)for(let e of i)if(e.sentences?.length)for(let t of e.sentences)t.text&&p.push(t.text);else e.text&&p.push(e.text)}return{...f,text:p.join(`
53
53
  `),transcripts:m}}function va(e){let{output:t,request_id:n,usage:r}=e,i={task_id:t.task_id,task_status:t.task_status,request_id:n};if(t.video_url&&(i.video_url=t.video_url),t.choices){let e=t.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);e.length>0&&(i.urls=e)}if(t.results){let e=t.results.map(e=>e.url).filter(Boolean);e.length>0&&!i.urls&&(i.urls=e)}return t.task_metrics&&(i.task_metrics=t.task_metrics),r&&(i.usage=r),i}async function ya(e,t,n){return await xa(e,t,3e3,e.settings.timeout*1e3,n)}async function ba(e,t,n,r,i){let a=Date.now(),o=0;for(;;){if(i?.signal?.aborted)throw new U(`aborted`,`Task polling was aborted`,{details:{taskId:t}});await Ca(n,i?.signal),o++;let s=Ne(t),c=await e.client.requestJson({path:s,method:`GET`,signal:i?.signal}),l=c.output.task_status;if(l===`SUCCEEDED`)return c;if(l===`FAILED`)throw new U(`async_task_failed`,c.output.message||c.output.code||`Task failed`,{details:{taskId:t,data:c}});let u=Date.now()-a;if(await i?.emitEvent?.({type:`step.polling`,timestamp:(/* @__PURE__ */ new Date()).toISOString(),status:`running`,taskId:t,taskStatus:l,elapsedMs:u,pollAttempt:o}),u>r)throw new U(`async_poll_timeout`,`Task ${t} timed out after ${Math.round(r/1e3)}s`,{details:{taskId:t,timeoutMs:r,pollAttempts:o}})}}async function xa(e,t,n,r,i){return va(await ba(e,t,n,r,i))}async function Sa(e,t,n,r,i){return await ba(e,t,n,r,i)}function Ca(e,t){return t?new Promise((n,r)=>{let i=setTimeout(()=>{o(),n()},e),a=()=>{o(),r(new U(`aborted`,`Poll delay was aborted`))},o=()=>{clearTimeout(i),t.removeEventListener(`abort`,a)};t.aborted?a():t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}const wa={"text/chat":(e,t,n)=>ua(e,t,n),"vision/describe":(e,t,n)=>da(e,t,n),"image/generate":(e,t,n)=>fa(e,t,n),"image/edit":(e,t,n)=>pa(e,t,n),"video/generate":(e,t,n)=>ha(e,t,n),"speech/synthesize":(e,t,n)=>ga(e,t,n),"speech/recognize":(e,t,n)=>_a(e,t,n)},Ta={"image/generate":e=>({data:e,artifacts:ka(e),warnings:[],metadata:{}}),"image/edit":e=>({data:e,artifacts:ka(e),warnings:[],metadata:{}}),"video/generate":e=>({data:e,artifacts:ka(e),warnings:[],metadata:{}}),"speech/synthesize":e=>({data:e,artifacts:Aa(e,`audio`),warnings:[],metadata:{}}),"speech/recognize":e=>({data:e,artifacts:Aa(e,`transcript`),warnings:[],metadata:{}})},Ea={"text/chat":{description:`LLM text completion via chat API`,paths:[{path:`/data/choices/0/message/content`,description:`Generated text content`},{path:`/data/choices/0/message/role`,description:`Message role (assistant)`},{path:`/data/usage/total_tokens`,description:`Total token usage`}]},"vision/describe":{description:`Multimodal vision understanding (image/video to text)`,paths:[{path:`/data/choices/0/message/content`,description:`Generated description text`},{path:`/data/choices/0/message/role`,description:`Message role (assistant)`},{path:`/data/usage/total_tokens`,description:`Total token usage`}]},"image/generate":{description:`Text-to-image generation`,paths:[{path:`/data/urls`,description:`Array of generated image URLs`},{path:`/data/urls/0`,description:`First generated image URL`},{path:`/data/task_id`,description:`Async task ID (if applicable)`},{path:`/artifacts/0/url`,description:`First artifact URL`},{path:`/artifacts/0/path`,description:`First artifact local path (if saved)`}]},"image/edit":{description:`Image editing with reference image(s)`,paths:[{path:`/data/urls`,description:`Array of generated image URLs`},{path:`/data/urls/0`,description:`First generated image URL`},{path:`/data/task_id`,description:`Async task ID (if applicable)`},{path:`/artifacts/0/url`,description:`First artifact URL`},{path:`/artifacts/0/path`,description:`First artifact local path (if saved)`}]},"video/generate":{description:`Video generation (text-to-video or image-to-video)`,paths:[{path:`/data/video_url`,description:`Generated video URL`},{path:`/data/task_id`,description:`Async task ID`},{path:`/artifacts/0/url`,description:`First artifact URL`},{path:`/artifacts/0/path`,description:`First artifact local path (if saved)`}]},"speech/synthesize":{description:`Text-to-speech synthesis`,paths:[{path:`/data/audio_url`,description:`Generated audio URL`},{path:`/data/url_expires_at`,description:`Audio URL expiration time`},{path:`/artifacts/0/url`,description:`First artifact URL`}]},"speech/recognize":{description:`Speech recognition (ASR)`,paths:[{path:`/data/text`,description:`Full transcribed text`},{path:`/data/task_id`,description:`Async task ID`},{path:`/artifacts/0/taskId`,description:`Task ID from artifact`}]}};function Da(e){for(let t of Object.keys(wa))$i(t,async(e,n)=>await Oa(t,e,n),e,Ea[t])}async function Oa(e,t,n){let r=n.blEnv??na();if(n.dryRun)return{metadata:{dryRun:!0,step:e,plannedInput:ta(e,t,r.settings)},warnings:[{code:`dry_run_skipped`,message:`Step ${e} was not executed in dry-run mode`}]};let i=wa[e];if(!i)throw Error(`No direct API handler registered for step: ${e}`);let a=await i(r,t,n),o=Ta[e];return o?o(a):{data:a,warnings:[],metadata:{}}}function ka(e){if(!W(e))return;let t=[],n=G(e.task_id)??G(e.taskId);for(let r of Na(e.urls))t.push({url:r,taskId:n,kind:Pa(r)});for(let r of Na(e.saved))t.push({path:r,taskId:n,kind:Fa(r)});let r=G(e.video_url)??G(e.videoUrl);r&&t.push({url:r,taskId:n,kind:`video`});let i=G(e.saved);if(i&&t.push({path:i,taskId:n,kind:Fa(i)}),Array.isArray(e.videos))for(let n of e.videos){if(!W(n))continue;let e=G(n.task_id)??G(n.taskId),r=G(n.video_url)??G(n.videoUrl),i=G(n.saved);r&&t.push({url:r,taskId:e,kind:`video`}),i&&t.push({path:i,taskId:e,kind:`video`})}let a=Array.isArray(e.task_ids)?e.task_ids.map(G).filter(Ma):[];for(let e of a)t.push({taskId:e,kind:`task`});return t.length===0&&n&&t.push({taskId:n,kind:`task`}),t.length>0?t:void 0}function Aa(e,t){if(!W(e))return;let n=[],r=G(e.task_id)??G(e.taskId),i=[G(e.url),G(e.audio_url),G(e.audioUrl),G(e.output_url),G(e.outputUrl)].filter(Ma);for(let e of i)n.push({url:e,taskId:r,kind:t});let a=[G(e.saved),G(e.path),G(e.output_path),G(e.outputPath)].filter(Ma);for(let e of a)n.push({path:e,taskId:r,kind:t});return n.length===0&&r&&n.push({taskId:r,kind:`task`}),n.length>0?ja(n):void 0}function ja(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e){let e=`${r.kind??``}:${r.taskId??``}:${r.url??``}:${r.path??``}`;t.has(e)||(t.add(e),n.push(r))}return n}function Ma(e){return typeof e==`string`}function G(e){return typeof e==`string`&&e.length>0?e:void 0}function Na(e){return Array.isArray(e)?e.map(G).filter(Ma):[]}function Pa(e){try{return Fa(new URL(e).pathname)}catch{return`artifact`}}function Fa(e){let t=e.toLowerCase();return t.endsWith(`.mp4`)||t.endsWith(`.mov`)||t.endsWith(`.webm`)?`video`:t.endsWith(`.png`)||t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)||t.endsWith(`.webp`)?`image`:`artifact`}var Ia=/* @__PURE__ */ F((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),La=/* @__PURE__ */ F((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ia();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=/* @__PURE__ */ new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||/* @__PURE__ */ new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),K=/* @__PURE__ */ F((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Ia(),n=La();var r=Ia();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=La();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=D(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=D(this.rhs,e,n),this}get names(){return te(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=D(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(ne(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(re(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=D(this.condition,e,t),this}get names(){let e=super.names;return te(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=D(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return te(te(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=D(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli-runtime",
3
- "version": "2.8.1",
3
+ "version": "2.8.3",
4
4
  "description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.",
5
5
  "homepage": "https://bailian.console.aliyun.com/cli",
6
6
  "bugs": {
@@ -30,7 +30,7 @@
30
30
  "boxen": "^8.0.1",
31
31
  "chalk": "^5.6.2",
32
32
  "undici": "^6.27.0",
33
- "bailian-cli-core": "2.8.1"
33
+ "bailian-cli-core": "2.8.3"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@clack/prompts": "^0.7.0",