bailian-cli 0.1.2-beta.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bailian.mjs +5 -5
  2. package/package.json +1 -1
package/dist/bailian.mjs CHANGED
@@ -95,7 +95,7 @@ Get API Key: https://bailian.console.aliyun.com/cn-beijing/?source_channel=al
95
95
  Re-authenticate: bailian auth login --api-key sk-xxxxx
96
96
  Get API Key: https://bailian.console.aliyun.com/cn-beijing/?source_channel=aliway&tab=app#/api-key`);if(e===429||$==="Throttling"||$==="Throttling.RateQuota"||$==="Throttling.AllocationQuota")return new u(`Rate limit or quota exceeded. ${i}`,h.QUOTA,`Please wait and retry, or check your DashScope quota at
97
97
  https://bailian.console.aliyun.com/cn-beijing/?source_channel=aliway&tab=app#/api-key`);if(e===408||e===504)return new u(`Request timed out (HTTP ${e}).`,h.TIMEOUT,"Try increasing --timeout or retry later.");if($==="InvalidParameter"||$==="BadRequest")return new u(`Invalid parameter: ${i}`,h.USAGE);if($==="ModelNotFound"||$==="AccessDenied")return new u(`Model access denied or not found: ${i}`,h.AUTH,"Check model availability at https://bailian.console.aliyun.com/cn-beijing/?source_channel=aliway&tab=app#/api-key");if($==="DataInspectionFailed")return new u(`Content flagged by safety filter: ${i}`,h.CONTENT_FILTER);return new u(`API error: ${i} (HTTP ${e}${$?`, code: ${$}`:""})`,h.GENERAL)}import{homedir as Vt}from"os";function g(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:"***"}var Et=!1;var ee="\x1B[0m",xe="\x1B[2m",sn="\x1B[1m",Fn="\x1B[38;2;43;82;255m",an="\x1B[38;2;147;51;234m",Dn="\x1B[38;2;6;184;212m",ln="\x1B[38;2;236;72;153m";function fn(e){return e.startsWith(Vt())?e.replace(Vt(),"~"):e}function ce(e,t,n){if(e.quiet||Et||!process.stderr.isTTY)return;Et=!0;let i=e.configPath?fn(e.configPath):"~/.bailian/config.json",$=e.fileRegion?`${e.fileRegion} (file)`:"cn (default)",p=e.apiKey?"(flag)":"(file)",r=g(t),y=n?` ${xe}|${ee} ${xe}Model:${ee} ${an}${n}${ee}`:"";process.stderr.write(`${sn}${Fn}BAILIAN${ee} ${xe}${i}${ee} ${xe}|${ee} ${xe}Region:${ee} ${Dn}${$}${ee} ${xe}|${ee} ${xe}Key:${ee} ${ln}${r}${ee} ${xe}${p}${ee}${y}
98
- `)}var gn={t1:"public",t2:""},rt=JSON.stringify({channel:"bailian-cli",tags:gn});function d(){return{"x-dashscope-source-config":rt}}async function ye(e,t){let n=typeof FormData<"u"&&t.body instanceof FormData,i="0.1.2-beta.0",$={"User-Agent":"bailian-cli/0.1.2-beta.0",...d(),...t.headers};if(!n&&!$["Content-Type"])$["Content-Type"]="application/json";if(t.async)$["X-DashScope-Async"]="enable";if(t.ossResolve)$["X-DashScope-OssResourceResolve"]="enable";if(!t.noAuth){let m=await V(e);if($.Authorization=`Bearer ${m.token}`,e.verbose)process.stderr.write(`> ${t.method??"GET"} ${t.url}
98
+ `)}var gn={t1:"public",t2:""},rt=JSON.stringify({channel:"bailian-cli",tags:gn});function d(){return{"x-dashscope-source-config":rt}}async function ye(e,t){let n=typeof FormData<"u"&&t.body instanceof FormData,i="0.1.2",$={"User-Agent":"bailian-cli/0.1.2",...d(),...t.headers};if(!n&&!$["Content-Type"])$["Content-Type"]="application/json";if(t.async)$["X-DashScope-Async"]="enable";if(t.ossResolve)$["X-DashScope-OssResourceResolve"]="enable";if(!t.noAuth){let m=await V(e);if($.Authorization=`Bearer ${m.token}`,e.verbose)process.stderr.write(`> ${t.method??"GET"} ${t.url}
99
99
  `),process.stderr.write(`> Auth: ${m.token.slice(0,8)}...
