@aiiware/aii 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +100 -77
  2. package/bin/aii +5 -5
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,11 +1,9 @@
1
1
  # @aiiware/aii
2
2
 
3
- **AI-powered CLI assistant** that brings intelligent AI capabilities directly to your terminal.
3
+ **AI-powered CLI assistant** with autonomous tool execution. An intelligent agent that can read, write, search, and execute commands in your terminal.
4
4
 
5
5
  ## Installation
6
6
 
7
- Install globally to use the `aii` command anywhere:
8
-
9
7
  ```bash
10
8
  npm install -g @aiiware/aii
11
9
  ```
@@ -18,105 +16,109 @@ npm install -g @aiiware/aii
18
16
  ## Quick Start
19
17
 
20
18
  ```bash
21
- # First run - auto-initializes configuration
22
- aii "explain what git rebase does"
19
+ # Start interactive agent mode
20
+ aii
21
+
22
+ # Or run a single query
23
+ aii "explain what this project does"
23
24
 
24
25
  # Pipe content for processing
25
26
  cat error.log | aii "summarize the errors"
26
27
 
27
- # Interactive chat mode
28
- aii chat
29
-
30
- # Clean output (just the result)
31
- aii "translate hello to spanish" --clean
32
-
33
- # Use a specific model
34
- aii "complex analysis" --model gpt-4o
28
+ # Auto-approve tool execution
29
+ aii --auto
35
30
  ```
36
31
 
37
- ## Commands
32
+ ## Agent Mode (Default)
33
+
34
+ Aii runs as an intelligent agent that can autonomously execute tools to complete tasks:
38
35
 
39
- ### AI Query (default)
40
36
  ```bash
41
- aii "your question"
42
- aii "your question" --clean # Just the result
43
- aii "your question" --standard # Result + metrics (default)
44
- aii "your question" --thinking # Full reasoning
37
+ aii # Start interactive session
38
+ aii "your task" # Run single task and exit
45
39
  ```
46
40
 
47
- ### Interactive Chat
48
-
49
- ```bash
50
- aii chat # Start interactive chat session
51
-
52
- # In chat mode:
53
- /help # Show available commands
54
- /clear # Clear conversation and start fresh
55
- /history # Show conversation history
56
- /stats # Show session statistics
57
- /exit # Exit chat mode
41
+ ### Available Tools
42
+
43
+ | Tool | Description |
44
+ |---------------|--------------------------------|
45
+ | **Read** | Read file contents |
46
+ | **Write** | Create or overwrite files |
47
+ | **Edit** | Make targeted edits to files |
48
+ | **Glob** | Find files by pattern |
49
+ | **Grep** | Search code with regex |
50
+ | **Bash** | Execute shell commands |
51
+ | **WebSearch** | Search the web |
52
+
53
+ ### Interactive Commands
54
+
55
+ In agent mode, use these commands:
56
+
57
+ ```text
58
+ /help Show available commands
59
+ /clear Clear conversation history
60
+ /history Show conversation history
61
+ /stats Show session statistics (tokens, cost)
62
+ /model <model> Switch LLM model
63
+ /provider <name> Switch LLM provider
64
+ /exit Exit the session
58
65
  ```
59
66
 
60
- ### Prompts (Templates)
67
+ ### Keyboard Shortcuts
68
+
69
+ | Key | Action |
70
+ |------------|----------------------------|
71
+ | `Enter` | Submit input |
72
+ | `Esc` | Cancel current request |
73
+ | `Ctrl+C` | Exit immediately |
74
+ | `Up/Down` | Navigate input history |
75
+ | `Tab` | Autocomplete commands |
76
+
77
+ ## Output Modes
61
78
 
62
79
  ```bash
63
- aii prompt list # List available prompts
64
- aii prompt show <name> # Show prompt details
65
- aii prompt use <name> [--var value] # Use a prompt template
80
+ aii "query" --clean # Just the result
81
+ aii "query" --standard # Result + metrics (default)
82
+ aii "query" --thinking # Full reasoning chain
66
83
  ```
67
84
 
68
- ### Configuration
85
+ ## Prompt Templates
86
+
87
+ Use pre-built templates for common tasks:
88
+
69
89
  ```bash
70
- aii config show # Show current configuration
71
- aii config validate # Validate configuration
72
- aii config set <key> <value> # Set a configuration value
73
- aii config model <model> # Change LLM model
74
- aii config provider <provider> # Change LLM provider
90
+ aii prompt list # List available prompts
91
+ aii prompt show <name> # Show prompt details
92
+ aii prompt use <name> --var value # Use a prompt template
75
93
  ```
76
94
 
77
- ### System
95
+ ## Configuration
96
+
78
97
  ```bash
79
- aii doctor # System health check
80
- aii --help # Show help
81
- aii --version # Show version
98
+ aii config show # Show current configuration
99
+ aii config validate # Validate configuration
100
+ aii config set <key> <value> # Set a configuration value
101
+ aii config model <model> # Change LLM model
102
+ aii config provider <provider> # Change LLM provider
82
103
  ```
83
104
 
84
- ## Options
85
-
86
- | Option | Description |
87
- |--------|-------------|
88
- | `--clean` | Clean output mode (just the result) |
89
- | `--standard` | Standard output mode (result + metrics) |
90
- | `--thinking` | Thinking mode (full reasoning) |
91
- | `--model <model>` | Override LLM model |
92
- | `--host <host:port>` | API server host |
93
- | `-y, --yes` | Auto-confirm shell commands |
94
- | `--offline` | Offline mode (no web/MCP) |
95
- | `--no-colors` | Disable colored output |
96
- | `--no-emojis` | Disable emoji icons |
97
- | `--no-streaming` | Disable streaming output |
98
-
99
- ## Configuration
105
+ ### Config Files
100
106
 
101
107
  Configuration is stored in `~/.aii/`:
102
- - `config.yaml` - Main configuration
103
- - `secrets.yaml` - API keys
104
108
 
105
- ### Example config.yaml
109
+ **config.yaml** - Main configuration:
106
110
 
107
111
  ```yaml
108
112
  llm:
109
- provider: deepseek
110
- model: deepseek-chat
113
+ provider: anthropic
114
+ model: claude-sonnet-4
111
115
  temperature: 0.7
112
116
 
113
117
  api:
114
118
  url: http://localhost:26169
115
119
  ```
116
120
 
117
- ### API Keys
118
-
119
- Store your LLM provider API keys in `~/.aii/secrets.yaml`:
121
+ **secrets.yaml** - API keys:
120
122
 
121
123
  ```yaml
122
124
  anthropic_api_key: sk-ant-...
@@ -124,19 +126,40 @@ openai_api_key: sk-...
124
126
  deepseek_api_key: sk-...
