@fmdzc/cli-ai 3.1.0 → 3.1.1

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/README.md CHANGED
@@ -6,9 +6,9 @@
6
6
 
7
7
  **Natural language to shell commands. Multi-provider AI support.**
8
8
 
9
- Describe what you want in plain English. Get the right command. Review, execute, or copy.
9
+ Describe what you want in plain English. Get the right command. Review, execute or copy.
10
10
 
11
- Supports **Anthropic**, **OpenAI**, and **OpenRouter** providers.
11
+ Supports **Anthropic**, **OpenAI** and **OpenRouter** providers.
12
12
 
13
13
  ![CLI AI Demo](assets/cli-ai.png)
14
14
 
@@ -18,7 +18,7 @@ Supports **Anthropic**, **OpenAI**, and **OpenRouter** providers.
18
18
  - **Natural language** - Just describe what you want to do
19
19
  - **Cross-platform** - Windows (PowerShell, CMD, Git Bash), macOS, Linux
20
20
  - **Shell-aware** - Commands tailored to your detected shell
21
- - **Interactive** - Execute, copy, edit, or request alternatives
21
+ - **Interactive** - Execute, copy, edit or request alternatives
22
22
  - **Context-aware** - Remembers your conversation history for smarter suggestions
23
23
  - **Secure** - API keys stored in system keyring, never in plain text
24
24
  - **Risk assessment** - Color-coded safety levels for every command
