@fmdzc/cli-ai 3.1.0 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/index.js +20 -23
- package/package.json +1 -1
- package/scripts/tag.js +28 -4
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
|
|
9
|
+
Describe what you want in plain English. Get the right command. Review, execute or copy.
|
|
10
10
|
|
|
11
|
-
Supports **Anthropic**, **OpenAI
|
|
11
|
+
Supports **Anthropic**, **OpenAI** and **OpenRouter** providers.
|
|
12
12
|
|
|
13
13
|

|
|
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
|
|
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
|
|
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,8 +1,8 @@
|
|
|
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(`
|
|
2
|
-
`)}function
|
|
3
|
-
${
|
|
4
|
-
`)}catch{}function
|
|
5
|
-
`)}catch{}}function
|
|
1
|
+
var tn=(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 ct={id:"__custom__",name:"Custom model...",description:"Enter any model ID"},Se={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"}]},on=Se.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 rn(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 mo(){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:rn(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 ie=mo();var Nt={name:"clear",description:"Clear conversation history",category:"session",aliases:["cls"],execute:()=>({type:"navigate",to:"clear"}),isAvailable:t=>t==="input"||t==="palette"};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"||t==="palette"};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};ie.register(Bt);ie.register(kt);ie.register(Nt);ie.register(Dt);var pe="3.1.2",Oe="CLI AI",fo="cli-ai";var go=".cli_ai_assistant",M=["anthropic","openrouter","openai"],xo="anthropic",K={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"}},nn=K[xo].defaultModel,Ne={provider:xo,model:nn,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3,contextEnabled:!0},yo=500,ho=10,Co=["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"],To=["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 "],vo=["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"],ae=500,J={maxAttempts:3,baseDelayMs:1e3,maxDelayMs:5e3};import pt from"conf";import{createHash as sn}from"crypto";import{existsSync as Po,unlinkSync as So}from"fs";import{hostname as an,userInfo as ln}from"os";import{homedir as cn}from"os";import{join as Io}from"path";var un="cli-ai-v3-encryption-key";function pn(){let t=`${an()}-${ln().username}-cli-ai-v3-salt`;return sn("sha256").update(t).digest("hex").slice(0,32)}var Qe=Io(cn(),go),mt=Io(Qe,"config.json");function mn(){if(!Po(mt))return null;try{let t=new pt({projectName:"cli-ai",cwd:Qe,encryptionKey:un}),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 dn(){let t=pn(),e=mn();if(e){try{So(mt)}catch{}let o=new pt({projectName:"cli-ai",cwd:Qe,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 pt({projectName:"cli-ai",cwd:Qe,encryptionKey:t});return fn(o),o}catch{try{Po(mt)&&So(mt)}catch{}return new pt({projectName:"cli-ai",cwd:Qe,encryptionKey:t})}}function fn(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=dn(),ut=null,Eo=!1,Mt=new Map,Xe=null;function gn(){if(Eo)return ut;Eo=!0;try{return ut=tn("@napi-rs/keyring"),ut}catch{return ut=null,null}}function _t(t){if(Xe===!1)return null;let e=Mt.get(t);if(e!==void 0)return e;let o=gn();if(!o)return Xe=!1,null;try{let r=K[t].keyringAccount,i=new o.Entry(fo,r);return i.getPassword(),Xe=!0,Mt.set(t,i),i}catch{return Mt.set(t,null),Xe===null&&(Xe=!1),null}}function _e(t){let e=K[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 dt(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 Le(t){let e=_e(t);return e!==null&&e.length>0}function me(){let t=ye.get("config")??{};return{...Ne,...t}}function he(t){let e=ye.get("config")??{};ye.set("config",{...e,...t})}function ft(t,e){let o=K[t];return t==="openai"?e.startsWith("sk-")&&e.length>20:e.startsWith(o.keyPrefix)&&e.length>20}function bo(t){let e=K[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 F,Text as X,useInput as Ao}from"ink";import{useState as We}from"react";import{TextInput as xn}from"@inkjs/ui";import{jsx as O,jsxs as le}from"react/jsx-runtime";var yn={anthropic:"https://console.anthropic.com/settings/keys",openai:"https://platform.openai.com/api-keys",openrouter:"https://openrouter.ai/keys"};function Ro({onComplete:t,onError:e,error:o,provider:r}){let[i,s]=We(r?"input":"welcome"),[a,c]=We(r??"anthropic"),[h,g]=We(0),[P,y]=We(""),[m,f]=We(null);Ao((I,d)=>{i==="welcome"&&(d.return||I===" ")&&s("provider")},{isActive:i==="welcome"}),Ao((I,d)=>{if(i==="provider"){if(d.upArrow){g(x=>(x-1+M.length)%M.length);return}if(d.downArrow){g(x=>(x+1)%M.length);return}if(d.return){let x=M[h];x&&(c(x),s("input"));return}let b=parseInt(I,10);if(b>=1&&b<=M.length){let x=M[b-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(!ft(a,d)){let b=K[a];f(`Invalid key format. ${b.name} API keys start with "${b.keyPrefix}"`);return}f(null),s("saving"),t(d,a)};if(i==="welcome")return le(F,{flexDirection:"column",paddingY:1,children:[O(F,{marginBottom:1,children:le(X,{bold:!0,color:"cyan",children:[Oe," v",pe]})}),O(F,{marginBottom:1,children:O(X,{children:"Welcome! This tool translates natural language into shell commands."})}),O(F,{marginBottom:1,children:O(X,{dimColor:!0,children:"To get started, you'll need an API key from one of the supported providers."})}),O(F,{children:O(X,{color:"green",children:"Press Enter to continue..."})})]});if(i==="provider")return le(F,{flexDirection:"column",paddingY:1,children:[O(F,{marginBottom:1,children:O(X,{bold:!0,children:"Select your AI provider:"})}),M.map((I,d)=>{let b=K[I],x=d===h;return le(F,{children:[O(X,{color:x?"cyan":"gray",bold:x,children:x?"> ":" "}),le(X,{color:x?"cyan":"white",children:[d+1,". ",b.name]})]},I)}),O(F,{marginTop:1,children:O(X,{dimColor:!0,children:"[Up/Down] Navigate [Enter] Select [1-3] Quick select"})})]});let C=o??m,v=K[a];return i==="input"?le(F,{flexDirection:"column",paddingY:1,children:[O(F,{marginBottom:1,children:le(X,{bold:!0,children:["Enter your ",v.name," API key:"]})}),O(F,{marginBottom:1,children:le(X,{dimColor:!0,children:["Get one at: ",O(X,{color:"blue",children:yn[a]})]})}),C&&O(F,{marginBottom:1,children:le(X,{color:"red",children:["\u26A0 ",C]})}),le(F,{children:[O(X,{dimColor:!0,children:"> "}),O(xn,{placeholder:`${v.keyPrefix}...`,onChange:y,onSubmit:n})]}),O(F,{marginTop:1,children:O(X,{color:"yellow",children:"\u{1F512} Your key is stored securely on this machine using your system's credential manager."})})]}):i==="saving"?O(F,{flexDirection:"column",paddingY:1,children:O(F,{children:O(X,{color:"yellow",children:"\u23F3 Saving API key..."})})}):le(F,{flexDirection:"column",paddingY:1,children:[O(F,{children:O(X,{color:"green",children:"\u2713 API key saved successfully!"})}),O(F,{marginTop:1,children:le(X,{children:["Starting ",Oe,"..."]})})]})}import{Box as gt,Text as Lt}from"ink";import{jsx as Je,jsxs as wo}from"react/jsx-runtime";function Oo({lines:t,command:e}){return wo(gt,{flexDirection:"column",marginY:1,children:[Je(gt,{marginBottom:1,children:wo(Lt,{dimColor:!0,children:["$ ",e]})}),Je(gt,{flexDirection:"column",children:t.map((o,r)=>{let i=o.startsWith("[ERR]");return Je(Lt,{color:i?"red":void 0,children:i?o.slice(6):o},r)})}),Je(gt,{marginTop:1,children:Je(Lt,{color:"yellow",children:"\u23F3 Running..."})})]})}import{Box as Ue,Text as Fe}from"ink";import{Box as hn,Text as Ee}from"ink";import{Fragment as Cn,jsx as Ke,jsxs as xt}from"react/jsx-runtime";function Kt({command:t,index:e,isSelected:o}){return xt(hn,{children:[Ke(Ee,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),xt(Ee,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),Ke(Ee,{children:" "}),xt(Ee,{color:o?"white":"gray",bold:o,children:["/",t.name]}),Ke(Ee,{children:" "}),Ke(Ee,{dimColor:!o,children:t.description}),t.shortcut?xt(Cn,{children:[Ke(Ee,{children:" "}),Ke(Ee,{dimColor:!0,color:"yellow",children:t.shortcut})]}):null]})}import{jsx as de,jsxs as No}from"react/jsx-runtime";function Ut({query:t,filteredCommands:e,selectedIndex:o,visible:r}){return r?No(Ue,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginTop:1,children:[No(Ue,{children:[de(Fe,{color:"blue",bold:!0,children:"/"}),de(Fe,{color:"white",children:t}),de(Fe,{color:"cyan",children:"_"})]}),de(Ue,{marginY:0,children:de(Fe,{dimColor:!0,children:"\u2500".repeat(50)})}),e.length>0?de(Ue,{flexDirection:"column",children:e.slice(0,9).map((i,s)=>de(Kt,{command:i,index:s,isSelected:s===o},i.name))}):de(Ue,{children:de(Fe,{dimColor:!0,children:"No matching commands"})}),de(Ue,{marginTop:1,children:de(Fe,{dimColor:!0,children:"[Enter] Select [1-9] Quick select [Esc] Close"})})]}):null}import{Box as Pe,Text as Be}from"ink";import xi from"chalk";function Tn(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(vo.includes(r.toLowerCase())){e.push({type:"keyword",value:r});continue}e.push({type:"default",value:r})}return e}function Bo(t){return Tn(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 Do({command:t}){let e=Bo(t);return ne(Be,{children:e.map((o,r)=>ne(Be,{color:o.color,bold:o.bold,children:o.text},r))})}function ko({proposal:t,showExplanation:e=!1}){return ze(Pe,{flexDirection:"column",children:[ne(Pe,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,children:ne(Do,{command:t.command})}),e&&t.explanation&&ne(Pe,{marginTop:1,paddingX:1,children:ne(Be,{dimColor:!0,children:t.explanation})})]})}function vn({command:t,index:e,selected:o=!1}){return ze(Pe,{children:[ze(Be,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),ne(Be,{children:" "}),ne(Do,{command:t})]})}function Mo({proposals:t,selectedIndex:e=-1}){return ze(Pe,{flexDirection:"column",marginY:1,children:[ne(Pe,{marginBottom:1,children:ne(Be,{bold:!0,children:"Alternative commands:"})}),t.map((o,r)=>ne(Pe,{marginBottom:1,children:ne(vn,{command:o.command,index:r,selected:r===e})},r)),ne(Pe,{marginTop:1,children:ze(Be,{dimColor:!0,children:["Press 1-",t.length," to select, or [5] Cancel"]})})]})}import{Box as Pi,Text as Ii}from"ink";import{Fragment as Ri,jsx as Ai,jsxs as wi}from"react/jsx-runtime";import{Text as Sn}from"ink";import Ze from"chalk";import{useMemo as _o}from"react";import{jsx as Pn}from"react/jsx-runtime";var Ft=Ze.inverse(" ");function yt({value:t,cursorOffset:e,placeholder:o="",isDisabled:r=!1}){let i=_o(()=>r?o?Ze.dim(o):"":o&&o.length>0?Ze.inverse(o[0])+Ze.dim(o.slice(1)):Ft,[r,o]),s=_o(()=>{if(r)return t;let a=0,c=t.length>0?"":Ft;for(let h of t)c+=a===e?Ze.inverse(h):h,a++;return t.length>0&&e===t.length&&(c+=Ft),c},[r,t,e]);return Pn(Sn,{children:t.length>0?s:i})}var En={value:"",cursorOffset:0};function Ht(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 En;case"set":return{value:e.value,cursorOffset:e.value.length};default:return t}}import{Box as ht,Text as Gt}from"ink";import{jsx as et,jsxs as Lo}from"react/jsx-runtime";function He({title:t,isActive:e,children:o}){return Lo(ht,{flexDirection:"column",marginBottom:1,children:[Lo(ht,{children:[et(Gt,{color:e?"cyan":"white",bold:!0,children:t}),e?et(Gt,{color:"cyan",children:" *"}):null]}),et(ht,{children:et(Gt,{dimColor:!0,children:"\u2500".repeat(50)})}),et(ht,{flexDirection:"column",paddingLeft:0,children:o})]})}import{Box as In,Text as Ct}from"ink";import{jsx as Tt,jsxs as bn}from"react/jsx-runtime";function $e({label:t,value:e,isSelected:o}){return bn(In,{children:[Tt(Ct,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),Tt(Ct,{color:e?"green":"gray",children:e?"[x]":"[ ]"}),Tt(Ct,{children:" "}),Tt(Ct,{color:o?"white":"gray",children:t})]})}import{Box as $,Text as A}from"ink";import{Fragment as Uo,jsx as E,jsxs as k}from"react/jsx-runtime";var Ko=["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=Ko.indexOf(e),y=Se[r.provider],m=!y.some(n=>n.id===r.model),f=M.length+y.length;return k($,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[k($,{justifyContent:"space-between",marginBottom:1,children:[E($,{children:E(A,{color:"cyan",bold:!0,children:"Settings"})}),E($,{children:E(A,{dimColor:!0,children:"[Esc] Close [Tab] Section [Enter] Select"})})]}),E(He,{title:"Provider & Model",isActive:e==="provider",children:k($,{flexDirection:"column",children:[E($,{marginBottom:1,children:E(A,{dimColor:!0,children:"Provider"})}),M.map((n,C)=>{let v=K[n],I=r.provider===n,d=Le(n),b=e==="provider"&&o===C;return k($,{children:[E(A,{color:b?"cyan":"gray",bold:b,children:b?"> ":" "}),k(A,{color:b?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",v.name]}),E(A,{children:" "}),E(A,{color:d?"green":"red",dimColor:!b,children:d?"\u2713 Key":"\u2717 No key"})]},n)}),E($,{marginTop:1,marginBottom:1,children:E(A,{dimColor:!0,children:"Model"})}),y.map((n,C)=>{let v=C+M.length,I=r.model===n.id,d=e==="provider"&&o===v;return k($,{children:[E(A,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),k(A,{color:d?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",n.name]}),k(A,{dimColor:!d,children:[" ",n.description]})]},n.id)}),k($,{children:[E(A,{color:e==="provider"&&o===f?"cyan":"gray",bold:e==="provider"&&o===f,children:e==="provider"&&o===f?"> ":" "}),h&&g?k(Uo,{children:[E(A,{color:"cyan",children:"\u25CB "}),E(yt,{value:g.value,cursorOffset:g.cursorOffset,placeholder:"model-id"}),E(A,{dimColor:!0,children:" (Enter to save, Esc to cancel)"})]}):k(Uo,{children:[k(A,{color:e==="provider"&&o===f?"cyan":m?"green":"white",children:[m?"\u25CF":"\u25CB"," ",ct.name]}),k(A,{dimColor:!(e==="provider"&&o===f),children:[" ",m?`(${r.model})`:ct.description]})]})]},ct.id)]})}),E(He,{title:"API Keys",isActive:e==="api-keys",children:E($,{flexDirection:"column",children:M.map((n,C)=>{let v=K[n],I=Le(n),d=e==="api-keys"&&o===C;return k($,{children:[E(A,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),k(A,{color:d?"cyan":"white",children:[v.name,": "]}),E(A,{color:I?"green":"red",children:I?"\u2713 Configured":"\u2717 Not set"}),k(A,{dimColor:!d,children:[" [Enter to ",I?"change":"add","]"]})]},n)})})}),k(He,{title:"Options",isActive:e==="toggles",children:[E($e,{label:"Context (pass history to AI)",value:c.contextEnabled,isSelected:e==="toggles"&&o===0}),E($e,{label:"Show explanations",value:c.showExplanations,isSelected:e==="toggles"&&o===1}),E($e,{label:"Syntax highlighting",value:c.syntaxHighlighting,isSelected:e==="toggles"&&o===2}),E($e,{label:"Simple mode",value:c.simpleMode,isSelected:e==="toggles"&&o===3})]}),E(He,{title:"About",isActive:e==="about",children:k($,{flexDirection:"column",children:[k($,{children:[E(A,{dimColor:!0,children:"Version: "}),k(A,{children:["CLI AI v",pe]})]}),k($,{children:[E(A,{dimColor:!0,children:"Provider: "}),E(A,{color:"magenta",children:K[r.provider].name})]}),k($,{children:[E(A,{dimColor:!0,children:"Model: "}),E(A,{color:"magenta",children:r.model})]}),k($,{children:[E(A,{dimColor:!0,children:"Storage: "}),E(A,{color:s.secure?"green":"yellow",children:s.description})]})]})}),E($,{marginTop:1,justifyContent:"center",children:Ko.map((n,C)=>E($,{marginX:1,children:k(A,{color:C===P?"cyan":"gray",children:[C===P?"[":" ",C+1,C===P?"]":" "]})},n))})]})}import{Box as zi,Text as Zi}from"ink";import{Fragment as oa,jsx as ta,jsxs as ra}from"react/jsx-runtime";import{Box as H,Text as ee}from"ink";import{jsx as N,jsxs as se}from"react/jsx-runtime";var An=[{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)"}],Rn=[{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"}],wn=[{key:"Up/Down",description:"Navigate commands"},{key:"Enter",description:"Select command"},{key:"Esc",description:"Close palette"},{key:"1-9",description:"Quick select"}],On=[{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 vt({title:t,shortcuts:e}){return se(H,{flexDirection:"column",marginBottom:1,children:[N(ee,{color:"yellow",bold:!0,children:t}),e.map(o=>se(H,{children:[N(H,{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(H,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[se(H,{justifyContent:"space-between",marginBottom:1,children:[N(H,{children:se(ee,{color:"cyan",bold:!0,children:["Help - ",Oe," v",pe]})}),N(H,{children:N(ee,{dimColor:!0,children:"[Esc] Close"})})]}),N(H,{marginBottom:1,children:N(ee,{children:"Natural language to shell command translator. Describe what you want in plain English and get executable commands."})}),se(H,{children:[se(H,{flexDirection:"column",marginRight:4,children:[N(vt,{title:"Input Mode",shortcuts:An}),N(vt,{title:"Command Palette",shortcuts:wn})]}),se(H,{flexDirection:"column",children:[N(vt,{title:"Proposal Mode",shortcuts:Rn}),N(vt,{title:"Config Panel",shortcuts:On})]})]}),se(H,{flexDirection:"column",marginTop:1,children:[N(ee,{color:"yellow",bold:!0,children:"Available Commands"}),se(H,{children:[N(H,{width:16,children:N(ee,{color:"cyan",children:"/config"})}),N(ee,{dimColor:!0,children:"Open settings panel"})]}),se(H,{children:[N(H,{width:16,children:N(ee,{color:"cyan",children:"/help"})}),N(ee,{dimColor:!0,children:"Show this help"})]}),se(H,{children:[N(H,{width:16,children:N(ee,{color:"cyan",children:"/clear"})}),N(ee,{dimColor:!0,children:"Clear command history"})]}),se(H,{children:[N(H,{width:16,children:N(ee,{color:"cyan",children:"/exit"})}),N(ee,{dimColor:!0,children:"Exit application"})]})]})]}):null}import{Box as St,Text as tt}from"ink";import{jsx as Ge,jsxs as Et}from"react/jsx-runtime";function Fo({textState:t,placeholder:e="Describe what you want to do...",disabled:o=!1,hasHistory:r=!1,visible:i=!0}){return i?o?Et(St,{children:[Ge(tt,{dimColor:!0,children:"> "}),Ge(tt,{dimColor:!0,children:t.value||"..."})]}):Et(St,{flexDirection:"column",children:[Et(St,{children:[Ge(tt,{color:"green",bold:!0,children:"> "}),Ge(yt,{value:t.value,cursorOffset:t.cursorOffset,placeholder:e,isDisabled:o})]}),r&&Ge(St,{marginTop:1,children:Et(tt,{dimColor:!0,children:[Ge(tt,{color:"blue",children:"[O]"})," Toggle output"]})})]}):null}import{Box as ot,Text as fe}from"ink";import{jsx as be,jsxs as Ie}from"react/jsx-runtime";var Nn=[{key:"1",label:"Execute"},{key:"2",label:"Copy"},{key:"3",label:"Edit"},{key:"4",label:"Alternatives"},{key:"5",label:"Cancel"}];function Ho({focusedIndex:t,showExplain:e=!0,visible:o=!0}){return o?Ie(ot,{flexDirection:"column",marginTop:1,children:[be(ot,{flexDirection:"row",gap:1,children:Nn.map((r,i)=>{let s=i===t;return Ie(ot,{children:[Ie(fe,{color:s?"cyan":"blue",bold:s,inverse:s,children:["[",r.key,"]"]}),Ie(fe,{color:s?"cyan":void 0,bold:s,children:[" ",r.label]})]},r.key)})}),e&&be(ot,{marginTop:1,children:Ie(fe,{dimColor:!0,children:[be(fe,{color:"blue",children:"[?]"})," Explain"," ",be(fe,{color:"blue",children:"[O]"})," Toggle output"," ",be(fe,{dimColor:!0,children:"| \u2190\u2192 Navigate, Enter Select"})]})})]}):null}function $o({count:t,focusedIndex:e,visible:o=!0}){return o?be(ot,{children:Ie(fe,{dimColor:!0,children:["Press ",Ie(fe,{color:"blue",children:["1-",t]})," or ",be(fe,{color:"blue",children:"\u2191\u2193"})," to select,"," ",be(fe,{color:"blue",children:"[5]"})," Cancel",e>=0&&Ie(fe,{color:"cyan",children:[" (focused: ",e+1,")"]})]})}):null}import{Box as jt,Text as Bn}from"ink";import{Spinner as Dn}from"@inkjs/ui";import{jsx as qt,jsxs as Go}from"react/jsx-runtime";function Xt({query:t,label:e="Thinking..."}){return Go(jt,{flexDirection:"column",marginY:1,children:[qt(jt,{children:qt(Dn,{label:e})}),t&&qt(jt,{marginTop:1,children:Go(Bn,{dimColor:!0,children:["Query: ",t]})})]})}import{Box as oe,Text as G}from"ink";import{homedir as kn,userInfo as Mn}from"os";import{jsx as j,jsxs as te}from"react/jsx-runtime";var _n=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 \u25B6 _ \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function Yo({shell:t,cwd:e,provider:o,model:r}){let i=Mn().username||"user",s=e.replace(kn(),"~"),a=o||"anthropic",c=K[a].name,h=r||K[a].defaultModel;return te(oe,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1,marginBottom:1,children:[te(oe,{marginBottom:1,children:[j(G,{color:"cyan",bold:!0,children:Oe}),te(G,{dimColor:!0,children:[" v",pe]})]}),te(oe,{children:[te(oe,{flexDirection:"column",marginRight:4,children:[te(oe,{marginBottom:1,children:[j(G,{children:"Welcome, "}),j(G,{color:"yellow",bold:!0,children:i}),j(G,{children:"!"})]}),j(oe,{flexDirection:"column",children:_n.map((g,P)=>j(G,{color:"cyan",children:g},P))}),te(oe,{marginTop:1,flexDirection:"column",children:[te(oe,{children:[j(G,{dimColor:!0,children:"Shell: "}),j(G,{color:"green",children:t})]}),te(oe,{children:[j(G,{dimColor:!0,children:"Path: "}),j(G,{children:s})]})]})]}),te(oe,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,children:[j(oe,{marginBottom:1,children:j(G,{color:"yellow",bold:!0,children:"Quick Start"})}),te(oe,{flexDirection:"column",children:[j(G,{dimColor:!0,children:"Describe what you want in natural language:"}),te(G,{color:"gray",italic:!0,children:[" ",'"list all files modified today"']}),te(G,{color:"gray",italic:!0,children:[" ",'"find large files over 100MB"']}),te(G,{color:"gray",italic:!0,children:[" ",'"show git status"']})]}),j(oe,{marginTop:1,flexDirection:"column",children:te(oe,{children:[j(G,{dimColor:!0,children:"AI: "}),j(G,{color:"magenta",children:c}),j(G,{dimColor:!0,children:" / "}),j(G,{color:"magenta",children:h})]})})]})]})]})}import{useCallback as At,useRef as tr,useState as Zn}from"react";import{readdirSync as Ln,statSync as Kn}from"fs";import{join as Un,relative as Fn}from"path";var Hn=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"]),$n=new Set([".DS_Store","Thumbs.db",".gitignore",".npmrc",".yarnrc","pnpm-lock.yaml","package-lock.json","yarn.lock"]),Gn=3,Yn=20;function Vo(t,e=0){if(e>=Gn)return[];try{let o=Ln(t),r=[],i=0;for(let s of o){if(i>=Yn){r.push({name:`... (${o.length-i} more)`,isDirectory:!1});break}if(s.startsWith(".")&&!s.startsWith(".env")||$n.has(s))continue;let a=Un(t,s);try{if(Kn(a).isDirectory()){if(Hn.has(s))continue;let h=Vo(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 jo(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(jo(r.children,`${e}${c}`))):o.push(`${e}${a}${r.name}`)}),o.join(`
|
|
2
|
+
`)}function qo(t){let e=Vo(t);return e.length===0?"(empty or inaccessible directory)":`${Fn(process.cwd(),t)||"."}/
|
|
3
|
+
${jo(e)}`}import{appendFileSync as Vn,writeFileSync as jn}from"fs";import{join as qn}from"path";var Xo=process.env.DEBUG==="1"||process.env.DEBUG==="true",Qo=qn(process.cwd(),"debug.log");if(Xo)try{jn(Qo,`=== Debug session started: ${new Date().toISOString()} ===
|
|
4
|
+
`)}catch{}function Wo(t,e){if(!Xo)return;let r=`[${new Date().toISOString().slice(11,23)}] ${t}`;e!==void 0&&(r+=`: ${JSON.stringify(e)}`);try{Vn(Qo,r+`
|
|
5
|
+
`)}catch{}}function Xn(t){let e=t.toLowerCase();for(let o of Co)if(e.includes(o.toLowerCase()))return"high";for(let o of To)if(e.includes(o.toLowerCase()))return"medium";return"low"}function Qt(t,e){let o=Xn(e),r={low:0,medium:1,high:2};return r[t]>=r[o]?t:o}function Ce(t){return`You are a CLI command generator for ${t}.
|
|
6
6
|
You translate natural language requests into shell commands.
|
|
7
7
|
|
|
8
8
|
IMPORTANT: Output ONLY valid JSON, no markdown, no explanation text.
|
|
@@ -18,41 +18,38 @@ Rules:
|
|
|
18
18
|
2. Use appropriate flags for the target shell
|
|
19
19
|
3. Prefer safe alternatives when possible
|
|
20
20
|
4. For destructive operations, include safety flags (-i for interactive, etc.)
|
|
21
|
-
5. Never include placeholder values - ask for specifics if needed`}function
|
|
21
|
+
5. Never include placeholder values - ask for specifics if needed`}function Qn(t,e){if(!t||t.length<=e)return t;let o=t.slice(0,e),r=o.lastIndexOf(`
|
|
22
22
|
`);return r>e*.5?o.slice(0,r)+`
|
|
23
23
|
... (truncated)`:o+"... (truncated)"}function Te(t,e){let o=[];if(o.push(`Current directory: ${e.cwd}`),o.push(`
|
|
24
24
|
Directory structure:
|
|
25
25
|
${e.directoryTree}`),e.history.length>0){o.push(`
|
|
26
|
-
Conversation context (recent queries and results):`);let r=e.history.slice(-
|
|
27
|
-
Query: "${i.query}"`),o.push(`Command: ${i.command}`),i.exitCode!==void 0&&o.push(`Exit code: ${i.exitCode}`),i.output){let s=
|
|
26
|
+
Conversation context (recent queries and results):`);let r=e.history.slice(-ho);for(let i of r)if(o.push(`
|
|
27
|
+
Query: "${i.query}"`),o.push(`Command: ${i.command}`),i.exitCode!==void 0&&o.push(`Exit code: ${i.exitCode}`),i.output){let s=Qn(i.output,yo);o.push(`Output:
|
|
28
28
|
${s}`)}}return o.push(`
|
|
29
29
|
User request: ${t}`),o.join(`
|
|
30
|
-
`)}function
|
|
30
|
+
`)}function Ye(t){let e=t.match(/\{[\s\S]*\}/);if(!e)throw new Error("No JSON found in AI response");let o=JSON.parse(e[0]);if(!o.command||typeof o.command!="string")throw new Error("Invalid response: missing command");let r=o.risk,i=r&&["low","medium","high"].includes(r)?r:"medium";return{command:o.command.trim(),risk:Qt(i,o.command)}}function Ve(t){let e=t.match(/\[[\s\S]*\]/);if(!e)throw new Error("No JSON array found in AI response");return JSON.parse(e[0]).filter(r=>r.command&&typeof r.command=="string").map(r=>{let i=r.risk,s=i&&["low","medium","high"].includes(i)?i:"medium";return{command:r.command.trim(),risk:Qt(s,r.command)}})}function je(t){return new Promise(e=>setTimeout(e,t))}import Wn from"@anthropic-ai/sdk";var Pt=class{client;model;constructor(e,o){this.client=new Wn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<J.maxAttempts;r++)try{let s=(await this.client.messages.create({model:this.model,max_tokens:ae,system:Ce(o.shell),messages:[{role:"user",content:Te(e,o)}]})).content.find(a=>a.type==="text");if(!s||s.type!=="text")throw new Error("No text content in AI response");return{success:!0,data:Ye(s.text)}}catch(i){if(r===J.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(J.baseDelayMs*Math.pow(2,r),J.maxDelayMs);await je(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
31
31
|
|
|
32
32
|
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
33
33
|
Exclude: ${r}
|
|
34
34
|
|
|
35
|
-
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.messages.create({model:this.model,max_tokens:
|
|
36
|
-
${e}`}]})).content.find(i=>i.type==="text");if(!r||r.type!=="text")throw new Error("No text content in AI response");return{success:!0,data:r.text.trim()}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}};import
|
|
35
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.messages.create({model:this.model,max_tokens:ae*2,system:Ce(o.shell),messages:[{role:"user",content:s}]})).content.find(h=>h.type==="text");if(!c||c.type!=="text")throw new Error("No text content in AI response");return{success:!0,data:Ve(c.text)}}catch(a){return{success:!1,error:a instanceof Error?a:new Error(String(a))}}}async explainCommand(e){try{let r=(await this.client.messages.create({model:this.model,max_tokens:ae,messages:[{role:"user",content:`Explain this command briefly (2-3 sentences max):
|
|
36
|
+
${e}`}]})).content.find(i=>i.type==="text");if(!r||r.type!=="text")throw new Error("No text content in AI response");return{success:!0,data:r.text.trim()}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}};import Jn from"openai";var It=class{client;model;constructor(e,o){this.client=new Jn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<J.maxAttempts;r++)try{let s=(await this.client.chat.completions.create({model:this.model,max_tokens:ae,messages:[{role:"system",content:Ce(o.shell)},{role:"user",content:Te(e,o)}]})).choices[0]?.message?.content;if(!s)throw new Error("No content in AI response");return{success:!0,data:Ye(s)}}catch(i){if(r===J.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(J.baseDelayMs*Math.pow(2,r),J.maxDelayMs);await je(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
37
37
|
|
|
38
38
|
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
39
39
|
Exclude: ${r}
|
|
40
40
|
|
|
41
|
-
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.completions.create({model:this.model,max_tokens:
|
|
42
|
-
${e}`}]})).choices[0]?.message?.content;if(!r)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))}}}};import{OpenRouter as
|
|
41
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.completions.create({model:this.model,max_tokens:ae*2,messages:[{role:"system",content:Ce(o.shell)},{role:"user",content:s}]})).choices[0]?.message?.content;if(!c)throw new Error("No content in AI response");return{success:!0,data:Ve(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.completions.create({model:this.model,max_tokens:ae,messages:[{role:"user",content:`Explain this command briefly (2-3 sentences max):
|
|
42
|
+
${e}`}]})).choices[0]?.message?.content;if(!r)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))}}}};import{OpenRouter as zn}from"@openrouter/sdk";var bt=class{client;model;constructor(e,o){this.client=new zn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<J.maxAttempts;r++)try{let s=(await this.client.chat.send({model:this.model,maxTokens:ae,messages:[{role:"system",content:Ce(o.shell)},{role:"user",content:Te(e,o)}]})).choices?.[0]?.message?.content;if(!s||typeof s!="string")throw new Error("No content in AI response");return{success:!0,data:Ye(s)}}catch(i){if(r===J.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(J.baseDelayMs*Math.pow(2,r),J.maxDelayMs);await je(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
43
43
|
|
|
44
44
|
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
45
45
|
Exclude: ${r}
|
|
46
46
|
|
|
47
|
-
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.send({model:this.model,maxTokens:
|
|
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
|
|
49
|
-
`).filter(Boolean);for(let d of I)f.push(d),o?.(d,!1),s(
|
|
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(`
|
|
51
|
-
`).slice(0,
|
|
52
|
-
|
|
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(`
|
|
55
|
-
CLI AI v${me} - Natural language to shell commands
|
|
47
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.send({model:this.model,maxTokens:ae*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:Ve(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:ae,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 Jo(t,e,o){switch(Wo(`Creating provider: ${t}/${o}`),t){case"anthropic":return new Pt(e,o);case"openai":return new It(e,o);case"openrouter":return new bt(e,o)}}var Wt=null;function Jt(){let t=me(),e=_e(t.provider);if(!e)return null;let o=`${t.provider}:${t.model}:${e.slice(-4)}`;if(Wt?.key===o)return Wt.instance;let r=Jo(t.provider,e,t.model);return Wt={key:o,instance:r},r}async function zo(t,e){let o=Jt();return o?o.generateCommand(t,e):{success:!1,error:new Error("No API key configured")}}async function Zo(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 er(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:qo(o),history:e}}function or({shell:t,history:e=[],contextEnabled:o=!0}){let[r,i]=Zn({isLoading:!1,error:null,lastProposal:null}),s=tr(e);s.current=e;let a=tr(o);a.current=o;let c=At(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=a.current?s.current:[],f=zt(t,m),n=await zo(y,f);return n.success?i(C=>({...C,isLoading:!1,lastProposal:n.data})):i(C=>({...C,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=At(async(y,m)=>{i(f=>({...f,isLoading:!0,error:null}));try{let f=a.current?s.current:[],n=zt(t,f),C=await Zo(y,n,m);return i(v=>({...v,isLoading:!1})),C.success||i(v=>({...v,error:C.error})),C}catch(f){let n=f instanceof Error?f:new Error(String(f));return i(C=>({...C,isLoading:!1,error:n})),{success:!1,error:n}}},[t]),g=At(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=await er(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=At(()=>{i(y=>({...y,error:null}))},[]);return{...r,generate:c,getAlternatives:h,explain:g,clearError:P}}import{useCallback as Ae,useMemo as es,useState as rr}from"react";function nr({sessionStatus:t,config:e,updateConfig:o,onOpenConfig:r,onOpenHelp:i,onClearHistory:s,onExit:a}){let[c,h]=rr(""),[g,P]=rr(0),y=es(()=>ie.filter(c).filter(Z=>!Z.isAvailable||Z.isAvailable(t)),[c,t]),m=Ae(x=>{h(x),P(0)},[]),f=Ae(()=>{P(x=>y.length===0?0:(x-1+y.length)%y.length)},[y.length]),n=Ae(()=>{P(x=>y.length===0?0:(x+1)%y.length)},[y.length]),C=Ae(()=>({sessionStatus:t,config:e,updateConfig:o,exit:a}),[t,e,o,a]),v=Ae(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=Ae(()=>{if(y.length===0)return null;let x=y[g];if(!x)return null;let Z=C(),Q=x.execute(Z);return Q instanceof Promise?(Q.then(v),null):v(Q)},[y,g,C,v]),d=Ae(x=>{let Z=ie.get(x);if(!Z||Z.isAvailable&&!Z.isAvailable(t))return null;let Q=C(),ce=Z.execute(Q);return ce instanceof Promise?(ce.then(v),null):v(ce)},[t,C,v]),b=Ae(()=>{h(""),P(0)},[]);return{query:c,setQuery:m,filteredCommands:y,focusedIndex:g,focusUp:f,focusDown:n,executeSelected:I,executeCommand:d,reset:b}}import{useCallback as Zt,useEffect as ts,useState as os}from"react";function sr(){let[t,e]=os({isLoading:!0,hasKey:!1,config:me(),error:null});ts(()=>{try{let s=me(),a=Le(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(!ft(s,a))return e(c=>({...c,error:`Invalid API key format for ${s}`})),!1;try{let c=dt(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=me(),a=Le(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 rs}from"execa";import{useCallback as lr,useRef as ns,useState as ss}from"react";function ir(){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 ar(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 cr({shell:t,maxOutputLines:e=Ne.maxOutputLines,onOutput:o,onComplete:r}){let[i,s]=ss({isExecuting:!1,liveOutput:[],error:null}),a=ns(null),c=lr(async g=>{s({isExecuting:!0,liveOutput:[],error:null});let{cmd:P,args:y}=ar(t,g);try{let m=rs(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
|
+
`).filter(Boolean);for(let d of I)f.push(d),o?.(d,!1),s(b=>({...b,liveOutput:[...b.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 b=`[ERR] ${d}`;f.push(b),o?.(d,!0),s(x=>({...x,liveOutput:[...x.liveOutput,b].slice(-e)}))}});let n=await m;a.current=null;let C={command:g,stdout:n.stdout??"",stderr:n.stderr??"",exitCode:n.exitCode??0};return s(v=>({...v,isExecuting:!1})),r?.(C),{success:!0,data:C}}catch(m){a.current=null;let f=m instanceof Error?m:new Error(String(m));s(C=>({...C,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=lr(()=>{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 is}from"ink";import{useCallback as ur,useReducer as pr,useRef as mr,useState as rt}from"react";function dr({mode:t,menuCallbacks:e,selectionCallbacks:o,textCallbacks:r,paletteCallbacks:i,configCallbacks:s,helpCallbacks:a,initialTextValue:c="",paletteQuery:h=""}){let[g,P]=pr($t,Ht(c)),[y,m]=pr($t,Ht("")),[f,n]=rt(0),[C,v]=rt(0),[I,d]=rt(0),[b,x]=rt(0),[Z,Q]=rt(0),ce=mr(c);ce.current!==c&&(ce.current=c,P({type:"set",value:c}));let D=mr(t);D.current!==t&&(t==="menu"?n(0):t==="selection"?v(0):t==="palette"?d(0):t==="config"&&(x(0),Q(0)),D.current=t);let Re=ur(()=>{P({type:"clear"})},[]),De=ur(B=>{P({type:"set",value:B})},[]);return is((B,u)=>{if(t!=="disabled"){if(t==="text"&&r){if(u.ctrl&&!u.meta&&B==="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(B.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(B&&B.length>0){P({type:"insert",text:B});let S=g.value.slice(0,g.cursorOffset)+B+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(B>="1"&&B<="5"){let S=parseInt(B,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(B==="?"){e.onExplain();return}if(B.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(C);return}let V=parseInt(B,10);if(V>=1&&V<=S){o.onSelect(V-1);return}if(B==="5"||B.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 V=parseInt(B,10);if(V>=1&&V<=9&&V<=S){d(V-1),i.onSelect();return}if(B&&B.length>0){let w=h+B;i.onQueryChange(w),d(0)}return}if(t==="config"&&s){let S=s.sectionCount,V=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&&B&&B.length>0){m({type:"insert",text:B});return}return}if(u.tab&&!u.shift){x(w=>(w+1)%S),Q(0),s.onNavigateSection("next");return}if(u.tab&&u.shift){x(w=>(w-1+S)%S),Q(0),s.onNavigateSection("prev");return}if(u.upArrow){Q(w=>V===0?0:(w-1+V)%V),s.onNavigateItem("up");return}if(u.downArrow){Q(w=>V===0?0:(w+1)%V),s.onNavigateItem("down");return}if(u.return||B===" "){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:De,menuFocusIndex:f,selectionFocusIndex:C,paletteFocusIndex:I,configSectionIndex:b,configItemIndex:Z,customModelState:y,dispatchCustomModel:m}}import{useCallback as _,useReducer as as}from"react";var ls={state:{status:"setup"},history:[],currentQuery:"",editingCommand:null,outputExpanded:!1,error:null};function cs(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(-Ne.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 fr(){let[t,e]=as(cs,ls),o=_(D=>{e({type:"SUBMIT",query:D})},[]),r=_(D=>{e({type:"AI_RESPONSE",proposal:D})},[]),i=_(D=>{e({type:"AI_ALTERNATIVES",proposals:D})},[]),s=_(D=>{e({type:"AI_ERROR",error:D})},[]),a=_(()=>{e({type:"EXECUTE"})},[]),c=_(D=>{e({type:"EXECUTE_EDITED",command:D})},[]),h=_(D=>{e({type:"EXEC_DONE",result:D})},[]),g=_(()=>{e({type:"COPY"})},[]),P=_(D=>{e({type:"EDIT",command:D})},[]),y=_(()=>{e({type:"CANCEL"})},[]),m=_(()=>{e({type:"TOGGLE_OUTPUT"})},[]),f=_(()=>{e({type:"SETUP_COMPLETE"})},[]),n=_(()=>{e({type:"EDIT",command:""})},[]),C=_(()=>{e({type:"OPEN_PALETTE"})},[]),v=_((D,Re)=>{e({type:"UPDATE_PALETTE",query:D,filteredCommands:Re})},[]),I=_(()=>{e({type:"CLOSE_PALETTE"})},[]),d=_(()=>{e({type:"OPEN_CONFIG"})},[]),b=_(D=>{e({type:"UPDATE_CONFIG_SECTION",section:D})},[]),x=_(()=>{e({type:"CLOSE_CONFIG"})},[]),Z=_(()=>{e({type:"OPEN_HELP"})},[]),Q=_(()=>{e({type:"CLOSE_HELP"})},[]),ce=_(()=>{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:C,updatePalette:v,closePalette:I,openConfig:d,updateConfigSection:b,closeConfig:x,openHelp:Z,closeHelp:Q,clearHistory:ce}}import us from"clipboardy";async function gr(t){try{return await us.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 q,Text as U,useApp as ps}from"ink";import{useCallback as Y,useEffect as eo,useMemo as qe,useState as ge}from"react";import{Fragment as xr,jsx as T,jsxs as z}from"react/jsx-runtime";function yr(){let{exit:t}=ps(),e=ir(),[o,r]=ge(null),[i,s]=ge(null),[a,c]=ge([]),[h,g]=ge(0),{isLoading:P,hasKey:y,error:m,refreshKeyStatus:f}=sr(),{store:n,submitQuery:C,handleAIResponse:v,handleAIAlternatives:I,handleAIError:d,execute:b,executeEdited:x,markExecutionDone:Z,copy:Q,edit:ce,cancel:D,toggleOutput:Re,completeSetup:De,openPalette:B,updatePalette:u,closePalette:S,openConfig:V,updateConfigSection:w,closeConfig:nt,openHelp:hr,closeHelp:Cr,clearHistory:Tr}=fr(),[ve,st]=ge(0),[ue,it]=ge(()=>me().model),[at,vr]=ge(()=>({contextEnabled:me().contextEnabled,showExplanations:!0,syntaxHighlighting:!0,simpleMode:!1})),[Sr,to]=ge(!1),[Er,oo]=ge(null),[ke,we]=ge(!1),[W,ro]=ge(()=>me().provider),Pr=qe(()=>bo(W),[y,W]),Ir=qe(()=>{let l=_e(W);return l?l.length<=12?"***":`${l.slice(0,7)}...${l.slice(-4)}`:null},[y,W]),no=qe(()=>({provider:W,model:ue,contextEnabled:at.contextEnabled,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3}),[W,ue,at.contextEnabled]),re=nr({sessionStatus:n.state.status,config:no,updateConfig:()=>{},onOpenConfig:V,onOpenHelp:hr,onClearHistory:Tr,onExit:()=>t()}),so=qe(()=>n.history,[n.history]),{generate:io,getAlternatives:ao,explain:lo,isLoading:Me}=or({shell:e,history:n.history,contextEnabled:at.contextEnabled}),{execute:lt,kill:hs,isExecuting:Rt,liveOutput:br}=cr({shell:e,onComplete:Z}),Ar=qe(()=>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"?Me?"disabled":"menu":n.state.status==="alternatives"?Me?"disabled":"selection":n.state.status==="input"?"text":"disabled",[P,y,n.state.status,Rt,Me]),Rr=Y((l,p)=>{dt(p,l).success&&(!y&&n.state.status==="setup"&&(he({provider:p,model:K[p].defaultModel}),ro(p),it(K[p].defaultModel)),f(),to(!1),oo(null),De())},[y,n.state.status,f,De]);eo(()=>{!P&&y&&n.state.status==="setup"&&De()},[P,y,n.state.status,De]),eo(()=>{let l=me().model;ue!==l&&he({model:ue})},[ue]);let wr=Y(l=>{if(l.startsWith("/")){let p=l.slice(1),R=ie.filter(p);c(R),g(0)}else c([]),g(0)},[]),Or=Y(async l=>{if(l.startsWith("/")){let R=l.slice(1).trim();if(a.length>0){let L=a[h];if(L&&re.executeCommand(L.name)){c([]),g(0);return}}if(R&&re.executeCommand(R)){c([]),g(0);return}c([]),g(0);return}if(c([]),g(0),n.editingCommand){x(l),await lt(l);return}C(l),s(null);let p=await io(l);p.success?v(p.data):d(p.error)},[n.editingCommand,C,io,v,d,x,lt,re,a,h]),Nr=Y(async()=>{n.state.status==="proposal"&&(b(),await lt(n.state.proposal.command))},[n.state,b,lt]),Br=Y(async()=>{if(n.state.status!=="proposal")return;(await gr(n.state.proposal.command)).success?(r("\u2713 Copied to clipboard"),setTimeout(()=>r(null),2e3)):(r("\u2717 Failed to copy"),setTimeout(()=>r(null),2e3)),Q()},[n.state,Q]),Dr=Y(()=>{n.state.status==="proposal"&&ce(n.state.proposal.command)},[n.state,ce]),kr=Y(async()=>{if(n.state.status!=="proposal")return;let l=await ao(n.currentQuery,n.state.proposal.command);l.success?I(l.data):d(l.error)},[n.state,n.currentQuery,ao,I,d]),Mr=Y(()=>{D(),s(null)},[D]),_r=Y(async()=>{if(n.state.status!=="proposal")return;let l=await lo(n.state.proposal.command);l.success&&s(l.data)},[n.state,lo]),Lr=Y(()=>{Re()},[Re]),Kr=Y(l=>{if(n.state.status!=="alternatives")return;let p=n.state.proposals[l];p&&v(p)},[n.state,v]),Ur=Y(l=>{let p=ie.filter(l);re.setQuery(l),u(l,p)},[re,u]),Fr=Y(()=>{re.executeSelected()&&(S(),re.reset())},[re,S]),Hr=Y(l=>{l==="up"?re.focusUp():re.focusDown()},[re]),$r=Y(()=>{S(),re.reset()},[S,re]),Gr=Y(l=>{let p=["provider","api-keys","toggles","about"];if(n.state.status!=="config")return;ke&&we(!1);let R=p.indexOf(n.state.section),L;l==="next"?L=(R+1)%p.length:L=(R-1+p.length)%p.length,w(p[L]),st(0)},[n.state,w,ke]),Yr=Y(l=>{if(n.state.status!=="config")return;let p;n.state.section==="provider"?p=M.length+Se[W].length+1:p={provider:0,"api-keys":M.length,toggles:4,about:0}[n.state.section],p!==0&&st(R=>l==="up"?(R-1+p)%p:(R+1)%p)},[n.state,W]),Vr=Y(()=>{if(n.state.status==="config"){if(n.state.section==="toggles"){vr(l=>{let R=["contextEnabled","showExplanations","syntaxHighlighting","simpleMode"][ve];if(R){let L=!l[R];return R==="contextEnabled"&&he({contextEnabled:L}),{...l,[R]:L}}return l});return}if(n.state.section==="provider"){let l=M,p=Se[W],R=M.length+p.length;if(ve<M.length){let L=l[ve];if(L&&L!==W){let xe=K[L].defaultModel;he({provider:L,model:xe}),ro(L),it(xe),we(!1),st(0),f()}}else if(ve===R)we(!0);else{let L=ve-M.length,xe=p[L];xe&&xe.id!==ue&&(he({model:xe.id}),it(xe.id),we(!1))}return}if(n.state.section==="api-keys"){let p=M[ve];p&&(nt(),oo(p),to(!0));return}}},[n.state,ve,nt,W,f,ue]),jr=Y(()=>{nt(),st(0),we(!1)},[nt]),qr=n.state.status==="palette"?n.state.query:"",Xr=qe(()=>n.state.status!=="config"?0:n.state.section==="provider"?M.length+Se[W].length+1:{provider:0,"api-keys":M.length,toggles:4,about:0}[n.state.section],[n.state,W]),{textState:Qr,clearText:Cs,setText:Ts,menuFocusIndex:Wr,selectionFocusIndex:Jr,paletteFocusIndex:zr,configSectionIndex:vs,customModelState:Zr,dispatchCustomModel:co}=dr({mode:Ar,initialTextValue:n.editingCommand??"",paletteQuery:qr,menuCallbacks:{onExecute:Nr,onCopy:Br,onEdit:Dr,onAlternatives:kr,onCancel:Mr,onExplain:_r,onToggle:Lr},selectionCallbacks:{onSelect:Kr,onCancel:D,count:n.state.status==="alternatives"?n.state.proposals.length:1},textCallbacks:{onSubmit:Or,onToggleOutput:Re,onTextChange:wr,onNavigateInlinePalette:l=>{g(p=>{let R=a.length;return R===0?0:l==="up"?(p-1+R)%R:(p+1)%R})},onCloseInlinePalette:()=>{c([]),g(0)},hasInlinePalette:a.length>0,hasHistory:n.history.length>0},paletteCallbacks:{onQueryChange:Ur,onSelect:Fr,onNavigate:Hr,onClose:$r,filteredCount:n.state.status==="palette"?n.state.filteredCommands.length:0},configCallbacks:{onNavigateSection:Gr,onNavigateItem:Yr,onToggle:Vr,onClose:jr,sectionCount:4,itemCount:Xr,isEditingCustomModel:ke,onCustomModelSubmit:l=>{he({model:l}),it(l),we(!1)},onCustomModelCancel:()=>{we(!1)}},helpCallbacks:{onClose:Cr}});return eo(()=>{if(ke){let l=!Se[W].some(p=>p.id===ue);co({type:"set",value:l?ue:""})}},[ke,W,ue,co]),P?T(q,{flexDirection:"column",paddingY:1,children:T(U,{dimColor:!0,children:"Loading configuration..."})}):Sr||!y&&n.state.status==="setup"?T(Ro,{onComplete:Rr,error:m,provider:Er??void 0}):z(q,{flexDirection:"column",children:[T(Yo,{shell:e,cwd:process.cwd(),provider:W,model:ue}),so.map((l,p)=>{let R=p===so.length-1;return z(q,{flexDirection:"column",marginBottom:1,children:[z(q,{children:[z(U,{color:"cyan",bold:!0,children:["\u276F"," "]}),T(U,{color:"cyan",children:l.query})]}),z(q,{marginLeft:2,flexDirection:"column",children:[z(q,{children:[z(U,{dimColor:!0,children:["$ ",l.command," "]}),T(U,{color:l.exitCode===0?"green":"red",children:l.exitCode===0?"\u2713":`\u2717 ${l.exitCode}`})]}),l.output&&T(q,{flexDirection:"column",children:(()=>{let L=l.output.split(`
|
|
51
|
+
`).filter(wt=>wt.length>0),xe=R&&n.outputExpanded?500:10,uo=L.slice(0,xe),po=L.length-uo.length;return z(xr,{children:[uo.map((wt,en)=>T(U,{children:wt},en)),po>0&&z(q,{children:[z(U,{dimColor:!0,children:["... (",po," more lines"]}),R&&z(xr,{children:[T(U,{dimColor:!0,children:", press "}),T(U,{color:"blue",children:"[O]"}),T(U,{dimColor:!0,children:" to expand"})]}),T(U,{dimColor:!0,children:")"})]})]})})()})]}),T(q,{marginTop:1,children:T(U,{dimColor:!0,children:"\u2500".repeat(50)})})]},`history-${p}`)}),n.error&&T(q,{marginY:1,children:z(U,{color:"red",children:["Error: ",n.error]})}),o&&T(q,{marginY:1,children:T(U,{color:"green",children:o})}),n.state.status==="loading"&&T(Xt,{query:n.state.query}),n.state.status==="proposal"&&z(q,{flexDirection:"column",marginY:1,children:[T(ko,{proposal:n.state.proposal,showExplanation:!!i}),i&&T(q,{marginTop:1,paddingX:1,children:T(U,{dimColor:!0,children:i})})]}),n.state.status==="proposal"&&Me&&T(Xt,{label:"Generating alternatives..."}),T(Ho,{focusedIndex:Wr,visible:n.state.status==="proposal"&&!Me}),n.state.status==="alternatives"&&T(q,{flexDirection:"column",marginY:1,children:T(Mo,{proposals:n.state.proposals})}),T($o,{count:n.state.status==="alternatives"?n.state.proposals.length:0,focusedIndex:Jr,visible:n.state.status==="alternatives"&&!Me}),(n.state.status==="executing"||Rt)&&T(Oo,{lines:br,command:n.state.status==="executing"?n.state.command:""}),T(Ut,{query:n.state.status==="palette"?n.state.query:"",filteredCommands:n.state.status==="palette"?n.state.filteredCommands:[],selectedIndex:zr,visible:n.state.status==="palette"}),T(Yt,{visible:n.state.status==="config",activeSection:n.state.status==="config"?n.state.section:"provider",sectionItemIndex:ve,config:no,hasApiKey:y,storageInfo:Pr,maskedKey:Ir,toggles:at,isEditingCustomModel:ke,customModelState:Zr}),T(Vt,{visible:n.state.status==="help"}),T(Fo,{textState:Qr,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&&z(q,{flexDirection:"column",marginLeft:2,marginTop:0,children:[T(q,{marginBottom:0,children:T(U,{dimColor:!0,children:"\u2500".repeat(50)})}),a.slice(0,5).map((l,p)=>z(q,{children:[T(U,{color:p===h?"cyan":"gray",bold:p===h,children:p===h?"> ":" "}),z(U,{color:p===h?"cyan":"blue",bold:p===h,children:["/",l.name]}),T(U,{children:" "}),T(U,{dimColor:p!==h,children:l.description})]},l.name)),T(q,{marginTop:0,children:T(U,{dimColor:!0,children:"[Enter] Select [Up/Down] Navigate [Esc] Cancel"})})]})]})}import{render as ms}from"ink";import{jsx as ys}from"react/jsx-runtime";var ds="\x1Bc",fs="\x1B]0;CLI AI\x07";function gs(){console.log(`
|
|
52
|
+
CLI AI v${pe} - Natural language to shell commands
|
|
56
53
|
|
|
57
54
|
Usage:
|
|
58
55
|
s Start interactive session
|
|
@@ -75,4 +72,4 @@ Session Controls:
|
|
|
75
72
|
Escape Cancel current action
|
|
76
73
|
exit, quit Exit the session
|
|
77
74
|
Ctrl+D Exit (empty input)
|
|
78
|
-
`)}async function
|
|
75
|
+
`)}async function xs(){let t=process.argv.slice(2);(t.includes("--help")||t.includes("-h"))&&(gs(),process.exit(0)),(t.includes("--version")||t.includes("-v"))&&(console.log(`CLI AI v${pe}`),process.exit(0)),process.stdout.write(ds+fs);let{waitUntilExit:e}=ms(ys(yr,{}),{incrementalRendering:!0});process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{process.exit(0)}),await e()}xs().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
|
package/package.json
CHANGED
package/scripts/tag.js
CHANGED
|
@@ -28,15 +28,39 @@ function getPackageTag() {
|
|
|
28
28
|
return `v${pkg.version}`;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
function
|
|
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
|
|
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
|
|
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);
|