125
127
  ```
126
128
 
127
- Or set via environment variables:
128
- - `ANTHROPIC_API_KEY`
129
- - `OPENAI_API_KEY`
130
- - `DEEPSEEK_API_KEY`
129
+ Or use environment variables: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `DEEPSEEK_API_KEY`
130
+
131
+ ## CLI Options
132
+
133
+ | Option | Description |
134
+ |----------------------|----------------------------------|
135
+ | `--auto` | Auto-approve all tool executions |
136
+ | `--clean` | Clean output mode |
137
+ | `--standard` | Standard output mode (default) |
138
+ | `--thinking` | Show full reasoning |
139
+ | `--model <model>` | Override LLM model |
140
+ | `--host <host:port>` | API server host |
141
+ | `--no-streaming` | Disable streaming output |
142
+ | `--quiet` | Minimal output |
143
+ | `--verbose` | Show detailed stats |
144
+
145
+ ## System Commands
146
+
147
+ ```bash
148
+ aii doctor # System health check
149
+ aii --help # Show help
150
+ aii --version # Show version
151
+ ```
131
152
 
132
153
  ## Features
133
154
 
155
+ - **Autonomous Agent**: Executes multi-step tasks with tool use
134
156
  - **Real-time Streaming**: Token-by-token response display
135
- - **Interactive Chat**: Multi-turn conversations with context
157
+ - **Interactive Mode**: Multi-turn conversations with full context
158
+ - **Tool Execution**: Read, write, search, and run commands
159
+ - **Multiple Providers**: Claude, GPT, Gemini, DeepSeek
136
160
  - **Prompt Templates**: Pre-built templates for common tasks
137
- - **Multiple LLM Providers**: Claude, GPT, Gemini, DeepSeek, and more
138
- - **Pipe Support**: Process piped content with AI
139
- - **Output Modes**: Clean, standard, or thinking mode
161
+ - **Input History**: Navigate previous inputs with arrow keys
162
+ - **Cancellation**: Press Esc to cancel any request
140
163
 
141
164
  ## Links
142
165
 
@@ -145,4 +168,4 @@ Or set via environment variables:
145
168
 
146
169
  ## License
147
170
 
148
- Proprietary - Copyright 2025-present AiiWare.com. All Rights Reserved.
171
+ Proprietary - Copyright 2025-present AiiWare.com. All Rights Reserved.
package/bin/aii CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * @aiiware/aii v0.2.1
3
+ * @aiiware/aii v0.2.2
4
4
  *
5
5
  * AI-powered CLI assistant for terminal productivity
6
6
  *
@@ -35,7 +35,7 @@ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let
35
35
  ${t}
36
36
  </context>
37
37
 
38
- ${e}`:e}});var PE=y(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});Af.createParser=DE;Af.parseArgs=Gz;var wE=bE(),SE=kf(),Kz="0.2.1";function DE(){let t=new wE.Command;return t.name("aii").description("AI-powered CLI assistant").version(Kz,"-V, --version","Show version number").helpOption(!1).enablePositionalOptions().argument("[query...]","Natural language query").option("--clean","Clean output mode (just the result)").option("--standard","Standard output mode (result + metrics)").option("--thinking","Thinking mode (full reasoning)").option("-v, --verbose","Verbose output (alias for --thinking)").option("-d, --debug","Debug output").option("--model <model>","Override LLM model").option("--host <host>","API server host:port").option("-y, --yes","Auto-confirm shell commands").option("--offline","Offline mode (no web/MCP)").option("-i, --interactive","Interactive chat mode").option("-c, --continue-chat <id>","Continue chat session").option("-n, --new-chat","Force new chat session").option("--auto","Auto mode - auto-approve all actions").option("-q, --quiet","Quiet mode - minimal output").option("--no-colors","Disable colored output").option("--no-emojis","Disable emoji icons").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","Show token usage").option("--show-cost","Show cost estimates").option("-h, --help","Show help"),t.command("config").description("Configuration management").argument("[action]","Action: init, show, validate, set").argument("[key]","Config key (for set)").argument("[value]","Config value (for set)").action(()=>{}),t.command("mcp").description("MCP server management").argument("[action]","Action: list, add, remove, status, etc.").argument("[rest...]","Server name and arguments").passThroughOptions().action(()=>{}),t.command("prompt").description("Prompt library").argument("[action]","Action: list, show, use, create").argument("[rest...]","Prompt name and arguments").allowUnknownOption().action(()=>{}),t.command("stats").description("Usage statistics").argument("[type]","Type: models, cost").action(()=>{}),t.command("history").description("Chat history").argument("[action]","Action: list, search, export, delete").argument("[query]","Search query or ID").action(()=>{}),t.command("doctor").description("System health check").action(()=>{}),t.command("chat").description("Interactive chat mode").action(()=>{}),t.command("agent").description("Interactive agent mode with tool execution").argument("[query...]","Optional query (non-interactive if provided)").action(()=>{}),t.command("run").description("Run domain-specific operations").argument("<operation>","Operation (e.g., git commit)").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("help").description("display help for command").argument("[command]","Command to show help for").action(()=>{}),t.command("version").description("Show version number").action(()=>{}),t}async function Gz(t){let e=DE();e.exitOverride(),e.configureOutput({writeErr:()=>{}});let r="query",n,i=[];try{e.parse(t),i=e.args;let c=e.args[0];c&&["config","mcp","prompt","stats","history","doctor","chat","run","help","version","agent"].includes(c)&&(r=c,n=e.args[1],i=e.args.slice(2))}catch(c){c instanceof wE.CommanderError&&(c.code==="commander.version"||c.code==="commander.helpDisplayed")&&process.exit(0),i=t.slice(2)}let o=e.opts(),s={clean:o.clean??!1,standard:o.standard??!1,thinking:o.thinking??!1,verbose:o.verbose??!1,debug:o.debug??!1,model:o.model,host:o.host,yes:o.yes??!1,offline:o.offline??!1,interactive:o.interactive??!1,continueChat:o.continueChat,newChat:o.newChat??!1,auto:o.auto??!1,quiet:o.quiet??!1,noColors:!o.colors,noEmojis:!o.emojis,noAnimations:!o.animations,noStreaming:!o.streaming,showTokens:o.showTokens??!1,showCost:o.showCost??!1,help:o.help??!1,version:o.version??!1},a;(0,SE.hasStdinInput)()&&(a=await(0,SE.readStdin)()),(r==="chat"||s.interactive)&&(r="agent"),r==="query"&&!i.length&&!a&&(r="agent");let u;if(r==="query"&&i.length>0)u=i.join(" ");else if(r==="agent"){let c=[];n&&c.push(n),i.length>0&&c.push(...i),c.length>0&&(u=c.join(" "))}return{command:r,subcommand:n,args:i,flags:s,stdinContent:a,query:u}}});var Mc=y(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.COMMAND_TIERS=Yr.DEFAULT_OUTPUT_MODES=Yr.CommandTier=void 0;Yr.resolveOutputMode=Wz;var _r;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(_r||(Yr.CommandTier=_r={}));Yr.DEFAULT_OUTPUT_MODES={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function Wz(t,e,r,n){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&r?.[e]?r[e]:e&&Yr.DEFAULT_OUTPUT_MODES[e]?Yr.DEFAULT_OUTPUT_MODES[e]:n||Yr.DEFAULT_OUTPUT_MODES._default}Yr.COMMAND_TIERS={config:_r.LOCAL,help:_r.LOCAL,version:_r.LOCAL,doctor:_r.LOCAL,mcp:_r.LOCAL,prompt:_r.LOCAL,stats:_r.LOCAL,history:_r.LOCAL,query:_r.SERVER,chat:_r.SERVER,run:_r.SERVER,agent:_r.SERVER}});var OE=y(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});hy.routeCommand=Hz;var Mr=Mc();function Hz(t){let e=Mr.COMMAND_TIERS[t.command]??Mr.CommandTier.SERVER;switch(t.command){case"config":return Jz(t);case"mcp":return Yz(t);case"prompt":return Xz(t);case"stats":return Qz(t);case"history":return eU(t);case"doctor":return{tier:Mr.CommandTier.LOCAL,handler:"doctor",params:{}};case"chat":return{tier:Mr.CommandTier.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return tU(t);case"agent":return{tier:Mr.CommandTier.SERVER,handler:"agent",params:{interactive:!t.query}};case"help":return{tier:Mr.CommandTier.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:Mr.CommandTier.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Jz(t){let e=t.subcommand??t.args[0]??"show";return{tier:Mr.CommandTier.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function Yz(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Xz(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Qz(t){let e=t.subcommand??t.args[0];return{tier:Mr.CommandTier.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function eU(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}function tU(t){let e=[];t.subcommand&&e.push(t.subcommand);let r=t.args.filter(i=>!i.startsWith("-"));e.push(...r);let n=e.join(" ");return{tier:Mr.CommandTier.SERVER,handler:"run",params:{operation:n}}}});var Fe=y(xt=>{"use strict";var gy=Symbol.for("yaml.alias"),EE=Symbol.for("yaml.document"),Mf=Symbol.for("yaml.map"),CE=Symbol.for("yaml.pair"),_y=Symbol.for("yaml.scalar"),Nf=Symbol.for("yaml.seq"),vo=Symbol.for("yaml.node.type"),rU=t=>!!t&&typeof t=="object"&&t[vo]===gy,nU=t=>!!t&&typeof t=="object"&&t[vo]===EE,iU=t=>!!t&&typeof t=="object"&&t[vo]===Mf,oU=t=>!!t&&typeof t=="object"&&t[vo]===CE,TE=t=>!!t&&typeof t=="object"&&t[vo]===_y,sU=t=>!!t&&typeof t=="object"&&t[vo]===Nf;function jE(t){if(t&&typeof t=="object")switch(t[vo]){case Mf:case Nf:return!0}return!1}function aU(t){if(t&&typeof t=="object")switch(t[vo]){case gy:case Mf:case _y:case Nf:return!0}return!1}var uU=t=>(TE(t)||jE(t))&&!!t.anchor;xt.ALIAS=gy;xt.DOC=EE;xt.MAP=Mf;xt.NODE_TYPE=vo;xt.PAIR=CE;xt.SCALAR=_y;xt.SEQ=Nf;xt.hasAnchor=uU;xt.isAlias=rU;xt.isCollection=jE;xt.isDocument=nU;xt.isMap=iU;xt.isNode=aU;xt.isPair=oU;xt.isScalar=TE;xt.isSeq=sU});var Nc=y(yy=>{"use strict";var Ct=Fe(),yr=Symbol("break visit"),IE=Symbol("skip children"),pi=Symbol("remove node");function Ff(t,e){let r=kE(e);Ct.isDocument(t)?Qa(null,t.contents,r,Object.freeze([t]))===pi&&(t.contents=null):Qa(null,t,r,Object.freeze([]))}Ff.BREAK=yr;Ff.SKIP=IE;Ff.REMOVE=pi;function Qa(t,e,r,n){let i=AE(t,e,r,n);if(Ct.isNode(i)||Ct.isPair(i))return ME(t,n,i),Qa(t,i,r,n);if(typeof i!="symbol"){if(Ct.isCollection(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let s=Qa(o,e.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===yr)return yr;s===pi&&(e.items.splice(o,1),o-=1)}}}else if(Ct.isPair(e)){n=Object.freeze(n.concat(e));let o=Qa("key",e.key,r,n);if(o===yr)return yr;o===pi&&(e.key=null);let s=Qa("value",e.value,r,n);if(s===yr)return yr;s===pi&&(e.value=null)}}return i}async function Rf(t,e){let r=kE(e);Ct.isDocument(t)?await eu(null,t.contents,r,Object.freeze([t]))===pi&&(t.contents=null):await eu(null,t,r,Object.freeze([]))}Rf.BREAK=yr;Rf.SKIP=IE;Rf.REMOVE=pi;async function eu(t,e,r,n){let i=await AE(t,e,r,n);if(Ct.isNode(i)||Ct.isPair(i))return ME(t,n,i),eu(t,i,r,n);if(typeof i!="symbol"){if(Ct.isCollection(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let s=await eu(o,e.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===yr)return yr;s===pi&&(e.items.splice(o,1),o-=1)}}}else if(Ct.isPair(e)){n=Object.freeze(n.concat(e));let o=await eu("key",e.key,r,n);if(o===yr)return yr;o===pi&&(e.key=null);let s=await eu("value",e.value,r,n);if(s===yr)return yr;s===pi&&(e.value=null)}}return i}function kE(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function AE(t,e,r,n){if(typeof r=="function")return r(t,e,n);if(Ct.isMap(e))return r.Map?.(t,e,n);if(Ct.isSeq(e))return r.Seq?.(t,e,n);if(Ct.isPair(e))return r.Pair?.(t,e,n);if(Ct.isScalar(e))return r.Scalar?.(t,e,n);if(Ct.isAlias(e))return r.Alias?.(t,e,n)}function ME(t,e,r){let n=e[e.length-1];if(Ct.isCollection(n))n.items[t]=r;else if(Ct.isPair(n))t==="key"?n.key=r:n.value=r;else if(Ct.isDocument(n))n.contents=r;else{let i=Ct.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}yy.visit=Ff;yy.visitAsync=Rf});var vy=y(FE=>{"use strict";var NE=Fe(),cU=Nc(),lU={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},dU=t=>t.replace(/[!,[\]{}]/g,e=>lU[e]),Fc=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,s]=n;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,s),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),s)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||r(`The ${e} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(s){return r(String(s)),null}return n==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,n]of Object.entries(this.tags))if(e.startsWith(n))return r+dU(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&NE.isNode(e.contents)){let o={};cU.visit(e.contents,(s,a)=>{NE.isNode(a)&&a.tag&&(o[a.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,s]of n)o==="!!"&&s==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(s)))&&r.push(`%TAG ${o} ${s}`);return r.join(`
38
+ ${e}`:e}});var PE=y(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});Af.createParser=DE;Af.parseArgs=Gz;var wE=bE(),SE=kf(),Kz="0.2.2";function DE(){let t=new wE.Command;return t.name("aii").description("AI-powered CLI assistant").version(Kz,"-V, --version","Show version number").helpOption(!1).enablePositionalOptions().argument("[query...]","Natural language query").option("--clean","Clean output mode (just the result)").option("--standard","Standard output mode (result + metrics)").option("--thinking","Thinking mode (full reasoning)").option("-v, --verbose","Verbose output (alias for --thinking)").option("-d, --debug","Debug output").option("--model <model>","Override LLM model").option("--host <host>","API server host:port").option("-y, --yes","Auto-confirm shell commands").option("--offline","Offline mode (no web/MCP)").option("-i, --interactive","Interactive chat mode").option("-c, --continue-chat <id>","Continue chat session").option("-n, --new-chat","Force new chat session").option("--auto","Auto mode - auto-approve all actions").option("-q, --quiet","Quiet mode - minimal output").option("--no-colors","Disable colored output").option("--no-emojis","Disable emoji icons").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","Show token usage").option("--show-cost","Show cost estimates").option("-h, --help","Show help"),t.command("config").description("Configuration management").argument("[action]","Action: init, show, validate, set").argument("[key]","Config key (for set)").argument("[value]","Config value (for set)").action(()=>{}),t.command("mcp").description("MCP server management").argument("[action]","Action: list, add, remove, status, etc.").argument("[rest...]","Server name and arguments").passThroughOptions().action(()=>{}),t.command("prompt").description("Prompt library").argument("[action]","Action: list, show, use, create").argument("[rest...]","Prompt name and arguments").allowUnknownOption().action(()=>{}),t.command("stats").description("Usage statistics").argument("[type]","Type: models, cost").action(()=>{}),t.command("history").description("Chat history").argument("[action]","Action: list, search, export, delete").argument("[query]","Search query or ID").action(()=>{}),t.command("doctor").description("System health check").action(()=>{}),t.command("chat").description("Interactive chat mode").action(()=>{}),t.command("agent").description("Interactive agent mode with tool execution").argument("[query...]","Optional query (non-interactive if provided)").action(()=>{}),t.command("run").description("Run domain-specific operations").argument("<operation>","Operation (e.g., git commit)").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("help").description("display help for command").argument("[command]","Command to show help for").action(()=>{}),t.command("version").description("Show version number").action(()=>{}),t}async function Gz(t){let e=DE();e.exitOverride(),e.configureOutput({writeErr:()=>{}});let r="query",n,i=[];try{e.parse(t),i=e.args;let c=e.args[0];c&&["config","mcp","prompt","stats","history","doctor","chat","run","help","version","agent"].includes(c)&&(r=c,n=e.args[1],i=e.args.slice(2))}catch(c){c instanceof wE.CommanderError&&(c.code==="commander.version"||c.code==="commander.helpDisplayed")&&process.exit(0),i=t.slice(2)}let o=e.opts(),s={clean:o.clean??!1,standard:o.standard??!1,thinking:o.thinking??!1,verbose:o.verbose??!1,debug:o.debug??!1,model:o.model,host:o.host,yes:o.yes??!1,offline:o.offline??!1,interactive:o.interactive??!1,continueChat:o.continueChat,newChat:o.newChat??!1,auto:o.auto??!1,quiet:o.quiet??!1,noColors:!o.colors,noEmojis:!o.emojis,noAnimations:!o.animations,noStreaming:!o.streaming,showTokens:o.showTokens??!1,showCost:o.showCost??!1,help:o.help??!1,version:o.version??!1},a;(0,SE.hasStdinInput)()&&(a=await(0,SE.readStdin)()),(r==="chat"||s.interactive)&&(r="agent"),r==="query"&&!i.length&&!a&&(r="agent");let u;if(r==="query"&&i.length>0)u=i.join(" ");else if(r==="agent"){let c=[];n&&c.push(n),i.length>0&&c.push(...i),c.length>0&&(u=c.join(" "))}return{command:r,subcommand:n,args:i,flags:s,stdinContent:a,query:u}}});var Mc=y(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.COMMAND_TIERS=Yr.DEFAULT_OUTPUT_MODES=Yr.CommandTier=void 0;Yr.resolveOutputMode=Wz;var _r;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(_r||(Yr.CommandTier=_r={}));Yr.DEFAULT_OUTPUT_MODES={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function Wz(t,e,r,n){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&r?.[e]?r[e]:e&&Yr.DEFAULT_OUTPUT_MODES[e]?Yr.DEFAULT_OUTPUT_MODES[e]:n||Yr.DEFAULT_OUTPUT_MODES._default}Yr.COMMAND_TIERS={config:_r.LOCAL,help:_r.LOCAL,version:_r.LOCAL,doctor:_r.LOCAL,mcp:_r.LOCAL,prompt:_r.LOCAL,stats:_r.LOCAL,history:_r.LOCAL,query:_r.SERVER,chat:_r.SERVER,run:_r.SERVER,agent:_r.SERVER}});var OE=y(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});hy.routeCommand=Hz;var Mr=Mc();function Hz(t){let e=Mr.COMMAND_TIERS[t.command]??Mr.CommandTier.SERVER;switch(t.command){case"config":return Jz(t);case"mcp":return Yz(t);case"prompt":return Xz(t);case"stats":return Qz(t);case"history":return eU(t);case"doctor":return{tier:Mr.CommandTier.LOCAL,handler:"doctor",params:{}};case"chat":return{tier:Mr.CommandTier.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return tU(t);case"agent":return{tier:Mr.CommandTier.SERVER,handler:"agent",params:{interactive:!t.query}};case"help":return{tier:Mr.CommandTier.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:Mr.CommandTier.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Jz(t){let e=t.subcommand??t.args[0]??"show";return{tier:Mr.CommandTier.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function Yz(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Xz(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Qz(t){let e=t.subcommand??t.args[0];return{tier:Mr.CommandTier.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function eU(t){let e=t.subcommand??t.args[0]??"list";return{tier:Mr.CommandTier.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}function tU(t){let e=[];t.subcommand&&e.push(t.subcommand);let r=t.args.filter(i=>!i.startsWith("-"));e.push(...r);let n=e.join(" ");return{tier:Mr.CommandTier.SERVER,handler:"run",params:{operation:n}}}});var Fe=y(xt=>{"use strict";var gy=Symbol.for("yaml.alias"),EE=Symbol.for("yaml.document"),Mf=Symbol.for("yaml.map"),CE=Symbol.for("yaml.pair"),_y=Symbol.for("yaml.scalar"),Nf=Symbol.for("yaml.seq"),vo=Symbol.for("yaml.node.type"),rU=t=>!!t&&typeof t=="object"&&t[vo]===gy,nU=t=>!!t&&typeof t=="object"&&t[vo]===EE,iU=t=>!!t&&typeof t=="object"&&t[vo]===Mf,oU=t=>!!t&&typeof t=="object"&&t[vo]===CE,TE=t=>!!t&&typeof t=="object"&&t[vo]===_y,sU=t=>!!t&&typeof t=="object"&&t[vo]===Nf;function jE(t){if(t&&typeof t=="object")switch(t[vo]){case Mf:case Nf:return!0}return!1}function aU(t){if(t&&typeof t=="object")switch(t[vo]){case gy:case Mf:case _y:case Nf:return!0}return!1}var uU=t=>(TE(t)||jE(t))&&!!t.anchor;xt.ALIAS=gy;xt.DOC=EE;xt.MAP=Mf;xt.NODE_TYPE=vo;xt.PAIR=CE;xt.SCALAR=_y;xt.SEQ=Nf;xt.hasAnchor=uU;xt.isAlias=rU;xt.isCollection=jE;xt.isDocument=nU;xt.isMap=iU;xt.isNode=aU;xt.isPair=oU;xt.isScalar=TE;xt.isSeq=sU});var Nc=y(yy=>{"use strict";var Ct=Fe(),yr=Symbol("break visit"),IE=Symbol("skip children"),pi=Symbol("remove node");function Ff(t,e){let r=kE(e);Ct.isDocument(t)?Qa(null,t.contents,r,Object.freeze([t]))===pi&&(t.contents=null):Qa(null,t,r,Object.freeze([]))}Ff.BREAK=yr;Ff.SKIP=IE;Ff.REMOVE=pi;function Qa(t,e,r,n){let i=AE(t,e,r,n);if(Ct.isNode(i)||Ct.isPair(i))return ME(t,n,i),Qa(t,i,r,n);if(typeof i!="symbol"){if(Ct.isCollection(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let s=Qa(o,e.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===yr)return yr;s===pi&&(e.items.splice(o,1),o-=1)}}}else if(Ct.isPair(e)){n=Object.freeze(n.concat(e));let o=Qa("key",e.key,r,n);if(o===yr)return yr;o===pi&&(e.key=null);let s=Qa("value",e.value,r,n);if(s===yr)return yr;s===pi&&(e.value=null)}}return i}async function Rf(t,e){let r=kE(e);Ct.isDocument(t)?await eu(null,t.contents,r,Object.freeze([t]))===pi&&(t.contents=null):await eu(null,t,r,Object.freeze([]))}Rf.BREAK=yr;Rf.SKIP=IE;Rf.REMOVE=pi;async function eu(t,e,r,n){let i=await AE(t,e,r,n);if(Ct.isNode(i)||Ct.isPair(i))return ME(t,n,i),eu(t,i,r,n);if(typeof i!="symbol"){if(Ct.isCollection(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let s=await eu(o,e.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===yr)return yr;s===pi&&(e.items.splice(o,1),o-=1)}}}else if(Ct.isPair(e)){n=Object.freeze(n.concat(e));let o=await eu("key",e.key,r,n);if(o===yr)return yr;o===pi&&(e.key=null);let s=await eu("value",e.value,r,n);if(s===yr)return yr;s===pi&&(e.value=null)}}return i}function kE(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function AE(t,e,r,n){if(typeof r=="function")return r(t,e,n);if(Ct.isMap(e))return r.Map?.(t,e,n);if(Ct.isSeq(e))return r.Seq?.(t,e,n);if(Ct.isPair(e))return r.Pair?.(t,e,n);if(Ct.isScalar(e))return r.Scalar?.(t,e,n);if(Ct.isAlias(e))return r.Alias?.(t,e,n)}function ME(t,e,r){let n=e[e.length-1];if(Ct.isCollection(n))n.items[t]=r;else if(Ct.isPair(n))t==="key"?n.key=r:n.value=r;else if(Ct.isDocument(n))n.contents=r;else{let i=Ct.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}yy.visit=Ff;yy.visitAsync=Rf});var vy=y(FE=>{"use strict";var NE=Fe(),cU=Nc(),lU={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},dU=t=>t.replace(/[!,[\]{}]/g,e=>lU[e]),Fc=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,s]=n;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,s),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),s)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||r(`The ${e} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(s){return r(String(s)),null}return n==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,n]of Object.entries(this.tags))if(e.startsWith(n))return r+dU(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&NE.isNode(e.contents)){let o={};cU.visit(e.contents,(s,a)=>{NE.isNode(a)&&a.tag&&(o[a.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,s]of n)o==="!!"&&s==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(s)))&&r.push(`%TAG ${o} ${s}`);return r.join(`
39
39
  `)}};Fc.defaultYaml={explicit:!1,version:"1.2"};Fc.defaultTags={"!!":"tag:yaml.org,2002:"};FE.Directives=Fc});var xf=y(Rc=>{"use strict";var RE=Fe(),fU=Nc();function pU(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function xE(t){let e=new Set;return fU.visit(t,{Value(r,n){n.anchor&&e.add(n.anchor)}}),e}function qE(t,e){for(let r=1;;++r){let n=`${t}${r}`;if(!e.has(n))return n}}function mU(t,e){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=xE(t));let s=qE(e,i);return i.add(s),s},setAnchors:()=>{for(let o of r){let s=n.get(o);if(typeof s=="object"&&s.anchor&&(RE.isScalar(s.node)||RE.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:n}}Rc.anchorIsValid=pU;Rc.anchorNames=xE;Rc.createNodeAnchors=mU;Rc.findNewAnchor=qE});var by=y(ZE=>{"use strict";function xc(t,e,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,o=n.length;i<o;++i){let s=n[i],a=xc(t,n,String(i),s);a===void 0?delete n[i]:a!==s&&(n[i]=a)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let o=n.get(i),s=xc(t,n,i,o);s===void 0?n.delete(i):s!==o&&n.set(i,s)}else if(n instanceof Set)for(let i of Array.from(n)){let o=xc(t,n,i,i);o===void 0?n.delete(i):o!==i&&(n.delete(i),n.add(o))}else for(let[i,o]of Object.entries(n)){let s=xc(t,n,i,o);s===void 0?delete n[i]:s!==o&&(n[i]=s)}return t.call(e,r,n)}ZE.applyReviver=xc});var Go=y(zE=>{"use strict";var hU=Fe();function LE(t,e,r){if(Array.isArray(t))return t.map((n,i)=>LE(n,String(i),r));if(t&&typeof t.toJSON=="function"){if(!r||!hU.hasAnchor(t))return t.toJSON(e,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(t,n),r.onCreate=o=>{n.res=o,delete r.onCreate};let i=t.toJSON(e,r);return r.onCreate&&r.onCreate(i),i}return typeof t=="bigint"&&!r?.keep?Number(t):t}zE.toJS=LE});var qf=y(BE=>{"use strict";var gU=by(),UE=Fe(),_U=Go(),$y=class{constructor(e){Object.defineProperty(this,UE.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:o}={}){if(!UE.isDocument(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=_U.toJS(this,"",s);if(typeof i=="function")for(let{count:u,res:c}of s.anchors.values())i(c,u);return typeof o=="function"?gU.applyReviver(o,{"":a},"",a):a}};BE.NodeBase=$y});var qc=y(VE=>{"use strict";var yU=xf(),vU=Nc(),tu=Fe(),bU=qf(),$U=Go(),Sy=class extends bU.NodeBase{constructor(e){super(tu.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],vU.visit(e,{Node:(o,s)=>{(tu.isAlias(s)||tu.hasAnchor(s))&&n.push(s)}}),r&&(r.aliasResolveCache=n));let i;for(let o of n){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(e,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:o}=r,s=this.resolve(i,r);if(!s){let u=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(u)}let a=n.get(s);if(a||($U.toJS(s,null,r),a=n.get(s)),a?.res===void 0){let u="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(u)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Zf(i,s,n)),a.count*a.aliasCount>o)){let u="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(u)}return a.res}toString(e,r,n){let i=`*${this.source}`;if(e){if(yU.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${i} `}return i}};function Zf(t,e,r){if(tu.isAlias(e)){let n=e.resolve(t),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(tu.isCollection(e)){let n=0;for(let i of e.items){let o=Zf(t,i,r);o>n&&(n=o)}return n}else if(tu.isPair(e)){let n=Zf(t,e.key,r),i=Zf(t,e.value,r);return Math.max(n,i)}return 1}VE.Alias=Sy});var Pt=y(wy=>{"use strict";var SU=Fe(),wU=qf(),DU=Go(),PU=t=>!t||typeof t!="function"&&typeof t!="object",Wo=class extends wU.NodeBase{constructor(e){super(SU.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:DU.toJS(this.value,e,r)}toString(){return String(this.value)}};Wo.BLOCK_FOLDED="BLOCK_FOLDED";Wo.BLOCK_LITERAL="BLOCK_LITERAL";Wo.PLAIN="PLAIN";Wo.QUOTE_DOUBLE="QUOTE_DOUBLE";Wo.QUOTE_SINGLE="QUOTE_SINGLE";wy.Scalar=Wo;wy.isScalarValue=PU});var Zc=y(GE=>{"use strict";var OU=qc(),Zs=Fe(),KE=Pt(),EU="tag:yaml.org,2002:";function CU(t,e,r){if(e){let n=r.filter(o=>o.tag===e),i=n.find(o=>!o.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return r.find(n=>n.identify?.(t)&&!n.format)}function TU(t,e,r){if(Zs.isDocument(t)&&(t=t.contents),Zs.isNode(t))return t;if(Zs.isPair(t)){let d=r.schema[Zs.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:o,schema:s,sourceObjects:a}=r,u;if(n&&t&&typeof t=="object"){if(u=a.get(t),u)return u.anchor??(u.anchor=i(t)),new OU.Alias(u.anchor);u={anchor:null,node:null},a.set(t,u)}e?.startsWith("!!")&&(e=EU+e.slice(2));let c=CU(t,e,s.tags);if(!c){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new KE.Scalar(t);return u&&(u.node=d),d}c=t instanceof Map?s[Zs.MAP]:Symbol.iterator in Object(t)?s[Zs.SEQ]:s[Zs.MAP]}o&&(o(c),delete r.onTagObj);let l=c?.createNode?c.createNode(r.schema,t,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,t,r):new KE.Scalar(t);return e?l.tag=e:c.default||(l.tag=c.tag),u&&(u.node=l),l}GE.createNode=TU});var zf=y(Lf=>{"use strict";var jU=Zc(),mi=Fe(),IU=qf();function Dy(t,e,r){let n=r;for(let i=e.length-1;i>=0;--i){let o=e[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=n,n=s}else n=new Map([[o,n]])}return jU.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var WE=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Py=class extends IU.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(n=>mi.isNode(n)||mi.isPair(n)?n.clone(e):n),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(WE(e))this.add(r);else{let[n,...i]=e,o=this.get(n,!0);if(mi.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,Dy(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[r,...n]=e;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(mi.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(e,r){let[n,...i]=e,o=this.get(n,!0);return i.length===0?!r&&mi.isScalar(o)?o.value:o:mi.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!mi.isPair(r))return!1;let n=r.value;return n==null||e&&mi.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[r,...n]=e;if(n.length===0)return this.has(r);let i=this.get(r,!0);return mi.isCollection(i)?i.hasIn(n):!1}setIn(e,r){let[n,...i]=e;if(i.length===0)this.set(n,r);else{let o=this.get(n,!0);if(mi.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,Dy(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Lf.Collection=Py;Lf.collectionFromPath=Dy;Lf.isEmptyPath=WE});var Lc=y(Uf=>{"use strict";var kU=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Oy(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var AU=(t,e,r)=>t.endsWith(`
40
40
  `)?Oy(r,e):r.includes(`
41
41
  `)?`
@@ -235,7 +235,7 @@ ${e}`,N_e=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),F_e=Obj
235
235
  `)}formatExecutionSummary(e){let r=[];if(e.function_name&&r.push(`${this.emoji("\u{1F527} ")}${e.function_name}`),e.model&&r.push(`${this.emoji("\u{1F916} ")}${e.model}`),e.tokens_in!==void 0||e.tokens_out!==void 0){let i=e.tokens_in??0,o=e.tokens_out??0;r.push(`${this.emoji("\u{1F522} ")}${i}\u2197 ${o}\u2198`)}if(e.cost!==void 0&&r.push(`${this.emoji("\u{1F4B0} ")}$${e.cost.toFixed(6)}`),e.execution_time!==void 0&&r.push(`${this.emoji("\u26A1 ")}${e.execution_time.toFixed(1)}s`),r.length===0)return"";let n=r.join(" \u2022 ");return this.color(n,ir.default.dim)}formatError(e){let r=[];return r.push(this.color(`${this.emoji("\u274C ")}${e.message}`,ir.default.red)),e.suggestions&&e.suggestions.length>0&&(r.push(""),r.push(this.color(`${this.emoji("\u{1F4A1} ")}Solutions:`,ir.default.yellow)),e.suggestions.forEach((n,i)=>{r.push(this.color(` ${i+1}. ${n}`,ir.default.gray))})),r.join(`
236
236
  `)}formatConfig(e){let r=[];r.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,ir.default.cyan)),r.push(`- Config file: ${e.configFile}`),r.push(`- Storage path: ${e.storagePath}`),e.apiUrl&&r.push(`- Aii Server: ${e.apiUrl}`);let n=e.hasApiKey?this.color("\u2713",ir.default.green):this.color("\u2717",ir.default.red);if(r.push(`- LLM provider: ${e.provider} (${e.model}) - ${n}`),e.webSearch){let i=e.webSearch.enabled?this.color("\u2713",ir.default.green):this.color("\u2717",ir.default.red);r.push(`- Web search: ${e.webSearch.provider??"none"} - ${i}`)}return e.issues&&e.issues.length>0&&r.push(`- Configuration issues: ${e.issues.length}`),r.join(`
237
237
  `)}formatHealthCheck(e){let r=[];r.push(this.color(`${this.emoji("\u{1F3E5} ")}AII Health Check`,ir.default.cyan)),r.push("");for(let o of e){let s,a;switch(o.status){case"ok":s="\u2713",a=ir.default.green;break;case"warn":s="\u26A0",a=ir.default.yellow;break;case"error":s="\u2717",a=ir.default.red;break}let u=this.color(s,a),c=this.color(o.message,a);r.push(` ${u} ${o.name.padEnd(20)} ${c}`)}let n=e.some(o=>o.status==="error"),i=e.some(o=>o.status==="warn");return r.push(""),n?r.push(this.color(`${this.emoji("\u274C ")}Some checks failed!`,ir.default.red)):i?r.push(this.color(`${this.emoji("\u26A0\uFE0F ")}All checks passed with warnings`,ir.default.yellow)):r.push(this.color(`${this.emoji("\u2705 ")}All checks passed!`,ir.default.green)),r.join(`
238
- `)}};Ba.OutputFormatter=h_;function iye(t={}){return new h_(t)}});var __=y(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});g_.inferProviderFromModel=T2;g_.resolveProvider=sye;var oye=[{provider:"anthropic",patterns:[/^claude-/,/^claude$/i]},{provider:"openai",patterns:[/^gpt-/,/^o1-/,/^o3-/,/^chatgpt-/,/^text-davinci/]},{provider:"gemini",patterns:[/^gemini-/,/^gemini$/i]},{provider:"deepseek",patterns:[/^deepseek-/,/^deepseek$/i]},{provider:"moonshot",patterns:[/^kimi-/,/^moonshot-/,/^moonshot$/i]},{provider:"zai",patterns:[/^glm-/,/^glm$/i,/^chatglm/i]}];function T2(t){if(!t)return;let e=t.toLowerCase();for(let{provider:r,patterns:n}of oye)for(let i of n)if(i.test(e))return r}function sye(t,e){return t?T2(t)??e:e}});var k2=y(or=>{"use strict";var aye=or&&or.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),uye=or&&or.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dO=or&&or.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&aye(r,e,n[i]);return uye(r,e),r}}();Object.defineProperty(or,"__esModule",{value:!0});or.loadCurrentConversation=fye;or.createNewConversation=fO;or.saveConversation=pO;or.setCurrentConversation=I2;or.addMessage=pye;or.clearCurrentConversation=mye;or.getConversationHistoryForAPI=hye;or.listConversations=gye;var ho=dO(require("fs")),y_=dO(require("path")),cye=dO(require("os")),wc=y_.join(cye.homedir(),".aii","conversations"),lO=y_.join(wc,"current.json");function sf(){ho.existsSync(wc)||ho.mkdirSync(wc,{recursive:!0})}function lye(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dye(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function j2(t){return y_.join(wc,`${t}.json`)}function fye(){sf();try{if(ho.existsSync(lO)){let t=ho.readFileSync(lO,"utf-8"),e=JSON.parse(t),r=j2(e.id);if(ho.existsSync(r)){let n=ho.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return fO()}function fO(){sf();let t={id:lye(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return pO(t),I2(t.id),t}function pO(t){if(sf(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=dye(r.content))}t.updatedAt=Date.now();let e=j2(t.id);ho.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}function I2(t){sf(),ho.writeFileSync(lO,JSON.stringify({id:t}),"utf-8")}function pye(t,e,r){t.messages.push({role:e,content:r,timestamp:Date.now()}),pO(t)}function mye(){return fO()}function hye(t){return t.messages.map(e=>({role:e.role,content:e.content}))}function gye(){sf();let t=[];try{let e=ho.readdirSync(wc);for(let r of e)if(r.endsWith(".json")&&r!=="current.json")try{let n=ho.readFileSync(y_.join(wc,r),"utf-8");t.push(JSON.parse(n))}catch{}}catch{}return t.sort((e,r)=>r.updatedAt-e.updatedAt)}});var mO=y(Vr=>{"use strict";var _ye=Vr&&Vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),yye=Vr&&Vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vye=Vr&&Vr.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&_ye(r,e,n[i]);return yye(r,e),r}}(),bye=Vr&&Vr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vr,"__esModule",{value:!0});Vr.InteractiveChatSession=void 0;Vr.handleChat=Cye;var $ye=vye(require("readline")),A2=bye((St(),Et(Tt))),Sye=vc(),wye=$c(),Dye=Sc(),Pye=Ns(),M2=So(),Oye=__(),af=k2(),Eye="0.2.1",v_=class{configManager;parsed;running=!1;conversation;stats;formatter;constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=(0,af.loadCurrentConversation)(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=(0,Pye.createFormatter)({colors:!e.flags.noColors,emojis:!e.flags.noEmojis})}async start(){for(this.running=!0,this.displayWelcome();this.running;)try{let e=await this.getUserInput();if(!e.trim()||await this.handleSpecialCommands(e))continue;this.conversation.messages.push({role:"user",content:e,timestamp:Date.now()}),(0,af.saveConversation)(this.conversation),await this.processWithContext(e)}catch(e){if(e instanceof Error&&e.message==="EXIT")break;if(e instanceof Error&&e.message==="INTERRUPTED"){console.log(`
238
+ `)}};Ba.OutputFormatter=h_;function iye(t={}){return new h_(t)}});var __=y(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});g_.inferProviderFromModel=T2;g_.resolveProvider=sye;var oye=[{provider:"anthropic",patterns:[/^claude-/,/^claude$/i]},{provider:"openai",patterns:[/^gpt-/,/^o1-/,/^o3-/,/^chatgpt-/,/^text-davinci/]},{provider:"gemini",patterns:[/^gemini-/,/^gemini$/i]},{provider:"deepseek",patterns:[/^deepseek-/,/^deepseek$/i]},{provider:"moonshot",patterns:[/^kimi-/,/^moonshot-/,/^moonshot$/i]},{provider:"zai",patterns:[/^glm-/,/^glm$/i,/^chatglm/i]}];function T2(t){if(!t)return;let e=t.toLowerCase();for(let{provider:r,patterns:n}of oye)for(let i of n)if(i.test(e))return r}function sye(t,e){return t?T2(t)??e:e}});var k2=y(or=>{"use strict";var aye=or&&or.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),uye=or&&or.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dO=or&&or.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&aye(r,e,n[i]);return uye(r,e),r}}();Object.defineProperty(or,"__esModule",{value:!0});or.loadCurrentConversation=fye;or.createNewConversation=fO;or.saveConversation=pO;or.setCurrentConversation=I2;or.addMessage=pye;or.clearCurrentConversation=mye;or.getConversationHistoryForAPI=hye;or.listConversations=gye;var ho=dO(require("fs")),y_=dO(require("path")),cye=dO(require("os")),wc=y_.join(cye.homedir(),".aii","conversations"),lO=y_.join(wc,"current.json");function sf(){ho.existsSync(wc)||ho.mkdirSync(wc,{recursive:!0})}function lye(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dye(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function j2(t){return y_.join(wc,`${t}.json`)}function fye(){sf();try{if(ho.existsSync(lO)){let t=ho.readFileSync(lO,"utf-8"),e=JSON.parse(t),r=j2(e.id);if(ho.existsSync(r)){let n=ho.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return fO()}function fO(){sf();let t={id:lye(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return pO(t),I2(t.id),t}function pO(t){if(sf(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=dye(r.content))}t.updatedAt=Date.now();let e=j2(t.id);ho.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}function I2(t){sf(),ho.writeFileSync(lO,JSON.stringify({id:t}),"utf-8")}function pye(t,e,r){t.messages.push({role:e,content:r,timestamp:Date.now()}),pO(t)}function mye(){return fO()}function hye(t){return t.messages.map(e=>({role:e.role,content:e.content}))}function gye(){sf();let t=[];try{let e=ho.readdirSync(wc);for(let r of e)if(r.endsWith(".json")&&r!=="current.json")try{let n=ho.readFileSync(y_.join(wc,r),"utf-8");t.push(JSON.parse(n))}catch{}}catch{}return t.sort((e,r)=>r.updatedAt-e.updatedAt)}});var mO=y(Vr=>{"use strict";var _ye=Vr&&Vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),yye=Vr&&Vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vye=Vr&&Vr.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&_ye(r,e,n[i]);return yye(r,e),r}}(),bye=Vr&&Vr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vr,"__esModule",{value:!0});Vr.InteractiveChatSession=void 0;Vr.handleChat=Cye;var $ye=vye(require("readline")),A2=bye((St(),Et(Tt))),Sye=vc(),wye=$c(),Dye=Sc(),Pye=Ns(),M2=So(),Oye=__(),af=k2(),Eye="0.2.2",v_=class{configManager;parsed;running=!1;conversation;stats;formatter;constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=(0,af.loadCurrentConversation)(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=(0,Pye.createFormatter)({colors:!e.flags.noColors,emojis:!e.flags.noEmojis})}async start(){for(this.running=!0,this.displayWelcome();this.running;)try{let e=await this.getUserInput();if(!e.trim()||await this.handleSpecialCommands(e))continue;this.conversation.messages.push({role:"user",content:e,timestamp:Date.now()}),(0,af.saveConversation)(this.conversation),await this.processWithContext(e)}catch(e){if(e instanceof Error&&e.message==="EXIT")break;if(e instanceof Error&&e.message==="INTERRUPTED"){console.log(`
239
239
  \u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(A2.default.red(`
240
240
  \u274C Error: ${e instanceof Error?e.message:String(e)}`)),this.conversation.messages.length>0&&this.conversation.messages[this.conversation.messages.length-1].role==="user"&&(this.conversation.messages.pop(),(0,af.saveConversation)(this.conversation))}}displayWelcome(){console.log("\u{1F916} Entering interactive mode."),console.log(""),console.log("Controls:"),console.log(" \u2022 Enter - Send message"),console.log(" \u2022 End with \\ - Multi-line mode"),console.log(" \u2022 /exit - Quit chat"),console.log(" \u2022 /help - Show all commands"),console.log("")}getUserInput(){return new Promise((e,r)=>{let n=$ye.createInterface({input:process.stdin,output:process.stdout}),i=[],o=!1,s=()=>{o=!0,n.close()},a=u=>{n.question(u,c=>{if(i.length===0&&c.trim().startsWith("/")){s(),e(c.trim());return}c.endsWith("\\")?(i.push(c.slice(0,-1)),a(" ")):(i.push(c),s(),e(i.join(`
241
241
  `).trim()))})};n.on("SIGINT",()=>{s(),r(new Error("INTERRUPTED"))}),n.on("close",()=>{o||r(new Error("EXIT"))}),a("> ")})}async handleSpecialCommands(e){let r=e.trim().toLowerCase();if(r.startsWith("/"))r=r.slice(1);else return!1;switch(r){case"exit":case"quit":return await this.handleExit(),!0;case"help":return this.displayHelp(),!0;case"clear":case"new":return this.clearConversation(),!0;case"history":return this.displayConversationHistory(),!0;case"stats":return this.displayStats(),!0;case"version":return this.displayVersion(),!0;default:return console.log(A2.default.yellow(`Unknown command: /${r}. Type /help for available commands.`)),console.log(""),!0}}async processWithContext(e){let r=await this.configManager.load(),n=this.configManager.validate();if(!n.valid)throw new M2.ConfigError(n.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",s=this.parsed.flags.model??r.llm.model,a=(0,Oye.resolveProvider)(this.parsed.flags.model,r.llm.provider),u=this.configManager.getApiKey(a);if(!u)throw new M2.AuthError(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let c=(0,wye.createSpinner)(!this.parsed.flags.noAnimations);c.start("");let l=(0,Dye.createStreamingFormatter)({spinner:c,enabled:!this.parsed.flags.noStreaming}),d=this.conversation.messages.slice(-21,-1).map(S=>({role:S.role,content:S.content})),p={api_key:o,system_prompt:null,user_prompt:e,user_message:e,output_mode:"CLEAN",streaming:!this.parsed.flags.noStreaming,model:s,llm_provider:a,llm_api_key:u,provider_api_key:u,client_type:"cli",offline:this.parsed.flags.offline,conversation_history:d.length>0?d:void 0},g=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,m=new Sye.AiiWebSocketClient({url:g}),h="",$=!1;try{let S=await m.executeRequest(p,{onToken:O=>{h+=O,$=!0,l.onToken(O)}});l.flush();let w=S.result||h;!$&&w&&console.log(w),console.log(""),S.metadata&&this.displayExecutionSummary(S.metadata),w&&(this.conversation.messages.push({role:"assistant",content:w,timestamp:Date.now()}),(0,af.saveConversation)(this.conversation))}catch(S){throw c.stop(!0),S}finally{m.disconnect()}}displayExecutionSummary(e){let r=e.cost||0,n=e.tokens_in||0,i=e.tokens_out||0,o=n+i;this.stats.cumulativeTokens+=o,this.stats.cumulativeCost+=r,console.log(this.formatter.formatExecutionSummary({model:e.model,tokens_in:n,tokens_out:i,cost:r,execution_time:e.execution_time})),console.log("")}clearConversation(){this.conversation=(0,af.clearCurrentConversation)(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
@@ -383,7 +383,7 @@ ${r.yellow("EXAMPLES:")}
383
383
  ${r.yellow("CONFIG FILE:")}
384
384
  ~/.aii/config.yaml Main configuration
385
385
  ~/.aii/secrets.yaml API keys (secure storage)
386
- `)}});var L2=y(zo=>{"use strict";var yve=zo&&zo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),vve=zo&&zo.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bve=zo&&zo.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&yve(r,e,n[i]);return vve(r,e),r}}();Object.defineProperty(zo,"__esModule",{value:!0});zo.handleDoctor=Sve;var bO=bve(require("fs")),$ve=Ns();async function Sve(t,e){let r=(0,$ve.createFormatter)({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[];e.configExists()?n.push({name:"Configuration file",status:"ok",message:"Found"}):n.push({name:"Configuration file",status:"warn",message:"Not found (using defaults)"});let i=await e.load(),o=e.getApiKey();if(o){let p=Dve(o);n.push({name:"LLM Model",status:"ok",message:`${i.llm.model}@${i.llm.provider} (${p})`})}else n.push({name:"LLM Model",status:"error",message:`Not configured for ${i.llm.provider}`});let s=await wve(i.api.url);n.push({name:"AII Server",status:s.ok?"ok":"error",message:s.message});let a=`${e.getConfigDir()}/mcp_servers.json`;if(bO.existsSync(a))try{let p=bO.readFileSync(a,"utf-8"),g=JSON.parse(p),m=Object.keys(g.mcpServers??{}).length;m>0?n.push({name:"MCP Servers",status:"ok",message:`${m} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});let u=e.getConfigDir();bO.existsSync(u)?n.push({name:"Storage Directory",status:"ok",message:u}):n.push({name:"Storage Directory",status:"warn",message:"Not created"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js Version",status:"ok",message:c}):n.push({name:"Node.js Version",status:"error",message:`${c} (requires >= 18)`}),console.log(r.formatHealthCheck(n)),n.some(p=>p.status==="error")&&process.exit(1)}async function wve(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let i=new URL(t);return{ok:!0,message:`Running at ${i.hostname}:${i.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}function Dve(t){return t.length<=10?"***":t.slice(0,6)+"..."+t.slice(-4)}});var U2=y(Dc=>{"use strict";var Pve=Dc&&Dc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dc,"__esModule",{value:!0});Dc.handleHelp=Eve;Dc.handleVersion=Cve;var Ove=Pve((St(),Et(Tt))),z2="0.2.1";function Eve(t){let r=!t.flags.noColors?Ove.default:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
386
+ `)}});var L2=y(zo=>{"use strict";var yve=zo&&zo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),vve=zo&&zo.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bve=zo&&zo.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&yve(r,e,n[i]);return vve(r,e),r}}();Object.defineProperty(zo,"__esModule",{value:!0});zo.handleDoctor=Sve;var bO=bve(require("fs")),$ve=Ns();async function Sve(t,e){let r=(0,$ve.createFormatter)({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[];e.configExists()?n.push({name:"Configuration file",status:"ok",message:"Found"}):n.push({name:"Configuration file",status:"warn",message:"Not found (using defaults)"});let i=await e.load(),o=e.getApiKey();if(o){let p=Dve(o);n.push({name:"LLM Model",status:"ok",message:`${i.llm.model}@${i.llm.provider} (${p})`})}else n.push({name:"LLM Model",status:"error",message:`Not configured for ${i.llm.provider}`});let s=await wve(i.api.url);n.push({name:"AII Server",status:s.ok?"ok":"error",message:s.message});let a=`${e.getConfigDir()}/mcp_servers.json`;if(bO.existsSync(a))try{let p=bO.readFileSync(a,"utf-8"),g=JSON.parse(p),m=Object.keys(g.mcpServers??{}).length;m>0?n.push({name:"MCP Servers",status:"ok",message:`${m} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});let u=e.getConfigDir();bO.existsSync(u)?n.push({name:"Storage Directory",status:"ok",message:u}):n.push({name:"Storage Directory",status:"warn",message:"Not created"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js Version",status:"ok",message:c}):n.push({name:"Node.js Version",status:"error",message:`${c} (requires >= 18)`}),console.log(r.formatHealthCheck(n)),n.some(p=>p.status==="error")&&process.exit(1)}async function wve(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let i=new URL(t);return{ok:!0,message:`Running at ${i.hostname}:${i.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}function Dve(t){return t.length<=10?"***":t.slice(0,6)+"..."+t.slice(-4)}});var U2=y(Dc=>{"use strict";var Pve=Dc&&Dc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dc,"__esModule",{value:!0});Dc.handleHelp=Eve;Dc.handleVersion=Cve;var Ove=Pve((St(),Et(Tt))),z2="0.2.2";function Eve(t){let r=!t.flags.noColors?Ove.default:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
387
387
  ${r.cyan("AII")} - AI-powered CLI assistant v${z2}
388
388
 
389
389
  ${r.yellow("USAGE:")}
@@ -511,7 +511,7 @@ ${r.yellow("DOCUMENTATION:")}
511
511
  `){if(this.commandMenu?.getIsVisible()){let w=this.commandMenu.getSelected();if(w){let O="\b \b".repeat(s.length);process.stdout.write(O),s="/"+w.name,process.stdout.write(s),this.commandMenu.hide(c()),l();return}}m(s);return}if(S===" "){if(this.commandMenu?.getIsVisible()){let w=this.commandMenu.getSelected();if(w){let O="\b \b".repeat(s.length);process.stdout.write(O),s="/"+w.name+" ",process.stdout.write(s),this.commandMenu.hide(c()),l()}}return}if(S===""&&(this.commandMenu&&this.commandMenu.hide(c()),process.stdin.removeListener("data",h),process.stdin.isTTY&&process.stdin.setRawMode(d??!1),console.log(`
512
512
  `),process.exit(0)),S==="\f"){this.emit("clearScreen",s);return}if(S==="\x7F"||S==="\b"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"),l(),g());return}for(let w of S)w>=" "&&w<="~"&&s.length<e&&(p(),s+=w,process.stdout.write(w),l());g()};process.stdin.on("data",h)})}async getChar(e=""){return new Promise(r=>{e&&process.stdout.write(e);let n=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let i=o=>{let s=o.toString();s===""&&(process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.removeListener("data",i),console.log(`
513
513
  `),process.exit(0)),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.removeListener("data",i),process.stdout.write(s+`
514
- `),r(s)};process.stdin.once("data",i)})}async confirm(e,r=!1){let n=r?"[Y/n]":"[y/N]",i=await this.getInput(`${e} ${n} `);return i.trim()?i.toLowerCase().startsWith("y"):r}addToHistory(e){this.inputHistory[this.inputHistory.length-1]!==e&&(this.inputHistory.push(e),this.historyIndex=this.inputHistory.length,this.inputHistory.length>100&&(this.inputHistory.shift(),this.historyIndex=this.inputHistory.length))}getPreviousInput(){return this.historyIndex>0?(this.historyIndex--,this.inputHistory[this.historyIndex]??null):null}getNextInput(){return this.historyIndex<this.inputHistory.length-1?(this.historyIndex++,this.inputHistory[this.historyIndex]??null):(this.historyIndex=this.inputHistory.length,null)}clearLine(){process.stdout.isTTY&&(K2.clearLine(process.stdout,0),K2.cursorTo(process.stdout,0))}close(){process.stdin.isTTY&&process.stdin.isRaw&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.unref(),this.emit("close")}};Wr.InputHandler=O_;function Vve(){return new O_}});var Ec=y(N=>{"use strict";var Kve=N&&N.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(N,"__esModule",{value:!0});N.colors=N.VERSION=void 0;N.printLogo=Gve;N.printPrompt=Wve;N.printAction=Hve;N.printToolComplete=Jve;N.printToolFailed=Yve;N.printSuccess=Xve;N.printWarning=Qve;N.printError=ebe;N.printDivider=H2;N.printHeader=tbe;N.getActionIndicator=rbe;N.formatPath=nbe;N.formatCode=ibe;N.printPermissionPrompt=obe;N.printModelInfo=sbe;N.printTokenUsage=abe;N.shortenPath=ube;N.padEndAnsi=cbe;N.printWelcomeBanner=lbe;N.printInputBox=dbe;N.printContextLine=fbe;N.getModeDisplay=J2;N.printStatusBar=pbe;N.printInputBoxTop=mbe;N.printInputBoxBottom=hbe;N.getPromptWithHint=gbe;N.printExitSummary=ybe;var bt=Kve((St(),Et(Tt)));N.VERSION="0.2.1";var W2=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u255A\u2550\u255D \u255A\u2550\u255D","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"];N.colors={logo:bt.default.cyan.bold,prompt:bt.default.cyan.bold,model:bt.default.cyan,success:bt.default.green,warning:bt.default.yellow,error:bt.default.red,thinking:bt.default.dim.cyan,filePath:bt.default.blue,code:bt.default.white,muted:bt.default.gray,dim:bt.default.dim,safe:bt.default.green,risky:bt.default.yellow,destructive:bt.default.red,border:bt.default.cyan,bannerBorder:bt.default.cyan};function Gve(t=N.VERSION){console.log(N.colors.logo(W2)+N.colors.dim(` v${t}`))}function Wve(t="> "){process.stdout.write(N.colors.prompt(t))}function Hve(t,e){console.log(N.colors.dim("\u25CB ")+bt.default.white(t)+" "+N.colors.filePath(e))}function Jve(t,e){console.log(N.colors.success("\u2713 ")+bt.default.white(t)+" "+N.colors.filePath(e))}function Yve(t,e,r){console.log(N.colors.error("\u2717 ")+bt.default.white(t)+" "+N.colors.filePath(e)),r&&console.log(N.colors.dim(" \u2192 ")+N.colors.error(r))}function Xve(t){console.log(N.colors.success("\u2713 ")+t)}function Qve(t){console.log(N.colors.warning("\u26A0 ")+t)}function ebe(t){console.log(N.colors.error("\u2717 ")+t)}function H2(t=60){console.log(N.colors.dim("\u2500".repeat(t)))}function tbe(t){console.log(N.colors.logo(t)),H2(t.length)}function rbe(t){return N.colors.thinking(`[${t}]`)}function nbe(t){let e=process.env.HOME??process.env.USERPROFILE??"";return e&&t.startsWith(e)?N.colors.filePath("~"+t.slice(e.length)):N.colors.filePath(t)}function ibe(t){return N.colors.code(t)}function obe(t,e){let r=" Permission Required ",n="(y)es / (n)o / (a)lways / (s)ession",i=`Aii wants to run: ${t}`,o=60,s=process.stdout.columns||80,a=Math.min(s-2,120),u=[i.length+4,e.length+4,n.length+4],c=Math.max(...u),l=Math.max(o,Math.min(c,a)),d=Math.max(0,l-3-r.length),p=l-2,g=h=>h.replace(/\x1b\[[0-9;]*m/g,""),m=(h,$)=>{let S=$??g(h),w=h,O=S.length,T=p-1;if(O>T){let x=S.slice(0,T-3)+"...";w=h===S?x:N.colors.dim(x),O=x.length}let C=Math.max(0,p-O-1);return N.colors.warning("\u2502")+" "+w+" ".repeat(C)+N.colors.warning("\u2502")};console.log(""),console.log(N.colors.warning("\u250C\u2500"+r+"\u2500".repeat(d)+"\u2510")),console.log(m("")),console.log(m(`Aii wants to run: ${bt.default.bold(t)}`,i)),console.log(m(N.colors.dim(e),e)),console.log(m("")),console.log(m(N.colors.prompt(n),n)),console.log(N.colors.warning("\u2514"+"\u2500".repeat(l-2)+"\u2518"))}function sbe(t,e){let r=e?N.colors.dim(` (${e})`):"";console.log(`Model: ${N.colors.model(t)}${r}`)}function abe(t,e,r){let n=`${N.colors.dim("Tokens:")} ${t} in / ${e} out`;r!==void 0&&(n+=` ${N.colors.dim("\u2022")} $${r.toFixed(4)}`),console.log(N.colors.dim(n))}function Oc(){return process.stdout.columns||80}function ube(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let i=n.split("/").filter(s=>s.length>0);if(i.length>=2){let s=i.slice(-2).join("/");if(s.length<=e-4)return".../"+s}return".../"+(i[i.length-1]||i[i.length-2])}function SO(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function cbe(t,e){let r=SO(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function lbe(t){let e=Oc(),r=Math.min(e,90),n=r-5,i=Math.floor(n*.42),o=n-i,s=S=>S.replace(/\x1b\[[0-9;]*m/g,"").length,a=(S,w)=>{let O=s(S);return S+" ".repeat(Math.max(0,w-O))},u=W2.map(S=>N.colors.logo(S)),c=N.colors.success("Tips for getting started"),l="Ask questions, edit files, or run commands.",d="Be specific for the best results.",p=N.colors.dim("/help")+" for more information.",g=[];g.push({left:"",right:c});for(let S=0;S<6;S++){let w=u[S]||"",O="";S===0&&(O=l),S===1&&(O=d),S===2&&(O=p),g.push({left:w,right:O})}let m=` Aii CLI v${N.VERSION} `,h=m.length,$=r-4-h;console.log(N.colors.bannerBorder("\u250C\u2500")+bt.default.bold.white(m)+N.colors.bannerBorder("\u2500".repeat(Math.max(0,$)))+N.colors.bannerBorder("\u2500\u2510"));for(let S of g){let w=a(S.left,i),O=a(S.right,o);console.log(N.colors.bannerBorder("\u2502")+" "+w+N.colors.bannerBorder("\u2502")+" "+O+N.colors.bannerBorder("\u2502"))}console.log(N.colors.bannerBorder("\u2514"+"\u2500".repeat(r-2)+"\u2518"))}function dbe(){let t=Math.min(Oc()-2,80);console.log(N.colors.dim("\u250C"+"\u2500".repeat(t)+"\u2510")),console.log(N.colors.dim("\u2502 ")+N.colors.prompt("> ")+N.colors.dim("Type your message or @path/to/file")+N.colors.dim(" ".repeat(Math.max(0,t-36)))+N.colors.dim("\u2502")),console.log(N.colors.dim("\u2514"+"\u2500".repeat(t)+"\u2518"))}function fbe(t){let e=[];t.tools&&t.tools>0&&e.push(`${t.tools} tool${t.tools>1?"s":""}`);let r=t.mcpServers??0;r>0&&e.push(`${r} MCP server${r>1?"s":""}`),t.contextFiles&&t.contextFiles>0&&e.push(`${t.contextFiles} context file${t.contextFiles>1?"s":""}`),e.length>0&&console.log(N.colors.dim("Using: ")+N.colors.dim(e.join(" | ")))}function J2(t){switch(t){case"auto":return N.colors.warning("Auto");case"plan":return N.colors.thinking("Plan");case"interactive":default:return N.colors.success("Normal")}}function pbe(t){let e=Oc(),r=N.colors.filePath(t.projectPath);t.branch&&(r+=N.colors.dim(` (${t.branch})`));let n=t.model.replace("claude-","").replace("deepseek-","").replace("-latest",""),i=J2(t.mode)+N.colors.dim(" (")+N.colors.model(n)+N.colors.dim(")");t.memoryMB!==void 0&&(i+=N.colors.dim(" | ")+N.colors.dim(`${t.memoryMB.toFixed(1)} MB`));let o=SO(r),s=SO(i),a=Math.max(1,e-o-s-2);console.log(r+" ".repeat(a)+i)}function mbe(){let t=Math.min(Oc(),100);console.log(N.colors.dim("\u250C"+"\u2500".repeat(t-2)+"\u2510"))}function hbe(){let t=Math.min(Oc(),100);console.log(N.colors.dim("\u2514"+"\u2500".repeat(t-2)+"\u2518"))}function gbe(t=!0){return t?N.colors.prompt("> ")+N.colors.dim("Type your message..."):N.colors.prompt("> ")}function _be(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function G2(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function ybe(t){let e=Oc(),r=Math.min(e-2,76),n=r-4,i=(p,g)=>{let m=p.replace(/\x1b\[[0-9;]*m/g,"").length;return p+" ".repeat(Math.max(0,g-m))},o=p=>N.colors.border("\u2502")+" "+i(p,n)+" "+N.colors.border("\u2502"),s=(p,g,m,h)=>{let $=Math.floor(n/2),S=N.colors.dim(p.padEnd(15))+g,w=N.colors.dim(m.padEnd(15))+h;return o(i(S,$)+w)},a=_be(t.durationSeconds),u=G2(t.tokensIn),c=G2(t.tokensOut),l=`$${t.totalCost.toFixed(4)}`,d=`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(N.colors.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(bt.default.cyan.bold("Agent powering down. Goodbye!"))),console.log(N.colors.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(N.colors.success("Session Summary"))),console.log(o(N.colors.dim("\u2500".repeat(15)))),console.log(s("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(s("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(N.colors.success("Token Usage"))),console.log(o(N.colors.dim("\u2500".repeat(11)))),console.log(s("Input",u,"Output",c)),console.log(o(N.colors.dim("Cost".padEnd(15))+l)),console.log(o("")),console.log(o(N.colors.dim("Model: ")+N.colors.model(d))),console.log(N.colors.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}});var wO=y(Ka=>{"use strict";var vbe=Ka&&Ka.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ka,"__esModule",{value:!0});Ka.CommandRegistry=void 0;Ka.createCommandRegistry=$be;var de=vbe((St(),Et(Tt))),bbe=Ec(),C_=class{commands=new Map;constructor(){this.registerBuiltinCommands()}register(e){if(this.commands.set(e.name,e),e.aliases)for(let r of e.aliases)this.commands.set(r,e)}isCommand(e){return e.startsWith("/")}async execute(e,r){if(!this.isCommand(e))return{continue:!0,handled:!1};let n=e.slice(1).split(/\s+/),i=n[0]?.toLowerCase()??"",o=n.slice(1).join(" "),s=this.commands.get(i);return s?s.handler(o,r):{continue:!0,handled:!0,output:de.default.yellow(`Unknown command: /${i}. Type /help for available commands.`)}}getCommands(){let e=new Set,r=[];for(let[,n]of this.commands)e.has(n.name)||(e.add(n.name),r.push(n));return r.sort((n,i)=>n.name.localeCompare(i.name))}registerBuiltinCommands(){this.register({name:"help",aliases:["?","h"],description:"Show available commands",handler:()=>{let e=[];e.push(de.default.cyan.bold("Available Commands:")),e.push("");for(let r of this.getCommands()){let n=r.aliases?de.default.dim(` (${r.aliases.join(", ")})`):"";e.push(` ${de.default.cyan("/"+r.name)}${n}`),e.push(` ${de.default.gray(r.description)}`),r.usage&&e.push(` ${de.default.dim("Usage: "+r.usage)}`)}return{continue:!0,handled:!0,output:e.join(`
514
+ `),r(s)};process.stdin.once("data",i)})}async confirm(e,r=!1){let n=r?"[Y/n]":"[y/N]",i=await this.getInput(`${e} ${n} `);return i.trim()?i.toLowerCase().startsWith("y"):r}addToHistory(e){this.inputHistory[this.inputHistory.length-1]!==e&&(this.inputHistory.push(e),this.historyIndex=this.inputHistory.length,this.inputHistory.length>100&&(this.inputHistory.shift(),this.historyIndex=this.inputHistory.length))}getPreviousInput(){return this.historyIndex>0?(this.historyIndex--,this.inputHistory[this.historyIndex]??null):null}getNextInput(){return this.historyIndex<this.inputHistory.length-1?(this.historyIndex++,this.inputHistory[this.historyIndex]??null):(this.historyIndex=this.inputHistory.length,null)}clearLine(){process.stdout.isTTY&&(K2.clearLine(process.stdout,0),K2.cursorTo(process.stdout,0))}close(){process.stdin.isTTY&&process.stdin.isRaw&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.unref(),this.emit("close")}};Wr.InputHandler=O_;function Vve(){return new O_}});var Ec=y(N=>{"use strict";var Kve=N&&N.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(N,"__esModule",{value:!0});N.colors=N.VERSION=void 0;N.printLogo=Gve;N.printPrompt=Wve;N.printAction=Hve;N.printToolComplete=Jve;N.printToolFailed=Yve;N.printSuccess=Xve;N.printWarning=Qve;N.printError=ebe;N.printDivider=H2;N.printHeader=tbe;N.getActionIndicator=rbe;N.formatPath=nbe;N.formatCode=ibe;N.printPermissionPrompt=obe;N.printModelInfo=sbe;N.printTokenUsage=abe;N.shortenPath=ube;N.padEndAnsi=cbe;N.printWelcomeBanner=lbe;N.printInputBox=dbe;N.printContextLine=fbe;N.getModeDisplay=J2;N.printStatusBar=pbe;N.printInputBoxTop=mbe;N.printInputBoxBottom=hbe;N.getPromptWithHint=gbe;N.printExitSummary=ybe;var bt=Kve((St(),Et(Tt)));N.VERSION="0.2.2";var W2=[" \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u255A\u2550\u255D \u255A\u2550\u255D","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"];N.colors={logo:bt.default.cyan.bold,prompt:bt.default.cyan.bold,model:bt.default.cyan,success:bt.default.green,warning:bt.default.yellow,error:bt.default.red,thinking:bt.default.dim.cyan,filePath:bt.default.blue,code:bt.default.white,muted:bt.default.gray,dim:bt.default.dim,safe:bt.default.green,risky:bt.default.yellow,destructive:bt.default.red,border:bt.default.cyan,bannerBorder:bt.default.cyan};function Gve(t=N.VERSION){console.log(N.colors.logo(W2)+N.colors.dim(` v${t}`))}function Wve(t="> "){process.stdout.write(N.colors.prompt(t))}function Hve(t,e){console.log(N.colors.dim("\u25CB ")+bt.default.white(t)+" "+N.colors.filePath(e))}function Jve(t,e){console.log(N.colors.success("\u2713 ")+bt.default.white(t)+" "+N.colors.filePath(e))}function Yve(t,e,r){console.log(N.colors.error("\u2717 ")+bt.default.white(t)+" "+N.colors.filePath(e)),r&&console.log(N.colors.dim(" \u2192 ")+N.colors.error(r))}function Xve(t){console.log(N.colors.success("\u2713 ")+t)}function Qve(t){console.log(N.colors.warning("\u26A0 ")+t)}function ebe(t){console.log(N.colors.error("\u2717 ")+t)}function H2(t=60){console.log(N.colors.dim("\u2500".repeat(t)))}function tbe(t){console.log(N.colors.logo(t)),H2(t.length)}function rbe(t){return N.colors.thinking(`[${t}]`)}function nbe(t){let e=process.env.HOME??process.env.USERPROFILE??"";return e&&t.startsWith(e)?N.colors.filePath("~"+t.slice(e.length)):N.colors.filePath(t)}function ibe(t){return N.colors.code(t)}function obe(t,e){let r=" Permission Required ",n="(y)es / (n)o / (a)lways / (s)ession",i=`Aii wants to run: ${t}`,o=60,s=process.stdout.columns||80,a=Math.min(s-2,120),u=[i.length+4,e.length+4,n.length+4],c=Math.max(...u),l=Math.max(o,Math.min(c,a)),d=Math.max(0,l-3-r.length),p=l-2,g=h=>h.replace(/\x1b\[[0-9;]*m/g,""),m=(h,$)=>{let S=$??g(h),w=h,O=S.length,T=p-1;if(O>T){let x=S.slice(0,T-3)+"...";w=h===S?x:N.colors.dim(x),O=x.length}let C=Math.max(0,p-O-1);return N.colors.warning("\u2502")+" "+w+" ".repeat(C)+N.colors.warning("\u2502")};console.log(""),console.log(N.colors.warning("\u250C\u2500"+r+"\u2500".repeat(d)+"\u2510")),console.log(m("")),console.log(m(`Aii wants to run: ${bt.default.bold(t)}`,i)),console.log(m(N.colors.dim(e),e)),console.log(m("")),console.log(m(N.colors.prompt(n),n)),console.log(N.colors.warning("\u2514"+"\u2500".repeat(l-2)+"\u2518"))}function sbe(t,e){let r=e?N.colors.dim(` (${e})`):"";console.log(`Model: ${N.colors.model(t)}${r}`)}function abe(t,e,r){let n=`${N.colors.dim("Tokens:")} ${t} in / ${e} out`;r!==void 0&&(n+=` ${N.colors.dim("\u2022")} $${r.toFixed(4)}`),console.log(N.colors.dim(n))}function Oc(){return process.stdout.columns||80}function ube(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let i=n.split("/").filter(s=>s.length>0);if(i.length>=2){let s=i.slice(-2).join("/");if(s.length<=e-4)return".../"+s}return".../"+(i[i.length-1]||i[i.length-2])}function SO(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function cbe(t,e){let r=SO(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function lbe(t){let e=Oc(),r=Math.min(e,90),n=r-5,i=Math.floor(n*.42),o=n-i,s=S=>S.replace(/\x1b\[[0-9;]*m/g,"").length,a=(S,w)=>{let O=s(S);return S+" ".repeat(Math.max(0,w-O))},u=W2.map(S=>N.colors.logo(S)),c=N.colors.success("Tips for getting started"),l="Ask questions, edit files, or run commands.",d="Be specific for the best results.",p=N.colors.dim("/help")+" for more information.",g=[];g.push({left:"",right:c});for(let S=0;S<6;S++){let w=u[S]||"",O="";S===0&&(O=l),S===1&&(O=d),S===2&&(O=p),g.push({left:w,right:O})}let m=` Aii CLI v${N.VERSION} `,h=m.length,$=r-4-h;console.log(N.colors.bannerBorder("\u250C\u2500")+bt.default.bold.white(m)+N.colors.bannerBorder("\u2500".repeat(Math.max(0,$)))+N.colors.bannerBorder("\u2500\u2510"));for(let S of g){let w=a(S.left,i),O=a(S.right,o);console.log(N.colors.bannerBorder("\u2502")+" "+w+N.colors.bannerBorder("\u2502")+" "+O+N.colors.bannerBorder("\u2502"))}console.log(N.colors.bannerBorder("\u2514"+"\u2500".repeat(r-2)+"\u2518"))}function dbe(){let t=Math.min(Oc()-2,80);console.log(N.colors.dim("\u250C"+"\u2500".repeat(t)+"\u2510")),console.log(N.colors.dim("\u2502 ")+N.colors.prompt("> ")+N.colors.dim("Type your message or @path/to/file")+N.colors.dim(" ".repeat(Math.max(0,t-36)))+N.colors.dim("\u2502")),console.log(N.colors.dim("\u2514"+"\u2500".repeat(t)+"\u2518"))}function fbe(t){let e=[];t.tools&&t.tools>0&&e.push(`${t.tools} tool${t.tools>1?"s":""}`);let r=t.mcpServers??0;r>0&&e.push(`${r} MCP server${r>1?"s":""}`),t.contextFiles&&t.contextFiles>0&&e.push(`${t.contextFiles} context file${t.contextFiles>1?"s":""}`),e.length>0&&console.log(N.colors.dim("Using: ")+N.colors.dim(e.join(" | ")))}function J2(t){switch(t){case"auto":return N.colors.warning("Auto");case"plan":return N.colors.thinking("Plan");case"interactive":default:return N.colors.success("Normal")}}function pbe(t){let e=Oc(),r=N.colors.filePath(t.projectPath);t.branch&&(r+=N.colors.dim(` (${t.branch})`));let n=t.model.replace("claude-","").replace("deepseek-","").replace("-latest",""),i=J2(t.mode)+N.colors.dim(" (")+N.colors.model(n)+N.colors.dim(")");t.memoryMB!==void 0&&(i+=N.colors.dim(" | ")+N.colors.dim(`${t.memoryMB.toFixed(1)} MB`));let o=SO(r),s=SO(i),a=Math.max(1,e-o-s-2);console.log(r+" ".repeat(a)+i)}function mbe(){let t=Math.min(Oc(),100);console.log(N.colors.dim("\u250C"+"\u2500".repeat(t-2)+"\u2510"))}function hbe(){let t=Math.min(Oc(),100);console.log(N.colors.dim("\u2514"+"\u2500".repeat(t-2)+"\u2518"))}function gbe(t=!0){return t?N.colors.prompt("> ")+N.colors.dim("Type your message..."):N.colors.prompt("> ")}function _be(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function G2(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function ybe(t){let e=Oc(),r=Math.min(e-2,76),n=r-4,i=(p,g)=>{let m=p.replace(/\x1b\[[0-9;]*m/g,"").length;return p+" ".repeat(Math.max(0,g-m))},o=p=>N.colors.border("\u2502")+" "+i(p,n)+" "+N.colors.border("\u2502"),s=(p,g,m,h)=>{let $=Math.floor(n/2),S=N.colors.dim(p.padEnd(15))+g,w=N.colors.dim(m.padEnd(15))+h;return o(i(S,$)+w)},a=_be(t.durationSeconds),u=G2(t.tokensIn),c=G2(t.tokensOut),l=`$${t.totalCost.toFixed(4)}`,d=`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(N.colors.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(bt.default.cyan.bold("Agent powering down. Goodbye!"))),console.log(N.colors.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(N.colors.success("Session Summary"))),console.log(o(N.colors.dim("\u2500".repeat(15)))),console.log(s("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(s("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(N.colors.success("Token Usage"))),console.log(o(N.colors.dim("\u2500".repeat(11)))),console.log(s("Input",u,"Output",c)),console.log(o(N.colors.dim("Cost".padEnd(15))+l)),console.log(o("")),console.log(o(N.colors.dim("Model: ")+N.colors.model(d))),console.log(N.colors.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}});var wO=y(Ka=>{"use strict";var vbe=Ka&&Ka.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ka,"__esModule",{value:!0});Ka.CommandRegistry=void 0;Ka.createCommandRegistry=$be;var de=vbe((St(),Et(Tt))),bbe=Ec(),C_=class{commands=new Map;constructor(){this.registerBuiltinCommands()}register(e){if(this.commands.set(e.name,e),e.aliases)for(let r of e.aliases)this.commands.set(r,e)}isCommand(e){return e.startsWith("/")}async execute(e,r){if(!this.isCommand(e))return{continue:!0,handled:!1};let n=e.slice(1).split(/\s+/),i=n[0]?.toLowerCase()??"",o=n.slice(1).join(" "),s=this.commands.get(i);return s?s.handler(o,r):{continue:!0,handled:!0,output:de.default.yellow(`Unknown command: /${i}. Type /help for available commands.`)}}getCommands(){let e=new Set,r=[];for(let[,n]of this.commands)e.has(n.name)||(e.add(n.name),r.push(n));return r.sort((n,i)=>n.name.localeCompare(i.name))}registerBuiltinCommands(){this.register({name:"help",aliases:["?","h"],description:"Show available commands",handler:()=>{let e=[];e.push(de.default.cyan.bold("Available Commands:")),e.push("");for(let r of this.getCommands()){let n=r.aliases?de.default.dim(` (${r.aliases.join(", ")})`):"";e.push(` ${de.default.cyan("/"+r.name)}${n}`),e.push(` ${de.default.gray(r.description)}`),r.usage&&e.push(` ${de.default.dim("Usage: "+r.usage)}`)}return{continue:!0,handled:!0,output:e.join(`
515
515
  `)}}}),this.register({name:"exit",aliases:["quit","q"],description:"End the session and exit",handler:(e,r)=>{let n=Math.floor((Date.now()-r.stats.startTime)/1e3),i={sessionId:r.id.slice(-8),durationSeconds:n,turns:r.stats.totalTurns,toolCalls:r.stats.toolCalls,filesModified:r.stats.filesModified,tokensIn:r.stats.tokensIn,tokensOut:r.stats.tokensOut,totalCost:r.stats.totalCost,model:r.model,provider:r.provider};return(0,bbe.printExitSummary)(i),{continue:!1,handled:!0}}}),this.register({name:"clear",description:"Clear conversation history",handler:(e,r)=>(r.messages=[],{continue:!0,handled:!0,output:de.default.green("\u2713 Conversation history cleared")})}),this.register({name:"model",aliases:["m"],description:"Show or switch the current model",usage:"/model [model-name]",handler:(e,r)=>{if(!e.trim())return{continue:!0,handled:!0,output:`Current model: ${de.default.cyan(r.model)}`};let n=e.trim();return r.model=n,{continue:!0,handled:!0,output:de.default.green(`\u2713 Model switched to ${de.default.cyan(n)}`)}}}),this.register({name:"provider",aliases:["p"],description:"Show or switch the LLM provider",usage:"/provider [anthropic|openai|gemini|deepseek|moonshot|zai]",handler:(e,r)=>{let n={anthropic:{name:"Claude (Sonnet 4, Opus 4, Haiku 4.5)",defaultModel:"claude-haiku-4.5"},openai:{name:"GPT (GPT-5.2, GPT-4o, GPT-4.1)",defaultModel:"gpt-4.1-mini"},gemini:{name:"Gemini (3-pro, 2.5-pro, 2.5-flash)",defaultModel:"gemini-2.5-flash"},moonshot:{name:"Kimi (K2 Thinking, Vision)",defaultModel:"kimi-k2-thinking"},deepseek:{name:"DeepSeek (chat, coder, reasoner)",defaultModel:"deepseek-chat"},zai:{name:"Z.ai GLM (GLM-4.7, 4.6V, 4.5)",defaultModel:"glm-4.5-air"}},i=Object.keys(n);if(!e.trim()){let a=[];a.push(`Current provider: ${de.default.cyan(r.provider)} (${r.model})`),a.push(""),a.push(de.default.dim("Available providers:"));for(let[u,c]of Object.entries(n)){let l=u===r.provider?de.default.green("\u2192"):" ";a.push(`${l} ${de.default.cyan(u.padEnd(10))} ${de.default.dim(c.name)}`)}return{continue:!0,handled:!0,output:a.join(`
516
516
  `)}}let o=e.trim().toLowerCase();if(!i.includes(o))return{continue:!0,handled:!0,output:de.default.yellow(`Invalid provider: ${o}
517
517
  Available: ${i.join(", ")}`)};let s=n[o];return r.provider=o,r.model=s.defaultModel,{continue:!0,handled:!0,output:de.default.green(`\u2713 Provider switched to ${de.default.cyan(o)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiiware/aii",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "AI-powered CLI assistant for terminal productivity",
5
5
  "author": "AiiWare <support@aiiware.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",