@@ -151,7 +151,7 @@ If the system keyring is unavailable, keys are stored in an encrypted file at `~
151
151
  ### Key Management
152
152
 
153
153
  - **View**: See masked keys and storage method per provider in `/config`
154
- - **Add**: Configure API keys for Anthropic, OpenAI, or OpenRouter
154
+ - **Add**: Configure API keys for Anthropic, OpenAI or OpenRouter
155
155
  - **Change**: Update any API key anytime through settings
156
156
  - **Status**: Green ✓ indicates configured, red ✗ indicates not set
157
157
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var zr=(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 ut={id:"__custom__",name:"Custom model...",description:"Enter any model ID"},Ee={anthropic:[{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",description:"Fast and capable"},{id:"claude-opus-4-5",name:"Claude Opus 4.5",description:"Most capable"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",description:"Fastest"}],openrouter:[{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",description:"Anthropic"},{id:"xiaomi/mimo-v2-flash:free",name:"MiMo-V2-Flash",description:"Xiaomi (Free)"},{id:"x-ai/grok-code-fast-1",name:"Grok Code Fast 1",description:"xAI"},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",description:"Google"}],openai:[{id:"gpt-5.2",name:"GPT-5.2",description:"Most capable"},{id:"gpt-5-mini",name:"GPT-5 Mini",description:"Fast and efficient"},{id:"gpt-5-nano",name:"GPT-5 Nano",description:"Fastest"}]},Zr=Ee.anthropic;function Ot(t,e){let o=t.toLowerCase(),r=e.toLowerCase();if(r.startsWith(o))return 100+(100-r.length);if(r.includes(o))return 50+(50-r.indexOf(o));let i=0,s=0;for(let a=0;a<r.length&&s<o.length;a++)r[a]===o[s]&&(i+=10,s++);return s===o.length?i:0}function en(t,e){let o=Ot(t,e.name),r=Ot(t,e.description),i=(e.aliases??[]).map(s=>Ot(t,s));return Math.max(o,r,...i)}function co(){let t=[],e=new Map;function o(){e.clear();for(let r of t){e.set(r.name.toLowerCase(),r);for(let i of r.aliases??[])e.set(i.toLowerCase(),r)}}return{get commands(){return t},get(r){return e.get(r.toLowerCase())},filter(r){return r?t.map(s=>({cmd:s,score:en(r,s)})).filter(({score:s})=>s>0).sort((s,a)=>a.score-s.score).map(({cmd:s})=>s):[...t]},register(r){e.get(r.name.toLowerCase())||(t.push(r),o())}}}var ae=co();var Nt={name:"clear",description:"Clear conversation history",category:"session",aliases:["cls"],execute:()=>({type:"navigate",to:"clear"}),isAvailable:t=>t==="input"};var Bt={name:"config",description:"Open settings and configuration panel",category:"settings",aliases:["settings","preferences","prefs"],shortcut:"Ctrl+,",execute:()=>({type:"panel",panel:"config"}),isAvailable:t=>t==="input"};var Dt={name:"exit",description:"Exit the application",category:"session",aliases:["quit","q"],execute:()=>({type:"exit"}),isAvailable:()=>!0};var kt={name:"help",description:"Show help and keyboard shortcuts",category:"help",aliases:["h","?"],execute:()=>({type:"panel",panel:"help"}),isAvailable:()=>!0};ae.register(Bt);ae.register(kt);ae.register(Nt);ae.register(Dt);var me="3.1.0",Ne="CLI AI",uo="cli-ai";var po=".cli_ai_assistant",K=["anthropic","openrouter","openai"],mo="anthropic",F={anthropic:{name:"Anthropic",envVar:"ANTHROPIC_API_KEY",keyringAccount:"anthropic",keyPrefix:"sk-ant-",defaultModel:"claude-sonnet-4-5"},openrouter:{name:"OpenRouter",envVar:"OPENROUTER_API_KEY",keyringAccount:"openrouter",keyPrefix:"sk-or-",defaultModel:"anthropic/claude-sonnet-4.5"},openai:{name:"OpenAI",envVar:"OPENAI_API_KEY",keyringAccount:"openai",keyPrefix:"sk-",defaultModel:"gpt-5.2"}},tn=F[mo].defaultModel,Be={provider:mo,model:tn,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3,contextEnabled:!0},fo=500,go=10,xo=["rm -rf","sudo rm","chmod 777","mkfs","dd if=","> /dev/","format","del /f","rmdir /s","DROP TABLE","DELETE FROM","--no-preserve-root",":(){:|:&};:","| sh","| bash","curl | bash","wget | bash","eval","sudo su","passwd","chown -R","> /etc/","fdisk","wipefs","shred"],yo=["rm ","mv ","cp ","sudo ","npm install","pnpm install","yarn add","pip install","brew install","apt install","apt-get install","pacman -S","chmod ","chown ","git push","git reset","git rebase","docker ","kubectl ","systemctl ","service ","kill ","pkill "],ho=["sudo","rm","git","npm","pnpm","yarn","docker","kubectl","pip","python","node","npx","cd","ls","cat","grep","find","mkdir","touch","mv","cp","echo","curl","wget","ssh","scp"],le=500,z={maxAttempts:3,baseDelayMs:1e3,maxDelayMs:5e3};import mt from"conf";import{createHash as on}from"crypto";import{existsSync as vo,unlinkSync as Co}from"fs";import{hostname as rn,userInfo as nn}from"os";import{homedir as sn}from"os";import{join as So}from"path";var an="cli-ai-v3-encryption-key";function ln(){let t=`${rn()}-${nn().username}-cli-ai-v3-salt`;return on("sha256").update(t).digest("hex").slice(0,32)}var We=So(sn(),po),dt=So(We,"config.json");function cn(){if(!vo(dt))return null;try{let t=new mt({projectName:"cli-ai",cwd:We,encryptionKey:an}),e=t.get("apiKey"),o=t.get("apiKeys"),r=t.get("config");if(e||o||r)return{apiKey:e,apiKeys:o,config:r}}catch{}return null}function un(){let t=ln(),e=cn();if(e){try{Co(dt)}catch{}let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});if(e.apiKey&&!e.apiKeys?o.set("apiKeys",{anthropic:e.apiKey}):e.apiKeys&&o.set("apiKeys",e.apiKeys),e.config){let r={...e.config};r.provider||(r.provider="anthropic"),o.set("config",r)}return o}try{let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});return pn(o),o}catch{try{vo(dt)&&Co(dt)}catch{}return new mt({projectName:"cli-ai",cwd:We,encryptionKey:t})}}function pn(t){let e=t.get("apiKey");e&&!t.get("apiKeys")&&(t.set("apiKeys",{anthropic:e}),t.delete("apiKey"));let o=t.get("config");o&&!o.provider&&t.set("config",{...o,provider:"anthropic"})}var ye=un(),pt=null,To=!1,Mt=new Map,Qe=null;function mn(){if(To)return pt;To=!0;try{return pt=zr("@napi-rs/keyring"),pt}catch{return pt=null,null}}function _t(t){if(Qe===!1)return null;let e=Mt.get(t);if(e!==void 0)return e;let o=mn();if(!o)return Qe=!1,null;try{let r=F[t].keyringAccount,i=new o.Entry(uo,r);return i.getPassword(),Qe=!0,Mt.set(t,i),i}catch{return Mt.set(t,null),Qe===null&&(Qe=!1),null}}function Le(t){let e=F[t].envVar,o=process.env[e];if(o)return o;let r=_t(t);if(r)try{let s=r.getPassword();if(s)return s}catch{}return ye.get("apiKeys")?.[t]??null}function ft(t,e){try{let o=_t(t);if(o)try{o.setPassword(e);let i=ye.get("apiKeys")??{};return delete i[t],Object.keys(i).length>0?ye.set("apiKeys",i):ye.delete("apiKeys"),{success:!0,data:void 0}}catch{}let r=ye.get("apiKeys")??{};return r[t]=e,ye.set("apiKeys",r),{success:!0,data:void 0}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}function Ke(t){let e=Le(t);return e!==null&&e.length>0}function de(){let t=ye.get("config")??{};return{...Be,...t}}function he(t){let e=ye.get("config")??{};ye.set("config",{...e,...t})}function gt(t,e){let o=F[t];return t==="openai"?e.startsWith("sk-")&&e.length>20:e.startsWith(o.keyPrefix)&&e.length>20}function Eo(t){let e=F[t].envVar;if(process.env[e])return{method:"env",secure:!1,description:"Environment variable"};let o=_t(t);if(o)try{if(o.getPassword())return{method:"keyring",secure:!0,description:"System keyring"}}catch{}return ye.get("apiKeys")?.[t]?{method:"encrypted-file",secure:!1,description:"Encrypted file"}:{method:"none",secure:!1,description:"Not configured"}}import{Box as $,Text as Q,useInput as Po}from"ink";import{useState as Je}from"react";import{TextInput as dn}from"@inkjs/ui";import{jsx as O,jsxs as ce}from"react/jsx-runtime";var fn={anthropic:"https://console.anthropic.com/settings/keys",openai:"https://platform.openai.com/api-keys",openrouter:"https://openrouter.ai/keys"};function Io({onComplete:t,onError:e,error:o,provider:r}){let[i,s]=Je(r?"input":"welcome"),[a,c]=Je(r??"anthropic"),[h,g]=Je(0),[P,y]=Je(""),[m,f]=Je(null);Po((I,d)=>{i==="welcome"&&(d.return||I===" ")&&s("provider")},{isActive:i==="welcome"}),Po((I,d)=>{if(i==="provider"){if(d.upArrow){g(x=>(x-1+K.length)%K.length);return}if(d.downArrow){g(x=>(x+1)%K.length);return}if(d.return){let x=K[h];x&&(c(x),s("input"));return}let A=parseInt(I,10);if(A>=1&&A<=K.length){let x=K[A-1];x&&(c(x),s("input"))}}},{isActive:i==="provider"});let n=I=>{let d=I.trim();if(!d){f("API key cannot be empty");return}if(!gt(a,d)){let A=F[a];f(`Invalid key format. ${A.name} API keys start with "${A.keyPrefix}"`);return}f(null),s("saving"),t(d,a)};if(i==="welcome")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,color:"cyan",children:[Ne," v",me]})}),O($,{marginBottom:1,children:O(Q,{children:"Welcome! This tool translates natural language into shell commands."})}),O($,{marginBottom:1,children:O(Q,{dimColor:!0,children:"To get started, you'll need an API key from one of the supported providers."})}),O($,{children:O(Q,{color:"green",children:"Press Enter to continue..."})})]});if(i==="provider")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:O(Q,{bold:!0,children:"Select your AI provider:"})}),K.map((I,d)=>{let A=F[I],x=d===h;return ce($,{children:[O(Q,{color:x?"cyan":"gray",bold:x,children:x?"> ":" "}),ce(Q,{color:x?"cyan":"white",children:[d+1,". ",A.name]})]},I)}),O($,{marginTop:1,children:O(Q,{dimColor:!0,children:"[Up/Down] Navigate [Enter] Select [1-3] Quick select"})})]});let T=o??m,v=F[a];return i==="input"?ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,children:["Enter your ",v.name," API key:"]})}),O($,{marginBottom:1,children:ce(Q,{dimColor:!0,children:["Get one at: ",O(Q,{color:"blue",children:fn[a]})]})}),T&&O($,{marginBottom:1,children:ce(Q,{color:"red",children:["\u26A0 ",T]})}),ce($,{children:[O(Q,{dimColor:!0,children:"> "}),O(dn,{placeholder:`${v.keyPrefix}...`,onChange:y,onSubmit:n})]}),O($,{marginTop:1,children:O(Q,{color:"yellow",children:"\u{1F512} Your key is stored securely on this machine using your system's credential manager."})})]}):i==="saving"?O($,{flexDirection:"column",paddingY:1,children:O($,{children:O(Q,{color:"yellow",children:"\u23F3 Saving API key..."})})}):ce($,{flexDirection:"column",paddingY:1,children:[O($,{children:O(Q,{color:"green",children:"\u2713 API key saved successfully!"})}),O($,{marginTop:1,children:ce(Q,{children:["Starting ",Ne,"..."]})})]})}import{Box as xt,Text as Lt}from"ink";import{jsx as ze,jsxs as bo}from"react/jsx-runtime";function Ao({lines:t,command:e}){return bo(xt,{flexDirection:"column",marginY:1,children:[ze(xt,{marginBottom:1,children:bo(Lt,{dimColor:!0,children:["$ ",e]})}),ze(xt,{flexDirection:"column",children:t.map((o,r)=>{let i=o.startsWith("[ERR]");return ze(Lt,{color:i?"red":void 0,children:i?o.slice(6):o},r)})}),ze(xt,{marginTop:1,children:ze(Lt,{color:"yellow",children:"\u23F3 Running..."})})]})}import{Box as He,Text as Fe}from"ink";import{Box as gn,Text as Pe}from"ink";import{Fragment as xn,jsx as Ue,jsxs as yt}from"react/jsx-runtime";function Kt({command:t,index:e,isSelected:o}){return yt(gn,{children:[Ue(Pe,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),yt(Pe,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),Ue(Pe,{children:" "}),yt(Pe,{color:o?"white":"gray",bold:o,children:["/",t.name]}),Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!o,children:t.description}),t.shortcut?yt(xn,{children:[Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!0,color:"yellow",children:t.shortcut})]}):null]})}import{jsx as fe,jsxs as Ro}from"react/jsx-runtime";function Ut({query:t,filteredCommands:e,selectedIndex:o,visible:r}){return r?Ro(He,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginTop:1,children:[Ro(He,{children:[fe(Fe,{color:"blue",bold:!0,children:"/"}),fe(Fe,{color:"white",children:t}),fe(Fe,{color:"cyan",children:"_"})]}),fe(He,{marginY:0,children:fe(Fe,{dimColor:!0,children:"\u2500".repeat(50)})}),e.length>0?fe(He,{flexDirection:"column",children:e.slice(0,9).map((i,s)=>fe(Kt,{command:i,index:s,isSelected:s===o},i.name))}):fe(He,{children:fe(Fe,{dimColor:!0,children:"No matching commands"})}),fe(He,{marginTop:1,children:fe(Fe,{dimColor:!0,children:"[Enter] Select [1-9] Quick select [Esc] Close"})})]}):null}import{Box as Ie,Text as De}from"ink";import gi from"chalk";function yn(t){let e=[],o=t.split(/(\s+)/);for(let r of o)if(r){if(/^\s+$/.test(r)){e.push({type:"default",value:r});continue}if(/^[|><&;]+$/.test(r)||r==="&&"||r==="||"){e.push({type:"pipe",value:r});continue}if(/^-{1,2}[\w-]+=?/.test(r)){e.push({type:"flag",value:r});continue}if(/^\$[\w{}]+/.test(r)){e.push({type:"variable",value:r});continue}if(/^["'].*["']$/.test(r)){e.push({type:"string",value:r});continue}if(r.includes("/")||r.includes("\\")){e.push({type:"path",value:r});continue}if(ho.includes(r.toLowerCase())){e.push({type:"keyword",value:r});continue}e.push({type:"default",value:r})}return e}function wo(t){return yn(t).map(o=>{switch(o.type){case"keyword":return{text:o.value,color:"cyan",bold:!0};case"flag":return{text:o.value,color:"yellow"};case"string":return{text:o.value,color:"green"};case"pipe":return{text:o.value,color:"magenta"};case"path":return{text:o.value,color:"blue"};case"variable":return{text:o.value,color:"cyan"};default:return{text:o.value}}})}import{jsx as ne,jsxs as Ze}from"react/jsx-runtime";function Oo({command:t}){let e=wo(t);return ne(De,{children:e.map((o,r)=>ne(De,{color:o.color,bold:o.bold,children:o.text},r))})}function No({proposal:t,showExplanation:e=!1}){return Ze(Ie,{flexDirection:"column",children:[ne(Ie,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,children:ne(Oo,{command:t.command})}),e&&t.explanation&&ne(Ie,{marginTop:1,paddingX:1,children:ne(De,{dimColor:!0,children:t.explanation})})]})}function hn({command:t,index:e,selected:o=!1}){return Ze(Ie,{children:[Ze(De,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),ne(De,{children:" "}),ne(Oo,{command:t})]})}function Bo({proposals:t,selectedIndex:e=-1}){return Ze(Ie,{flexDirection:"column",marginY:1,children:[ne(Ie,{marginBottom:1,children:ne(De,{bold:!0,children:"Alternative commands:"})}),t.map((o,r)=>ne(Ie,{marginBottom:1,children:ne(hn,{command:o.command,index:r,selected:r===e})},r)),ne(Ie,{marginTop:1,children:Ze(De,{dimColor:!0,children:["Press 1-",t.length," to select, or [5] Cancel"]})})]})}import{Box as Ei,Text as Pi}from"ink";import{Fragment as Ai,jsx as bi,jsxs as Ri}from"react/jsx-runtime";import{Text as Cn}from"ink";import et from"chalk";import{useMemo as Do}from"react";import{jsx as vn}from"react/jsx-runtime";var Ht=et.inverse(" ");function ht({value:t,cursorOffset:e,placeholder:o="",isDisabled:r=!1}){let i=Do(()=>r?o?et.dim(o):"":o&&o.length>0?et.inverse(o[0])+et.dim(o.slice(1)):Ht,[r,o]),s=Do(()=>{if(r)return t;let a=0,c=t.length>0?"":Ht;for(let h of t)c+=a===e?et.inverse(h):h,a++;return t.length>0&&e===t.length&&(c+=Ht),c},[r,t,e]);return vn(Cn,{children:t.length>0?s:i})}var Tn={value:"",cursorOffset:0};function Ft(t=""){return{value:t,cursorOffset:t.length}}function $t(t,e){switch(e.type){case"insert":return{value:t.value.slice(0,t.cursorOffset)+e.text+t.value.slice(t.cursorOffset),cursorOffset:t.cursorOffset+e.text.length};case"delete":{if(t.cursorOffset===0)return t;let o=t.cursorOffset-1;return{value:t.value.slice(0,o)+t.value.slice(o+1),cursorOffset:o}}case"move-left":return{...t,cursorOffset:Math.max(0,t.cursorOffset-1)};case"move-right":return{...t,cursorOffset:Math.min(t.value.length,t.cursorOffset+1)};case"clear":return Tn;case"set":return{value:e.value,cursorOffset:e.value.length};default:return t}}import{Box as Ct,Text as Gt}from"ink";import{jsx as tt,jsxs as ko}from"react/jsx-runtime";function $e({title:t,isActive:e,children:o}){return ko(Ct,{flexDirection:"column",marginBottom:1,children:[ko(Ct,{children:[tt(Gt,{color:e?"cyan":"white",bold:!0,children:t}),e?tt(Gt,{color:"cyan",children:" *"}):null]}),tt(Ct,{children:tt(Gt,{dimColor:!0,children:"\u2500".repeat(50)})}),tt(Ct,{flexDirection:"column",paddingLeft:0,children:o})]})}import{Box as Sn,Text as Tt}from"ink";import{jsx as vt,jsxs as En}from"react/jsx-runtime";function Ge({label:t,value:e,isSelected:o}){return En(Sn,{children:[vt(Tt,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),vt(Tt,{color:e?"green":"gray",children:e?"[x]":"[ ]"}),vt(Tt,{children:" "}),vt(Tt,{color:o?"white":"gray",children:t})]})}import{Box as Y,Text as R}from"ink";import{Fragment as _o,jsx as E,jsxs as M}from"react/jsx-runtime";var Mo=["provider","api-keys","toggles","about"];function Yt({visible:t,activeSection:e,sectionItemIndex:o,config:r,hasApiKey:i,storageInfo:s,maskedKey:a,toggles:c,isEditingCustomModel:h=!1,customModelState:g}){if(!t)return null;let P=Mo.indexOf(e),y=Ee[r.provider],m=!y.some(n=>n.id===r.model),f=K.length+y.length;return M(Y,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[M(Y,{justifyContent:"space-between",marginBottom:1,children:[E(Y,{children:E(R,{color:"cyan",bold:!0,children:"Settings"})}),E(Y,{children:E(R,{dimColor:!0,children:"[Esc] Close [Tab] Section [Enter] Select"})})]}),E($e,{title:"Provider & Model",isActive:e==="provider",children:M(Y,{flexDirection:"column",children:[E(Y,{marginBottom:1,children:E(R,{dimColor:!0,children:"Provider"})}),K.map((n,T)=>{let v=F[n],I=r.provider===n,d=Ke(n),A=e==="provider"&&o===T;return M(Y,{children:[E(R,{color:A?"cyan":"gray",bold:A,children:A?"> ":" "}),M(R,{color:A?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",v.name]}),E(R,{children:" "}),E(R,{color:d?"green":"red",dimColor:!A,children:d?"\u2713 Key":"\u2717 No key"})]},n)}),E(Y,{marginTop:1,marginBottom:1,children:E(R,{dimColor:!0,children:"Model"})}),y.map((n,T)=>{let v=T+K.length,I=r.model===n.id,d=e==="provider"&&o===v;return M(Y,{children:[E(R,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(R,{color:d?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",n.name]}),M(R,{dimColor:!d,children:[" ",n.description]})]},n.id)}),M(Y,{children:[E(R,{color:e==="provider"&&o===f?"cyan":"gray",bold:e==="provider"&&o===f,children:e==="provider"&&o===f?"> ":" "}),h&&g?M(_o,{children:[E(R,{color:"cyan",children:"\u25CB "}),E(ht,{value:g.value,cursorOffset:g.cursorOffset,placeholder:"model-id"}),E(R,{dimColor:!0,children:" (Enter to save, Esc to cancel)"})]}):M(_o,{children:[M(R,{color:e==="provider"&&o===f?"cyan":m?"green":"white",children:[m?"\u25CF":"\u25CB"," ",ut.name]}),M(R,{dimColor:!(e==="provider"&&o===f),children:[" ",m?`(${r.model})`:ut.description]})]})]},ut.id)]})}),E($e,{title:"API Keys",isActive:e==="api-keys",children:E(Y,{flexDirection:"column",children:K.map((n,T)=>{let v=F[n],I=Ke(n),d=e==="api-keys"&&o===T;return M(Y,{children:[E(R,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(R,{color:d?"cyan":"white",children:[v.name,": "]}),E(R,{color:I?"green":"red",children:I?"\u2713 Configured":"\u2717 Not set"}),M(R,{dimColor:!d,children:[" [Enter to ",I?"change":"add","]"]})]},n)})})}),M($e,{title:"Options",isActive:e==="toggles",children:[E(Ge,{label:"Context (pass history to AI)",value:c.contextEnabled,isSelected:e==="toggles"&&o===0}),E(Ge,{label:"Show explanations",value:c.showExplanations,isSelected:e==="toggles"&&o===1}),E(Ge,{label:"Syntax highlighting",value:c.syntaxHighlighting,isSelected:e==="toggles"&&o===2}),E(Ge,{label:"Simple mode",value:c.simpleMode,isSelected:e==="toggles"&&o===3})]}),E($e,{title:"About",isActive:e==="about",children:M(Y,{flexDirection:"column",children:[M(Y,{children:[E(R,{dimColor:!0,children:"Version: "}),M(R,{children:["CLI AI v",me]})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Provider: "}),E(R,{color:"magenta",children:F[r.provider].name})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Model: "}),E(R,{color:"magenta",children:r.model})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Storage: "}),E(R,{color:s.secure?"green":"yellow",children:s.description})]})]})}),E(Y,{marginTop:1,justifyContent:"center",children:Mo.map((n,T)=>E(Y,{marginX:1,children:M(R,{color:T===P?"cyan":"gray",children:[T===P?"[":" ",T+1,T===P?"]":" "]})},n))})]})}import{Box as Ji,Text as zi}from"ink";import{Fragment as ta,jsx as ea,jsxs as oa}from"react/jsx-runtime";import{Box as G,Text as ee}from"ink";import{jsx as N,jsxs as se}from"react/jsx-runtime";var Pn=[{key:"/",description:"Open command palette"},{key:"Enter",description:"Submit query"},{key:"Ctrl+D",description:"Exit (when input is empty)"},{key:"O",description:"Toggle output expansion (when input is empty)"}],In=[{key:"1 / Enter",description:"Execute command"},{key:"2",description:"Copy to clipboard"},{key:"3",description:"Edit command"},{key:"4",description:"Show alternatives"},{key:"5 / Esc",description:"Cancel"},{key:"?",description:"Explain command"},{key:"O",description:"Toggle output"}],bn=[{key:"Up/Down",description:"Navigate commands"},{key:"Enter",description:"Select command"},{key:"Esc",description:"Close palette"},{key:"1-9",description:"Quick select"}],An=[{key:"Tab",description:"Next section"},{key:"Shift+Tab",description:"Previous section"},{key:"Up/Down",description:"Navigate items"},{key:"Enter/Space",description:"Toggle/Select"},{key:"Esc",description:"Close panel"}];function St({title:t,shortcuts:e}){return se(G,{flexDirection:"column",marginBottom:1,children:[N(ee,{color:"yellow",bold:!0,children:t}),e.map(o=>se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:o.key})}),N(ee,{dimColor:!0,children:o.description})]},o.key))]})}function Vt({visible:t}){return t?se(G,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[se(G,{justifyContent:"space-between",marginBottom:1,children:[N(G,{children:se(ee,{color:"cyan",bold:!0,children:["Help - ",Ne," v",me]})}),N(G,{children:N(ee,{dimColor:!0,children:"[Esc] Close"})})]}),N(G,{marginBottom:1,children:N(ee,{children:"Natural language to shell command translator. Describe what you want in plain English and get executable commands."})}),se(G,{children:[se(G,{flexDirection:"column",marginRight:4,children:[N(St,{title:"Input Mode",shortcuts:Pn}),N(St,{title:"Command Palette",shortcuts:bn})]}),se(G,{flexDirection:"column",children:[N(St,{title:"Proposal Mode",shortcuts:In}),N(St,{title:"Config Panel",shortcuts:An})]})]}),se(G,{flexDirection:"column",marginTop:1,children:[N(ee,{color:"yellow",bold:!0,children:"Available Commands"}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/config"})}),N(ee,{dimColor:!0,children:"Open settings panel"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/help"})}),N(ee,{dimColor:!0,children:"Show this help"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/clear"})}),N(ee,{dimColor:!0,children:"Clear command history"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/exit"})}),N(ee,{dimColor:!0,children:"Exit application"})]})]})]}):null}import{Box as Et,Text as ot}from"ink";import{jsx as Ye,jsxs as Pt}from"react/jsx-runtime";function Lo({textState:t,placeholder:e="Describe what you want to do...",disabled:o=!1,hasHistory:r=!1,visible:i=!0}){return i?o?Pt(Et,{children:[Ye(ot,{dimColor:!0,children:"> "}),Ye(ot,{dimColor:!0,children:t.value||"..."})]}):Pt(Et,{flexDirection:"column",children:[Pt(Et,{children:[Ye(ot,{color:"green",bold:!0,children:"> "}),Ye(ht,{value:t.value,cursorOffset:t.cursorOffset,placeholder:e,isDisabled:o})]}),r&&Ye(Et,{marginTop:1,children:Pt(ot,{dimColor:!0,children:[Ye(ot,{color:"blue",children:"[O]"})," Toggle output"]})})]}):null}import{Box as rt,Text as ge}from"ink";import{jsx as Ae,jsxs as be}from"react/jsx-runtime";var Rn=[{key:"1",label:"Execute"},{key:"2",label:"Copy"},{key:"3",label:"Edit"},{key:"4",label:"Alternatives"},{key:"5",label:"Cancel"}];function Ko({focusedIndex:t,showExplain:e=!0,visible:o=!0}){return o?be(rt,{flexDirection:"column",marginTop:1,children:[Ae(rt,{flexDirection:"row",gap:1,children:Rn.map((r,i)=>{let s=i===t;return be(rt,{children:[be(ge,{color:s?"cyan":"blue",bold:s,inverse:s,children:["[",r.key,"]"]}),be(ge,{color:s?"cyan":void 0,bold:s,children:[" ",r.label]})]},r.key)})}),e&&Ae(rt,{marginTop:1,children:be(ge,{dimColor:!0,children:[Ae(ge,{color:"blue",children:"[?]"})," Explain"," ",Ae(ge,{color:"blue",children:"[O]"})," Toggle output"," ",Ae(ge,{dimColor:!0,children:"| \u2190\u2192 Navigate, Enter Select"})]})})]}):null}function Uo({count:t,focusedIndex:e,visible:o=!0}){return o?Ae(rt,{children:be(ge,{dimColor:!0,children:["Press ",be(ge,{color:"blue",children:["1-",t]})," or ",Ae(ge,{color:"blue",children:"\u2191\u2193"})," to select,"," ",Ae(ge,{color:"blue",children:"[5]"})," Cancel",e>=0&&be(ge,{color:"cyan",children:[" (focused: ",e+1,")"]})]})}):null}import{Box as jt,Text as wn}from"ink";import{Spinner as On}from"@inkjs/ui";import{jsx as qt,jsxs as Ho}from"react/jsx-runtime";function Xt({query:t,label:e="Thinking..."}){return Ho(jt,{flexDirection:"column",marginY:1,children:[qt(jt,{children:qt(On,{label:e})}),t&&qt(jt,{marginTop:1,children:Ho(wn,{dimColor:!0,children:["Query: ",t]})})]})}import{Box as oe,Text as V}from"ink";import{homedir as Nn,userInfo as Bn}from"os";import{jsx as X,jsxs as te}from"react/jsx-runtime";var Dn=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 \u25B6 _ \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function Fo({shell:t,cwd:e,provider:o,model:r}){let i=Bn().username||"user",s=e.replace(Nn(),"~"),a=o||"anthropic",c=F[a].name,h=r||F[a].defaultModel;return te(oe,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1,marginBottom:1,children:[te(oe,{marginBottom:1,children:[X(V,{color:"cyan",bold:!0,children:Ne}),te(V,{dimColor:!0,children:[" v",me]})]}),te(oe,{children:[te(oe,{flexDirection:"column",marginRight:4,children:[te(oe,{marginBottom:1,children:[X(V,{children:"Welcome, "}),X(V,{color:"yellow",bold:!0,children:i}),X(V,{children:"!"})]}),X(oe,{flexDirection:"column",children:Dn.map((g,P)=>X(V,{color:"cyan",children:g},P))}),te(oe,{marginTop:1,flexDirection:"column",children:[te(oe,{children:[X(V,{dimColor:!0,children:"Shell: "}),X(V,{color:"green",children:t})]}),te(oe,{children:[X(V,{dimColor:!0,children:"Path: "}),X(V,{children:s})]})]})]}),te(oe,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,children:[X(oe,{marginBottom:1,children:X(V,{color:"yellow",bold:!0,children:"Quick Start"})}),te(oe,{flexDirection:"column",children:[X(V,{dimColor:!0,children:"Describe what you want in natural language:"}),te(V,{color:"gray",italic:!0,children:[" ",'"list all files modified today"']}),te(V,{color:"gray",italic:!0,children:[" ",'"find large files over 100MB"']}),te(V,{color:"gray",italic:!0,children:[" ",'"show git status"']})]}),X(oe,{marginTop:1,flexDirection:"column",children:te(oe,{children:[X(V,{dimColor:!0,children:"AI: "}),X(V,{color:"magenta",children:c}),X(V,{dimColor:!0,children:" / "}),X(V,{color:"magenta",children:h})]})})]})]})]})}import{useCallback as Rt,useRef as zo,useState as Wn}from"react";import{readdirSync as kn,statSync as Mn}from"fs";import{join as _n,relative as Ln}from"path";var Kn=new Set(["node_modules",".git",".next","dist","build","__pycache__",".venv","venv",".idea",".vscode","coverage",".cache",".npm",".yarn",".pnpm",".turbo",".nuxt",".output","target","vendor",".angular",".svelte-kit"]),Un=new Set([".DS_Store","Thumbs.db",".gitignore",".npmrc",".yarnrc","pnpm-lock.yaml","package-lock.json","yarn.lock"]),Hn=3,Fn=20;function $o(t,e=0){if(e>=Hn)return[];try{let o=kn(t),r=[],i=0;for(let s of o){if(i>=Fn){r.push({name:`... (${o.length-i} more)`,isDirectory:!1});break}if(s.startsWith(".")&&!s.startsWith(".env")||Un.has(s))continue;let a=_n(t,s);try{if(Mn(a).isDirectory()){if(Kn.has(s))continue;let h=$o(a,e+1);r.push({name:s,isDirectory:!0,children:h.length>0?h:void 0})}else r.push({name:s,isDirectory:!1});i++}catch{continue}}return r}catch{return[]}}function Go(t,e=""){let o=[];return t.forEach((r,i)=>{let s=i===t.length-1,a=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=s?" ":"\u2502 ";r.isDirectory?(o.push(`${e}${a}${r.name}/`),r.children&&r.children.length>0&&o.push(Go(r.children,`${e}${c}`))):o.push(`${e}${a}${r.name}`)}),o.join(`
1
+ var zr=(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 ut={id:"__custom__",name:"Custom model...",description:"Enter any model ID"},Ee={anthropic:[{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",description:"Fast and capable"},{id:"claude-opus-4-5",name:"Claude Opus 4.5",description:"Most capable"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",description:"Fastest"}],openrouter:[{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",description:"Anthropic"},{id:"xiaomi/mimo-v2-flash:free",name:"MiMo-V2-Flash",description:"Xiaomi (Free)"},{id:"x-ai/grok-code-fast-1",name:"Grok Code Fast 1",description:"xAI"},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",description:"Google"}],openai:[{id:"gpt-5.2",name:"GPT-5.2",description:"Most capable"},{id:"gpt-5-mini",name:"GPT-5 Mini",description:"Fast and efficient"},{id:"gpt-5-nano",name:"GPT-5 Nano",description:"Fastest"}]},Zr=Ee.anthropic;function Ot(t,e){let o=t.toLowerCase(),r=e.toLowerCase();if(r.startsWith(o))return 100+(100-r.length);if(r.includes(o))return 50+(50-r.indexOf(o));let i=0,s=0;for(let a=0;a<r.length&&s<o.length;a++)r[a]===o[s]&&(i+=10,s++);return s===o.length?i:0}function en(t,e){let o=Ot(t,e.name),r=Ot(t,e.description),i=(e.aliases??[]).map(s=>Ot(t,s));return Math.max(o,r,...i)}function co(){let t=[],e=new Map;function o(){e.clear();for(let r of t){e.set(r.name.toLowerCase(),r);for(let i of r.aliases??[])e.set(i.toLowerCase(),r)}}return{get commands(){return t},get(r){return e.get(r.toLowerCase())},filter(r){return r?t.map(s=>({cmd:s,score:en(r,s)})).filter(({score:s})=>s>0).sort((s,a)=>a.score-s.score).map(({cmd:s})=>s):[...t]},register(r){e.get(r.name.toLowerCase())||(t.push(r),o())}}}var ae=co();var Nt={name:"clear",description:"Clear conversation history",category:"session",aliases:["cls"],execute:()=>({type:"navigate",to:"clear"}),isAvailable:t=>t==="input"};var Bt={name:"config",description:"Open settings and configuration panel",category:"settings",aliases:["settings","preferences","prefs"],shortcut:"Ctrl+,",execute:()=>({type:"panel",panel:"config"}),isAvailable:t=>t==="input"};var Dt={name:"exit",description:"Exit the application",category:"session",aliases:["quit","q"],execute:()=>({type:"exit"}),isAvailable:()=>!0};var kt={name:"help",description:"Show help and keyboard shortcuts",category:"help",aliases:["h","?"],execute:()=>({type:"panel",panel:"help"}),isAvailable:()=>!0};ae.register(Bt);ae.register(kt);ae.register(Nt);ae.register(Dt);var me="3.1.1",Ne="CLI AI",uo="cli-ai";var po=".cli_ai_assistant",K=["anthropic","openrouter","openai"],mo="anthropic",F={anthropic:{name:"Anthropic",envVar:"ANTHROPIC_API_KEY",keyringAccount:"anthropic",keyPrefix:"sk-ant-",defaultModel:"claude-sonnet-4-5"},openrouter:{name:"OpenRouter",envVar:"OPENROUTER_API_KEY",keyringAccount:"openrouter",keyPrefix:"sk-or-",defaultModel:"anthropic/claude-sonnet-4.5"},openai:{name:"OpenAI",envVar:"OPENAI_API_KEY",keyringAccount:"openai",keyPrefix:"sk-",defaultModel:"gpt-5.2"}},tn=F[mo].defaultModel,Be={provider:mo,model:tn,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3,contextEnabled:!0},fo=500,go=10,xo=["rm -rf","sudo rm","chmod 777","mkfs","dd if=","> /dev/","format","del /f","rmdir /s","DROP TABLE","DELETE FROM","--no-preserve-root",":(){:|:&};:","| sh","| bash","curl | bash","wget | bash","eval","sudo su","passwd","chown -R","> /etc/","fdisk","wipefs","shred"],yo=["rm ","mv ","cp ","sudo ","npm install","pnpm install","yarn add","pip install","brew install","apt install","apt-get install","pacman -S","chmod ","chown ","git push","git reset","git rebase","docker ","kubectl ","systemctl ","service ","kill ","pkill "],ho=["sudo","rm","git","npm","pnpm","yarn","docker","kubectl","pip","python","node","npx","cd","ls","cat","grep","find","mkdir","touch","mv","cp","echo","curl","wget","ssh","scp"],le=500,z={maxAttempts:3,baseDelayMs:1e3,maxDelayMs:5e3};import mt from"conf";import{createHash as on}from"crypto";import{existsSync as vo,unlinkSync as Co}from"fs";import{hostname as rn,userInfo as nn}from"os";import{homedir as sn}from"os";import{join as So}from"path";var an="cli-ai-v3-encryption-key";function ln(){let t=`${rn()}-${nn().username}-cli-ai-v3-salt`;return on("sha256").update(t).digest("hex").slice(0,32)}var We=So(sn(),po),dt=So(We,"config.json");function cn(){if(!vo(dt))return null;try{let t=new mt({projectName:"cli-ai",cwd:We,encryptionKey:an}),e=t.get("apiKey"),o=t.get("apiKeys"),r=t.get("config");if(e||o||r)return{apiKey:e,apiKeys:o,config:r}}catch{}return null}function un(){let t=ln(),e=cn();if(e){try{Co(dt)}catch{}let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});if(e.apiKey&&!e.apiKeys?o.set("apiKeys",{anthropic:e.apiKey}):e.apiKeys&&o.set("apiKeys",e.apiKeys),e.config){let r={...e.config};r.provider||(r.provider="anthropic"),o.set("config",r)}return o}try{let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});return pn(o),o}catch{try{vo(dt)&&Co(dt)}catch{}return new mt({projectName:"cli-ai",cwd:We,encryptionKey:t})}}function pn(t){let e=t.get("apiKey");e&&!t.get("apiKeys")&&(t.set("apiKeys",{anthropic:e}),t.delete("apiKey"));let o=t.get("config");o&&!o.provider&&t.set("config",{...o,provider:"anthropic"})}var ye=un(),pt=null,To=!1,Mt=new Map,Qe=null;function mn(){if(To)return pt;To=!0;try{return pt=zr("@napi-rs/keyring"),pt}catch{return pt=null,null}}function _t(t){if(Qe===!1)return null;let e=Mt.get(t);if(e!==void 0)return e;let o=mn();if(!o)return Qe=!1,null;try{let r=F[t].keyringAccount,i=new o.Entry(uo,r);return i.getPassword(),Qe=!0,Mt.set(t,i),i}catch{return Mt.set(t,null),Qe===null&&(Qe=!1),null}}function Le(t){let e=F[t].envVar,o=process.env[e];if(o)return o;let r=_t(t);if(r)try{let s=r.getPassword();if(s)return s}catch{}return ye.get("apiKeys")?.[t]??null}function ft(t,e){try{let o=_t(t);if(o)try{o.setPassword(e);let i=ye.get("apiKeys")??{};return delete i[t],Object.keys(i).length>0?ye.set("apiKeys",i):ye.delete("apiKeys"),{success:!0,data:void 0}}catch{}let r=ye.get("apiKeys")??{};return r[t]=e,ye.set("apiKeys",r),{success:!0,data:void 0}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}function Ke(t){let e=Le(t);return e!==null&&e.length>0}function de(){let t=ye.get("config")??{};return{...Be,...t}}function he(t){let e=ye.get("config")??{};ye.set("config",{...e,...t})}function gt(t,e){let o=F[t];return t==="openai"?e.startsWith("sk-")&&e.length>20:e.startsWith(o.keyPrefix)&&e.length>20}function Eo(t){let e=F[t].envVar;if(process.env[e])return{method:"env",secure:!1,description:"Environment variable"};let o=_t(t);if(o)try{if(o.getPassword())return{method:"keyring",secure:!0,description:"System keyring"}}catch{}return ye.get("apiKeys")?.[t]?{method:"encrypted-file",secure:!1,description:"Encrypted file"}:{method:"none",secure:!1,description:"Not configured"}}import{Box as $,Text as Q,useInput as Po}from"ink";import{useState as Je}from"react";import{TextInput as dn}from"@inkjs/ui";import{jsx as O,jsxs as ce}from"react/jsx-runtime";var fn={anthropic:"https://console.anthropic.com/settings/keys",openai:"https://platform.openai.com/api-keys",openrouter:"https://openrouter.ai/keys"};function Io({onComplete:t,onError:e,error:o,provider:r}){let[i,s]=Je(r?"input":"welcome"),[a,c]=Je(r??"anthropic"),[h,g]=Je(0),[P,y]=Je(""),[m,f]=Je(null);Po((I,d)=>{i==="welcome"&&(d.return||I===" ")&&s("provider")},{isActive:i==="welcome"}),Po((I,d)=>{if(i==="provider"){if(d.upArrow){g(x=>(x-1+K.length)%K.length);return}if(d.downArrow){g(x=>(x+1)%K.length);return}if(d.return){let x=K[h];x&&(c(x),s("input"));return}let A=parseInt(I,10);if(A>=1&&A<=K.length){let x=K[A-1];x&&(c(x),s("input"))}}},{isActive:i==="provider"});let n=I=>{let d=I.trim();if(!d){f("API key cannot be empty");return}if(!gt(a,d)){let A=F[a];f(`Invalid key format. ${A.name} API keys start with "${A.keyPrefix}"`);return}f(null),s("saving"),t(d,a)};if(i==="welcome")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,color:"cyan",children:[Ne," v",me]})}),O($,{marginBottom:1,children:O(Q,{children:"Welcome! This tool translates natural language into shell commands."})}),O($,{marginBottom:1,children:O(Q,{dimColor:!0,children:"To get started, you'll need an API key from one of the supported providers."})}),O($,{children:O(Q,{color:"green",children:"Press Enter to continue..."})})]});if(i==="provider")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:O(Q,{bold:!0,children:"Select your AI provider:"})}),K.map((I,d)=>{let A=F[I],x=d===h;return ce($,{children:[O(Q,{color:x?"cyan":"gray",bold:x,children:x?"> ":" "}),ce(Q,{color:x?"cyan":"white",children:[d+1,". ",A.name]})]},I)}),O($,{marginTop:1,children:O(Q,{dimColor:!0,children:"[Up/Down] Navigate [Enter] Select [1-3] Quick select"})})]});let T=o??m,v=F[a];return i==="input"?ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,children:["Enter your ",v.name," API key:"]})}),O($,{marginBottom:1,children:ce(Q,{dimColor:!0,children:["Get one at: ",O(Q,{color:"blue",children:fn[a]})]})}),T&&O($,{marginBottom:1,children:ce(Q,{color:"red",children:["\u26A0 ",T]})}),ce($,{children:[O(Q,{dimColor:!0,children:"> "}),O(dn,{placeholder:`${v.keyPrefix}...`,onChange:y,onSubmit:n})]}),O($,{marginTop:1,children:O(Q,{color:"yellow",children:"\u{1F512} Your key is stored securely on this machine using your system's credential manager."})})]}):i==="saving"?O($,{flexDirection:"column",paddingY:1,children:O($,{children:O(Q,{color:"yellow",children:"\u23F3 Saving API key..."})})}):ce($,{flexDirection:"column",paddingY:1,children:[O($,{children:O(Q,{color:"green",children:"\u2713 API key saved successfully!"})}),O($,{marginTop:1,children:ce(Q,{children:["Starting ",Ne,"..."]})})]})}import{Box as xt,Text as Lt}from"ink";import{jsx as ze,jsxs as bo}from"react/jsx-runtime";function Ao({lines:t,command:e}){return bo(xt,{flexDirection:"column",marginY:1,children:[ze(xt,{marginBottom:1,children:bo(Lt,{dimColor:!0,children:["$ ",e]})}),ze(xt,{flexDirection:"column",children:t.map((o,r)=>{let i=o.startsWith("[ERR]");return ze(Lt,{color:i?"red":void 0,children:i?o.slice(6):o},r)})}),ze(xt,{marginTop:1,children:ze(Lt,{color:"yellow",children:"\u23F3 Running..."})})]})}import{Box as He,Text as Fe}from"ink";import{Box as gn,Text as Pe}from"ink";import{Fragment as xn,jsx as Ue,jsxs as yt}from"react/jsx-runtime";function Kt({command:t,index:e,isSelected:o}){return yt(gn,{children:[Ue(Pe,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),yt(Pe,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),Ue(Pe,{children:" "}),yt(Pe,{color:o?"white":"gray",bold:o,children:["/",t.name]}),Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!o,children:t.description}),t.shortcut?yt(xn,{children:[Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!0,color:"yellow",children:t.shortcut})]}):null]})}import{jsx as fe,jsxs as wo}from"react/jsx-runtime";function Ut({query:t,filteredCommands:e,selectedIndex:o,visible:r}){return r?wo(He,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginTop:1,children:[wo(He,{children:[fe(Fe,{color:"blue",bold:!0,children:"/"}),fe(Fe,{color:"white",children:t}),fe(Fe,{color:"cyan",children:"_"})]}),fe(He,{marginY:0,children:fe(Fe,{dimColor:!0,children:"\u2500".repeat(50)})}),e.length>0?fe(He,{flexDirection:"column",children:e.slice(0,9).map((i,s)=>fe(Kt,{command:i,index:s,isSelected:s===o},i.name))}):fe(He,{children:fe(Fe,{dimColor:!0,children:"No matching commands"})}),fe(He,{marginTop:1,children:fe(Fe,{dimColor:!0,children:"[Enter] Select [1-9] Quick select [Esc] Close"})})]}):null}import{Box as Ie,Text as De}from"ink";import gi from"chalk";function yn(t){let e=[],o=t.split(/(\s+)/);for(let r of o)if(r){if(/^\s+$/.test(r)){e.push({type:"default",value:r});continue}if(/^[|><&;]+$/.test(r)||r==="&&"||r==="||"){e.push({type:"pipe",value:r});continue}if(/^-{1,2}[\w-]+=?/.test(r)){e.push({type:"flag",value:r});continue}if(/^\$[\w{}]+/.test(r)){e.push({type:"variable",value:r});continue}if(/^["'].*["']$/.test(r)){e.push({type:"string",value:r});continue}if(r.includes("/")||r.includes("\\")){e.push({type:"path",value:r});continue}if(ho.includes(r.toLowerCase())){e.push({type:"keyword",value:r});continue}e.push({type:"default",value:r})}return e}function Ro(t){return yn(t).map(o=>{switch(o.type){case"keyword":return{text:o.value,color:"cyan",bold:!0};case"flag":return{text:o.value,color:"yellow"};case"string":return{text:o.value,color:"green"};case"pipe":return{text:o.value,color:"magenta"};case"path":return{text:o.value,color:"blue"};case"variable":return{text:o.value,color:"cyan"};default:return{text:o.value}}})}import{jsx as ne,jsxs as Ze}from"react/jsx-runtime";function Oo({command:t}){let e=Ro(t);return ne(De,{children:e.map((o,r)=>ne(De,{color:o.color,bold:o.bold,children:o.text},r))})}function No({proposal:t,showExplanation:e=!1}){return Ze(Ie,{flexDirection:"column",children:[ne(Ie,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,children:ne(Oo,{command:t.command})}),e&&t.explanation&&ne(Ie,{marginTop:1,paddingX:1,children:ne(De,{dimColor:!0,children:t.explanation})})]})}function hn({command:t,index:e,selected:o=!1}){return Ze(Ie,{children:[Ze(De,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),ne(De,{children:" "}),ne(Oo,{command:t})]})}function Bo({proposals:t,selectedIndex:e=-1}){return Ze(Ie,{flexDirection:"column",marginY:1,children:[ne(Ie,{marginBottom:1,children:ne(De,{bold:!0,children:"Alternative commands:"})}),t.map((o,r)=>ne(Ie,{marginBottom:1,children:ne(hn,{command:o.command,index:r,selected:r===e})},r)),ne(Ie,{marginTop:1,children:Ze(De,{dimColor:!0,children:["Press 1-",t.length," to select, or [5] Cancel"]})})]})}import{Box as Ei,Text as Pi}from"ink";import{Fragment as Ai,jsx as bi,jsxs as wi}from"react/jsx-runtime";import{Text as Cn}from"ink";import et from"chalk";import{useMemo as Do}from"react";import{jsx as vn}from"react/jsx-runtime";var Ht=et.inverse(" ");function ht({value:t,cursorOffset:e,placeholder:o="",isDisabled:r=!1}){let i=Do(()=>r?o?et.dim(o):"":o&&o.length>0?et.inverse(o[0])+et.dim(o.slice(1)):Ht,[r,o]),s=Do(()=>{if(r)return t;let a=0,c=t.length>0?"":Ht;for(let h of t)c+=a===e?et.inverse(h):h,a++;return t.length>0&&e===t.length&&(c+=Ht),c},[r,t,e]);return vn(Cn,{children:t.length>0?s:i})}var Tn={value:"",cursorOffset:0};function Ft(t=""){return{value:t,cursorOffset:t.length}}function $t(t,e){switch(e.type){case"insert":return{value:t.value.slice(0,t.cursorOffset)+e.text+t.value.slice(t.cursorOffset),cursorOffset:t.cursorOffset+e.text.length};case"delete":{if(t.cursorOffset===0)return t;let o=t.cursorOffset-1;return{value:t.value.slice(0,o)+t.value.slice(o+1),cursorOffset:o}}case"move-left":return{...t,cursorOffset:Math.max(0,t.cursorOffset-1)};case"move-right":return{...t,cursorOffset:Math.min(t.value.length,t.cursorOffset+1)};case"clear":return Tn;case"set":return{value:e.value,cursorOffset:e.value.length};default:return t}}import{Box as Ct,Text as Gt}from"ink";import{jsx as tt,jsxs as ko}from"react/jsx-runtime";function $e({title:t,isActive:e,children:o}){return ko(Ct,{flexDirection:"column",marginBottom:1,children:[ko(Ct,{children:[tt(Gt,{color:e?"cyan":"white",bold:!0,children:t}),e?tt(Gt,{color:"cyan",children:" *"}):null]}),tt(Ct,{children:tt(Gt,{dimColor:!0,children:"\u2500".repeat(50)})}),tt(Ct,{flexDirection:"column",paddingLeft:0,children:o})]})}import{Box as Sn,Text as Tt}from"ink";import{jsx as vt,jsxs as En}from"react/jsx-runtime";function Ge({label:t,value:e,isSelected:o}){return En(Sn,{children:[vt(Tt,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),vt(Tt,{color:e?"green":"gray",children:e?"[x]":"[ ]"}),vt(Tt,{children:" "}),vt(Tt,{color:o?"white":"gray",children:t})]})}import{Box as Y,Text as w}from"ink";import{Fragment as _o,jsx as E,jsxs as M}from"react/jsx-runtime";var Mo=["provider","api-keys","toggles","about"];function Yt({visible:t,activeSection:e,sectionItemIndex:o,config:r,hasApiKey:i,storageInfo:s,maskedKey:a,toggles:c,isEditingCustomModel:h=!1,customModelState:g}){if(!t)return null;let P=Mo.indexOf(e),y=Ee[r.provider],m=!y.some(n=>n.id===r.model),f=K.length+y.length;return M(Y,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[M(Y,{justifyContent:"space-between",marginBottom:1,children:[E(Y,{children:E(w,{color:"cyan",bold:!0,children:"Settings"})}),E(Y,{children:E(w,{dimColor:!0,children:"[Esc] Close [Tab] Section [Enter] Select"})})]}),E($e,{title:"Provider & Model",isActive:e==="provider",children:M(Y,{flexDirection:"column",children:[E(Y,{marginBottom:1,children:E(w,{dimColor:!0,children:"Provider"})}),K.map((n,T)=>{let v=F[n],I=r.provider===n,d=Ke(n),A=e==="provider"&&o===T;return M(Y,{children:[E(w,{color:A?"cyan":"gray",bold:A,children:A?"> ":" "}),M(w,{color:A?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",v.name]}),E(w,{children:" "}),E(w,{color:d?"green":"red",dimColor:!A,children:d?"\u2713 Key":"\u2717 No key"})]},n)}),E(Y,{marginTop:1,marginBottom:1,children:E(w,{dimColor:!0,children:"Model"})}),y.map((n,T)=>{let v=T+K.length,I=r.model===n.id,d=e==="provider"&&o===v;return M(Y,{children:[E(w,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(w,{color:d?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",n.name]}),M(w,{dimColor:!d,children:[" ",n.description]})]},n.id)}),M(Y,{children:[E(w,{color:e==="provider"&&o===f?"cyan":"gray",bold:e==="provider"&&o===f,children:e==="provider"&&o===f?"> ":" "}),h&&g?M(_o,{children:[E(w,{color:"cyan",children:"\u25CB "}),E(ht,{value:g.value,cursorOffset:g.cursorOffset,placeholder:"model-id"}),E(w,{dimColor:!0,children:" (Enter to save, Esc to cancel)"})]}):M(_o,{children:[M(w,{color:e==="provider"&&o===f?"cyan":m?"green":"white",children:[m?"\u25CF":"\u25CB"," ",ut.name]}),M(w,{dimColor:!(e==="provider"&&o===f),children:[" ",m?`(${r.model})`:ut.description]})]})]},ut.id)]})}),E($e,{title:"API Keys",isActive:e==="api-keys",children:E(Y,{flexDirection:"column",children:K.map((n,T)=>{let v=F[n],I=Ke(n),d=e==="api-keys"&&o===T;return M(Y,{children:[E(w,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(w,{color:d?"cyan":"white",children:[v.name,": "]}),E(w,{color:I?"green":"red",children:I?"\u2713 Configured":"\u2717 Not set"}),M(w,{dimColor:!d,children:[" [Enter to ",I?"change":"add","]"]})]},n)})})}),M($e,{title:"Options",isActive:e==="toggles",children:[E(Ge,{label:"Context (pass history to AI)",value:c.contextEnabled,isSelected:e==="toggles"&&o===0}),E(Ge,{label:"Show explanations",value:c.showExplanations,isSelected:e==="toggles"&&o===1}),E(Ge,{label:"Syntax highlighting",value:c.syntaxHighlighting,isSelected:e==="toggles"&&o===2}),E(Ge,{label:"Simple mode",value:c.simpleMode,isSelected:e==="toggles"&&o===3})]}),E($e,{title:"About",isActive:e==="about",children:M(Y,{flexDirection:"column",children:[M(Y,{children:[E(w,{dimColor:!0,children:"Version: "}),M(w,{children:["CLI AI v",me]})]}),M(Y,{children:[E(w,{dimColor:!0,children:"Provider: "}),E(w,{color:"magenta",children:F[r.provider].name})]}),M(Y,{children:[E(w,{dimColor:!0,children:"Model: "}),E(w,{color:"magenta",children:r.model})]}),M(Y,{children:[E(w,{dimColor:!0,children:"Storage: "}),E(w,{color:s.secure?"green":"yellow",children:s.description})]})]})}),E(Y,{marginTop:1,justifyContent:"center",children:Mo.map((n,T)=>E(Y,{marginX:1,children:M(w,{color:T===P?"cyan":"gray",children:[T===P?"[":" ",T+1,T===P?"]":" "]})},n))})]})}import{Box as Ji,Text as zi}from"ink";import{Fragment as ta,jsx as ea,jsxs as oa}from"react/jsx-runtime";import{Box as G,Text as ee}from"ink";import{jsx as N,jsxs as se}from"react/jsx-runtime";var Pn=[{key:"/",description:"Open command palette"},{key:"Enter",description:"Submit query"},{key:"Ctrl+D",description:"Exit (when input is empty)"},{key:"O",description:"Toggle output expansion (when input is empty)"}],In=[{key:"1 / Enter",description:"Execute command"},{key:"2",description:"Copy to clipboard"},{key:"3",description:"Edit command"},{key:"4",description:"Show alternatives"},{key:"5 / Esc",description:"Cancel"},{key:"?",description:"Explain command"},{key:"O",description:"Toggle output"}],bn=[{key:"Up/Down",description:"Navigate commands"},{key:"Enter",description:"Select command"},{key:"Esc",description:"Close palette"},{key:"1-9",description:"Quick select"}],An=[{key:"Tab",description:"Next section"},{key:"Shift+Tab",description:"Previous section"},{key:"Up/Down",description:"Navigate items"},{key:"Enter/Space",description:"Toggle/Select"},{key:"Esc",description:"Close panel"}];function St({title:t,shortcuts:e}){return se(G,{flexDirection:"column",marginBottom:1,children:[N(ee,{color:"yellow",bold:!0,children:t}),e.map(o=>se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:o.key})}),N(ee,{dimColor:!0,children:o.description})]},o.key))]})}function Vt({visible:t}){return t?se(G,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[se(G,{justifyContent:"space-between",marginBottom:1,children:[N(G,{children:se(ee,{color:"cyan",bold:!0,children:["Help - ",Ne," v",me]})}),N(G,{children:N(ee,{dimColor:!0,children:"[Esc] Close"})})]}),N(G,{marginBottom:1,children:N(ee,{children:"Natural language to shell command translator. Describe what you want in plain English and get executable commands."})}),se(G,{children:[se(G,{flexDirection:"column",marginRight:4,children:[N(St,{title:"Input Mode",shortcuts:Pn}),N(St,{title:"Command Palette",shortcuts:bn})]}),se(G,{flexDirection:"column",children:[N(St,{title:"Proposal Mode",shortcuts:In}),N(St,{title:"Config Panel",shortcuts:An})]})]}),se(G,{flexDirection:"column",marginTop:1,children:[N(ee,{color:"yellow",bold:!0,children:"Available Commands"}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/config"})}),N(ee,{dimColor:!0,children:"Open settings panel"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/help"})}),N(ee,{dimColor:!0,children:"Show this help"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/clear"})}),N(ee,{dimColor:!0,children:"Clear command history"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/exit"})}),N(ee,{dimColor:!0,children:"Exit application"})]})]})]}):null}import{Box as Et,Text as ot}from"ink";import{jsx as Ye,jsxs as Pt}from"react/jsx-runtime";function Lo({textState:t,placeholder:e="Describe what you want to do...",disabled:o=!1,hasHistory:r=!1,visible:i=!0}){return i?o?Pt(Et,{children:[Ye(ot,{dimColor:!0,children:"> "}),Ye(ot,{dimColor:!0,children:t.value||"..."})]}):Pt(Et,{flexDirection:"column",children:[Pt(Et,{children:[Ye(ot,{color:"green",bold:!0,children:"> "}),Ye(ht,{value:t.value,cursorOffset:t.cursorOffset,placeholder:e,isDisabled:o})]}),r&&Ye(Et,{marginTop:1,children:Pt(ot,{dimColor:!0,children:[Ye(ot,{color:"blue",children:"[O]"})," Toggle output"]})})]}):null}import{Box as rt,Text as ge}from"ink";import{jsx as Ae,jsxs as be}from"react/jsx-runtime";var wn=[{key:"1",label:"Execute"},{key:"2",label:"Copy"},{key:"3",label:"Edit"},{key:"4",label:"Alternatives"},{key:"5",label:"Cancel"}];function Ko({focusedIndex:t,showExplain:e=!0,visible:o=!0}){return o?be(rt,{flexDirection:"column",marginTop:1,children:[Ae(rt,{flexDirection:"row",gap:1,children:wn.map((r,i)=>{let s=i===t;return be(rt,{children:[be(ge,{color:s?"cyan":"blue",bold:s,inverse:s,children:["[",r.key,"]"]}),be(ge,{color:s?"cyan":void 0,bold:s,children:[" ",r.label]})]},r.key)})}),e&&Ae(rt,{marginTop:1,children:be(ge,{dimColor:!0,children:[Ae(ge,{color:"blue",children:"[?]"})," Explain"," ",Ae(ge,{color:"blue",children:"[O]"})," Toggle output"," ",Ae(ge,{dimColor:!0,children:"| \u2190\u2192 Navigate, Enter Select"})]})})]}):null}function Uo({count:t,focusedIndex:e,visible:o=!0}){return o?Ae(rt,{children:be(ge,{dimColor:!0,children:["Press ",be(ge,{color:"blue",children:["1-",t]})," or ",Ae(ge,{color:"blue",children:"\u2191\u2193"})," to select,"," ",Ae(ge,{color:"blue",children:"[5]"})," Cancel",e>=0&&be(ge,{color:"cyan",children:[" (focused: ",e+1,")"]})]})}):null}import{Box as jt,Text as Rn}from"ink";import{Spinner as On}from"@inkjs/ui";import{jsx as qt,jsxs as Ho}from"react/jsx-runtime";function Xt({query:t,label:e="Thinking..."}){return Ho(jt,{flexDirection:"column",marginY:1,children:[qt(jt,{children:qt(On,{label:e})}),t&&qt(jt,{marginTop:1,children:Ho(Rn,{dimColor:!0,children:["Query: ",t]})})]})}import{Box as oe,Text as V}from"ink";import{homedir as Nn,userInfo as Bn}from"os";import{jsx as X,jsxs as te}from"react/jsx-runtime";var Dn=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 \u25B6 _ \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function Fo({shell:t,cwd:e,provider:o,model:r}){let i=Bn().username||"user",s=e.replace(Nn(),"~"),a=o||"anthropic",c=F[a].name,h=r||F[a].defaultModel;return te(oe,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1,marginBottom:1,children:[te(oe,{marginBottom:1,children:[X(V,{color:"cyan",bold:!0,children:Ne}),te(V,{dimColor:!0,children:[" v",me]})]}),te(oe,{children:[te(oe,{flexDirection:"column",marginRight:4,children:[te(oe,{marginBottom:1,children:[X(V,{children:"Welcome, "}),X(V,{color:"yellow",bold:!0,children:i}),X(V,{children:"!"})]}),X(oe,{flexDirection:"column",children:Dn.map((g,P)=>X(V,{color:"cyan",children:g},P))}),te(oe,{marginTop:1,flexDirection:"column",children:[te(oe,{children:[X(V,{dimColor:!0,children:"Shell: "}),X(V,{color:"green",children:t})]}),te(oe,{children:[X(V,{dimColor:!0,children:"Path: "}),X(V,{children:s})]})]})]}),te(oe,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,children:[X(oe,{marginBottom:1,children:X(V,{color:"yellow",bold:!0,children:"Quick Start"})}),te(oe,{flexDirection:"column",children:[X(V,{dimColor:!0,children:"Describe what you want in natural language:"}),te(V,{color:"gray",italic:!0,children:[" ",'"list all files modified today"']}),te(V,{color:"gray",italic:!0,children:[" ",'"find large files over 100MB"']}),te(V,{color:"gray",italic:!0,children:[" ",'"show git status"']})]}),X(oe,{marginTop:1,flexDirection:"column",children:te(oe,{children:[X(V,{dimColor:!0,children:"AI: "}),X(V,{color:"magenta",children:c}),X(V,{dimColor:!0,children:" / "}),X(V,{color:"magenta",children:h})]})})]})]})]})}import{useCallback as wt,useRef as zo,useState as Wn}from"react";import{readdirSync as kn,statSync as Mn}from"fs";import{join as _n,relative as Ln}from"path";var Kn=new Set(["node_modules",".git",".next","dist","build","__pycache__",".venv","venv",".idea",".vscode","coverage",".cache",".npm",".yarn",".pnpm",".turbo",".nuxt",".output","target","vendor",".angular",".svelte-kit"]),Un=new Set([".DS_Store","Thumbs.db",".gitignore",".npmrc",".yarnrc","pnpm-lock.yaml","package-lock.json","yarn.lock"]),Hn=3,Fn=20;function $o(t,e=0){if(e>=Hn)return[];try{let o=kn(t),r=[],i=0;for(let s of o){if(i>=Fn){r.push({name:`... (${o.length-i} more)`,isDirectory:!1});break}if(s.startsWith(".")&&!s.startsWith(".env")||Un.has(s))continue;let a=_n(t,s);try{if(Mn(a).isDirectory()){if(Kn.has(s))continue;let h=$o(a,e+1);r.push({name:s,isDirectory:!0,children:h.length>0?h:void 0})}else r.push({name:s,isDirectory:!1});i++}catch{continue}}return r}catch{return[]}}function Go(t,e=""){let o=[];return t.forEach((r,i)=>{let s=i===t.length-1,a=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=s?" ":"\u2502 ";r.isDirectory?(o.push(`${e}${a}${r.name}/`),r.children&&r.children.length>0&&o.push(Go(r.children,`${e}${c}`))):o.push(`${e}${a}${r.name}`)}),o.join(`
2
2
  `)}function Yo(t){let e=$o(t);return e.length===0?"(empty or inaccessible directory)":`${Ln(process.cwd(),t)||"."}/
3
3
  ${Go(e)}`}import{appendFileSync as $n,writeFileSync as Gn}from"fs";import{join as Yn}from"path";var Vo=process.env.DEBUG==="1"||process.env.DEBUG==="true",jo=Yn(process.cwd(),"debug.log");if(Vo)try{Gn(jo,`=== Debug session started: ${new Date().toISOString()} ===
4
4
  `)}catch{}function qo(t,e){if(!Vo)return;let r=`[${new Date().toISOString().slice(11,23)}] ${t}`;e!==void 0&&(r+=`: ${JSON.stringify(e)}`);try{$n(jo,r+`
@@ -45,13 +45,13 @@ Generate ${i} ALTERNATIVE commands (different approaches).
45
45
  Exclude: ${r}
46
46
 
47
47
  Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.send({model:this.model,maxTokens:le*2,messages:[{role:"system",content:Ce(o.shell)},{role:"user",content:s}]})).choices?.[0]?.message?.content;if(!c||typeof c!="string")throw new Error("No content in AI response");return{success:!0,data:je(c)}}catch(a){return{success:!1,error:a instanceof Error?a:new Error(String(a))}}}async explainCommand(e){try{let r=(await this.client.chat.send({model:this.model,maxTokens:le,messages:[{role:"user",content:`Explain this command briefly (2-3 sentences max):
48
- ${e}`}]})).choices?.[0]?.message?.content;if(!r||typeof r!="string")throw new Error("No content in AI response");return{success:!0,data:r.trim()}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}};function Xo(t,e,o){switch(qo(`Creating provider: ${t}/${o}`),t){case"anthropic":return new It(e,o);case"openai":return new bt(e,o);case"openrouter":return new At(e,o)}}var Wt=null;function Jt(){let t=de(),e=Le(t.provider);if(!e)return null;let o=`${t.provider}:${t.model}:${e.slice(-4)}`;if(Wt?.key===o)return Wt.instance;let r=Xo(t.provider,e,t.model);return Wt={key:o,instance:r},r}async function Qo(t,e){let o=Jt();return o?o.generateCommand(t,e):{success:!1,error:new Error("No API key configured")}}async function Wo(t,e,o,r=3){let i=Jt();return i?i.generateAlternatives(t,e,o,r):{success:!1,error:new Error("No API key configured")}}async function Jo(t){let e=Jt();return e?e.explainCommand(t):{success:!1,error:new Error("No API key configured")}}function zt(t,e=[]){let o=process.cwd();return{shell:t,cwd:o,platform:process.platform,directoryTree:Yo(o),history:e}}function Zo({shell:t,history:e=[],contextEnabled:o=!0}){let[r,i]=Wn({isLoading:!1,error:null,lastProposal:null}),s=zo(e);s.current=e;let a=zo(o);a.current=o;let c=Rt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=a.current?s.current:[],f=zt(t,m),n=await Qo(y,f);return n.success?i(T=>({...T,isLoading:!1,lastProposal:n.data})):i(T=>({...T,isLoading:!1,error:n.error})),n}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[t]),h=Rt(async(y,m)=>{i(f=>({...f,isLoading:!0,error:null}));try{let f=a.current?s.current:[],n=zt(t,f),T=await Wo(y,n,m);return i(v=>({...v,isLoading:!1})),T.success||i(v=>({...v,error:T.error})),T}catch(f){let n=f instanceof Error?f:new Error(String(f));return i(T=>({...T,isLoading:!1,error:n})),{success:!1,error:n}}},[t]),g=Rt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=await Jo(y);return i(f=>({...f,isLoading:!1})),m.success||i(f=>({...f,error:m.error})),m}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[]),P=Rt(()=>{i(y=>({...y,error:null}))},[]);return{...r,generate:c,getAlternatives:h,explain:g,clearError:P}}import{useCallback as Re,useMemo as Jn,useState as er}from"react";function tr({sessionStatus:t,config:e,updateConfig:o,onOpenConfig:r,onOpenHelp:i,onClearHistory:s,onExit:a}){let[c,h]=er(""),[g,P]=er(0),y=Jn(()=>ae.filter(c).filter(Z=>!Z.isAvailable||Z.isAvailable(t)),[c,t]),m=Re(x=>{h(x),P(0)},[]),f=Re(()=>{P(x=>y.length===0?0:(x-1+y.length)%y.length)},[y.length]),n=Re(()=>{P(x=>y.length===0?0:(x+1)%y.length)},[y.length]),T=Re(()=>({sessionStatus:t,config:e,updateConfig:o,exit:a}),[t,e,o,a]),v=Re(x=>{switch(x.type){case"panel":x.panel==="config"?r():x.panel==="help"&&i();break;case"navigate":x.to==="clear"&&s();break;case"exit":a();break}return x},[r,i,s,a]),I=Re(()=>{if(y.length===0)return null;let x=y[g];if(!x)return null;let Z=T(),W=x.execute(Z);return W instanceof Promise?(W.then(v),null):v(W)},[y,g,T,v]),d=Re(x=>{let Z=ae.get(x);if(!Z||Z.isAvailable&&!Z.isAvailable(t))return null;let W=T(),ue=Z.execute(W);return ue instanceof Promise?(ue.then(v),null):v(ue)},[t,T,v]),A=Re(()=>{h(""),P(0)},[]);return{query:c,setQuery:m,filteredCommands:y,focusedIndex:g,focusUp:f,focusDown:n,executeSelected:I,executeCommand:d,reset:A}}import{useCallback as Zt,useEffect as zn,useState as Zn}from"react";function or(){let[t,e]=Zn({isLoading:!0,hasKey:!1,config:de(),error:null});zn(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,isLoading:!1,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,isLoading:!1,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);let o=Zt((s,a)=>{if(!gt(s,a))return e(c=>({...c,error:`Invalid API key format for ${s}`})),!1;try{let c=ft(s,a);return c.success?(e(h=>({...h,hasKey:!0,error:null})),!0):(e(h=>({...h,error:c.error.message})),!1)}catch(c){return e(h=>({...h,error:c instanceof Error?c.message:"Failed to save API key"})),!1}},[]),r=Zt(s=>{he(s),e(a=>({...a,config:{...a.config,...s}}))},[]),i=Zt(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);return{...t,saveKey:o,updateConfig:r,refreshKeyStatus:i}}import{execa as es}from"execa";import{useCallback as sr,useRef as ts,useState as os}from"react";function rr(){if(process.platform==="win32")return process.env.MSYSTEM||process.env.MINGW_PREFIX?"bash":process.env.PSModulePath?.includes("PowerShell\\7")?"pwsh":process.env.PSModulePath?"powershell":"cmd";let t=process.env.SHELL??"/bin/bash";return t.includes("zsh")?"zsh":t.includes("fish")?"fish":"bash"}function nr(t,e){switch(t){case"powershell":return{cmd:"powershell",args:["-Command",e]};case"pwsh":return{cmd:"pwsh",args:["-Command",e]};case"cmd":return{cmd:"cmd",args:["/c",e]};default:return{cmd:t,args:["-c",e]}}}function ir({shell:t,maxOutputLines:e=Be.maxOutputLines,onOutput:o,onComplete:r}){let[i,s]=os({isExecuting:!1,liveOutput:[],error:null}),a=ts(null),c=sr(async g=>{s({isExecuting:!0,liveOutput:[],error:null});let{cmd:P,args:y}=nr(t,g);try{let m=es(P,y,{reject:!1,all:!0,buffer:!0});a.current=m;let f=[];m.stdout&&m.stdout.on("data",v=>{let I=v.toString().split(`
48
+ ${e}`}]})).choices?.[0]?.message?.content;if(!r||typeof r!="string")throw new Error("No content in AI response");return{success:!0,data:r.trim()}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}};function Xo(t,e,o){switch(qo(`Creating provider: ${t}/${o}`),t){case"anthropic":return new It(e,o);case"openai":return new bt(e,o);case"openrouter":return new At(e,o)}}var Wt=null;function Jt(){let t=de(),e=Le(t.provider);if(!e)return null;let o=`${t.provider}:${t.model}:${e.slice(-4)}`;if(Wt?.key===o)return Wt.instance;let r=Xo(t.provider,e,t.model);return Wt={key:o,instance:r},r}async function Qo(t,e){let o=Jt();return o?o.generateCommand(t,e):{success:!1,error:new Error("No API key configured")}}async function Wo(t,e,o,r=3){let i=Jt();return i?i.generateAlternatives(t,e,o,r):{success:!1,error:new Error("No API key configured")}}async function Jo(t){let e=Jt();return e?e.explainCommand(t):{success:!1,error:new Error("No API key configured")}}function zt(t,e=[]){let o=process.cwd();return{shell:t,cwd:o,platform:process.platform,directoryTree:Yo(o),history:e}}function Zo({shell:t,history:e=[],contextEnabled:o=!0}){let[r,i]=Wn({isLoading:!1,error:null,lastProposal:null}),s=zo(e);s.current=e;let a=zo(o);a.current=o;let c=wt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=a.current?s.current:[],f=zt(t,m),n=await Qo(y,f);return n.success?i(T=>({...T,isLoading:!1,lastProposal:n.data})):i(T=>({...T,isLoading:!1,error:n.error})),n}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[t]),h=wt(async(y,m)=>{i(f=>({...f,isLoading:!0,error:null}));try{let f=a.current?s.current:[],n=zt(t,f),T=await Wo(y,n,m);return i(v=>({...v,isLoading:!1})),T.success||i(v=>({...v,error:T.error})),T}catch(f){let n=f instanceof Error?f:new Error(String(f));return i(T=>({...T,isLoading:!1,error:n})),{success:!1,error:n}}},[t]),g=wt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=await Jo(y);return i(f=>({...f,isLoading:!1})),m.success||i(f=>({...f,error:m.error})),m}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[]),P=wt(()=>{i(y=>({...y,error:null}))},[]);return{...r,generate:c,getAlternatives:h,explain:g,clearError:P}}import{useCallback as we,useMemo as Jn,useState as er}from"react";function tr({sessionStatus:t,config:e,updateConfig:o,onOpenConfig:r,onOpenHelp:i,onClearHistory:s,onExit:a}){let[c,h]=er(""),[g,P]=er(0),y=Jn(()=>ae.filter(c).filter(Z=>!Z.isAvailable||Z.isAvailable(t)),[c,t]),m=we(x=>{h(x),P(0)},[]),f=we(()=>{P(x=>y.length===0?0:(x-1+y.length)%y.length)},[y.length]),n=we(()=>{P(x=>y.length===0?0:(x+1)%y.length)},[y.length]),T=we(()=>({sessionStatus:t,config:e,updateConfig:o,exit:a}),[t,e,o,a]),v=we(x=>{switch(x.type){case"panel":x.panel==="config"?r():x.panel==="help"&&i();break;case"navigate":x.to==="clear"&&s();break;case"exit":a();break}return x},[r,i,s,a]),I=we(()=>{if(y.length===0)return null;let x=y[g];if(!x)return null;let Z=T(),W=x.execute(Z);return W instanceof Promise?(W.then(v),null):v(W)},[y,g,T,v]),d=we(x=>{let Z=ae.get(x);if(!Z||Z.isAvailable&&!Z.isAvailable(t))return null;let W=T(),ue=Z.execute(W);return ue instanceof Promise?(ue.then(v),null):v(ue)},[t,T,v]),A=we(()=>{h(""),P(0)},[]);return{query:c,setQuery:m,filteredCommands:y,focusedIndex:g,focusUp:f,focusDown:n,executeSelected:I,executeCommand:d,reset:A}}import{useCallback as Zt,useEffect as zn,useState as Zn}from"react";function or(){let[t,e]=Zn({isLoading:!0,hasKey:!1,config:de(),error:null});zn(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,isLoading:!1,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,isLoading:!1,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);let o=Zt((s,a)=>{if(!gt(s,a))return e(c=>({...c,error:`Invalid API key format for ${s}`})),!1;try{let c=ft(s,a);return c.success?(e(h=>({...h,hasKey:!0,error:null})),!0):(e(h=>({...h,error:c.error.message})),!1)}catch(c){return e(h=>({...h,error:c instanceof Error?c.message:"Failed to save API key"})),!1}},[]),r=Zt(s=>{he(s),e(a=>({...a,config:{...a.config,...s}}))},[]),i=Zt(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);return{...t,saveKey:o,updateConfig:r,refreshKeyStatus:i}}import{execa as es}from"execa";import{useCallback as sr,useRef as ts,useState as os}from"react";function rr(){if(process.platform==="win32")return process.env.MSYSTEM||process.env.MINGW_PREFIX?"bash":process.env.PSModulePath?.includes("PowerShell\\7")?"pwsh":process.env.PSModulePath?"powershell":"cmd";let t=process.env.SHELL??"/bin/bash";return t.includes("zsh")?"zsh":t.includes("fish")?"fish":"bash"}function nr(t,e){switch(t){case"powershell":return{cmd:"powershell",args:["-Command",e]};case"pwsh":return{cmd:"pwsh",args:["-Command",e]};case"cmd":return{cmd:"cmd",args:["/c",e]};default:return{cmd:t,args:["-c",e]}}}function ir({shell:t,maxOutputLines:e=Be.maxOutputLines,onOutput:o,onComplete:r}){let[i,s]=os({isExecuting:!1,liveOutput:[],error:null}),a=ts(null),c=sr(async g=>{s({isExecuting:!0,liveOutput:[],error:null});let{cmd:P,args:y}=nr(t,g);try{let m=es(P,y,{reject:!1,all:!0,buffer:!0});a.current=m;let f=[];m.stdout&&m.stdout.on("data",v=>{let I=v.toString().split(`
49
49
  `).filter(Boolean);for(let d of I)f.push(d),o?.(d,!1),s(A=>({...A,liveOutput:[...A.liveOutput,d].slice(-e)}))}),m.stderr&&m.stderr.on("data",v=>{let I=v.toString().split(`
50
- `).filter(Boolean);for(let d of I){let A=`[ERR] ${d}`;f.push(A),o?.(d,!0),s(x=>({...x,liveOutput:[...x.liveOutput,A].slice(-e)}))}});let n=await m;a.current=null;let T={command:g,stdout:n.stdout??"",stderr:n.stderr??"",exitCode:n.exitCode??0};return s(v=>({...v,isExecuting:!1})),r?.(T),{success:!0,data:T}}catch(m){a.current=null;let f=m instanceof Error?m:new Error(String(m));s(T=>({...T,isExecuting:!1,error:f}));let n={command:g,stdout:"",stderr:f.message,exitCode:1};return r?.(n),{success:!1,error:f}}},[t,e,o,r]),h=sr(()=>{a.current&&(a.current.kill("SIGINT"),a.current=null,s(g=>({...g,isExecuting:!1,liveOutput:[...g.liveOutput,"[Interrupted]"]})))},[]);return{...i,execute:c,kill:h}}import{useInput as rs}from"ink";import{useCallback as ar,useReducer as lr,useRef as cr,useState as nt}from"react";function ur({mode:t,menuCallbacks:e,selectionCallbacks:o,textCallbacks:r,paletteCallbacks:i,configCallbacks:s,helpCallbacks:a,initialTextValue:c="",paletteQuery:h=""}){let[g,P]=lr($t,Ft(c)),[y,m]=lr($t,Ft("")),[f,n]=nt(0),[T,v]=nt(0),[I,d]=nt(0),[A,x]=nt(0),[Z,W]=nt(0),ue=cr(c);ue.current!==c&&(ue.current=c,P({type:"set",value:c}));let k=cr(t);k.current!==t&&(t==="menu"?n(0):t==="selection"?v(0):t==="palette"?d(0):t==="config"&&(x(0),W(0)),k.current=t);let we=ar(()=>{P({type:"clear"})},[]),ke=ar(D=>{P({type:"set",value:D})},[]);return rs((D,u)=>{if(t!=="disabled"){if(t==="text"&&r){if(u.ctrl&&!u.meta&&D==="d"){g.value.trim()===""&&process.exit(130);return}if(u.return){let S=g.value.trim();(S.toLowerCase()==="exit"||S.toLowerCase()==="quit")&&process.exit(0),S&&(r.onSubmit(S),P({type:"clear"}));return}if(D.toLowerCase()==="o"&&g.value.trim()===""&&r.onToggleOutput&&r.hasHistory){r.onToggleOutput();return}if(r.hasInlinePalette&&r.onNavigateInlinePalette){if(u.upArrow){r.onNavigateInlinePalette("up");return}if(u.downArrow){r.onNavigateInlinePalette("down");return}}if(u.leftArrow){P({type:"move-left"});return}if(u.rightArrow){P({type:"move-right"});return}if(u.backspace||u.delete){P({type:"delete"});let S=g.value.slice(0,g.cursorOffset-1)+g.value.slice(g.cursorOffset);r.onTextChange?.(S);return}if(u.escape){r.hasInlinePalette&&r.onCloseInlinePalette&&(r.onCloseInlinePalette(),P({type:"clear"}));return}if(u.ctrl||u.meta||u.tab)return;if(D&&D.length>0){P({type:"insert",text:D});let S=g.value.slice(0,g.cursorOffset)+D+g.value.slice(g.cursorOffset);r.onTextChange?.(S)}return}if(t==="menu"&&e){if(u.leftArrow){n(S=>(S-1+5)%5);return}if(u.rightArrow){n(S=>(S+1)%5);return}if(u.return){switch(["execute","copy","edit","alternatives","cancel"][f]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D>="1"&&D<="5"){let S=parseInt(D,10)-1;switch(["execute","copy","edit","alternatives","cancel"][S]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D==="?"){e.onExplain();return}if(D.toLowerCase()==="o"){e.onToggle();return}if(u.escape){e.onCancel();return}return}if(t==="selection"&&o){let S=o.count;if(u.upArrow){v(w=>(w-1+S)%S);return}if(u.downArrow){v(w=>(w+1)%S);return}if(u.return){o.onSelect(T);return}let q=parseInt(D,10);if(q>=1&&q<=S){o.onSelect(q-1);return}if(D==="5"||D.toLowerCase()==="c"||u.escape){o.onCancel();return}return}if(t==="palette"&&i){let S=i.filteredCount;if(u.upArrow){d(w=>S===0?0:(w-1+S)%S),i.onNavigate("up");return}if(u.downArrow){d(w=>S===0?0:(w+1)%S),i.onNavigate("down");return}if(u.return){i.onSelect();return}if(u.escape){i.onClose();return}if((u.backspace||u.delete)&&h===""){i.onClose();return}if(u.backspace||u.delete){let w=h.slice(0,-1);i.onQueryChange(w),d(0);return}if(u.ctrl||u.meta||u.tab)return;let q=parseInt(D,10);if(q>=1&&q<=9&&q<=S){d(q-1),i.onSelect();return}if(D&&D.length>0){let w=h+D;i.onQueryChange(w),d(0)}return}if(t==="config"&&s){let S=s.sectionCount,q=s.itemCount;if(s.isEditingCustomModel){if(u.escape){m({type:"clear"}),s.onCustomModelCancel?.();return}if(u.return){let w=y.value;w.trim()?s.onCustomModelSubmit?.(w.trim()):s.onCustomModelCancel?.(),m({type:"clear"});return}if(u.leftArrow){m({type:"move-left"});return}if(u.rightArrow){m({type:"move-right"});return}if(u.backspace||u.delete){m({type:"delete"});return}if(!u.ctrl&&!u.meta&&!u.tab&&D&&D.length>0){m({type:"insert",text:D});return}return}if(u.tab&&!u.shift){x(w=>(w+1)%S),W(0),s.onNavigateSection("next");return}if(u.tab&&u.shift){x(w=>(w-1+S)%S),W(0),s.onNavigateSection("prev");return}if(u.upArrow){W(w=>q===0?0:(w-1+q)%q),s.onNavigateItem("up");return}if(u.downArrow){W(w=>q===0?0:(w+1)%q),s.onNavigateItem("down");return}if(u.return||D===" "){s.onToggle();return}if(u.escape){s.onClose();return}return}if(t==="help"&&a){if(u.escape){a.onClose();return}return}}},{isActive:t!=="disabled"}),{textState:g,dispatchText:P,clearText:we,setText:ke,menuFocusIndex:f,selectionFocusIndex:T,paletteFocusIndex:I,configSectionIndex:A,configItemIndex:Z,customModelState:y,dispatchCustomModel:m}}import{useCallback as H,useReducer as ns}from"react";var ss={state:{status:"setup"},history:[],currentQuery:"",editingCommand:null,outputExpanded:!1,error:null};function is(t,e){switch(e.type){case"SETUP_COMPLETE":return{...t,state:{status:"input"},error:null};case"SUBMIT":return{...t,state:{status:"loading",query:e.query},currentQuery:e.query,editingCommand:null,error:null};case"AI_RESPONSE":return{...t,state:{status:"proposal",proposal:e.proposal},error:null};case"AI_ALTERNATIVES":return{...t,state:{status:"alternatives",proposals:e.proposals,originalQuery:t.currentQuery},error:null};case"AI_ERROR":return{...t,state:{status:"input"},error:e.error.message};case"EXECUTE":{let o=t.state;return o.status!=="proposal"?t:{...t,state:{status:"executing",command:o.proposal.command},error:null}}case"EXECUTE_EDITED":return{...t,state:{status:"executing",command:e.command},editingCommand:null,error:null};case"EXEC_DONE":{let o=[...t.history,{query:t.currentQuery,command:e.result.command,output:e.result.stdout||e.result.stderr,exitCode:e.result.exitCode}].slice(-Be.maxHistoryEntries);return{...t,state:{status:"input"},history:o,outputExpanded:!1,error:null}}case"COPY":return{...t,state:{status:"input"},error:null};case"EDIT":return{...t,state:{status:"input"},editingCommand:e.command,error:null};case"CANCEL":return{...t,state:{status:"input"},editingCommand:null,error:null};case"TOGGLE_OUTPUT":return t.history.length===0?t:{...t,outputExpanded:!t.outputExpanded};case"OPEN_PALETTE":return{...t,state:{status:"palette",query:"",filteredCommands:[]},error:null};case"UPDATE_PALETTE":return{...t,state:{status:"palette",query:e.query,filteredCommands:e.filteredCommands}};case"CLOSE_PALETTE":return{...t,state:{status:"input"},error:null};case"OPEN_CONFIG":return{...t,state:{status:"config",section:"provider"},error:null};case"UPDATE_CONFIG_SECTION":return{...t,state:{status:"config",section:e.section}};case"CLOSE_CONFIG":return{...t,state:{status:"input"},error:null};case"OPEN_HELP":return{...t,state:{status:"help"},error:null};case"CLOSE_HELP":return{...t,state:{status:"input"},error:null};case"CLEAR_HISTORY":return{...t,state:{status:"input"},history:[],outputExpanded:!1,error:null};default:return t}}function pr(){let[t,e]=ns(is,ss),o=H(k=>{e({type:"SUBMIT",query:k})},[]),r=H(k=>{e({type:"AI_RESPONSE",proposal:k})},[]),i=H(k=>{e({type:"AI_ALTERNATIVES",proposals:k})},[]),s=H(k=>{e({type:"AI_ERROR",error:k})},[]),a=H(()=>{e({type:"EXECUTE"})},[]),c=H(k=>{e({type:"EXECUTE_EDITED",command:k})},[]),h=H(k=>{e({type:"EXEC_DONE",result:k})},[]),g=H(()=>{e({type:"COPY"})},[]),P=H(k=>{e({type:"EDIT",command:k})},[]),y=H(()=>{e({type:"CANCEL"})},[]),m=H(()=>{e({type:"TOGGLE_OUTPUT"})},[]),f=H(()=>{e({type:"SETUP_COMPLETE"})},[]),n=H(()=>{e({type:"EDIT",command:""})},[]),T=H(()=>{e({type:"OPEN_PALETTE"})},[]),v=H((k,we)=>{e({type:"UPDATE_PALETTE",query:k,filteredCommands:we})},[]),I=H(()=>{e({type:"CLOSE_PALETTE"})},[]),d=H(()=>{e({type:"OPEN_CONFIG"})},[]),A=H(k=>{e({type:"UPDATE_CONFIG_SECTION",section:k})},[]),x=H(()=>{e({type:"CLOSE_CONFIG"})},[]),Z=H(()=>{e({type:"OPEN_HELP"})},[]),W=H(()=>{e({type:"CLOSE_HELP"})},[]),ue=H(()=>{e({type:"CLEAR_HISTORY"})},[]);return{store:t,dispatch:e,submitQuery:o,handleAIResponse:r,handleAIAlternatives:i,handleAIError:s,execute:a,executeEdited:c,markExecutionDone:h,copy:g,edit:P,cancel:y,toggleOutput:m,completeSetup:f,clearEditingCommand:n,openPalette:T,updatePalette:v,closePalette:I,openConfig:d,updateConfigSection:A,closeConfig:x,openHelp:Z,closeHelp:W,clearHistory:ue}}import as from"clipboardy";async function mr(t){try{return await as.write(t),{success:!0,data:{success:!0,message:"Copied to clipboard"}}}catch(e){return{success:!1,error:e instanceof Error?e:new Error("Failed to copy to clipboard")}}}import{Box as _,Static as ls,Text as B,useApp as cs}from"ink";import{useCallback as j,useEffect as eo,useMemo as Xe,useState as xe}from"react";import{Fragment as us,jsx as C,jsxs as U}from"react/jsx-runtime";function dr(){let{exit:t}=cs(),e=rr(),[o,r]=xe(null),[i,s]=xe(null),[a,c]=xe([]),[h,g]=xe(0),{isLoading:P,hasKey:y,error:m,refreshKeyStatus:f}=or(),{store:n,submitQuery:T,handleAIResponse:v,handleAIAlternatives:I,handleAIError:d,execute:A,executeEdited:x,markExecutionDone:Z,copy:W,edit:ue,cancel:k,toggleOutput:we,completeSetup:ke,openPalette:D,updatePalette:u,closePalette:S,openConfig:q,updateConfigSection:w,closeConfig:st,openHelp:fr,closeHelp:gr,clearHistory:xr}=pr(),[ve,it]=xe(0),[pe,at]=xe(()=>de().model),[lt,yr]=xe(()=>({contextEnabled:de().contextEnabled,showExplanations:!0,syntaxHighlighting:!0,simpleMode:!1})),[hr,to]=xe(!1),[Cr,oo]=xe(null),[Me,Oe]=xe(!1),[J,ro]=xe(()=>de().provider),Tr=Xe(()=>Eo(J),[y,J]),vr=Xe(()=>{let l=Le(J);return l?l.length<=12?"***":`${l.slice(0,7)}...${l.slice(-4)}`:null},[y,J]),no=Xe(()=>({provider:J,model:pe,contextEnabled:lt.contextEnabled,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3}),[J,pe,lt.contextEnabled]),re=tr({sessionStatus:n.state.status,config:no,updateConfig:()=>{},onOpenConfig:q,onOpenHelp:fr,onClearHistory:xr,onExit:()=>t()}),Sr=Xe(()=>{let l=[];return n.history.slice(0,-1).forEach((b,L)=>{l.push({id:`history-${L}`,type:"history",entry:b})}),l},[n.history]),Se=n.history.length>0?n.history[n.history.length-1]:null,{generate:so,getAlternatives:io,explain:ao,isLoading:_e}=Zo({shell:e,history:n.history,contextEnabled:lt.contextEnabled}),{execute:ct,kill:ys,isExecuting:wt,liveOutput:Er}=ir({shell:e,onComplete:Z}),Pr=Xe(()=>P||!y||n.state.status==="setup"||n.state.status==="loading"||n.state.status==="executing"||wt?"disabled":n.state.status==="palette"?"palette":n.state.status==="config"?"config":n.state.status==="help"?"help":n.state.status==="proposal"?_e?"disabled":"menu":n.state.status==="alternatives"?_e?"disabled":"selection":n.state.status==="input"?"text":"disabled",[P,y,n.state.status,wt,_e]),Ir=j((l,p)=>{ft(p,l).success&&(!y&&n.state.status==="setup"&&(he({provider:p,model:F[p].defaultModel}),ro(p),at(F[p].defaultModel)),f(),to(!1),oo(null),ke())},[y,n.state.status,f,ke]);eo(()=>{!P&&y&&n.state.status==="setup"&&ke()},[P,y,n.state.status,ke]),eo(()=>{let l=de().model;pe!==l&&he({model:pe})},[pe]);let br=j(l=>{if(l.startsWith("/")){let p=l.slice(1),b=ae.filter(p);c(b),g(0)}else c([]),g(0)},[]),Ar=j(async l=>{if(l.startsWith("/")){let b=l.slice(1).trim();if(a.length>0){let L=a[h];if(L&&re.executeCommand(L.name)){c([]),g(0);return}}if(b&&re.executeCommand(b)){c([]),g(0);return}c([]),g(0);return}if(c([]),g(0),n.editingCommand){x(l),await ct(l);return}T(l),s(null);let p=await so(l);p.success?v(p.data):d(p.error)},[n.editingCommand,T,so,v,d,x,ct,re,a,h]),Rr=j(async()=>{n.state.status==="proposal"&&(A(),await ct(n.state.proposal.command))},[n.state,A,ct]),wr=j(async()=>{if(n.state.status!=="proposal")return;(await mr(n.state.proposal.command)).success?(r("\u2713 Copied to clipboard"),setTimeout(()=>r(null),2e3)):(r("\u2717 Failed to copy"),setTimeout(()=>r(null),2e3)),W()},[n.state,W]),Or=j(()=>{n.state.status==="proposal"&&ue(n.state.proposal.command)},[n.state,ue]),Nr=j(async()=>{if(n.state.status!=="proposal")return;let l=await io(n.currentQuery,n.state.proposal.command);l.success?I(l.data):d(l.error)},[n.state,n.currentQuery,io,I,d]),Br=j(()=>{k(),s(null)},[k]),Dr=j(async()=>{if(n.state.status!=="proposal")return;let l=await ao(n.state.proposal.command);l.success&&s(l.data)},[n.state,ao]),kr=j(()=>{we()},[we]),Mr=j(l=>{if(n.state.status!=="alternatives")return;let p=n.state.proposals[l];p&&v(p)},[n.state,v]),_r=j(l=>{let p=ae.filter(l);re.setQuery(l),u(l,p)},[re,u]),Lr=j(()=>{re.executeSelected()&&(S(),re.reset())},[re,S]),Kr=j(l=>{l==="up"?re.focusUp():re.focusDown()},[re]),Ur=j(()=>{S(),re.reset()},[S,re]),Hr=j(l=>{let p=["provider","api-keys","toggles","about"];if(n.state.status!=="config")return;Me&&Oe(!1);let b=p.indexOf(n.state.section),L;l==="next"?L=(b+1)%p.length:L=(b-1+p.length)%p.length,w(p[L]),it(0)},[n.state,w,Me]),Fr=j(l=>{if(n.state.status!=="config")return;let p;n.state.section==="provider"?p=K.length+Ee[J].length+1:p={provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],p!==0&&it(b=>l==="up"?(b-1+p)%p:(b+1)%p)},[n.state,J]),$r=j(()=>{if(n.state.status==="config"){if(n.state.section==="toggles"){yr(l=>{let b=["contextEnabled","showExplanations","syntaxHighlighting","simpleMode"][ve];if(b){let L=!l[b];return b==="contextEnabled"&&he({contextEnabled:L}),{...l,[b]:L}}return l});return}if(n.state.section==="provider"){let l=K,p=Ee[J],b=K.length+p.length;if(ve<K.length){let L=l[ve];if(L&&L!==J){let ie=F[L].defaultModel;he({provider:L,model:ie}),ro(L),at(ie),Oe(!1),it(0),f()}}else if(ve===b)Oe(!0);else{let L=ve-K.length,ie=p[L];ie&&ie.id!==pe&&(he({model:ie.id}),at(ie.id),Oe(!1))}return}if(n.state.section==="api-keys"){let p=K[ve];p&&(st(),oo(p),to(!0));return}}},[n.state,ve,st,J,f,pe]),Gr=j(()=>{st(),it(0),Oe(!1)},[st]),Yr=n.state.status==="palette"?n.state.query:"",Vr=Xe(()=>n.state.status!=="config"?0:n.state.section==="provider"?K.length+Ee[J].length+1:{provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],[n.state,J]),{textState:jr,clearText:hs,setText:Cs,menuFocusIndex:qr,selectionFocusIndex:Xr,paletteFocusIndex:Qr,configSectionIndex:Ts,customModelState:Wr,dispatchCustomModel:lo}=ur({mode:Pr,initialTextValue:n.editingCommand??"",paletteQuery:Yr,menuCallbacks:{onExecute:Rr,onCopy:wr,onEdit:Or,onAlternatives:Nr,onCancel:Br,onExplain:Dr,onToggle:kr},selectionCallbacks:{onSelect:Mr,onCancel:k,count:n.state.status==="alternatives"?n.state.proposals.length:1},textCallbacks:{onSubmit:Ar,onToggleOutput:we,onTextChange:br,onNavigateInlinePalette:l=>{g(p=>{let b=a.length;return b===0?0:l==="up"?(p-1+b)%b:(p+1)%b})},onCloseInlinePalette:()=>{c([]),g(0)},hasInlinePalette:a.length>0,hasHistory:n.history.length>0},paletteCallbacks:{onQueryChange:_r,onSelect:Lr,onNavigate:Kr,onClose:Ur,filteredCount:n.state.status==="palette"?n.state.filteredCommands.length:0},configCallbacks:{onNavigateSection:Hr,onNavigateItem:Fr,onToggle:$r,onClose:Gr,sectionCount:4,itemCount:Vr,isEditingCustomModel:Me,onCustomModelSubmit:l=>{he({model:l}),at(l),Oe(!1)},onCustomModelCancel:()=>{Oe(!1)}},helpCallbacks:{onClose:gr}});return eo(()=>{if(Me){let l=!Ee[J].some(p=>p.id===pe);lo({type:"set",value:l?pe:""})}},[Me,J,pe,lo]),P?C(_,{flexDirection:"column",paddingY:1,children:C(B,{dimColor:!0,children:"Loading configuration..."})}):hr||!y&&n.state.status==="setup"?C(Io,{onComplete:Ir,error:m,provider:Cr??void 0}):U(_,{flexDirection:"column",children:[C(Fo,{shell:e,cwd:process.cwd(),provider:J,model:pe}),C(ls,{items:Sr,children:l=>U(_,{flexDirection:"column",marginBottom:1,children:[U(_,{children:[U(B,{color:"cyan",bold:!0,children:["\u276F"," "]}),C(B,{color:"cyan",children:l.entry.query})]}),U(_,{marginLeft:2,flexDirection:"column",children:[U(_,{children:[U(B,{dimColor:!0,children:["$ ",l.entry.command," "]}),C(B,{color:l.entry.exitCode===0?"green":"red",children:l.entry.exitCode===0?"\u2713":`\u2717 ${l.entry.exitCode}`})]}),l.entry.output&&U(_,{flexDirection:"column",children:[l.entry.output.split(`
50
+ `).filter(Boolean);for(let d of I){let A=`[ERR] ${d}`;f.push(A),o?.(d,!0),s(x=>({...x,liveOutput:[...x.liveOutput,A].slice(-e)}))}});let n=await m;a.current=null;let T={command:g,stdout:n.stdout??"",stderr:n.stderr??"",exitCode:n.exitCode??0};return s(v=>({...v,isExecuting:!1})),r?.(T),{success:!0,data:T}}catch(m){a.current=null;let f=m instanceof Error?m:new Error(String(m));s(T=>({...T,isExecuting:!1,error:f}));let n={command:g,stdout:"",stderr:f.message,exitCode:1};return r?.(n),{success:!1,error:f}}},[t,e,o,r]),h=sr(()=>{a.current&&(a.current.kill("SIGINT"),a.current=null,s(g=>({...g,isExecuting:!1,liveOutput:[...g.liveOutput,"[Interrupted]"]})))},[]);return{...i,execute:c,kill:h}}import{useInput as rs}from"ink";import{useCallback as ar,useReducer as lr,useRef as cr,useState as nt}from"react";function ur({mode:t,menuCallbacks:e,selectionCallbacks:o,textCallbacks:r,paletteCallbacks:i,configCallbacks:s,helpCallbacks:a,initialTextValue:c="",paletteQuery:h=""}){let[g,P]=lr($t,Ft(c)),[y,m]=lr($t,Ft("")),[f,n]=nt(0),[T,v]=nt(0),[I,d]=nt(0),[A,x]=nt(0),[Z,W]=nt(0),ue=cr(c);ue.current!==c&&(ue.current=c,P({type:"set",value:c}));let k=cr(t);k.current!==t&&(t==="menu"?n(0):t==="selection"?v(0):t==="palette"?d(0):t==="config"&&(x(0),W(0)),k.current=t);let Re=ar(()=>{P({type:"clear"})},[]),ke=ar(D=>{P({type:"set",value:D})},[]);return rs((D,u)=>{if(t!=="disabled"){if(t==="text"&&r){if(u.ctrl&&!u.meta&&D==="d"){g.value.trim()===""&&process.exit(130);return}if(u.return){let S=g.value.trim();(S.toLowerCase()==="exit"||S.toLowerCase()==="quit")&&process.exit(0),S&&(r.onSubmit(S),P({type:"clear"}));return}if(D.toLowerCase()==="o"&&g.value.trim()===""&&r.onToggleOutput&&r.hasHistory){r.onToggleOutput();return}if(r.hasInlinePalette&&r.onNavigateInlinePalette){if(u.upArrow){r.onNavigateInlinePalette("up");return}if(u.downArrow){r.onNavigateInlinePalette("down");return}}if(u.leftArrow){P({type:"move-left"});return}if(u.rightArrow){P({type:"move-right"});return}if(u.backspace||u.delete){P({type:"delete"});let S=g.value.slice(0,g.cursorOffset-1)+g.value.slice(g.cursorOffset);r.onTextChange?.(S);return}if(u.escape){r.hasInlinePalette&&r.onCloseInlinePalette&&(r.onCloseInlinePalette(),P({type:"clear"}));return}if(u.ctrl||u.meta||u.tab)return;if(D&&D.length>0){P({type:"insert",text:D});let S=g.value.slice(0,g.cursorOffset)+D+g.value.slice(g.cursorOffset);r.onTextChange?.(S)}return}if(t==="menu"&&e){if(u.leftArrow){n(S=>(S-1+5)%5);return}if(u.rightArrow){n(S=>(S+1)%5);return}if(u.return){switch(["execute","copy","edit","alternatives","cancel"][f]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D>="1"&&D<="5"){let S=parseInt(D,10)-1;switch(["execute","copy","edit","alternatives","cancel"][S]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D==="?"){e.onExplain();return}if(D.toLowerCase()==="o"){e.onToggle();return}if(u.escape){e.onCancel();return}return}if(t==="selection"&&o){let S=o.count;if(u.upArrow){v(R=>(R-1+S)%S);return}if(u.downArrow){v(R=>(R+1)%S);return}if(u.return){o.onSelect(T);return}let q=parseInt(D,10);if(q>=1&&q<=S){o.onSelect(q-1);return}if(D==="5"||D.toLowerCase()==="c"||u.escape){o.onCancel();return}return}if(t==="palette"&&i){let S=i.filteredCount;if(u.upArrow){d(R=>S===0?0:(R-1+S)%S),i.onNavigate("up");return}if(u.downArrow){d(R=>S===0?0:(R+1)%S),i.onNavigate("down");return}if(u.return){i.onSelect();return}if(u.escape){i.onClose();return}if((u.backspace||u.delete)&&h===""){i.onClose();return}if(u.backspace||u.delete){let R=h.slice(0,-1);i.onQueryChange(R),d(0);return}if(u.ctrl||u.meta||u.tab)return;let q=parseInt(D,10);if(q>=1&&q<=9&&q<=S){d(q-1),i.onSelect();return}if(D&&D.length>0){let R=h+D;i.onQueryChange(R),d(0)}return}if(t==="config"&&s){let S=s.sectionCount,q=s.itemCount;if(s.isEditingCustomModel){if(u.escape){m({type:"clear"}),s.onCustomModelCancel?.();return}if(u.return){let R=y.value;R.trim()?s.onCustomModelSubmit?.(R.trim()):s.onCustomModelCancel?.(),m({type:"clear"});return}if(u.leftArrow){m({type:"move-left"});return}if(u.rightArrow){m({type:"move-right"});return}if(u.backspace||u.delete){m({type:"delete"});return}if(!u.ctrl&&!u.meta&&!u.tab&&D&&D.length>0){m({type:"insert",text:D});return}return}if(u.tab&&!u.shift){x(R=>(R+1)%S),W(0),s.onNavigateSection("next");return}if(u.tab&&u.shift){x(R=>(R-1+S)%S),W(0),s.onNavigateSection("prev");return}if(u.upArrow){W(R=>q===0?0:(R-1+q)%q),s.onNavigateItem("up");return}if(u.downArrow){W(R=>q===0?0:(R+1)%q),s.onNavigateItem("down");return}if(u.return||D===" "){s.onToggle();return}if(u.escape){s.onClose();return}return}if(t==="help"&&a){if(u.escape){a.onClose();return}return}}},{isActive:t!=="disabled"}),{textState:g,dispatchText:P,clearText:Re,setText:ke,menuFocusIndex:f,selectionFocusIndex:T,paletteFocusIndex:I,configSectionIndex:A,configItemIndex:Z,customModelState:y,dispatchCustomModel:m}}import{useCallback as H,useReducer as ns}from"react";var ss={state:{status:"setup"},history:[],currentQuery:"",editingCommand:null,outputExpanded:!1,error:null};function is(t,e){switch(e.type){case"SETUP_COMPLETE":return{...t,state:{status:"input"},error:null};case"SUBMIT":return{...t,state:{status:"loading",query:e.query},currentQuery:e.query,editingCommand:null,error:null};case"AI_RESPONSE":return{...t,state:{status:"proposal",proposal:e.proposal},error:null};case"AI_ALTERNATIVES":return{...t,state:{status:"alternatives",proposals:e.proposals,originalQuery:t.currentQuery},error:null};case"AI_ERROR":return{...t,state:{status:"input"},error:e.error.message};case"EXECUTE":{let o=t.state;return o.status!=="proposal"?t:{...t,state:{status:"executing",command:o.proposal.command},error:null}}case"EXECUTE_EDITED":return{...t,state:{status:"executing",command:e.command},editingCommand:null,error:null};case"EXEC_DONE":{let o=[...t.history,{query:t.currentQuery,command:e.result.command,output:e.result.stdout||e.result.stderr,exitCode:e.result.exitCode}].slice(-Be.maxHistoryEntries);return{...t,state:{status:"input"},history:o,outputExpanded:!1,error:null}}case"COPY":return{...t,state:{status:"input"},error:null};case"EDIT":return{...t,state:{status:"input"},editingCommand:e.command,error:null};case"CANCEL":return{...t,state:{status:"input"},editingCommand:null,error:null};case"TOGGLE_OUTPUT":return t.history.length===0?t:{...t,outputExpanded:!t.outputExpanded};case"OPEN_PALETTE":return{...t,state:{status:"palette",query:"",filteredCommands:[]},error:null};case"UPDATE_PALETTE":return{...t,state:{status:"palette",query:e.query,filteredCommands:e.filteredCommands}};case"CLOSE_PALETTE":return{...t,state:{status:"input"},error:null};case"OPEN_CONFIG":return{...t,state:{status:"config",section:"provider"},error:null};case"UPDATE_CONFIG_SECTION":return{...t,state:{status:"config",section:e.section}};case"CLOSE_CONFIG":return{...t,state:{status:"input"},error:null};case"OPEN_HELP":return{...t,state:{status:"help"},error:null};case"CLOSE_HELP":return{...t,state:{status:"input"},error:null};case"CLEAR_HISTORY":return{...t,state:{status:"input"},history:[],outputExpanded:!1,error:null};default:return t}}function pr(){let[t,e]=ns(is,ss),o=H(k=>{e({type:"SUBMIT",query:k})},[]),r=H(k=>{e({type:"AI_RESPONSE",proposal:k})},[]),i=H(k=>{e({type:"AI_ALTERNATIVES",proposals:k})},[]),s=H(k=>{e({type:"AI_ERROR",error:k})},[]),a=H(()=>{e({type:"EXECUTE"})},[]),c=H(k=>{e({type:"EXECUTE_EDITED",command:k})},[]),h=H(k=>{e({type:"EXEC_DONE",result:k})},[]),g=H(()=>{e({type:"COPY"})},[]),P=H(k=>{e({type:"EDIT",command:k})},[]),y=H(()=>{e({type:"CANCEL"})},[]),m=H(()=>{e({type:"TOGGLE_OUTPUT"})},[]),f=H(()=>{e({type:"SETUP_COMPLETE"})},[]),n=H(()=>{e({type:"EDIT",command:""})},[]),T=H(()=>{e({type:"OPEN_PALETTE"})},[]),v=H((k,Re)=>{e({type:"UPDATE_PALETTE",query:k,filteredCommands:Re})},[]),I=H(()=>{e({type:"CLOSE_PALETTE"})},[]),d=H(()=>{e({type:"OPEN_CONFIG"})},[]),A=H(k=>{e({type:"UPDATE_CONFIG_SECTION",section:k})},[]),x=H(()=>{e({type:"CLOSE_CONFIG"})},[]),Z=H(()=>{e({type:"OPEN_HELP"})},[]),W=H(()=>{e({type:"CLOSE_HELP"})},[]),ue=H(()=>{e({type:"CLEAR_HISTORY"})},[]);return{store:t,dispatch:e,submitQuery:o,handleAIResponse:r,handleAIAlternatives:i,handleAIError:s,execute:a,executeEdited:c,markExecutionDone:h,copy:g,edit:P,cancel:y,toggleOutput:m,completeSetup:f,clearEditingCommand:n,openPalette:T,updatePalette:v,closePalette:I,openConfig:d,updateConfigSection:A,closeConfig:x,openHelp:Z,closeHelp:W,clearHistory:ue}}import as from"clipboardy";async function mr(t){try{return await as.write(t),{success:!0,data:{success:!0,message:"Copied to clipboard"}}}catch(e){return{success:!1,error:e instanceof Error?e:new Error("Failed to copy to clipboard")}}}import{Box as _,Static as ls,Text as B,useApp as cs}from"ink";import{useCallback as j,useEffect as eo,useMemo as Xe,useState as xe}from"react";import{Fragment as us,jsx as C,jsxs as U}from"react/jsx-runtime";function dr(){let{exit:t}=cs(),e=rr(),[o,r]=xe(null),[i,s]=xe(null),[a,c]=xe([]),[h,g]=xe(0),{isLoading:P,hasKey:y,error:m,refreshKeyStatus:f}=or(),{store:n,submitQuery:T,handleAIResponse:v,handleAIAlternatives:I,handleAIError:d,execute:A,executeEdited:x,markExecutionDone:Z,copy:W,edit:ue,cancel:k,toggleOutput:Re,completeSetup:ke,openPalette:D,updatePalette:u,closePalette:S,openConfig:q,updateConfigSection:R,closeConfig:st,openHelp:fr,closeHelp:gr,clearHistory:xr}=pr(),[ve,it]=xe(0),[pe,at]=xe(()=>de().model),[lt,yr]=xe(()=>({contextEnabled:de().contextEnabled,showExplanations:!0,syntaxHighlighting:!0,simpleMode:!1})),[hr,to]=xe(!1),[Cr,oo]=xe(null),[Me,Oe]=xe(!1),[J,ro]=xe(()=>de().provider),Tr=Xe(()=>Eo(J),[y,J]),vr=Xe(()=>{let l=Le(J);return l?l.length<=12?"***":`${l.slice(0,7)}...${l.slice(-4)}`:null},[y,J]),no=Xe(()=>({provider:J,model:pe,contextEnabled:lt.contextEnabled,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3}),[J,pe,lt.contextEnabled]),re=tr({sessionStatus:n.state.status,config:no,updateConfig:()=>{},onOpenConfig:q,onOpenHelp:fr,onClearHistory:xr,onExit:()=>t()}),Sr=Xe(()=>{let l=[];return l.push({id:"welcome",type:"welcome"}),n.history.slice(0,-1).forEach((b,L)=>{l.push({id:`history-${L}`,type:"history",entry:b})}),l},[n.history]),Se=n.history.length>0?n.history[n.history.length-1]:null,{generate:so,getAlternatives:io,explain:ao,isLoading:_e}=Zo({shell:e,history:n.history,contextEnabled:lt.contextEnabled}),{execute:ct,kill:ys,isExecuting:Rt,liveOutput:Er}=ir({shell:e,onComplete:Z}),Pr=Xe(()=>P||!y||n.state.status==="setup"||n.state.status==="loading"||n.state.status==="executing"||Rt?"disabled":n.state.status==="palette"?"palette":n.state.status==="config"?"config":n.state.status==="help"?"help":n.state.status==="proposal"?_e?"disabled":"menu":n.state.status==="alternatives"?_e?"disabled":"selection":n.state.status==="input"?"text":"disabled",[P,y,n.state.status,Rt,_e]),Ir=j((l,p)=>{ft(p,l).success&&(!y&&n.state.status==="setup"&&(he({provider:p,model:F[p].defaultModel}),ro(p),at(F[p].defaultModel)),f(),to(!1),oo(null),ke())},[y,n.state.status,f,ke]);eo(()=>{!P&&y&&n.state.status==="setup"&&ke()},[P,y,n.state.status,ke]),eo(()=>{let l=de().model;pe!==l&&he({model:pe})},[pe]);let br=j(l=>{if(l.startsWith("/")){let p=l.slice(1),b=ae.filter(p);c(b),g(0)}else c([]),g(0)},[]),Ar=j(async l=>{if(l.startsWith("/")){let b=l.slice(1).trim();if(a.length>0){let L=a[h];if(L&&re.executeCommand(L.name)){c([]),g(0);return}}if(b&&re.executeCommand(b)){c([]),g(0);return}c([]),g(0);return}if(c([]),g(0),n.editingCommand){x(l),await ct(l);return}T(l),s(null);let p=await so(l);p.success?v(p.data):d(p.error)},[n.editingCommand,T,so,v,d,x,ct,re,a,h]),wr=j(async()=>{n.state.status==="proposal"&&(A(),await ct(n.state.proposal.command))},[n.state,A,ct]),Rr=j(async()=>{if(n.state.status!=="proposal")return;(await mr(n.state.proposal.command)).success?(r("\u2713 Copied to clipboard"),setTimeout(()=>r(null),2e3)):(r("\u2717 Failed to copy"),setTimeout(()=>r(null),2e3)),W()},[n.state,W]),Or=j(()=>{n.state.status==="proposal"&&ue(n.state.proposal.command)},[n.state,ue]),Nr=j(async()=>{if(n.state.status!=="proposal")return;let l=await io(n.currentQuery,n.state.proposal.command);l.success?I(l.data):d(l.error)},[n.state,n.currentQuery,io,I,d]),Br=j(()=>{k(),s(null)},[k]),Dr=j(async()=>{if(n.state.status!=="proposal")return;let l=await ao(n.state.proposal.command);l.success&&s(l.data)},[n.state,ao]),kr=j(()=>{Re()},[Re]),Mr=j(l=>{if(n.state.status!=="alternatives")return;let p=n.state.proposals[l];p&&v(p)},[n.state,v]),_r=j(l=>{let p=ae.filter(l);re.setQuery(l),u(l,p)},[re,u]),Lr=j(()=>{re.executeSelected()&&(S(),re.reset())},[re,S]),Kr=j(l=>{l==="up"?re.focusUp():re.focusDown()},[re]),Ur=j(()=>{S(),re.reset()},[S,re]),Hr=j(l=>{let p=["provider","api-keys","toggles","about"];if(n.state.status!=="config")return;Me&&Oe(!1);let b=p.indexOf(n.state.section),L;l==="next"?L=(b+1)%p.length:L=(b-1+p.length)%p.length,R(p[L]),it(0)},[n.state,R,Me]),Fr=j(l=>{if(n.state.status!=="config")return;let p;n.state.section==="provider"?p=K.length+Ee[J].length+1:p={provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],p!==0&&it(b=>l==="up"?(b-1+p)%p:(b+1)%p)},[n.state,J]),$r=j(()=>{if(n.state.status==="config"){if(n.state.section==="toggles"){yr(l=>{let b=["contextEnabled","showExplanations","syntaxHighlighting","simpleMode"][ve];if(b){let L=!l[b];return b==="contextEnabled"&&he({contextEnabled:L}),{...l,[b]:L}}return l});return}if(n.state.section==="provider"){let l=K,p=Ee[J],b=K.length+p.length;if(ve<K.length){let L=l[ve];if(L&&L!==J){let ie=F[L].defaultModel;he({provider:L,model:ie}),ro(L),at(ie),Oe(!1),it(0),f()}}else if(ve===b)Oe(!0);else{let L=ve-K.length,ie=p[L];ie&&ie.id!==pe&&(he({model:ie.id}),at(ie.id),Oe(!1))}return}if(n.state.section==="api-keys"){let p=K[ve];p&&(st(),oo(p),to(!0));return}}},[n.state,ve,st,J,f,pe]),Gr=j(()=>{st(),it(0),Oe(!1)},[st]),Yr=n.state.status==="palette"?n.state.query:"",Vr=Xe(()=>n.state.status!=="config"?0:n.state.section==="provider"?K.length+Ee[J].length+1:{provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],[n.state,J]),{textState:jr,clearText:hs,setText:Cs,menuFocusIndex:qr,selectionFocusIndex:Xr,paletteFocusIndex:Qr,configSectionIndex:Ts,customModelState:Wr,dispatchCustomModel:lo}=ur({mode:Pr,initialTextValue:n.editingCommand??"",paletteQuery:Yr,menuCallbacks:{onExecute:wr,onCopy:Rr,onEdit:Or,onAlternatives:Nr,onCancel:Br,onExplain:Dr,onToggle:kr},selectionCallbacks:{onSelect:Mr,onCancel:k,count:n.state.status==="alternatives"?n.state.proposals.length:1},textCallbacks:{onSubmit:Ar,onToggleOutput:Re,onTextChange:br,onNavigateInlinePalette:l=>{g(p=>{let b=a.length;return b===0?0:l==="up"?(p-1+b)%b:(p+1)%b})},onCloseInlinePalette:()=>{c([]),g(0)},hasInlinePalette:a.length>0,hasHistory:n.history.length>0},paletteCallbacks:{onQueryChange:_r,onSelect:Lr,onNavigate:Kr,onClose:Ur,filteredCount:n.state.status==="palette"?n.state.filteredCommands.length:0},configCallbacks:{onNavigateSection:Hr,onNavigateItem:Fr,onToggle:$r,onClose:Gr,sectionCount:4,itemCount:Vr,isEditingCustomModel:Me,onCustomModelSubmit:l=>{he({model:l}),at(l),Oe(!1)},onCustomModelCancel:()=>{Oe(!1)}},helpCallbacks:{onClose:gr}});return eo(()=>{if(Me){let l=!Ee[J].some(p=>p.id===pe);lo({type:"set",value:l?pe:""})}},[Me,J,pe,lo]),P?C(_,{flexDirection:"column",paddingY:1,children:C(B,{dimColor:!0,children:"Loading configuration..."})}):hr||!y&&n.state.status==="setup"?C(Io,{onComplete:Ir,error:m,provider:Cr??void 0}):U(_,{flexDirection:"column",children:[C(ls,{items:Sr,children:l=>l.type==="welcome"?C(Fo,{shell:e,cwd:process.cwd(),provider:J,model:pe},l.id):U(_,{flexDirection:"column",marginBottom:1,children:[U(_,{children:[U(B,{color:"cyan",bold:!0,children:["\u276F"," "]}),C(B,{color:"cyan",children:l.entry.query})]}),U(_,{marginLeft:2,flexDirection:"column",children:[U(_,{children:[U(B,{dimColor:!0,children:["$ ",l.entry.command," "]}),C(B,{color:l.entry.exitCode===0?"green":"red",children:l.entry.exitCode===0?"\u2713":`\u2717 ${l.entry.exitCode}`})]}),l.entry.output&&U(_,{flexDirection:"column",children:[l.entry.output.split(`
51
51
  `).slice(0,10).map((p,b)=>C(B,{children:p},b)),l.entry.output.split(`
52
52
  `).length>10&&U(B,{dimColor:!0,children:["... (",l.entry.output.split(`
53
53
  `).length-10," more lines)"]})]})]}),C(_,{marginTop:1,children:C(B,{dimColor:!0,children:"\u2500".repeat(50)})})]},l.id)}),Se&&U(_,{flexDirection:"column",marginBottom:1,children:[U(_,{children:[U(B,{color:"cyan",bold:!0,children:["\u276F"," "]}),C(B,{color:"cyan",children:Se.query})]}),U(_,{marginLeft:2,flexDirection:"column",children:[U(_,{children:[U(B,{dimColor:!0,children:["$ ",Se.command," "]}),C(B,{color:Se.exitCode===0?"green":"red",children:Se.exitCode===0?"\u2713":`\u2717 ${Se.exitCode}`})]}),Se.output&&C(_,{flexDirection:"column",children:(()=>{let l=Se.output.split(`
54
- `).filter(ie=>ie.length>0),p=n.outputExpanded?500:10,b=l.slice(0,p),L=l.length-b.length;return U(us,{children:[b.map((ie,Jr)=>C(B,{children:ie},Jr)),L>0&&U(_,{children:[U(B,{dimColor:!0,children:["... (",L," more lines, press "]}),C(B,{color:"blue",children:"[O]"}),C(B,{dimColor:!0,children:" to expand)"})]})]})})()})]}),C(_,{marginTop:1,children:C(B,{dimColor:!0,children:"\u2500".repeat(50)})})]}),n.error&&C(_,{marginY:1,children:U(B,{color:"red",children:["Error: ",n.error]})}),o&&C(_,{marginY:1,children:C(B,{color:"green",children:o})}),n.state.status==="loading"&&C(Xt,{query:n.state.query}),n.state.status==="proposal"&&U(_,{flexDirection:"column",marginY:1,children:[C(No,{proposal:n.state.proposal,showExplanation:!!i}),i&&C(_,{marginTop:1,paddingX:1,children:C(B,{dimColor:!0,children:i})})]}),n.state.status==="proposal"&&_e&&C(Xt,{label:"Generating alternatives..."}),C(Ko,{focusedIndex:qr,visible:n.state.status==="proposal"&&!_e}),n.state.status==="alternatives"&&C(_,{flexDirection:"column",marginY:1,children:C(Bo,{proposals:n.state.proposals})}),C(Uo,{count:n.state.status==="alternatives"?n.state.proposals.length:0,focusedIndex:Xr,visible:n.state.status==="alternatives"&&!_e}),(n.state.status==="executing"||wt)&&C(Ao,{lines:Er,command:n.state.status==="executing"?n.state.command:""}),C(Ut,{query:n.state.status==="palette"?n.state.query:"",filteredCommands:n.state.status==="palette"?n.state.filteredCommands:[],selectedIndex:Qr,visible:n.state.status==="palette"}),C(Yt,{visible:n.state.status==="config",activeSection:n.state.status==="config"?n.state.section:"provider",sectionItemIndex:ve,config:no,hasApiKey:y,storageInfo:Tr,maskedKey:vr,toggles:lt,isEditingCustomModel:Me,customModelState:Wr}),C(Vt,{visible:n.state.status==="help"}),C(Lo,{textState:jr,placeholder:"Describe what you want to do... (type / for commands)",hasHistory:n.history.length>0,visible:n.state.status==="input"}),n.state.status==="input"&&a.length>0&&U(_,{flexDirection:"column",marginLeft:2,marginTop:0,children:[C(_,{marginBottom:0,children:C(B,{dimColor:!0,children:"\u2500".repeat(50)})}),a.slice(0,5).map((l,p)=>U(_,{children:[C(B,{color:p===h?"cyan":"gray",bold:p===h,children:p===h?"> ":" "}),U(B,{color:p===h?"cyan":"blue",bold:p===h,children:["/",l.name]}),C(B,{children:" "}),C(B,{dimColor:p!==h,children:l.description})]},l.name)),C(_,{marginTop:0,children:C(B,{dimColor:!0,children:"[Enter] Select [Up/Down] Navigate [Esc] Cancel"})})]})]})}import{render as ps}from"ink";import{jsx as xs}from"react/jsx-runtime";var ms="\x1Bc",ds="\x1B]0;CLI AI\x07";function fs(){console.log(`
54
+ `).filter(ie=>ie.length>0),p=n.outputExpanded?500:10,b=l.slice(0,p),L=l.length-b.length;return U(us,{children:[b.map((ie,Jr)=>C(B,{children:ie},Jr)),L>0&&U(_,{children:[U(B,{dimColor:!0,children:["... (",L," more lines, press "]}),C(B,{color:"blue",children:"[O]"}),C(B,{dimColor:!0,children:" to expand)"})]})]})})()})]}),C(_,{marginTop:1,children:C(B,{dimColor:!0,children:"\u2500".repeat(50)})})]}),n.error&&C(_,{marginY:1,children:U(B,{color:"red",children:["Error: ",n.error]})}),o&&C(_,{marginY:1,children:C(B,{color:"green",children:o})}),n.state.status==="loading"&&C(Xt,{query:n.state.query}),n.state.status==="proposal"&&U(_,{flexDirection:"column",marginY:1,children:[C(No,{proposal:n.state.proposal,showExplanation:!!i}),i&&C(_,{marginTop:1,paddingX:1,children:C(B,{dimColor:!0,children:i})})]}),n.state.status==="proposal"&&_e&&C(Xt,{label:"Generating alternatives..."}),C(Ko,{focusedIndex:qr,visible:n.state.status==="proposal"&&!_e}),n.state.status==="alternatives"&&C(_,{flexDirection:"column",marginY:1,children:C(Bo,{proposals:n.state.proposals})}),C(Uo,{count:n.state.status==="alternatives"?n.state.proposals.length:0,focusedIndex:Xr,visible:n.state.status==="alternatives"&&!_e}),(n.state.status==="executing"||Rt)&&C(Ao,{lines:Er,command:n.state.status==="executing"?n.state.command:""}),C(Ut,{query:n.state.status==="palette"?n.state.query:"",filteredCommands:n.state.status==="palette"?n.state.filteredCommands:[],selectedIndex:Qr,visible:n.state.status==="palette"}),C(Yt,{visible:n.state.status==="config",activeSection:n.state.status==="config"?n.state.section:"provider",sectionItemIndex:ve,config:no,hasApiKey:y,storageInfo:Tr,maskedKey:vr,toggles:lt,isEditingCustomModel:Me,customModelState:Wr}),C(Vt,{visible:n.state.status==="help"}),C(Lo,{textState:jr,placeholder:"Describe what you want to do... (type / for commands)",hasHistory:n.history.length>0,visible:n.state.status==="input"}),n.state.status==="input"&&a.length>0&&U(_,{flexDirection:"column",marginLeft:2,marginTop:0,children:[C(_,{marginBottom:0,children:C(B,{dimColor:!0,children:"\u2500".repeat(50)})}),a.slice(0,5).map((l,p)=>U(_,{children:[C(B,{color:p===h?"cyan":"gray",bold:p===h,children:p===h?"> ":" "}),U(B,{color:p===h?"cyan":"blue",bold:p===h,children:["/",l.name]}),C(B,{children:" "}),C(B,{dimColor:p!==h,children:l.description})]},l.name)),C(_,{marginTop:0,children:C(B,{dimColor:!0,children:"[Enter] Select [Up/Down] Navigate [Esc] Cancel"})})]})]})}import{render as ps}from"ink";import{jsx as xs}from"react/jsx-runtime";var ms="\x1Bc",ds="\x1B]0;CLI AI\x07";function fs(){console.log(`
55
55
  CLI AI v${me} - Natural language to shell commands
56
56
 
57
57
  Usage:
@@ -75,4 +75,4 @@ Session Controls:
75
75
  Escape Cancel current action
76
76
  exit, quit Exit the session
77
77
  Ctrl+D Exit (empty input)
78
- `)}async function gs(){let t=process.argv.slice(2);(t.includes("--help")||t.includes("-h"))&&(fs(),process.exit(0)),(t.includes("--version")||t.includes("-v"))&&(console.log(`CLI AI v${me}`),process.exit(0)),process.stdout.write(ms+ds);let{waitUntilExit:e}=ps(xs(dr,{}));process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{process.exit(0)}),await e()}gs().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
78
+ `)}async function gs(){let t=process.argv.slice(2);(t.includes("--help")||t.includes("-h"))&&(fs(),process.exit(0)),(t.includes("--version")||t.includes("-v"))&&(console.log(`CLI AI v${me}`),process.exit(0)),process.stdout.write(ms+ds);let{waitUntilExit:e}=ps(xs(dr,{}),{incrementalRendering:!0});process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{process.exit(0)}),await e()}gs().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fmdzc/cli-ai",
3
- "version": "3.1.0",
3
+ "version": "3.1.1",
4
4
  "description": "CLI AI Assistant v3 - Natural language to shell commands with persistent REPL session",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/scripts/tag.js CHANGED
@@ -28,15 +28,39 @@ function getPackageTag() {
28
28
  return `v${pkg.version}`;
29
29
  }
30
30
 
31
- function createTag(tag) {
31
+ function tagExists(tag) {
32
+ const result = git(`tag -l ${tag}`, { silent: true });
33
+ return result && result.trim() === tag;
34
+ }
35
+
36
+ function remoteTagExists(tag) {
37
+ const result = git(`ls-remote --tags origin refs/tags/${tag}`, { silent: true, ignoreError: true });
38
+ return result && result.includes(tag);
39
+ }
40
+
41
+ function createTag(tag, autoRepush = false) {
32
42
  const version = tag.slice(1);
33
- console.log(`Creating tag ${tag}...`);
34
43
 
44
+ // Check if tag already exists
45
+ const localExists = tagExists(tag);
46
+ const remoteExists = remoteTagExists(tag);
47
+
48
+ if (localExists || remoteExists) {
49
+ if (autoRepush) {
50
+ console.log(`Tag ${tag} already exists, re-pushing...`);
51
+ return repushTag(tag);
52
+ }
53
+ console.error(`\n✗ Tag ${tag} already exists${localExists ? ' locally' : ''}${remoteExists ? (localExists ? ' and' : '') + ' on remote' : ''}`);
54
+ console.error(`\nTo overwrite, run: pnpm tag --force ${tag}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ console.log(`Creating tag ${tag}...`);
35
59
  git(`tag -a ${tag} -m "Release ${version}"`);
36
60
  console.log(`✓ Tag ${tag} created locally`);
37
61
 
38
62
  console.log(`Pushing tag ${tag} to origin...`);
39
- git(`push origin ${tag}`);
63
+ git(`push origin refs/tags/${tag}`);
40
64
  console.log(`✓ Tag ${tag} pushed to origin`);
41
65
 
42
66
  return tag;
@@ -50,7 +74,7 @@ function repushTag(tag) {
50
74
  console.log(`✓ Local tag deleted (or didn't exist)`);
51
75
 
52
76
  console.log(`Deleting remote tag ${tag}...`);
53
- git(`push origin --delete ${tag}`, { ignoreError: true, silent: true });
77
+ git(`push origin --delete refs/tags/${tag}`, { ignoreError: true, silent: true });
54
78
  console.log(`✓ Remote tag deleted (or didn't exist)`);
55
79
 
56
80
  return createTag(tag);