@aiiware/aii 0.17.17 → 0.17.18

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 (2) hide show
  1. package/bin/aii +9 -9
  2. package/package.json +1 -1
package/bin/aii CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * @aiiware/aii v0.17.17
3
+ * @aiiware/aii v0.17.18
4
4
  *
5
5
  * AI-powered CLI assistant for terminal productivity
6
6
  *
@@ -204,7 +204,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
204
204
  Open this URL to sign in:
205
205
  ${p.verify_url}
206
206
  `),n(p.verify_url),i(" Waiting for authentication... (press Ctrl+C to cancel)");let f=Math.max(1,p.interval||2)*1e3,h=bge(p.expires_at,o());for(;;){try{let g=await c(p.poll_url);if(g.ok){let _=JSON.parse(g.text);if(_.status==="completed"&&_.api_key)return{apiKey:_.api_key};if(_.status==="expired")throw new Sa("The sign-in code expired. Run the command again to retry.")}}catch(g){if(g instanceof Sa)throw g}if(o()>=h)throw new Sa("Timed out waiting for sign-in. Run the command again to retry.");await s(f)}}var Sa,Ege,Cf=D(()=>{"use strict";Sa=class extends Error{constructor(e){super(e),this.name="DeviceAuthError"}},Ege=3e5});var DU={};ye(DU,{configureLogger:()=>Zy,debug:()=>Y,error:()=>kU,formatError:()=>e1,info:()=>CU,logger:()=>P,success:()=>AU,warn:()=>vU});function Zy(t){vf={...vf,...t}}function kf(t){return vf.emojis?t+" ":""}function Ll(t,e){return vf.colors?e(t):t}function Y(t,...e){vf.debug&&console.debug(Ll(`[DEBUG] ${t}`,m.gray),...e)}function CU(t,...e){console.log(t,...e)}function vU(t,...e){console.warn(Ll(`${kf("\u26A0\uFE0F")}${t}`,m.yellow),...e)}function kU(t,...e){console.error(Ll(`${kf("\u274C")}${t}`,m.red),...e)}function AU(t,...e){console.log(Ll(`${kf("\u2705")}${t}`,m.green),...e)}function e1(t){let e=[];return e.push(Ll(`${kf("\u274C")}${t.message}`,m.red)),t.suggestions&&t.suggestions.length>0&&(e.push(""),e.push(Ll(`${kf("\u{1F4A1}")}Solutions:`,m.yellow)),t.suggestions.forEach((r,n)=>{e.push(Ll(` ${n+1}. ${r}`,m.gray))})),e.join(`
