@fmdzc/cli-ai 3.0.4 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -63
- package/dist/index.js +37 -24
- package/package.json +9 -7
package/README.md
CHANGED
|
@@ -4,14 +4,17 @@
|
|
|
4
4
|
[](https://opensource.org/licenses/ISC)
|
|
5
5
|
[](https://nodejs.org/)
|
|
6
6
|
|
|
7
|
-
**Natural language to shell commands.
|
|
7
|
+
**Natural language to shell commands. Multi-provider AI support.**
|
|
8
8
|
|
|
9
9
|
Describe what you want in plain English. Get the right command. Review, execute, or copy.
|
|
10
10
|
|
|
11
|
+
Supports **Anthropic**, **OpenAI**, and **OpenRouter** providers.
|
|
12
|
+
|
|
11
13
|

|
|
12
14
|
|
|
13
15
|
## Features
|
|
14
16
|
|
|
17
|
+
- **Multi-provider** - Anthropic, OpenAI, OpenRouter with any model support
|
|
15
18
|
- **Natural language** - Just describe what you want to do
|
|
16
19
|
- **Cross-platform** - Windows (PowerShell, CMD, Git Bash), macOS, Linux
|
|
17
20
|
- **Shell-aware** - Commands tailored to your detected shell
|
|
@@ -32,7 +35,10 @@ s
|
|
|
32
35
|
cli-ai
|
|
33
36
|
```
|
|
34
37
|
|
|
35
|
-
On first run, you'll be prompted for
|
|
38
|
+
On first run, you'll be prompted for an API key. Get one from:
|
|
39
|
+
- [Anthropic](https://console.anthropic.com/settings/keys)
|
|
40
|
+
- [OpenAI](https://platform.openai.com/api-keys)
|
|
41
|
+
- [OpenRouter](https://openrouter.ai/keys)
|
|
36
42
|
|
|
37
43
|
## Usage
|
|
38
44
|
|
|
@@ -51,110 +57,116 @@ Risk: low
|
|
|
51
57
|
|
|
52
58
|
Type `/` to access commands:
|
|
53
59
|
|
|
54
|
-
| Command
|
|
55
|
-
|
|
56
|
-
| `/config` | Open settings panel
|
|
57
|
-
| `/help`
|
|
58
|
-
| `/clear`
|
|
59
|
-
| `/exit`
|
|
60
|
+
| Command | Description |
|
|
61
|
+
| --------- | ----------------------- |
|
|
62
|
+
| `/config` | Open settings panel |
|
|
63
|
+
| `/help` | Show help and shortcuts |
|
|
64
|
+
| `/clear` | Clear command history |
|
|
65
|
+
| `/exit` | Exit application |
|
|
60
66
|
|
|
61
67
|
### Keyboard Shortcuts
|
|
62
68
|
|
|
63
69
|
**Input Mode**
|
|
64
|
-
| Key
|
|
65
|
-
|
|
66
|
-
| `/`
|
|
67
|
-
| `Enter`
|
|
68
|
-
| `O`
|
|
69
|
-
| `Ctrl+D` | Exit (when empty)
|
|
70
|
+
| Key | Action |
|
|
71
|
+
| -------- | ----------------------- |
|
|
72
|
+
| `/` | Open command palette |
|
|
73
|
+
| `Enter` | Submit query |
|
|
74
|
+
| `O` | Toggle output expansion |
|
|
75
|
+
| `Ctrl+D` | Exit (when empty) |
|
|
70
76
|
|
|
71
77
|
**Command Proposal**
|
|
72
|
-
| Key
|
|
73
|
-
|
|
74
|
-
| `1` / `Enter` | Execute command
|
|
75
|
-
| `2`
|
|
76
|
-
| `3`
|
|
77
|
-
| `4`
|
|
78
|
-
| `5` / `Esc`
|
|
79
|
-
| `?`
|
|
78
|
+
| Key | Action |
|
|
79
|
+
| ------------- | ----------------- |
|
|
80
|
+
| `1` / `Enter` | Execute command |
|
|
81
|
+
| `2` | Copy to clipboard |
|
|
82
|
+
| `3` | Edit command |
|
|
83
|
+
| `4` | Show alternatives |
|
|
84
|
+
| `5` / `Esc` | Cancel |
|
|
85
|
+
| `?` | Explain command |
|
|
80
86
|
|
|
81
87
|
**Settings Panel**
|
|
82
|
-
| Key
|
|
83
|
-
|
|
84
|
-
| `Tab`
|
|
88
|
+
| Key | Action |
|
|
89
|
+
| --------- | -------------- |
|
|
90
|
+
| `Tab` | Next section |
|
|
85
91
|
| `Up/Down` | Navigate items |
|
|
86
|
-
| `Enter`
|
|
87
|
-
| `Esc`
|
|
92
|
+
| `Enter` | Toggle/Select |
|
|
93
|
+
| `Esc` | Close |
|
|
88
94
|
|
|
89
95
|
## Settings
|
|
90
96
|
|
|
91
97
|
Access settings with `/config`:
|
|
92
98
|
|
|
93
|
-
###
|
|
94
|
-
|
|
95
|
-
|
|
99
|
+
### Provider & Model
|
|
100
|
+
|
|
101
|
+
Supported AI providers:
|
|
102
|
+
- **Anthropic** - Claude models
|
|
103
|
+
- **OpenAI** - GPT models
|
|
104
|
+
- **OpenRouter** - 100+ models from various providers
|
|
105
|
+
|
|
106
|
+
Any model from your selected provider is supported. Use the built-in presets or enter a custom model ID.
|
|
107
|
+
|
|
108
|
+
### API Keys
|
|
96
109
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
| Claude Opus 4.5 | Most capable |
|
|
102
|
-
| Claude Haiku 4.5 | Fastest |
|
|
110
|
+
Manage API keys for each provider separately:
|
|
111
|
+
- View key status (✓ Configured / ✗ Not set)
|
|
112
|
+
- Add or change keys for any provider
|
|
113
|
+
- Keys are stored securely per provider
|
|
103
114
|
|
|
104
115
|
### Options
|
|
105
|
-
| Setting
|
|
106
|
-
|
|
107
|
-
| Context
|
|
108
|
-
| Show explanations
|
|
109
|
-
| Syntax highlighting | Colorize command output
|
|
110
|
-
| Simple mode
|
|
116
|
+
| Setting | Description |
|
|
117
|
+
| ------------------- | ------------------------------------------------------- |
|
|
118
|
+
| Context | Pass conversation history to AI for smarter suggestions |
|
|
119
|
+
| Show explanations | Display command explanations |
|
|
120
|
+
| Syntax highlighting | Colorize command output |
|
|
121
|
+
| Simple mode | Minimal UI mode |
|
|
111
122
|
|
|
112
123
|
## Risk Assessment
|
|
113
124
|
|
|
114
|
-
| Level
|
|
115
|
-
|
|
116
|
-
| Low
|
|
125
|
+
| Level | Color | Meaning |
|
|
126
|
+
| ------ | ------ | ------------------------------ |
|
|
127
|
+
| Low | Green | Safe, read-only commands |
|
|
117
128
|
| Medium | Yellow | Modifies files or system state |
|
|
118
|
-
| High
|
|
129
|
+
| High | Red | Potentially destructive |
|
|
119
130
|
|
|
120
131
|
## Security
|
|
121
132
|
|
|
122
133
|
### API Key Storage
|
|
123
134
|
|
|
124
|
-
Your
|
|
135
|
+
Your API keys are stored securely using industry-standard methods. Each provider's key is stored separately.
|
|
125
136
|
|
|
126
137
|
**Primary: System Keyring**
|
|
127
138
|
|
|
128
|
-
| Platform | Storage Backend
|
|
129
|
-
|
|
130
|
-
| macOS
|
|
131
|
-
| Windows
|
|
132
|
-
| Linux
|
|
139
|
+
| Platform | Storage Backend |
|
|
140
|
+
| -------- | ------------------------------------------- |
|
|
141
|
+
| macOS | Keychain |
|
|
142
|
+
| Windows | Credential Manager |
|
|
143
|
+
| Linux | Secret Service API (GNOME Keyring, KWallet) |
|
|
133
144
|
|
|
134
|
-
The system keyring provides OS-level encryption and access control.
|
|
145
|
+
The system keyring provides OS-level encryption and access control. API keys are never stored in plain text or environment variables.
|
|
135
146
|
|
|
136
147
|
**Fallback: Encrypted File**
|
|
137
148
|
|
|
138
|
-
If the system keyring is unavailable,
|
|
149
|
+
If the system keyring is unavailable, keys are stored in an encrypted file at `~/.cli_ai_assistant/`. The encryption key is derived from your machine's unique identifiers (hostname + username), making the encrypted file non-portable and machine-specific.
|
|
139
150
|
|
|
140
151
|
### Key Management
|
|
141
152
|
|
|
142
|
-
- **View**: See masked
|
|
143
|
-
- **
|
|
144
|
-
- **
|
|
153
|
+
- **View**: See masked keys and storage method per provider in `/config`
|
|
154
|
+
- **Add**: Configure API keys for Anthropic, OpenAI, or OpenRouter
|
|
155
|
+
- **Change**: Update any API key anytime through settings
|
|
156
|
+
- **Status**: Green ✓ indicates configured, red ✗ indicates not set
|
|
145
157
|
|
|
146
158
|
## Requirements
|
|
147
159
|
|
|
148
160
|
- **Node.js 20+**
|
|
149
161
|
- **Build tools** for native modules:
|
|
150
162
|
|
|
151
|
-
| Platform
|
|
152
|
-
|
|
153
|
-
| Windows
|
|
154
|
-
| macOS
|
|
163
|
+
| Platform | Command |
|
|
164
|
+
| ------------- | -------------------------------------------------- |
|
|
165
|
+
| Windows | `npm install -g windows-build-tools` (Admin) |
|
|
166
|
+
| macOS | `xcode-select --install` |
|
|
155
167
|
| Ubuntu/Debian | `sudo apt install build-essential libsecret-1-dev` |
|
|
156
|
-
| Fedora
|
|
157
|
-
| Arch
|
|
168
|
+
| Fedora | `sudo dnf install gcc-c++ libsecret-devel` |
|
|
169
|
+
| Arch | `sudo pacman -S base-devel libsecret` |
|
|
158
170
|
|
|
159
171
|
## Development
|
|
160
172
|
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
var Hn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{render as Wr}from"ink";var yt=[{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"}];function Ct(e,t){let o=e.toLowerCase(),n=t.toLowerCase();if(n.startsWith(o))return 100+(100-n.length);if(n.includes(o))return 50+(50-n.indexOf(o));let i=0,s=0;for(let a=0;a<n.length&&s<o.length;a++)n[a]===o[s]&&(i+=10,s++);return s===o.length?i:0}function Fn(e,t){let o=Ct(e,t.name),n=Ct(e,t.description),i=(t.aliases??[]).map(s=>Ct(e,s));return Math.max(o,n,...i)}function Xt(){let e=[],t=new Map;function o(){t.clear();for(let n of e){t.set(n.name.toLowerCase(),n);for(let i of n.aliases??[])t.set(i.toLowerCase(),n)}}return{get commands(){return e},get(n){return t.get(n.toLowerCase())},filter(n){return n?e.map(s=>({cmd:s,score:Fn(n,s)})).filter(({score:s})=>s>0).sort((s,a)=>a.score-s.score).map(({cmd:s})=>s):[...e]},register(n){t.get(n.name.toLowerCase())||(e.push(n),o())}}}var z=Xt();var ht={name:"clear",description:"Clear conversation history",category:"session",aliases:["cls"],execute:()=>({type:"navigate",to:"clear"}),isAvailable:e=>e==="input"};var Tt={name:"config",description:"Open settings and configuration panel",category:"settings",aliases:["settings","preferences","prefs"],shortcut:"Ctrl+,",execute:()=>({type:"panel",panel:"config"}),isAvailable:e=>e==="input"};var St={name:"exit",description:"Exit the application",category:"session",aliases:["quit","q"],execute:()=>({type:"exit"}),isAvailable:()=>!0};var Et={name:"help",description:"Show help and keyboard shortcuts",category:"help",aliases:["h","?"],execute:()=>({type:"panel",panel:"help"}),isAvailable:()=>!0};z.register(Tt);z.register(Et);z.register(ht);z.register(St);var ee="3.0.4",Ce="CLI AI",Wt="cli-ai",Qt="anthropic",Vt=".cli_ai_assistant",_e="claude-sonnet-4-5",he={model:_e,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3,contextEnabled:!0},zt=500,Jt=10,Zt=["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"],eo=["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 "],to=["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"],Je=500,Me={maxAttempts:3,baseDelayMs:1e3,maxDelayMs:5e3};import{Box as $,Text as J,useInput as $n}from"ink";import{useState as vt}from"react";import{TextInput as Yn}from"@inkjs/ui";import{jsx as N,jsxs as le}from"react/jsx-runtime";function oo({onComplete:e,onError:t,error:o}){let[n,i]=vt("welcome"),[s,a]=vt(""),[c,g]=vt(null);$n((d,u)=>{n==="welcome"&&(u.return||d===" ")&&i("input")},{isActive:n==="welcome"});let m=d=>{let u=d.trim();if(!u){g("API key cannot be empty");return}if(!u.startsWith("sk-ant-")){g('Invalid key format. Anthropic API keys start with "sk-ant-"');return}if(u.length<20){g("API key seems too short");return}g(null),i("saving"),e(u)};if(n==="welcome")return le($,{flexDirection:"column",paddingY:1,children:[N($,{marginBottom:1,children:le(J,{bold:!0,color:"cyan",children:[Ce," v",ee]})}),N($,{marginBottom:1,children:N(J,{children:"Welcome! This tool translates natural language into shell commands."})}),N($,{marginBottom:1,children:le(J,{dimColor:!0,children:["To get started, you'll need an Anthropic API key.",`
|
|
2
|
-
`,"Get one at: ",N(J,{color:"blue",children:"https://console.anthropic.com/settings/keys"})]})}),N($,{children:N(J,{color:"green",children:"Press Enter to continue..."})})]});let y=o??c;return n==="input"?le($,{flexDirection:"column",paddingY:1,children:[N($,{marginBottom:1,children:N(J,{bold:!0,children:"Enter your Anthropic API key:"})}),y&&N($,{marginBottom:1,children:le(J,{color:"red",children:["\u26A0 ",y]})}),le($,{children:[N(J,{dimColor:!0,children:"> "}),N(Yn,{placeholder:"sk-ant-...",onChange:a,onSubmit:m})]}),N($,{marginTop:1,children:N(J,{color:"yellow",children:"\u{1F512} Your key is stored securely on this machine using your system's credential manager (never sent anywhere except Anthropic's API)."})})]}):n==="saving"?N($,{flexDirection:"column",paddingY:1,children:N($,{children:N(J,{color:"yellow",children:"\u23F3 Saving API key..."})})}):le($,{flexDirection:"column",paddingY:1,children:[N($,{children:N(J,{color:"green",children:"\u2713 API key saved successfully!"})}),N($,{marginTop:1,children:le(J,{children:["Starting ",Ce,"..."]})})]})}import{Box as Ze,Text as bt}from"ink";import{jsx as Ke,jsxs as no}from"react/jsx-runtime";function ro({lines:e,command:t}){return no(Ze,{flexDirection:"column",marginY:1,children:[Ke(Ze,{marginBottom:1,children:no(bt,{dimColor:!0,children:["$ ",t]})}),Ke(Ze,{flexDirection:"column",children:e.map((o,n)=>{let i=o.startsWith("[ERR]");return Ke(bt,{color:i?"red":void 0,children:i?o.slice(6):o},n)})}),Ke(Ze,{marginTop:1,children:Ke(bt,{color:"yellow",children:"\u23F3 Running..."})})]})}import{Box as Ae,Text as we}from"ink";import{Box as Gn,Text as ce}from"ink";import{Fragment as jn,jsx as Ie,jsxs as et}from"react/jsx-runtime";function Pt({command:e,index:t,isSelected:o}){return et(Gn,{children:[Ie(ce,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),et(ce,{color:o?"cyan":"blue",bold:o,children:["[",t+1,"]"]}),Ie(ce,{children:" "}),et(ce,{color:o?"white":"gray",bold:o,children:["/",e.name]}),Ie(ce,{children:" "}),Ie(ce,{dimColor:!o,children:e.description}),e.shortcut?et(jn,{children:[Ie(ce,{children:" "}),Ie(ce,{dimColor:!0,color:"yellow",children:e.shortcut})]}):null]})}import{jsx as te,jsxs as so}from"react/jsx-runtime";function It({query:e,filteredCommands:t,selectedIndex:o,visible:n}){return n?so(Ae,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginTop:1,children:[so(Ae,{children:[te(we,{color:"blue",bold:!0,children:"/"}),te(we,{color:"white",children:e}),te(we,{color:"cyan",children:"_"})]}),te(Ae,{marginY:0,children:te(we,{dimColor:!0,children:"\u2500".repeat(50)})}),t.length>0?te(Ae,{flexDirection:"column",children:t.slice(0,9).map((i,s)=>te(Pt,{command:i,index:s,isSelected:s===o},i.name))}):te(Ae,{children:te(we,{dimColor:!0,children:"No matching commands"})}),te(Ae,{marginTop:1,children:te(we,{dimColor:!0,children:"[Enter] Select [1-9] Quick select [Esc] Close"})})]}):null}import{Box as ue,Text as Te}from"ink";import Ys from"chalk";function qn(e){let t=[],o=e.split(/(\s+)/);for(let n of o)if(n){if(/^\s+$/.test(n)){t.push({type:"default",value:n});continue}if(/^[|><&;]+$/.test(n)||n==="&&"||n==="||"){t.push({type:"pipe",value:n});continue}if(/^-{1,2}[\w-]+=?/.test(n)){t.push({type:"flag",value:n});continue}if(/^\$[\w{}]+/.test(n)){t.push({type:"variable",value:n});continue}if(/^["'].*["']$/.test(n)){t.push({type:"string",value:n});continue}if(n.includes("/")||n.includes("\\")){t.push({type:"path",value:n});continue}if(to.includes(n.toLowerCase())){t.push({type:"keyword",value:n});continue}t.push({type:"default",value:n})}return t}function io(e){return qn(e).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 X,jsxs as Ue}from"react/jsx-runtime";function ao({command:e}){let t=io(e);return X(Te,{children:t.map((o,n)=>X(Te,{color:o.color,bold:o.bold,children:o.text},n))})}function lo({proposal:e,showExplanation:t=!1}){return Ue(ue,{flexDirection:"column",children:[X(ue,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,children:X(ao,{command:e.command})}),t&&e.explanation&&X(ue,{marginTop:1,paddingX:1,children:X(Te,{dimColor:!0,children:e.explanation})})]})}function Xn({command:e,index:t,selected:o=!1}){return Ue(ue,{children:[Ue(Te,{color:o?"cyan":"blue",bold:o,children:["[",t+1,"]"]}),X(Te,{children:" "}),X(ao,{command:e})]})}function co({proposals:e,selectedIndex:t=-1}){return Ue(ue,{flexDirection:"column",marginY:1,children:[X(ue,{marginBottom:1,children:X(Te,{bold:!0,children:"Alternative commands:"})}),e.map((o,n)=>X(ue,{marginBottom:1,children:X(Xn,{command:o.command,index:n,selected:n===t})},n)),X(ue,{marginTop:1,children:Ue(Te,{dimColor:!0,children:["Press 1-",e.length," to select, or [5] Cancel"]})})]})}import{Box as He,Text as oe}from"ink";import{Fragment as Wn,jsx as se,jsxs as Se}from"react/jsx-runtime";function At({hasApiKey:e,storageMethod:t,storageDescription:o,isSecure:n,maskedKey:i,isSectionActive:s,focusedIndex:a}){return Se(He,{flexDirection:"column",children:[Se(He,{children:[se(oe,{dimColor:!0,children:"Status: "}),se(oe,{color:e?"green":"red",children:e?"Configured":"Not configured"}),e?Se(Wn,{children:[se(oe,{dimColor:!0,children:" ("}),se(oe,{color:n?"green":"yellow",children:o}),se(oe,{dimColor:!0,children:")"})]}):null]}),i?Se(He,{children:[se(oe,{dimColor:!0,children:"Key: "}),se(oe,{color:"gray",children:i})]}):null,Se(He,{marginTop:1,children:[se(oe,{color:s&&a===0?"cyan":"gray",bold:s&&a===0,children:s&&a===0?"> ":" "}),Se(oe,{color:s&&a===0?"cyan":"blue",children:["[",e?"Change API Key":"Set API Key","]"]})]}),e?Se(He,{children:[se(oe,{color:s&&a===1?"cyan":"gray",bold:s&&a===1,children:s&&a===1?"> ":" "}),se(oe,{color:s&&a===1?"red":"gray",children:"[Remove API Key]"})]}):null]})}import{Box as ie,Text as Ee}from"ink";import{Box as tt,Text as wt}from"ink";import{jsx as Fe,jsxs as uo}from"react/jsx-runtime";function Re({title:e,isActive:t,children:o}){return uo(tt,{flexDirection:"column",marginBottom:1,children:[uo(tt,{children:[Fe(wt,{color:t?"cyan":"white",bold:!0,children:e}),t?Fe(wt,{color:"cyan",children:" *"}):null]}),Fe(tt,{children:Fe(wt,{dimColor:!0,children:"\u2500".repeat(50)})}),Fe(tt,{flexDirection:"column",paddingLeft:0,children:o})]})}import{Box as po,Text as $e}from"ink";import{Fragment as Qn,jsx as Oe,jsxs as mo}from"react/jsx-runtime";function Rt({options:e,selectedValue:t,focusedIndex:o,isSectionActive:n}){return Oe(po,{flexDirection:"column",children:e.map((i,s)=>{let a=i.id===t,c=n&&s===o;return mo(po,{children:[Oe($e,{color:c?"cyan":"gray",bold:c,children:c?"> ":" "}),Oe($e,{color:a?"green":c?"white":"gray",children:a?"(*) ":"( ) "}),Oe($e,{color:c?"white":"gray",bold:a,children:i.name}),i.description?mo(Qn,{children:[Oe($e,{dimColor:!0,children:" - "}),Oe($e,{dimColor:!0,children:i.description})]}):null]},i.id)})})}import{Box as Vn,Text as ot}from"ink";import{jsx as nt,jsxs as zn}from"react/jsx-runtime";function Be({label:e,value:t,isSelected:o}){return zn(Vn,{children:[nt(ot,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),nt(ot,{color:t?"green":"gray",children:t?"[x]":"[ ]"}),nt(ot,{children:" "}),nt(ot,{color:o?"white":"gray",children:e})]})}import{jsx as K,jsxs as pe}from"react/jsx-runtime";var fo=["api-key","model","toggles","about"];function Ot({visible:e,activeSection:t,sectionItemIndex:o,config:n,hasApiKey:i,storageInfo:s,maskedKey:a,toggles:c}){if(!e)return null;let g=fo.indexOf(t);return pe(ie,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[pe(ie,{justifyContent:"space-between",marginBottom:1,children:[K(ie,{children:K(Ee,{color:"cyan",bold:!0,children:"Settings"})}),K(ie,{children:K(Ee,{dimColor:!0,children:"[Esc] Close [Tab] Section [Enter] Select"})})]}),K(Re,{title:"API Key",isActive:t==="api-key",children:K(At,{hasApiKey:i,storageMethod:s.method,storageDescription:s.description,isSecure:s.secure,maskedKey:a,isSectionActive:t==="api-key",focusedIndex:o})}),K(Re,{title:"Model",isActive:t==="model",children:K(Rt,{options:yt,selectedValue:n.model,focusedIndex:o,isSectionActive:t==="model"})}),pe(Re,{title:"Options",isActive:t==="toggles",children:[K(Be,{label:"Context (pass history to AI)",value:c.contextEnabled,isSelected:t==="toggles"&&o===0}),K(Be,{label:"Show explanations",value:c.showExplanations,isSelected:t==="toggles"&&o===1}),K(Be,{label:"Syntax highlighting",value:c.syntaxHighlighting,isSelected:t==="toggles"&&o===2}),K(Be,{label:"Simple mode",value:c.simpleMode,isSelected:t==="toggles"&&o===3})]}),K(Re,{title:"About",isActive:t==="about",children:pe(ie,{flexDirection:"column",children:[pe(ie,{children:[K(Ee,{dimColor:!0,children:"Version: "}),pe(Ee,{children:["CLI AI v",ee]})]}),pe(ie,{children:[K(Ee,{dimColor:!0,children:"Storage: "}),K(Ee,{color:s.secure?"green":"yellow",children:s.description})]})]})}),K(ie,{marginTop:1,justifyContent:"center",children:fo.map((m,y)=>K(ie,{marginX:1,children:pe(Ee,{color:y===g?"cyan":"gray",children:[y===g?"[":" ",y+1,y===g?"]":" "]})},m))})]})}import{Box as D,Text as Y}from"ink";import{jsx as P,jsxs as W}from"react/jsx-runtime";var Jn=[{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)"}],Zn=[{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"}],er=[{key:"Up/Down",description:"Navigate commands"},{key:"Enter",description:"Select command"},{key:"Esc",description:"Close palette"},{key:"1-9",description:"Quick select"}],tr=[{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 rt({title:e,shortcuts:t}){return W(D,{flexDirection:"column",marginBottom:1,children:[P(Y,{color:"yellow",bold:!0,children:e}),t.map(o=>W(D,{children:[P(D,{width:16,children:P(Y,{color:"cyan",children:o.key})}),P(Y,{dimColor:!0,children:o.description})]},o.key))]})}function Bt({visible:e}){return e?W(D,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[W(D,{justifyContent:"space-between",marginBottom:1,children:[P(D,{children:W(Y,{color:"cyan",bold:!0,children:["Help - ",Ce," v",ee]})}),P(D,{children:P(Y,{dimColor:!0,children:"[Esc] Close"})})]}),P(D,{marginBottom:1,children:P(Y,{children:"Natural language to shell command translator. Describe what you want in plain English and get executable commands."})}),W(D,{children:[W(D,{flexDirection:"column",marginRight:4,children:[P(rt,{title:"Input Mode",shortcuts:Jn}),P(rt,{title:"Command Palette",shortcuts:er})]}),W(D,{flexDirection:"column",children:[P(rt,{title:"Proposal Mode",shortcuts:Zn}),P(rt,{title:"Config Panel",shortcuts:tr})]})]}),W(D,{flexDirection:"column",marginTop:1,children:[P(Y,{color:"yellow",bold:!0,children:"Available Commands"}),W(D,{children:[P(D,{width:16,children:P(Y,{color:"cyan",children:"/config"})}),P(Y,{dimColor:!0,children:"Open settings panel"})]}),W(D,{children:[P(D,{width:16,children:P(Y,{color:"cyan",children:"/help"})}),P(Y,{dimColor:!0,children:"Show this help"})]}),W(D,{children:[P(D,{width:16,children:P(Y,{color:"cyan",children:"/clear"})}),P(Y,{dimColor:!0,children:"Clear command history"})]}),W(D,{children:[P(D,{width:16,children:P(Y,{color:"cyan",children:"/exit"})}),P(Y,{dimColor:!0,children:"Exit application"})]})]})]}):null}import{Box as st,Text as Ge}from"ink";import{Text as or}from"ink";import Ye from"chalk";import{useMemo as go}from"react";import{jsx as rr}from"react/jsx-runtime";var Nt=Ye.inverse(" ");function xo({value:e,cursorOffset:t,placeholder:o="",isDisabled:n=!1}){let i=go(()=>n?o?Ye.dim(o):"":o&&o.length>0?Ye.inverse(o[0])+Ye.dim(o.slice(1)):Nt,[n,o]),s=go(()=>{if(n)return e;let a=0,c=e.length>0?"":Nt;for(let g of e)c+=a===t?Ye.inverse(g):g,a++;return e.length>0&&t===e.length&&(c+=Nt),c},[n,e,t]);return rr(or,{children:e.length>0?s:i})}var nr={value:"",cursorOffset:0};function yo(e=""){return{value:e,cursorOffset:e.length}}function Co(e,t){switch(t.type){case"insert":return{value:e.value.slice(0,e.cursorOffset)+t.text+e.value.slice(e.cursorOffset),cursorOffset:e.cursorOffset+t.text.length};case"delete":{if(e.cursorOffset===0)return e;let o=e.cursorOffset-1;return{value:e.value.slice(0,o)+e.value.slice(o+1),cursorOffset:o}}case"move-left":return{...e,cursorOffset:Math.max(0,e.cursorOffset-1)};case"move-right":return{...e,cursorOffset:Math.min(e.value.length,e.cursorOffset+1)};case"clear":return nr;case"set":return{value:t.value,cursorOffset:t.value.length};default:return e}}import{jsx as Ne,jsxs as it}from"react/jsx-runtime";function ho({textState:e,placeholder:t="Describe what you want to do...",disabled:o=!1,hasHistory:n=!1,visible:i=!0}){return i?o?it(st,{children:[Ne(Ge,{dimColor:!0,children:"> "}),Ne(Ge,{dimColor:!0,children:e.value||"..."})]}):it(st,{flexDirection:"column",children:[it(st,{children:[Ne(Ge,{color:"green",bold:!0,children:"> "}),Ne(xo,{value:e.value,cursorOffset:e.cursorOffset,placeholder:t,isDisabled:o})]}),n&&Ne(st,{marginTop:1,children:it(Ge,{dimColor:!0,children:[Ne(Ge,{color:"blue",children:"[O]"})," Toggle output"]})})]}):null}import{Box as je,Text as ne}from"ink";import{jsx as de,jsxs as me}from"react/jsx-runtime";var sr=[{key:"1",label:"Execute"},{key:"2",label:"Copy"},{key:"3",label:"Edit"},{key:"4",label:"Alternatives"},{key:"5",label:"Cancel"}];function To({focusedIndex:e,showExplain:t=!0,visible:o=!0}){return o?me(je,{flexDirection:"column",marginTop:1,children:[de(je,{flexDirection:"row",gap:1,children:sr.map((n,i)=>{let s=i===e;return me(je,{children:[me(ne,{color:s?"cyan":"blue",bold:s,inverse:s,children:["[",n.key,"]"]}),me(ne,{color:s?"cyan":void 0,bold:s,children:[" ",n.label]})]},n.key)})}),t&&de(je,{marginTop:1,children:me(ne,{dimColor:!0,children:[de(ne,{color:"blue",children:"[?]"})," Explain"," ",de(ne,{color:"blue",children:"[O]"})," Toggle output"," ",de(ne,{dimColor:!0,children:"| \u2190\u2192 Navigate, Enter Select"})]})})]}):null}function So({count:e,focusedIndex:t,visible:o=!0}){return o?de(je,{children:me(ne,{dimColor:!0,children:["Press ",me(ne,{color:"blue",children:["1-",e]})," or ",de(ne,{color:"blue",children:"\u2191\u2193"})," to select,"," ",de(ne,{color:"blue",children:"[5]"})," Cancel",t>=0&&me(ne,{color:"cyan",children:[" (focused: ",t+1,")"]})]})}):null}import{Box as Dt,Text as ir}from"ink";import{Spinner as ar}from"@inkjs/ui";import{jsx as Lt,jsxs as Eo}from"react/jsx-runtime";function kt({query:e,label:t="Thinking..."}){return Eo(Dt,{flexDirection:"column",marginY:1,children:[Lt(Dt,{children:Lt(ar,{label:t})}),e&&Lt(Dt,{marginTop:1,children:Eo(ir,{dimColor:!0,children:["Query: ",e]})})]})}import{Box as Q,Text as H}from"ink";import{homedir as lr,userInfo as cr}from"os";import{jsx as U,jsxs as Z}from"react/jsx-runtime";var ur=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 \u25B6 _ \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function vo({shell:e,cwd:t,model:o}){let n=cr().username||"user",i=t.replace(lr(),"~"),s=o||"claude-sonnet-4-5";return Z(Q,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1,marginBottom:1,children:[Z(Q,{marginBottom:1,children:[U(H,{color:"cyan",bold:!0,children:Ce}),Z(H,{dimColor:!0,children:[" v",ee]})]}),Z(Q,{children:[Z(Q,{flexDirection:"column",marginRight:4,children:[Z(Q,{marginBottom:1,children:[U(H,{children:"Welcome, "}),U(H,{color:"yellow",bold:!0,children:n}),U(H,{children:"!"})]}),U(Q,{flexDirection:"column",children:ur.map((a,c)=>U(H,{color:"cyan",children:a},c))}),Z(Q,{marginTop:1,flexDirection:"column",children:[Z(Q,{children:[U(H,{dimColor:!0,children:"Shell: "}),U(H,{color:"green",children:e})]}),Z(Q,{children:[U(H,{dimColor:!0,children:"Path: "}),U(H,{children:i})]})]})]}),Z(Q,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,children:[U(Q,{marginBottom:1,children:U(H,{color:"yellow",bold:!0,children:"Quick Start"})}),Z(Q,{flexDirection:"column",children:[U(H,{dimColor:!0,children:"Describe what you want in natural language:"}),U(H,{color:"gray",italic:!0,children:' "list all files modified today"'}),U(H,{color:"gray",italic:!0,children:' "find large files over 100MB"'}),U(H,{color:"gray",italic:!0,children:' "show git status"'})]}),Z(Q,{marginTop:1,flexDirection:"column",children:[U(H,{dimColor:!0,children:"Model: "}),U(H,{color:"magenta",children:s.split("-").slice(0,2).join(" ")})]})]})]})]})}import{useCallback as dt,useRef as Uo,useState as Nr}from"react";import{readdirSync as pr,statSync as mr}from"fs";import{join as dr,relative as fr}from"path";var gr=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"]),xr=new Set([".DS_Store","Thumbs.db",".gitignore",".npmrc",".yarnrc","pnpm-lock.yaml","package-lock.json","yarn.lock"]),yr=3,Cr=20;function bo(e,t=0){if(t>=yr)return[];try{let o=pr(e),n=[],i=0;for(let s of o){if(i>=Cr){n.push({name:`... (${o.length-i} more)`,isDirectory:!1});break}if(s.startsWith(".")&&!s.startsWith(".env")||xr.has(s))continue;let a=dr(e,s);try{if(mr(a).isDirectory()){if(gr.has(s))continue;let g=bo(a,t+1);n.push({name:s,isDirectory:!0,children:g.length>0?g:void 0})}else n.push({name:s,isDirectory:!1});i++}catch{continue}}return n}catch{return[]}}function Po(e,t=""){let o=[];return e.forEach((n,i)=>{let s=i===e.length-1,a=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=s?" ":"\u2502 ";n.isDirectory?(o.push(`${t}${a}${n.name}/`),n.children&&n.children.length>0&&o.push(Po(n.children,`${t}${c}`))):o.push(`${t}${a}${n.name}`)}),o.join(`
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
var zr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ut={id:"__custom__",name:"Custom model...",description:"Enter any model ID"},Ee={anthropic:[{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",description:"Fast and capable"},{id:"claude-opus-4-5",name:"Claude Opus 4.5",description:"Most capable"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",description:"Fastest"}],openrouter:[{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5",description:"Anthropic"},{id:"xiaomi/mimo-v2-flash:free",name:"MiMo-V2-Flash",description:"Xiaomi (Free)"},{id:"x-ai/grok-code-fast-1",name:"Grok Code Fast 1",description:"xAI"},{id:"google/gemini-3-flash-preview",name:"Gemini 3 Flash Preview",description:"Google"}],openai:[{id:"gpt-5.2",name:"GPT-5.2",description:"Most capable"},{id:"gpt-5-mini",name:"GPT-5 Mini",description:"Fast and efficient"},{id:"gpt-5-nano",name:"GPT-5 Nano",description:"Fastest"}]},Zr=Ee.anthropic;function Ot(t,e){let o=t.toLowerCase(),r=e.toLowerCase();if(r.startsWith(o))return 100+(100-r.length);if(r.includes(o))return 50+(50-r.indexOf(o));let i=0,s=0;for(let a=0;a<r.length&&s<o.length;a++)r[a]===o[s]&&(i+=10,s++);return s===o.length?i:0}function en(t,e){let o=Ot(t,e.name),r=Ot(t,e.description),i=(e.aliases??[]).map(s=>Ot(t,s));return Math.max(o,r,...i)}function co(){let t=[],e=new Map;function o(){e.clear();for(let r of t){e.set(r.name.toLowerCase(),r);for(let i of r.aliases??[])e.set(i.toLowerCase(),r)}}return{get commands(){return t},get(r){return e.get(r.toLowerCase())},filter(r){return r?t.map(s=>({cmd:s,score:en(r,s)})).filter(({score:s})=>s>0).sort((s,a)=>a.score-s.score).map(({cmd:s})=>s):[...t]},register(r){e.get(r.name.toLowerCase())||(t.push(r),o())}}}var ae=co();var Nt={name:"clear",description:"Clear conversation history",category:"session",aliases:["cls"],execute:()=>({type:"navigate",to:"clear"}),isAvailable:t=>t==="input"};var Bt={name:"config",description:"Open settings and configuration panel",category:"settings",aliases:["settings","preferences","prefs"],shortcut:"Ctrl+,",execute:()=>({type:"panel",panel:"config"}),isAvailable:t=>t==="input"};var Dt={name:"exit",description:"Exit the application",category:"session",aliases:["quit","q"],execute:()=>({type:"exit"}),isAvailable:()=>!0};var kt={name:"help",description:"Show help and keyboard shortcuts",category:"help",aliases:["h","?"],execute:()=>({type:"panel",panel:"help"}),isAvailable:()=>!0};ae.register(Bt);ae.register(kt);ae.register(Nt);ae.register(Dt);var me="3.1.0",Ne="CLI AI",uo="cli-ai";var po=".cli_ai_assistant",K=["anthropic","openrouter","openai"],mo="anthropic",F={anthropic:{name:"Anthropic",envVar:"ANTHROPIC_API_KEY",keyringAccount:"anthropic",keyPrefix:"sk-ant-",defaultModel:"claude-sonnet-4-5"},openrouter:{name:"OpenRouter",envVar:"OPENROUTER_API_KEY",keyringAccount:"openrouter",keyPrefix:"sk-or-",defaultModel:"anthropic/claude-sonnet-4.5"},openai:{name:"OpenAI",envVar:"OPENAI_API_KEY",keyringAccount:"openai",keyPrefix:"sk-",defaultModel:"gpt-5.2"}},tn=F[mo].defaultModel,Be={provider:mo,model:tn,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3,contextEnabled:!0},fo=500,go=10,xo=["rm -rf","sudo rm","chmod 777","mkfs","dd if=","> /dev/","format","del /f","rmdir /s","DROP TABLE","DELETE FROM","--no-preserve-root",":(){:|:&};:","| sh","| bash","curl | bash","wget | bash","eval","sudo su","passwd","chown -R","> /etc/","fdisk","wipefs","shred"],yo=["rm ","mv ","cp ","sudo ","npm install","pnpm install","yarn add","pip install","brew install","apt install","apt-get install","pacman -S","chmod ","chown ","git push","git reset","git rebase","docker ","kubectl ","systemctl ","service ","kill ","pkill "],ho=["sudo","rm","git","npm","pnpm","yarn","docker","kubectl","pip","python","node","npx","cd","ls","cat","grep","find","mkdir","touch","mv","cp","echo","curl","wget","ssh","scp"],le=500,z={maxAttempts:3,baseDelayMs:1e3,maxDelayMs:5e3};import mt from"conf";import{createHash as on}from"crypto";import{existsSync as vo,unlinkSync as Co}from"fs";import{hostname as rn,userInfo as nn}from"os";import{homedir as sn}from"os";import{join as So}from"path";var an="cli-ai-v3-encryption-key";function ln(){let t=`${rn()}-${nn().username}-cli-ai-v3-salt`;return on("sha256").update(t).digest("hex").slice(0,32)}var We=So(sn(),po),dt=So(We,"config.json");function cn(){if(!vo(dt))return null;try{let t=new mt({projectName:"cli-ai",cwd:We,encryptionKey:an}),e=t.get("apiKey"),o=t.get("apiKeys"),r=t.get("config");if(e||o||r)return{apiKey:e,apiKeys:o,config:r}}catch{}return null}function un(){let t=ln(),e=cn();if(e){try{Co(dt)}catch{}let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});if(e.apiKey&&!e.apiKeys?o.set("apiKeys",{anthropic:e.apiKey}):e.apiKeys&&o.set("apiKeys",e.apiKeys),e.config){let r={...e.config};r.provider||(r.provider="anthropic"),o.set("config",r)}return o}try{let o=new mt({projectName:"cli-ai",cwd:We,encryptionKey:t});return pn(o),o}catch{try{vo(dt)&&Co(dt)}catch{}return new mt({projectName:"cli-ai",cwd:We,encryptionKey:t})}}function pn(t){let e=t.get("apiKey");e&&!t.get("apiKeys")&&(t.set("apiKeys",{anthropic:e}),t.delete("apiKey"));let o=t.get("config");o&&!o.provider&&t.set("config",{...o,provider:"anthropic"})}var ye=un(),pt=null,To=!1,Mt=new Map,Qe=null;function mn(){if(To)return pt;To=!0;try{return pt=zr("@napi-rs/keyring"),pt}catch{return pt=null,null}}function _t(t){if(Qe===!1)return null;let e=Mt.get(t);if(e!==void 0)return e;let o=mn();if(!o)return Qe=!1,null;try{let r=F[t].keyringAccount,i=new o.Entry(uo,r);return i.getPassword(),Qe=!0,Mt.set(t,i),i}catch{return Mt.set(t,null),Qe===null&&(Qe=!1),null}}function Le(t){let e=F[t].envVar,o=process.env[e];if(o)return o;let r=_t(t);if(r)try{let s=r.getPassword();if(s)return s}catch{}return ye.get("apiKeys")?.[t]??null}function ft(t,e){try{let o=_t(t);if(o)try{o.setPassword(e);let i=ye.get("apiKeys")??{};return delete i[t],Object.keys(i).length>0?ye.set("apiKeys",i):ye.delete("apiKeys"),{success:!0,data:void 0}}catch{}let r=ye.get("apiKeys")??{};return r[t]=e,ye.set("apiKeys",r),{success:!0,data:void 0}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}function Ke(t){let e=Le(t);return e!==null&&e.length>0}function de(){let t=ye.get("config")??{};return{...Be,...t}}function he(t){let e=ye.get("config")??{};ye.set("config",{...e,...t})}function gt(t,e){let o=F[t];return t==="openai"?e.startsWith("sk-")&&e.length>20:e.startsWith(o.keyPrefix)&&e.length>20}function Eo(t){let e=F[t].envVar;if(process.env[e])return{method:"env",secure:!1,description:"Environment variable"};let o=_t(t);if(o)try{if(o.getPassword())return{method:"keyring",secure:!0,description:"System keyring"}}catch{}return ye.get("apiKeys")?.[t]?{method:"encrypted-file",secure:!1,description:"Encrypted file"}:{method:"none",secure:!1,description:"Not configured"}}import{Box as $,Text as Q,useInput as Po}from"ink";import{useState as Je}from"react";import{TextInput as dn}from"@inkjs/ui";import{jsx as O,jsxs as ce}from"react/jsx-runtime";var fn={anthropic:"https://console.anthropic.com/settings/keys",openai:"https://platform.openai.com/api-keys",openrouter:"https://openrouter.ai/keys"};function Io({onComplete:t,onError:e,error:o,provider:r}){let[i,s]=Je(r?"input":"welcome"),[a,c]=Je(r??"anthropic"),[h,g]=Je(0),[P,y]=Je(""),[m,f]=Je(null);Po((I,d)=>{i==="welcome"&&(d.return||I===" ")&&s("provider")},{isActive:i==="welcome"}),Po((I,d)=>{if(i==="provider"){if(d.upArrow){g(x=>(x-1+K.length)%K.length);return}if(d.downArrow){g(x=>(x+1)%K.length);return}if(d.return){let x=K[h];x&&(c(x),s("input"));return}let A=parseInt(I,10);if(A>=1&&A<=K.length){let x=K[A-1];x&&(c(x),s("input"))}}},{isActive:i==="provider"});let n=I=>{let d=I.trim();if(!d){f("API key cannot be empty");return}if(!gt(a,d)){let A=F[a];f(`Invalid key format. ${A.name} API keys start with "${A.keyPrefix}"`);return}f(null),s("saving"),t(d,a)};if(i==="welcome")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,color:"cyan",children:[Ne," v",me]})}),O($,{marginBottom:1,children:O(Q,{children:"Welcome! This tool translates natural language into shell commands."})}),O($,{marginBottom:1,children:O(Q,{dimColor:!0,children:"To get started, you'll need an API key from one of the supported providers."})}),O($,{children:O(Q,{color:"green",children:"Press Enter to continue..."})})]});if(i==="provider")return ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:O(Q,{bold:!0,children:"Select your AI provider:"})}),K.map((I,d)=>{let A=F[I],x=d===h;return ce($,{children:[O(Q,{color:x?"cyan":"gray",bold:x,children:x?"> ":" "}),ce(Q,{color:x?"cyan":"white",children:[d+1,". ",A.name]})]},I)}),O($,{marginTop:1,children:O(Q,{dimColor:!0,children:"[Up/Down] Navigate [Enter] Select [1-3] Quick select"})})]});let T=o??m,v=F[a];return i==="input"?ce($,{flexDirection:"column",paddingY:1,children:[O($,{marginBottom:1,children:ce(Q,{bold:!0,children:["Enter your ",v.name," API key:"]})}),O($,{marginBottom:1,children:ce(Q,{dimColor:!0,children:["Get one at: ",O(Q,{color:"blue",children:fn[a]})]})}),T&&O($,{marginBottom:1,children:ce(Q,{color:"red",children:["\u26A0 ",T]})}),ce($,{children:[O(Q,{dimColor:!0,children:"> "}),O(dn,{placeholder:`${v.keyPrefix}...`,onChange:y,onSubmit:n})]}),O($,{marginTop:1,children:O(Q,{color:"yellow",children:"\u{1F512} Your key is stored securely on this machine using your system's credential manager."})})]}):i==="saving"?O($,{flexDirection:"column",paddingY:1,children:O($,{children:O(Q,{color:"yellow",children:"\u23F3 Saving API key..."})})}):ce($,{flexDirection:"column",paddingY:1,children:[O($,{children:O(Q,{color:"green",children:"\u2713 API key saved successfully!"})}),O($,{marginTop:1,children:ce(Q,{children:["Starting ",Ne,"..."]})})]})}import{Box as xt,Text as Lt}from"ink";import{jsx as ze,jsxs as bo}from"react/jsx-runtime";function Ao({lines:t,command:e}){return bo(xt,{flexDirection:"column",marginY:1,children:[ze(xt,{marginBottom:1,children:bo(Lt,{dimColor:!0,children:["$ ",e]})}),ze(xt,{flexDirection:"column",children:t.map((o,r)=>{let i=o.startsWith("[ERR]");return ze(Lt,{color:i?"red":void 0,children:i?o.slice(6):o},r)})}),ze(xt,{marginTop:1,children:ze(Lt,{color:"yellow",children:"\u23F3 Running..."})})]})}import{Box as He,Text as Fe}from"ink";import{Box as gn,Text as Pe}from"ink";import{Fragment as xn,jsx as Ue,jsxs as yt}from"react/jsx-runtime";function Kt({command:t,index:e,isSelected:o}){return yt(gn,{children:[Ue(Pe,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),yt(Pe,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),Ue(Pe,{children:" "}),yt(Pe,{color:o?"white":"gray",bold:o,children:["/",t.name]}),Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!o,children:t.description}),t.shortcut?yt(xn,{children:[Ue(Pe,{children:" "}),Ue(Pe,{dimColor:!0,color:"yellow",children:t.shortcut})]}):null]})}import{jsx as fe,jsxs as Ro}from"react/jsx-runtime";function Ut({query:t,filteredCommands:e,selectedIndex:o,visible:r}){return r?Ro(He,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:1,marginTop:1,children:[Ro(He,{children:[fe(Fe,{color:"blue",bold:!0,children:"/"}),fe(Fe,{color:"white",children:t}),fe(Fe,{color:"cyan",children:"_"})]}),fe(He,{marginY:0,children:fe(Fe,{dimColor:!0,children:"\u2500".repeat(50)})}),e.length>0?fe(He,{flexDirection:"column",children:e.slice(0,9).map((i,s)=>fe(Kt,{command:i,index:s,isSelected:s===o},i.name))}):fe(He,{children:fe(Fe,{dimColor:!0,children:"No matching commands"})}),fe(He,{marginTop:1,children:fe(Fe,{dimColor:!0,children:"[Enter] Select [1-9] Quick select [Esc] Close"})})]}):null}import{Box as Ie,Text as De}from"ink";import gi from"chalk";function yn(t){let e=[],o=t.split(/(\s+)/);for(let r of o)if(r){if(/^\s+$/.test(r)){e.push({type:"default",value:r});continue}if(/^[|><&;]+$/.test(r)||r==="&&"||r==="||"){e.push({type:"pipe",value:r});continue}if(/^-{1,2}[\w-]+=?/.test(r)){e.push({type:"flag",value:r});continue}if(/^\$[\w{}]+/.test(r)){e.push({type:"variable",value:r});continue}if(/^["'].*["']$/.test(r)){e.push({type:"string",value:r});continue}if(r.includes("/")||r.includes("\\")){e.push({type:"path",value:r});continue}if(ho.includes(r.toLowerCase())){e.push({type:"keyword",value:r});continue}e.push({type:"default",value:r})}return e}function wo(t){return yn(t).map(o=>{switch(o.type){case"keyword":return{text:o.value,color:"cyan",bold:!0};case"flag":return{text:o.value,color:"yellow"};case"string":return{text:o.value,color:"green"};case"pipe":return{text:o.value,color:"magenta"};case"path":return{text:o.value,color:"blue"};case"variable":return{text:o.value,color:"cyan"};default:return{text:o.value}}})}import{jsx as ne,jsxs as Ze}from"react/jsx-runtime";function Oo({command:t}){let e=wo(t);return ne(De,{children:e.map((o,r)=>ne(De,{color:o.color,bold:o.bold,children:o.text},r))})}function No({proposal:t,showExplanation:e=!1}){return Ze(Ie,{flexDirection:"column",children:[ne(Ie,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,children:ne(Oo,{command:t.command})}),e&&t.explanation&&ne(Ie,{marginTop:1,paddingX:1,children:ne(De,{dimColor:!0,children:t.explanation})})]})}function hn({command:t,index:e,selected:o=!1}){return Ze(Ie,{children:[Ze(De,{color:o?"cyan":"blue",bold:o,children:["[",e+1,"]"]}),ne(De,{children:" "}),ne(Oo,{command:t})]})}function Bo({proposals:t,selectedIndex:e=-1}){return Ze(Ie,{flexDirection:"column",marginY:1,children:[ne(Ie,{marginBottom:1,children:ne(De,{bold:!0,children:"Alternative commands:"})}),t.map((o,r)=>ne(Ie,{marginBottom:1,children:ne(hn,{command:o.command,index:r,selected:r===e})},r)),ne(Ie,{marginTop:1,children:Ze(De,{dimColor:!0,children:["Press 1-",t.length," to select, or [5] Cancel"]})})]})}import{Box as Ei,Text as Pi}from"ink";import{Fragment as Ai,jsx as bi,jsxs as Ri}from"react/jsx-runtime";import{Text as Cn}from"ink";import et from"chalk";import{useMemo as Do}from"react";import{jsx as vn}from"react/jsx-runtime";var Ht=et.inverse(" ");function ht({value:t,cursorOffset:e,placeholder:o="",isDisabled:r=!1}){let i=Do(()=>r?o?et.dim(o):"":o&&o.length>0?et.inverse(o[0])+et.dim(o.slice(1)):Ht,[r,o]),s=Do(()=>{if(r)return t;let a=0,c=t.length>0?"":Ht;for(let h of t)c+=a===e?et.inverse(h):h,a++;return t.length>0&&e===t.length&&(c+=Ht),c},[r,t,e]);return vn(Cn,{children:t.length>0?s:i})}var Tn={value:"",cursorOffset:0};function Ft(t=""){return{value:t,cursorOffset:t.length}}function $t(t,e){switch(e.type){case"insert":return{value:t.value.slice(0,t.cursorOffset)+e.text+t.value.slice(t.cursorOffset),cursorOffset:t.cursorOffset+e.text.length};case"delete":{if(t.cursorOffset===0)return t;let o=t.cursorOffset-1;return{value:t.value.slice(0,o)+t.value.slice(o+1),cursorOffset:o}}case"move-left":return{...t,cursorOffset:Math.max(0,t.cursorOffset-1)};case"move-right":return{...t,cursorOffset:Math.min(t.value.length,t.cursorOffset+1)};case"clear":return Tn;case"set":return{value:e.value,cursorOffset:e.value.length};default:return t}}import{Box as Ct,Text as Gt}from"ink";import{jsx as tt,jsxs as ko}from"react/jsx-runtime";function $e({title:t,isActive:e,children:o}){return ko(Ct,{flexDirection:"column",marginBottom:1,children:[ko(Ct,{children:[tt(Gt,{color:e?"cyan":"white",bold:!0,children:t}),e?tt(Gt,{color:"cyan",children:" *"}):null]}),tt(Ct,{children:tt(Gt,{dimColor:!0,children:"\u2500".repeat(50)})}),tt(Ct,{flexDirection:"column",paddingLeft:0,children:o})]})}import{Box as Sn,Text as Tt}from"ink";import{jsx as vt,jsxs as En}from"react/jsx-runtime";function Ge({label:t,value:e,isSelected:o}){return En(Sn,{children:[vt(Tt,{color:o?"cyan":"gray",bold:o,children:o?"> ":" "}),vt(Tt,{color:e?"green":"gray",children:e?"[x]":"[ ]"}),vt(Tt,{children:" "}),vt(Tt,{color:o?"white":"gray",children:t})]})}import{Box as Y,Text as R}from"ink";import{Fragment as _o,jsx as E,jsxs as M}from"react/jsx-runtime";var Mo=["provider","api-keys","toggles","about"];function Yt({visible:t,activeSection:e,sectionItemIndex:o,config:r,hasApiKey:i,storageInfo:s,maskedKey:a,toggles:c,isEditingCustomModel:h=!1,customModelState:g}){if(!t)return null;let P=Mo.indexOf(e),y=Ee[r.provider],m=!y.some(n=>n.id===r.model),f=K.length+y.length;return M(Y,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[M(Y,{justifyContent:"space-between",marginBottom:1,children:[E(Y,{children:E(R,{color:"cyan",bold:!0,children:"Settings"})}),E(Y,{children:E(R,{dimColor:!0,children:"[Esc] Close [Tab] Section [Enter] Select"})})]}),E($e,{title:"Provider & Model",isActive:e==="provider",children:M(Y,{flexDirection:"column",children:[E(Y,{marginBottom:1,children:E(R,{dimColor:!0,children:"Provider"})}),K.map((n,T)=>{let v=F[n],I=r.provider===n,d=Ke(n),A=e==="provider"&&o===T;return M(Y,{children:[E(R,{color:A?"cyan":"gray",bold:A,children:A?"> ":" "}),M(R,{color:A?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",v.name]}),E(R,{children:" "}),E(R,{color:d?"green":"red",dimColor:!A,children:d?"\u2713 Key":"\u2717 No key"})]},n)}),E(Y,{marginTop:1,marginBottom:1,children:E(R,{dimColor:!0,children:"Model"})}),y.map((n,T)=>{let v=T+K.length,I=r.model===n.id,d=e==="provider"&&o===v;return M(Y,{children:[E(R,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(R,{color:d?"cyan":I?"green":"white",children:[I?"\u25CF":"\u25CB"," ",n.name]}),M(R,{dimColor:!d,children:[" ",n.description]})]},n.id)}),M(Y,{children:[E(R,{color:e==="provider"&&o===f?"cyan":"gray",bold:e==="provider"&&o===f,children:e==="provider"&&o===f?"> ":" "}),h&&g?M(_o,{children:[E(R,{color:"cyan",children:"\u25CB "}),E(ht,{value:g.value,cursorOffset:g.cursorOffset,placeholder:"model-id"}),E(R,{dimColor:!0,children:" (Enter to save, Esc to cancel)"})]}):M(_o,{children:[M(R,{color:e==="provider"&&o===f?"cyan":m?"green":"white",children:[m?"\u25CF":"\u25CB"," ",ut.name]}),M(R,{dimColor:!(e==="provider"&&o===f),children:[" ",m?`(${r.model})`:ut.description]})]})]},ut.id)]})}),E($e,{title:"API Keys",isActive:e==="api-keys",children:E(Y,{flexDirection:"column",children:K.map((n,T)=>{let v=F[n],I=Ke(n),d=e==="api-keys"&&o===T;return M(Y,{children:[E(R,{color:d?"cyan":"gray",bold:d,children:d?"> ":" "}),M(R,{color:d?"cyan":"white",children:[v.name,": "]}),E(R,{color:I?"green":"red",children:I?"\u2713 Configured":"\u2717 Not set"}),M(R,{dimColor:!d,children:[" [Enter to ",I?"change":"add","]"]})]},n)})})}),M($e,{title:"Options",isActive:e==="toggles",children:[E(Ge,{label:"Context (pass history to AI)",value:c.contextEnabled,isSelected:e==="toggles"&&o===0}),E(Ge,{label:"Show explanations",value:c.showExplanations,isSelected:e==="toggles"&&o===1}),E(Ge,{label:"Syntax highlighting",value:c.syntaxHighlighting,isSelected:e==="toggles"&&o===2}),E(Ge,{label:"Simple mode",value:c.simpleMode,isSelected:e==="toggles"&&o===3})]}),E($e,{title:"About",isActive:e==="about",children:M(Y,{flexDirection:"column",children:[M(Y,{children:[E(R,{dimColor:!0,children:"Version: "}),M(R,{children:["CLI AI v",me]})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Provider: "}),E(R,{color:"magenta",children:F[r.provider].name})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Model: "}),E(R,{color:"magenta",children:r.model})]}),M(Y,{children:[E(R,{dimColor:!0,children:"Storage: "}),E(R,{color:s.secure?"green":"yellow",children:s.description})]})]})}),E(Y,{marginTop:1,justifyContent:"center",children:Mo.map((n,T)=>E(Y,{marginX:1,children:M(R,{color:T===P?"cyan":"gray",children:[T===P?"[":" ",T+1,T===P?"]":" "]})},n))})]})}import{Box as Ji,Text as zi}from"ink";import{Fragment as ta,jsx as ea,jsxs as oa}from"react/jsx-runtime";import{Box as G,Text as ee}from"ink";import{jsx as N,jsxs as se}from"react/jsx-runtime";var Pn=[{key:"/",description:"Open command palette"},{key:"Enter",description:"Submit query"},{key:"Ctrl+D",description:"Exit (when input is empty)"},{key:"O",description:"Toggle output expansion (when input is empty)"}],In=[{key:"1 / Enter",description:"Execute command"},{key:"2",description:"Copy to clipboard"},{key:"3",description:"Edit command"},{key:"4",description:"Show alternatives"},{key:"5 / Esc",description:"Cancel"},{key:"?",description:"Explain command"},{key:"O",description:"Toggle output"}],bn=[{key:"Up/Down",description:"Navigate commands"},{key:"Enter",description:"Select command"},{key:"Esc",description:"Close palette"},{key:"1-9",description:"Quick select"}],An=[{key:"Tab",description:"Next section"},{key:"Shift+Tab",description:"Previous section"},{key:"Up/Down",description:"Navigate items"},{key:"Enter/Space",description:"Toggle/Select"},{key:"Esc",description:"Close panel"}];function St({title:t,shortcuts:e}){return se(G,{flexDirection:"column",marginBottom:1,children:[N(ee,{color:"yellow",bold:!0,children:t}),e.map(o=>se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:o.key})}),N(ee,{dimColor:!0,children:o.description})]},o.key))]})}function Vt({visible:t}){return t?se(G,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1,children:[se(G,{justifyContent:"space-between",marginBottom:1,children:[N(G,{children:se(ee,{color:"cyan",bold:!0,children:["Help - ",Ne," v",me]})}),N(G,{children:N(ee,{dimColor:!0,children:"[Esc] Close"})})]}),N(G,{marginBottom:1,children:N(ee,{children:"Natural language to shell command translator. Describe what you want in plain English and get executable commands."})}),se(G,{children:[se(G,{flexDirection:"column",marginRight:4,children:[N(St,{title:"Input Mode",shortcuts:Pn}),N(St,{title:"Command Palette",shortcuts:bn})]}),se(G,{flexDirection:"column",children:[N(St,{title:"Proposal Mode",shortcuts:In}),N(St,{title:"Config Panel",shortcuts:An})]})]}),se(G,{flexDirection:"column",marginTop:1,children:[N(ee,{color:"yellow",bold:!0,children:"Available Commands"}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/config"})}),N(ee,{dimColor:!0,children:"Open settings panel"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/help"})}),N(ee,{dimColor:!0,children:"Show this help"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/clear"})}),N(ee,{dimColor:!0,children:"Clear command history"})]}),se(G,{children:[N(G,{width:16,children:N(ee,{color:"cyan",children:"/exit"})}),N(ee,{dimColor:!0,children:"Exit application"})]})]})]}):null}import{Box as Et,Text as ot}from"ink";import{jsx as Ye,jsxs as Pt}from"react/jsx-runtime";function Lo({textState:t,placeholder:e="Describe what you want to do...",disabled:o=!1,hasHistory:r=!1,visible:i=!0}){return i?o?Pt(Et,{children:[Ye(ot,{dimColor:!0,children:"> "}),Ye(ot,{dimColor:!0,children:t.value||"..."})]}):Pt(Et,{flexDirection:"column",children:[Pt(Et,{children:[Ye(ot,{color:"green",bold:!0,children:"> "}),Ye(ht,{value:t.value,cursorOffset:t.cursorOffset,placeholder:e,isDisabled:o})]}),r&&Ye(Et,{marginTop:1,children:Pt(ot,{dimColor:!0,children:[Ye(ot,{color:"blue",children:"[O]"})," Toggle output"]})})]}):null}import{Box as rt,Text as ge}from"ink";import{jsx as Ae,jsxs as be}from"react/jsx-runtime";var Rn=[{key:"1",label:"Execute"},{key:"2",label:"Copy"},{key:"3",label:"Edit"},{key:"4",label:"Alternatives"},{key:"5",label:"Cancel"}];function Ko({focusedIndex:t,showExplain:e=!0,visible:o=!0}){return o?be(rt,{flexDirection:"column",marginTop:1,children:[Ae(rt,{flexDirection:"row",gap:1,children:Rn.map((r,i)=>{let s=i===t;return be(rt,{children:[be(ge,{color:s?"cyan":"blue",bold:s,inverse:s,children:["[",r.key,"]"]}),be(ge,{color:s?"cyan":void 0,bold:s,children:[" ",r.label]})]},r.key)})}),e&&Ae(rt,{marginTop:1,children:be(ge,{dimColor:!0,children:[Ae(ge,{color:"blue",children:"[?]"})," Explain"," ",Ae(ge,{color:"blue",children:"[O]"})," Toggle output"," ",Ae(ge,{dimColor:!0,children:"| \u2190\u2192 Navigate, Enter Select"})]})})]}):null}function Uo({count:t,focusedIndex:e,visible:o=!0}){return o?Ae(rt,{children:be(ge,{dimColor:!0,children:["Press ",be(ge,{color:"blue",children:["1-",t]})," or ",Ae(ge,{color:"blue",children:"\u2191\u2193"})," to select,"," ",Ae(ge,{color:"blue",children:"[5]"})," Cancel",e>=0&&be(ge,{color:"cyan",children:[" (focused: ",e+1,")"]})]})}):null}import{Box as jt,Text as wn}from"ink";import{Spinner as On}from"@inkjs/ui";import{jsx as qt,jsxs as Ho}from"react/jsx-runtime";function Xt({query:t,label:e="Thinking..."}){return Ho(jt,{flexDirection:"column",marginY:1,children:[qt(jt,{children:qt(On,{label:e})}),t&&qt(jt,{marginTop:1,children:Ho(wn,{dimColor:!0,children:["Query: ",t]})})]})}import{Box as oe,Text as V}from"ink";import{homedir as Nn,userInfo as Bn}from"os";import{jsx as X,jsxs as te}from"react/jsx-runtime";var Dn=[" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E "," \u2502 \u25B6 _ \u2502 "," \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "];function Fo({shell:t,cwd:e,provider:o,model:r}){let i=Bn().username||"user",s=e.replace(Nn(),"~"),a=o||"anthropic",c=F[a].name,h=r||F[a].defaultModel;return te(oe,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1,marginBottom:1,children:[te(oe,{marginBottom:1,children:[X(V,{color:"cyan",bold:!0,children:Ne}),te(V,{dimColor:!0,children:[" v",me]})]}),te(oe,{children:[te(oe,{flexDirection:"column",marginRight:4,children:[te(oe,{marginBottom:1,children:[X(V,{children:"Welcome, "}),X(V,{color:"yellow",bold:!0,children:i}),X(V,{children:"!"})]}),X(oe,{flexDirection:"column",children:Dn.map((g,P)=>X(V,{color:"cyan",children:g},P))}),te(oe,{marginTop:1,flexDirection:"column",children:[te(oe,{children:[X(V,{dimColor:!0,children:"Shell: "}),X(V,{color:"green",children:t})]}),te(oe,{children:[X(V,{dimColor:!0,children:"Path: "}),X(V,{children:s})]})]})]}),te(oe,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,children:[X(oe,{marginBottom:1,children:X(V,{color:"yellow",bold:!0,children:"Quick Start"})}),te(oe,{flexDirection:"column",children:[X(V,{dimColor:!0,children:"Describe what you want in natural language:"}),te(V,{color:"gray",italic:!0,children:[" ",'"list all files modified today"']}),te(V,{color:"gray",italic:!0,children:[" ",'"find large files over 100MB"']}),te(V,{color:"gray",italic:!0,children:[" ",'"show git status"']})]}),X(oe,{marginTop:1,flexDirection:"column",children:te(oe,{children:[X(V,{dimColor:!0,children:"AI: "}),X(V,{color:"magenta",children:c}),X(V,{dimColor:!0,children:" / "}),X(V,{color:"magenta",children:h})]})})]})]})]})}import{useCallback as Rt,useRef as zo,useState as Wn}from"react";import{readdirSync as kn,statSync as Mn}from"fs";import{join as _n,relative as Ln}from"path";var Kn=new Set(["node_modules",".git",".next","dist","build","__pycache__",".venv","venv",".idea",".vscode","coverage",".cache",".npm",".yarn",".pnpm",".turbo",".nuxt",".output","target","vendor",".angular",".svelte-kit"]),Un=new Set([".DS_Store","Thumbs.db",".gitignore",".npmrc",".yarnrc","pnpm-lock.yaml","package-lock.json","yarn.lock"]),Hn=3,Fn=20;function $o(t,e=0){if(e>=Hn)return[];try{let o=kn(t),r=[],i=0;for(let s of o){if(i>=Fn){r.push({name:`... (${o.length-i} more)`,isDirectory:!1});break}if(s.startsWith(".")&&!s.startsWith(".env")||Un.has(s))continue;let a=_n(t,s);try{if(Mn(a).isDirectory()){if(Kn.has(s))continue;let h=$o(a,e+1);r.push({name:s,isDirectory:!0,children:h.length>0?h:void 0})}else r.push({name:s,isDirectory:!1});i++}catch{continue}}return r}catch{return[]}}function Go(t,e=""){let o=[];return t.forEach((r,i)=>{let s=i===t.length-1,a=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=s?" ":"\u2502 ";r.isDirectory?(o.push(`${e}${a}${r.name}/`),r.children&&r.children.length>0&&o.push(Go(r.children,`${e}${c}`))):o.push(`${e}${a}${r.name}`)}),o.join(`
|
|
2
|
+
`)}function Yo(t){let e=$o(t);return e.length===0?"(empty or inaccessible directory)":`${Ln(process.cwd(),t)||"."}/
|
|
3
|
+
${Go(e)}`}import{appendFileSync as $n,writeFileSync as Gn}from"fs";import{join as Yn}from"path";var Vo=process.env.DEBUG==="1"||process.env.DEBUG==="true",jo=Yn(process.cwd(),"debug.log");if(Vo)try{Gn(jo,`=== Debug session started: ${new Date().toISOString()} ===
|
|
4
|
+
`)}catch{}function qo(t,e){if(!Vo)return;let r=`[${new Date().toISOString().slice(11,23)}] ${t}`;e!==void 0&&(r+=`: ${JSON.stringify(e)}`);try{$n(jo,r+`
|
|
5
|
+
`)}catch{}}function Vn(t){let e=t.toLowerCase();for(let o of xo)if(e.includes(o.toLowerCase()))return"high";for(let o of yo)if(e.includes(o.toLowerCase()))return"medium";return"low"}function Qt(t,e){let o=Vn(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}.
|
|
5
6
|
You translate natural language requests into shell commands.
|
|
6
7
|
|
|
7
8
|
IMPORTANT: Output ONLY valid JSON, no markdown, no explanation text.
|
|
@@ -17,29 +18,41 @@ Rules:
|
|
|
17
18
|
2. Use appropriate flags for the target shell
|
|
18
19
|
3. Prefer safe alternatives when possible
|
|
19
20
|
4. For destructive operations, include safety flags (-i for interactive, etc.)
|
|
20
|
-
5. Never include placeholder values - ask for specifics if needed`}function
|
|
21
|
-
`);return
|
|
22
|
-
... (truncated)`:o+"... (truncated)"}function
|
|
21
|
+
5. Never include placeholder values - ask for specifics if needed`}function jn(t,e){if(!t||t.length<=e)return t;let o=t.slice(0,e),r=o.lastIndexOf(`
|
|
22
|
+
`);return r>e*.5?o.slice(0,r)+`
|
|
23
|
+
... (truncated)`:o+"... (truncated)"}function Te(t,e){let o=[];if(o.push(`Current directory: ${e.cwd}`),o.push(`
|
|
23
24
|
Directory structure:
|
|
24
|
-
${
|
|
25
|
-
Conversation context (recent queries and results):`);let
|
|
26
|
-
Query: "${i.query}"`),o.push(`Command: ${i.command}`),i.exitCode!==void 0&&o.push(`Exit code: ${i.exitCode}`),i.output){let s=
|
|
25
|
+
${e.directoryTree}`),e.history.length>0){o.push(`
|
|
26
|
+
Conversation context (recent queries and results):`);let r=e.history.slice(-go);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=jn(i.output,fo);o.push(`Output:
|
|
27
28
|
${s}`)}}return o.push(`
|
|
28
|
-
User request: ${
|
|
29
|
-
`)}function
|
|
29
|
+
User request: ${t}`),o.join(`
|
|
30
|
+
`)}function Ve(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 je(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 qe(t){return new Promise(e=>setTimeout(e,t))}import qn from"@anthropic-ai/sdk";var It=class{client;model;constructor(e,o){this.client=new qn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<z.maxAttempts;r++)try{let s=(await this.client.messages.create({model:this.model,max_tokens:le,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:Ve(s.text)}}catch(i){if(r===z.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(z.baseDelayMs*Math.pow(2,r),z.maxDelayMs);await qe(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
30
31
|
|
|
31
|
-
Generate ${
|
|
32
|
-
Exclude: ${
|
|
32
|
+
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
33
|
+
Exclude: ${r}
|
|
33
34
|
|
|
34
|
-
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let
|
|
35
|
-
${e}`}]})).content.find(
|
|
36
|
-
|
|
37
|
-
`).filter(Boolean);for(let L of V){let G=`[ERR] ${L}`;p.push(G),o?.(L,!0),s(T=>({...T,liveOutput:[...T.liveOutput,G].slice(-t)}))}});let r=await u;a.current=null;let v={command:m,stdout:r.stdout??"",stderr:r.stderr??"",exitCode:r.exitCode??0};return s(S=>({...S,isExecuting:!1})),n?.(v),{success:!0,data:v}}catch(u){a.current=null;let p=u instanceof Error?u:new Error(String(u));s(v=>({...v,isExecuting:!1,error:p}));let r={command:m,stdout:"",stderr:p.message,exitCode:1};return n?.(r),{success:!1,error:p}}},[e,t,o,n]),g=qo(()=>{a.current&&(a.current.kill("SIGINT"),a.current=null,s(m=>({...m,isExecuting:!1,liveOutput:[...m.liveOutput,"[Interrupted]"]})))},[]);return{...i,execute:c,kill:g}}import{useInput as Ur}from"ink";import{useCallback as Wo,useReducer as Hr,useRef as Qo,useState as Qe}from"react";function Vo({mode:e,menuCallbacks:t,selectionCallbacks:o,textCallbacks:n,paletteCallbacks:i,configCallbacks:s,helpCallbacks:a,initialTextValue:c="",paletteQuery:g=""}){let[m,y]=Hr(Co,yo(c)),[d,u]=Qe(0),[p,r]=Qe(0),[v,S]=Qe(0),[V,L]=Qe(0),[G,T]=Qe(0),F=Qo(c);F.current!==c&&(F.current=c,y({type:"set",value:c}));let j=Qo(e);j.current!==e&&(e==="menu"?u(0):e==="selection"?r(0):e==="palette"?S(0):e==="config"&&(L(0),T(0)),j.current=e);let re=Wo(()=>{y({type:"clear"})},[]),R=Wo(b=>{y({type:"set",value:b})},[]);return Ur((b,f)=>{if(e!=="disabled"){if(e==="text"&&n){if(f.ctrl&&!f.meta&&b==="d"){m.value.trim()===""&&process.exit(130);return}if(f.return){let h=m.value.trim();(h.toLowerCase()==="exit"||h.toLowerCase()==="quit")&&process.exit(0),h&&(n.onSubmit(h),y({type:"clear"}));return}if(b.toLowerCase()==="o"&&m.value.trim()===""&&n.onToggleOutput&&n.hasHistory){n.onToggleOutput();return}if(n.hasInlinePalette&&n.onNavigateInlinePalette){if(f.upArrow){n.onNavigateInlinePalette("up");return}if(f.downArrow){n.onNavigateInlinePalette("down");return}}if(f.leftArrow){y({type:"move-left"});return}if(f.rightArrow){y({type:"move-right"});return}if(f.backspace||f.delete){y({type:"delete"});let h=m.value.slice(0,m.cursorOffset-1)+m.value.slice(m.cursorOffset);n.onTextChange?.(h);return}if(f.escape){n.hasInlinePalette&&n.onCloseInlinePalette&&(n.onCloseInlinePalette(),y({type:"clear"}));return}if(f.ctrl||f.meta||f.tab)return;if(b&&b.length>0){y({type:"insert",text:b});let h=m.value.slice(0,m.cursorOffset)+b+m.value.slice(m.cursorOffset);n.onTextChange?.(h)}return}if(e==="menu"&&t){if(f.leftArrow){u(h=>(h-1+5)%5);return}if(f.rightArrow){u(h=>(h+1)%5);return}if(f.return){switch(["execute","copy","edit","alternatives","cancel"][d]){case"execute":t.onExecute();break;case"copy":t.onCopy();break;case"edit":t.onEdit();break;case"alternatives":t.onAlternatives();break;case"cancel":t.onCancel();break}return}if(b>="1"&&b<="5"){let h=parseInt(b,10)-1;switch(["execute","copy","edit","alternatives","cancel"][h]){case"execute":t.onExecute();break;case"copy":t.onCopy();break;case"edit":t.onEdit();break;case"alternatives":t.onAlternatives();break;case"cancel":t.onCancel();break}return}if(b==="?"){t.onExplain();return}if(b.toLowerCase()==="o"){t.onToggle();return}if(f.escape){t.onCancel();return}return}if(e==="selection"&&o){let h=o.count;if(f.upArrow){r(A=>(A-1+h)%h);return}if(f.downArrow){r(A=>(A+1)%h);return}if(f.return){o.onSelect(p);return}let k=parseInt(b,10);if(k>=1&&k<=h){o.onSelect(k-1);return}if(b==="5"||b.toLowerCase()==="c"||f.escape){o.onCancel();return}return}if(e==="palette"&&i){let h=i.filteredCount;if(f.upArrow){S(A=>h===0?0:(A-1+h)%h),i.onNavigate("up");return}if(f.downArrow){S(A=>h===0?0:(A+1)%h),i.onNavigate("down");return}if(f.return){i.onSelect();return}if(f.escape){i.onClose();return}if((f.backspace||f.delete)&&g===""){i.onClose();return}if(f.backspace||f.delete){let A=g.slice(0,-1);i.onQueryChange(A),S(0);return}if(f.ctrl||f.meta||f.tab)return;let k=parseInt(b,10);if(k>=1&&k<=9&&k<=h){S(k-1),i.onSelect();return}if(b&&b.length>0){let A=g+b;i.onQueryChange(A),S(0)}return}if(e==="config"&&s){let h=s.sectionCount,k=s.itemCount;if(f.tab&&!f.shift){L(A=>(A+1)%h),T(0),s.onNavigateSection("next");return}if(f.tab&&f.shift){L(A=>(A-1+h)%h),T(0),s.onNavigateSection("prev");return}if(f.upArrow){T(A=>k===0?0:(A-1+k)%k),s.onNavigateItem("up");return}if(f.downArrow){T(A=>k===0?0:(A+1)%k),s.onNavigateItem("down");return}if(f.return||b===" "){s.onToggle();return}if(f.escape){s.onClose();return}return}if(e==="help"&&a){if(f.escape){a.onClose();return}return}}},{isActive:e!=="disabled"}),{textState:m,dispatchText:y,clearText:re,setText:R,menuFocusIndex:d,selectionFocusIndex:p,paletteFocusIndex:v,configSectionIndex:V,configItemIndex:G}}import{useCallback as O,useReducer as Fr}from"react";var $r={state:{status:"setup"},history:[],currentQuery:"",editingCommand:null,outputExpanded:!1,error:null};function Yr(e,t){switch(t.type){case"SETUP_COMPLETE":return{...e,state:{status:"input"},error:null};case"SUBMIT":return{...e,state:{status:"loading",query:t.query},currentQuery:t.query,editingCommand:null,error:null};case"AI_RESPONSE":return{...e,state:{status:"proposal",proposal:t.proposal},error:null};case"AI_ALTERNATIVES":return{...e,state:{status:"alternatives",proposals:t.proposals,originalQuery:e.currentQuery},error:null};case"AI_ERROR":return{...e,state:{status:"input"},error:t.error.message};case"EXECUTE":{let o=e.state;return o.status!=="proposal"?e:{...e,state:{status:"executing",command:o.proposal.command},error:null}}case"EXECUTE_EDITED":return{...e,state:{status:"executing",command:t.command},editingCommand:null,error:null};case"EXEC_DONE":{let o=[...e.history,{query:e.currentQuery,command:t.result.command,output:t.result.stdout||t.result.stderr,exitCode:t.result.exitCode}].slice(-he.maxHistoryEntries);return{...e,state:{status:"input"},history:o,outputExpanded:!1,error:null}}case"COPY":return{...e,state:{status:"input"},error:null};case"EDIT":return{...e,state:{status:"input"},editingCommand:t.command,error:null};case"CANCEL":return{...e,state:{status:"input"},editingCommand:null,error:null};case"TOGGLE_OUTPUT":return e.history.length===0?e:{...e,outputExpanded:!e.outputExpanded};case"OPEN_PALETTE":return{...e,state:{status:"palette",query:"",filteredCommands:[]},error:null};case"UPDATE_PALETTE":return{...e,state:{status:"palette",query:t.query,filteredCommands:t.filteredCommands}};case"CLOSE_PALETTE":return{...e,state:{status:"input"},error:null};case"OPEN_CONFIG":return{...e,state:{status:"config",section:"api-key"},error:null};case"UPDATE_CONFIG_SECTION":return{...e,state:{status:"config",section:t.section}};case"CLOSE_CONFIG":return{...e,state:{status:"input"},error:null};case"OPEN_HELP":return{...e,state:{status:"help"},error:null};case"CLOSE_HELP":return{...e,state:{status:"input"},error:null};case"CLEAR_HISTORY":return{...e,state:{status:"input"},history:[],outputExpanded:!1,error:null};default:return e}}function zo(){let[e,t]=Fr(Yr,$r),o=O(R=>{t({type:"SUBMIT",query:R})},[]),n=O(R=>{t({type:"AI_RESPONSE",proposal:R})},[]),i=O(R=>{t({type:"AI_ALTERNATIVES",proposals:R})},[]),s=O(R=>{t({type:"AI_ERROR",error:R})},[]),a=O(()=>{t({type:"EXECUTE"})},[]),c=O(R=>{t({type:"EXECUTE_EDITED",command:R})},[]),g=O(R=>{t({type:"EXEC_DONE",result:R})},[]),m=O(()=>{t({type:"COPY"})},[]),y=O(R=>{t({type:"EDIT",command:R})},[]),d=O(()=>{t({type:"CANCEL"})},[]),u=O(()=>{t({type:"TOGGLE_OUTPUT"})},[]),p=O(()=>{t({type:"SETUP_COMPLETE"})},[]),r=O(()=>{t({type:"EDIT",command:""})},[]),v=O(()=>{t({type:"OPEN_PALETTE"})},[]),S=O((R,b)=>{t({type:"UPDATE_PALETTE",query:R,filteredCommands:b})},[]),V=O(()=>{t({type:"CLOSE_PALETTE"})},[]),L=O(()=>{t({type:"OPEN_CONFIG"})},[]),G=O(R=>{t({type:"UPDATE_CONFIG_SECTION",section:R})},[]),T=O(()=>{t({type:"CLOSE_CONFIG"})},[]),F=O(()=>{t({type:"OPEN_HELP"})},[]),j=O(()=>{t({type:"CLOSE_HELP"})},[]),re=O(()=>{t({type:"CLEAR_HISTORY"})},[]);return{store:e,dispatch:t,submitQuery:o,handleAIResponse:n,handleAIAlternatives:i,handleAIError:s,execute:a,executeEdited:c,markExecutionDone:g,copy:m,edit:y,cancel:d,toggleOutput:u,completeSetup:p,clearEditingCommand:r,openPalette:v,updatePalette:S,closePalette:V,openConfig:L,updateConfigSection:G,closeConfig:T,openHelp:F,closeHelp:j,clearHistory:re}}import Gr from"clipboardy";async function Jo(e){try{return await Gr.write(e),{success:!0,data:{success:!0,message:"Copied to clipboard"}}}catch(t){return{success:!1,error:t instanceof Error?t:new Error("Failed to copy to clipboard")}}}import{Box as w,Static as jr,Text as I,useApp as qr}from"ink";import{useCallback as _,useEffect as Zo,useMemo as Le,useState as ye}from"react";import{Fragment as Xr,jsx as x,jsxs as B}from"react/jsx-runtime";function en(){let{exit:e}=qr(),t=Go(),[o,n]=ye(null),[i,s]=ye(null),[a,c]=ye([]),[g,m]=ye(0),{isLoading:y,hasKey:d,error:u,refreshKeyStatus:p}=Yo(),{store:r,submitQuery:v,handleAIResponse:S,handleAIAlternatives:V,handleAIError:L,execute:G,executeEdited:T,markExecutionDone:F,copy:j,edit:re,cancel:R,toggleOutput:b,completeSetup:f,openPalette:h,updatePalette:k,closePalette:A,openConfig:tn,updateConfigSection:Ft,closeConfig:ke,openHelp:on,closeHelp:nn,clearHistory:rn}=zo(),[ve,ft]=ye(0),[be,sn]=ye(()=>De().model),[gt,an]=ye(()=>({contextEnabled:De().contextEnabled,showExplanations:!0,syntaxHighlighting:!0,simpleMode:!1})),[ln,$t]=ye(!1),cn=Le(()=>Do(),[d]),un=Le(()=>{let l=ge();return l?l.length<=12?"***":`${l.slice(0,7)}...${l.slice(-4)}`:null},[d]),Yt=Le(()=>({model:be,contextEnabled:gt.contextEnabled,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3}),[be]),q=$o({sessionStatus:r.state.status,config:Yt,updateConfig:()=>{},onOpenConfig:tn,onOpenHelp:on,onClearHistory:rn,onExit:()=>e()}),pn=Le(()=>{let l=[{id:"header",type:"header"}];return r.history.slice(0,-1).forEach((E,M)=>{l.push({id:`history-${M}`,type:"history",entry:E})}),l},[r.history]),ae=r.history.length>0?r.history[r.history.length-1]:null,{generate:Gt,getAlternatives:jt,explain:qt,isLoading:Pe}=Ho({shell:t,history:r.history,contextEnabled:gt.contextEnabled}),{execute:Ve,kill:es,isExecuting:xt,liveOutput:mn}=Xo({shell:t,onComplete:F}),dn=Le(()=>y||!d||r.state.status==="setup"||r.state.status==="loading"||r.state.status==="executing"||xt?"disabled":r.state.status==="palette"?"palette":r.state.status==="config"?"config":r.state.status==="help"?"help":r.state.status==="proposal"?Pe?"disabled":"menu":r.state.status==="alternatives"?Pe?"disabled":"selection":r.state.status==="input"?"text":"disabled",[y,d,r.state.status,xt,Pe]),fn=_(l=>{mt(l).success&&(p(),$t(!1),f())},[p,f]);Zo(()=>{!y&&d&&r.state.status==="setup"&&f()},[y,d,r.state.status,f]),Zo(()=>{let l=De().model;be!==l&&We({model:be})},[be]);let gn=_(l=>{if(l.startsWith("/")){let C=l.slice(1),E=z.filter(C);c(E),m(0)}else c([]),m(0)},[]),xn=_(async l=>{if(l.startsWith("/")){let E=l.slice(1).trim();if(a.length>0){let M=a[g];if(M&&q.executeCommand(M.name)){c([]),m(0);return}}if(E&&q.executeCommand(E)){c([]),m(0);return}c([]),m(0);return}if(c([]),m(0),r.editingCommand){T(l),await Ve(l);return}v(l),s(null);let C=await Gt(l);C.success?S(C.data):L(C.error)},[r.editingCommand,v,Gt,S,L,T,Ve,q,a,g]),yn=_(async()=>{r.state.status==="proposal"&&(G(),await Ve(r.state.proposal.command))},[r.state,G,Ve]),Cn=_(async()=>{if(r.state.status!=="proposal")return;(await Jo(r.state.proposal.command)).success?(n("\u2713 Copied to clipboard"),setTimeout(()=>n(null),2e3)):(n("\u2717 Failed to copy"),setTimeout(()=>n(null),2e3)),j()},[r.state,j]),hn=_(()=>{r.state.status==="proposal"&&re(r.state.proposal.command)},[r.state,re]),Tn=_(async()=>{if(r.state.status!=="proposal")return;let l=await jt(r.currentQuery,r.state.proposal.command);l.success?V(l.data):L(l.error)},[r.state,r.currentQuery,jt,V,L]),Sn=_(()=>{R(),s(null)},[R]),En=_(async()=>{if(r.state.status!=="proposal")return;let l=await qt(r.state.proposal.command);l.success&&s(l.data)},[r.state,qt]),vn=_(()=>{b()},[b]),bn=_(l=>{if(r.state.status!=="alternatives")return;let C=r.state.proposals[l];C&&S(C)},[r.state,S]),Pn=_(l=>{let C=z.filter(l);q.setQuery(l),k(l,C)},[q,k]),In=_(()=>{q.executeSelected()&&(A(),q.reset())},[q,A]),An=_(l=>{l==="up"?q.focusUp():q.focusDown()},[q]),wn=_(()=>{A(),q.reset()},[A,q]),Rn=_(l=>{let C=["api-key","model","toggles","about"];if(r.state.status!=="config")return;let E=C.indexOf(r.state.section),M;l==="next"?M=(E+1)%C.length:M=(E-1+C.length)%C.length,Ft(C[M]),ft(0)},[r.state,Ft]),On=_(l=>{let C={"api-key":d?2:1,model:3,toggles:4,about:0};if(r.state.status!=="config")return;let E=C[r.state.section];E!==0&&ft(M=>l==="up"?(M-1+E)%E:(M+1)%E)},[r.state,d]),Bn=_(()=>{if(r.state.status==="config"){if(r.state.section==="toggles"){an(l=>{let E=["contextEnabled","showExplanations","syntaxHighlighting","simpleMode"][ve];if(E){let M=!l[E];return E==="contextEnabled"&&We({contextEnabled:M}),{...l,[E]:M}}return l});return}if(r.state.section==="model"){let C=["claude-sonnet-4-5","claude-opus-4-5","claude-haiku-4-5"][ve];C&&sn(C);return}if(r.state.section==="api-key"){ve===0?(ke(),$t(!0)):ve===1&&d&&Bo().success&&(p(),ke());return}}},[r.state,ve,ke,d,p]),Nn=_(()=>{ke(),ft(0)},[ke]),Dn=r.state.status==="palette"?r.state.query:"",Ln=Le(()=>r.state.status!=="config"?0:{"api-key":d?2:1,model:3,toggles:4,about:0}[r.state.section],[r.state,d]),{textState:kn,clearText:ts,setText:os,menuFocusIndex:_n,selectionFocusIndex:Mn,paletteFocusIndex:Kn,configSectionIndex:ns}=Vo({mode:dn,initialTextValue:r.editingCommand??"",paletteQuery:Dn,menuCallbacks:{onExecute:yn,onCopy:Cn,onEdit:hn,onAlternatives:Tn,onCancel:Sn,onExplain:En,onToggle:vn},selectionCallbacks:{onSelect:bn,onCancel:R,count:r.state.status==="alternatives"?r.state.proposals.length:1},textCallbacks:{onSubmit:xn,onToggleOutput:b,onTextChange:gn,onNavigateInlinePalette:l=>{m(C=>{let E=a.length;return E===0?0:l==="up"?(C-1+E)%E:(C+1)%E})},onCloseInlinePalette:()=>{c([]),m(0)},hasInlinePalette:a.length>0,hasHistory:r.history.length>0},paletteCallbacks:{onQueryChange:Pn,onSelect:In,onNavigate:An,onClose:wn,filteredCount:r.state.status==="palette"?r.state.filteredCommands.length:0},configCallbacks:{onNavigateSection:Rn,onNavigateItem:On,onToggle:Bn,onClose:Nn,sectionCount:4,itemCount:Ln},helpCallbacks:{onClose:nn}});return y?x(w,{flexDirection:"column",paddingY:1,children:x(I,{dimColor:!0,children:"Loading configuration..."})}):ln||!d&&r.state.status==="setup"?x(oo,{onComplete:fn,error:u}):B(w,{flexDirection:"column",children:[x(jr,{items:pn,children:l=>l.type==="header"?x(vo,{shell:t,cwd:process.cwd(),model:be},l.id):l.type==="history"?B(w,{flexDirection:"column",marginBottom:1,children:[B(w,{children:[x(I,{color:"cyan",bold:!0,children:"\u276F "}),x(I,{color:"cyan",children:l.entry.query})]}),B(w,{marginLeft:2,flexDirection:"column",children:[B(w,{children:[B(I,{dimColor:!0,children:["$ ",l.entry.command," "]}),x(I,{color:l.entry.exitCode===0?"green":"red",children:l.entry.exitCode===0?"\u2713":`\u2717 ${l.entry.exitCode}`})]}),l.entry.output&&B(w,{flexDirection:"column",children:[l.entry.output.split(`
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
`)
|
|
42
|
-
|
|
35
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.messages.create({model:this.model,max_tokens:le*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:je(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:le,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 Xn from"openai";var bt=class{client;model;constructor(e,o){this.client=new Xn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<z.maxAttempts;r++)try{let s=(await this.client.chat.completions.create({model:this.model,max_tokens:le,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:Ve(s)}}catch(i){if(r===z.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(z.baseDelayMs*Math.pow(2,r),z.maxDelayMs);await qe(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
37
|
+
|
|
38
|
+
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
39
|
+
Exclude: ${r}
|
|
40
|
+
|
|
41
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.completions.create({model:this.model,max_tokens:le*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:je(c)}}catch(a){return{success:!1,error:a instanceof Error?a:new Error(String(a))}}}async explainCommand(e){try{let r=(await this.client.chat.completions.create({model:this.model,max_tokens:le,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 Qn}from"@openrouter/sdk";var At=class{client;model;constructor(e,o){this.client=new Qn({apiKey:e}),this.model=o}async generateCommand(e,o){for(let r=0;r<z.maxAttempts;r++)try{let s=(await this.client.chat.send({model:this.model,maxTokens:le,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:Ve(s)}}catch(i){if(r===z.maxAttempts-1)return{success:!1,error:i instanceof Error?i:new Error(String(i))};let s=Math.min(z.baseDelayMs*Math.pow(2,r),z.maxDelayMs);await qe(s)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,o,r,i){let s=`${Te(e,o)}
|
|
43
|
+
|
|
44
|
+
Generate ${i} ALTERNATIVE commands (different approaches).
|
|
45
|
+
Exclude: ${r}
|
|
46
|
+
|
|
47
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let c=(await this.client.chat.send({model:this.model,maxTokens:le*2,messages:[{role:"system",content:Ce(o.shell)},{role:"user",content:s}]})).choices?.[0]?.message?.content;if(!c||typeof c!="string")throw new Error("No content in AI response");return{success:!0,data:je(c)}}catch(a){return{success:!1,error:a instanceof Error?a:new Error(String(a))}}}async explainCommand(e){try{let r=(await this.client.chat.send({model:this.model,maxTokens:le,messages:[{role:"user",content:`Explain this command briefly (2-3 sentences max):
|
|
48
|
+
${e}`}]})).choices?.[0]?.message?.content;if(!r||typeof r!="string")throw new Error("No content in AI response");return{success:!0,data:r.trim()}}catch(o){return{success:!1,error:o instanceof Error?o:new Error(String(o))}}}};function Xo(t,e,o){switch(qo(`Creating provider: ${t}/${o}`),t){case"anthropic":return new It(e,o);case"openai":return new bt(e,o);case"openrouter":return new At(e,o)}}var Wt=null;function Jt(){let t=de(),e=Le(t.provider);if(!e)return null;let o=`${t.provider}:${t.model}:${e.slice(-4)}`;if(Wt?.key===o)return Wt.instance;let r=Xo(t.provider,e,t.model);return Wt={key:o,instance:r},r}async function Qo(t,e){let o=Jt();return o?o.generateCommand(t,e):{success:!1,error:new Error("No API key configured")}}async function Wo(t,e,o,r=3){let i=Jt();return i?i.generateAlternatives(t,e,o,r):{success:!1,error:new Error("No API key configured")}}async function Jo(t){let e=Jt();return e?e.explainCommand(t):{success:!1,error:new Error("No API key configured")}}function zt(t,e=[]){let o=process.cwd();return{shell:t,cwd:o,platform:process.platform,directoryTree:Yo(o),history:e}}function Zo({shell:t,history:e=[],contextEnabled:o=!0}){let[r,i]=Wn({isLoading:!1,error:null,lastProposal:null}),s=zo(e);s.current=e;let a=zo(o);a.current=o;let c=Rt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=a.current?s.current:[],f=zt(t,m),n=await Qo(y,f);return n.success?i(T=>({...T,isLoading:!1,lastProposal:n.data})):i(T=>({...T,isLoading:!1,error:n.error})),n}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[t]),h=Rt(async(y,m)=>{i(f=>({...f,isLoading:!0,error:null}));try{let f=a.current?s.current:[],n=zt(t,f),T=await Wo(y,n,m);return i(v=>({...v,isLoading:!1})),T.success||i(v=>({...v,error:T.error})),T}catch(f){let n=f instanceof Error?f:new Error(String(f));return i(T=>({...T,isLoading:!1,error:n})),{success:!1,error:n}}},[t]),g=Rt(async y=>{i(m=>({...m,isLoading:!0,error:null}));try{let m=await Jo(y);return i(f=>({...f,isLoading:!1})),m.success||i(f=>({...f,error:m.error})),m}catch(m){let f=m instanceof Error?m:new Error(String(m));return i(n=>({...n,isLoading:!1,error:f})),{success:!1,error:f}}},[]),P=Rt(()=>{i(y=>({...y,error:null}))},[]);return{...r,generate:c,getAlternatives:h,explain:g,clearError:P}}import{useCallback as Re,useMemo as Jn,useState as er}from"react";function tr({sessionStatus:t,config:e,updateConfig:o,onOpenConfig:r,onOpenHelp:i,onClearHistory:s,onExit:a}){let[c,h]=er(""),[g,P]=er(0),y=Jn(()=>ae.filter(c).filter(Z=>!Z.isAvailable||Z.isAvailable(t)),[c,t]),m=Re(x=>{h(x),P(0)},[]),f=Re(()=>{P(x=>y.length===0?0:(x-1+y.length)%y.length)},[y.length]),n=Re(()=>{P(x=>y.length===0?0:(x+1)%y.length)},[y.length]),T=Re(()=>({sessionStatus:t,config:e,updateConfig:o,exit:a}),[t,e,o,a]),v=Re(x=>{switch(x.type){case"panel":x.panel==="config"?r():x.panel==="help"&&i();break;case"navigate":x.to==="clear"&&s();break;case"exit":a();break}return x},[r,i,s,a]),I=Re(()=>{if(y.length===0)return null;let x=y[g];if(!x)return null;let Z=T(),W=x.execute(Z);return W instanceof Promise?(W.then(v),null):v(W)},[y,g,T,v]),d=Re(x=>{let Z=ae.get(x);if(!Z||Z.isAvailable&&!Z.isAvailable(t))return null;let W=T(),ue=Z.execute(W);return ue instanceof Promise?(ue.then(v),null):v(ue)},[t,T,v]),A=Re(()=>{h(""),P(0)},[]);return{query:c,setQuery:m,filteredCommands:y,focusedIndex:g,focusUp:f,focusDown:n,executeSelected:I,executeCommand:d,reset:A}}import{useCallback as Zt,useEffect as zn,useState as Zn}from"react";function or(){let[t,e]=Zn({isLoading:!0,hasKey:!1,config:de(),error:null});zn(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,isLoading:!1,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,isLoading:!1,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);let o=Zt((s,a)=>{if(!gt(s,a))return e(c=>({...c,error:`Invalid API key format for ${s}`})),!1;try{let c=ft(s,a);return c.success?(e(h=>({...h,hasKey:!0,error:null})),!0):(e(h=>({...h,error:c.error.message})),!1)}catch(c){return e(h=>({...h,error:c instanceof Error?c.message:"Failed to save API key"})),!1}},[]),r=Zt(s=>{he(s),e(a=>({...a,config:{...a.config,...s}}))},[]),i=Zt(()=>{try{let s=de(),a=Ke(s.provider);e(c=>({...c,hasKey:a,config:s,error:null}))}catch(s){e(a=>({...a,error:s instanceof Error?s.message:"Failed to check API key"}))}},[]);return{...t,saveKey:o,updateConfig:r,refreshKeyStatus:i}}import{execa as es}from"execa";import{useCallback as sr,useRef as ts,useState as os}from"react";function rr(){if(process.platform==="win32")return process.env.MSYSTEM||process.env.MINGW_PREFIX?"bash":process.env.PSModulePath?.includes("PowerShell\\7")?"pwsh":process.env.PSModulePath?"powershell":"cmd";let t=process.env.SHELL??"/bin/bash";return t.includes("zsh")?"zsh":t.includes("fish")?"fish":"bash"}function nr(t,e){switch(t){case"powershell":return{cmd:"powershell",args:["-Command",e]};case"pwsh":return{cmd:"pwsh",args:["-Command",e]};case"cmd":return{cmd:"cmd",args:["/c",e]};default:return{cmd:t,args:["-c",e]}}}function ir({shell:t,maxOutputLines:e=Be.maxOutputLines,onOutput:o,onComplete:r}){let[i,s]=os({isExecuting:!1,liveOutput:[],error:null}),a=ts(null),c=sr(async g=>{s({isExecuting:!0,liveOutput:[],error:null});let{cmd:P,args:y}=nr(t,g);try{let m=es(P,y,{reject:!1,all:!0,buffer:!0});a.current=m;let f=[];m.stdout&&m.stdout.on("data",v=>{let I=v.toString().split(`
|
|
49
|
+
`).filter(Boolean);for(let d of I)f.push(d),o?.(d,!1),s(A=>({...A,liveOutput:[...A.liveOutput,d].slice(-e)}))}),m.stderr&&m.stderr.on("data",v=>{let I=v.toString().split(`
|
|
50
|
+
`).filter(Boolean);for(let d of I){let A=`[ERR] ${d}`;f.push(A),o?.(d,!0),s(x=>({...x,liveOutput:[...x.liveOutput,A].slice(-e)}))}});let n=await m;a.current=null;let T={command:g,stdout:n.stdout??"",stderr:n.stderr??"",exitCode:n.exitCode??0};return s(v=>({...v,isExecuting:!1})),r?.(T),{success:!0,data:T}}catch(m){a.current=null;let f=m instanceof Error?m:new Error(String(m));s(T=>({...T,isExecuting:!1,error:f}));let n={command:g,stdout:"",stderr:f.message,exitCode:1};return r?.(n),{success:!1,error:f}}},[t,e,o,r]),h=sr(()=>{a.current&&(a.current.kill("SIGINT"),a.current=null,s(g=>({...g,isExecuting:!1,liveOutput:[...g.liveOutput,"[Interrupted]"]})))},[]);return{...i,execute:c,kill:h}}import{useInput as rs}from"ink";import{useCallback as ar,useReducer as lr,useRef as cr,useState as nt}from"react";function ur({mode:t,menuCallbacks:e,selectionCallbacks:o,textCallbacks:r,paletteCallbacks:i,configCallbacks:s,helpCallbacks:a,initialTextValue:c="",paletteQuery:h=""}){let[g,P]=lr($t,Ft(c)),[y,m]=lr($t,Ft("")),[f,n]=nt(0),[T,v]=nt(0),[I,d]=nt(0),[A,x]=nt(0),[Z,W]=nt(0),ue=cr(c);ue.current!==c&&(ue.current=c,P({type:"set",value:c}));let k=cr(t);k.current!==t&&(t==="menu"?n(0):t==="selection"?v(0):t==="palette"?d(0):t==="config"&&(x(0),W(0)),k.current=t);let we=ar(()=>{P({type:"clear"})},[]),ke=ar(D=>{P({type:"set",value:D})},[]);return rs((D,u)=>{if(t!=="disabled"){if(t==="text"&&r){if(u.ctrl&&!u.meta&&D==="d"){g.value.trim()===""&&process.exit(130);return}if(u.return){let S=g.value.trim();(S.toLowerCase()==="exit"||S.toLowerCase()==="quit")&&process.exit(0),S&&(r.onSubmit(S),P({type:"clear"}));return}if(D.toLowerCase()==="o"&&g.value.trim()===""&&r.onToggleOutput&&r.hasHistory){r.onToggleOutput();return}if(r.hasInlinePalette&&r.onNavigateInlinePalette){if(u.upArrow){r.onNavigateInlinePalette("up");return}if(u.downArrow){r.onNavigateInlinePalette("down");return}}if(u.leftArrow){P({type:"move-left"});return}if(u.rightArrow){P({type:"move-right"});return}if(u.backspace||u.delete){P({type:"delete"});let S=g.value.slice(0,g.cursorOffset-1)+g.value.slice(g.cursorOffset);r.onTextChange?.(S);return}if(u.escape){r.hasInlinePalette&&r.onCloseInlinePalette&&(r.onCloseInlinePalette(),P({type:"clear"}));return}if(u.ctrl||u.meta||u.tab)return;if(D&&D.length>0){P({type:"insert",text:D});let S=g.value.slice(0,g.cursorOffset)+D+g.value.slice(g.cursorOffset);r.onTextChange?.(S)}return}if(t==="menu"&&e){if(u.leftArrow){n(S=>(S-1+5)%5);return}if(u.rightArrow){n(S=>(S+1)%5);return}if(u.return){switch(["execute","copy","edit","alternatives","cancel"][f]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D>="1"&&D<="5"){let S=parseInt(D,10)-1;switch(["execute","copy","edit","alternatives","cancel"][S]){case"execute":e.onExecute();break;case"copy":e.onCopy();break;case"edit":e.onEdit();break;case"alternatives":e.onAlternatives();break;case"cancel":e.onCancel();break}return}if(D==="?"){e.onExplain();return}if(D.toLowerCase()==="o"){e.onToggle();return}if(u.escape){e.onCancel();return}return}if(t==="selection"&&o){let S=o.count;if(u.upArrow){v(w=>(w-1+S)%S);return}if(u.downArrow){v(w=>(w+1)%S);return}if(u.return){o.onSelect(T);return}let q=parseInt(D,10);if(q>=1&&q<=S){o.onSelect(q-1);return}if(D==="5"||D.toLowerCase()==="c"||u.escape){o.onCancel();return}return}if(t==="palette"&&i){let S=i.filteredCount;if(u.upArrow){d(w=>S===0?0:(w-1+S)%S),i.onNavigate("up");return}if(u.downArrow){d(w=>S===0?0:(w+1)%S),i.onNavigate("down");return}if(u.return){i.onSelect();return}if(u.escape){i.onClose();return}if((u.backspace||u.delete)&&h===""){i.onClose();return}if(u.backspace||u.delete){let w=h.slice(0,-1);i.onQueryChange(w),d(0);return}if(u.ctrl||u.meta||u.tab)return;let q=parseInt(D,10);if(q>=1&&q<=9&&q<=S){d(q-1),i.onSelect();return}if(D&&D.length>0){let w=h+D;i.onQueryChange(w),d(0)}return}if(t==="config"&&s){let S=s.sectionCount,q=s.itemCount;if(s.isEditingCustomModel){if(u.escape){m({type:"clear"}),s.onCustomModelCancel?.();return}if(u.return){let w=y.value;w.trim()?s.onCustomModelSubmit?.(w.trim()):s.onCustomModelCancel?.(),m({type:"clear"});return}if(u.leftArrow){m({type:"move-left"});return}if(u.rightArrow){m({type:"move-right"});return}if(u.backspace||u.delete){m({type:"delete"});return}if(!u.ctrl&&!u.meta&&!u.tab&&D&&D.length>0){m({type:"insert",text:D});return}return}if(u.tab&&!u.shift){x(w=>(w+1)%S),W(0),s.onNavigateSection("next");return}if(u.tab&&u.shift){x(w=>(w-1+S)%S),W(0),s.onNavigateSection("prev");return}if(u.upArrow){W(w=>q===0?0:(w-1+q)%q),s.onNavigateItem("up");return}if(u.downArrow){W(w=>q===0?0:(w+1)%q),s.onNavigateItem("down");return}if(u.return||D===" "){s.onToggle();return}if(u.escape){s.onClose();return}return}if(t==="help"&&a){if(u.escape){a.onClose();return}return}}},{isActive:t!=="disabled"}),{textState:g,dispatchText:P,clearText:we,setText:ke,menuFocusIndex:f,selectionFocusIndex:T,paletteFocusIndex:I,configSectionIndex:A,configItemIndex:Z,customModelState:y,dispatchCustomModel:m}}import{useCallback as H,useReducer as ns}from"react";var ss={state:{status:"setup"},history:[],currentQuery:"",editingCommand:null,outputExpanded:!1,error:null};function is(t,e){switch(e.type){case"SETUP_COMPLETE":return{...t,state:{status:"input"},error:null};case"SUBMIT":return{...t,state:{status:"loading",query:e.query},currentQuery:e.query,editingCommand:null,error:null};case"AI_RESPONSE":return{...t,state:{status:"proposal",proposal:e.proposal},error:null};case"AI_ALTERNATIVES":return{...t,state:{status:"alternatives",proposals:e.proposals,originalQuery:t.currentQuery},error:null};case"AI_ERROR":return{...t,state:{status:"input"},error:e.error.message};case"EXECUTE":{let o=t.state;return o.status!=="proposal"?t:{...t,state:{status:"executing",command:o.proposal.command},error:null}}case"EXECUTE_EDITED":return{...t,state:{status:"executing",command:e.command},editingCommand:null,error:null};case"EXEC_DONE":{let o=[...t.history,{query:t.currentQuery,command:e.result.command,output:e.result.stdout||e.result.stderr,exitCode:e.result.exitCode}].slice(-Be.maxHistoryEntries);return{...t,state:{status:"input"},history:o,outputExpanded:!1,error:null}}case"COPY":return{...t,state:{status:"input"},error:null};case"EDIT":return{...t,state:{status:"input"},editingCommand:e.command,error:null};case"CANCEL":return{...t,state:{status:"input"},editingCommand:null,error:null};case"TOGGLE_OUTPUT":return t.history.length===0?t:{...t,outputExpanded:!t.outputExpanded};case"OPEN_PALETTE":return{...t,state:{status:"palette",query:"",filteredCommands:[]},error:null};case"UPDATE_PALETTE":return{...t,state:{status:"palette",query:e.query,filteredCommands:e.filteredCommands}};case"CLOSE_PALETTE":return{...t,state:{status:"input"},error:null};case"OPEN_CONFIG":return{...t,state:{status:"config",section:"provider"},error:null};case"UPDATE_CONFIG_SECTION":return{...t,state:{status:"config",section:e.section}};case"CLOSE_CONFIG":return{...t,state:{status:"input"},error:null};case"OPEN_HELP":return{...t,state:{status:"help"},error:null};case"CLOSE_HELP":return{...t,state:{status:"input"},error:null};case"CLEAR_HISTORY":return{...t,state:{status:"input"},history:[],outputExpanded:!1,error:null};default:return t}}function pr(){let[t,e]=ns(is,ss),o=H(k=>{e({type:"SUBMIT",query:k})},[]),r=H(k=>{e({type:"AI_RESPONSE",proposal:k})},[]),i=H(k=>{e({type:"AI_ALTERNATIVES",proposals:k})},[]),s=H(k=>{e({type:"AI_ERROR",error:k})},[]),a=H(()=>{e({type:"EXECUTE"})},[]),c=H(k=>{e({type:"EXECUTE_EDITED",command:k})},[]),h=H(k=>{e({type:"EXEC_DONE",result:k})},[]),g=H(()=>{e({type:"COPY"})},[]),P=H(k=>{e({type:"EDIT",command:k})},[]),y=H(()=>{e({type:"CANCEL"})},[]),m=H(()=>{e({type:"TOGGLE_OUTPUT"})},[]),f=H(()=>{e({type:"SETUP_COMPLETE"})},[]),n=H(()=>{e({type:"EDIT",command:""})},[]),T=H(()=>{e({type:"OPEN_PALETTE"})},[]),v=H((k,we)=>{e({type:"UPDATE_PALETTE",query:k,filteredCommands:we})},[]),I=H(()=>{e({type:"CLOSE_PALETTE"})},[]),d=H(()=>{e({type:"OPEN_CONFIG"})},[]),A=H(k=>{e({type:"UPDATE_CONFIG_SECTION",section:k})},[]),x=H(()=>{e({type:"CLOSE_CONFIG"})},[]),Z=H(()=>{e({type:"OPEN_HELP"})},[]),W=H(()=>{e({type:"CLOSE_HELP"})},[]),ue=H(()=>{e({type:"CLEAR_HISTORY"})},[]);return{store:t,dispatch:e,submitQuery:o,handleAIResponse:r,handleAIAlternatives:i,handleAIError:s,execute:a,executeEdited:c,markExecutionDone:h,copy:g,edit:P,cancel:y,toggleOutput:m,completeSetup:f,clearEditingCommand:n,openPalette:T,updatePalette:v,closePalette:I,openConfig:d,updateConfigSection:A,closeConfig:x,openHelp:Z,closeHelp:W,clearHistory:ue}}import as from"clipboardy";async function mr(t){try{return await as.write(t),{success:!0,data:{success:!0,message:"Copied to clipboard"}}}catch(e){return{success:!1,error:e instanceof Error?e:new Error("Failed to copy to clipboard")}}}import{Box as _,Static as ls,Text as B,useApp as cs}from"ink";import{useCallback as j,useEffect as eo,useMemo as Xe,useState as xe}from"react";import{Fragment as us,jsx as C,jsxs as U}from"react/jsx-runtime";function dr(){let{exit:t}=cs(),e=rr(),[o,r]=xe(null),[i,s]=xe(null),[a,c]=xe([]),[h,g]=xe(0),{isLoading:P,hasKey:y,error:m,refreshKeyStatus:f}=or(),{store:n,submitQuery:T,handleAIResponse:v,handleAIAlternatives:I,handleAIError:d,execute:A,executeEdited:x,markExecutionDone:Z,copy:W,edit:ue,cancel:k,toggleOutput:we,completeSetup:ke,openPalette:D,updatePalette:u,closePalette:S,openConfig:q,updateConfigSection:w,closeConfig:st,openHelp:fr,closeHelp:gr,clearHistory:xr}=pr(),[ve,it]=xe(0),[pe,at]=xe(()=>de().model),[lt,yr]=xe(()=>({contextEnabled:de().contextEnabled,showExplanations:!0,syntaxHighlighting:!0,simpleMode:!1})),[hr,to]=xe(!1),[Cr,oo]=xe(null),[Me,Oe]=xe(!1),[J,ro]=xe(()=>de().provider),Tr=Xe(()=>Eo(J),[y,J]),vr=Xe(()=>{let l=Le(J);return l?l.length<=12?"***":`${l.slice(0,7)}...${l.slice(-4)}`:null},[y,J]),no=Xe(()=>({provider:J,model:pe,contextEnabled:lt.contextEnabled,maxHistoryEntries:5,maxOutputLines:10,maxAlternatives:3}),[J,pe,lt.contextEnabled]),re=tr({sessionStatus:n.state.status,config:no,updateConfig:()=>{},onOpenConfig:q,onOpenHelp:fr,onClearHistory:xr,onExit:()=>t()}),Sr=Xe(()=>{let l=[];return n.history.slice(0,-1).forEach((b,L)=>{l.push({id:`history-${L}`,type:"history",entry:b})}),l},[n.history]),Se=n.history.length>0?n.history[n.history.length-1]:null,{generate:so,getAlternatives:io,explain:ao,isLoading:_e}=Zo({shell:e,history:n.history,contextEnabled:lt.contextEnabled}),{execute:ct,kill:ys,isExecuting:wt,liveOutput:Er}=ir({shell:e,onComplete:Z}),Pr=Xe(()=>P||!y||n.state.status==="setup"||n.state.status==="loading"||n.state.status==="executing"||wt?"disabled":n.state.status==="palette"?"palette":n.state.status==="config"?"config":n.state.status==="help"?"help":n.state.status==="proposal"?_e?"disabled":"menu":n.state.status==="alternatives"?_e?"disabled":"selection":n.state.status==="input"?"text":"disabled",[P,y,n.state.status,wt,_e]),Ir=j((l,p)=>{ft(p,l).success&&(!y&&n.state.status==="setup"&&(he({provider:p,model:F[p].defaultModel}),ro(p),at(F[p].defaultModel)),f(),to(!1),oo(null),ke())},[y,n.state.status,f,ke]);eo(()=>{!P&&y&&n.state.status==="setup"&&ke()},[P,y,n.state.status,ke]),eo(()=>{let l=de().model;pe!==l&&he({model:pe})},[pe]);let br=j(l=>{if(l.startsWith("/")){let p=l.slice(1),b=ae.filter(p);c(b),g(0)}else c([]),g(0)},[]),Ar=j(async l=>{if(l.startsWith("/")){let b=l.slice(1).trim();if(a.length>0){let L=a[h];if(L&&re.executeCommand(L.name)){c([]),g(0);return}}if(b&&re.executeCommand(b)){c([]),g(0);return}c([]),g(0);return}if(c([]),g(0),n.editingCommand){x(l),await ct(l);return}T(l),s(null);let p=await so(l);p.success?v(p.data):d(p.error)},[n.editingCommand,T,so,v,d,x,ct,re,a,h]),Rr=j(async()=>{n.state.status==="proposal"&&(A(),await ct(n.state.proposal.command))},[n.state,A,ct]),wr=j(async()=>{if(n.state.status!=="proposal")return;(await mr(n.state.proposal.command)).success?(r("\u2713 Copied to clipboard"),setTimeout(()=>r(null),2e3)):(r("\u2717 Failed to copy"),setTimeout(()=>r(null),2e3)),W()},[n.state,W]),Or=j(()=>{n.state.status==="proposal"&&ue(n.state.proposal.command)},[n.state,ue]),Nr=j(async()=>{if(n.state.status!=="proposal")return;let l=await io(n.currentQuery,n.state.proposal.command);l.success?I(l.data):d(l.error)},[n.state,n.currentQuery,io,I,d]),Br=j(()=>{k(),s(null)},[k]),Dr=j(async()=>{if(n.state.status!=="proposal")return;let l=await ao(n.state.proposal.command);l.success&&s(l.data)},[n.state,ao]),kr=j(()=>{we()},[we]),Mr=j(l=>{if(n.state.status!=="alternatives")return;let p=n.state.proposals[l];p&&v(p)},[n.state,v]),_r=j(l=>{let p=ae.filter(l);re.setQuery(l),u(l,p)},[re,u]),Lr=j(()=>{re.executeSelected()&&(S(),re.reset())},[re,S]),Kr=j(l=>{l==="up"?re.focusUp():re.focusDown()},[re]),Ur=j(()=>{S(),re.reset()},[S,re]),Hr=j(l=>{let p=["provider","api-keys","toggles","about"];if(n.state.status!=="config")return;Me&&Oe(!1);let b=p.indexOf(n.state.section),L;l==="next"?L=(b+1)%p.length:L=(b-1+p.length)%p.length,w(p[L]),it(0)},[n.state,w,Me]),Fr=j(l=>{if(n.state.status!=="config")return;let p;n.state.section==="provider"?p=K.length+Ee[J].length+1:p={provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],p!==0&&it(b=>l==="up"?(b-1+p)%p:(b+1)%p)},[n.state,J]),$r=j(()=>{if(n.state.status==="config"){if(n.state.section==="toggles"){yr(l=>{let b=["contextEnabled","showExplanations","syntaxHighlighting","simpleMode"][ve];if(b){let L=!l[b];return b==="contextEnabled"&&he({contextEnabled:L}),{...l,[b]:L}}return l});return}if(n.state.section==="provider"){let l=K,p=Ee[J],b=K.length+p.length;if(ve<K.length){let L=l[ve];if(L&&L!==J){let ie=F[L].defaultModel;he({provider:L,model:ie}),ro(L),at(ie),Oe(!1),it(0),f()}}else if(ve===b)Oe(!0);else{let L=ve-K.length,ie=p[L];ie&&ie.id!==pe&&(he({model:ie.id}),at(ie.id),Oe(!1))}return}if(n.state.section==="api-keys"){let p=K[ve];p&&(st(),oo(p),to(!0));return}}},[n.state,ve,st,J,f,pe]),Gr=j(()=>{st(),it(0),Oe(!1)},[st]),Yr=n.state.status==="palette"?n.state.query:"",Vr=Xe(()=>n.state.status!=="config"?0:n.state.section==="provider"?K.length+Ee[J].length+1:{provider:0,"api-keys":K.length,toggles:4,about:0}[n.state.section],[n.state,J]),{textState:jr,clearText:hs,setText:Cs,menuFocusIndex:qr,selectionFocusIndex:Xr,paletteFocusIndex:Qr,configSectionIndex:Ts,customModelState:Wr,dispatchCustomModel:lo}=ur({mode:Pr,initialTextValue:n.editingCommand??"",paletteQuery:Yr,menuCallbacks:{onExecute:Rr,onCopy:wr,onEdit:Or,onAlternatives:Nr,onCancel:Br,onExplain:Dr,onToggle:kr},selectionCallbacks:{onSelect:Mr,onCancel:k,count:n.state.status==="alternatives"?n.state.proposals.length:1},textCallbacks:{onSubmit:Ar,onToggleOutput:we,onTextChange:br,onNavigateInlinePalette:l=>{g(p=>{let b=a.length;return b===0?0:l==="up"?(p-1+b)%b:(p+1)%b})},onCloseInlinePalette:()=>{c([]),g(0)},hasInlinePalette:a.length>0,hasHistory:n.history.length>0},paletteCallbacks:{onQueryChange:_r,onSelect:Lr,onNavigate:Kr,onClose:Ur,filteredCount:n.state.status==="palette"?n.state.filteredCommands.length:0},configCallbacks:{onNavigateSection:Hr,onNavigateItem:Fr,onToggle:$r,onClose:Gr,sectionCount:4,itemCount:Vr,isEditingCustomModel:Me,onCustomModelSubmit:l=>{he({model:l}),at(l),Oe(!1)},onCustomModelCancel:()=>{Oe(!1)}},helpCallbacks:{onClose:gr}});return eo(()=>{if(Me){let l=!Ee[J].some(p=>p.id===pe);lo({type:"set",value:l?pe:""})}},[Me,J,pe,lo]),P?C(_,{flexDirection:"column",paddingY:1,children:C(B,{dimColor:!0,children:"Loading configuration..."})}):hr||!y&&n.state.status==="setup"?C(Io,{onComplete:Ir,error:m,provider:Cr??void 0}):U(_,{flexDirection:"column",children:[C(Fo,{shell:e,cwd:process.cwd(),provider:J,model:pe}),C(ls,{items:Sr,children:l=>U(_,{flexDirection:"column",marginBottom:1,children:[U(_,{children:[U(B,{color:"cyan",bold:!0,children:["\u276F"," "]}),C(B,{color:"cyan",children:l.entry.query})]}),U(_,{marginLeft:2,flexDirection:"column",children:[U(_,{children:[U(B,{dimColor:!0,children:["$ ",l.entry.command," "]}),C(B,{color:l.entry.exitCode===0?"green":"red",children:l.entry.exitCode===0?"\u2713":`\u2717 ${l.entry.exitCode}`})]}),l.entry.output&&U(_,{flexDirection:"column",children:[l.entry.output.split(`
|
|
51
|
+
`).slice(0,10).map((p,b)=>C(B,{children:p},b)),l.entry.output.split(`
|
|
52
|
+
`).length>10&&U(B,{dimColor:!0,children:["... (",l.entry.output.split(`
|
|
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
|
|
43
56
|
|
|
44
57
|
Usage:
|
|
45
58
|
s Start interactive session
|
|
@@ -62,4 +75,4 @@ Session Controls:
|
|
|
62
75
|
Escape Cancel current action
|
|
63
76
|
exit, quit Exit the session
|
|
64
77
|
Ctrl+D Exit (empty input)
|
|
65
|
-
`)}async function
|
|
78
|
+
`)}async function gs(){let t=process.argv.slice(2);(t.includes("--help")||t.includes("-h"))&&(fs(),process.exit(0)),(t.includes("--version")||t.includes("-v"))&&(console.log(`CLI AI v${me}`),process.exit(0)),process.stdout.write(ms+ds);let{waitUntilExit:e}=ps(xs(dr,{}));process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{process.exit(0)}),await e()}gs().catch(t=>{console.error("Fatal error:",t),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fmdzc/cli-ai",
|
|
3
|
-
"version": "3.0
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"description": "CLI AI Assistant v3 - Natural language to shell commands with persistent REPL session",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -84,24 +84,26 @@
|
|
|
84
84
|
"@anthropic-ai/sdk": "^0.71.2",
|
|
85
85
|
"@inkjs/ui": "^2.0.0",
|
|
86
86
|
"@napi-rs/keyring": "^1.2.0",
|
|
87
|
+
"@openrouter/sdk": "^0.3.12",
|
|
87
88
|
"chalk": "^5.3.0",
|
|
88
89
|
"clipboardy": "^4.0.0",
|
|
89
90
|
"conf": "^13.0.0",
|
|
90
91
|
"execa": "^9.0.0",
|
|
91
92
|
"ink": "^6.0.0",
|
|
93
|
+
"openai": "^6.16.0",
|
|
92
94
|
"react": "^19.0.0",
|
|
93
95
|
"zod": "^3.23.0"
|
|
94
96
|
},
|
|
95
97
|
"optionalDependencies": {
|
|
96
|
-
"@napi-rs/keyring-win32-x64-msvc": "^1.2.0",
|
|
97
|
-
"@napi-rs/keyring-win32-ia32-msvc": "^1.2.0",
|
|
98
|
-
"@napi-rs/keyring-win32-arm64-msvc": "^1.2.0",
|
|
99
|
-
"@napi-rs/keyring-darwin-x64": "^1.2.0",
|
|
100
98
|
"@napi-rs/keyring-darwin-arm64": "^1.2.0",
|
|
99
|
+
"@napi-rs/keyring-darwin-x64": "^1.2.0",
|
|
100
|
+
"@napi-rs/keyring-linux-arm64-gnu": "^1.2.0",
|
|
101
|
+
"@napi-rs/keyring-linux-arm64-musl": "^1.2.0",
|
|
101
102
|
"@napi-rs/keyring-linux-x64-gnu": "^1.2.0",
|
|
102
103
|
"@napi-rs/keyring-linux-x64-musl": "^1.2.0",
|
|
103
|
-
"@napi-rs/keyring-
|
|
104
|
-
"@napi-rs/keyring-
|
|
104
|
+
"@napi-rs/keyring-win32-arm64-msvc": "^1.2.0",
|
|
105
|
+
"@napi-rs/keyring-win32-ia32-msvc": "^1.2.0",
|
|
106
|
+
"@napi-rs/keyring-win32-x64-msvc": "^1.2.0"
|
|
105
107
|
},
|
|
106
108
|
"devDependencies": {
|
|
107
109
|
"@eslint/js": "8.57.0",
|