100
100
  `),process.stderr.write(`> x-dashscope-source-config: ${rt}
101
101
  `);let x=t.body&&typeof t.body==="object"&&"model"in t.body?String(t.body.model):void 0;ce(e,m.token,x)}let p=(t.timeout??e.timeout)*1000,r=await fetch(t.url,{method:t.method??"GET",headers:$,body:t.body?n?t.body:JSON.stringify(t.body):void 0,signal:AbortSignal.timeout(p)}),y=r.headers.get("x-request-id");if(e.verbose)process.stderr.write(`< ${r.status} ${r.statusText}
@@ -181,7 +181,7 @@ Or set output_dir: bl config set --key output_dir --value ~/my-output`);let $=B(
181
181
  `),process.exit(1);if(rn(k))i.push(k);else n=k}else throw new u("Missing required argument --image or --video.",h.USAGE,`bl vision describe --image <path-or-url>
182
182
  bl vision describe --video <url-or-path>`);let m=B(e.output);if(e.dryRun){A({request:{prompt:y,image:n,video:i.length?i:void 0,model:$}},m);return}let x=[],b=!1;if(i.length>0)for(let k of i){let G=k;if(de(k)){if(!nn(k))throw new u(`Video file not found: ${k}`,h.USAGE);let z=await V(e);if(G=await E(k,z.token,$,e.quiet),G.startsWith("oss://"))b=!0}x.push({type:"video_url",video_url:{url:G}})}if(n){let k=await a$(n),G=k;if(de(n)&&k.startsWith("data:")){let{statSync:z}=await import("fs");if(z(n).size>5242880){let Z=await V(e);if(G=await E(n,Z.token,$,e.quiet),G.startsWith("oss://"))b=!0}}x.push({type:"image_url",image_url:{url:G}})}x.push({type:"text",text:y});let w={model:$,messages:[{role:"user",content:x}]},S=be(e.baseUrl),q=await Q(e,{url:S,method:"POST",body:w,ossResolve:b}),o=q.choices?.[0]?.message?.content;if(m!=="text"){A(q,m);return}N(o||"")}});var yn=K({name:"config show",description:"Display current configuration",usage:"bl config show",examples:["bl config show","bl config show --output json"],async run(e,t){let n=te(),i=B(e.output),$={region:e.region,base_url:e.baseUrl,output:e.output,timeout:e.timeout,config_file:ie()};if(n.api_key)$.api_key=g(n.api_key);if(n.default_text_model)$.default_text_model=n.default_text_model;if(n.default_video_model)$.default_video_model=n.default_video_model;if(n.default_image_model)$.default_image_model=n.default_image_model;A($,i)}});var _n=["region","base_url","output","output_dir","timeout","api_key","default_text_model","default_video_model","default_image_model","default_speech_model","default_omni_model","access_key_id","access_key_secret","workspace_id"],D$={"base-url":"base_url","output-dir":"output_dir","api-key":"api_key","default-text-model":"default_text_model","default-video-model":"default_video_model","default-image-model":"default_image_model","default-speech-model":"default_speech_model","default-omni-model":"default_omni_model","access-key-id":"access_key_id","access-key-secret":"access_key_secret","workspace-id":"workspace_id"},mn=K({name:"config set",description:"Set a config value",usage:"bl config set --key <key> --value <value>",options:[{flag:"--key <key>",description:"Config key (region, base_url, output, output_dir, timeout, api_key, default_*_model, access_key_id, access_key_secret, workspace_id)"},{flag:"--value <value>",description:"Value to set"}],examples:["bl config set --key output --value json","bl config set --key timeout --value 600","bl config set --key base_url --value https://dashscope.aliyuncs.com"],async run(e,t){let{key:n,value:i}=t;if(!n||i===void 0)throw new u("--key and --value are required.",h.USAGE,"bl config set --key <key> --value <value>");let $=D$[n]||n;if(!_n.includes($))throw new u(`Invalid config key "${n}". Valid keys: ${_n.join(", ")}`,h.USAGE);if($==="region"&&!["cn","us","intl"].includes(i))throw new u(`Invalid region "${i}". Valid values: cn, us, intl`,h.USAGE);if($==="output"&&!["text","json"].includes(i))throw new u(`Invalid output format "${i}". Valid values: text, json`,h.USAGE);if($==="timeout"){let y=Number(i);if(isNaN(y)||y<=0)throw new u(`Invalid timeout "${i}". Must be a positive number.`,h.USAGE)}let p=B(e.output);if(e.dryRun){A({would_set:{[$]:i}},p);return}let r=te();if(r[$]=$==="timeout"?Number(i):i,await Je(r),!e.quiet)A({[$]:r[$]},p)}});function l$(e){let t=e.match(/^--([a-zA-Z0-9-]+)/),n=t?t[1]:"",i=n.replace(/-([a-zA-Z0-9])/g,(r,y)=>y.toUpperCase()),$="string",p=!1;if(!e.includes("<")&&!e.includes("["))$="boolean";else if(e.includes("<n>")||e.includes("<hz>")||e.includes("<bps>")||e.includes("<count>"))$="number";if(e.toLowerCase().includes("repeatable"))p=!0;return{name:i,kebabName:n,inferredType:$,isArray:p}}function Ht(e){let n={name:`bailian_${e.name.replace(/ /g,"_")}`,description:e.description,input_schema:{type:"object",properties:{},required:[]}};if(e.options)for(let i of e.options){let{name:$,inferredType:p,isArray:r}=l$(i.flag);if(!$)continue;let y=i.type,m=r?"array":y??p,x={description:i.description};if(m==="array")x.type="array",x.items={type:"string"};else x.type=m;let b=n.input_schema;if(b.properties[$]=x,i.required)b.required.push($)}return n}var f$=["auth ","config ","update"],xn=K({name:"config export-schema",description:"Export all (or one) CLI command(s) as Anthropic/OpenAI-compatible JSON tool schemas",usage:'bl config export-schema [--command "<name>"]',options:[{flag:"--command <name>",description:'Export schema for a specific command only (e.g. "image generate")'}],examples:["bl config export-schema",'bl config export-schema --command "video generate"'],async run(e,t){let n=t.command;if(n){try{let{command:p}=me.resolve(n.split(" ")),r=Ht(p);process.stdout.write(JSON.stringify(r,null,2)+`
183
183
  `)}catch{throw new u(`Command "${n}" not found.`,h.USAGE)}return}let $=me.getAllCommands().filter((p)=>!f$.some((r)=>p.name.startsWith(r))).map((p)=>Ht(p));process.stdout.write(JSON.stringify($,null,2)+`
184
- `)}});import{execSync as bn}from"child_process";import{writeFileSync as g$}from"fs";import{join as ep}from"path";var ae="0.1.2-beta.0";async function tp(){try{let e=Be.replace("/","%2f"),t=await fetch(`${He}/${e}/latest`,{headers:{Accept:"application/json",...d()},signal:AbortSignal.timeout(5000)});if(!t.ok)return null;return(await t.json()).version??null}catch{return null}}function rp(e="latest"){return{cmd:`npm install -g ${Be}@${e} --registry=${He}`,label:"npm"}}var wn=K({name:"update",description:"Update bl to the latest version",usage:"bl update",examples:["bl update"],async run(){let e=process.stderr.isTTY,t=e?"\x1B[32m":"",n=e?"\x1B[33m":"",i=e?"\x1B[0m":"";process.stderr.write(`Current version: ${n}${ae}${i}
184
+ `)}});import{execSync as bn}from"child_process";import{writeFileSync as g$}from"fs";import{join as ep}from"path";var ae="0.1.2";async function tp(){try{let e=Be.replace("/","%2f"),t=await fetch(`${He}/${e}/latest`,{headers:{Accept:"application/json",...d()},signal:AbortSignal.timeout(5000)});if(!t.ok)return null;return(await t.json()).version??null}catch{return null}}function rp(e="latest"){return{cmd:`npm install -g ${Be}@${e} --registry=${He}`,label:"npm"}}var wn=K({name:"update",description:"Update bl to the latest version",usage:"bl update",examples:["bl update"],async run(){let e=process.stderr.isTTY,t=e?"\x1B[32m":"",n=e?"\x1B[33m":"",i=e?"\x1B[0m":"";process.stderr.write(`Current version: ${n}${ae}${i}
185
185
  `),process.stderr.write(`Checking for updates...
186
186
  `);let $=await tp();if($&&$===ae){process.stderr.write(`${t}✓ Already up to date (${ae}).${i}
187
187
  `);return}if($)process.stderr.write(`Latest version: ${t}${$}${i}
@@ -229,9 +229,9 @@ Set via: --access-key-id / --access-key-secret flags,
229
229
  Set via: --workspace-id flag, or env: BAILIAN_WORKSPACE_ID, or config: bl config set workspace_id <id>`,h.USAGE);let y={IndexId:n,Query:i};if(t.topK!==void 0)y.TopK=t.topK;if(t.rerank)y.Rerank=!0;if(t.rerankTopN!==void 0)y.RerankTopN=t.rerankTopN;let m=B(e.output),x=`/${r}/index/retrieve`;if(e.dryRun){A({endpoint:`https://${Zt}${x}`,workspaceId:r,request:y},m);return}let b=JSON.stringify(y),w=Bn({accessKeyId:$,accessKeySecret:p,action:"Retrieve",version:"2023-12-29",body:b,host:Zt,pathname:x}),S=`https://${Zt}${x}`;if(e.verbose)process.stderr.write(`> POST ${S}
230
230
  `),process.stderr.write(`> AK: ${$.slice(0,8)}...
231
231
  `);let q=e.timeout*1000,o=await fetch(S,{method:"POST",headers:{...w,...d()},body:b,signal:AbortSignal.timeout(q)});if(e.verbose)process.stderr.write(`< ${o.status} ${o.statusText}
232
- `);let k=await o.json();if(!o.ok||k.Code&&k.Code!=="Success")throw new u(`Knowledge retrieve failed: ${k.Code||o.status} - ${k.Message||o.statusText}`,h.GENERAL);if(e.quiet||m==="text"){let G=k.Data?.Nodes||[];if(G.length===0)N("No results found.");else for(let z=0;z<G.length;z++){let J=G[z];N(`[${z+1}] (score: ${J.Score.toFixed(4)})`),N(J.Text),N("")}}else A(k,m)}});class De{baseUrl;sessionId;nextId=1;config;authToken;constructor(e,t){this.config=e,this.baseUrl=t}async initialize(){let e=await V(this.config);this.authToken=e.token,ce(this.config,e.token,void 0);let t=await this.rpc("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"bailian-cli",version:"0.1.2-beta.0"}});if(this.config.verbose)process.stderr.write(`[MCP] Session initialized: ${this.sessionId??"no session"}
232
+ `);let k=await o.json();if(!o.ok||k.Code&&k.Code!=="Success")throw new u(`Knowledge retrieve failed: ${k.Code||o.status} - ${k.Message||o.statusText}`,h.GENERAL);if(e.quiet||m==="text"){let G=k.Data?.Nodes||[];if(G.length===0)N("No results found.");else for(let z=0;z<G.length;z++){let J=G[z];N(`[${z+1}] (score: ${J.Score.toFixed(4)})`),N(J.Text),N("")}}else A(k,m)}});class De{baseUrl;sessionId;nextId=1;config;authToken;constructor(e,t){this.config=e,this.baseUrl=t}async initialize(){let e=await V(this.config);this.authToken=e.token,ce(this.config,e.token,void 0);let t=await this.rpc("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"bailian-cli",version:"0.1.2"}});if(this.config.verbose)process.stderr.write(`[MCP] Session initialized: ${this.sessionId??"no session"}
233
233
  `),process.stderr.write(`[MCP] Server: ${JSON.stringify(t)}
234
- `);await this.notify("notifications/initialized")}async listTools(){return(await this.rpc("tools/list")).tools||[]}async callTool(e,t){return await this.rpc("tools/call",{name:e,arguments:t})}async rpc(e,t){let i={jsonrpc:"2.0",id:this.nextId++,method:e,...t?{params:t}:{}},p=await(await this.send(i)).json();if(p.error)throw new u(`MCP error (${p.error.code}): ${p.error.message}`,h.GENERAL);return p.result}async notify(e,t){let n={jsonrpc:"2.0",method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":"bailian-cli/0.1.2-beta.0",...d()};if(this.authToken)t.Authorization=`Bearer ${this.authToken}`;if(this.sessionId)t["Mcp-Session-Id"]=this.sessionId;if(this.config.verbose)process.stderr.write(`> POST ${this.baseUrl}
234
+ `);await this.notify("notifications/initialized")}async listTools(){return(await this.rpc("tools/list")).tools||[]}async callTool(e,t){return await this.rpc("tools/call",{name:e,arguments:t})}async rpc(e,t){let i={jsonrpc:"2.0",id:this.nextId++,method:e,...t?{params:t}:{}},p=await(await this.send(i)).json();if(p.error)throw new u(`MCP error (${p.error.code}): ${p.error.message}`,h.GENERAL);return p.result}async notify(e,t){let n={jsonrpc:"2.0",method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":"bailian-cli/0.1.2",...d()};if(this.authToken)t.Authorization=`Bearer ${this.authToken}`;if(this.sessionId)t["Mcp-Session-Id"]=this.sessionId;if(this.config.verbose)process.stderr.write(`> POST ${this.baseUrl}
235
235
  `),process.stderr.write(`> Method: ${e.method}
236
236
  `);let n=this.config.timeout*1000,i=await fetch(this.baseUrl,{method:"POST",headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});if(this.config.verbose)process.stderr.write(`< ${i.status} ${i.statusText}
237
237
  `);let $=i.headers.get("Mcp-Session-Id")||i.headers.get("mcp-session-id");if($)this.sessionId=$;if(!i.ok){let p=`MCP request failed: ${i.status} ${i.statusText}`;try{let r=await i.text();if(r)p+=` - ${r.slice(0,500)}`}catch{}throw new u(p,h.GENERAL)}return i}}var Rn=K({name:"search web",description:"Search the web using DashScope MCP WebSearch service",usage:"bl search web --query <text> [flags]",options:[{flag:"--query <text>",description:"Search query text",required:!0},{flag:"--count <n>",description:"Number of search results (default: 10)",type:"number"},{flag:"--list-tools",description:"List available MCP tools and exit"}],examples:['bl search web --query "阿里云百炼最新功能"','bl search web --query "TypeScript 5.9 new features" --count 5','bl search web --query "今日新闻"',"bl search web --list-tools"],async run(e,t){let n=Ft(e.baseUrl),i=B(e.output);if(t.listTools){if(e.dryRun){A({endpoint:n,action:"tools/list"},i);return}let y=new De(e,n);await y.initialize();let m=await y.listTools();A({tools:m},i);return}let $=t.query;if(!$)if(Y({nonInteractive:e.nonInteractive})){let y=await L({message:"Enter your search query:"});if(!y)process.stderr.write(`Search cancelled.
@@ -354,7 +354,7 @@ Error: ${String(e)}
354
354
  `);process.exit(h.GENERAL)}import{join as Sp}from"path";import{readFileSync as kp,writeFileSync as qp}from"fs";var Zn=()=>Sp(Re(),"update-state.json"),op=14400000,Gp=3000;function Hn(e,t){let n=e.split(".").map(Number),i=t.split(".").map(Number);for(let $=0;$<3;$++){if((n[$]??0)>(i[$]??0))return!0;if((n[$]??0)<(i[$]??0))return!1}return!1}function Kp(){try{let e=kp(Zn(),"utf-8");return JSON.parse(e)}catch{return null}}function Np(e){try{qp(Zn(),JSON.stringify(e))}catch{}}async function Bp(){try{let e=Be.replace("/","%2f"),t=await fetch(`${He}/${e}/latest`,{headers:{Accept:"application/json",...d()},signal:AbortSignal.timeout(Gp)});if(!t.ok)return null;return(await t.json()).version??null}catch{return null}}var Xt=null;function zn(){return Xt}async function Xn(e){if(process.env.CI||!process.stderr.isTTY)return;let t=Kp(),n=Date.now();if(t&&n-t.lastChecked<op){if(t.latestVersion&&Hn(t.latestVersion,e))Xt=t.latestVersion;return}let i=await Bp();if(!i)return;if(Np({lastChecked:n,latestVersion:i}),i&&Hn(i,e))Xt=i}async function Pn(e){if(e.apiKey||e.fileApiKey)return;let t=process.env.DASHSCOPE_API_KEY,n;if(t){if(!Y({nonInteractive:e.nonInteractive}))n=t;else if(await Yr({message:`Found DASHSCOPE_API_KEY in environment (${g(t)}). Save it to config file?`}))n=t}if(!n){if(!Y({nonInteractive:e.nonInteractive}))throw new u("No API key found.",h.AUTH,`Set env var: export DASHSCOPE_API_KEY=sk-xxxxx
355
355
  Pass directly: --api-key sk-xxxxx
356
356
  Get API Key: https://bailian.console.aliyun.com/cn-beijing/?source_channel=aliway&tab=app#/api-key`);let p=await L({message:"Enter your DashScope API key:"});if(!p)throw new u("API key is required.",h.AUTH);n=p}let i={...te(),api_key:n};await Je(i),e.fileApiKey=n;let $=e.configPath??"~/.bailian/config.json";process.stderr.write(`API key saved to ${$}
357
- `)}var Pt="0.1.2-beta.0";process.on("SIGINT",()=>{process.stderr.write(`
357
+ `)}var Pt="0.1.2";process.on("SIGINT",()=>{process.stderr.write(`
358
358
  Interrupted. Exiting.
359
359
  `),process.exit(130)});process.stdout.on("error",(e)=>{if(e.code==="EPIPE")process.exit(0);else throw e});var jp=[["auth","login"],["auth","logout"],["config","show"],["config","set"],["config","export-schema"],["update"],["knowledge","retrieve"]];async function Rp(){let e=process.argv.slice(2);if(e.includes("--version")||e.includes("-v"))process.stdout.write(`bl ${Pt}
360
360
  `),process.exit(0);let t=Ct(e,Oe);if(e.includes("--help")||e.includes("-h")){let b=e.indexOf("--region"),w=b>=0&&e[b+1]||process.env.DASHSCOPE_REGION||te().region||"cn";me.printHelp(t,process.stderr,w),process.exit(0)}if(t.length===0){me.printHelp([],process.stderr);let b=ge(e,Oe),w=mt(b);if(!(w.apiKey||w.fileApiKey)){let q=process.stderr.isTTY,o=q?"\x1B[38;2;147;51;234m":"",k=q?"\x1B[0m":"";process.stderr.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailian-cli",
3
- "version": "0.1.2-beta.0",
3
+ "version": "0.1.2",
4
4
  "description": "CLI for Alibaba Cloud Bailian (DashScope) AI Platform",
5
5
  "author": "ali-pizza",
6
6
  "license": "Apache-2.0",