207
- `)}var Tge,vf,P,at=D(()=>{"use strict";Se();Tge={debug:!1,colors:!0,emojis:!0},vf={...Tge};P={debug:Y,info:CU,warn:vU,error:kU,success:AU,formatError:e1,configure:Zy}});function IU(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function t1(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:IU(t.protocol_version)}}function RU(t){if(typeof t!="object"||t===null||typeof t.type=="string")return null;let e=t.error;return typeof e!="string"||e===""?null:{unknown_model:"That model is not available on Aii Cloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --local.",insufficient_credits:"Out of Aii Cloud credits. Top up to continue, or run with --local.",quota_exceeded:"Daily free-tier limit reached on Aii Cloud. Try again later, upgrade, or run with --local.",quota_check_failed:"Aii Cloud could not verify your quota \u2014 please retry.",worker_unavailable:"Aii Cloud is temporarily unavailable \u2014 please retry, or run with --local."}[e]??`Aii Cloud error: ${e}`}function Bk(t){return t==null||typeof t=="object"}function n1(t){switch(t.type){case"tool_request":return Bk(t.input);case"mcp_tool_request":return Bk(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&Bk(r.input))}default:return!0}}function s1(t){return IU(t)>2?"hard":"compatible"}function o1(t){return`This Aii Server speaks protocol v${t}, but your CLI speaks v2. Some responses may not work correctly. Update with: aii upgrade`}var NU,OU,r1,Gk=D(()=>{"use strict";NU=new Set(["token","complete","error","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),OU=new Set(["session_started","turn_ready","token","iteration_tokens_usage","tool_request","tool_batch_request","tool_status","complete","error","mcp_tools_loaded","permission_request","permission_resolution","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),r1=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});var qk={};ye(qk,{MCPConfigManager:()=>Xt,MCP_CATALOG:()=>Fl});import*as ns from"fs";import*as i1 from"path";import*as zk from"os";var Fl,Xt,ba=D(()=>{"use strict";Fl={github:{name:"GitHub",description:"GitHub API integration for repos, issues, PRs, and more",command:"npx",args:["-y","@modelcontextprotocol/server-github"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"${GITHUB_TOKEN}"},category:"development"},filesystem:{name:"Filesystem",description:"Read/write files on the local filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",zk.homedir()],category:"system"},"brave-search":{name:"Brave Search",description:"Web search using Brave Search API",command:"npx",args:["-y","@brave/brave-search-mcp-server"],env:{BRAVE_API_KEY:"${BRAVE_API_KEY}"},category:"search"},sqlite:{name:"SQLite",description:"Query SQLite databases",command:"uvx",args:["mcp-server-sqlite","--db-path","./database.db"],category:"database"},postgres:{name:"PostgreSQL",description:"Query PostgreSQL databases",command:"npx",args:["-y","@anthropic/mcp-server-postgres"],env:{DATABASE_URL:"${DATABASE_URL}"},category:"database"},"chrome-devtools":{name:"Chrome DevTools",description:"Control Chrome browser via DevTools protocol",command:"npx",args:["chrome-devtools-mcp@latest"],category:"browser"},memory:{name:"Memory",description:"Persistent memory storage for conversation context",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],category:"utility"},puppeteer:{name:"Puppeteer",description:"Browser automation with Puppeteer",command:"npx",args:["-y","@anthropic/mcp-server-puppeteer"],category:"browser"}},Xt=class{configPath;constructor(e){this.configPath=e||i1.join(zk.homedir(),".aii","mcp_servers.json"),this.ensureConfigDir()}ensureConfigDir(){let e=i1.dirname(this.configPath);ns.existsSync(e)||ns.mkdirSync(e,{recursive:!0})}loadConfig(){if(!ns.existsSync(this.configPath))return{mcpServers:{}};try{let e=ns.readFileSync(this.configPath,"utf-8"),r=JSON.parse(e);return typeof r=="object"&&r!==null?r:{mcpServers:{}}}catch{return{mcpServers:{}}}}saveConfig(e){try{return this.ensureConfigDir(),ns.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf-8"),!0}catch{return!1}}backupConfig(){if(!ns.existsSync(this.configPath))return!0;try{let e=this.configPath+".backup";return ns.copyFileSync(this.configPath,e),!0}catch{return!1}}getConfigPath(){return this.configPath}}});var wge,Cge,vge,kge,Age,Dge,Ige,$l,a1,Ta,Hk=D(()=>{"use strict";Se();wge={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:m.hex("#3B82F6"),userInput:m.hex("#3B82F6"),userInputText:m.hex("#93C5FD"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#A855F7"),link:m.hex("#3B82F6").underline,heading:m.hex("#A855F7").bold,filePath:m.hex("#3B82F6"),indicator:m.hex("#3B82F6")}},Cge={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:m.hex("#4E6BF5"),userInput:m.hex("#4E6BF5"),userInputText:m.hex("#A5B4FC"),success:m.hex("#28CA41"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#4E6BF5"),link:m.hex("#4E6BF5").underline,heading:m.hex("#4E6BF5").bold,filePath:m.hex("#4E6BF5"),indicator:m.hex("#4E6BF5")}},vge={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:m.hex("#00BCD4"),userInput:m.hex("#00BCD4"),userInputText:m.hex("#67E8F9"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#00BCD4"),link:m.hex("#00BCD4").underline,heading:m.hex("#00BCD4").bold,filePath:m.hex("#00BCD4"),indicator:m.hex("#00BCD4")}},kge={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:m.hex("#6B8AFF"),userInput:m.hex("#6B8AFF"),userInputText:m.hex("#A5B4FC"),success:m.hex("#28CA41"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#6B8AFF"),link:m.hex("#6B8AFF").underline,heading:m.hex("#6B8AFF").bold,filePath:m.hex("#6B8AFF"),indicator:m.hex("#6B8AFF")}},Age={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:m.hex("#22C55E"),userInput:m.hex("#22C55E"),userInputText:m.hex("#86EFAC"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#22C55E"),link:m.hex("#22C55E").underline,heading:m.hex("#22C55E").bold,filePath:m.hex("#22C55E"),indicator:m.hex("#22C55E")}},Dge={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:m.hex("#F59E0B"),userInput:m.hex("#F59E0B"),userInputText:m.hex("#FCD34D"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#F59E0B"),link:m.hex("#F59E0B").underline,heading:m.hex("#F59E0B").bold,filePath:m.hex("#F59E0B"),indicator:m.hex("#F59E0B")}},Ige={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:m.reset,userInput:m.reset,userInputText:m.hex("#CBD5E1"),success:m.reset,warning:m.reset,error:m.bold,muted:m.dim,dim:m.dim,code:m.reset,link:m.underline,heading:m.bold,filePath:m.reset,indicator:m.bold}},$l={classic:wge,brand:Cge,teal:vge,indigo:kge,forest:Age,amber:Dge,grayscale:Ige},a1="classic",Ta=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Ul={};ye(Ul,{ThemeManager:()=>mi,getAccentColorName:()=>ke,getThemeColors:()=>q,getUserInputTextColorName:()=>Hu});function q(){return mi.getInstance().getColors()}function ke(){return mi.getInstance().getAccentColorName()}function Hu(){return mi.getInstance().getUserInputTextColorName()}var mi,wa=D(()=>{"use strict";Hk();mi=class t{static instance=null;activeTheme;constructor(){this.activeTheme=$l[a1]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=$l[e];if(!r){let n=Ta.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in $l}getAvailableThemes(){return Ta.map(e=>$l[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}reset(){this.activeTheme=$l[a1]}}});var dt=D(()=>{"use strict";Hk();wa()});import{resolve as Rge}from"path";function Nge(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:!(t==="dumb"||!process.stdout.isTTY)}function Af(){return jk===null&&(jk=Nge()),jk}function Oge(){return process.platform==="darwin"?"Cmd":"Ctrl"}function MU(){return xU||!Af()?"":(xU=!0,` (${Oge()}+Click to open)`)}function xge(t,e){return Af()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function PU(t,e){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;r&&t.startsWith(r)&&(n="~"+t.slice(r.length));let s=e?`${n}:${e}`:n;if(!Af())return q().filePath(s);let o=q().accent(s),a=`file://${Rge(t)}`;return e!==void 0&&e>0&&(a+=`#L${e}`),xge(o,a)}var jk,xU,LU=D(()=>{"use strict";dt();jk=null,xU=!1});var UU={};ye(UU,{VERSION:()=>Bl,colors:()=>L,formatCode:()=>zge,formatPath:()=>If,getActionIndicator:()=>Gge,padEndAnsi:()=>Yge,printAction:()=>Mge,printDivider:()=>$U,printError:()=>Uge,printExitSummary:()=>Wk,printHeader:()=>Bge,printSuccess:()=>Fge,printToolComplete:()=>Pge,printToolFailed:()=>Lge,printToolResultCompact:()=>ju,printWarning:()=>$ge,shortenPath:()=>Hge});function Df(t){return t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-zA-Z]:\\/.test(t)||/\.(ts|tsx|js|jsx|json|md|py|go|rs|java|c|cpp|h|hpp|css|scss|html|xml|yaml|yml|toml|sh|bash|zsh)$/.test(t)||/^src\//.test(t)||/^lib\//.test(t)||/^test[s]?\//.test(t)}function Mge(t,e,r=console.log){let n=Df(e)?If(e):L.filePath(e);r(L.dim("\u25CB ")+m.bold(t)+" "+n)}function Pge(t,e,r=console.log){let n=Df(e)?If(e):L.filePath(e);r(L.success("\u2713 ")+m.bold(t)+" "+n)}function Lge(t,e,r,n=console.log){let s=Df(e)?If(e):L.filePath(e);n(L.error("\u2717 ")+m.bold(t)+" "+s),r&&n(L.dim(" \u2192 ")+L.error(r))}function ju(t,e,r=!0,n,s=console.log){let o=r?L.success("\u25CF"):L.error("\u25CF"),i=60,a=e.length>i?e.slice(0,i-3)+"...":e;if(Df(e)){let u=e.match(/:(\d+)$/),d=u?parseInt(u[1],10):void 0,p=u?e.replace(/:(\d+)$/,""):e;a=If(p,d)}s(`${o} ${m.bold(t)}(${a})`);let l=Df(e)?L.dim(MU()):"",c=!l&&!FU?L.dim(" (ctrl+o to expand)"):"";if(c&&(FU=!0),n){let u=r?L.dim:L.error;s(u(`\u2514 ${n}`)+l+c)}else{let u=r?"(No content)":"(Error)",d=r?L.dim:L.error;s(d(`\u2514 ${u}`)+l+c)}}function Fge(t){console.log(L.success("\u2713 ")+t)}function $ge(t){console.log(L.warning("\u26A0 ")+t)}function Uge(t){console.log(L.error("\u2717 ")+t)}function $U(t=60){console.log(L.dim("\u2500".repeat(t)))}function Bge(t){console.log(L.logo(t)),$U(t.length)}function Gge(t){return L.thinking(`[${t}]`)}function If(t,e){if(Af())return PU(t,e);let r=process.env.HOME??process.env.USERPROFILE??"",n=t;return r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),e&&(n+=`:${e}`),L.filePath(n)}function zge(t){return L.code(t)}function qge(){return process.stdout.columns||80}function Hge(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 s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function jge(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Yge(t,e){let r=jge(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function Wge(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 Yk(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Wk(t){let e=qge(),r=Math.min(e-2,76),n=r-4,s=(g,_)=>{let E=g.replace(/\x1b\[[0-9;]*m/g,"").length;return g+" ".repeat(Math.max(0,_-E))},o=g=>L.border("\u2502")+" "+s(g,n)+" "+L.border("\u2502"),i=(g,_,E,y)=>{let T=Math.floor(n/2),w=L.dim(g.padEnd(15))+_,C=L.dim(E.padEnd(15))+y;return o(s(w,T)+C)},a=Wge(t.durationSeconds),l=Yk(t.tokensIn),c=Yk(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601 Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(L.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(L.logo("Session complete. \u{1FABC}"))),console.log(L.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(L.logo("Session Summary"))),console.log(o(L.dim("\u2500".repeat(15)))),console.log(i("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(i("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(L.logo("Token Usage"))),console.log(o(L.dim("\u2500".repeat(11)))),console.log(i("Input",l,"Output",c));let p=t.cachedTokens??0;if(p>0){let g=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(L.dim("Cached".padEnd(15))+`${Yk(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?L.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(L.dim("Cost".padEnd(15))+u+h)),console.log(o("")),console.log(o(L.dim("Model: ")+L.model(d))),console.log(L.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Bl,L,FU,sr=D(()=>{"use strict";Se();LU();dt();Bl="0.17.17",L={get logo(){return q().accent.bold},get prompt(){return q().accent.bold},get model(){return q().accent},get success(){return q().success},get warning(){return q().warning},get error(){return q().error},get thinking(){return q().dim},get filePath(){return q().filePath},get code(){return q().code},get muted(){return q().muted},get dim(){return q().dim},get safe(){return q().success},get risky(){return q().warning},get destructive(){return q().error},get border(){return q().accent},get bannerBorder(){return q().accent}};FU=!1});var ss,Yu,Vk=D(()=>{"use strict";ss={maxConcurrent:5,maxIterations:100,timeout:3e5,autoBackgroundTimeout:12e4,compressionLevel:"medium",permissionMode:"default"},Yu={maxConcurrent:3,timeout:30*60*1e3,permissionMode:"dontAsk"}});var l1,Kk=D(()=>{"use strict";l1=`You are an expert codebase explorer. Your task is to efficiently explore and understand codebases.
207
+ `)}var Tge,vf,P,at=D(()=>{"use strict";Se();Tge={debug:!1,colors:!0,emojis:!0},vf={...Tge};P={debug:Y,info:CU,warn:vU,error:kU,success:AU,formatError:e1,configure:Zy}});function IU(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function t1(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:IU(t.protocol_version)}}function RU(t){if(typeof t!="object"||t===null||typeof t.type=="string")return null;let e=t.error;return typeof e!="string"||e===""?null:{unknown_model:"That model is not available on Aii Cloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --local.",insufficient_credits:"Out of Aii Cloud credits. Top up to continue, or run with --local.",quota_exceeded:"Daily free-tier limit reached on Aii Cloud. Try again later, upgrade, or run with --local.",quota_check_failed:"Aii Cloud could not verify your quota \u2014 please retry.",worker_unavailable:"Aii Cloud is temporarily unavailable \u2014 please retry, or run with --local."}[e]??`Aii Cloud error: ${e}`}function Bk(t){return t==null||typeof t=="object"}function n1(t){switch(t.type){case"tool_request":return Bk(t.input);case"mcp_tool_request":return Bk(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&Bk(r.input))}default:return!0}}function s1(t){return IU(t)>2?"hard":"compatible"}function o1(t){return`This Aii Server speaks protocol v${t}, but your CLI speaks v2. Some responses may not work correctly. Update with: aii upgrade`}var NU,OU,r1,Gk=D(()=>{"use strict";NU=new Set(["token","complete","error","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),OU=new Set(["session_started","turn_ready","token","iteration_tokens_usage","tool_request","tool_batch_request","tool_status","complete","error","mcp_tools_loaded","permission_request","permission_resolution","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),r1=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});var qk={};ye(qk,{MCPConfigManager:()=>Xt,MCP_CATALOG:()=>Fl});import*as ns from"fs";import*as i1 from"path";import*as zk from"os";var Fl,Xt,ba=D(()=>{"use strict";Fl={github:{name:"GitHub",description:"GitHub API integration for repos, issues, PRs, and more",command:"npx",args:["-y","@modelcontextprotocol/server-github"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"${GITHUB_TOKEN}"},category:"development"},filesystem:{name:"Filesystem",description:"Read/write files on the local filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem",zk.homedir()],category:"system"},"brave-search":{name:"Brave Search",description:"Web search using Brave Search API",command:"npx",args:["-y","@brave/brave-search-mcp-server"],env:{BRAVE_API_KEY:"${BRAVE_API_KEY}"},category:"search"},sqlite:{name:"SQLite",description:"Query SQLite databases",command:"uvx",args:["mcp-server-sqlite","--db-path","./database.db"],category:"database"},postgres:{name:"PostgreSQL",description:"Query PostgreSQL databases",command:"npx",args:["-y","@anthropic/mcp-server-postgres"],env:{DATABASE_URL:"${DATABASE_URL}"},category:"database"},"chrome-devtools":{name:"Chrome DevTools",description:"Control Chrome browser via DevTools protocol",command:"npx",args:["chrome-devtools-mcp@latest"],category:"browser"},memory:{name:"Memory",description:"Persistent memory storage for conversation context",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],category:"utility"},puppeteer:{name:"Puppeteer",description:"Browser automation with Puppeteer",command:"npx",args:["-y","@anthropic/mcp-server-puppeteer"],category:"browser"}},Xt=class{configPath;constructor(e){this.configPath=e||i1.join(zk.homedir(),".aii","mcp_servers.json"),this.ensureConfigDir()}ensureConfigDir(){let e=i1.dirname(this.configPath);ns.existsSync(e)||ns.mkdirSync(e,{recursive:!0})}loadConfig(){if(!ns.existsSync(this.configPath))return{mcpServers:{}};try{let e=ns.readFileSync(this.configPath,"utf-8"),r=JSON.parse(e);return typeof r=="object"&&r!==null?r:{mcpServers:{}}}catch{return{mcpServers:{}}}}saveConfig(e){try{return this.ensureConfigDir(),ns.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf-8"),!0}catch{return!1}}backupConfig(){if(!ns.existsSync(this.configPath))return!0;try{let e=this.configPath+".backup";return ns.copyFileSync(this.configPath,e),!0}catch{return!1}}getConfigPath(){return this.configPath}}});var wge,Cge,vge,kge,Age,Dge,Ige,$l,a1,Ta,Hk=D(()=>{"use strict";Se();wge={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:m.hex("#3B82F6"),userInput:m.hex("#3B82F6"),userInputText:m.hex("#93C5FD"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#A855F7"),link:m.hex("#3B82F6").underline,heading:m.hex("#A855F7").bold,filePath:m.hex("#3B82F6"),indicator:m.hex("#3B82F6")}},Cge={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:m.hex("#4E6BF5"),userInput:m.hex("#4E6BF5"),userInputText:m.hex("#A5B4FC"),success:m.hex("#28CA41"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#4E6BF5"),link:m.hex("#4E6BF5").underline,heading:m.hex("#4E6BF5").bold,filePath:m.hex("#4E6BF5"),indicator:m.hex("#4E6BF5")}},vge={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:m.hex("#00BCD4"),userInput:m.hex("#00BCD4"),userInputText:m.hex("#67E8F9"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#00BCD4"),link:m.hex("#00BCD4").underline,heading:m.hex("#00BCD4").bold,filePath:m.hex("#00BCD4"),indicator:m.hex("#00BCD4")}},kge={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:m.hex("#6B8AFF"),userInput:m.hex("#6B8AFF"),userInputText:m.hex("#A5B4FC"),success:m.hex("#28CA41"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#6B8AFF"),link:m.hex("#6B8AFF").underline,heading:m.hex("#6B8AFF").bold,filePath:m.hex("#6B8AFF"),indicator:m.hex("#6B8AFF")}},Age={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:m.hex("#22C55E"),userInput:m.hex("#22C55E"),userInputText:m.hex("#86EFAC"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#22C55E"),link:m.hex("#22C55E").underline,heading:m.hex("#22C55E").bold,filePath:m.hex("#22C55E"),indicator:m.hex("#22C55E")}},Dge={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:m.hex("#F59E0B"),userInput:m.hex("#F59E0B"),userInputText:m.hex("#FCD34D"),success:m.hex("#22C55E"),warning:m.hex("#EAB308"),error:m.hex("#EF4444"),muted:m.hex("#94A3B8"),dim:m.dim,code:m.hex("#F59E0B"),link:m.hex("#F59E0B").underline,heading:m.hex("#F59E0B").bold,filePath:m.hex("#F59E0B"),indicator:m.hex("#F59E0B")}},Ige={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:m.reset,userInput:m.reset,userInputText:m.hex("#CBD5E1"),success:m.reset,warning:m.reset,error:m.bold,muted:m.dim,dim:m.dim,code:m.reset,link:m.underline,heading:m.bold,filePath:m.reset,indicator:m.bold}},$l={classic:wge,brand:Cge,teal:vge,indigo:kge,forest:Age,amber:Dge,grayscale:Ige},a1="classic",Ta=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Ul={};ye(Ul,{ThemeManager:()=>mi,getAccentColorName:()=>ke,getThemeColors:()=>q,getUserInputTextColorName:()=>Hu});function q(){return mi.getInstance().getColors()}function ke(){return mi.getInstance().getAccentColorName()}function Hu(){return mi.getInstance().getUserInputTextColorName()}var mi,wa=D(()=>{"use strict";Hk();mi=class t{static instance=null;activeTheme;constructor(){this.activeTheme=$l[a1]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=$l[e];if(!r){let n=Ta.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in $l}getAvailableThemes(){return Ta.map(e=>$l[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}reset(){this.activeTheme=$l[a1]}}});var dt=D(()=>{"use strict";Hk();wa()});import{resolve as Rge}from"path";function Nge(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:!(t==="dumb"||!process.stdout.isTTY)}function Af(){return jk===null&&(jk=Nge()),jk}function Oge(){return process.platform==="darwin"?"Cmd":"Ctrl"}function MU(){return xU||!Af()?"":(xU=!0,` (${Oge()}+Click to open)`)}function xge(t,e){return Af()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function PU(t,e){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;r&&t.startsWith(r)&&(n="~"+t.slice(r.length));let s=e?`${n}:${e}`:n;if(!Af())return q().filePath(s);let o=q().accent(s),a=`file://${Rge(t)}`;return e!==void 0&&e>0&&(a+=`#L${e}`),xge(o,a)}var jk,xU,LU=D(()=>{"use strict";dt();jk=null,xU=!1});var UU={};ye(UU,{VERSION:()=>Bl,colors:()=>L,formatCode:()=>zge,formatPath:()=>If,getActionIndicator:()=>Gge,padEndAnsi:()=>Yge,printAction:()=>Mge,printDivider:()=>$U,printError:()=>Uge,printExitSummary:()=>Wk,printHeader:()=>Bge,printSuccess:()=>Fge,printToolComplete:()=>Pge,printToolFailed:()=>Lge,printToolResultCompact:()=>ju,printWarning:()=>$ge,shortenPath:()=>Hge});function Df(t){return t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-zA-Z]:\\/.test(t)||/\.(ts|tsx|js|jsx|json|md|py|go|rs|java|c|cpp|h|hpp|css|scss|html|xml|yaml|yml|toml|sh|bash|zsh)$/.test(t)||/^src\//.test(t)||/^lib\//.test(t)||/^test[s]?\//.test(t)}function Mge(t,e,r=console.log){let n=Df(e)?If(e):L.filePath(e);r(L.dim("\u25CB ")+m.bold(t)+" "+n)}function Pge(t,e,r=console.log){let n=Df(e)?If(e):L.filePath(e);r(L.success("\u2713 ")+m.bold(t)+" "+n)}function Lge(t,e,r,n=console.log){let s=Df(e)?If(e):L.filePath(e);n(L.error("\u2717 ")+m.bold(t)+" "+s),r&&n(L.dim(" \u2192 ")+L.error(r))}function ju(t,e,r=!0,n,s=console.log){let o=r?L.success("\u25CF"):L.error("\u25CF"),i=60,a=e.length>i?e.slice(0,i-3)+"...":e;if(Df(e)){let u=e.match(/:(\d+)$/),d=u?parseInt(u[1],10):void 0,p=u?e.replace(/:(\d+)$/,""):e;a=If(p,d)}s(`${o} ${m.bold(t)}(${a})`);let l=Df(e)?L.dim(MU()):"",c=!l&&!FU?L.dim(" (ctrl+o to expand)"):"";if(c&&(FU=!0),n){let u=r?L.dim:L.error;s(u(`\u2514 ${n}`)+l+c)}else{let u=r?"(No content)":"(Error)",d=r?L.dim:L.error;s(d(`\u2514 ${u}`)+l+c)}}function Fge(t){console.log(L.success("\u2713 ")+t)}function $ge(t){console.log(L.warning("\u26A0 ")+t)}function Uge(t){console.log(L.error("\u2717 ")+t)}function $U(t=60){console.log(L.dim("\u2500".repeat(t)))}function Bge(t){console.log(L.logo(t)),$U(t.length)}function Gge(t){return L.thinking(`[${t}]`)}function If(t,e){if(Af())return PU(t,e);let r=process.env.HOME??process.env.USERPROFILE??"",n=t;return r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),e&&(n+=`:${e}`),L.filePath(n)}function zge(t){return L.code(t)}function qge(){return process.stdout.columns||80}function Hge(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 s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function jge(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Yge(t,e){let r=jge(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function Wge(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 Yk(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Wk(t){let e=qge(),r=Math.min(e-2,76),n=r-4,s=(g,_)=>{let E=g.replace(/\x1b\[[0-9;]*m/g,"").length;return g+" ".repeat(Math.max(0,_-E))},o=g=>L.border("\u2502")+" "+s(g,n)+" "+L.border("\u2502"),i=(g,_,E,y)=>{let T=Math.floor(n/2),w=L.dim(g.padEnd(15))+_,C=L.dim(E.padEnd(15))+y;return o(s(w,T)+C)},a=Wge(t.durationSeconds),l=Yk(t.tokensIn),c=Yk(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601 Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(L.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(L.logo("Session complete. \u{1FABC}"))),console.log(L.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(L.logo("Session Summary"))),console.log(o(L.dim("\u2500".repeat(15)))),console.log(i("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(i("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(L.logo("Token Usage"))),console.log(o(L.dim("\u2500".repeat(11)))),console.log(i("Input",l,"Output",c));let p=t.cachedTokens??0;if(p>0){let g=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(L.dim("Cached".padEnd(15))+`${Yk(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?L.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(L.dim("Cost".padEnd(15))+u+h)),console.log(o("")),console.log(o(L.dim("Model: ")+L.model(d))),console.log(L.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Bl,L,FU,sr=D(()=>{"use strict";Se();LU();dt();Bl="0.17.18",L={get logo(){return q().accent.bold},get prompt(){return q().accent.bold},get model(){return q().accent},get success(){return q().success},get warning(){return q().warning},get error(){return q().error},get thinking(){return q().dim},get filePath(){return q().filePath},get code(){return q().code},get muted(){return q().muted},get dim(){return q().dim},get safe(){return q().success},get risky(){return q().warning},get destructive(){return q().error},get border(){return q().accent},get bannerBorder(){return q().accent}};FU=!1});var ss,Yu,Vk=D(()=>{"use strict";ss={maxConcurrent:5,maxIterations:100,timeout:3e5,autoBackgroundTimeout:12e4,compressionLevel:"medium",permissionMode:"default"},Yu={maxConcurrent:3,timeout:30*60*1e3,permissionMode:"dontAsk"}});var l1,Kk=D(()=>{"use strict";l1=`You are an expert codebase explorer. Your task is to efficiently explore and understand codebases.
208
208
 
