bailian-cli-runtime 1.24.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -46,7 +46,7 @@ If you are behind a VPN or corporate proxy, route ${z} through it:\nexport HTTPS
|
|
|
46
46
|
`):On(e),process.exit(e.exitCode)),e instanceof Error){if(e.name===`AbortError`||e.name===`TimeoutError`||e.message.includes(`timed out`))return V(new m(`Request timed out.`,x.TIMEOUT,`Try increasing --timeout (e.g. --timeout 60).
|
|
47
47
|
${yn()}\nRun: ${z} auth status — to check credentials.`,{cause:e}),z);if(e instanceof TypeError&&e.message===`fetch failed`)return V(wn(e),z);let t=e.code;if(typeof t==`string`&&t.startsWith(`E`))return V(En(e),z);process.stderr.write(`\n${B(`Error:`)}${e.message}\n`),Dn(e),process.env.DASHSCOPE_VERBOSE===`1`&&process.stderr.write(`${e.stack}\n`)}else process.stderr.write(`\n${B(`Error:`)}${String(e)}\n`);process.exit(x.GENERAL)}function kn(e){return M(ce(),`plugins`,e.npmPackage)}function An(e){return M(kn(e),`package.json`)}function jn(e,t){return M(kn(e),`node_modules`,...t.split(`/`))}async function Mn(e){try{return JSON.parse(await Ke(e,`utf8`))}catch(t){throw new m(`Could not parse JSON file: ${e}`,x.GENERAL,`Repair or remove the invalid file and try again.`,{cause:t})}}async function Nn(e){let t=An(e);return He(t)?Mn(t):{dependencies:{}}}async function Pn(e,t){return Fn(jn(e,t))}async function Fn(e){return Mn(M(e,`package.json`))}const In=new Set([`none`,`apiKey`,`console`,`openapi`]),Ln=/^[a-z0-9][a-z0-9-]*$/;function Rn(e,t,n){if(t.name!==e)throw Error(`Package name mismatch: expected "${e}", received "${t.name??``}".`);let r=t.bailianCli;if(!r||r.type!==`command-pack`)throw Error(`Package "${e}" is missing bailianCli.type="command-pack".`);if(r.apiVersion!==h)throw Error(`Command Pack API ${r.apiVersion} is not supported; this CLI supports API ${h}.`);if(r.minCliVersion&&Jt(n.version,r.minCliVersion)<0)throw Error(`Command Pack requires ${n.npmPackage} ${r.minCliVersion} or newer; current version is ${n.version}.`);if(!r.entry||Ze(r.entry))throw Error(`Command Pack "${e}" must declare a relative bailianCli.entry.`);return r}function zn(e,t){let n=e.split(/\s+/).filter(Boolean).join(` `);if(!e||e!==n||!e.split(` `).every(e=>Ln.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 Bn(e){if(typeof e==`string`)return e.length>0;if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return T.every(e=>typeof t[e]==`string`&&t[e].length>0)}function Vn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return t.level===`high`&&Bn(t.message)}function Hn(e,t){if(!t||typeof t!=`object`)throw Error(`Command "${e}" must export an object.`);let n=t;if(!Bn(n.description))throw Error(`Command "${e}" is missing a description.`);if(!n.auth||!In.has(n.auth))throw Error(`Command "${e}" has an invalid auth requirement.`);if(n.risk!==void 0&&!Vn(n.risk))throw Error(`Command "${e}" has invalid risk metadata.`);if(typeof n.run!=`function`)throw Error(`Command "${e}" is missing run(ctx).`)}function Un(e,t,n){return Object.fromEntries(Object.entries(t).map(([t,r])=>[t,{description:r.description,auth:r.auth,risk:r.risk,usageArgs:r.usageArgs,exampleArgs:r.exampleArgs,notes:r.notes,flags:r.flags,validate:r.validate,run:i=>{let a={identity:i.identity,settings:i.settings,flags:i.flags,client:i.client,output:{result(e,t){let n=i.settings.output===`text`&&t?.text!==void 0?t.text:se(e,i.settings.output);process.stdout.write(`${n}\n`)},line(e){process.stdout.write(`${e}\n`)},write(e){process.stdout.write(e)}},errors:{general(e,t){return new m(e,x.GENERAL,t?.hint,{cause:t?.cause})},usage(e,t){return new E(e,t)},timeout(e=`Request timed out.`,t){return new m(e,x.TIMEOUT,t?.hint,{cause:t?.cause})}},credentials:{apiKey(){if(!n.credentialAccess?.includes(`apiKey`))throw new m(`Command Pack "${e}" is not allowed to access API-key credentials.`,x.GENERAL);if(r.auth!==`apiKey`)throw new m(`Command "${t}" must declare auth="apiKey" before accessing API-key credentials.`,x.GENERAL);let a=i.client.exportApiCredential();if(!a)throw new m(`No API key available to the Command Pack.`,x.AUTH);return a}}};return r.run(a)}}]))}async function Wn(e,t,n,r,i=jn(r,e)){let a=Rn(e,t,r),o=await qe(i),s=await qe($e(o,a.entry)),c=Qe(o,s);if(!c||c.startsWith(`..`)||Ze(c))throw Error(`Command Pack entry must stay inside the package root: ${a.entry}`);let l=(await import(et(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)zn(e,n),Hn(e,t);let d=Un(e,l,n);return new Pt(d,r.binName),d}function Gn(e){return e.startsWith(`file:`)?`linked`:`installed`}async function Kn(e,t,n){let r={...e},i=[],a;try{a=await Nn(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=Gn(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 Pn(t,e),o=await Wn(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 qn={name:`bailian-cli-command-packs`,private:!0,dependencies:{}},Jn=new Set(`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(`.`)),Yn=new Set([`registry`,`userconfig`,`globalconfig`,`cache`,`proxy`,`https_proxy`,`noproxy`,`strict_ssl`,`ca`,`cafile`]);function Xn(e){let t=/^(?:npm_config_|NPM_CONFIG_)(.+)$/.exec(e);return!!t&&Yn.has(t[1].toLowerCase())}function Zn(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 Qn(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(Jn.has(n)||n.startsWith(`LC_`)||Xn(n))&&(t[n]=r);return t}async function $n(e){await We(e,{recursive:!0,mode:448});let t=M(e,`package.json`);He(t)||await Xe(t,`${JSON.stringify(qn,null,2)}\n`,{mode:384})}async function er(e,t){if(nt(`npm`,[`--version`],{encoding:`utf-8`}).status!==0){let e=ue()?"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 m(`npm is required to install, link, or remove Command Packs, but was not found on PATH.`,x.GENERAL,e)}await new Promise((n,r)=>{let i=tt(`npm`,e,{cwd:t,env:Qn(),stdio:[`inherit`,`pipe`,`pipe`]});i.stdout.on(`data`,e=>process.stderr.write(e)),i.stderr.on(`data`,e=>process.stderr.write(e)),i.once(`error`,r),i.once(`close`,(t,i)=>{if(t===0){n();return}r(new m(`npm ${e[0]} failed${i?` with signal ${i}`:` with exit code ${t}`}.`,x.GENERAL))})})}async function tr(e){let t=kn(e);await $n(t);let n=M(t,`.lock`);for(let e=0;e<2;e++)try{let e=await Ge(n,`wx`,384);return await e.writeFile(`${process.pid} ${Date.now()}\n`),await e.close(),async()=>{try{await Ye(n)}catch{}}}catch(e){if(e.code!==`EEXIST`)throw e;try{let e=await Je(n);if(Date.now()-e.mtimeMs>6e5){await Ye(n);continue}}catch{continue}throw new m(`Another Command Pack install, link, or remove operation is already running.`,x.GENERAL,`Wait for it to finish and try again.`)}throw new m(`Could not acquire the Command Pack operation lock.`,x.GENERAL)}async function nr(e,t){let n=await tr(e);try{return await t()}finally{await n()}}function rr(e,t,n){let r=e.trim(),i=/^(@[^/\s]+\/[^@/\s]+)(?:@([a-zA-Z0-9][a-zA-Z0-9._-]*))?$/.exec(r);if(!i)throw new m(`Unsupported Command Pack package spec: "${e}".`,x.USAGE,`Use an allowlisted scoped package name with an optional version or tag.`);let a=i[1];if(!n.supported[a])throw new m(`Command Pack "${a}" is not allowlisted for ${t.binName}.`,x.USAGE,Zn(t,n));return{name:a,requested:r}}async function ir(e,t,n,r){let i=r.supported[e],a=await Fn(t);return{pjson:a,commands:await Wn(e,a,i,n,t)}}function ar(e,t){return t.startsWith(`file:`)?t:`${e}@${t}`}async function or(e,t,n){if(t){await er([`install`,ar(e,t),`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],n);return}await er([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],n)}async function sr(e,t,n){let{name:r,requested:i}=rr(e,t,n);return nr(t,async()=>{let e=kn(t),a=(await Nn(t)).dependencies?.[r];try{await er([`install`,i,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],e);let a=await ir(r,jn(t,r),t,n);if(!a.pjson.version)throw new m(`Command Pack "${r}" has no package version.`,x.USAGE);return{name:r,version:a.pjson.version,commands:Object.keys(a.commands).sort()}}catch(t){try{await or(r,a,e)}catch{}throw t}})}async function cr(e,t,n){let r=$e(e);if(!He(M(r,`package.json`)))throw new m(`Command Pack path does not exist: ${r}`,x.USAGE);let i=(await Fn(r)).name;if(!i||!n.supported[i])throw new m(`Local package "${i??`(unnamed)`}" is not an allowlisted Command Pack for ${t.binName}.`,x.USAGE,Zn(t,n));let a=await ir(i,r,t,n);return nr(t,async()=>{await er([`install`,`file:${r}`,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],kn(t));let e=await ir(i,jn(t,i),t,n);return{name:i,version:e.pjson.version??a.pjson.version,commands:Object.keys(e.commands).sort()}})}async function lr(e,t,n){if(!n.supported[e])throw new m(`Command Pack "${e}" is not allowlisted for ${t.binName}.`,x.USAGE,Zn(t,n));if(!(e in((await Nn(t)).dependencies??{})))throw new m(`Command Pack "${e}" is not installed.`,x.USAGE);await nr(t,()=>er([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],kn(t)))}async function ur(e,t){return(await Kn({},e,t)).reports}function dr(e,t){return{install:n=>sr(n,e,t),link:n=>cr(n,e,t),list:()=>ur(e,t),remove:n=>lr(n,e,t)}}function fr(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function pr(e){for(let t=0;t<e.length;t++){let n=e[t];if(n===`--config`)return{config:e[t+1]};if(n?.startsWith(`--config=`))return{config:n.slice(9)}}return{}}function mr(e){try{vn()}catch(t){V(t,e)}process.on(`SIGINT`,()=>{process.stderr.write(`
|
|
48
48
|
Interrupted. Exiting.
|
|
49
|
-
`),oe(500).finally(()=>process.exit(130))}),process.stdout.on(`error`,e=>{if(e.code===`EPIPE`)process.exit(0);else throw e})}function hr(e,t){let{binName:n,version:r,npmPackage:i,clientName:a}=t,o={binName:n,version:r,npmPackage:i,clientName:a},s=t.commandPacks??{supported:{}},c=dr(o,s),l;mr(n);let u=un([fn,mn,pn,dn,hn]);function d(){return l||=Kn(e,o,s),l}async function f(e){let t=Rt(A(pr(e)).file.language??b);return{registry:new Pt((await d()).commands,n,t),localize:e=>t.localize(e)}}function p(e,n,r){if(e.printHelp(n,process.stderr),n.length>0)return;let i=!1;try{let e=re(A(mt(r,{...S,...C,...g,...w})));i=!!(e.apiKey||e.console)}catch{}i?t.quickStartTasks?.length&&e.printQuickStart(t.quickStartTasks):e.printWelcome()}async function m(e,t,i){let a=Ft(t,e);switch(a.kind){case`version`:process.stdout.write(`${n} ${r}\n`);return;case`help`:p(e,a.path,t);return;case`usageError`:V(a.error,n);return;case`run`:try{let e=j(a.command),t=Ot(a.command),n=mt(a.rest,{...S,...e,...t,...a.command.flags}),r=fr(n,[...Object.keys(S),...Object.keys(e)]),s=fr(n,Object.keys(a.command.flags??{})),l=await a.command.validate?.(s);if(l)throw new E(l);let d=A(r),f=k(d);await u({identity:o,path:a.path,command:a.command,flags:s,confirmed:n.yes===!0,localize:i,settings:f,sources:d,configStore:pe(d.configName),authStore:fe(d),commandPacks:c,client:new _({identity:o,settings:f,...Se(d)})}),await oe(1e3)}catch(t){if(t instanceof E&&a.rest.length===0){e.printHelp(a.path,process.stderr);return}await oe(1e3),V(t,n)}return}}return{run(e=process.argv.slice(2)){return Promise.resolve().then(()=>f(e)).then(({registry:t,localize:n})=>m(t,e,n)).catch(e=>oe(1e3).finally(()=>V(e,n)))}}}const gr=`1.
|
|
49
|
+
`),oe(500).finally(()=>process.exit(130))}),process.stdout.on(`error`,e=>{if(e.code===`EPIPE`)process.exit(0);else throw e})}function hr(e,t){let{binName:n,version:r,npmPackage:i,clientName:a}=t,o={binName:n,version:r,npmPackage:i,clientName:a},s=t.commandPacks??{supported:{}},c=dr(o,s),l;mr(n);let u=un([fn,mn,pn,dn,hn]);function d(){return l||=Kn(e,o,s),l}async function f(e){let t=Rt(A(pr(e)).file.language??b);return{registry:new Pt((await d()).commands,n,t),localize:e=>t.localize(e)}}function p(e,n,r){if(e.printHelp(n,process.stderr),n.length>0)return;let i=!1;try{let e=re(A(mt(r,{...S,...C,...g,...w})));i=!!(e.apiKey||e.console)}catch{}i?t.quickStartTasks?.length&&e.printQuickStart(t.quickStartTasks):e.printWelcome()}async function m(e,t,i){let a=Ft(t,e);switch(a.kind){case`version`:process.stdout.write(`${n} ${r}\n`);return;case`help`:p(e,a.path,t);return;case`usageError`:V(a.error,n);return;case`run`:try{let e=j(a.command),t=Ot(a.command),n=mt(a.rest,{...S,...e,...t,...a.command.flags}),r=fr(n,[...Object.keys(S),...Object.keys(e)]),s=fr(n,Object.keys(a.command.flags??{})),l=await a.command.validate?.(s);if(l)throw new E(l);let d=A(r),f=k(d);await u({identity:o,path:a.path,command:a.command,flags:s,confirmed:n.yes===!0,localize:i,settings:f,sources:d,configStore:pe(d.configName),authStore:fe(d),commandPacks:c,client:new _({identity:o,settings:f,...Se(d)})}),await oe(1e3)}catch(t){if(t instanceof E&&a.rest.length===0){e.printHelp(a.path,process.stderr);return}await oe(1e3),V(t,n)}return}}return{run(e=process.argv.slice(2)){return Promise.resolve().then(()=>f(e)).then(({registry:t,localize:n})=>m(t,e,n)).catch(e=>oe(1e3).finally(()=>V(e,n)))}}}const gr=`1.25.0`;function _r(e,t){process.stdout.write(se(e,t)+`
|
|
50
50
|
`)}function vr(e){process.stdout.write(e+`
|
|
51
51
|
`)}function yr(e,t){!e||t||process.stderr.write(`request_id: ${e}\n`)}function br(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 xr(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 H(e){let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=xr(e)?2:1}return t}function Sr(e,t){let n=t-H(e);return n>0?e+` `.repeat(n):e}const Cr=` │ `,wr=[0,150,160],Tr=[176,205,250],Er=[160,160,170];function Dr(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(!Ct(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 Or(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 kr(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 Ar(e,t,n,r,i=38){return e>=3?`${i};2;${t};${n};${r}`:e===2?`${i};5;${Or(t,n,r)}`:String(kr(t,n,r,i))}function jr(e,[t,n,r],i){return e<=0?i:`\x1b[${Ar(e,t,n,r)}m${i}\x1b[0m`}function Mr(e,t,n){return t<=0?e:`\x1b[1;${Ar(t,255,255,255,38)};${Ar(t,n[0],n[1],n[2],48)}m${e}\x1b[0m`}function Nr(e,t){let n=t-H(e);return n>0?` `.repeat(n)+e:e}function Pr(e,t,n=20,r=process.stdout){return Fr(e,t,n,Dr(r))}function Fr(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+=jr(r,wr,`█`)):(s+=` `,c+=` `);let l=a?Tr:Er;return s+=` ${t}`,c+=` ${jr(r,l,t)}`,{plain:s,colored:c}}function Ir(e){let t=Dr(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(Fr(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=H(t);for(let t=0;t<e.rows.length;t++){let e=H(o(t,n));e>r&&(r=e)}return r}),c=[],l=e.headers.map((e,t)=>n[t]===`right`?Nr(e,s[t]):Sr(e,s[t])).join(Cr),u=Math.max(H(l),...e.rows.map((e,t)=>H(Array.from({length:i},(e,n)=>o(t,n)).join(Cr))));c.push(Mr(` ${Sr(l,u)} `,t,wr));let d=` ${jr(t,wr,`│`)} `;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-H(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`?Nr(c,i):Sr(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}const Lr=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];function Rr(e){let t=process.stderr.isTTY,n=0,r=null,i=e;return{start(){t&&(r=setInterval(()=>{process.stderr.write(`\r${Lr[n%Lr.length]} ${i}`),n++},80))},update(e){i=e},stop(e){r&&=(clearInterval(r),null),t&&(process.stderr.write(`\r\x1B[K`),e&&process.stderr.write(`${e}\n`))}}}function zr(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(`
|
|
52
52
|
`)}}}async function Br(e,t,n){let r=Date.now()+n.timeoutSec*1e3,i=Rr(`Polling...`);t.quiet||i.start();try{for(;Date.now()<r;){let r=await e.requestJson({path:n.url});if(n.getStatus&&!t.quiet&&i.update(`Status: ${n.getStatus(r)}`),n.isComplete(r))return i.stop(`Done.`),r;if(n.isFailed(r)){i.stop(`Failed.`),t.verbose&&process.stderr.write(`[verbose] Task response: ${JSON.stringify(r,null,2)}\n`);let e=n.getErrorMessage?.(r);throw new m(e?`Task failed: ${e}`:`Task failed.`,x.GENERAL,e?void 0:`Use --verbose to see full API response details.`)}await new Promise(e=>setTimeout(e,n.intervalSec*1e3))}}finally{i.stop()}throw new m(`Polling timed out.`,x.TIMEOUT,`Try increasing --timeout or check task status manually.`)}async function Vr(e,t,n){let r=await fetch(e);if(!r.ok)throw new m(`Download failed: HTTP ${r.status}`,x.GENERAL);let i=Number(r.headers.get(`content-length`)||0),a=r.body?.getReader();if(!a)throw new m(`No response body`,x.GENERAL);Ie(Ne(t),{recursive:!0});let o=Fe(t),s=i>0&&!n?.quiet?zr(i,`Downloading`):null,c=0,l=!1;try{let e=new Promise((e,t)=>{o.on(`error`,t)});for(;;){let{done:t,value:n}=await Promise.race([a.read(),e]);if(t)break;o.write(n)||await new Promise(e=>o.once(`drain`,()=>e())),c+=n.byteLength,s?.update(c)}l=!0}finally{if(a.releaseLock(),s?.finish(),await new Promise((e,t)=>{o.on(`finish`,e),o.on(`error`,t),o.end()}),!l)try{Re(t)}catch{}}return{size:c}}function Hr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Ur(e){return Math.max(1,e.concurrent??1)}async function Wr(e,t,n,r=`requests`){if(e<=1)return[await n(0)];t.quiet||process.stderr.write(`[Concurrent: ${e} ${r}]\n`);let i=Array.from({length:e},(e,t)=>n(t));return Promise.all(i)}async function Gr(e,t,n){return Promise.all(e.map(({url:e,destPath:r})=>t(e,r,n).then(()=>r)))}const Kr={"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 qr(e,t){if(e)return Kr[typeof t==`boolean`?t?`qwen-image-2.0`:`qwen-image-fixed`:t][e]??e}const Jr={"en-US":`Enable watermark (true/false). Omit flag to use the Profile setting or CLI default (true).`,"zh-CN":`是否启用水印(true/false)。不传时使用 Profile 配置或 CLI 默认值 true。`},Yr={"en-US":`Enable prompt extend (true/false). Omit flag to use CLI default (true).`,"zh-CN":`是否启用提示词扩展(true/false)。不传时使用 CLI 默认值 true。`},Xr={"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 默认值)。`},Zr={"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 Qr(e,t){return e instanceof U?e:new U(`step_execution_error`,e instanceof Error?e.message:String(e),{step:t})}var $r=class{handlers=new Map;outputSchemas=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 ei=new $r;function ti(){return ei}function ni(e,t,n,r){let i,a;n instanceof $r?(i=n,a=r):(i=ei,a=n??r),i.registerStep(e,t,a)}const ri=new Set([`image/generate`,`image/edit`,`video/generate`]);function ii(e,t,n){return!ri.has(e)||t.watermark!==void 0?t:{...t,watermark:n.watermark}}function ai(){let e=A({}),t={...k(e),output:`json`,outputExplicit:!0,quiet:!0},n={binName:`bl`,version:`0.0.0-dev`,npmPackage:`bailian-cli`,clientName:`bailian-cli`},r;try{r=he(e)}catch{}return{client:new _({identity:n,settings:t,baseUrl:xe(e),apiCred:r}),settings:t}}const oi=[`download`,`out-dir`,`output`];function si(e){return e.startsWith(`./`)||e.startsWith(`../`)}function ci(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))typeof a==`string`&&si(a)?(n[i]=$e(t,a),r.push(i)):n[i]=a;return{input:n,resolvedKeys:r}}async function li(e,t,n){let r=[];for(let i of t){let t=e[i];typeof t==`string`&&(await Ue(t).then(()=>!0,()=>!1)||r.push(`Step "${n}" input "${i}" references file that does not exist: ${t}`))}return r}function ui(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 di(e,t){if(Array.isArray(e)){e.forEach(e=>di(e,t));return}if(W(e)){`$from`in e&&typeof e.$from==`string`&&t.add(e.$from);for(let n of Object.values(e))di(n,t)}}async function fi(e,t){let n=[];for(let r of e)for(let[e,i]of Object.entries(r.input)){if(oi.includes(e)||typeof i!=`string`||!si(i))continue;let a=$e(t,i);await Ue(a).then(()=>!0,()=>!1)||n.push(`Step "${r.id}" input "${e}" references file that does not exist: ${a}`)}return n}async function pi(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=te();return await e.client.requestJson({path:o,method:`POST`,body:a,timeout:n.blRequestTimeoutSeconds,signal:n.signal})}async function mi(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;de(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;de(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=te();return await e.client.requestJson({path:l,method:`POST`,body:c,signal:n.signal})}async function hi(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=be(r),a=t.n??1,o=_e(t[`prompt-extend`],i.promptExtendDefault,`prompt-extend`),s={size:qr(t.size,i.sizeProfile),n:a,seed:t.seed,prompt_extend:o,watermark:we(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 _i(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 Si(e,l,n),d=await _i(Array.isArray(u.urls)?u.urls:[],t[`out-dir`],t[`out-prefix`]);return d&&(u.saved=d),u}async function gi(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=ye(i),o=t.n??1,s=_e(t[`prompt-extend`],a.promptExtendDefault,`prompt-extend`),c=[];for(let t of r){let r=t;de(t)&&(r=await e.client.uploadFile(t,i,{signal:n.signal})),c.push(r)}let l={size:qr(t.size,a.sizeProfile),n:o,seed:t.seed,prompt_extend:s,watermark:we(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 _i(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 Si(e,d,n),p=await _i(Array.isArray(f.urls)?f.urls:[],t[`out-dir`],t[`out-prefix`]);return p&&(f.saved=p),f}async function _i(e,t,n){if(!t||e.length===0)return;await We(t,{recursive:!0});let r=n&&n.length>0?n:`image`,i=e.length===1?[{url:e[0],destPath:M(t,`${r}.png`)}]:e.map((e,n)=>({url:e,destPath:M(t,`${r}_${String(n+1).padStart(3,`0`)}.png`)})),a=[];for(let{url:e,destPath:t}of i)await Vr(e,t,{quiet:!0}),a.push(t);return a}async function vi(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=de(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:_e(t[`prompt-extend`],void 0,`prompt-extend`),watermark:we(t.watermark,e.settings.watermark),seed:t.seed}};Oe(a.parameters);let o=je(),s=(await e.client.requestJson({path:o,method:`POST`,body:a,async:!0,signal:n.signal})).output.task_id;return await wi(e,s,(t[`poll-interval`]??10)*1e3,(n.timeoutSeconds??900)*1e3,n)}async function yi(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`]}};Oe(a.input);let o=De(),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 bi(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=ge(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)de(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=ee({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:ae(c,r),model:i,mode:`sync`,raw:c}}let s=O(a.asyncLanguageStyle??`language_hints`,t.language),c={model:i,input:{...a.asyncInputStyle===`file_url`?{file_url:o[0]}:{file_urls:o},...t.context?{context:D(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}};Oe(c.parameters);let l=(await e.client.requestJson({path:Ee(),method:`POST`,body:c,async:!0,signal:n.signal})).output.task_id,u=await Ti(e,l,(t[`poll-interval`]??2)*1e3,(n.timeoutSeconds??300)*1e3,n),d=ne(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 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(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bailian-cli-runtime",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.25.0",
|
|
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": "1.
|
|
33
|
+
"bailian-cli-core": "1.25.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@clack/prompts": "^0.7.0",
|