@iamharshil/aix-cli 3.3.5 → 3.4.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.js CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
- var we=Object.defineProperty;var be=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>{for(var o in e)we(t,o,{get:e[o],enumerable:!0})};var ae={};L(ae,{ConfigService:()=>D,configService:()=>s});import Me from"conf";var D,s,M=O(()=>{"use strict";D=class{store;constructor(){this.store=new Me({projectName:"aix",defaults:{lmStudioUrl:"http://localhost",lmStudioPort:1234,lmStudioContextLength:32768,ollamaUrl:"http://localhost",ollamaPort:11434,defaultTimeout:3e4,autoStartServer:!1},clearInvalidConfig:!0})}get(e){return this.store.get(e)}set(e,o){this.store.set(e,o)}delete(e){this.store.delete(e)}setModel(e){this.store.set("model",e)}getLastUsedModel(){return this.store.get("model")}setDefaultProvider(e){this.store.set("defaultProvider",e)}getDefaultProvider(){return this.store.get("defaultProvider")}setDefaultBackend(e){this.store.set("defaultBackend",e)}getDefaultBackend(){return this.store.get("defaultBackend")}getLMStudioUrl(){let e=this.store.get("lmStudioUrl"),o=this.store.get("lmStudioPort");return`${e}:${o}`}getOllamaUrl(){let e=this.store.get("ollamaUrl"),o=this.store.get("ollamaPort");return`${e}:${o}`}reset(){this.store.clear()}},s=new D});var ce={};L(ce,{LMStudioService:()=>_,lmStudioService:()=>v});import{execa as z}from"execa";import se from"ora";import le from"chalk";var de,_,v,A=O(()=>{"use strict";M();de=[1234,1235,1236,1237],_=class{baseUrl;constructor(){this.baseUrl=s.getLMStudioUrl()}getApiUrl(e){return`${this.baseUrl}${e}`}async checkStatus(){try{return(await fetch(this.getApiUrl("/api/status"),{method:"GET",signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async getAvailableModels(){let e=["/api/v1/models","/api/models","/v1/models","/api/ls-model/list"];for(let o of e)try{let i=await fetch(this.getApiUrl(o),{method:"GET",signal:AbortSignal.timeout(1e4)});if(!i.ok)continue;let n=await i.json(),r=[];return Array.isArray(n)?r=n:n.models&&Array.isArray(n.models)?r=n.models:n.data&&Array.isArray(n.data)&&(r=n.data),r.map(a=>{let l=a;return{id:String(l.key||l.id||l.model||""),name:String(l.display_name||l.name||l.id||l.model||""),size:Number(l.size_bytes||l.size||l.file_size||0),quantization:String(l.quantization?typeof l.quantization=="object"?l.quantization.name:l.quantization:"")}}).filter(a=>a.id&&a.name)}catch{continue}return[]}async getStatus(){if(!await this.checkStatus())return{running:!1,port:s.get("lmStudioPort"),models:[]};try{let o=await fetch(this.getApiUrl("/api/status"),{method:"GET",signal:AbortSignal.timeout(1e4)});if(!o.ok)return{running:!1,port:s.get("lmStudioPort"),models:[]};let i=await o.json();return{running:!0,port:s.get("lmStudioPort"),models:i.models??[],activeModel:i.active_model}}catch{return{running:!1,port:s.get("lmStudioPort"),models:[]}}}async loadModel(e,o){let i=o??se({text:`Loading model: ${le.cyan(e)}`,color:"cyan"}).start();try{let n=s.get("lmStudioContextLength"),r=await fetch(this.getApiUrl("/api/model/load"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e,context_length:n}),signal:AbortSignal.timeout(3e5)});if(!r.ok)throw new Error(`Failed to load model: ${r.statusText}`);return i.succeed(`Model ${le.green(e)} loaded successfully`),s.setModel(e),{loadSpinner:i}}catch(n){throw i.fail(`Failed to load model: ${n instanceof Error?n.message:"Unknown error"}`),n}}async startServer(e){let o=e??se({text:"Starting LM Studio server...",color:"cyan"}).start();try{let i=process.platform==="darwin",n=process.platform==="linux",r=process.platform==="win32",a;if(i){let l=["/Applications/LM Studio.app",`${process.env.HOME}/Applications/LM Studio.app`];for(let m of l)try{let{existsSync:u}=await import("fs");if(u(m)){a=`open "${m}" --args --server`;break}}catch{}if(a?.startsWith("open")){await z("open",[l.find(m=>{try{let{existsSync:u}=be("fs");return u(m)}catch{return!1}})||"/Applications/LM Studio.app","--args","--server"],{detached:!0,stdio:"ignore"}),o.succeed("LM Studio server started"),await this.waitForServer(6e4);return}}else n?a=await this.findLinuxBinary():r&&(a=await this.findWindowsExecutable());if(!a)throw o.fail("LM Studio not found. Please install it from https://lmstudio.ai"),new Error("LM Studio not installed");await z(a,["--server"],{detached:!0,stdio:"ignore",env:{...process.env,LM_STUDIO_SERVER_PORT:String(s.get("lmStudioPort"))}}),o.succeed("LM Studio server started"),await this.waitForServer(6e4)}catch(i){throw o.fail(`Failed to start LM Studio: ${i instanceof Error?i.message:"Unknown error"}`),i}}async findLinuxBinary(){let e=["/usr/bin/lm-studio","/usr/local/bin/lm-studio",`${process.env.HOME}/.local/bin/lm-studio`];for(let o of e)try{return await z("test",["-x",o]),o}catch{continue}}async findWindowsExecutable(){let e=process.env.LOCALAPPDATA,o=process.env.PROGRAMFILES,i=[e?`${e}\\Programs\\LM Studio\\lm-studio.exe`:"",o?`${o}\\LM Studio\\lm-studio.exe`:""].filter(Boolean);for(let n of i)try{return await z("cmd",["/c","if exist",`"${n}"`,"echo","yes"]),n}catch{continue}}async waitForServer(e=6e4){let o=Date.now();for(;Date.now()-o<e;){if(await this.checkStatus())return!0;await this.sleep(2e3)}return!1}sleep(e){return new Promise(o=>setTimeout(o,e))}async findAvailablePort(){for(let e of de)try{if((await fetch(`http://localhost:${e}/api/status`,{method:"GET",signal:AbortSignal.timeout(1e3)})).ok)return e}catch{return s.set("lmStudioPort",e),e}return de[0]??1234}},v=new _});var ue={};L(ue,{OllamaService:()=>T,ollamaService:()=>w});var T,w,E=O(()=>{"use strict";M();T=class{getBaseUrl(){return s.getOllamaUrl()}getApiUrl(e){return`${this.getBaseUrl()}${e}`}async checkStatus(){try{return(await fetch(this.getApiUrl("/api/tags"),{method:"GET",signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async getAvailableModels(){try{let e=await fetch(this.getApiUrl("/api/tags"),{method:"GET",signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).models??[]).map(n=>{let r=n.details??{};return{id:String(n.name??n.model??""),name:String(n.name??n.model??""),size:Number(n.size??0),quantization:String(r.quantization_level??""),family:String(r.family??""),parameterSize:String(r.parameter_size??"")}}).filter(n=>n.id&&n.name):[]}catch{return[]}}async getRunningModels(){try{let e=await fetch(this.getApiUrl("/api/ps"),{method:"GET",signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models??[]).map(n=>String(n.name??n.model??"")).filter(Boolean):[]}catch{return[]}}async getStatus(){if(!await this.checkStatus())return{running:!1,port:s.get("ollamaPort"),models:[],runningModels:[]};let[o,i]=await Promise.all([this.getAvailableModels(),this.getRunningModels()]);return{running:!0,port:s.get("ollamaPort"),models:o,runningModels:i}}},w=new T});var ge={};L(ge,{ClaudeService:()=>G,claudeService:()=>R});import{execa as J}from"execa";import xe from"chalk";var G,R,Q=O(()=>{"use strict";M();G=class{async isClaudeCodeInstalled(){try{return await J("claude",["--version"],{stdio:"ignore"}),!0}catch{return!1}}async run(e){let{model:o,args:i=[],verbose:n=!1}=e,r=this.extractProvider(o),a=this.extractModelName(o);if(!r||!a)throw new Error(`Invalid model format: ${o}. Expected format: provider/model-name`);let l=["--model",a,...i];n&&console.log(xe.dim(`
3
- Running: claude ${l.join(" ")}
4
- `));let m=r==="ollama"?s.getOllamaUrl():s.getLMStudioUrl(),u=r==="ollama"?"ollama":"lmstudio";try{await J("claude",l,{stdio:"inherit",env:{...process.env,ANTHROPIC_MODEL:a,ANTHROPIC_BASE_URL:m,ANTHROPIC_AUTH_TOKEN:u,ANTHROPIC_API_KEY:""}})}catch(c){if(c instanceof Error&&"exitCode"in c){let S=c.exitCode;process.exit(S??1)}throw c}}extractProvider(e){return e.split("/")[0]}extractModelName(e){let o=e.split("/");if(!(o.length<2))return o.slice(1).join("/")}async getVersion(){try{return(await J("claude",["--version"])).stdout}catch{return}}},R=new G});var pe={};L(pe,{OpenCodeService:()=>W,openCodeService:()=>U});import{execa as Z}from"execa";import Oe from"chalk";var W,U,ee=O(()=>{"use strict";M();W=class{async isOpenCodeInstalled(){try{return await Z("opencode",["--version"],{stdio:"ignore"}),!0}catch{return!1}}async run(e){let{model:o,args:i=[],verbose:n=!1}=e,r=this.extractProvider(o),a=this.extractModelName(o);if(!r||!a)throw new Error(`Invalid model format: ${o}. Expected format: provider/model-name`);let l=["--model",a,...i];n&&console.log(Oe.dim(`
5
- Running: opencode ${l.join(" ")}
6
- `));let u=`${r==="ollama"?s.getOllamaUrl():s.getLMStudioUrl()}/v1`,c=r==="ollama"?"ollama":"openai-compatible";try{await Z("opencode",l,{stdio:"inherit",env:{...process.env,OPENCODE_MODEL_NAME:a,OPENCODE_MODEL_PROVIDER:c,OPENAI_BASE_URL:u,OPENAI_API_KEY:"local-no-key-required",OPENAI_COMPATIBLE_BASE_URL:u,OPENAI_COMPATIBLE_API_KEY:"local-no-key-required"}})}catch(S){if(S instanceof Error&&"exitCode"in S){let P=S.exitCode;process.exit(P??1)}throw S}}extractProvider(e){return e.split("/")[0]}extractModelName(e){let o=e.split("/");if(!(o.length<2))return o.slice(1).join("/")}async getVersion(){try{return(await Z("opencode",["--version"])).stdout}catch{return}}},U=new W});import{Command as De}from"commander";import g from"chalk";A();E();M();import F from"ora";import p from"chalk";import K from"inquirer";import me from"inquirer";async function k(t,e){let o=t.map(r=>({name:`${r.name} (${r.id})`,value:r,short:r.name})),i=e?o.findIndex(r=>r.value.id===e):0;return(await me.prompt([{type:"list",name:"model",message:"Select a model to load:",choices:o,default:Math.max(0,i),pageSize:Math.min(t.length,15)}])).model}async function j(t,e=!0){return(await me.prompt([{type:"confirm",name:"confirm",message:t,default:e}])).confirm}import H from"chalk";function C(t){if(t===0)return"0 B";let e=1024,o=["B","KB","MB","GB","TB"],i=Math.floor(Math.log(t)/Math.log(e));return`${parseFloat((t/Math.pow(e,i)).toFixed(2))} ${o[i]}`}function y(t){console.log(H.green("\u2713")+" "+t)}function X(t){console.error(H.red("\u2717")+" "+t)}function q(t){console.log(H.blue("\u2139")+" "+t)}function f(t,e=1){X(t),process.exit(e)}async function $e(){let t=s.getDefaultBackend(),{backendSelection:e}=await K.prompt([{type:"list",name:"backendSelection",message:"Select model backend:",default:t??"lmstudio",choices:[{name:"\u{1F5A5}\uFE0F LM Studio",value:"lmstudio"},{name:"\u{1F999} Ollama",value:"ollama"}]}]),{saveDefault:o}=await K.prompt([{type:"confirm",name:"saveDefault",message:"Save as default backend?",default:!1}]);return o&&(s.setDefaultBackend(e),y(`Default backend set to ${p.cyan(e)}`)),e}async function Pe(t){let e=s.getDefaultProvider(),o=[{name:"Claude Code",value:"claude"},{name:"OpenCode",value:"opencode"}],i=e??"claude",{providerSelection:n}=await K.prompt([{type:"list",name:"providerSelection",message:"Select coding tool:",default:i,choices:o}]),{saveDefault:r}=await K.prompt([{type:"confirm",name:"saveDefault",message:"Save as default coding tool?",default:!1}]);return r&&(s.setDefaultProvider(n),y(`Default coding tool set to ${p.cyan(n)}`)),n}async function ke(t,e){let o=F({text:"Checking LM Studio status...",color:"cyan"}).start(),i=await v.checkStatus();i||(o.info("LM Studio server not running"),o.stop(),await j("Would you like to start the LM Studio server?")||f("LM Studio server must be running. Start it manually or use the Server tab in LM Studio."),await v.startServer(),i=!0),o.succeed("Connected to LM Studio");let n=F({text:"Fetching available models...",color:"cyan"}).start(),r=await v.getAvailableModels();r.length===0&&(n.fail("No models found. Download some models in LM Studio first."),f("No models available")),n.succeed(`Found ${p.bold(r.length)} model${r.length===1?"":"s"}`),console.log(),console.log(p.bold("Available Models:")),console.log(p.dim("\u2500".repeat(process.stdout.columns||80))),r.forEach((c,S)=>{let P=C(c.size),$=c.loaded?p.green(" [LOADED]"):"";console.log(` ${p.dim(String(S+1).padStart(2))}. ${c.name} ${p.dim(`(${P})`)}${$}`)}),console.log();let a=s.getLastUsedModel(),l=t.model,m=l?r.find(c=>c.id===l||c.name.includes(l)):await k(r,a);m||f("No model selected"),await v.loadModel(m.id,o);let u=m.id;y(p.bold(`
7
- Model ready: ${m.name}`)),console.log(),console.log("Start your interactive coding session:"),console.log(` ${p.cyan(`aix-cli run --provider ${e} --backend lmstudio --model ${u}`)}`),console.log()}async function Ce(t,e){let o=F({text:"Checking Ollama status...",color:"cyan"}).start();await w.checkStatus()||(o.fail("Ollama is not running"),f("Ollama must be running. Start it with: ollama serve")),o.succeed("Connected to Ollama");let n=F({text:"Fetching available models...",color:"cyan"}).start(),r=await w.getAvailableModels();r.length===0&&(n.fail("No models found. Pull a model first: ollama pull <model>"),f("No models available")),n.succeed(`Found ${p.bold(r.length)} model${r.length===1?"":"s"}`);let a=await w.getRunningModels();console.log(),console.log(p.bold("Available Models:")),console.log(p.dim("\u2500".repeat(process.stdout.columns||80))),r.forEach((c,S)=>{let P=C(c.size),V=a.includes(c.id)?p.green(" [RUNNING]"):"",ye=c.parameterSize?p.dim(` ${c.parameterSize}`):"";console.log(` ${p.dim(String(S+1).padStart(2))}. ${c.name}${ye} ${p.dim(`(${P})`)}${V}`)}),console.log();let l=s.getLastUsedModel(),m=t.model,u=m?r.find(c=>c.id===m||c.name.includes(m)):await k(r,l);u||f("No model selected"),s.setModel(u.id),y(p.bold(`
8
- Model selected: ${u.name}`)),console.log(),console.log("Start your interactive coding session:"),console.log(` ${p.cyan(`aix-cli run --provider ${e} --backend ollama --model ${u.id}`)}`),console.log()}async function Y(t={}){let e=t.backend??await $e(),o=t.provider??await Pe(e);e==="ollama"?await Ce(t,o):await ke(t,o)}A();E();Q();ee();M();import x from"ora";import fe from"chalk";import ve from"inquirer";async function Le(t){let e=s.getDefaultBackend();if(e)return e;let{backendSelection:o}=await ve.prompt([{type:"list",name:"backendSelection",message:"Select model backend:",choices:[{name:"\u{1F5A5}\uFE0F LM Studio",value:"lmstudio"},{name:"\u{1F999} Ollama",value:"ollama"}]}]);return o}async function Ae(){let t=await R.isClaudeCodeInstalled(),e=await U.isOpenCodeInstalled(),o=[{name:"Claude Code",value:"claude",disabled:t?!1:"Not installed (install: npm i -g @anthropic-ai/claude-code)"},{name:"OpenCode",value:"opencode",disabled:e?!1:"Not installed (install: npm i -g opencode-ai)"}];!t&&!e&&f("Neither Claude Code nor OpenCode is installed.");let{providerSelection:i}=await ve.prompt([{type:"list",name:"providerSelection",message:"Select coding tool:",choices:o}]);return i}function I(t){return t==="opencode"?"OpenCode":"Claude Code"}async function Ee(t,e){let o=x({text:"Checking LM Studio status...",color:"cyan"}).start(),i=await v.checkStatus();i||(o.info("LM Studio server not running"),o.stop(),await j("Would you like to start the LM Studio server?")||f("LM Studio server must be running. Start it manually or use the Server tab in LM Studio."),await v.startServer(),i=!0),o.succeed("Connected to LM Studio");let n=x({text:"Fetching available models...",color:"cyan"}).start(),r=await v.getAvailableModels();r.length===0&&(n.fail("No models found. Download some models in LM Studio first."),f("No models available")),n.stop();let a;if(t.model){let u=r.find(c=>c.id===t.model||c.name.toLowerCase().includes(t.model.toLowerCase()));u||f(`Model "${t.model}" not found. Available models: ${r.map(c=>c.name).join(", ")}`),a=u.id}else{let u=s.getLastUsedModel();a=(await k(r,u)).id}let l=x({text:`Loading model: ${fe.cyan(a)}`,color:"cyan"}).start();await v.loadModel(a,l);let m=`lmstudio/${a}`;await he(e,m,t)}async function Re(t,e){let o=x({text:"Checking Ollama status...",color:"cyan"}).start();await w.checkStatus()||(o.fail("Ollama is not running"),f("Ollama must be running. Start it with: ollama serve")),o.succeed("Connected to Ollama");let n=x({text:"Fetching available models...",color:"cyan"}).start(),r=await w.getAvailableModels();r.length===0&&(n.fail("No models found. Pull a model first: ollama pull <model>"),f("No models available")),n.stop();let a;if(t.model){let m=r.find(u=>u.id===t.model||u.name.toLowerCase().includes(t.model.toLowerCase()));m||f(`Model "${t.model}" not found. Available models: ${r.map(u=>u.name).join(", ")}`),a=m.id}else{let m=s.getLastUsedModel();a=(await k(r,m)).id}s.setModel(a);let l=`ollama/${a}`;await he(e,l,t)}async function he(t,e,o){let i=I(t);y(fe.green(`
9
- Starting ${i} with model: ${e}
10
- `));try{t==="opencode"?await U.run({model:e,args:o.args??[],verbose:o.verbose}):await R.run({model:e,args:o.args??[],verbose:o.verbose})}catch(n){f(`Failed to run ${i}: ${n instanceof Error?n.message:"Unknown error"}`)}}async function oe(t={}){let e;if(t.provider)e=t.provider;else{let r=s.getDefaultProvider();r?e=r:e=await Ae()}let o=x({text:`Checking ${I(e)} installation...`,color:"cyan"}).start();(e==="opencode"?await U.isOpenCodeInstalled():await R.isClaudeCodeInstalled())||(o.fail(`${I(e)} is not installed.`),f(`Please install ${I(e)} first.`)),o.succeed(`${I(e)} is installed`);let n=t.backend??await Le(e);n==="ollama"&&e==="claude"&&f("Claude Code requires an Anthropic-compatible API. LM Studio supports this natively, but Ollama does not. Please select OpenCode for Ollama, or switch to LM Studio."),n==="ollama"?await Re(t,e):await Ee(t,e)}A();E();import d from"chalk";async function te(){let[t,e]=await Promise.all([v.getStatus(),w.getStatus()]);console.log(),console.log(d.bold("LM Studio")),console.log(d.dim("\u2500".repeat(50))),console.log(` ${t.running?d.green("\u25CF"):d.red("\u25CB")} Server: ${t.running?d.green("Running"):d.red("Stopped")}`),console.log(` ${d.dim("\u25B8")} Port: ${d.cyan(String(t.port))}`),console.log(` ${d.dim("\u25B8")} URL: ${d.cyan(`http://localhost:${t.port}`)}`),t.activeModel&&console.log(` ${d.dim("\u25B8")} Active Model: ${d.green(t.activeModel)}`),t.running&&t.models.length>0?(console.log(),console.log(d.bold(" Models")),t.models.forEach((o,i)=>{let n=C(o.size),r=o.id===t.activeModel?` ${d.green("[LOADED]")}`:"";console.log(` ${d.dim(String(i+1)+".")} ${o.name}${r}`),console.log(` ${d.dim("ID:")} ${o.id}`),console.log(` ${d.dim("Size:")} ${n}`),o.quantization&&console.log(` ${d.dim("Quantization:")} ${o.quantization}`)})):t.running&&console.log(` ${d.dim("No models available")}`),console.log(),console.log(d.bold("Ollama")),console.log(d.dim("\u2500".repeat(50))),console.log(` ${e.running?d.green("\u25CF"):d.red("\u25CB")} Server: ${e.running?d.green("Running"):d.red("Stopped")}`),console.log(` ${d.dim("\u25B8")} Port: ${d.cyan(String(e.port))}`),console.log(` ${d.dim("\u25B8")} URL: ${d.cyan(`http://localhost:${e.port}`)}`),e.running&&e.runningModels.length>0&&console.log(` ${d.dim("\u25B8")} Running: ${d.green(e.runningModels.join(", "))}`),e.running&&e.models.length>0?(console.log(),console.log(d.bold(" Models")),e.models.forEach((o,i)=>{let n=C(o.size),a=e.runningModels.includes(o.id)?` ${d.green("[RUNNING]")}`:"",l=o.parameterSize?` ${d.dim(o.parameterSize)}`:"";console.log(` ${d.dim(String(i+1)+".")} ${o.name}${l}${a}`),console.log(` ${d.dim("Size:")} ${n}`),o.family&&console.log(` ${d.dim("Family:")} ${o.family}`),o.quantization&&console.log(` ${d.dim("Quantization:")} ${o.quantization}`)})):e.running&&console.log(` ${d.dim("No models available")}`),console.log()}import Ue from"ora";import N from"chalk";import{execa as Se}from"execa";import{readFileSync as Ie}from"fs";import{fileURLToPath as Ne}from"url";function ne(){try{let t=Ne(new URL("../../package.json",import.meta.url)),e=JSON.parse(Ie(t,"utf8"));return String(e.version)}catch{return"unknown"}}async function re(){let t=Ue({text:"Checking for updates...",color:"cyan"}).start();try{let e=ne();if(e==="unknown"){t.fail("Could not determine current version.");return}let{stdout:o}=await Se("npm",["view","@iamharshil/aix-cli","version"]),i=o.trim();if(e===i){t.succeed(`You're already on the latest version: ${N.green(`v${e}`)}`);return}t.text=`Updating: ${N.yellow(`v${e}`)} \u2192 ${N.green(`v${i}`)}...`,await Se("npm",["install","-g","@iamharshil/aix-cli@latest"]),t.succeed(`Successfully updated to ${N.green(`v${i}`)}! \u{1F680}`),q(`Restart your terminal or run ${N.cyan("aix-cli --help")} to see what's new.`)}catch(e){t.fail("Failed to update."),X(e instanceof Error?e.message:String(e))}}M();import h from"chalk";import Be from"inquirer";async function ie(t,e,o){if(t==="reset"){let{confirm:n}=await Be.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to completely reset all configuration to defaults?",default:!1}]);n?(s.reset(),y("Configuration has been reset to defaults.")):q("Reset cancelled.");return}if(t==="set"&&e&&o){let n=o;o==="true"?n=!0:o==="false"?n=!1:Number.isNaN(Number(o))||(n=Number(o)),s.set(e,n),y(`Set ${h.cyan(e)} to ${h.green(o)}`);return}if(t==="unset"&&e){s.delete(e),y(`Unset configuration key ${h.cyan(e)}`);return}console.log(),console.log(h.bold.cyan("\u2699\uFE0F AIX CLI Configuration")),console.log(h.dim("\u2500".repeat(40))),["defaultBackend","defaultProvider","model","lmStudioUrl","lmStudioPort","lmStudioContextLength","ollamaUrl","ollamaPort","defaultTimeout","autoStartServer"].forEach(n=>{let r=s.get(n);console.log(r!==void 0?` ${h.bold(n)}: ${h.green(r)}`:` ${h.bold(n)}: ${h.dim("not set")}`)}),console.log(),console.log(h.dim("Commands:")),console.log(h.dim(" aix-cli config set <key> <value>")),console.log(h.dim(" aix-cli config unset <key>")),console.log(h.dim(" aix-cli config reset")),console.log()}var b=new De;b.name("aix-cli").description("Run Claude Code or OpenCode with local AI models from LM Studio or Ollama").version(ne()).option("--ollama","Shortcut to use Ollama backend").option("--lmstudio","Shortcut to use LM Studio backend").showHelpAfterError();function B(t=0){console.log(),console.log(g.dim(t===0?"\u{1F44B} Goodbye!":"\u274C Cancelled.")),process.exit(t)}process.on("SIGINT",()=>B(0));process.on("SIGTERM",()=>B(0));process.on("uncaughtException",t=>{t.message?.includes("ExitPromptError")||t.message?.includes("User force closed")||t.message?.includes("prompt")?B(0):(console.error(g.red("Error:"),t.message),process.exit(1))});process.on("unhandledRejection",t=>{let e=String(t);(e.includes("ExitPromptError")||e.includes("User force closed")||e.includes("prompt"))&&B(0)});b.command("init",{isDefault:!1}).aliases(["i","load"]).description("Select a backend, load a model, and configure your provider").option("-m, --model <name>","Model name or ID to load").option("-p, --provider <provider>","Coding tool to use (claude or opencode)").option("-b, --backend <backend>","Model backend to use (lmstudio or ollama)").action(t=>{let e=b.opts();return e.ollama&&(t.backend="ollama"),e.lmstudio&&(t.backend="lmstudio"),Y(t)});b.command("run",{isDefault:!1}).aliases(["r"]).description("Run Claude Code or OpenCode with a model from LM Studio or Ollama").option("-m, --model <name>","Model name or ID to use").option("-p, --provider <provider>","Coding tool to use (claude or opencode)").option("-b, --backend <backend>","Model backend to use (lmstudio or ollama)").option("-v, --verbose","Show verbose output").argument("[args...]","Additional arguments for the provider").action(async(t,e)=>{let o=b.opts();o.ollama&&(e.backend="ollama"),o.lmstudio&&(e.backend="lmstudio"),await oe({...e,args:t})});b.command("status",{isDefault:!1}).aliases(["s","stats"]).description("Show LM Studio and Ollama status and available models").action(te);b.command("doctor",{isDefault:!1}).aliases(["d","check"]).description("Check system requirements and configuration").action(async()=>{let{lmStudioService:t}=await Promise.resolve().then(()=>(A(),ce)),{ollamaService:e}=await Promise.resolve().then(()=>(E(),ue)),{claudeService:o}=await Promise.resolve().then(()=>(Q(),ge)),{openCodeService:i}=await Promise.resolve().then(()=>(ee(),pe)),{configService:n}=await Promise.resolve().then(()=>(M(),ae));console.log(g.bold.cyan("\u{1F527} AIX CLI System Check")),console.log(g.dim("\u2500".repeat(40)));let[r,a,l,m]=await Promise.all([t.checkStatus(),e.checkStatus(),o.isClaudeCodeInstalled(),i.isOpenCodeInstalled()]),u=n.getDefaultProvider(),c=n.getDefaultBackend(),S=n.get("lmStudioPort"),P=n.get("ollamaPort");console.log(),console.log(g.bold("Backends")),console.log(` ${r?"\u2705":"\u26A0\uFE0F"} LM Studio: ${r?g.green("Running"):g.yellow("Not running")} ${g.dim(`(port ${S})`)}`),console.log(` ${a?"\u2705":"\u26A0\uFE0F"} Ollama: ${a?g.green("Running"):g.yellow("Not running")} ${g.dim(`(port ${P})`)}`),console.log(),console.log(g.bold("Coding Tools")),console.log(` ${l?"\u2705":"\u274C"} Claude Code: ${l?g.green("Installed"):g.red("Not installed")}`),console.log(` ${m?"\u2705":"\u274C"} OpenCode: ${m?g.green("Installed"):g.red("Not installed")}`),console.log(),console.log(g.bold("Defaults")),console.log(` \u{1F4CC} Backend: ${g.cyan(c??"not set")}`),console.log(` \u{1F4CC} Coding tool: ${g.cyan(u??"not set")}`);let $=[];l||$.push(` \u2192 ${g.cyan("npm install -g @anthropic-ai/claude-code")}`),m||$.push(` \u2192 ${g.cyan("npm install -g opencode-ai")}`),!r&&!a&&$.push(` \u2192 Start LM Studio or run ${g.cyan("ollama serve")}`),$.length>0&&(console.log(),console.log(g.bold("\u{1F4CB} Next Steps:")),$.forEach(V=>console.log(V))),console.log()});b.command("update",{isDefault:!1}).aliases(["upgrade","u"]).description("Update AIX CLI to the latest version").action(re);b.command("config [action] [key] [value]",{isDefault:!1}).aliases(["c","settings"]).description("View, set, or reset AIX CLI configuration constraints").action(ie);b.parse();
2
+ var ge=Object.defineProperty;var fe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var B=(o,e)=>()=>(o&&(e=o(o=0)),e);var N=(o,e)=>{for(var t in e)ge(o,t,{get:e[t],enumerable:!0})};var ne={};N(ne,{ConfigService:()=>D,configService:()=>l});import pe from"conf";var D,l,M=B(()=>{"use strict";D=class{store;constructor(){this.store=new pe({projectName:"aix",defaults:{lmStudioUrl:"http://localhost",lmStudioPort:1234,lmStudioContextLength:65536,ollamaUrl:"http://localhost",ollamaPort:11434,defaultTimeout:3e4,autoStartServer:!1},clearInvalidConfig:!0})}get(e){return this.store.get(e)}set(e,t){this.store.set(e,t)}delete(e){this.store.delete(e)}setModel(e){this.store.set("model",e)}getLastUsedModel(){return this.store.get("model")}setDefaultProvider(e){this.store.set("defaultProvider",e)}getDefaultProvider(){return this.store.get("defaultProvider")}setDefaultBackend(e){this.store.set("defaultBackend",e)}getDefaultBackend(){return this.store.get("defaultBackend")}getLMStudioUrl(){let e=this.store.get("lmStudioUrl"),t=this.store.get("lmStudioPort");return`${e}:${t}`}getOllamaUrl(){let e=this.store.get("ollamaUrl"),t=this.store.get("ollamaPort");return`${e}:${t}`}reset(){this.store.clear()}},l=new D});var re={};N(re,{LMStudioService:()=>z,lmStudioService:()=>S});import{execa as I}from"execa";import ie from"ora";import W from"chalk";var he,z,S,L=B(()=>{"use strict";M();he=[1234,1235,1236,1237],z=class{constructor(){}getBaseUrl(){return l.getLMStudioUrl()}getApiUrl(e){return`${this.getBaseUrl()}${e}`}async checkStatus(){try{return(await fetch(this.getApiUrl("/api/status"),{method:"GET",signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async getAvailableModels(){let e=["/api/v1/models","/api/models","/v1/models","/api/ls-model/list"];for(let t of e)try{let r=await fetch(this.getApiUrl(t),{method:"GET",signal:AbortSignal.timeout(1e4)});if(!r.ok)continue;let n=await r.json(),i=[];return Array.isArray(n)?i=n:n.models&&Array.isArray(n.models)?i=n.models:n.data&&Array.isArray(n.data)&&(i=n.data),i.map(a=>{let s=a;return{id:String(s.key||s.id||s.model||""),name:String(s.display_name||s.name||s.id||s.model||""),size:Number(s.size_bytes||s.size||s.file_size||0),quantization:String(s.quantization?typeof s.quantization=="object"?s.quantization.name:s.quantization:"")}}).filter(a=>a.id&&a.name)}catch{continue}return[]}async getStatus(){if(!await this.checkStatus())return{running:!1,port:l.get("lmStudioPort"),models:[]};try{let t=await fetch(this.getApiUrl("/api/status"),{method:"GET",signal:AbortSignal.timeout(1e4)});if(!t.ok)return{running:!1,port:l.get("lmStudioPort"),models:[]};let r=await t.json();return{running:!0,port:l.get("lmStudioPort"),models:r.models??[],activeModel:r.active_model}}catch{return{running:!1,port:l.get("lmStudioPort"),models:[]}}}async loadModel(e,t){let r=t??ie({text:`Loading model: ${W.cyan(e)}`,color:"cyan"}).start();try{let n=l.get("lmStudioContextLength"),i=["/api/v1/models/load","/api/model/load"],a=async(m,c)=>{let u={model:e};c&&(u.context_length=n);let g=await fetch(this.getApiUrl(m),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(3e5)});if(g.ok)return;let v="";try{v=await g.text()}catch{v=""}let k=v?` ${v}`:"";throw new Error(`Failed to load model: ${g.status} ${g.statusText}${k}`)},s;for(let m of i)try{return await a(m,!0),r.succeed(`Model ${W.green(e)} loaded successfully`),l.setModel(e),{loadSpinner:r}}catch(c){s=c;let u=c instanceof Error?c.message:String(c);if(/context|token|max.*(context|token)|too.*large/i.test(u))try{return r.warn(`Model load failed with context_length=${n}. Retrying with LM Studio defaults...`),await a(m,!1),r.succeed(`Model ${W.green(e)} loaded successfully`),l.setModel(e),{loadSpinner:r}}catch(v){s=v}}throw s instanceof Error?s:new Error(String(s))}catch(n){throw r.fail(`Failed to load model: ${n instanceof Error?n.message:"Unknown error"}`),n}}async startServer(e){let t=e??ie({text:"Starting LM Studio server...",color:"cyan"}).start();try{let r=process.platform==="darwin",n=process.platform==="linux",i=process.platform==="win32",a;if(r){let s=["/Applications/LM Studio.app",`${process.env.HOME}/Applications/LM Studio.app`];for(let m of s)try{let{existsSync:c}=await import("fs");if(c(m)){a=`open "${m}" --args --server`;break}}catch{}if(a?.startsWith("open")){await I("open",[s.find(m=>{try{let{existsSync:c}=fe("fs");return c(m)}catch{return!1}})||"/Applications/LM Studio.app","--args","--server"],{detached:!0,stdio:"ignore"}),t.succeed("LM Studio server started"),await this.waitForServer(6e4);return}}else n?a=await this.findLinuxBinary():i&&(a=await this.findWindowsExecutable());if(!a)throw t.fail("LM Studio not found. Please install it from https://lmstudio.ai"),new Error("LM Studio not installed");await I(a,["--server"],{detached:!0,stdio:"ignore",env:{...process.env,LM_STUDIO_SERVER_PORT:String(l.get("lmStudioPort"))}}),t.succeed("LM Studio server started"),await this.waitForServer(6e4)}catch(r){throw t.fail(`Failed to start LM Studio: ${r instanceof Error?r.message:"Unknown error"}`),r}}async findLinuxBinary(){let e=["/usr/bin/lm-studio","/usr/local/bin/lm-studio",`${process.env.HOME}/.local/bin/lm-studio`];for(let t of e)try{return await I("test",["-x",t]),t}catch{continue}}async findWindowsExecutable(){let e=process.env.LOCALAPPDATA,t=process.env.PROGRAMFILES,r=[e?`${e}\\Programs\\LM Studio\\lm-studio.exe`:"",t?`${t}\\LM Studio\\lm-studio.exe`:""].filter(Boolean);for(let n of r)try{return await I("cmd",["/c","if exist",`"${n}"`,"echo","yes"]),n}catch{continue}}async waitForServer(e=6e4){let t=Date.now();for(;Date.now()-t<e;){if(await this.checkStatus())return!0;await this.sleep(2e3)}return!1}sleep(e){return new Promise(t=>setTimeout(t,e))}async findAvailablePort(){for(let e of he)try{if((await fetch(`http://localhost:${e}/api/status`,{method:"GET",signal:AbortSignal.timeout(1e3)})).ok)return l.set("lmStudioPort",e),e}catch{continue}return l.get("lmStudioPort")}},S=new z});var ae={};N(ae,{OllamaService:()=>T,ollamaService:()=>b});var T,b,A=B(()=>{"use strict";M();T=class{getBaseUrl(){return l.getOllamaUrl()}getApiUrl(e){return`${this.getBaseUrl()}${e}`}async checkStatus(){try{return(await fetch(this.getApiUrl("/api/tags"),{method:"GET",signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async getAvailableModels(){try{let e=await fetch(this.getApiUrl("/api/tags"),{method:"GET",signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).models??[]).map(n=>{let i=n.details??{};return{id:String(n.name??n.model??""),name:String(n.name??n.model??""),size:Number(n.size??0),quantization:String(i.quantization_level??""),family:String(i.family??""),parameterSize:String(i.parameter_size??"")}}).filter(n=>n.id&&n.name):[]}catch{return[]}}async getRunningModels(){try{let e=await fetch(this.getApiUrl("/api/ps"),{method:"GET",signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models??[]).map(n=>String(n.name??n.model??"")).filter(Boolean):[]}catch{return[]}}async getStatus(){if(!await this.checkStatus())return{running:!1,port:l.get("ollamaPort"),models:[],runningModels:[]};let[t,r]=await Promise.all([this.getAvailableModels(),this.getRunningModels()]);return{running:!0,port:l.get("ollamaPort"),models:t,runningModels:r}}},b=new T});var le={};N(le,{ClaudeService:()=>K,claudeService:()=>O});import{execa as J}from"execa";import be from"chalk";var K,O,Q=B(()=>{"use strict";M();K=class{async isClaudeCodeInstalled(){try{return await J("claude",["--version"],{stdio:"ignore"}),!0}catch{return!1}}async run(e){let{model:t,args:r=[],verbose:n=!1}=e,i=this.extractProvider(t),a=this.extractModelName(t);if(!i||!a)throw new Error(`Invalid model format: ${t}. Expected format: provider/model-name`);let s=["--model",a,...r];n&&console.log(be.dim(`
3
+ Running: claude ${s.join(" ")}
4
+ `));let m=i==="ollama"?l.getOllamaUrl():l.getLMStudioUrl(),c=i==="ollama"?"ollama":"lmstudio",u=`${m}/v1/messages`;try{let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":c},body:JSON.stringify({model:a,max_tokens:1,messages:[{role:"user",content:"test"}]}),signal:AbortSignal.timeout(3e3)});if(!g.ok&&g.status>=500)throw new Error(`HTTP ${g.status} ${g.statusText}`)}catch(g){let v=g instanceof Error?g.message:String(g),k=i==="ollama"?"Claude Code requires an Anthropic-compatible API. Ollama does not support this. Use OpenCode for Ollama, or switch to LM Studio.":"Ensure LM Studio server is running and the Anthropic Compatibility server is enabled. Check the Developer tab in LM Studio.";throw new Error(`Claude Code could not reach an Anthropic-compatible endpoint at ${u} (${v}). ${k}`)}try{await J("claude",s,{stdio:"inherit",env:{...process.env,ANTHROPIC_MODEL:a,ANTHROPIC_BASE_URL:m,ANTHROPIC_AUTH_TOKEN:c,ANTHROPIC_API_KEY:""}})}catch(g){if(g instanceof Error&&"exitCode"in g){let v=g.exitCode;process.exit(v??1)}throw g}}extractProvider(e){return e.split("/")[0]}extractModelName(e){let t=e.split("/");if(!(t.length<2))return t.slice(1).join("/")}async getVersion(){try{return(await J("claude",["--version"])).stdout}catch{return}}},O=new K});import{Command as Ee}from"commander";import p from"chalk";L();A();M();import F from"ora";import h from"chalk";import q from"inquirer";import se from"inquirer";async function P(o,e){let t=o.map(i=>({name:`${i.name} (${i.id})`,value:i,short:i.name})),r=e?t.findIndex(i=>i.value.id===e):0;return(await se.prompt([{type:"list",name:"model",message:"Select a model to load:",choices:t,default:Math.max(0,r),pageSize:Math.min(o.length,15)}])).model}async function j(o,e=!0){return(await se.prompt([{type:"confirm",name:"confirm",message:o,default:e}])).confirm}import H from"chalk";function x(o){if(o===0)return"0 B";let e=1024,t=["B","KB","MB","GB","TB"],r=Math.floor(Math.log(o)/Math.log(e));return`${parseFloat((o/Math.pow(e,r)).toFixed(2))} ${t[r]}`}function w(o){console.log(H.green("\u2713")+" "+o)}function V(o){console.error(H.red("\u2717")+" "+o)}function _(o){console.log(H.blue("\u2139")+" "+o)}function f(o,e=1){V(o),process.exit(e)}async function ve(){let o=l.getDefaultBackend(),{backendSelection:e}=await q.prompt([{type:"list",name:"backendSelection",message:"Select model backend:",default:o??"lmstudio",choices:[{name:"\u{1F5A5}\uFE0F LM Studio",value:"lmstudio"},{name:"\u{1F999} Ollama",value:"ollama"}]}]),{saveDefault:t}=await q.prompt([{type:"confirm",name:"saveDefault",message:"Save as default backend?",default:!1}]);return t&&(l.setDefaultBackend(e),w(`Default backend set to ${h.cyan(e)}`)),e}async function Se(o){let e=l.getDefaultProvider(),t=[{name:"Claude Code",value:"claude"}],r=e??"claude",{providerSelection:n}=await q.prompt([{type:"list",name:"providerSelection",message:"Select coding tool:",default:r,choices:t}]),{saveDefault:i}=await q.prompt([{type:"confirm",name:"saveDefault",message:"Save as default coding tool?",default:!1}]);return i&&(l.setDefaultProvider(n),w(`Default coding tool set to ${h.cyan(n)}`)),n}async function ye(o,e){let t=F({text:"Checking LM Studio status...",color:"cyan"}).start(),r=await S.checkStatus();r||(t.info("LM Studio server not running"),t.stop(),await j("Would you like to start the LM Studio server?")||f("LM Studio server must be running. Start it manually or use the Server tab in LM Studio."),await S.startServer(),r=!0),t.succeed("Connected to LM Studio");let n=F({text:"Fetching available models...",color:"cyan"}).start(),i=await S.getAvailableModels();i.length===0&&(n.fail("No models found. Download some models in LM Studio first."),f("No models available")),n.succeed(`Found ${h.bold(i.length)} model${i.length===1?"":"s"}`),console.log(),console.log(h.bold("Available Models:")),console.log(h.dim("\u2500".repeat(process.stdout.columns||80))),i.forEach((u,g)=>{let v=x(u.size),k=u.loaded?h.green(" [LOADED]"):"";console.log(` ${h.dim(String(g+1).padStart(2))}. ${u.name} ${h.dim(`(${v})`)}${k}`)}),console.log();let a=l.getLastUsedModel(),s=o.model,m=s?i.find(u=>u.id===s||u.name.includes(s)):await P(i,a);m||f("No model selected"),await S.loadModel(m.id,t);let c=m.id;w(h.bold(`
5
+ Model ready: ${m.name}`)),console.log(),console.log("Start your interactive coding session:"),console.log(` ${h.cyan(`aix-cli run --provider ${e} --backend lmstudio --model ${c}`)}`),console.log()}async function we(o,e){let t=F({text:"Checking Ollama status...",color:"cyan"}).start();await b.checkStatus()||(t.fail("Ollama is not running"),f("Ollama must be running. Start it with: ollama serve")),t.succeed("Connected to Ollama");let n=F({text:"Fetching available models...",color:"cyan"}).start(),i=await b.getAvailableModels();i.length===0&&(n.fail("No models found. Pull a model first: ollama pull <model>"),f("No models available")),n.succeed(`Found ${h.bold(i.length)} model${i.length===1?"":"s"}`);let a=await b.getRunningModels();console.log(),console.log(h.bold("Available Models:")),console.log(h.dim("\u2500".repeat(process.stdout.columns||80))),i.forEach((u,g)=>{let v=x(u.size),ue=a.includes(u.id)?h.green(" [RUNNING]"):"",me=u.parameterSize?h.dim(` ${u.parameterSize}`):"";console.log(` ${h.dim(String(g+1).padStart(2))}. ${u.name}${me} ${h.dim(`(${v})`)}${ue}`)}),console.log();let s=l.getLastUsedModel(),m=o.model,c=m?i.find(u=>u.id===m||u.name.includes(m)):await P(i,s);c||f("No model selected"),l.setModel(c.id),w(h.bold(`
6
+ Model selected: ${c.name}`)),console.log(),console.log("Start your interactive coding session:"),console.log(` ${h.cyan(`aix-cli run --provider ${e} --backend ollama --model ${c.id}`)}`),console.log()}async function X(o={}){let e=o.backend??await ve(),t=o.provider??await Se(e);e==="ollama"?await we(o,t):await ye(o,t)}L();A();Q();M();import C from"ora";import G from"chalk";import $e from"inquirer";import{execa as Me}from"execa";async function ke(o){let e=l.getDefaultBackend();if(e)return e;let{backendSelection:t}=await $e.prompt([{type:"list",name:"backendSelection",message:"Select model backend:",choices:[{name:"\u{1F5A5}\uFE0F LM Studio",value:"lmstudio"},{name:"\u{1F999} Ollama",value:"ollama"}]}]);return t}async function Pe(){return await O.isClaudeCodeInstalled()||f("Claude Code is not installed."),"claude"}function R(o){return"Claude Code"}async function xe(o,e){let t=C({text:"Checking LM Studio status...",color:"cyan"}).start();await S.findAvailablePort();let r=await S.checkStatus();r||(t.info("LM Studio server not running"),t.stop(),await j("Would you like to start the LM Studio server?")||f("LM Studio server must be running. Start it manually or use the Server tab in LM Studio."),await S.startServer(),r=!0),t.succeed("Connected to LM Studio");let n=C({text:"Fetching available models...",color:"cyan"}).start(),i=await S.getAvailableModels();i.length===0&&(n.fail("No models found. Download some models in LM Studio first."),f("No models available")),n.stop();let a;if(o.model){let c=i.find(u=>u.id===o.model||u.name.toLowerCase().includes(o.model.toLowerCase()));c||f(`Model "${o.model}" not found. Available models: ${i.map(u=>u.name).join(", ")}`),a=c.id}else{let c=l.getLastUsedModel();a=(await P(i,c)).id}let s=C({text:`Loading model: ${G.cyan(a)}`,color:"cyan"}).start();await S.loadModel(a,s);let m=`lmstudio/${a}`;await de(e,m,o)}async function Ce(o,e){let t=C({text:"Checking Ollama status...",color:"cyan"}).start();await b.checkStatus()||(t.fail("Ollama is not running"),f("Ollama must be running. Start it with: ollama serve")),t.succeed("Connected to Ollama");let n=C({text:"Fetching available models...",color:"cyan"}).start(),i=await b.getAvailableModels();i.length===0&&(n.fail("No models found. Pull a model first: ollama pull <model>"),f("No models available")),n.stop();let a;if(o.model){let m=i.find(c=>c.id===o.model||c.name.toLowerCase().includes(o.model.toLowerCase()));m||f(`Model "${o.model}" not found. Available models: ${i.map(c=>c.name).join(", ")}`),a=m.id}else{let m=l.getLastUsedModel();a=(await P(i,m)).id}l.setModel(a);let s=`ollama/${a}`;await de(e,s,o)}async function de(o,e,t){let r=R(o);w(G.green(`
7
+ Starting ${r} with model: ${e}
8
+ `));try{await O.run({model:e,args:t.args??[],verbose:t.verbose})}catch(n){f(`Failed to run ${r}: ${n instanceof Error?n.message:"Unknown error"}`)}}async function Y(o={}){let e;if(o.provider)e=o.provider;else{let i=l.getDefaultProvider();i?e=i:e=await Pe()}let t=C({text:`Checking ${R(e)} installation...`,color:"cyan"}).start();await O.isClaudeCodeInstalled()||(t.fail(`${R(e)} is not installed.`),f(`Please install ${R(e)} first.`)),t.succeed(`${R(e)} is installed`);let n=o.backend??await ke(e);if(o.native&&n==="ollama"){let i=o.model??l.getLastUsedModel();i||f("No model specified. Use -m, --model to specify a model."),await Le(i,o.args??[],o.verbose??!1);return}n==="ollama"&&e==="claude"&&f("Claude Code requires an Anthropic-compatible API. LM Studio supports this natively, but Ollama does not. Use --native to use Ollama's built-in Claude Code integration, or switch to LM Studio."),n==="ollama"?await Ce(o,e):await xe(o,e)}async function Le(o,e,t){w(G.green(`
9
+ Starting Claude Code with Ollama native integration...
10
+ `)),t&&console.log(G.dim(`Running: ollama launch claude --model ${o}
11
+ `));try{await Me("ollama",["launch","claude","--model",o,...e],{stdio:"inherit"})}catch(r){f(`Failed to launch Claude Code via Ollama: ${r instanceof Error?r.message:"Unknown error"}`)}}L();A();import d from"chalk";async function Z(){let[o,e]=await Promise.all([S.getStatus(),b.getStatus()]);console.log(),console.log(d.bold("LM Studio")),console.log(d.dim("\u2500".repeat(50))),console.log(` ${o.running?d.green("\u25CF"):d.red("\u25CB")} Server: ${o.running?d.green("Running"):d.red("Stopped")}`),console.log(` ${d.dim("\u25B8")} Port: ${d.cyan(String(o.port))}`),console.log(` ${d.dim("\u25B8")} URL: ${d.cyan(`http://localhost:${o.port}`)}`),o.activeModel&&console.log(` ${d.dim("\u25B8")} Active Model: ${d.green(o.activeModel)}`),o.running&&o.models.length>0?(console.log(),console.log(d.bold(" Models")),o.models.forEach((t,r)=>{let n=x(t.size),i=t.id===o.activeModel?` ${d.green("[LOADED]")}`:"";console.log(` ${d.dim(String(r+1)+".")} ${t.name}${i}`),console.log(` ${d.dim("ID:")} ${t.id}`),console.log(` ${d.dim("Size:")} ${n}`),t.quantization&&console.log(` ${d.dim("Quantization:")} ${t.quantization}`)})):o.running&&console.log(` ${d.dim("No models available")}`),console.log(),console.log(d.bold("Ollama")),console.log(d.dim("\u2500".repeat(50))),console.log(` ${e.running?d.green("\u25CF"):d.red("\u25CB")} Server: ${e.running?d.green("Running"):d.red("Stopped")}`),console.log(` ${d.dim("\u25B8")} Port: ${d.cyan(String(e.port))}`),console.log(` ${d.dim("\u25B8")} URL: ${d.cyan(`http://localhost:${e.port}`)}`),e.running&&e.runningModels.length>0&&console.log(` ${d.dim("\u25B8")} Running: ${d.green(e.runningModels.join(", "))}`),e.running&&e.models.length>0?(console.log(),console.log(d.bold(" Models")),e.models.forEach((t,r)=>{let n=x(t.size),a=e.runningModels.includes(t.id)?` ${d.green("[RUNNING]")}`:"",s=t.parameterSize?` ${d.dim(t.parameterSize)}`:"";console.log(` ${d.dim(String(r+1)+".")} ${t.name}${s}${a}`),console.log(` ${d.dim("Size:")} ${n}`),t.family&&console.log(` ${d.dim("Family:")} ${t.family}`),t.quantization&&console.log(` ${d.dim("Quantization:")} ${t.quantization}`)})):e.running&&console.log(` ${d.dim("No models available")}`),console.log()}import Ae from"ora";import U from"chalk";import{execa as ce}from"execa";import{readFileSync as Oe}from"fs";import{fileURLToPath as Re}from"url";function ee(){try{let o=Re(new URL("../../package.json",import.meta.url)),e=JSON.parse(Oe(o,"utf8"));return String(e.version)}catch{return"unknown"}}async function oe(){let o=Ae({text:"Checking for updates...",color:"cyan"}).start();try{let e=ee();if(e==="unknown"){o.fail("Could not determine current version.");return}let{stdout:t}=await ce("npm",["view","@iamharshil/aix-cli","version"]),r=t.trim();if(e===r){o.succeed(`You're already on the latest version: ${U.green(`v${e}`)}`);return}o.text=`Updating: ${U.yellow(`v${e}`)} \u2192 ${U.green(`v${r}`)}...`,await ce("npm",["install","-g","@iamharshil/aix-cli@latest"]),o.succeed(`Successfully updated to ${U.green(`v${r}`)}! \u{1F680}`),_(`Restart your terminal or run ${U.cyan("aix-cli --help")} to see what's new.`)}catch(e){o.fail("Failed to update."),V(e instanceof Error?e.message:String(e))}}M();import y from"chalk";import Ue from"inquirer";async function te(o,e,t){if(o==="reset"){let{confirm:n}=await Ue.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to completely reset all configuration to defaults?",default:!1}]);n?(l.reset(),w("Configuration has been reset to defaults.")):_("Reset cancelled.");return}if(o==="set"&&e&&t){let n=t;t==="true"?n=!0:t==="false"?n=!1:Number.isNaN(Number(t))||(n=Number(t)),l.set(e,n),w(`Set ${y.cyan(e)} to ${y.green(t)}`);return}if(o==="unset"&&e){l.delete(e),w(`Unset configuration key ${y.cyan(e)}`);return}console.log(),console.log(y.bold.cyan("\u2699\uFE0F AIX CLI Configuration")),console.log(y.dim("\u2500".repeat(40))),["defaultBackend","defaultProvider","model","lmStudioUrl","lmStudioPort","lmStudioContextLength","ollamaUrl","ollamaPort","defaultTimeout","autoStartServer"].forEach(n=>{let i=l.get(n);console.log(i!==void 0?` ${y.bold(n)}: ${y.green(i)}`:` ${y.bold(n)}: ${y.dim("not set")}`)}),console.log(),console.log(y.dim("Commands:")),console.log(y.dim(" aix-cli config set <key> <value>")),console.log(y.dim(" aix-cli config unset <key>")),console.log(y.dim(" aix-cli config reset")),console.log()}var $=new Ee;$.name("aix-cli").description("Run Claude Code with local AI models from LM Studio or Ollama").version(ee()).option("--ollama","Shortcut to use Ollama backend").option("--lmstudio","Shortcut to use LM Studio backend").showHelpAfterError();function E(o=0){console.log(),console.log(p.dim(o===0?"\u{1F44B} Goodbye!":"\u274C Cancelled.")),process.exit(o)}process.on("SIGINT",()=>E(0));process.on("SIGTERM",()=>E(0));process.on("uncaughtException",o=>{o.message?.includes("ExitPromptError")||o.message?.includes("User force closed")||o.message?.includes("prompt")?E(0):(console.error(p.red("Error:"),o.message),process.exit(1))});process.on("unhandledRejection",o=>{let e=String(o);(e.includes("ExitPromptError")||e.includes("User force closed")||e.includes("prompt"))&&E(0)});$.command("init",{isDefault:!1}).aliases(["i","load"]).description("Select a backend, load a model, and configure your provider").option("-m, --model <name>","Model name or ID to load").option("-p, --provider <provider>","Coding tool to use (claude)").option("-b, --backend <backend>","Model backend to use (lmstudio or ollama)").action(o=>{let e=$.opts();return e.ollama&&(o.backend="ollama"),e.lmstudio&&(o.backend="lmstudio"),X(o)});$.command("run",{isDefault:!1}).aliases(["r"]).description("Run Claude Code with a model from LM Studio or Ollama").option("-m, --model <name>","Model name or ID to use").option("-p, --provider <provider>","Coding tool to use (claude)").option("-b, --backend <backend>","Model backend to use (lmstudio or ollama)").option("-n, --native","Use Ollama's native Claude Code integration (ollama launch)").option("-v, --verbose","Show verbose output").argument("[args...]","Additional arguments for the provider").action(async(o,e)=>{let t=$.opts();t.ollama&&(e.backend="ollama"),t.lmstudio&&(e.backend="lmstudio"),await Y({...e,args:o})});$.command("status",{isDefault:!1}).aliases(["s","stats"]).description("Show LM Studio and Ollama status and available models").action(Z);$.command("doctor",{isDefault:!1}).aliases(["d","check"]).description("Check system requirements and configuration").action(async()=>{let{lmStudioService:o}=await Promise.resolve().then(()=>(L(),re)),{ollamaService:e}=await Promise.resolve().then(()=>(A(),ae)),{claudeService:t}=await Promise.resolve().then(()=>(Q(),le)),{configService:r}=await Promise.resolve().then(()=>(M(),ne));console.log(p.bold.cyan("\u{1F527} AIX CLI System Check")),console.log(p.dim("\u2500".repeat(40)));let[n,i,a]=await Promise.all([o.checkStatus(),e.checkStatus(),t.isClaudeCodeInstalled()]),s=r.getDefaultProvider(),m=r.getDefaultBackend(),c=r.get("lmStudioPort"),u=r.get("ollamaPort");console.log(),console.log(p.bold("Backends")),console.log(` ${n?"\u2705":"\u26A0\uFE0F"} LM Studio: ${n?p.green("Running"):p.yellow("Not running")} ${p.dim(`(port ${c})`)}`),console.log(` ${i?"\u2705":"\u26A0\uFE0F"} Ollama: ${i?p.green("Running"):p.yellow("Not running")} ${p.dim(`(port ${u})`)}`),console.log(),console.log(p.bold("Coding Tools")),console.log(` ${a?"\u2705":"\u274C"} Claude Code: ${a?p.green("Installed"):p.red("Not installed")}`),console.log(),console.log(p.bold("Defaults")),console.log(` \u{1F4CC} Backend: ${p.cyan(m??"not set")}`),console.log(` \u{1F4CC} Coding tool: ${p.cyan(s??"not set")}`);let g=[];if(a||g.push(` \u2192 ${p.cyan("npm install -g @anthropic-ai/claude-code")}`),!n&&!i&&g.push(` \u2192 Start LM Studio or run ${p.cyan("ollama serve")}`),g.length>0){console.log(),console.log(p.bold("\u{1F4CB} Next Steps:"));for(let v of g)console.log(v)}console.log()});$.command("update",{isDefault:!1}).aliases(["upgrade","u"]).description("Update AIX CLI to the latest version").action(oe);$.command("config [action] [key] [value]",{isDefault:!1}).aliases(["c","settings"]).description("View, set, or reset AIX CLI configuration constraints").action(te);$.parse();
11
12
  //# sourceMappingURL=index.js.map