209
209
  ## Core Capabilities
210
210
  You have access to these tools for codebase exploration:
@@ -788,7 +788,7 @@ ${w.content}`:`${w.role==="user"?"User":"Assistant"}: ${w.content}`).join(`
788
788
  ${g}`)}})()}),a.on("error",p=>{let f=`${p.message} (ws: ${e})`,h=/handshake has timed out|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH/i.test(p.message),g=!!this.config.cloudApiKey&&h;g&&Y(`WebSocket dial failure (cloud): ${f}`);let _=g?wl(new URL(e).hostname):`WebSocket error: ${f}`;n.onError?.(_),this.ws=null,l=!0,i(new Error(g?_:f))}),a.on("close",()=>{let p=!l&&this.ws!==null;this.ws=null,p?i(new Error("WebSocket disconnected unexpectedly")):o()})})}async createSession(e){let r=await this.boundedFetch(`${this.config.baseUrl}/v0/session`,{method:"POST",headers:this.authHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e)});if(!r.ok)throw new Error(`Failed to create session: ${r.status} - ${r.text}`);return JSON.parse(r.text)}async sessionTurn(e,r){let n=r.interrupt?"?interrupt=true":"",s=await this.boundedFetch(`${this.config.baseUrl}/v0/session/${e}/turn${n}`,{method:"POST",headers:this.authHeaders({"Content-Type":"application/json"}),body:JSON.stringify({input:r.input,channel:r.channel})});if(!s.ok)throw new Error(`Failed to submit turn: ${s.status} - ${s.text}`);return JSON.parse(s.text)}async listSessions(e){let r=new URLSearchParams;e?.q&&r.set("q",e.q),e?.searchContent&&r.set("search_content","true"),e?.channel&&r.set("channel",e.channel),e?.projectPath&&r.set("project_path",e.projectPath),e?.status&&r.set("status",e.status),e?.includeSubagents&&r.set("include_subagents","true"),e?.parentSessionId&&r.set("parent_session_id",e.parentSessionId),e?.sort&&r.set("sort",e.sort),e?.limit&&r.set("limit",String(e.limit));let n=r.toString(),s=`${this.config.baseUrl}/v0/session/active${n?"?"+n:""}`,o=await this.boundedFetch(s,{headers:this.authHeaders()});if(!o.ok)throw new Error(`Failed to list sessions: ${o.status} - ${o.text}`);return JSON.parse(o.text)}async getSession(e,r){let n=new URLSearchParams;r?.messages&&n.set("messages","true"),r?.messagesLimit&&n.set("messages_limit",String(r.messagesLimit));let s=n.toString(),o=`${this.config.baseUrl}/v0/session/${e}${s?"?"+s:""}`,i=await this.boundedFetch(o,{headers:this.authHeaders()});if(!i.ok)throw new Error(`Failed to get session: ${i.status} - ${i.text}`);return JSON.parse(i.text)}async updateSession(e,r){let n=await this.boundedFetch(`${this.config.baseUrl}/v0/session/${e}`,{method:"PATCH",headers:this.authHeaders({"Content-Type":"application/json"}),body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to update session: ${n.status} - ${n.text}`);return JSON.parse(n.text)}async deleteSession(e){let r=await this.boundedFetch(`${this.config.baseUrl}/v0/session/${e}`,{method:"DELETE",headers:this.authHeaders()});if(!r.ok)throw new Error(`Failed to delete session: ${r.status} - ${r.text}`);return JSON.parse(r.text)}async switchSessionModel(e,r,n){let s=await this.boundedFetch(`${this.config.baseUrl}/v0/session/${e}/model`,{method:"POST",headers:this.authHeaders({"Content-Type":"application/json"}),body:JSON.stringify({model:r,provider:n})});if(!s.ok)throw new Error(`Failed to switch session model: ${s.status} - ${s.text}`);return JSON.parse(s.text)}async runSessionTurn(e,r,n,s,o){let i=await this.sessionTurn(e,{input:r,channel:n}),a=[...V_e],l={type:"init",provider_api_key:this.config.providerApiKey,input:r,available_tools:a,max_iterations:500,max_output_tokens:8192,tool_timeout_ms:parseInt(process.env.AII_TOOL_TIMEOUT_MS??"",10)||6e5,client_type:"cli",agent_mode:"plan-first",capabilities:{parallel_tools:!0},protocol_version:2,context:{workspace_root:process.cwd(),auto_mode:!0}};return this._runWebSocketLoop(wB(i.websocketUrl,this.config.baseUrl),s,o,l)}setState(e){this.state=e,this.emit("stateChange",e)}}});var Ue,or=D(()=>{"use strict";Ue=class{get definition(){return{name:this.name,description:this.description,parameters:this.inputSchema}}getPermissionLevel(e){return this.permissionLevel}success(e,r,n){return{callId:e,success:!0,output:r,metadata:n}}error(e,r,n=""){return{callId:e,success:!1,output:n,error:r}}validateRequired(e,r){for(let n of r)if(e[n]===void 0||e[n]===null)return`Missing required parameter: ${n}`;return null}resolvePath(e,r){if(e.startsWith("/"))return e;if(e.startsWith("~")){let n=process.env.HOME??process.env.USERPROFILE??"";return e.replace("~",n)}return`${r}/${e}`}}});var R1={};ye(R1,{HEADLESS_DEFAULT_POLICY:()=>NA,isAutonomous:()=>Wl,mapPermissionMode:()=>OA,resolvePermissionPolicy:()=>Oa});function OA(t){switch(t){case"bypassPermissions":return"bypass";case"dontAsk":return"dontAsk";case"acceptEdits":return"acceptEdits";case"plan":return"plan";case"default":case void 0:default:return"auto"}}function K_e(t){let e=t.mode;return e==="normal"?"interactive":e in RA?e:"interactive"}function Oa(t){let e=K_e(t),r={...RA[e]};(t.outputFormat==="json"||t.outputFormat==="stream-json")&&(r.canPrompt=!1);let n=e==="interactive"&&t.connectionMode==="cloud";return{posture:e,...r,relayMirror:n}}function Wl(t){return Oa(t).autonomous}var RA,NA,_i=D(()=>{"use strict";RA={interactive:{mutating:"prompt",riskyNonMutating:"prompt",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!0,autonomous:!1},auto:{mutating:"autoApprove",riskyNonMutating:"autoApprove",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!1,autonomous:!0},plan:{mutating:"autoDeny",riskyNonMutating:"autoApprove",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!1,autonomous:!1},dontAsk:{mutating:"autoDeny",riskyNonMutating:"autoApprove",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!1,autonomous:!0},acceptEdits:{mutating:"editsOnly",riskyNonMutating:"prompt",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!0,autonomous:!1},bypass:{mutating:"autoApprove",riskyNonMutating:"autoApprove",fenceEnforced:!1,sensitiveReadDenied:!0,canPrompt:!1,autonomous:!0},headless:{mutating:"autoApprove",riskyNonMutating:"autoApprove",fenceEnforced:!0,sensitiveReadDenied:!0,canPrompt:!1,autonomous:!0}},NA={posture:"headless",...RA.headless,relayMirror:!1}});function eEe(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Q_e.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function tEe(t){let e=t.trim().split(/\s+/).filter(Boolean),r=0;for(;r<e.length&&(e[r]==="sudo"||e[r]==="env"||/^\w+=/.test(e[r]));)r++;let n=e[r]?e[r].split("/").pop()??"":"",s=e[r+1]??"";return!!(n==="xargs"||n==="make"||n==="git"&&s==="config"||(n==="docker"||n==="podman")&&(s==="run"||s==="exec"||s==="create")||n==="find"&&e.some(o=>Z_e.includes(o)))}function CB(t,e){if(t!=="Bash")return!0;let r=typeof e.command=="string"?e.command:"";return!X_e.test(r)&&!J_e.test(r)&&!tEe(r)}function xA(t,e){if(t==="Bash"){let r=typeof e.command=="string"?e.command:"";return eEe(r)}if(t==="Write"||t==="Edit"){let r=typeof e.file_path=="string"?e.file_path:"";return`${t}:${r?Dn(r):""}`}return t}var Q_e,X_e,J_e,Z_e,vB=D(()=>{"use strict";ii();Q_e=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),X_e=/[;&|<>`\n]|\$\(/,J_e=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,Z_e=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function sEe(t,e=rEe){let r=t.split(`
789
789
  `);return r.length<=e?t:r.slice(0,e).join(`
790
790
  `)+`
791
- \u2026 (+${r.length-e} more lines)`}function oEe(t,e){if(t==="Edit"||t==="Write"||t==="Read"){let r=e.file_path??e.path;return typeof r=="string"?r:void 0}}function kB(t,e,r,n,s){let o=oEe(t,e),i={tool_name:$e(t),action:$e(n),risk:r};if(o&&(i.path=$e(o)),t==="Edit"||t==="Write")if(o&&s(o))i.detail=nEe;else{let a=iEe(t,e);a&&(i.detail=$e(sEe(a)))}return i}function iEe(t,e){if(t==="Edit"&&typeof e.old_string=="string"&&typeof e.new_string=="string"){let r=String(e.old_string).split(`
791
+ \u2026 (+${r.length-e} more lines)`}function oEe(t,e){if(t==="Edit"||t==="Write"||t==="Read"){let r=e.file_path??e.path;return typeof r=="string"?r:void 0}}function kB(t,e,r,n,s){let o=oEe(t,e),i=(t==="Bash"||t==="run_command")&&typeof e.command=="string"&&e.command?e.command:n,a={tool_name:$e(t),action:$e(i),risk:r};if(o&&(a.path=$e(o)),t==="Edit"||t==="Write")if(o&&s(o))a.detail=nEe;else{let l=iEe(t,e);l&&(a.detail=$e(sEe(l)))}return a}function iEe(t,e){if(t==="Edit"&&typeof e.old_string=="string"&&typeof e.new_string=="string"){let r=String(e.old_string).split(`
792
792
  `).map(s=>`- ${s}`),n=String(e.new_string).split(`
793
793
  `).map(s=>`+ ${s}`);return[...r,...n].join(`
794
794
  `)}if(t==="Write"&&typeof e.content=="string")return String(e.content).split(`
@@ -3520,7 +3520,7 @@ To enter: cd ${s.path}`);break}case"list":{let s=await cl(n);if(s.length===0){co
3520
3520
  `)),console.log(" aii cloud login Sign in to Aii Cloud (device authorization)"),console.log(" aii cloud status Show connection + credit balance"),console.log(m.gray(`
3521
3521
  Note: running the agent over cloud arrives in a later release; today this
3522
3522
  sets up + inspects the connection.
3523
- `))}var gle=D(()=>{"use strict";Se();Kp();Cf();fle()});var yle={};ye(yle,{handleUpgrade:()=>X6e});import{execSync as _le}from"node:child_process";async function X6e(t){let e=t.args[0]||null,r="0.17.17",n=e?`${Ele}@${e}`:`${Ele}@latest`;console.log(""),console.log(e?`Upgrading Aii CLI to v${e}...`:"Upgrading Aii CLI to latest..."),console.log(` Current version: ${r}`),console.log("");try{_le(`npm install -g ${n}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
3523
+ `))}var gle=D(()=>{"use strict";Se();Kp();Cf();fle()});var yle={};ye(yle,{handleUpgrade:()=>X6e});import{execSync as _le}from"node:child_process";async function X6e(t){let e=t.args[0]||null,r="0.17.18",n=e?`${Ele}@${e}`:`${Ele}@latest`;console.log(""),console.log(e?`Upgrading Aii CLI to v${e}...`:"Upgrading Aii CLI to latest..."),console.log(` Current version: ${r}`),console.log("");try{_le(`npm install -g ${n}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
3524
3524
  Upgrade failed. Try running with sudo or check npm permissions.`),console.error(` Manual: npm install -g ${n}`),process.exit(1)}try{let s=_le("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(s===r?`Already up to date (${r})`:`Upgraded: ${r} -> ${s}`)}catch{console.log(""),console.log("Installed. Restart your terminal to use the new version.")}}var Ele,Sle=D(()=>{"use strict";Ele="@aiiware/aii"});var ble={};ye(ble,{handleSkillCmd:()=>Z6e});function J6e(t){return t.userInvocable&&t.modelInvocable?"":t.userInvocable?"(CLI only)":t.modelInvocable?"(agent only)":"(disabled)"}async function Z6e(t,e){let r=(t.subcommand??t.args[0]??"help").toLowerCase(),n=t.subcommand?t.args[0]:t.args[1]??null;switch(r){case"list":return eGe();case"info":return tGe(n);case"install":return rGe(n);case"help":default:return nGe()}}async function eGe(){let{SkillManager:t}=await Promise.resolve().then(()=>(bo(),Hl)),e;if(t.hasInstance())e=t.getInstance();else{e=t.getInstance(process.cwd());let o;try{let{PersonaManager:i}=await Promise.resolve().then(()=>(At(),Ot)),a=i.getInstance(process.cwd());await a.initialize(),a.isActive()&&(o=a.getActive()?.skillPaths)}catch{}await e.discover(o)}let r=e.getRegistry().getAll();if(r.length===0){console.log("No skills installed."),console.log(" Install one: aii skill install <owner/repo/skill>");return}let n=new Map;for(let o of r){let i=n.get(o.source)||[];i.push(o),n.set(o.source,i)}let s=["project-command","project","user","persona-bundled","universal","built-in","plugin","remote"];console.log(""),console.log(" Name Source Invocation Description"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let o of s){let i=n.get(o);if(i)for(let a of i){let l=a.name.padEnd(18),c=a.source.padEnd(16),u=J6e(a).padEnd(14),d=(a.description||"").slice(0,34);console.log(` ${l}${c}${u}${d}`)}}console.log("")}async function tGe(t){if(!t){console.log("Usage: aii skill info <name>");return}let{SkillManager:e}=await Promise.resolve().then(()=>(bo(),Hl)),r;if(e.hasInstance())r=e.getInstance();else{r=e.getInstance(process.cwd());let s;try{let{PersonaManager:o}=await Promise.resolve().then(()=>(At(),Ot)),i=o.getInstance(process.cwd());await i.initialize(),i.isActive()&&(s=i.getActive()?.skillPaths)}catch{}await r.discover(s)}let n=r.getRegistry().getByName(t);if(!n){let o=r.getRegistry().getAll().map(i=>i.name).join(", ");console.error(`Skill "${t}" not found.`),o&&console.error(`Available skills: ${o}`),process.exit(1)}console.log(""),console.log(` Name: ${n.name}`),console.log(` Source: ${n.source}`),console.log(` Description: ${n.description||"(none)"}`),console.log(` Invocable: ${[n.userInvocable?"user":"",n.modelInvocable?"model":""].filter(Boolean).join(" + ")||"none"}`),n.allowedTools?.length&&console.log(` Tools: ${n.allowedTools.join(" ")}`),console.log(` Path: ${n.path||"(embedded)"}`),console.log("")}async function rGe(t){if(!t){console.log("Usage: aii skill install <owner/repo/skill>");return}let{SkillInstaller:e}=await Promise.resolve().then(()=>(Kf(),k1)),r=new e({projectRoot:process.cwd()});try{let n=await r.install(t,{scope:"user"});n.success?(console.log(`Installed skill: ${n.skillName}`),n.installPath&&console.log(` Location: ${n.installPath}`)):(console.error(`Failed to install skill: ${n.error||"Unknown error"}`),process.exit(1))}catch(n){let s=n instanceof Error?n.message:String(n);console.error(`Failed to install skill: ${s}`),process.exit(1)}}function nGe(){let t=[""];t.push(m.cyan.bold(" Skill System")),t.push(""),t.push(m.yellow(" USAGE:")),t.push(` ${m.green("aii skill list")} List all available skills`),t.push(` ${m.green("aii skill info <name>")} Show details for a skill`),t.push(` ${m.green("aii skill install <ref>")} Install a skill from GitHub`),t.push(` ${m.green("aii skill help")} Show this help`),t.push(""),t.push(m.yellow(" EXAMPLES:")),t.push(m.dim(" aii skill list")),t.push(m.dim(" aii skill info commit")),t.push(m.dim(" aii skill install aiiware/aii-skills/skills/commit --user")),t.push(""),console.log(t.join(`
3525
3525
  `))}var Tle=D(()=>{"use strict";Se()});var wle={};ye(wle,{handlePluginCmd:()=>sGe});async function sGe(t,e){let r=(t.subcommand??t.args[0]??"help").toLowerCase(),n=t.subcommand?t.args[0]:t.args[1]??null,s=t.subcommand?t.args.slice(1):t.args.slice(2);switch(r){case"install":return oGe(n,s);case"uninstall":case"remove":return iGe(n);case"update":return aGe(n);case"list":case"ls":return lGe();case"help":default:return cGe()}}async function oGe(t,e){if(!t){console.log("Usage: aii plugin install <owner/repo>");return}let{PluginInstaller:r}=await Promise.resolve().then(()=>(Ia(),ql)),n=e.includes("--force")||e.includes("-f"),s=t,o;if(t.includes("@")){let a=t.lastIndexOf("@");s=t.slice(0,a),o=t.slice(a+1)}let i=new r({onProgress:a=>console.log(` ${m.dim(a)}`)});try{console.log(""),console.log(` Installing plugin from ${m.cyan(s)}...`),console.log("");let a=await i.install(s,{version:o,force:n});a.success?(console.log(""),console.log(` ${m.green("\u2713")} Plugin ${m.bold(a.pluginName)} v${a.version} installed`),console.log(` ${a.skillCount} skills available (use ${m.cyan("aii skill list")} to see them)`),a.installPath&&console.log(` Stored in ${m.dim(a.installPath)}`),console.log("")):(console.error(` ${m.red("\u2717")} ${a.error||"Unknown error"}`),process.exit(1))}catch(a){let l=a instanceof Error?a.message:String(a);console.error(` ${m.red("\u2717")} Failed to install plugin: ${l}`),process.exit(1)}}async function iGe(t){if(!t){console.log("Usage: aii plugin uninstall <name>");return}let{PluginInstaller:e}=await Promise.resolve().then(()=>(Ia(),ql)),r=new e;try{let n=await r.uninstall(t);n.success?(console.log(""),console.log(` ${m.green("\u2713")} Plugin ${m.bold(t)} uninstalled`),n.skillCount&&console.log(` ${n.skillCount} skills removed`),console.log("")):(console.error(` ${m.red("\u2717")} ${n.error||"Unknown error"}`),process.exit(1))}catch(n){let s=n instanceof Error?n.message:String(n);console.error(` ${m.red("\u2717")} Failed to uninstall plugin: ${s}`),process.exit(1)}}async function aGe(t){if(!t){console.log("Usage: aii plugin update <name>");return}let{PluginInstaller:e}=await Promise.resolve().then(()=>(Ia(),ql)),r=new e({onProgress:n=>console.log(` ${m.dim(n)}`)});try{console.log(""),console.log(` Checking for updates to ${m.cyan(t)}...`);let n=await r.update(t);n.success?(n.error?.includes("already up to date")?console.log(` ${m.green("\u2713")} ${n.error}`):(console.log(` ${m.green("\u2713")} Plugin ${m.bold(t)} updated to v${n.version}`),n.skillCount&&console.log(` ${n.skillCount} skills available`)),console.log("")):(console.error(` ${m.red("\u2717")} ${n.error||"Unknown error"}`),process.exit(1))}catch(n){let s=n instanceof Error?n.message:String(n);console.error(` ${m.red("\u2717")} Failed to update plugin: ${s}`),process.exit(1)}}async function lGe(){let{PluginManager:t}=await Promise.resolve().then(()=>(Hf(),qf)),r=await new t().listInstalled();if(r.length===0){console.log(""),console.log(" No plugins installed."),console.log(` Install one: ${m.cyan("aii plugin install <owner/repo>")}`),console.log("");return}console.log(""),console.log(m.bold(" INSTALLED PLUGINS")),console.log(""),console.log(" Name Version Skills Installed"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let n of r){let s=n.name.padEnd(18),o=`v${n.version}`.padEnd(12),i=String(n.skillCount).padEnd(8),a=new Date(n.installedAt).toLocaleDateString();console.log(` ${s}${o}${i}${a}`)}console.log("")}function cGe(){let t=[""];t.push(m.cyan.bold("Plugin System")),t.push(""),t.push(m.yellow("USAGE:")),t.push(` ${m.green("aii plugin install <source>")} Install a plugin from GitHub`),t.push(` ${m.green("aii plugin uninstall <name>")} Uninstall a plugin`),t.push(` ${m.green("aii plugin update <name>")} Update a plugin to latest`),t.push(` ${m.green("aii plugin list")} List installed plugins`),t.push(` ${m.green("aii plugin help")} Show this help`),t.push(""),t.push(m.yellow("EXAMPLES:")),t.push(m.dim(" aii plugin install aiiware/aii-skills")),t.push(m.dim(" aii plugin install aiiware/aii-skills@v0.1.0")),t.push(m.dim(" aii plugin list")),t.push(m.dim(" aii plugin update aii-skills")),t.push(m.dim(" aii plugin uninstall aii-skills")),t.push(""),console.log(t.join(`
3526
3526
  `))}var Cle=D(()=>{"use strict";Se()});var vle={};ye(vle,{handlePersona:()=>dGe});function uGe(t){return process.stdin.isTTY?async({originId:e,event:r,command:n,index:s,total:o})=>{s===1&&(console.log(`
@@ -3543,7 +3543,7 @@ Upgrade failed. Try running with sudo or check npm permissions.`),console.error(
3543
3543
  ${t}
3544
3544
  </context>
3545
3545
 
3546
- ${e}`:e}var Te;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(Te||(Te={}));var yC={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function uo(t,e,r,n){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&r?.[e]?r[e]:e&&yC[e]?yC[e]:n||yC._default}var TE=[{name:"config",tier:Te.LOCAL},{name:"help",tier:Te.LOCAL},{name:"version",tier:Te.LOCAL},{name:"doctor",tier:Te.LOCAL},{name:"mcp",tier:Te.LOCAL},{name:"prompt",tier:Te.LOCAL},{name:"stats",tier:Te.LOCAL},{name:"history",tier:Te.LOCAL},{name:"query",tier:Te.SERVER},{name:"chat",tier:Te.SERVER},{name:"run",tier:Te.SERVER},{name:"agent",tier:Te.SERVER},{name:"loop",tier:Te.SERVER},{name:"telegram",tier:Te.SERVER},{name:"sessions",tier:Te.SERVER},{name:"install",tier:Te.LOCAL},{name:"worktree",tier:Te.LOCAL},{name:"soul",tier:Te.LOCAL},{name:"skill",tier:Te.LOCAL},{name:"plugin",tier:Te.LOCAL},{name:"persona",tier:Te.LOCAL},{name:"cloud",tier:Te.LOCAL},{name:"upgrade",tier:Te.LOCAL}];function sce(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==Te.LOCAL&&r.tier!==Te.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var oce=sce(TE);function PF(t){return oce.get(t)?.tier}var dze=Object.fromEntries(TE.map(t=>[t.name,t.tier]));var ice=new Set(TE.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),ace="0.17.17",lce=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--offline","-D","--direct","-i","--interactive","-c","--continue-chat","-n","--new-chat","--auto","--auto-background-timeout","--no-colors","--colors","--no-emojis","--emojis","--no-animations","--animations","--no-streaming","--streaming","--show-tokens","--show-cost","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--bare","--append-system-prompt","--append-system-prompt-file","--no-project-config","--project-config","--local","-h","--help","-V","--version"]),cce=new Set(["--model","--openrouter-provider","--host","-c","--continue-chat","--auto-background-timeout","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--append-system-prompt","--append-system-prompt-file"]);function uce(t){let e=[];for(let r=0;r<t.length;r++){if(lce.has(t[r])){cce.has(t[r])&&r++;continue}e.push(t[r])}return e}function dce(t){if(t===void 0)return;let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`Invalid --max-turns "${t}": expected a non-negative integer`);return e}function pce(t){if(t===void 0)return;let e=Number(t);if(!Number.isFinite(e)||e<0)throw new Error(`Invalid --max-budget-usd "${t}": expected a non-negative number`);return e}function mce(){let t=new xF;return t.name("aii").description("AI-powered CLI assistant").version(ace,"-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 (e.g., ollama/llama3.1:8b, deepseek/deepseek-chat)").option("--openrouter-provider <slug>","Pin OpenRouter requests to a specific backend provider").option("--host <host>","API server host:port").option("--local","Force the local backend for this run (ignore managed cloud)").option("-y, --yes","Auto-confirm shell commands").option("--offline","Offline mode (no web/MCP)").option("-D, --direct","Direct mode (bypass server intent recognition)").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("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip project .aii/settings.json + settings.local.json and their deny rules for this session").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("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of tools (comma-separated, e.g., "Read,Bash,Edit")').option("--exclude-tools <list>",'Exclude tools (comma-separated, e.g., "WebSearch,WebFetch")').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--max-budget-usd <amount>","Stop before a new turn once cumulative est. cost reaches $amount").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--append-system-prompt <text>","Append additive instructions to this run").option("--append-system-prompt-file <path>","Append a workspace file of additive instructions to this run").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)").allowUnknownOption().helpOption(!1).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("install [target...]").description("Install or update Aii CLI, skills, or MCP servers").allowUnknownOption().helpOption(!1).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("loop").description("Autonomous agent loop (Ralph Wiggum pattern)").argument("[args...]","Loop arguments (prompt, --max, --verify, --budget, etc.)").allowUnknownOption().action(()=>{}),t.command("telegram").description("Telegram bot channel (chat with Aii from Telegram)").argument("[action]","Action: start, pair, status, unpair").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("sessions").description("Manage server sessions (list, info, resume, rename, delete)").argument("[action]","Action: list, info, resume, rename, delete").argument("[args...]","Additional arguments (session ID, name, etc.)").allowUnknownOption().action(()=>{}),t.command("worktree").description("Manage git worktrees for isolated development").argument("[action]","Action: create, list, remove, clean").argument("[name]","Worktree name (for create/remove)").allowUnknownOption().action(()=>{}),t.command("soul").description("Manage agent soul (personality & identity)").argument("[action]","Action: switch, show").argument("[name]","Soul name (for switch)").allowUnknownOption().action(()=>{}),t.command("cloud").description("Manage the Aii Cloud connection (login, status)").argument("[action]","Action: login, status").allowUnknownOption().action(()=>{}),t.command("skill").description("Manage AI skills").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("plugin").description("Manage skill plugins").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("persona").description("Manage workspace personas").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("upgrade").description("Update Aii CLI to latest version").argument("[version]","Target version (default: latest)").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 LF(t){let e=mce();e.exitOverride(),e.configureOutput({writeErr:()=>{}});let r="query",n,s=[];try{e.parse(t),s=e.args;let c=e.args[0];c&&ice.has(c)&&(r=c,n=e.args[1],s=e.args.slice(2))}catch(c){c instanceof OF&&(c.code==="commander.version"||c.code==="commander.helpDisplayed")&&process.exit(0),s=uce(t.slice(2))}let o=e.opts(),i={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,local:o.local??!1,openrouterProvider:o.openrouterProvider,yes:o.yes??!1,offline:o.offline??!1,direct:o.direct??!1,interactive:o.interactive??!1,continueChat:o.continueChat,newChat:o.newChat??!1,auto:o.auto??!1,quiet:!1,noProjectConfig:o.projectConfig===!1,autoBackgroundTimeout:(()=>{let c=parseInt(o.autoBackgroundTimeout??"120",10);return isNaN(c)||c===0?0:Math.max(30,Math.min(600,c))*1e3})(),noColors:!o.colors,noEmojis:!o.emojis,noAnimations:!o.animations,noStreaming:!o.streaming,showTokens:o.showTokens??!1,showCost:o.showCost??!1,outputFormat:o.outputFormat,tools:o.tools,excludeTools:o.excludeTools,maxTurns:dce(o.maxTurns),maxBudgetUsd:pce(o.maxBudgetUsd),bare:o.bare??!1,appendSystemPrompt:o.appendSystemPrompt,appendSystemPromptFile:o.appendSystemPromptFile,help:o.help??!1,version:o.version??!1},a;EC()&&(a=await MF()),(r==="chat"||i.interactive)&&(r="agent"),r==="query"&&!s.length&&!a&&(r="agent");let l;if(r==="query"&&s.length>0)l=s.join(" ");else if(r==="agent"){let c=[];n&&c.push(n),s.length>0&&c.push(...s),c.length>0&&(l=c.join(" "))}return{command:r,subcommand:n,args:s,flags:i,stdinContent:a,query:l}}function FF(t){let e=PF(t.command)??Te.SERVER;switch(t.command){case"config":return fce(t);case"mcp":return hce(t);case"prompt":return gce(t);case"stats":return _ce(t);case"history":return Ece(t);case"doctor":return{tier:Te.LOCAL,handler:"doctor",params:{}};case"install":return{tier:Te.LOCAL,handler:"install",params:{}};case"chat":return{tier:Te.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return Sce(t);case"agent":return{tier:Te.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:Te.SERVER,handler:"loop",params:{}};case"telegram":return{tier:Te.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:Te.SERVER,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:Te.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:Te.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:Te.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"skill":return{tier:Te.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:Te.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:Te.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:Te.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:Te.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:Te.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function fce(t){let e=t.subcommand??t.args[0]??"show";return{tier:Te.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function hce(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function gce(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function _ce(t){let e=t.subcommand??t.args[0];return{tier:Te.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Ece(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var yce=new Set(["--model","--host","--continue-chat","-c"]);function Sce(t){let e=[];t.subcommand&&e.push(t.subcommand);let r=[];for(let s=0;s<t.args.length;s++){let o=t.args[s];if(yce.has(o)){s++;continue}o.startsWith("-")||r.push(o)}e.push(...r);let n=e.join(" ");return{tier:Te.SERVER,handler:"run",params:{operation:n}}}vt();Oy();go();Se();import{createInterface as J8e}from"readline";import{spawn as Z8e}from"child_process";Fk();An();Cf();at();Gk();var d4e={timeout:12e4,retries:3,retryDelay:1e3,handshakeTimeout:5e3};function p4e(t,e){let r=new URL(t),n=r.protocol==="https:"?"wss:":"ws:";if(e){if(!(r.protocol==="https:"||r.protocol==="wss:")&&!Uk(r.hostname))throw new Error(`Refusing to send the cloud key over an insecure (${r.protocol}) connection to ${r.hostname} \u2014 use https/wss.`);return{url:`${n}//${r.host}/v1/ws/execute`,headers:{Authorization:`Bearer ${e}`}}}return{url:`${n}//${r.host}/ws/execute`}}var vs=class{options;ws=null;activityTimeout=null;mcpExecutor=null;constructor(e){this.options={...d4e,...e}}async initializeMCP(){if(!this.mcpExecutor){let{ClientMCPExecutor:e}=await Promise.resolve().then(()=>(rd(),td)),{createHeadlessMcpGate:r}=await Promise.resolve().then(()=>(wo(),Na));this.mcpExecutor=new e,this.mcpExecutor.setPermissionGate(r()),await this.mcpExecutor.initialize(),Y(`MCP executor initialized with ${this.mcpExecutor.getConnectionCount()} connections`)}}async executeRequest(e,r){let n=null,s=p4e(this.options.url,this.options.cloudApiKey);for(let o=0;o<this.options.retries;o++)try{return await this.executeWithRetry(s,e,r)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),Y(`Attempt ${o+1} failed: ${n.message}`),n instanceof Cu||n.message.includes("Authentication"))throw n;if(this.options.cloudApiKey&&n instanceof wu){let a=new URL(this.options.url);throw new fo(wl(a.hostname),"CLOUD_UNREACHABLE")}if(o<this.options.retries-1){let a=this.options.retryDelay*Math.pow(2,o);Y(`Retrying in ${a}ms...`),await this.sleep(a)}}throw n??new ha("Max retries exceeded")}async executeWithRetry(e,r,n){return new Promise((s,o)=>{let i=e.url;Y(`Connecting to ${i}`);try{this.ws=new Eo(i,{handshakeTimeout:this.options.handshakeTimeout,...e.headers?{headers:e.headers}:{}})}catch{let p=new URL(this.options.url);o(new wu(p.hostname||"localhost",p.port||void 0));return}let a=!1,l=null,c=null,u=!1,d=p=>{a||(a=!0,this.cleanup(),o(p))};this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new af("WebSocket activity",this.options.timeout)))}),this.ws.on("open",()=>{Y("WebSocket connected, sending request"),this.ws?.send(JSON.stringify({...r,protocol_version:2}))}),this.ws.on("message",p=>{this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new af("WebSocket activity",this.options.timeout)))});let f;try{f=JSON.parse(p.toString())}catch(_){let E=p?String(p):"<undefined>";Y(`Failed to parse message: ${E}`),d(new Error(`Failed to parse server message: ${_.message}`));return}let h=t1(f,NU);if(h.kind==="malformed"){let _=RU(f);d(_?new Cu("cloud_error",_):new ha(`Malformed server frame: ${h.reason}`));return}if(h.kind==="unknown"){u||(u=!0,Y(`Received an unrecognized frame type '${h.type}'; ignoring`));return}let g=h.frame;if(c===null&&g.protocol_version!==void 0&&(c=s1(g.protocol_version),c==="hard")){d(new ha(o1(g.protocol_version)));return}if(r1.has(g.type)&&!n1(g)){d(new ha(`Malformed ${g.type} payload`));return}this.handleMessage(g,n,_=>{a=!0,l=_,this.cleanup(),s(_)},_=>{a=!0,this.cleanup(),o(_)})}),this.ws.on("error",p=>{if(Y(`WebSocket error: ${p.message}`),!a){a=!0,this.cleanup();let f=new URL(this.options.url);o(new wu(f.hostname||"localhost",f.port||void 0))}}),this.ws.on("close",(p,f)=>{Y(`WebSocket closed: ${p} ${f.toString()}`),a||(a=!0,this.cleanup(),l?s(l):o(new ha(`Connection closed unexpectedly: ${p}`)))})})}handleMessage(e,r,n,s){switch(e.type){case"token":{let o=e;r?.onToken?.(o.data);break}case"complete":{let o=e,i=o.metadata||{},a=this.convertServerMetadata(o),l={result:o.result,metadata:a,clientSideExecution:i.client_side_execution===!0,userRequest:i.user_request};r?.onComplete?.(l),n(l);break}case"error":{let o=e,i=new Cu(o.code,o.message);r?.onError?.(i),s(i);break}case"mcp_query_tools":{Y("Received mcp_query_tools request"),this.handleMCPQueryTools(e);break}case"mcp_tool_request":{Y("Received mcp_tool_request"),this.handleMCPToolRequest(e);break}default:Y(`Unknown message type: ${e.type}`)}}convertServerMetadata(e){let r=e.metadata||{},n,s;r.tokens?(n=r.tokens.input,s=r.tokens.output):(n=r.input_tokens,s=r.output_tokens);let o=r.cost??r.cost_usd,i=r.execution_time??r.total_time;return{function_name:e.function_name,tokens_in:n,tokens_out:s,cost:typeof o=="number"?o:void 0,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,execution_time:typeof i=="number"?i:void 0,task_id:typeof r.task_id=="string"?r.task_id:void 0,chat_url:typeof r.chat_url=="string"?r.chat_url:void 0}}async handleMCPQueryTools(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:n}=await Promise.resolve().then(()=>(rd(),td)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(wo(),Na));this.mcpExecutor=new n,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let r=await this.mcpExecutor.handleQueryTools(e);this.ws?.send(JSON.stringify(r))}catch(r){let n=r instanceof Error?r.message:String(r),s=r instanceof Error?r.stack:void 0;Y(`Error handling mcp_query_tools: ${n}${s?`
3546
+ ${e}`:e}var Te;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(Te||(Te={}));var yC={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function uo(t,e,r,n){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&r?.[e]?r[e]:e&&yC[e]?yC[e]:n||yC._default}var TE=[{name:"config",tier:Te.LOCAL},{name:"help",tier:Te.LOCAL},{name:"version",tier:Te.LOCAL},{name:"doctor",tier:Te.LOCAL},{name:"mcp",tier:Te.LOCAL},{name:"prompt",tier:Te.LOCAL},{name:"stats",tier:Te.LOCAL},{name:"history",tier:Te.LOCAL},{name:"query",tier:Te.SERVER},{name:"chat",tier:Te.SERVER},{name:"run",tier:Te.SERVER},{name:"agent",tier:Te.SERVER},{name:"loop",tier:Te.SERVER},{name:"telegram",tier:Te.SERVER},{name:"sessions",tier:Te.SERVER},{name:"install",tier:Te.LOCAL},{name:"worktree",tier:Te.LOCAL},{name:"soul",tier:Te.LOCAL},{name:"skill",tier:Te.LOCAL},{name:"plugin",tier:Te.LOCAL},{name:"persona",tier:Te.LOCAL},{name:"cloud",tier:Te.LOCAL},{name:"upgrade",tier:Te.LOCAL}];function sce(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==Te.LOCAL&&r.tier!==Te.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var oce=sce(TE);function PF(t){return oce.get(t)?.tier}var dze=Object.fromEntries(TE.map(t=>[t.name,t.tier]));var ice=new Set(TE.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),ace="0.17.18",lce=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--offline","-D","--direct","-i","--interactive","-c","--continue-chat","-n","--new-chat","--auto","--auto-background-timeout","--no-colors","--colors","--no-emojis","--emojis","--no-animations","--animations","--no-streaming","--streaming","--show-tokens","--show-cost","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--bare","--append-system-prompt","--append-system-prompt-file","--no-project-config","--project-config","--local","-h","--help","-V","--version"]),cce=new Set(["--model","--openrouter-provider","--host","-c","--continue-chat","--auto-background-timeout","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--append-system-prompt","--append-system-prompt-file"]);function uce(t){let e=[];for(let r=0;r<t.length;r++){if(lce.has(t[r])){cce.has(t[r])&&r++;continue}e.push(t[r])}return e}function dce(t){if(t===void 0)return;let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`Invalid --max-turns "${t}": expected a non-negative integer`);return e}function pce(t){if(t===void 0)return;let e=Number(t);if(!Number.isFinite(e)||e<0)throw new Error(`Invalid --max-budget-usd "${t}": expected a non-negative number`);return e}function mce(){let t=new xF;return t.name("aii").description("AI-powered CLI assistant").version(ace,"-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 (e.g., ollama/llama3.1:8b, deepseek/deepseek-chat)").option("--openrouter-provider <slug>","Pin OpenRouter requests to a specific backend provider").option("--host <host>","API server host:port").option("--local","Force the local backend for this run (ignore managed cloud)").option("-y, --yes","Auto-confirm shell commands").option("--offline","Offline mode (no web/MCP)").option("-D, --direct","Direct mode (bypass server intent recognition)").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("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip project .aii/settings.json + settings.local.json and their deny rules for this session").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("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of tools (comma-separated, e.g., "Read,Bash,Edit")').option("--exclude-tools <list>",'Exclude tools (comma-separated, e.g., "WebSearch,WebFetch")').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--max-budget-usd <amount>","Stop before a new turn once cumulative est. cost reaches $amount").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--append-system-prompt <text>","Append additive instructions to this run").option("--append-system-prompt-file <path>","Append a workspace file of additive instructions to this run").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)").allowUnknownOption().helpOption(!1).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("install [target...]").description("Install or update Aii CLI, skills, or MCP servers").allowUnknownOption().helpOption(!1).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("loop").description("Autonomous agent loop (Ralph Wiggum pattern)").argument("[args...]","Loop arguments (prompt, --max, --verify, --budget, etc.)").allowUnknownOption().action(()=>{}),t.command("telegram").description("Telegram bot channel (chat with Aii from Telegram)").argument("[action]","Action: start, pair, status, unpair").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("sessions").description("Manage server sessions (list, info, resume, rename, delete)").argument("[action]","Action: list, info, resume, rename, delete").argument("[args...]","Additional arguments (session ID, name, etc.)").allowUnknownOption().action(()=>{}),t.command("worktree").description("Manage git worktrees for isolated development").argument("[action]","Action: create, list, remove, clean").argument("[name]","Worktree name (for create/remove)").allowUnknownOption().action(()=>{}),t.command("soul").description("Manage agent soul (personality & identity)").argument("[action]","Action: switch, show").argument("[name]","Soul name (for switch)").allowUnknownOption().action(()=>{}),t.command("cloud").description("Manage the Aii Cloud connection (login, status)").argument("[action]","Action: login, status").allowUnknownOption().action(()=>{}),t.command("skill").description("Manage AI skills").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("plugin").description("Manage skill plugins").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("persona").description("Manage workspace personas").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("upgrade").description("Update Aii CLI to latest version").argument("[version]","Target version (default: latest)").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 LF(t){let e=mce();e.exitOverride(),e.configureOutput({writeErr:()=>{}});let r="query",n,s=[];try{e.parse(t),s=e.args;let c=e.args[0];c&&ice.has(c)&&(r=c,n=e.args[1],s=e.args.slice(2))}catch(c){c instanceof OF&&(c.code==="commander.version"||c.code==="commander.helpDisplayed")&&process.exit(0),s=uce(t.slice(2))}let o=e.opts(),i={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,local:o.local??!1,openrouterProvider:o.openrouterProvider,yes:o.yes??!1,offline:o.offline??!1,direct:o.direct??!1,interactive:o.interactive??!1,continueChat:o.continueChat,newChat:o.newChat??!1,auto:o.auto??!1,quiet:!1,noProjectConfig:o.projectConfig===!1,autoBackgroundTimeout:(()=>{let c=parseInt(o.autoBackgroundTimeout??"120",10);return isNaN(c)||c===0?0:Math.max(30,Math.min(600,c))*1e3})(),noColors:!o.colors,noEmojis:!o.emojis,noAnimations:!o.animations,noStreaming:!o.streaming,showTokens:o.showTokens??!1,showCost:o.showCost??!1,outputFormat:o.outputFormat,tools:o.tools,excludeTools:o.excludeTools,maxTurns:dce(o.maxTurns),maxBudgetUsd:pce(o.maxBudgetUsd),bare:o.bare??!1,appendSystemPrompt:o.appendSystemPrompt,appendSystemPromptFile:o.appendSystemPromptFile,help:o.help??!1,version:o.version??!1},a;EC()&&(a=await MF()),(r==="chat"||i.interactive)&&(r="agent"),r==="query"&&!s.length&&!a&&(r="agent");let l;if(r==="query"&&s.length>0)l=s.join(" ");else if(r==="agent"){let c=[];n&&c.push(n),s.length>0&&c.push(...s),c.length>0&&(l=c.join(" "))}return{command:r,subcommand:n,args:s,flags:i,stdinContent:a,query:l}}function FF(t){let e=PF(t.command)??Te.SERVER;switch(t.command){case"config":return fce(t);case"mcp":return hce(t);case"prompt":return gce(t);case"stats":return _ce(t);case"history":return Ece(t);case"doctor":return{tier:Te.LOCAL,handler:"doctor",params:{}};case"install":return{tier:Te.LOCAL,handler:"install",params:{}};case"chat":return{tier:Te.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return Sce(t);case"agent":return{tier:Te.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:Te.SERVER,handler:"loop",params:{}};case"telegram":return{tier:Te.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:Te.SERVER,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:Te.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:Te.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:Te.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"skill":return{tier:Te.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:Te.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:Te.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:Te.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:Te.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:Te.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function fce(t){let e=t.subcommand??t.args[0]??"show";return{tier:Te.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function hce(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function gce(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function _ce(t){let e=t.subcommand??t.args[0];return{tier:Te.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Ece(t){let e=t.subcommand??t.args[0]??"list";return{tier:Te.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var yce=new Set(["--model","--host","--continue-chat","-c"]);function Sce(t){let e=[];t.subcommand&&e.push(t.subcommand);let r=[];for(let s=0;s<t.args.length;s++){let o=t.args[s];if(yce.has(o)){s++;continue}o.startsWith("-")||r.push(o)}e.push(...r);let n=e.join(" ");return{tier:Te.SERVER,handler:"run",params:{operation:n}}}vt();Oy();go();Se();import{createInterface as J8e}from"readline";import{spawn as Z8e}from"child_process";Fk();An();Cf();at();Gk();var d4e={timeout:12e4,retries:3,retryDelay:1e3,handshakeTimeout:5e3};function p4e(t,e){let r=new URL(t),n=r.protocol==="https:"?"wss:":"ws:";if(e){if(!(r.protocol==="https:"||r.protocol==="wss:")&&!Uk(r.hostname))throw new Error(`Refusing to send the cloud key over an insecure (${r.protocol}) connection to ${r.hostname} \u2014 use https/wss.`);return{url:`${n}//${r.host}/v1/ws/execute`,headers:{Authorization:`Bearer ${e}`}}}return{url:`${n}//${r.host}/ws/execute`}}var vs=class{options;ws=null;activityTimeout=null;mcpExecutor=null;constructor(e){this.options={...d4e,...e}}async initializeMCP(){if(!this.mcpExecutor){let{ClientMCPExecutor:e}=await Promise.resolve().then(()=>(rd(),td)),{createHeadlessMcpGate:r}=await Promise.resolve().then(()=>(wo(),Na));this.mcpExecutor=new e,this.mcpExecutor.setPermissionGate(r()),await this.mcpExecutor.initialize(),Y(`MCP executor initialized with ${this.mcpExecutor.getConnectionCount()} connections`)}}async executeRequest(e,r){let n=null,s=p4e(this.options.url,this.options.cloudApiKey);for(let o=0;o<this.options.retries;o++)try{return await this.executeWithRetry(s,e,r)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),Y(`Attempt ${o+1} failed: ${n.message}`),n instanceof Cu||n.message.includes("Authentication"))throw n;if(this.options.cloudApiKey&&n instanceof wu){let a=new URL(this.options.url);throw new fo(wl(a.hostname),"CLOUD_UNREACHABLE")}if(o<this.options.retries-1){let a=this.options.retryDelay*Math.pow(2,o);Y(`Retrying in ${a}ms...`),await this.sleep(a)}}throw n??new ha("Max retries exceeded")}async executeWithRetry(e,r,n){return new Promise((s,o)=>{let i=e.url;Y(`Connecting to ${i}`);try{this.ws=new Eo(i,{handshakeTimeout:this.options.handshakeTimeout,...e.headers?{headers:e.headers}:{}})}catch{let p=new URL(this.options.url);o(new wu(p.hostname||"localhost",p.port||void 0));return}let a=!1,l=null,c=null,u=!1,d=p=>{a||(a=!0,this.cleanup(),o(p))};this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new af("WebSocket activity",this.options.timeout)))}),this.ws.on("open",()=>{Y("WebSocket connected, sending request"),this.ws?.send(JSON.stringify({...r,protocol_version:2}))}),this.ws.on("message",p=>{this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new af("WebSocket activity",this.options.timeout)))});let f;try{f=JSON.parse(p.toString())}catch(_){let E=p?String(p):"<undefined>";Y(`Failed to parse message: ${E}`),d(new Error(`Failed to parse server message: ${_.message}`));return}let h=t1(f,NU);if(h.kind==="malformed"){let _=RU(f);d(_?new Cu("cloud_error",_):new ha(`Malformed server frame: ${h.reason}`));return}if(h.kind==="unknown"){u||(u=!0,Y(`Received an unrecognized frame type '${h.type}'; ignoring`));return}let g=h.frame;if(c===null&&g.protocol_version!==void 0&&(c=s1(g.protocol_version),c==="hard")){d(new ha(o1(g.protocol_version)));return}if(r1.has(g.type)&&!n1(g)){d(new ha(`Malformed ${g.type} payload`));return}this.handleMessage(g,n,_=>{a=!0,l=_,this.cleanup(),s(_)},_=>{a=!0,this.cleanup(),o(_)})}),this.ws.on("error",p=>{if(Y(`WebSocket error: ${p.message}`),!a){a=!0,this.cleanup();let f=new URL(this.options.url);o(new wu(f.hostname||"localhost",f.port||void 0))}}),this.ws.on("close",(p,f)=>{Y(`WebSocket closed: ${p} ${f.toString()}`),a||(a=!0,this.cleanup(),l?s(l):o(new ha(`Connection closed unexpectedly: ${p}`)))})})}handleMessage(e,r,n,s){switch(e.type){case"token":{let o=e;r?.onToken?.(o.data);break}case"complete":{let o=e,i=o.metadata||{},a=this.convertServerMetadata(o),l={result:o.result,metadata:a,clientSideExecution:i.client_side_execution===!0,userRequest:i.user_request};r?.onComplete?.(l),n(l);break}case"error":{let o=e,i=new Cu(o.code,o.message);r?.onError?.(i),s(i);break}case"mcp_query_tools":{Y("Received mcp_query_tools request"),this.handleMCPQueryTools(e);break}case"mcp_tool_request":{Y("Received mcp_tool_request"),this.handleMCPToolRequest(e);break}default:Y(`Unknown message type: ${e.type}`)}}convertServerMetadata(e){let r=e.metadata||{},n,s;r.tokens?(n=r.tokens.input,s=r.tokens.output):(n=r.input_tokens,s=r.output_tokens);let o=r.cost??r.cost_usd,i=r.execution_time??r.total_time;return{function_name:e.function_name,tokens_in:n,tokens_out:s,cost:typeof o=="number"?o:void 0,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,execution_time:typeof i=="number"?i:void 0,task_id:typeof r.task_id=="string"?r.task_id:void 0,chat_url:typeof r.chat_url=="string"?r.chat_url:void 0}}async handleMCPQueryTools(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:n}=await Promise.resolve().then(()=>(rd(),td)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(wo(),Na));this.mcpExecutor=new n,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let r=await this.mcpExecutor.handleQueryTools(e);this.ws?.send(JSON.stringify(r))}catch(r){let n=r instanceof Error?r.message:String(r),s=r instanceof Error?r.stack:void 0;Y(`Error handling mcp_query_tools: ${n}${s?`
3547
3547
  ${s}`:""}`),this.ws?.send(JSON.stringify({type:"mcp_query_tools_response",request_id:e.request_id||"unknown",success:!1,error:n,tools:[]}))}}async handleMCPToolRequest(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:n}=await Promise.resolve().then(()=>(rd(),td)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(wo(),Na));this.mcpExecutor=new n,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let r=await this.mcpExecutor.handleToolExecution(e);this.ws?.send(JSON.stringify(r))}catch(r){Y(`Error handling mcp_tool_request: ${r}`),this.ws?.send(JSON.stringify({type:"mcp_tool_response",request_id:e.request_id||"unknown",success:!1,error:String(r)}))}}resetActivityTimeout(e){this.activityTimeout&&clearTimeout(this.activityTimeout),this.activityTimeout=setTimeout(e,this.options.timeout)}cleanup(){if(this.activityTimeout&&(clearTimeout(this.activityTimeout),this.activityTimeout=null),this.ws){try{this.ws.close()}catch(e){Y(`WebSocket close error: ${e instanceof Error?e.message:String(e)}`)}this.ws=null}}async shutdownMCP(){this.mcpExecutor&&(await this.mcpExecutor.shutdown(),this.mcpExecutor=null)}disconnect(){this.cleanup()}sleep(e){return new Promise(r=>setTimeout(r,e))}};Se();import ow from"node:process";import pie from"node:process";import rw from"node:process";var m4e=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let s=Object.getOwnPropertyDescriptor(t,r),o=Object.getOwnPropertyDescriptor(e,r);!f4e(s,o)&&n||Object.defineProperty(t,r,o)},f4e=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},h4e=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},g4e=(t,e)=>`/* Wrapped ${t}*/
3548
3548
  ${e}`,_4e=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),E4e=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),y4e=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=g4e.bind(null,n,e.toString());Object.defineProperty(s,"name",E4e);let{writable:o,enumerable:i,configurable:a}=_4e;Object.defineProperty(t,"toString",{value:s,writable:o,enumerable:i,configurable:a})};function CP(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let s of Reflect.ownKeys(e))m4e(t,e,s,r);return h4e(t,e),y4e(t,e,n),t}var Z0=new WeakMap,aie=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,n=0,s=t.displayName||t.name||"<anonymous>",o=function(...i){if(Z0.set(o,++n),n===1)r=t.apply(this,i),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return CP(o,t),Z0.set(o,n),o};aie.callCount=t=>{if(!Z0.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Z0.get(t)};var lie=aie;var ru=[];ru.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&ru.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&ru.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var ew=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",vP=Symbol.for("signal-exit emitter"),kP=globalThis,S4e=Object.defineProperty.bind(Object),AP=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(kP[vP])return kP[vP];S4e(kP,vP,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],s=n.indexOf(r);s!==-1&&(s===0&&n.length===1?n.length=0:n.splice(s,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let s=!1;for(let o of this.listeners[e])s=o(r,n)===!0||s;return e==="exit"&&(s=this.emit("afterExit",r,n)||s),s}},tw=class{},b4e=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),DP=class extends tw{onExit(){return()=>{}}load(){}unload(){}},IP=class extends tw{#i=RP.platform==="win32"?"SIGINT":"SIGHUP";#r=new AP;#e;#s;#p;#t={};#o=!1;constructor(e){super(),this.#e=e,this.#t={};for(let r of ru)this.#t[r]=()=>{let n=this.#e.listeners(r),{count:s}=this.#r,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(s+=o.__signal_exit_emitter__.count),n.length===s){this.unload();let i=this.#r.emit("exit",null,r),a=r==="SIGHUP"?this.#i:r;i||e.kill(e.pid,a)}};this.#p=e.reallyExit,this.#s=e.emit}onExit(e,r){if(!ew(this.#e))return()=>{};this.#o===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#r.on(n,e),()=>{this.#r.removeListener(n,e),this.#r.listeners.exit.length===0&&this.#r.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#r.count+=1;for(let e of ru)try{let r=this.#t[e];r&&this.#e.on(e,r)}catch{}this.#e.emit=(e,...r)=>this.#m(e,...r),this.#e.reallyExit=e=>this.#n(e)}}unload(){this.#o&&(this.#o=!1,ru.forEach(e=>{let r=this.#t[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,r)}catch{}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#p,this.#r.count-=1)}#n(e){return ew(this.#e)?(this.#e.exitCode=e||0,this.#r.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...r){let n=this.#s;if(e==="exit"&&ew(this.#e)){typeof r[0]=="number"&&(this.#e.exitCode=r[0]);let s=n.call(this.#e,e,...r);return this.#r.emit("exit",this.#e.exitCode,null),s}else return n.call(this.#e,e,...r)}},RP=globalThis.process,{onExit:cie,load:vmt,unload:kmt}=b4e(ew(RP)?new IP(RP):new DP);var uie=rw.stderr.isTTY?rw.stderr:rw.stdout.isTTY?rw.stdout:void 0,T4e=uie?lie(()=>{cie(()=>{uie.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},die=T4e;var nw=!1,em={};em.show=(t=pie.stderr)=>{t.isTTY&&(nw=!1,t.write("\x1B[?25h"))};em.hide=(t=pie.stderr)=>{t.isTTY&&(die(),nw=!0,t.write("\x1B[?25l"))};em.toggle=(t,e)=>{t!==void 0&&(nw=t),nw?em.show(e):em.hide(e)};var NP=em;var H_=Ct(OP(),1);Se();import no from"node:process";function xP(){return no.platform!=="win32"?no.env.TERM!=="linux":!!no.env.CI||!!no.env.WT_SESSION||!!no.env.TERMINUS_SUBLIME||no.env.ConEmuTask==="{cmd::Cmder}"||no.env.TERM_PROGRAM==="Terminus-Sublime"||no.env.TERM_PROGRAM==="vscode"||no.env.TERM==="xterm-256color"||no.env.TERM==="alacritty"||no.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var C4e={info:m.blue("\u2139"),success:m.green("\u2714"),warning:m.yellow("\u26A0"),error:m.red("\u2716")},v4e={info:m.blue("i"),success:m.green("\u221A"),warning:m.yellow("\u203C"),error:m.red("\xD7")},k4e=xP()?C4e:v4e,q_=k4e;Db();var A4e=lc();function MP(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(A4e,"")}Db();var D4e=lc();function PP(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(D4e,"")}function gie(t){return t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109}function _ie(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function Eie(t){return t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9776&&t<=9783||t>=9800&&t<=9811||t===9855||t>=9866&&t<=9871||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12773||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t>=94192&&t<=94198||t>=94208&&t<=101589||t>=101631&&t<=101662||t>=101760&&t<=101874||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t>=119552&&t<=119638||t>=119648&&t<=119670||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128728||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129674||t>=129678&&t<=129734||t===129736||t>=129741&&t<=129756||t>=129759&&t<=129770||t>=129775&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141}function I4e(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function yie(t,{ambiguousAsWide:e=!1}={}){return I4e(t),_ie(t)||Eie(t)||e&&gie(t)?2:1}var Tie=Ct(bie(),1),R4e=new Intl.Segmenter,N4e=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function LP(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=e;if(n||(t=PP(t)),t.length===0)return 0;let s=0,o={ambiguousAsWide:!r};for(let{segment:i}of R4e.segment(t)){let a=i.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!N4e.test(i)){if((0,Tie.default)().test(i)){s+=2;continue}s+=yie(a,o)}}return s}function FP({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import wie from"node:process";function $P(){let{env:t}=wie,{TERM:e,TERM_PROGRAM:r}=t;return wie.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}import Vo from"node:process";var O4e=3,UP=class{#i=0;start(){this.#i++,this.#i===1&&this.#r()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#r(){Vo.platform==="win32"||!Vo.stdin.isTTY||(Vo.stdin.setRawMode(!0),Vo.stdin.on("data",this.#s),Vo.stdin.resume())}#e(){Vo.stdin.isTTY&&(Vo.stdin.off("data",this.#s),Vo.stdin.pause(),Vo.stdin.setRawMode(!1))}#s(e){e[0]===O4e&&Vo.emit("SIGINT")}},x4e=new UP,BP=x4e;var M4e=Ct(OP(),1),GP=class{#i=0;#r=!1;#e=0;#s=-1;#p=0;#t;#o;#n;#m;#h;#c;#u;#d;#g;#a;#l;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:ow.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#h=this.#t.interval,this.#n=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:FP({stream:this.#n}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,ow.env.NODE_ENV==="test"&&(this._stream=this.#n,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(r){this.#i=r}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#s}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#h??this.#o.interval??100}get spinner(){return this.#o}set spinner(e){if(this.#s=-1,this.#h=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#o=e}else if(!$P())this.#o=H_.default.line;else if(e===void 0)this.#o=H_.default.dots;else if(e!=="default"&&H_.default[e])this.#o=H_.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#g}set text(e=""){this.#g=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#l}set suffixText(e=""){this.#l=e,this.#f()}get isSpinning(){return this.#m!==void 0}#_(e=this.#a,r=" "){return typeof e=="string"&&e!==""?e+r:typeof e=="function"?e()+r:""}#E(e=this.#l,r=" "){return typeof e=="string"&&e!==""?r+e:typeof e=="function"?r+e():""}#f(){let e=this.#n.columns??80,r=this.#_(this.#a,"-"),n=this.#E(this.#l,"-"),s=" ".repeat(this.#d)+r+"--"+this.#g+"--"+n;this.#e=0;for(let o of MP(s).split(`
3549
3549
  `))this.#e+=Math.max(1,Math.ceil(LP(o,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#c&&!this.#u}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=e}get isSilent(){return this.#u}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#u=e}frame(){let e=Date.now();(this.#s===-1||e-this.#p>=this.interval)&&(this.#s=++this.#s%this.#o.frames.length,this.#p=e);let{frames:r}=this.#o,n=r[this.#s];this.color&&(n=m[this.color](n));let s=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",o=typeof this.text=="string"?" "+this.text:"",i=typeof this.#l=="string"&&this.#l!==""?" "+this.#l:"";return s+n+o+i}clear(){if(!this.#c||!this.#n.isTTY)return this;this.#n.cursorTo(0);for(let e=0;e<this.#i;e++)e>0&&this.#n.moveCursor(0,-1),this.#n.clearLine(1);return(this.#d||this.lastIndent!==this.#d)&&this.#n.cursorTo(this.#d),this.lastIndent=this.#d,this.#i=0,this}render(){return this.#u?this:(this.clear(),this.#n.write(this.frame()),this.#i=this.#e,this)}start(e){return e&&(this.text=e),this.#u?this:this.#c?this.isSpinning?this:(this.#t.hideCursor&&NP.hide(this.#n),this.#t.discardStdin&&ow.stdin.isTTY&&(this.#r=!0,BP.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#n.write(`- ${this.text}
@@ -3554,7 +3554,7 @@ ${e}`,_4e=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),E4e=Obj
3554
3554
  `+this.color(s,m.dim)}formatError(e){let r=[];return r.push(this.color(`${this.emoji("\u274C ")}${e.message}`,m.red)),e.suggestions&&e.suggestions.length>0&&(r.push(""),r.push(this.color(`${this.emoji("\u{1F4A1} ")}Solutions:`,m.yellow)),e.suggestions.forEach((n,s)=>{r.push(this.color(` ${s+1}. ${n}`,m.gray))})),r.join(`
3555
3555
  `)}formatConfig(e){let r=[];r.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,L.model)),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",m.green):this.color("\u2717",m.red),s=e.model.startsWith(e.provider+"/")?e.model.slice(e.provider.length+1):e.model;if(r.push(`- LLM provider: ${e.provider} (${s}) - ${n}`),e.webSearch){let o=e.webSearch.enabled?this.color("\u2713",m.green):this.color("\u2717",m.red);r.push(`- Web search: ${e.webSearch.provider??"none"} - ${o}`)}return e.issues&&e.issues.length>0&&r.push(`- Configuration issues: ${e.issues.length}`),r.join(`
3556
3556
  `)}formatHealthCheck(e,r){let n=[],s=r?`Aii Doctor v${r}`:"Aii Doctor";n.push(this.color(s,L.model)),n.push("");let o=22;for(let l of e){let c=o-l.name.length-1,u=".".repeat(Math.max(2,c)),d,p;switch(l.status){case"ok":d="OK",p=m.green;break;case"warn":d="WARN",p=m.yellow;break;case"error":d="FAIL",p=m.red;break}let f=this.color(d,p),h=l.message?` (${l.message})`:"";n.push(` ${l.name} ${this.color(u,m.gray)} ${f}${h}`)}let i=e.filter(l=>l.status==="error").length,a=e.filter(l=>l.status==="warn").length;return n.push(""),i>0?n.push(` ${this.color(`${i} check${i>1?"s":""} failed.`,m.red)}`):a>0?n.push(` ${this.color("All checks passed with warnings.",m.yellow)}`):n.push(` ${this.color("All checks passed.",m.green)}`),n.join(`
3557
- `)}};function $n(t={}){return new jP(t)}An();var nu={openrouter:"openrouter",ollama:"ollama",anthropic:"anthropic",openai:"openai",gemini:"gemini",google:"gemini",deepseek:"deepseek",moonshot:"moonshot",zai:"zai"},L4e=[{provider:"openrouter",patterns:[/^openrouter\//]},{provider:"ollama",patterns:[/^ollama\//]},{provider:"anthropic",patterns:[/^anthropic\//,/^claude-/,/^claude$/i]},{provider:"openai",patterns:[/^openai\//,/^gpt-/,/^o1-/,/^o3-/,/^chatgpt-/,/^text-davinci/]},{provider:"gemini",patterns:[/^gemini\//,/^google\//,/^gemini-/,/^gemini$/i]},{provider:"deepseek",patterns:[/^deepseek\//,/^deepseek-/,/^deepseek$/i]},{provider:"moonshot",patterns:[/^moonshot\//,/^kimi-/,/^moonshot-/,/^moonshot$/i]},{provider:"zai",patterns:[/^zai\//,/^glm-/,/^glm$/i,/^chatglm/i]}];function gr(t){if(!t)return t;let e=t.indexOf(":");if(e>0){let r=t.substring(0,e).toLowerCase();if(r in nu)return r+"/"+t.substring(e+1)}return t}function YP(t){if(!t)return;let e=t.toLowerCase();for(let{provider:r,patterns:n}of L4e)for(let s of n)if(s.test(e))return r}function _r(t,e){if(!t)return t;let r=t.indexOf("/");if(r===-1)return t;let n=t.substring(0,r).toLowerCase();return n!=="ollama"&&n in nu?e&&nu[n]!==e?t:t.substring(r+1):t}function iw(t){if(!t)return;let e=t.indexOf("/");if(e>0){let n=t.substring(0,e).toLowerCase();if(n in nu){let s=nu[n],o=t.substring(e+1),i=s==="ollama"?`ollama/${o}`:o;return{provider:s,model:i}}}let r=t.indexOf(":");if(r>0){let n=t.substring(0,r).toLowerCase();if(n in nu){let s=nu[n],o=t.substring(r+1),i=s==="ollama"?`ollama/${o}`:o;return{provider:s,model:i}}}}function Ji(t){let e=t.lastIndexOf("@");return e===-1||e===t.length-1?{model:t,openrouterProvider:void 0}:{model:t.slice(0,e),openrouterProvider:t.slice(e+1)}}function Ur(t,e){if(t){let r=YP(t);if(r)return r}return e}Se();import*as Iie from"readline";An();import*as ks from"fs";import*as aw from"path";import*as Cie from"os";import*as rm from"fs";import{randomUUID as F4e}from"crypto";function WP(t,e,r=384){let n=`${t}.${process.pid}.${F4e()}.tmp`;try{rm.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),rm.renameSync(n,t)}catch(s){try{rm.unlinkSync(n)}catch{}throw s}}var j_=aw.join(Cie.homedir(),".aii","conversations"),VP=aw.join(j_,"current.json");function lw(){ks.existsSync(j_)||ks.mkdirSync(j_,{recursive:!0,mode:448});try{ks.chmodSync(j_,448)}catch{}}function $4e(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function U4e(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function vie(t){return aw.join(j_,`${t}.json`)}function kie(){lw();try{if(ks.existsSync(VP)){let t=ks.readFileSync(VP,"utf-8"),e=JSON.parse(t),r=vie(e.id);if(ks.existsSync(r)){let n=ks.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return Aie()}function Aie(){lw();let t={id:$4e(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Y_(t),B4e(t.id),t}function Y_(t){if(lw(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=U4e(r.content))}t.updatedAt=Date.now();let e=vie(t.id);WP(e,JSON.stringify(t,null,2))}function B4e(t){lw(),WP(VP,JSON.stringify({id:t}))}function Die(){return Aie()}Fc();var G4e="0.17.17",KP=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=kie(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=$n({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()}),Y_(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(`
3557
+ `)}};function $n(t={}){return new jP(t)}An();var nu={openrouter:"openrouter",ollama:"ollama",anthropic:"anthropic",openai:"openai",gemini:"gemini",google:"gemini",deepseek:"deepseek",moonshot:"moonshot",zai:"zai"},L4e=[{provider:"openrouter",patterns:[/^openrouter\//]},{provider:"ollama",patterns:[/^ollama\//]},{provider:"anthropic",patterns:[/^anthropic\//,/^claude-/,/^claude$/i]},{provider:"openai",patterns:[/^openai\//,/^gpt-/,/^o1-/,/^o3-/,/^chatgpt-/,/^text-davinci/]},{provider:"gemini",patterns:[/^gemini\//,/^google\//,/^gemini-/,/^gemini$/i]},{provider:"deepseek",patterns:[/^deepseek\//,/^deepseek-/,/^deepseek$/i]},{provider:"moonshot",patterns:[/^moonshot\//,/^kimi-/,/^moonshot-/,/^moonshot$/i]},{provider:"zai",patterns:[/^zai\//,/^glm-/,/^glm$/i,/^chatglm/i]}];function gr(t){if(!t)return t;let e=t.indexOf(":");if(e>0){let r=t.substring(0,e).toLowerCase();if(r in nu)return r+"/"+t.substring(e+1)}return t}function YP(t){if(!t)return;let e=t.toLowerCase();for(let{provider:r,patterns:n}of L4e)for(let s of n)if(s.test(e))return r}function _r(t,e){if(!t)return t;let r=t.indexOf("/");if(r===-1)return t;let n=t.substring(0,r).toLowerCase();return n!=="ollama"&&n in nu?e&&nu[n]!==e?t:t.substring(r+1):t}function iw(t){if(!t)return;let e=t.indexOf("/");if(e>0){let n=t.substring(0,e).toLowerCase();if(n in nu){let s=nu[n],o=t.substring(e+1),i=s==="ollama"?`ollama/${o}`:o;return{provider:s,model:i}}}let r=t.indexOf(":");if(r>0){let n=t.substring(0,r).toLowerCase();if(n in nu){let s=nu[n],o=t.substring(r+1),i=s==="ollama"?`ollama/${o}`:o;return{provider:s,model:i}}}}function Ji(t){let e=t.lastIndexOf("@");return e===-1||e===t.length-1?{model:t,openrouterProvider:void 0}:{model:t.slice(0,e),openrouterProvider:t.slice(e+1)}}function Ur(t,e){if(t){let r=YP(t);if(r)return r}return e}Se();import*as Iie from"readline";An();import*as ks from"fs";import*as aw from"path";import*as Cie from"os";import*as rm from"fs";import{randomUUID as F4e}from"crypto";function WP(t,e,r=384){let n=`${t}.${process.pid}.${F4e()}.tmp`;try{rm.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),rm.renameSync(n,t)}catch(s){try{rm.unlinkSync(n)}catch{}throw s}}var j_=aw.join(Cie.homedir(),".aii","conversations"),VP=aw.join(j_,"current.json");function lw(){ks.existsSync(j_)||ks.mkdirSync(j_,{recursive:!0,mode:448});try{ks.chmodSync(j_,448)}catch{}}function $4e(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function U4e(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function vie(t){return aw.join(j_,`${t}.json`)}function kie(){lw();try{if(ks.existsSync(VP)){let t=ks.readFileSync(VP,"utf-8"),e=JSON.parse(t),r=vie(e.id);if(ks.existsSync(r)){let n=ks.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return Aie()}function Aie(){lw();let t={id:$4e(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Y_(t),B4e(t.id),t}function Y_(t){if(lw(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=U4e(r.content))}t.updatedAt=Date.now();let e=vie(t.id);WP(e,JSON.stringify(t,null,2))}function B4e(t){lw(),WP(VP,JSON.stringify({id:t}))}function Die(){return Aie()}Fc();var G4e="0.17.18",KP=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=kie(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=$n({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()}),Y_(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(`
3558
3558
  \u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(m.red(`
3559
3559
  \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(),Y_(this.conversation))}}displayWelcome(){console.log("\u{1FABC} 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=Iie.createInterface({input:process.stdin,output:process.stdout}),s=[],o=!1,i=()=>{o=!0,n.close()},a=l=>{n.question(l,c=>{if(s.length===0&&c.trim().startsWith("/")){i(),e(c.trim());return}c.endsWith("\\")?(s.push(c.slice(0,-1)),a(" ")):(s.push(c),i(),e(s.join(`
3560
3560
  `).trim()))})};n.on("SIGINT",()=>{i(),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(m.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 zr(n.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",i=gr(this.parsed.flags.model??""),a=Ur(i||void 0,r.llm.provider),l=_r(i||r.llm.model,a);this.effectiveProvider=a;let c=this.configManager.getApiKey(a);if(!c)throw new qt(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let u=Ko(!this.parsed.flags.noAnimations);u.start("");let d=Qo({spinner:u,enabled:!this.parsed.flags.noStreaming}),p=this.conversation.messages.slice(-21,-1).map(y=>({role:y.role,content:y.content})),f={api_key:o,system_prompt:null,user_prompt:e,user_message:e,output_mode:"CLEAN",streaming:!this.parsed.flags.noStreaming,model:l,llm_provider:a,llm_api_key:c,provider_api_key:c,client_type:"cli",offline:this.parsed.flags.offline,conversation_history:p.length>0?p:void 0,soul:rn.getInstance().getSoulName()},h=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,g=new vs({url:h}),_="",E=!1;try{let y=await g.executeRequest(f,{onToken:w=>{_+=w,E=!0,d.onToken(w)}});d.flush();let T=y.result||_;!E&&T&&console.log(T),console.log(""),y.metadata&&this.displayExecutionSummary(y.metadata),T&&(this.conversation.messages.push({role:"assistant",content:T,timestamp:Date.now()}),Y_(this.conversation))}catch(y){throw u.stop(!0),y}finally{g.disconnect()}}displayExecutionSummary(e){let r=e.cost||0,n=e.tokens_in||0,s=e.tokens_out||0,o=n+s;this.stats.cumulativeTokens+=o,this.stats.cumulativeCost+=r;let i=e.provider,a=!i;console.log(this.formatter.formatExecutionSummary({provider:i||this.effectiveProvider,providerInferred:a,model:e.model,tokens_in:n,tokens_out:s,cost:r,execution_time:e.execution_time})),console.log("")}clearConversation(){this.conversation=Die(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
@@ -4244,10 +4244,10 @@ ${r.yellow("CONFIG FILE:")}
4244
4244
  .aii/settings.json Project config (committed, restrict-only)
4245
4245
  .aii/settings.local.json Your local overrides (gitignored)
4246
4246
  ${r.gray("Skip both for a session with: aii --no-project-config")}
4247
- `)}import*as ti from"fs";sr();async function zae(t,e){let r=$n({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await R3e(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let l=`${e.getConfigDir()}/mcp_servers.json`;if(ti.existsSync(l))try{let f=ti.readFileSync(l,"utf-8"),h=JSON.parse(f),g=Object.keys(h.mcpServers??{}).length;g>0?n.push({name:"MCP Servers",status:"ok",message:`${g} 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"});if(dw())try{let{execSync:f}=await import("child_process"),g=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:g?`v${g[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});dw()?pw()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:c}):n.push({name:"Node.js",status:"error",message:`${c} (requires >= 18)`});let d=await N3e();n.push(...d),console.log(r.formatHealthCheck(n,Bl)),n.some(f=>f.status==="error")&&process.exit(1)}async function R3e(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 s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.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"}}}async function N3e(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(zn(),h1)),r=`${e()}/skills`;if(!ti.existsSync(r))return t;let n=ti.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;ti.existsSync(o)||t.push({name:"Skill Shadow",status:"warn",message:`~/.aii/skills/${s.name}/ has no SKILL.md \u2014 may shadow other skills`})}try{let{PersonaManager:s}=await Promise.resolve().then(()=>(At(),Ot));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",l=`${r}/${a}`;ti.existsSync(l)&&ti.existsSync(`${l}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}Se();sr();import{execSync as ML}from"node:child_process";var Fw="@aiiware/aii";async function qae(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.17.17";console.log(""),console.log(L.logo(" Install")),console.log(""),console.log(` Current version: ${L.model(n)}`),console.log(""),console.log(m.yellow(" USAGE:")),console.log(` ${m.green("aii install")} Update to latest version`),console.log(` ${m.green("aii install <version>")} Install specific version`),console.log(` ${m.green("aii install skill <src>")} Install a skill package ${m.dim("(coming soon)")}`),console.log(` ${m.green("aii install mcp <name>")} Install an MCP server ${m.dim("(coming soon)")}`),console.log(""),console.log(m.yellow(" EXAMPLES:")),console.log(` ${m.green("aii install")} ${m.dim("# Self-update to latest")}`),console.log(` ${m.green("aii install 0.13.10")} ${m.dim("# Pin to specific version")}`),console.log("");return}if(r==="skill"){console.log("Skill installation coming soon. For now use: /skills install owner/repo");return}if(r==="mcp"){console.log("MCP installation coming soon. For now use: aii mcp install <server>");return}console.log("\x1B[33m\u26A0 `aii install` for self-update is deprecated. Use `aii upgrade` instead.\x1B[0m"),console.log(`\x1B[33m This alias will be removed in v0.16.x.\x1B[0m
4248
- `),await O3e(r)}async function O3e(t){let e="0.17.17",r=t&&t!=="latest"?t:"";if(console.log(""),r){console.log(`\u{1FABC} Installing Aii CLI v${r}...`),console.log("");try{ML(`npm install -g ${Fw}@${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
4247
+ `)}import*as ti from"fs";sr();async function zae(t,e){let r=$n({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await R3e(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let l=`${e.getConfigDir()}/mcp_servers.json`;if(ti.existsSync(l))try{let f=ti.readFileSync(l,"utf-8"),h=JSON.parse(f),g=Object.keys(h.mcpServers??{}).length;g>0?n.push({name:"MCP Servers",status:"ok",message:`${g} 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"});if(dw())try{let{execSync:f}=await import("child_process"),g=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:g?`v${g[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});dw()?pw()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:c}):n.push({name:"Node.js",status:"error",message:`${c} (requires >= 18)`});let d=await N3e();n.push(...d),console.log(r.formatHealthCheck(n,Bl)),n.some(f=>f.status==="error")&&process.exit(1)}async function R3e(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 s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.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"}}}async function N3e(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(zn(),h1)),r=`${e()}/skills`;if(!ti.existsSync(r))return t;let n=ti.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;ti.existsSync(o)||t.push({name:"Skill Shadow",status:"warn",message:`~/.aii/skills/${s.name}/ has no SKILL.md \u2014 may shadow other skills`})}try{let{PersonaManager:s}=await Promise.resolve().then(()=>(At(),Ot));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",l=`${r}/${a}`;ti.existsSync(l)&&ti.existsSync(`${l}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}Se();sr();import{execSync as ML}from"node:child_process";var Fw="@aiiware/aii";async function qae(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.17.18";console.log(""),console.log(L.logo(" Install")),console.log(""),console.log(` Current version: ${L.model(n)}`),console.log(""),console.log(m.yellow(" USAGE:")),console.log(` ${m.green("aii install")} Update to latest version`),console.log(` ${m.green("aii install <version>")} Install specific version`),console.log(` ${m.green("aii install skill <src>")} Install a skill package ${m.dim("(coming soon)")}`),console.log(` ${m.green("aii install mcp <name>")} Install an MCP server ${m.dim("(coming soon)")}`),console.log(""),console.log(m.yellow(" EXAMPLES:")),console.log(` ${m.green("aii install")} ${m.dim("# Self-update to latest")}`),console.log(` ${m.green("aii install 0.13.10")} ${m.dim("# Pin to specific version")}`),console.log("");return}if(r==="skill"){console.log("Skill installation coming soon. For now use: /skills install owner/repo");return}if(r==="mcp"){console.log("MCP installation coming soon. For now use: aii mcp install <server>");return}console.log("\x1B[33m\u26A0 `aii install` for self-update is deprecated. Use `aii upgrade` instead.\x1B[0m"),console.log(`\x1B[33m This alias will be removed in v0.16.x.\x1B[0m
4248
+ `),await O3e(r)}async function O3e(t){let e="0.17.18",r=t&&t!=="latest"?t:"";if(console.log(""),r){console.log(`\u{1FABC} Installing Aii CLI v${r}...`),console.log("");try{ML(`npm install -g ${Fw}@${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
4249
4249
  \u274C Failed to install v${r}`),console.error(` Try manually: npm install -g ${Fw}@${r}`),process.exit(1)}}else{console.log("\u{1FABC} Updating Aii CLI to latest..."),console.log(` Current version: ${e}`),console.log("");try{ML(`npm install -g ${Fw}@latest`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
4250
- \u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${Fw}@latest`),process.exit(1)}}try{let n=ML("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}Se();var Hae="0.17.17";function PL(t){let r=!t.flags.noColors?m:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
4250
+ \u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${Fw}@latest`),process.exit(1)}}try{let n=ML("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}Se();var Hae="0.17.18";function PL(t){let r=!t.flags.noColors?m:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
4251
4251
  ${r.cyan("AII")} - AI-powered CLI assistant v${Hae}
4252
4252
 
4253
4253
  ${r.yellow("USAGE:")}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiiware/aii",
3
- "version": "0.17.17",
3
+ "version": "0.17.18",
4
4
  "type": "module",
5
5
  "description": "🪼 AI-powered CLI assistant for terminal productivity",
6
6
  "author": "AiiWare <support@aiiware.com>",