@aiiware/aii 0.21.6 → 0.21.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/aii +14 -14
- 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.21.
|
|
3
|
+
* @aiiware/aii v0.21.8
|
|
4
4
|
*
|
|
5
5
|
* AI-powered CLI assistant for terminal productivity
|
|
6
6
|
*
|
|
@@ -214,7 +214,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
214
214
|
Open this URL to sign in:
|
|
215
215
|
${p.verify_url}
|
|
216
216
|
`),r(p.verify_url),i(" Waiting for authentication... (press Ctrl+C to cancel)");let h=Math.max(1,p.interval||2)*1e3,f=u0e(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 hl("The sign-in code expired. Run the command again to retry.")}}catch(g){if(g instanceof hl)throw g}if(o()>=f)throw new hl("Timed out waiting for sign-in. Run the command again to retry.");await s(h)}}var hl,a0e,Vc=k(()=>{"use strict";hl=class extends Error{constructor(e){super(e),this.name="DeviceAuthError"}},a0e=3e5});var A6={};ue(A6,{configureLogger:()=>ZS,debug:()=>W,error:()=>v6,formatError:()=>eb,info:()=>w6,logger:()=>L,success:()=>k6,warn:()=>C6});function ZS(t){dg={...dg,...t}}function pg(t){return dg.emojis?t+" ":""}function Kc(t,e){return dg.colors?e(t):t}function W(t,...e){dg.debug&&console.debug(Kc(`[DEBUG] ${t}`,m.gray),...e)}function w6(t,...e){console.log(t,...e)}function C6(t,...e){console.warn(Kc(`${pg("\u26A0\uFE0F")}${t}`,m.yellow),...e)}function v6(t,...e){console.error(Kc(`${pg("\u274C")}${t}`,m.red),...e)}function k6(t,...e){console.log(Kc(`${pg("\u2705")}${t}`,m.green),...e)}function eb(t){let e=[];return e.push(Kc(`${pg("\u274C")}${t.message}`,m.red)),t.suggestions&&t.suggestions.length>0&&(e.push(""),e.push(Kc(`${pg("\u{1F4A1}")}Solutions:`,m.yellow)),t.suggestions.forEach((n,r)=>{e.push(Kc(` ${r+1}. ${n}`,m.gray))})),e.join(`
|
|
217
|
-
`)}var d0e,dg,L,ut=k(()=>{"use strict";ye();d0e={debug:!1,colors:!0,emojis:!0},dg={...d0e};L={debug:W,info:w6,warn:C6,error:v6,success:k6,formatError:eb,configure:ZS}});function I6(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function tb(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let n=t.type;return typeof n!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(n)?{kind:"ok",frame:t}:{kind:"unknown",type:n,protocolVersion:I6(t.protocol_version)}}function D6(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 XD(t){return t==null||typeof t=="object"}function rb(t){switch(t.type){case"tool_request":return XD(t.input);case"mcp_tool_request":return XD(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(n=>n==null||typeof n=="object"&&XD(n.input))}default:return!0}}function sb(t){return I6(t)>2?"hard":"compatible"}function ob(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 N6,R6,nb,JD=k(()=>{"use strict";N6=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"]),R6=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"]),nb=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});var eN={};ue(eN,{MCPConfigManager:()=>an,MCP_CATALOG:()=>Qc});import*as Is from"fs";import*as ib from"path";import*as ZD from"os";var Qc,an,gl=k(()=>{"use strict";Qc={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",ZD.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"}},an=class{configPath;constructor(e){this.configPath=e||ib.join(ZD.homedir(),".aii","mcp_servers.json"),this.ensureConfigDir()}ensureConfigDir(){let e=ib.dirname(this.configPath);Is.existsSync(e)||Is.mkdirSync(e,{recursive:!0})}loadConfig(){if(!Is.existsSync(this.configPath))return{mcpServers:{}};try{let e=Is.readFileSync(this.configPath,"utf-8"),n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{mcpServers:{}}}catch{return{mcpServers:{}}}}saveConfig(e){try{return this.ensureConfigDir(),Is.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf-8"),!0}catch{return!1}}backupConfig(){if(!Is.existsSync(this.configPath))return!0;try{let e=this.configPath+".backup";return Is.copyFileSync(this.configPath,e),!0}catch{return!1}}getConfigPath(){return this.configPath}}});var p0e,m0e,f0e,h0e,g0e,_0e,E0e,Xc,ab,_l,tN=k(()=>{"use strict";ye();p0e={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")}},m0e={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")}},f0e={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")}},h0e={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")}},g0e={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")}},_0e={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")}},E0e={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}},Xc={classic:p0e,brand:m0e,teal:f0e,indigo:h0e,forest:g0e,amber:_0e,grayscale:E0e},ab="classic",_l=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Jc={};ue(Jc,{BAND_STYLE_INFO:()=>mg,BAND_STYLE_ORDER:()=>El,DEFAULT_BAND_STYLE:()=>rN,ThemeManager:()=>_o,getAccentColorName:()=>De,getThemeColors:()=>j,getUserInputTextColorName:()=>mp,resolveBandBg:()=>pp});function pp(t,e){let n=mg[t];if(n.blend===null)return y0e;let r=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(r.replace("#",""),16),o=n.blend,i=(a,l)=>Math.round(a*o+l*(1-o));return"#"+(i(s>>16&255,nN[0])<<16|i(s>>8&255,nN[1])<<8|i(s&255,nN[2])).toString(16).padStart(6,"0")}function j(){return _o.getInstance().getColors()}function De(){return _o.getInstance().getAccentColorName()}function mp(){return _o.getInstance().getUserInputTextColorName()}var El,mg,rN,nN,y0e,_o,yl=k(()=>{"use strict";tN();ct();El=["subtle","themed","neutral","bold"],mg={subtle:{blend:.16,description:"Faint theme tint \u2014 quietest"},themed:{blend:.28,description:"Theme-tinted band (default)"},neutral:{blend:null,description:"Fixed neutral gray (theme-independent)"},bold:{blend:.4,description:"Strong theme tint \u2014 selection-like"}},rN="themed",nN=[20,22,27],y0e="#262C34";_o=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Xc[ab]}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 n=Xc[e];if(!n){let r=_l.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${r}`)}this.activeTheme=n}isValidTheme(e){return e in Xc}getAvailableThemes(){return _l.map(e=>Xc[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Ce().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=rN,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${El.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return El.includes(e)}reset(){this.activeTheme=Xc[ab],this.bandStyle=null}}});var mt=k(()=>{"use strict";tN();yl()});import{resolve as S0e}from"path";function b0e(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",n=process.env.COLORTERM??"",r=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"||r||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||n==="truecolor"?!0:!(t==="dumb"||!process.stdout.isTTY)}function fg(){return sN===null&&(sN=b0e()),sN}function T0e(){return process.platform==="darwin"?"Cmd":"Ctrl"}function x6(){return O6||!fg()?"":(O6=!0,` (${T0e()}+Click to open)`)}function w0e(t,e){return fg()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function M6(t,e){let n=process.env.HOME??process.env.USERPROFILE??"",r=t;n&&t.startsWith(n)&&(r="~"+t.slice(n.length));let s=e?`${r}:${e}`:r;if(!fg())return j().filePath(s);let o=j().accent(s),a=`file://${S0e(t)}`;return e!==void 0&&e>0&&(a+=`#L${e}`),w0e(o,a)}var sN,O6,P6=k(()=>{"use strict";mt();sN=null,O6=!1});var $6={};ue($6,{VERSION:()=>Zc,colors:()=>$,formatCode:()=>O0e,formatPath:()=>gg,getActionIndicator:()=>R0e,padEndAnsi:()=>L0e,printAction:()=>C0e,printDivider:()=>F6,printError:()=>D0e,printExitSummary:()=>iN,printHeader:()=>N0e,printSuccess:()=>A0e,printToolComplete:()=>v0e,printToolFailed:()=>k0e,printToolResultCompact:()=>Sl,printWarning:()=>I0e,shortenPath:()=>M0e});function hg(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 C0e(t,e,n=console.log){let r=hg(e)?gg(e):$.filePath(e);n($.dim("\u25CB ")+m.bold(t)+" "+r)}function v0e(t,e,n=console.log){let r=hg(e)?gg(e):$.filePath(e);n($.success("\u2713 ")+m.bold(t)+" "+r)}function k0e(t,e,n,r=console.log){let s=hg(e)?gg(e):$.filePath(e);r($.error("\u2717 ")+m.bold(t)+" "+s),n&&r($.dim(" \u2192 ")+$.error(n))}function Sl(t,e,n=!0,r,s=console.log,o=!0){let i=n?$.success("\u25CF"):$.error("\u25CF"),a=60,l=e.length>a?e.slice(0,a-3)+"...":e;if(hg(e)){let d=e.match(/:(\d+)$/),p=d?parseInt(d[1],10):void 0,h=d?e.replace(/:(\d+)$/,""):e;l=gg(h,p)}s(`${i} ${m.bold(t)}(${l})`);let c=o&&hg(e)?$.dim(x6()):"",u=o&&!c&&!L6?$.dim(" (ctrl+o to expand)"):"";if(u&&(L6=!0),r){let d=n?$.dim:$.error;s(d(`\u2514 ${r}`)+c+u)}else{let d=n?"(No content)":"(Error)",p=n?$.dim:$.error;s(p(`\u2514 ${d}`)+c+u)}}function A0e(t){console.log($.success("\u2713 ")+t)}function I0e(t){console.log($.warning("\u26A0 ")+t)}function D0e(t){console.log($.error("\u2717 ")+t)}function F6(t=60){console.log($.dim("\u2500".repeat(t)))}function N0e(t){console.log($.logo(t)),F6(t.length)}function R0e(t){return $.thinking(`[${t}]`)}function gg(t,e){if(fg())return M6(t,e);let n=process.env.HOME??process.env.USERPROFILE??"",r=t;return n&&t.startsWith(n)&&(r="~"+t.slice(n.length)),e&&(r+=`:${e}`),$.filePath(r)}function O0e(t){return $.code(t)}function x0e(){return process.stdout.columns||80}function M0e(t,e=40){let n=process.env.HOME??process.env.USERPROFILE??"",r=t;if(n&&t.startsWith(n)&&(r="~"+t.slice(n.length)),r.length<=e)return r;let s=r.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 P0e(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function L0e(t,e){let n=P0e(t),r=Math.max(0,e-n);return t+" ".repeat(r)}function F0e(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),n=t%60;return n>0?`${e}m ${n}s`:`${e}m`}function oN(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function iN(t){let e=x0e(),n=Math.min(e-2,76),r=n-4,s=(_,E)=>{let y=_.replace(/\x1b\[[0-9;]*m/g,"").length;return _+" ".repeat(Math.max(0,E-y))},o=_=>$.border("\u2502")+" "+s(_,r)+" "+$.border("\u2502"),i=(_,E,y,S)=>{let T=Math.floor(r/2),C=$.dim(_.padEnd(15))+E,v=$.dim(y.padEnd(15))+S;return o(s(C,T)+v)},a=F0e(t.durationSeconds),l=oN(t.tokensIn),c=oN(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601\uFE0F Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log($.border("\u250C"+"\u2500".repeat(n-2)+"\u2510")),console.log(o($.logo("Session complete. \u{1FABC}"))),console.log($.border("\u251C"+"\u2500".repeat(n-2)+"\u2524")),console.log(o($.logo("Session Summary"))),console.log(o($.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($.logo("Token Usage"))),console.log(o($.dim("\u2500".repeat(11)))),console.log(i("Input",l,"Output",c));let p=t.cachedTokens??0;if(p>0){let _=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o($.dim("Cached".padEnd(15))+`${oN(p)} (${_}%)`))}let h=t.cacheSavings??0,f=h>0?$.dim(` \xB7 saved ~$${h.toFixed(4)} by prompt caching`):"";console.log(o($.dim("Cost".padEnd(15))+u+f)),console.log(o(""));let g=(_,E)=>_.length>E?`${_.slice(0,Math.max(0,E-1))}\u2026`:_;if(t.goalLine){let _=t.goalLine.replace(/^Goal:\s*/,"");console.log(o($.dim("Goal: ")+g(_,r-6)))}t.goalResumeLine&&console.log(o($.dim(g(` ${t.goalResumeLine}`,r)))),console.log(o($.dim("Model: ")+$.model(d))),console.log($.border("\u2514"+"\u2500".repeat(n-2)+"\u2518")),console.log("")}var Zc,$,L6,_n=k(()=>{"use strict";ye();P6();mt();Zc="0.21.6",$={get logo(){return j().accent.bold},get prompt(){return j().accent.bold},get model(){return j().accent},get success(){return j().success},get warning(){return j().warning},get error(){return j().error},get thinking(){return j().dim},get filePath(){return j().filePath},get code(){return j().code},get muted(){return j().muted},get dim(){return j().dim},get safe(){return j().success},get risky(){return j().warning},get destructive(){return j().error},get border(){return j().accent},get bannerBorder(){return j().accent}};L6=!1});function eu({onlyFirst:t=!1}={}){let s="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(s,t?void 0:"g")}var lb=k(()=>{});function aN(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace($0e,"")}var $0e,U6=k(()=>{lb();$0e=eu()});function B6(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 G6(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function z6(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}var q6=k(()=>{});function U0e(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function H6(t,{ambiguousAsWide:e=!1}={}){return U0e(t),G6(t)||z6(t)||e&&B6(t)?2:1}var j6=k(()=>{q6()});var W6=w((ytt,Y6)=>{Y6.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});function fp(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=e;if(r||(t=aN(t)),t.length===0)return 0;let s=0,o={ambiguousAsWide:!n};for(let{segment:i}of B0e.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)&&!G0e.test(i)){if((0,V6.default)().test(i)){s+=2;continue}s+=H6(a,o)}}return s}var V6,B0e,G0e,lN=k(()=>{U6();j6();V6=Nt(W6(),1),B0e=new Intl.Segmenter,G0e=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u")});var Ds,hp,cN=k(()=>{"use strict";Ds={maxConcurrent:5,maxIterations:100,timeout:3e5,autoBackgroundTimeout:12e4,compressionLevel:"medium",permissionMode:"default"},hp={maxConcurrent:3,timeout:30*60*1e3,permissionMode:"dontAsk"}});var cb,uN=k(()=>{"use strict";cb=`You are an expert codebase explorer. Your task is to efficiently explore and understand codebases.
|
|
217
|
+
`)}var d0e,dg,L,ut=k(()=>{"use strict";ye();d0e={debug:!1,colors:!0,emojis:!0},dg={...d0e};L={debug:W,info:w6,warn:C6,error:v6,success:k6,formatError:eb,configure:ZS}});function I6(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function tb(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let n=t.type;return typeof n!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(n)?{kind:"ok",frame:t}:{kind:"unknown",type:n,protocolVersion:I6(t.protocol_version)}}function D6(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 XD(t){return t==null||typeof t=="object"}function rb(t){switch(t.type){case"tool_request":return XD(t.input);case"mcp_tool_request":return XD(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(n=>n==null||typeof n=="object"&&XD(n.input))}default:return!0}}function sb(t){return I6(t)>2?"hard":"compatible"}function ob(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 N6,R6,nb,JD=k(()=>{"use strict";N6=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"]),R6=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"]),nb=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});var eN={};ue(eN,{MCPConfigManager:()=>an,MCP_CATALOG:()=>Qc});import*as Is from"fs";import*as ib from"path";import*as ZD from"os";var Qc,an,gl=k(()=>{"use strict";Qc={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",ZD.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"}},an=class{configPath;constructor(e){this.configPath=e||ib.join(ZD.homedir(),".aii","mcp_servers.json"),this.ensureConfigDir()}ensureConfigDir(){let e=ib.dirname(this.configPath);Is.existsSync(e)||Is.mkdirSync(e,{recursive:!0})}loadConfig(){if(!Is.existsSync(this.configPath))return{mcpServers:{}};try{let e=Is.readFileSync(this.configPath,"utf-8"),n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{mcpServers:{}}}catch{return{mcpServers:{}}}}saveConfig(e){try{return this.ensureConfigDir(),Is.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf-8"),!0}catch{return!1}}backupConfig(){if(!Is.existsSync(this.configPath))return!0;try{let e=this.configPath+".backup";return Is.copyFileSync(this.configPath,e),!0}catch{return!1}}getConfigPath(){return this.configPath}}});var p0e,m0e,f0e,h0e,g0e,_0e,E0e,Xc,ab,_l,tN=k(()=>{"use strict";ye();p0e={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")}},m0e={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")}},f0e={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")}},h0e={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")}},g0e={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")}},_0e={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")}},E0e={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}},Xc={classic:p0e,brand:m0e,teal:f0e,indigo:h0e,forest:g0e,amber:_0e,grayscale:E0e},ab="classic",_l=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Jc={};ue(Jc,{BAND_STYLE_INFO:()=>mg,BAND_STYLE_ORDER:()=>El,DEFAULT_BAND_STYLE:()=>rN,ThemeManager:()=>_o,getAccentColorName:()=>De,getThemeColors:()=>j,getUserInputTextColorName:()=>mp,resolveBandBg:()=>pp});function pp(t,e){let n=mg[t];if(n.blend===null)return y0e;let r=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(r.replace("#",""),16),o=n.blend,i=(a,l)=>Math.round(a*o+l*(1-o));return"#"+(i(s>>16&255,nN[0])<<16|i(s>>8&255,nN[1])<<8|i(s&255,nN[2])).toString(16).padStart(6,"0")}function j(){return _o.getInstance().getColors()}function De(){return _o.getInstance().getAccentColorName()}function mp(){return _o.getInstance().getUserInputTextColorName()}var El,mg,rN,nN,y0e,_o,yl=k(()=>{"use strict";tN();ct();El=["subtle","themed","neutral","bold"],mg={subtle:{blend:.16,description:"Faint theme tint \u2014 quietest"},themed:{blend:.28,description:"Theme-tinted band (default)"},neutral:{blend:null,description:"Fixed neutral gray (theme-independent)"},bold:{blend:.4,description:"Strong theme tint \u2014 selection-like"}},rN="themed",nN=[20,22,27],y0e="#262C34";_o=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Xc[ab]}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 n=Xc[e];if(!n){let r=_l.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${r}`)}this.activeTheme=n}isValidTheme(e){return e in Xc}getAvailableThemes(){return _l.map(e=>Xc[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Ce().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=rN,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${El.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return El.includes(e)}reset(){this.activeTheme=Xc[ab],this.bandStyle=null}}});var mt=k(()=>{"use strict";tN();yl()});import{resolve as S0e}from"path";function b0e(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",n=process.env.COLORTERM??"",r=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"||r||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||n==="truecolor"?!0:!(t==="dumb"||!process.stdout.isTTY)}function fg(){return sN===null&&(sN=b0e()),sN}function T0e(){return process.platform==="darwin"?"Cmd":"Ctrl"}function x6(){return O6||!fg()?"":(O6=!0,` (${T0e()}+Click to open)`)}function w0e(t,e){return fg()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function M6(t,e){let n=process.env.HOME??process.env.USERPROFILE??"",r=t;n&&t.startsWith(n)&&(r="~"+t.slice(n.length));let s=e?`${r}:${e}`:r;if(!fg())return j().filePath(s);let o=j().accent(s),a=`file://${S0e(t)}`;return e!==void 0&&e>0&&(a+=`#L${e}`),w0e(o,a)}var sN,O6,P6=k(()=>{"use strict";mt();sN=null,O6=!1});var $6={};ue($6,{VERSION:()=>Zc,colors:()=>$,formatCode:()=>O0e,formatPath:()=>gg,getActionIndicator:()=>R0e,padEndAnsi:()=>L0e,printAction:()=>C0e,printDivider:()=>F6,printError:()=>D0e,printExitSummary:()=>iN,printHeader:()=>N0e,printSuccess:()=>A0e,printToolComplete:()=>v0e,printToolFailed:()=>k0e,printToolResultCompact:()=>Sl,printWarning:()=>I0e,shortenPath:()=>M0e});function hg(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 C0e(t,e,n=console.log){let r=hg(e)?gg(e):$.filePath(e);n($.dim("\u25CB ")+m.bold(t)+" "+r)}function v0e(t,e,n=console.log){let r=hg(e)?gg(e):$.filePath(e);n($.success("\u2713 ")+m.bold(t)+" "+r)}function k0e(t,e,n,r=console.log){let s=hg(e)?gg(e):$.filePath(e);r($.error("\u2717 ")+m.bold(t)+" "+s),n&&r($.dim(" \u2192 ")+$.error(n))}function Sl(t,e,n=!0,r,s=console.log,o=!0){let i=n?$.success("\u25CF"):$.error("\u25CF"),a=60,l=e.length>a?e.slice(0,a-3)+"...":e;if(hg(e)){let d=e.match(/:(\d+)$/),p=d?parseInt(d[1],10):void 0,h=d?e.replace(/:(\d+)$/,""):e;l=gg(h,p)}s(`${i} ${m.bold(t)}(${l})`);let c=o&&hg(e)?$.dim(x6()):"",u=o&&!c&&!L6?$.dim(" (ctrl+o to expand)"):"";if(u&&(L6=!0),r){let d=n?$.dim:$.error;s(d(`\u2514 ${r}`)+c+u)}else{let d=n?"(No content)":"(Error)",p=n?$.dim:$.error;s(p(`\u2514 ${d}`)+c+u)}}function A0e(t){console.log($.success("\u2713 ")+t)}function I0e(t){console.log($.warning("\u26A0 ")+t)}function D0e(t){console.log($.error("\u2717 ")+t)}function F6(t=60){console.log($.dim("\u2500".repeat(t)))}function N0e(t){console.log($.logo(t)),F6(t.length)}function R0e(t){return $.thinking(`[${t}]`)}function gg(t,e){if(fg())return M6(t,e);let n=process.env.HOME??process.env.USERPROFILE??"",r=t;return n&&t.startsWith(n)&&(r="~"+t.slice(n.length)),e&&(r+=`:${e}`),$.filePath(r)}function O0e(t){return $.code(t)}function x0e(){return process.stdout.columns||80}function M0e(t,e=40){let n=process.env.HOME??process.env.USERPROFILE??"",r=t;if(n&&t.startsWith(n)&&(r="~"+t.slice(n.length)),r.length<=e)return r;let s=r.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 P0e(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function L0e(t,e){let n=P0e(t),r=Math.max(0,e-n);return t+" ".repeat(r)}function F0e(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),n=t%60;return n>0?`${e}m ${n}s`:`${e}m`}function oN(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function iN(t){let e=x0e(),n=Math.min(e-2,76),r=n-4,s=(_,E)=>{let y=_.replace(/\x1b\[[0-9;]*m/g,"").length;return _+" ".repeat(Math.max(0,E-y))},o=_=>$.border("\u2502")+" "+s(_,r)+" "+$.border("\u2502"),i=(_,E,y,S)=>{let T=Math.floor(r/2),C=$.dim(_.padEnd(15))+E,v=$.dim(y.padEnd(15))+S;return o(s(C,T)+v)},a=F0e(t.durationSeconds),l=oN(t.tokensIn),c=oN(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601\uFE0F Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log($.border("\u250C"+"\u2500".repeat(n-2)+"\u2510")),console.log(o($.logo("Session complete. \u{1FABC}"))),console.log($.border("\u251C"+"\u2500".repeat(n-2)+"\u2524")),console.log(o($.logo("Session Summary"))),console.log(o($.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($.logo("Token Usage"))),console.log(o($.dim("\u2500".repeat(11)))),console.log(i("Input",l,"Output",c));let p=t.cachedTokens??0;if(p>0){let _=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o($.dim("Cached".padEnd(15))+`${oN(p)} (${_}%)`))}let h=t.cacheSavings??0,f=h>0?$.dim(` \xB7 saved ~$${h.toFixed(4)} by prompt caching`):"";console.log(o($.dim("Cost".padEnd(15))+u+f)),console.log(o(""));let g=(_,E)=>_.length>E?`${_.slice(0,Math.max(0,E-1))}\u2026`:_;if(t.goalLine){let _=t.goalLine.replace(/^Goal:\s*/,"");console.log(o($.dim("Goal: ")+g(_,r-6)))}t.goalResumeLine&&console.log(o($.dim(g(` ${t.goalResumeLine}`,r)))),console.log(o($.dim("Model: ")+$.model(d))),console.log($.border("\u2514"+"\u2500".repeat(n-2)+"\u2518")),console.log("")}var Zc,$,L6,_n=k(()=>{"use strict";ye();P6();mt();Zc="0.21.8",$={get logo(){return j().accent.bold},get prompt(){return j().accent.bold},get model(){return j().accent},get success(){return j().success},get warning(){return j().warning},get error(){return j().error},get thinking(){return j().dim},get filePath(){return j().filePath},get code(){return j().code},get muted(){return j().muted},get dim(){return j().dim},get safe(){return j().success},get risky(){return j().warning},get destructive(){return j().error},get border(){return j().accent},get bannerBorder(){return j().accent}};L6=!1});function eu({onlyFirst:t=!1}={}){let s="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(s,t?void 0:"g")}var lb=k(()=>{});function aN(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace($0e,"")}var $0e,U6=k(()=>{lb();$0e=eu()});function B6(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 G6(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function z6(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}var q6=k(()=>{});function U0e(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function H6(t,{ambiguousAsWide:e=!1}={}){return U0e(t),G6(t)||z6(t)||e&&B6(t)?2:1}var j6=k(()=>{q6()});var W6=w((ytt,Y6)=>{Y6.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});function fp(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=e;if(r||(t=aN(t)),t.length===0)return 0;let s=0,o={ambiguousAsWide:!n};for(let{segment:i}of B0e.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)&&!G0e.test(i)){if((0,V6.default)().test(i)){s+=2;continue}s+=H6(a,o)}}return s}var V6,B0e,G0e,lN=k(()=>{U6();j6();V6=Nt(W6(),1),B0e=new Intl.Segmenter,G0e=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u")});var Ds,hp,cN=k(()=>{"use strict";Ds={maxConcurrent:5,maxIterations:100,timeout:3e5,autoBackgroundTimeout:12e4,compressionLevel:"medium",permissionMode:"default"},hp={maxConcurrent:3,timeout:30*60*1e3,permissionMode:"dontAsk"}});var cb,uN=k(()=>{"use strict";cb=`You are an expert codebase explorer. Your task is to efficiently explore and understand codebases.
|
|
218
218
|
|
|
219
219
|
## Core Capabilities
|
|
220
220
|
You have access to these tools for codebase exploration:
|
|
@@ -3606,7 +3606,7 @@ To enter: cd ${s.path}`);break}case"list":{let s=await fc(r);if(s.length===0){co
|
|
|
3606
3606
|
`)),console.log(" aii cloud login Sign in to Aii Cloud (verifies an existing sign-in;"),console.log(" --force re-authenticates)"),console.log(" aii cloud connect Stay online to run tasks dispatched from the Portal"),console.log(" aii cloud status Show connection + credit balance"),console.log(m.gray(`
|
|
3607
3607
|
\`aii cloud connect\` registers this machine so you can start a task from the
|
|
3608
3608
|
web ("Run on \u25BE \xB7 this machine") and approve its tool calls from the Portal.
|
|
3609
|
-
`))}var N5=k(()=>{"use strict";ye();Ga();Vc();ohe();che();fhe();_he();vhe();Ahe();yk()});var Rhe={};ue(Rhe,{handleUpgrade:()=>_Qe});import{execSync as Dhe}from"node:child_process";async function _Qe(t){let e=t.args[0]||null,n="0.21.
|
|
3609
|
+
`))}var N5=k(()=>{"use strict";ye();Ga();Vc();ohe();che();fhe();_he();vhe();Ahe();yk()});var Rhe={};ue(Rhe,{handleUpgrade:()=>_Qe});import{execSync as Dhe}from"node:child_process";async function _Qe(t){let e=t.args[0]||null,n="0.21.8",r=e?`${Nhe}@${e}`:`${Nhe}@latest`;console.log(""),console.log(e?`Upgrading Aii CLI to v${e}...`:"Upgrading Aii CLI to latest..."),console.log(` Current version: ${n}`),console.log("");try{Dhe(`npm install -g ${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
3610
3610
|
Upgrade failed. Try running with sudo or check npm permissions.`),console.error(` Manual: npm install -g ${r}`),process.exit(1)}try{let s=Dhe("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(s===n?`Already up to date (${n})`:`Upgraded: ${n} -> ${s}`)}catch{console.log(""),console.log("Installed. Restart your terminal to use the new version.")}}var Nhe,Ohe=k(()=>{"use strict";Nhe="@aiiware/aii"});var xhe={};ue(xhe,{handleSkillCmd:()=>yQe});function EQe(t){return t.userInvocable&&t.modelInvocable?"":t.userInvocable?"(CLI only)":t.modelInvocable?"(agent only)":"(disabled)"}async function yQe(t,e){let n=t.args.filter(i=>!i.startsWith("-")),r=t.flags.yes||t.args.includes("--yes")||t.args.includes("-y"),s=(t.subcommand??n[0]??"help").toLowerCase(),o=t.subcommand?n[0]??null:n[1]??null;switch(s){case"list":return SQe();case"info":return bQe(o);case"install":return wQe(o,r);case"help":default:return CQe()}}async function SQe(){let{SkillManager:t}=await Promise.resolve().then(()=>(li(),iu)),e;if(t.hasInstance())e=t.getInstance();else{e=t.getInstance(process.cwd());let o;try{let{PersonaManager:i}=await Promise.resolve().then(()=>(It(),Ot)),a=i.getInstance(process.cwd());await a.initialize(),a.isActive()&&(o=a.getActive()?.skillPaths)}catch{}await e.discover(o)}let n=e.getRegistry().getAll();if(n.length===0){console.log("No skills installed."),console.log(" Install one: aii skill install <owner/repo/skill>");return}let r=new Map;for(let o of n){let i=r.get(o.source)||[];i.push(o),r.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=r.get(o);if(i)for(let a of i){let l=a.name.padEnd(18),c=a.source.padEnd(16),u=EQe(a).padEnd(14),d=(a.description||"").slice(0,34);console.log(` ${l}${c}${u}${d}`)}}console.log("")}async function bQe(t){if(!t){console.log("Usage: aii skill info <name>");return}let{SkillManager:e}=await Promise.resolve().then(()=>(li(),iu)),n;if(e.hasInstance())n=e.getInstance();else{n=e.getInstance(process.cwd());let s;try{let{PersonaManager:o}=await Promise.resolve().then(()=>(It(),Ot)),i=o.getInstance(process.cwd());await i.initialize(),i.isActive()&&(s=i.getActive()?.skillPaths)}catch{}await n.discover(s)}let r=n.getRegistry().getByName(t);if(!r){let o=n.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: ${r.name}`),console.log(` Source: ${r.source}`),console.log(` Description: ${r.description||"(none)"}`),console.log(` Invocable: ${[r.userInvocable?"user":"",r.modelInvocable?"model":""].filter(Boolean).join(" + ")||"none"}`),r.allowedTools?.length&&console.log(` Tools: ${r.allowedTools.join(" ")}`),console.log(` Path: ${r.path||"(embedded)"}`),console.log("")}function TQe(){return!process.stdin.isTTY||!process.stdout.isTTY?null:async({bodyLines:t})=>{console.log("");for(let r of t)console.log(` ${r}`);let{createInterface:e}=await import("node:readline/promises"),n=e({input:process.stdin,output:process.stdout});try{let r=await n.question("Install this skill? [y/N] ");return/^y(es)?$/i.test(r.trim())}finally{n.close()}}}async function wQe(t,e=!1){if(!t){console.log("Usage: aii skill install <owner/repo | owner/repo/skill> [--yes]");return}let{SkillInstaller:n}=await Promise.resolve().then(()=>($g(),zb)),r=new n({projectRoot:process.cwd(),onProgress:s=>console.error(s),prompter:TQe()});try{let s=await r.install(t,{scope:"user",yes:e});s.success?(console.log(`Installed skill: ${s.skillName}`),s.installPath&&console.log(` Location: ${s.installPath}`)):s.status==="ambiguous"?(console.error(s.error||"Repository contains multiple skills."),process.exit(1)):(console.error(`Failed to install skill: ${s.error||"Unknown error"}`),process.exit(1))}catch(s){let o=s instanceof Error?s.message:String(s);console.error(`Failed to install skill: ${o}`),process.exit(1)}}function CQe(){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(" INSTALL FORMS:")),t.push(m.dim(" owner/repo Bare repo \u2014 resolves a root skill or a")),t.push(m.dim(" single-skill subdirectory automatically")),t.push(m.dim(" owner/repo/skill-path Explicit skill within a repository")),t.push(m.dim(" https://github.com/... Full tree/blob URL")),t.push(""),t.push(m.dim(" Installs show a trust preview and ask for confirmation;")),t.push(m.dim(" pass --yes (-y) to skip the prompt (required when non-interactive).")),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 tt-a1i/archify")),t.push(m.dim(" aii skill install aiiware/aii-skills/skills/commit --yes")),t.push(""),console.log(t.join(`
|
|
3611
3611
|
`))}var Mhe=k(()=>{"use strict";ye()});var Phe={};ue(Phe,{handlePluginCmd:()=>vQe});async function vQe(t,e){let n=(t.subcommand??t.args[0]??"help").toLowerCase(),r=t.subcommand?t.args[0]:t.args[1]??null,s=t.subcommand?t.args.slice(1):t.args.slice(2);switch(n){case"install":return kQe(r,s);case"uninstall":case"remove":return AQe(r);case"update":return IQe(r);case"list":case"ls":return DQe();case"help":default:return NQe()}}async function kQe(t,e){if(!t){console.log("Usage: aii plugin install <owner/repo>");return}let{PluginInstaller:n}=await Promise.resolve().then(()=>(Il(),ou)),r=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 n({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:r});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 AQe(t){if(!t){console.log("Usage: aii plugin uninstall <name>");return}let{PluginInstaller:e}=await Promise.resolve().then(()=>(Il(),ou)),n=new e;try{let r=await n.uninstall(t);r.success?(console.log(""),console.log(` ${m.green("\u2713")} Plugin ${m.bold(t)} uninstalled`),r.skillCount&&console.log(` ${r.skillCount} skills removed`),console.log("")):(console.error(` ${m.red("\u2717")} ${r.error||"Unknown error"}`),process.exit(1))}catch(r){let s=r instanceof Error?r.message:String(r);console.error(` ${m.red("\u2717")} Failed to uninstall plugin: ${s}`),process.exit(1)}}async function IQe(t){if(!t){console.log("Usage: aii plugin update <name>");return}let{PluginInstaller:e}=await Promise.resolve().then(()=>(Il(),ou)),n=new e({onProgress:r=>console.log(` ${m.dim(r)}`)});try{console.log(""),console.log(` Checking for updates to ${m.cyan(t)}...`);let r=await n.update(t);r.success?(r.error?.includes("already up to date")?console.log(` ${m.green("\u2713")} ${r.error}`):(console.log(` ${m.green("\u2713")} Plugin ${m.bold(t)} updated to v${r.version}`),r.skillCount&&console.log(` ${r.skillCount} skills available`)),console.log("")):(console.error(` ${m.red("\u2717")} ${r.error||"Unknown error"}`),process.exit(1))}catch(r){let s=r instanceof Error?r.message:String(r);console.error(` ${m.red("\u2717")} Failed to update plugin: ${s}`),process.exit(1)}}async function DQe(){let{PluginManager:t}=await Promise.resolve().then(()=>(xg(),Og)),n=await new t().listInstalled();if(n.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 r of n){let s=r.name.padEnd(18),o=`v${r.version}`.padEnd(12),i=String(r.skillCount).padEnd(8),a=new Date(r.installedAt).toLocaleDateString();console.log(` ${s}${o}${i}${a}`)}console.log("")}function NQe(){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(`
|
|
3612
3612
|
`))}var Lhe=k(()=>{"use strict";ye()});var Fhe={};ue(Fhe,{handlePersona:()=>OQe});function RQe(t){return process.stdin.isTTY?async({originId:e,event:n,command:r,index:s,total:o})=>{s===1&&(console.log(`
|
|
@@ -3631,7 +3631,7 @@ Upgrade failed. Try running with sudo or check npm permissions.`),console.error(
|
|
|
3631
3631
|
${t}
|
|
3632
3632
|
</context>
|
|
3633
3633
|
|
|
3634
|
-
${e}`:e}var be;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(be||(be={}));var bA={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function Vo(t,e,n,r){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&n?.[e]?n[e]:e&&bA[e]?bA[e]:r||bA._default}var m1=[{name:"config",tier:be.LOCAL},{name:"help",tier:be.LOCAL},{name:"version",tier:be.LOCAL},{name:"doctor",tier:be.LOCAL},{name:"mcp",tier:be.LOCAL},{name:"prompt",tier:be.LOCAL},{name:"stats",tier:be.LOCAL},{name:"history",tier:be.LOCAL},{name:"query",tier:be.SERVER},{name:"chat",tier:be.SERVER},{name:"run",tier:be.SERVER},{name:"agent",tier:be.SERVER},{name:"loop",tier:be.SERVER},{name:"telegram",tier:be.SERVER},{name:"sessions",tier:be.SERVER},{name:"goals",tier:be.LOCAL},{name:"install",tier:be.LOCAL},{name:"worktree",tier:be.LOCAL},{name:"soul",tier:be.LOCAL},{name:"skill",tier:be.LOCAL},{name:"plugin",tier:be.LOCAL},{name:"persona",tier:be.LOCAL},{name:"cloud",tier:be.LOCAL},{name:"login",tier:be.LOCAL},{name:"upgrade",tier:be.LOCAL}];function vge(t){let e=new Map;for(let n of t){if(!n.name)throw new Error("CLI command descriptor is missing a name");if(n.tier!==be.LOCAL&&n.tier!==be.SERVER)throw new Error(`CLI command "${n.name}" has an invalid tier: ${String(n.tier)}`);for(let r of[n.name,...n.aliases??[]]){if(e.has(r))throw new Error(`Duplicate CLI command name/alias: "${r}"`);e.set(r,n)}}return e}var kge=vge(m1);function _U(t){return kge.get(t)?.tier}var GXe=Object.fromEntries(m1.map(t=>[t.name,t.tier]));var yU=new Set(m1.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),Age="0.21.6",Ige=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","--continue","--signature","--no-signature","--no-project-config","--project-config","--local","-h","--help","-V","--version"]),TA=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","--signature"]);function Dge(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],s=r.indexOf("="),o=s>0?r.slice(0,s):r;if(Ige.has(o)){s===-1&&TA.has(o)&&n++;continue}e.push(r)}return e}var EU=/^[a-z0-9_]{2,40}$/i;function Nge(t){for(let e=2;e<t.length;e++){let n=t[e];if(n.startsWith("-")){!n.includes("=")&&TA.has(n)&&e++;continue}return n}}function Rge(t){for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith("-")){!n.includes("=")&&TA.has(n)&&e++;continue}return!0}return!1}function Oge(t){let e=Nge(t);if(e!==void 0&&e!=="agent"&&yU.has(e))return{argv:t};let n=[],r,s;for(let o=0;o<t.length;o++){let i=t[o];if(i==="--continue"){n.push(i);let a=t[o+1];r===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&EU.test(a)&&(Rge(t.slice(o+2))?s=`--continue ${a} \u2026: ambiguous \u2014 quote the text (aii --continue "${a} \u2026") to run it as a prompt, or run \`aii --continue ${a}\` alone to resume that session.`:(r=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);n.push("--continue"),EU.test(a)?r===void 0&&(r=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}n.push(i)}return{argv:n,continueId:r,error:s}}function xge(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 Mge(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 Pge(){let t=new hU;return t.name("aii").description("AI-powered CLI assistant").version(Age,"-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("--continue","Resume the most recent local session of this project (conversation + goal)").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("goals").description("List goals across this project's local sessions (pick one up with --continue <id>)").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, connect, status)").argument("[action]","Action: login, connect, status").allowUnknownOption().action(()=>{}),t.command("login").description("Sign in to an AI provider with your subscription (e.g., xAI SuperGrok)").argument("[args...]","Flags: --provider <name>, --status, --logout").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 SU(t){let e=Oge(t),n=e.argv,r=Pge();r.exitOverride(),r.configureOutput({writeErr:()=>{}});let s="query",o,i=[];try{r.parse(n),i=r.args;let d=r.args[0];d&&yU.has(d)&&(s=d,o=r.args[1],i=r.args.slice(2))}catch(d){d instanceof fU&&(d.code==="commander.version"||d.code==="commander.helpDisplayed")&&process.exit(0),i=Dge(n.slice(2))}let a=r.opts(),l={clean:a.clean??!1,standard:a.standard??!1,thinking:a.thinking??!1,verbose:a.verbose??!1,debug:a.debug??!1,model:a.model,host:a.host,local:a.local??!1,openrouterProvider:a.openrouterProvider,yes:a.yes??!1,offline:a.offline??!1,direct:a.direct??!1,interactive:a.interactive??!1,continueChat:a.continueChat,newChat:a.newChat??!1,auto:a.auto??!1,quiet:!1,noProjectConfig:a.projectConfig===!1,autoBackgroundTimeout:(()=>{let d=parseInt(a.autoBackgroundTimeout??"120",10);return isNaN(d)||d===0?0:Math.max(30,Math.min(600,d))*1e3})(),noColors:!a.colors,noEmojis:!a.emojis,noAnimations:!a.animations,noStreaming:!a.streaming,showTokens:a.showTokens??!1,showCost:a.showCost??!1,outputFormat:a.outputFormat,tools:a.tools,excludeTools:a.excludeTools,maxTurns:xge(a.maxTurns),maxBudgetUsd:Mge(a.maxBudgetUsd),bare:a.bare??!1,appendSystemPrompt:a.appendSystemPrompt,appendSystemPromptFile:a.appendSystemPromptFile,continue:a.continue??!1,continueId:e.continueId,continueIdError:e.error,help:a.help??!1,version:a.version??!1},c;SA()&&(c=await gU()),(s==="chat"||l.interactive)&&(s="agent"),s==="query"&&!i.length&&!c&&(s="agent");let u;if(s==="query"&&i.length>0)u=i.join(" ");else if(s==="agent"){let d=[];o&&d.push(o),i.length>0&&d.push(...i),d.length>0&&(u=d.join(" "))}return{command:s,subcommand:o,args:i,flags:l,stdinContent:c,query:u}}function bU(t){let e=_U(t.command)??be.SERVER;switch(t.command){case"config":return Lge(t);case"mcp":return Fge(t);case"prompt":return $ge(t);case"stats":return Uge(t);case"history":return Bge(t);case"doctor":return{tier:be.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:be.LOCAL,handler:"goals",params:{}};case"install":return{tier:be.LOCAL,handler:"install",params:{}};case"chat":return{tier:be.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return zge(t);case"agent":return{tier:be.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:be.SERVER,handler:"loop",params:{}};case"telegram":return{tier:be.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:be.SERVER,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:be.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:be.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:be.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:be.LOCAL,handler:"login",params:{}};case"skill":return{tier:be.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:be.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:be.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:be.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:be.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:be.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Lge(t){let e=t.subcommand??t.args[0]??"show";return{tier:be.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function Fge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function $ge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Uge(t){let e=t.subcommand??t.args[0];return{tier:be.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Bge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var Gge=new Set(["--model","--host","--continue-chat","-c","--signature","--base"]);function zge(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],n=[];for(let s=0;s<e.length;s++){let o=e[s];if(Gge.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||n.push(o)}let r=n.join(" ");return{tier:be.SERVER,handler:"run",params:{operation:r}}}ct();wS();ni();ye();import{createInterface as cWe}from"readline";import{spawn as uWe}from"child_process";HS();Hr();lg();KD();Vc();ut();JD();var YHe={timeout:12e4,retries:3,retryDelay:1e3,handshakeTimeout:5e3};function WHe(t,e){let n=new URL(t),r=n.protocol==="https:"?"wss:":"ws:";if(e){if(!(n.protocol==="https:"||n.protocol==="wss:")&&!Wc(n.hostname))throw new Error(`Refusing to send the cloud key over an insecure (${n.protocol}) connection to ${n.hostname} \u2014 use https/wss.`);return{url:`${r}//${n.host}/v1/ws/execute`,headers:{Authorization:`Bearer ${e}`}}}return{url:`${r}//${n.host}/ws/execute`}}var no=class{options;ws=null;activityTimeout=null;mcpExecutor=null;constructor(e){this.options={...YHe,...e}}async initializeMCP(){if(!this.mcpExecutor){let{ClientMCPExecutor:e}=await Promise.resolve().then(()=>(xp(),Op)),{createHeadlessMcpGate:n}=await Promise.resolve().then(()=>(ui(),Rl));this.mcpExecutor=new e,this.mcpExecutor.setPermissionGate(n()),await this.mcpExecutor.initialize(),W(`MCP executor initialized with ${this.mcpExecutor.getConnectionCount()} connections`)}}async executeRequest(e,n){let r=WHe(this.options.url,this.options.cloudApiKey),s=e.auth_type==="oauth_bearer"?ei(e.llm_provider):void 0;if(!s)return this.executeWithLadder(r,e,n);let o,i={...n,onError:a=>{if(o===void 0&&a instanceof al&&XS(a.message)){o=a;return}n?.onError?.(a)}};try{return await this.executeWithLadder(r,e,i)}catch(a){if(o===void 0||a!==o)throw a;let l=await JS(s);if(l.status==="ok")return this.executeWithLadder(r,{...e,llm_api_key:l.accessToken},n);if(l.status==="dead"){let c=new al(o.code,s.pl04Line);throw n?.onError?.(c),c}throw n?.onError?.(o),o}}async executeWithLadder(e,n,r){let s=null;for(let o=0;o<this.options.retries;o++)try{return await this.executeWithRetry(e,n,r)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),W(`Attempt ${o+1} failed: ${s.message}`),s instanceof al||s.message.includes("Authentication"))throw s;if(this.options.cloudApiKey&&s instanceof Wd){let a=new URL(this.options.url);throw new Xo(Dc(a.hostname),"CLOUD_UNREACHABLE")}if(o<this.options.retries-1){let a=this.options.retryDelay*Math.pow(2,o);W(`Retrying in ${a}ms...`),await this.sleep(a)}}throw s??new il("Max retries exceeded")}async executeWithRetry(e,n,r){return new Promise((s,o)=>{let i=e.url;W(`Connecting to ${i}`);try{this.ws=new As(i,{handshakeTimeout:this.options.handshakeTimeout,...e.headers?{headers:e.headers}:{}})}catch{let p=new URL(this.options.url);o(new Wd(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 jh("WebSocket activity",this.options.timeout)))}),this.ws.on("open",()=>{W("WebSocket connected, sending request"),this.ws?.send(JSON.stringify({...n,protocol_version:2}))}),this.ws.on("message",p=>{this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new jh("WebSocket activity",this.options.timeout)))});let h;try{h=JSON.parse(p.toString())}catch(_){let E=p?String(p):"<undefined>";W(`Failed to parse message: ${E}`),d(new Error(`Failed to parse server message: ${_.message}`));return}let f=tb(h,N6);if(f.kind==="malformed"){let _=D6(h);d(_?new al("cloud_error",_):new il(`Malformed server frame: ${f.reason}`));return}if(f.kind==="unknown"){u||(u=!0,W(`Received an unrecognized frame type '${f.type}'; ignoring`));return}let g=f.frame;if(c===null&&g.protocol_version!==void 0&&(c=sb(g.protocol_version),c==="hard")){d(new il(ob(g.protocol_version)));return}if(nb.has(g.type)&&!rb(g)){d(new il(`Malformed ${g.type} payload`));return}this.handleMessage(g,r,_=>{a=!0,l=_,this.cleanup(),s(_)},_=>{a=!0,this.cleanup(),o(_)})}),this.ws.on("error",p=>{if(W(`WebSocket error: ${p.message}`),!a){a=!0,this.cleanup();let h=new URL(this.options.url);o(new Wd(h.hostname||"localhost",h.port||void 0))}}),this.ws.on("close",(p,h)=>{W(`WebSocket closed: ${p} ${h.toString()}`),a||(a=!0,this.cleanup(),l?s(l):o(new il(`Connection closed unexpectedly: ${p}`)))})})}handleMessage(e,n,r,s){switch(e.type){case"token":{let o=e;n?.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};n?.onComplete?.(l),r(l);break}case"error":{let o=e,i=new al(o.code,YS(o.message));n?.onError?.(i),s(i);break}case"mcp_query_tools":{W("Received mcp_query_tools request"),this.handleMCPQueryTools(e);break}case"mcp_tool_request":{W("Received mcp_tool_request"),this.handleMCPToolRequest(e);break}default:W(`Unknown message type: ${e.type}`)}}convertServerMetadata(e){let n=e.metadata||{},r,s;n.tokens?(r=n.tokens.input,s=n.tokens.output):(r=n.input_tokens,s=n.output_tokens);let o=n.cost??n.cost_usd,i=n.execution_time??n.total_time;return{function_name:e.function_name,tokens_in:r,tokens_out:s,cost:typeof o=="number"?o:void 0,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,execution_time:typeof i=="number"?i:void 0,task_id:typeof n.task_id=="string"?n.task_id:void 0,chat_url:typeof n.chat_url=="string"?n.chat_url:void 0}}async handleMCPQueryTools(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:r}=await Promise.resolve().then(()=>(xp(),Op)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(ui(),Rl));this.mcpExecutor=new r,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let n=await this.mcpExecutor.handleQueryTools(e);this.ws?.send(JSON.stringify(n))}catch(n){let r=n instanceof Error?n.message:String(n),s=n instanceof Error?n.stack:void 0;W(`Error handling mcp_query_tools: ${r}${s?`
|
|
3634
|
+
${e}`:e}var be;(function(t){t[t.LOCAL=1]="LOCAL",t[t.SERVER=2]="SERVER"})(be||(be={}));var bA={translate:"clean",shell:"clean",shell_generate:"clean",mcp:"standard",explain:"standard",code_generate:"standard",code_review:"standard",summarize:"standard",research:"standard",_default:"standard"};function Vo(t,e,n,r){return t.clean?"clean":t.thinking||t.verbose?"thinking":t.standard?"standard":e&&n?.[e]?n[e]:e&&bA[e]?bA[e]:r||bA._default}var m1=[{name:"config",tier:be.LOCAL},{name:"help",tier:be.LOCAL},{name:"version",tier:be.LOCAL},{name:"doctor",tier:be.LOCAL},{name:"mcp",tier:be.LOCAL},{name:"prompt",tier:be.LOCAL},{name:"stats",tier:be.LOCAL},{name:"history",tier:be.LOCAL},{name:"query",tier:be.SERVER},{name:"chat",tier:be.SERVER},{name:"run",tier:be.SERVER},{name:"agent",tier:be.SERVER},{name:"loop",tier:be.SERVER},{name:"telegram",tier:be.SERVER},{name:"sessions",tier:be.SERVER},{name:"goals",tier:be.LOCAL},{name:"install",tier:be.LOCAL},{name:"worktree",tier:be.LOCAL},{name:"soul",tier:be.LOCAL},{name:"skill",tier:be.LOCAL},{name:"plugin",tier:be.LOCAL},{name:"persona",tier:be.LOCAL},{name:"cloud",tier:be.LOCAL},{name:"login",tier:be.LOCAL},{name:"upgrade",tier:be.LOCAL}];function vge(t){let e=new Map;for(let n of t){if(!n.name)throw new Error("CLI command descriptor is missing a name");if(n.tier!==be.LOCAL&&n.tier!==be.SERVER)throw new Error(`CLI command "${n.name}" has an invalid tier: ${String(n.tier)}`);for(let r of[n.name,...n.aliases??[]]){if(e.has(r))throw new Error(`Duplicate CLI command name/alias: "${r}"`);e.set(r,n)}}return e}var kge=vge(m1);function _U(t){return kge.get(t)?.tier}var GXe=Object.fromEntries(m1.map(t=>[t.name,t.tier]));var yU=new Set(m1.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),Age="0.21.8",Ige=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","--continue","--signature","--no-signature","--no-project-config","--project-config","--local","-h","--help","-V","--version"]),TA=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","--signature"]);function Dge(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],s=r.indexOf("="),o=s>0?r.slice(0,s):r;if(Ige.has(o)){s===-1&&TA.has(o)&&n++;continue}e.push(r)}return e}var EU=/^[a-z0-9_]{2,40}$/i;function Nge(t){for(let e=2;e<t.length;e++){let n=t[e];if(n.startsWith("-")){!n.includes("=")&&TA.has(n)&&e++;continue}return n}}function Rge(t){for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith("-")){!n.includes("=")&&TA.has(n)&&e++;continue}return!0}return!1}function Oge(t){let e=Nge(t);if(e!==void 0&&e!=="agent"&&yU.has(e))return{argv:t};let n=[],r,s;for(let o=0;o<t.length;o++){let i=t[o];if(i==="--continue"){n.push(i);let a=t[o+1];r===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&EU.test(a)&&(Rge(t.slice(o+2))?s=`--continue ${a} \u2026: ambiguous \u2014 quote the text (aii --continue "${a} \u2026") to run it as a prompt, or run \`aii --continue ${a}\` alone to resume that session.`:(r=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);n.push("--continue"),EU.test(a)?r===void 0&&(r=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}n.push(i)}return{argv:n,continueId:r,error:s}}function xge(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 Mge(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 Pge(){let t=new hU;return t.name("aii").description("AI-powered CLI assistant").version(Age,"-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("--continue","Resume the most recent local session of this project (conversation + goal)").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("goals").description("List goals across this project's local sessions (pick one up with --continue <id>)").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, connect, status)").argument("[action]","Action: login, connect, status").allowUnknownOption().action(()=>{}),t.command("login").description("Sign in to an AI provider with your subscription (e.g., xAI SuperGrok)").argument("[args...]","Flags: --provider <name>, --status, --logout").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 SU(t){let e=Oge(t),n=e.argv,r=Pge();r.exitOverride(),r.configureOutput({writeErr:()=>{}});let s="query",o,i=[];try{r.parse(n),i=r.args;let d=r.args[0];d&&yU.has(d)&&(s=d,o=r.args[1],i=r.args.slice(2))}catch(d){d instanceof fU&&(d.code==="commander.version"||d.code==="commander.helpDisplayed")&&process.exit(0),i=Dge(n.slice(2))}let a=r.opts(),l={clean:a.clean??!1,standard:a.standard??!1,thinking:a.thinking??!1,verbose:a.verbose??!1,debug:a.debug??!1,model:a.model,host:a.host,local:a.local??!1,openrouterProvider:a.openrouterProvider,yes:a.yes??!1,offline:a.offline??!1,direct:a.direct??!1,interactive:a.interactive??!1,continueChat:a.continueChat,newChat:a.newChat??!1,auto:a.auto??!1,quiet:!1,noProjectConfig:a.projectConfig===!1,autoBackgroundTimeout:(()=>{let d=parseInt(a.autoBackgroundTimeout??"120",10);return isNaN(d)||d===0?0:Math.max(30,Math.min(600,d))*1e3})(),noColors:!a.colors,noEmojis:!a.emojis,noAnimations:!a.animations,noStreaming:!a.streaming,showTokens:a.showTokens??!1,showCost:a.showCost??!1,outputFormat:a.outputFormat,tools:a.tools,excludeTools:a.excludeTools,maxTurns:xge(a.maxTurns),maxBudgetUsd:Mge(a.maxBudgetUsd),bare:a.bare??!1,appendSystemPrompt:a.appendSystemPrompt,appendSystemPromptFile:a.appendSystemPromptFile,continue:a.continue??!1,continueId:e.continueId,continueIdError:e.error,help:a.help??!1,version:a.version??!1},c;SA()&&(c=await gU()),(s==="chat"||l.interactive)&&(s="agent"),s==="query"&&!i.length&&!c&&(s="agent");let u;if(s==="query"&&i.length>0)u=i.join(" ");else if(s==="agent"){let d=[];o&&d.push(o),i.length>0&&d.push(...i),d.length>0&&(u=d.join(" "))}return{command:s,subcommand:o,args:i,flags:l,stdinContent:c,query:u}}function bU(t){let e=_U(t.command)??be.SERVER;switch(t.command){case"config":return Lge(t);case"mcp":return Fge(t);case"prompt":return $ge(t);case"stats":return Uge(t);case"history":return Bge(t);case"doctor":return{tier:be.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:be.LOCAL,handler:"goals",params:{}};case"install":return{tier:be.LOCAL,handler:"install",params:{}};case"chat":return{tier:be.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return zge(t);case"agent":return{tier:be.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:be.SERVER,handler:"loop",params:{}};case"telegram":return{tier:be.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:be.SERVER,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:be.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:be.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:be.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:be.LOCAL,handler:"login",params:{}};case"skill":return{tier:be.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:be.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:be.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:be.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:be.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:be.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Lge(t){let e=t.subcommand??t.args[0]??"show";return{tier:be.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function Fge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function $ge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Uge(t){let e=t.subcommand??t.args[0];return{tier:be.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Bge(t){let e=t.subcommand??t.args[0]??"list";return{tier:be.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var Gge=new Set(["--model","--host","--continue-chat","-c","--signature","--base"]);function zge(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],n=[];for(let s=0;s<e.length;s++){let o=e[s];if(Gge.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||n.push(o)}let r=n.join(" ");return{tier:be.SERVER,handler:"run",params:{operation:r}}}ct();wS();ni();ye();import{createInterface as cWe}from"readline";import{spawn as uWe}from"child_process";HS();Hr();lg();KD();Vc();ut();JD();var YHe={timeout:12e4,retries:3,retryDelay:1e3,handshakeTimeout:5e3};function WHe(t,e){let n=new URL(t),r=n.protocol==="https:"?"wss:":"ws:";if(e){if(!(n.protocol==="https:"||n.protocol==="wss:")&&!Wc(n.hostname))throw new Error(`Refusing to send the cloud key over an insecure (${n.protocol}) connection to ${n.hostname} \u2014 use https/wss.`);return{url:`${r}//${n.host}/v1/ws/execute`,headers:{Authorization:`Bearer ${e}`}}}return{url:`${r}//${n.host}/ws/execute`}}var no=class{options;ws=null;activityTimeout=null;mcpExecutor=null;constructor(e){this.options={...YHe,...e}}async initializeMCP(){if(!this.mcpExecutor){let{ClientMCPExecutor:e}=await Promise.resolve().then(()=>(xp(),Op)),{createHeadlessMcpGate:n}=await Promise.resolve().then(()=>(ui(),Rl));this.mcpExecutor=new e,this.mcpExecutor.setPermissionGate(n()),await this.mcpExecutor.initialize(),W(`MCP executor initialized with ${this.mcpExecutor.getConnectionCount()} connections`)}}async executeRequest(e,n){let r=WHe(this.options.url,this.options.cloudApiKey),s=e.auth_type==="oauth_bearer"?ei(e.llm_provider):void 0;if(!s)return this.executeWithLadder(r,e,n);let o,i={...n,onError:a=>{if(o===void 0&&a instanceof al&&XS(a.message)){o=a;return}n?.onError?.(a)}};try{return await this.executeWithLadder(r,e,i)}catch(a){if(o===void 0||a!==o)throw a;let l=await JS(s);if(l.status==="ok")return this.executeWithLadder(r,{...e,llm_api_key:l.accessToken},n);if(l.status==="dead"){let c=new al(o.code,s.pl04Line);throw n?.onError?.(c),c}throw n?.onError?.(o),o}}async executeWithLadder(e,n,r){let s=null;for(let o=0;o<this.options.retries;o++)try{return await this.executeWithRetry(e,n,r)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),W(`Attempt ${o+1} failed: ${s.message}`),s instanceof al||s.message.includes("Authentication"))throw s;if(this.options.cloudApiKey&&s instanceof Wd){let a=new URL(this.options.url);throw new Xo(Dc(a.hostname),"CLOUD_UNREACHABLE")}if(o<this.options.retries-1){let a=this.options.retryDelay*Math.pow(2,o);W(`Retrying in ${a}ms...`),await this.sleep(a)}}throw s??new il("Max retries exceeded")}async executeWithRetry(e,n,r){return new Promise((s,o)=>{let i=e.url;W(`Connecting to ${i}`);try{this.ws=new As(i,{handshakeTimeout:this.options.handshakeTimeout,...e.headers?{headers:e.headers}:{}})}catch{let p=new URL(this.options.url);o(new Wd(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 jh("WebSocket activity",this.options.timeout)))}),this.ws.on("open",()=>{W("WebSocket connected, sending request"),this.ws?.send(JSON.stringify({...n,protocol_version:2}))}),this.ws.on("message",p=>{this.resetActivityTimeout(()=>{a||(this.cleanup(),o(new jh("WebSocket activity",this.options.timeout)))});let h;try{h=JSON.parse(p.toString())}catch(_){let E=p?String(p):"<undefined>";W(`Failed to parse message: ${E}`),d(new Error(`Failed to parse server message: ${_.message}`));return}let f=tb(h,N6);if(f.kind==="malformed"){let _=D6(h);d(_?new al("cloud_error",_):new il(`Malformed server frame: ${f.reason}`));return}if(f.kind==="unknown"){u||(u=!0,W(`Received an unrecognized frame type '${f.type}'; ignoring`));return}let g=f.frame;if(c===null&&g.protocol_version!==void 0&&(c=sb(g.protocol_version),c==="hard")){d(new il(ob(g.protocol_version)));return}if(nb.has(g.type)&&!rb(g)){d(new il(`Malformed ${g.type} payload`));return}this.handleMessage(g,r,_=>{a=!0,l=_,this.cleanup(),s(_)},_=>{a=!0,this.cleanup(),o(_)})}),this.ws.on("error",p=>{if(W(`WebSocket error: ${p.message}`),!a){a=!0,this.cleanup();let h=new URL(this.options.url);o(new Wd(h.hostname||"localhost",h.port||void 0))}}),this.ws.on("close",(p,h)=>{W(`WebSocket closed: ${p} ${h.toString()}`),a||(a=!0,this.cleanup(),l?s(l):o(new il(`Connection closed unexpectedly: ${p}`)))})})}handleMessage(e,n,r,s){switch(e.type){case"token":{let o=e;n?.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};n?.onComplete?.(l),r(l);break}case"error":{let o=e,i=new al(o.code,YS(o.message));n?.onError?.(i),s(i);break}case"mcp_query_tools":{W("Received mcp_query_tools request"),this.handleMCPQueryTools(e);break}case"mcp_tool_request":{W("Received mcp_tool_request"),this.handleMCPToolRequest(e);break}default:W(`Unknown message type: ${e.type}`)}}convertServerMetadata(e){let n=e.metadata||{},r,s;n.tokens?(r=n.tokens.input,s=n.tokens.output):(r=n.input_tokens,s=n.output_tokens);let o=n.cost??n.cost_usd,i=n.execution_time??n.total_time;return{function_name:e.function_name,tokens_in:r,tokens_out:s,cost:typeof o=="number"?o:void 0,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,execution_time:typeof i=="number"?i:void 0,task_id:typeof n.task_id=="string"?n.task_id:void 0,chat_url:typeof n.chat_url=="string"?n.chat_url:void 0}}async handleMCPQueryTools(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:r}=await Promise.resolve().then(()=>(xp(),Op)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(ui(),Rl));this.mcpExecutor=new r,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let n=await this.mcpExecutor.handleQueryTools(e);this.ws?.send(JSON.stringify(n))}catch(n){let r=n instanceof Error?n.message:String(n),s=n instanceof Error?n.stack:void 0;W(`Error handling mcp_query_tools: ${r}${s?`
|
|
3635
3635
|
${s}`:""}`),this.ws?.send(JSON.stringify({type:"mcp_query_tools_response",request_id:e.request_id||"unknown",success:!1,error:r,tools:[]}))}}async handleMCPToolRequest(e){try{if(!this.mcpExecutor){let{ClientMCPExecutor:r}=await Promise.resolve().then(()=>(xp(),Op)),{createHeadlessMcpGate:s}=await Promise.resolve().then(()=>(ui(),Rl));this.mcpExecutor=new r,this.mcpExecutor.setPermissionGate(s()),await this.mcpExecutor.initialize()}let n=await this.mcpExecutor.handleToolExecution(e);this.ws?.send(JSON.stringify(n))}catch(n){W(`Error handling mcp_tool_request: ${n}`),this.ws?.send(JSON.stringify({type:"mcp_tool_response",request_id:e.request_id||"unknown",success:!1,error:String(n)}))}}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){W(`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(n=>setTimeout(n,e))}};ye();import xv from"node:process";import rpe from"node:process";import Nv from"node:process";var VHe=(t,e,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let s=Object.getOwnPropertyDescriptor(t,n),o=Object.getOwnPropertyDescriptor(e,n);!KHe(s,o)&&r||Object.defineProperty(t,n,o)},KHe=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)},QHe=(t,e)=>{let n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)},XHe=(t,e)=>`/* Wrapped ${t}*/
|
|
3636
3636
|
${e}`,JHe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ZHe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),eje=(t,e,n)=>{let r=n===""?"":`with ${n.trim()}() `,s=XHe.bind(null,r,e.toString());Object.defineProperty(s,"name",ZHe);let{writable:o,enumerable:i,configurable:a}=JHe;Object.defineProperty(t,"toString",{value:s,writable:o,enumerable:i,configurable:a})};function P9(t,e,{ignoreNonConfigurable:n=!1}={}){let{name:r}=t;for(let s of Reflect.ownKeys(e))VHe(t,e,s,n);return QHe(t,e),eje(t,e,r),t}var Av=new WeakMap,Jde=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let n,r=0,s=t.displayName||t.name||"<anonymous>",o=function(...i){if(Av.set(o,++r),r===1)n=t.apply(this,i),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return P9(o,t),Av.set(o,r),o};Jde.callCount=t=>{if(!Av.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Av.get(t)};var Zde=Jde;var wd=[];wd.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&wd.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&wd.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Iv=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",L9=Symbol.for("signal-exit emitter"),F9=globalThis,tje=Object.defineProperty.bind(Object),$9=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(F9[L9])return F9[L9];tje(F9,L9,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,n){this.listeners[e].push(n)}removeListener(e,n){let r=this.listeners[e],s=r.indexOf(n);s!==-1&&(s===0&&r.length===1?r.length=0:r.splice(s,1))}emit(e,n,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let s=!1;for(let o of this.listeners[e])s=o(n,r)===!0||s;return e==="exit"&&(s=this.emit("afterExit",n,r)||s),s}},Dv=class{},nje=t=>({onExit(e,n){return t.onExit(e,n)},load(){return t.load()},unload(){return t.unload()}}),U9=class extends Dv{onExit(){return()=>{}}load(){}unload(){}},B9=class extends Dv{#i=G9.platform==="win32"?"SIGINT":"SIGHUP";#n=new $9;#e;#s;#p;#t={};#o=!1;constructor(e){super(),this.#e=e,this.#t={};for(let n of wd)this.#t[n]=()=>{let r=this.#e.listeners(n),{count:s}=this.#n,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(s+=o.__signal_exit_emitter__.count),r.length===s){this.unload();let i=this.#n.emit("exit",null,n),a=n==="SIGHUP"?this.#i:n;i||e.kill(e.pid,a)}};this.#p=e.reallyExit,this.#s=e.emit}onExit(e,n){if(!Iv(this.#e))return()=>{};this.#o===!1&&this.load();let r=n?.alwaysLast?"afterExit":"exit";return this.#n.on(r,e),()=>{this.#n.removeListener(r,e),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#n.count+=1;for(let e of wd)try{let n=this.#t[e];n&&this.#e.on(e,n)}catch{}this.#e.emit=(e,...n)=>this.#m(e,...n),this.#e.reallyExit=e=>this.#r(e)}}unload(){this.#o&&(this.#o=!1,wd.forEach(e=>{let n=this.#t[e];if(!n)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,n)}catch{}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#p,this.#n.count-=1)}#r(e){return Iv(this.#e)?(this.#e.exitCode=e||0,this.#n.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...n){let r=this.#s;if(e==="exit"&&Iv(this.#e)){typeof n[0]=="number"&&(this.#e.exitCode=n[0]);let s=r.call(this.#e,e,...n);return this.#n.emit("exit",this.#e.exitCode,null),s}else return r.call(this.#e,e,...n)}},G9=globalThis.process,{onExit:epe,load:Owt,unload:xwt}=nje(Iv(G9)?new B9(G9):new U9);var tpe=Nv.stderr.isTTY?Nv.stderr:Nv.stdout.isTTY?Nv.stdout:void 0,rje=tpe?Zde(()=>{epe(()=>{tpe.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},npe=rje;var Rv=!1,Lf={};Lf.show=(t=rpe.stderr)=>{t.isTTY&&(Rv=!1,t.write("\x1B[?25h"))};Lf.hide=(t=rpe.stderr)=>{t.isTTY&&(npe(),Rv=!0,t.write("\x1B[?25l"))};Lf.toggle=(t,e)=>{t!==void 0&&(Rv=t),Rv?Lf.show(e):Lf.hide(e)};var z9=Lf;var ky=Nt(q9(),1);ye();import Go from"node:process";function H9(){return Go.platform!=="win32"?Go.env.TERM!=="linux":!!Go.env.CI||!!Go.env.WT_SESSION||!!Go.env.TERMINUS_SUBLIME||Go.env.ConEmuTask==="{cmd::Cmder}"||Go.env.TERM_PROGRAM==="Terminus-Sublime"||Go.env.TERM_PROGRAM==="vscode"||Go.env.TERM==="xterm-256color"||Go.env.TERM==="alacritty"||Go.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var oje={info:m.blue("\u2139"),success:m.green("\u2714"),warning:m.yellow("\u26A0"),error:m.red("\u2716")},ije={info:m.blue("i"),success:m.green("\u221A"),warning:m.yellow("\u203C"),error:m.red("\xD7")},aje=H9()?oje:ije,vy=aje;lb();var lje=eu();function j9(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(lje,"")}lN();function Y9({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import ape from"node:process";function W9(){let{env:t}=ape,{TERM:e,TERM_PROGRAM:n}=t;return ape.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}import Li from"node:process";var cje=3,V9=class{#i=0;start(){this.#i++,this.#i===1&&this.#n()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#n(){Li.platform==="win32"||!Li.stdin.isTTY||(Li.stdin.setRawMode(!0),Li.stdin.on("data",this.#s),Li.stdin.resume())}#e(){Li.stdin.isTTY&&(Li.stdin.off("data",this.#s),Li.stdin.pause(),Li.stdin.setRawMode(!1))}#s(e){e[0]===cje&&Li.emit("SIGINT")}},uje=new V9,K9=uje;var dje=Nt(q9(),1),Q9=class{#i=0;#n=!1;#e=0;#s=-1;#p=0;#t;#o;#r;#m;#h;#c;#u;#d;#g;#a;#l;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:xv.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#h=this.#t.interval,this.#r=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Y9({stream:this.#r}),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,xv.env.NODE_ENV==="test"&&(this._stream=this.#r,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(n){this.#i=n}}),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(!W9())this.#o=ky.default.line;else if(e===void 0)this.#o=ky.default.dots;else if(e!=="default"&&ky.default[e])this.#o=ky.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,n=" "){return typeof e=="string"&&e!==""?e+n:typeof e=="function"?e()+n:""}#E(e=this.#l,n=" "){return typeof e=="string"&&e!==""?n+e:typeof e=="function"?n+e():""}#f(){let e=this.#r.columns??80,n=this.#_(this.#a,"-"),r=this.#E(this.#l,"-"),s=" ".repeat(this.#d)+n+"--"+this.#g+"--"+r;this.#e=0;for(let o of j9(s).split(`
|
|
3637
3637
|
`))this.#e+=Math.max(1,Math.ceil(fp(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:n}=this.#o,r=n[this.#s];this.color&&(r=m[this.color](r));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+r+o+i}clear(){if(!this.#c||!this.#r.isTTY)return this;this.#r.cursorTo(0);for(let e=0;e<this.#i;e++)e>0&&this.#r.moveCursor(0,-1),this.#r.clearLine(1);return(this.#d||this.lastIndent!==this.#d)&&this.#r.cursorTo(this.#d),this.lastIndent=this.#d,this.#i=0,this}render(){return this.#u?this:(this.clear(),this.#r.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&&z9.hide(this.#r),this.#t.discardStdin&&xv.stdin.isTTY&&(this.#n=!0,K9.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#r.write(`- ${this.text}
|
|
@@ -3642,7 +3642,7 @@ ${e}`,JHe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ZHe=Obj
|
|
|
3642
3642
|
`+this.color(s,m.dim)}formatError(e){let n=[];return n.push(this.color(`${this.emoji("\u274C ")}${e.message}`,m.red)),e.suggestions&&e.suggestions.length>0&&(n.push(""),n.push(this.color(`${this.emoji("\u{1F4A1} ")}Solutions:`,m.yellow)),e.suggestions.forEach((r,s)=>{n.push(this.color(` ${s+1}. ${r}`,m.gray))})),n.join(`
|
|
3643
3643
|
`)}formatConfig(e){let n=[];n.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,$.model)),n.push(`- Config file: ${e.configFile}`),n.push(`- Storage path: ${e.storagePath}`),e.apiUrl&&n.push(`- Aii Server: ${e.apiUrl}`);let r=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(n.push(`- LLM provider: ${e.provider} (${s}) - ${r}`),e.webSearch){let o=e.webSearch.enabled?this.color("\u2713",m.green):this.color("\u2717",m.red);n.push(`- Web search: ${e.webSearch.provider??"none"} - ${o}`)}return e.issues&&e.issues.length>0&&n.push(`- Configuration issues: ${e.issues.length}`),n.join(`
|
|
3644
3644
|
`)}formatHealthCheck(e,n){let r=[],s=n?`Aii Doctor v${n}`:"Aii Doctor";r.push(this.color(s,$.model)),r.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 h=this.color(d,p),f=l.message?` (${l.message})`:"";r.push(` ${l.name} ${this.color(u,m.gray)} ${h}${f}`)}let i=e.filter(l=>l.status==="error").length,a=e.filter(l=>l.status==="warn").length;return r.push(""),i>0?r.push(` ${this.color(`${i} check${i>1?"s":""} failed.`,m.red)}`):a>0?r.push(` ${this.color("All checks passed with warnings.",m.yellow)}`):r.push(` ${this.color("All checks passed.",m.green)}`),r.join(`
|
|
3645
|
-
`)}};function as(t={}){return new e$(t)}Hr();zo();ye();import*as mpe from"readline";Hr();Dr();zo();mS();import*as ro from"fs";import*as Pv from"path";import*as lpe from"os";var Ay=Pv.join(lpe.homedir(),".aii","conversations"),n$=Pv.join(Ay,"current.json");function Lv(){ro.existsSync(Ay)||ro.mkdirSync(Ay,{recursive:!0,mode:448});try{ro.chmodSync(Ay,448)}catch{}}function fje(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hje(t){let n=t.trim().replace(/\s+/g," ");return n.length>50&&(n=n.substring(0,50).trim()+"..."),n}function cpe(t){return Pv.join(Ay,`${t}.json`)}function upe(){Lv();try{if(ro.existsSync(n$)){let t=ro.readFileSync(n$,"utf-8"),e=JSON.parse(t),n=cpe(e.id);if(ro.existsSync(n)){let r=ro.readFileSync(n,"utf-8");return JSON.parse(r)}}}catch{}return dpe()}function dpe(){Lv();let t={id:fje(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Iy(t),gje(t.id),t}function Iy(t){if(Lv(),t.title==="New Conversation"&&t.messages.length>0){let n=t.messages.find(r=>r.role==="user");n&&(t.title=hje(n.content))}t.updatedAt=Date.now();let e=cpe(t.id);Nc(e,JSON.stringify(t,null,2))}function gje(t){Lv(),Nc(n$,JSON.stringify({id:t}))}function ppe(){return dpe()}Ju();var _je="0.21.
|
|
3645
|
+
`)}};function as(t={}){return new e$(t)}Hr();zo();ye();import*as mpe from"readline";Hr();Dr();zo();mS();import*as ro from"fs";import*as Pv from"path";import*as lpe from"os";var Ay=Pv.join(lpe.homedir(),".aii","conversations"),n$=Pv.join(Ay,"current.json");function Lv(){ro.existsSync(Ay)||ro.mkdirSync(Ay,{recursive:!0,mode:448});try{ro.chmodSync(Ay,448)}catch{}}function fje(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hje(t){let n=t.trim().replace(/\s+/g," ");return n.length>50&&(n=n.substring(0,50).trim()+"..."),n}function cpe(t){return Pv.join(Ay,`${t}.json`)}function upe(){Lv();try{if(ro.existsSync(n$)){let t=ro.readFileSync(n$,"utf-8"),e=JSON.parse(t),n=cpe(e.id);if(ro.existsSync(n)){let r=ro.readFileSync(n,"utf-8");return JSON.parse(r)}}}catch{}return dpe()}function dpe(){Lv();let t={id:fje(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Iy(t),gje(t.id),t}function Iy(t){if(Lv(),t.title==="New Conversation"&&t.messages.length>0){let n=t.messages.find(r=>r.role==="user");n&&(t.title=hje(n.content))}t.updatedAt=Date.now();let e=cpe(t.id);Nc(e,JSON.stringify(t,null,2))}function gje(t){Lv(),Nc(n$,JSON.stringify({id:t}))}function ppe(){return dpe()}Ju();var _je="0.21.8",r$=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,n){this.parsed=e,this.configManager=n,this.conversation=upe(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=as({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()}),Iy(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(`
|
|
3646
3646
|
\u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(m.red(`
|
|
3647
3647
|
\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(),Iy(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,n)=>{let r=mpe.createInterface({input:process.stdin,output:process.stdout}),s=[],o=!1,i=()=>{o=!0,r.close()},a=l=>{r.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(`
|
|
3648
3648
|
`).trim()))})};r.on("SIGINT",()=>{i(),n(new Error("INTERRUPTED"))}),r.on("close",()=>{o||n(new Error("EXIT"))}),a("> ")})}async handleSpecialCommands(e){let n=e.trim().toLowerCase();if(n.startsWith("/"))n=n.slice(1);else return!1;switch(n){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: /${n}. Type /help for available commands.`)),console.log(""),!0}}async processWithContext(e){let n=await this.configManager.load(),r=this.configManager.validate();if(!r.valid)throw new rr(r.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",i=In(this.parsed.flags.model??""),a=Xn(i||void 0,n.llm.provider),l=Dn(i||n.llm.model,a);this.effectiveProvider=a;let c=this.parsed.flags.host?`http://${this.parsed.flags.host}`:n.api.url,u=await gt(a,this.configManager,{serverBaseUrl:c,serverApiKey:o}),d=u?.key;if(!d)throw new Jt(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let p=Fi(!this.parsed.flags.noAnimations);p.start("");let h=$i({spinner:p,enabled:!this.parsed.flags.noStreaming}),f=this.conversation.messages.slice(-21,-1).map(T=>({role:T.role,content:T.content})),g={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:d,provider_api_key:d,...u?.authType?{auth_type:u.authType}:{},...u?.accountId?{account_id:u.accountId}:{},client_type:"cli",offline:this.parsed.flags.offline,conversation_history:f.length>0?f:void 0,soul:yr.getInstance().getSoulName()},_=this.parsed.flags.host?`http://${this.parsed.flags.host}`:n.api.url,E=new no({url:_}),y="",S=!1;try{let T=await E.executeRequest(g,{onToken:v=>{y+=v,S=!0,h.onToken(v)}});h.flush();let C=T.result||y;!S&&C&&console.log(C),console.log(""),T.metadata&&this.displayExecutionSummary(T.metadata),C&&(this.conversation.messages.push({role:"assistant",content:C,timestamp:Date.now()}),Iy(this.conversation))}catch(T){throw p.stop(!0),T}finally{E.disconnect()}}displayExecutionSummary(e){let n=e.cost||0,r=e.tokens_in||0,s=e.tokens_out||0,o=r+s;this.stats.cumulativeTokens+=o,this.stats.cumulativeCost+=n;let i=e.provider,a=!i;console.log(this.formatter.formatExecutionSummary({provider:i||this.effectiveProvider,providerInferred:a,model:e.model,tokens_in:r,tokens_out:s,cost:n,execution_time:e.execution_time})),console.log("")}clearConversation(){this.conversation=ppe(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
|
|
@@ -4007,18 +4007,18 @@ Additional rules:
|
|
|
4007
4007
|
- IMPORTANT: If the input is a conversational request that mentions "this project", "the codebase", "explore", or asks to work with local files, set should_invoke=false and needs_agent=true \u2014 route to the agent, not a skill
|
|
4008
4008
|
- Only invoke skills when the user's intent is clearly to run a specific workflow (e.g., "brainstorm the auth design" vs "explore this project to figure out the API design")`}parseResponse(e){let n=e.match(/\{[\s\S]*\}/);if(!n)return{shouldInvoke:!1,confidence:0};try{let r=JSON.parse(n[0]);return{shouldInvoke:r.should_invoke===!0,skillName:r.skill_name??void 0,skillArgs:r.skill_args??"",confidence:typeof r.confidence=="number"?r.confidence:0,needsAgent:r.needs_agent??!1}}catch{return{shouldInvoke:!1,confidence:0}}}timeout(){return new Promise((e,n)=>{setTimeout(()=>n(new Error("Classification timed out")),this.timeoutMs).unref()})}};mt();ye();Xf();Uy();Eg();import{execSync as sYe}from"child_process";function T$(t,e){return!t||!e?!1:t.includes(e)}function w$(t,e,n){let r=Date.now();try{return{passed:!0,stdout:sYe(t,{cwd:e,timeout:n,encoding:"utf-8",stdio:["pipe","pipe","pipe"],env:{...process.env}})??"",stderr:"",exitCode:0,durationMs:Date.now()-r}}catch(s){let o=s;return{passed:!1,stdout:o.stdout??"",stderr:o.stderr??o.message??"",exitCode:o.status??1,durationMs:Date.now()-r}}}function Hpe(t){let e=t?.target??process,n=t?.exit??(i=>process.exit(i)),r=t?.restoreTerminal??(()=>{try{process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h")}catch{}}),s=()=>{r(),n(130)};e.on("SIGINT",s);let o=!1;return()=>{o||(o=!0,e.removeListener("SIGINT",s))}}_n();ye();Xf();_n();im();function C$(){return Math.min((process.stdout.columns||80)-2,76)}function oYe(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function jpe(t,e){return t+" ".repeat(Math.max(0,e-oYe(t)))}function Jn(t,e){let n=e-4;return $.model("\u2502")+" "+jpe(t,n)+" "+$.model("\u2502")}function Ec(t,e,n,r,s){let o=s-4,i=Math.floor(o/2),a=m.dim(t.padEnd(13))+e,l=m.dim(n.padEnd(13))+r;return Jn(jpe(a,i)+l,s)}function Ad(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}function yc(t){let e=Math.floor(t/1e3),n=Math.floor(e/31536e3);e%=31536e3;let r=Math.floor(e/86400);e%=86400;let s=Math.floor(e/3600);e%=3600;let o=Math.floor(e/60);e%=60;let i=[];return n>0&&i.push(`${n}y`),r>0&&i.push(`${r}d`),s>0&&i.push(`${s}h`),o>0&&i.push(`${o}m`),(e>0||i.length===0)&&i.push(`${e}s`),i.join(" ")}function Ype(t){return{completion_promise:"Completion promise detected",verification_passed:"Verification command passed",both_passed:"Promise + verification passed",max_iterations:"Max iterations reached",budget_exceeded:"Estimated cost budget exceeded",input_tokens_exceeded:"Input token limit reached",output_tokens_exceeded:"Output token limit reached",duration_exceeded:"Time limit reached",graceful_stop:"Stopped gracefully by user",user_abort:"Aborted by user",error:"Error occurred",stagnation:"Stagnation detected"}[t]??t}function v$(t,e=console.log,n){let r=C$(),s=n?" Loop (resumed) ":" Loop ",o=Math.max(0,r-3-s.length);if(e($.model("\u250C\u2500")+m.white.bold(s)+$.model("\u2500".repeat(o)+"\u2510")),t.prompt){let u=r-12,d=t.prompt.length>u?t.prompt.slice(0,u-3)+"...":t.prompt;e(Jn(`Task: ${d}`,r))}else e(Jn(m.dim("Mode: AGENTS.md-driven activity"),r));if(n){let u=n.maxIterations>0?`iteration ${n.iteration+1}/${n.maxIterations}`:`iteration ${n.iteration+1}`,d=n.budgetUsd>0?` \xB7 $${n.spentUsd.toFixed(2)} of $${n.budgetUsd} already spent`:n.spentUsd>0?` \xB7 ~$${n.spentUsd.toFixed(2)} already spent`:"";if(e(Jn(`Continuing at ${u}${d}`,r)),t.verifyCommand){let p=r-14,h=t.verifyCommand.length>p?t.verifyCommand.slice(0,p-1)+"\u2026":t.verifyCommand;e(Jn(m.dim(`verify: ${h}`),r))}}let i=[];t.maxIterations>0&&i.push(`max ${t.maxIterations} iterations`),t.durationSeconds>0&&i.push(`time ${yc(t.durationSeconds*1e3)}`),t.budgetUsd>0&&i.push(`budget ~$${t.budgetUsd}`),t.inputTokensLimit>0&&i.push(`input limit ${Ad(t.inputTokensLimit)} tokens`),t.outputTokensLimit>0&&i.push(`output limit ${Ad(t.outputTokensLimit)} tokens`),i.length>0?e(Jn(`Limits: ${i.join(", ")}`,r)):e(Jn(m.dim("Limits: none (hard cap: 1000 iterations)"),r)),Qf(t)&&(t.verifyCommand&&e(Jn(`Verify: ${t.verifyCommand}`,r)),t.completionPromise&&e(Jn(`Promise: "${t.completionPromise}"`,r)));let a="Type to queue \xB7 /note injects now \xB7 /pause /stop /stats \xB7 Esc cancels",l=r-4,c=a.length>l?a.slice(0,Math.max(0,l-1))+"\u2026":a;e(Jn(m.dim(c),r)),e($.model("\u2514"+"\u2500".repeat(r-2)+"\u2518"))}function Wpe(t,e,n,r=console.log){let s=C$(),o=" Loop Stats ",i=Math.max(0,s-3-o.length),a=Date.now()-t.startTime,l=yc(a),c=t.config.maxIterations>0?`${t.iteration}/${t.config.maxIterations}`:`${t.iteration}`,u=tt(),d=u.loopTotalInputTokens,p=u.loopTotalOutputTokens,h=u.loopCost,f=u.loopToolCalls;if(r($.model("\u250C\u2500")+m.white.bold(o)+$.model("\u2500".repeat(i)+"\u2510")),r(Ec("Iteration:",c,"Wall clock:",l,s)),t.totalPauseMs>0||t.pauseStartTime){let g=t.pauseStartTime?Date.now()-t.pauseStartTime:0,_=t.totalPauseMs+g,E=a-_;r(Ec("Active:",yc(E),"Paused:",yc(_),s))}r(Ec("Cost:",`~$${h.toFixed(2)}`,"Tokens:",`${Ad(d)} in / ${Ad(p)} out`,s)),r(Ec("Tool calls:",`${f}`,"Failures:",`${n}`,s)),r($.model("\u2514"+"\u2500".repeat(s-2)+"\u2518"))}function Vv(t,e,n=console.log){switch(e){case"running_verify":n(""),n(m.dim(` \u25CB Verifying: ${t.config.verifyCommand}`));break;case"verify_passed":n(m.green(" \u2713 Verification passed"));break;case"verify_failed":if(n(m.red(" \u2717 Verification failed")),t.lastVerifyOutput){let r=(t.lastVerifyOutput.stdout+t.lastVerifyOutput.stderr).trim();r&&r.split(`
|
|
4009
4009
|
`).slice(-5).forEach(o=>n(m.dim(` ${o}`)))}break}}function k$(t,e=console.log){e(m.yellow(` \u26A0 No tool calls for ${t} consecutive iterations`))}function Kv(t,e,n=console.log,r){let s=C$();if(n(""),n($.model("\u250C"+"\u2500".repeat(s-2)+"\u2510")),t.success?n(Jn(m.green.bold("\u2713 Loop Complete"),s)):n(Jn(m.yellow.bold("\u26A0 Loop Stopped"),s)),n($.model("\u251C"+"\u2500".repeat(s-2)+"\u2524")),e.prompt){let l=s-12,c=e.prompt.length>l?e.prompt.slice(0,l-3)+"...":e.prompt;n(Jn(m.dim("Task: ")+c,s)),n(Jn("",s))}process.env.AII_LOOP_DEBUG&&(console.error("[LOOP-DEBUG] displayLoopSummary received:"),console.error(` result.totalCost=${t.totalCost}`),console.error(` result.totalInputTokens=${t.totalInputTokens}`),console.error(` result.totalOutputTokens=${t.totalOutputTokens}`));let o=e.maxIterations>0?`${t.iterations}/${e.maxIterations}`:`${t.iterations}`;n(Ec("Iteration:",o,"Wall clock:",yc(t.durationMs),s)),t.totalPauseMs&&t.totalPauseMs>0&&n(Ec("Active:",yc(t.activeExecutionMs),"Paused:",yc(t.totalPauseMs),s)),n(Ec("Cost:",`~$${t.totalCost.toFixed(2)}`,"Tokens:",`${Ad(t.totalInputTokens)} in / ${Ad(t.totalOutputTokens)} out`,s)),n(Ec("Tool calls:",`${t.totalToolCalls}`,"Failures:",`${t.consecutiveFailures??0}`,s));let i=Ype(t.exitReason),a=t.success?m.green:m.yellow;if(n(Jn(m.dim("Result:".padEnd(13))+a(i),s)),r){n(Jn("",s));let l=s-12,c=r.length>l?r.slice(0,Math.max(0,l-1))+"\u2026":r;n(Jn(m.green("Resume: ")+c,s))}n($.model("\u2514"+"\u2500".repeat(s-2)+"\u2518")),n("")}function Vpe(t){return async(e,n)=>{if(t.isPauseRequested()){e.controller.suspendStallDetection(),t.onPauseEntered();let r=await t.waitForResume();if(e.controller.resumeStallDetection(),t.onPauseExited(),r==="aborted")return{success:!1,output:"",error:"Loop aborted during pause"}}return n()}}function Qv(t){let e=!1;return async(n,r)=>{e&&(e=!1,t.onNoteProcessed?.());let s=t.getPendingNote();return s?(t.onNoteInjected(),e=!0,{success:!0,output:["[USER NOTE]",s,"[/USER NOTE]","","The user has sent a note. Please acknowledge this note and adjust your current approach accordingly.",`The tool "${n.toolName}" was not executed \u2014 address the user's note first, then decide whether to proceed with the original tool call or take a different action.`].join(`
|
|
4010
|
-
`)}):r()}}im();SP();eh();Si();Vl();la();var fYe=["WebSocket disconnected unexpectedly","ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","socket hang up","WebSocket was closed","WebSocket error","StallTimeout","No response for","fetch failed","Failed to fetch","AbnormalDisconnect","unexpected EOF","connection reset by peer","LLM call failed","HTTP request failed","server error","502 Bad Gateway","503 Service Unavailable","504 Gateway Timeout","overloaded"],hYe=["status 401","status 403","authentication_error","Authentication Fails","api key","API key","Invalid API key","invalid_api_key","Unauthorized","Forbidden","model not found","invalid model","does not exist"],gYe=["maximum context length","context_length_exceeded","reduce the length of the messages","maximum number of tokens","token limit exceeded","context window"],Id={THRESHOLD:3,INITIAL_WAIT_MS:12e4,MAX_WAIT_MS:9e5,MULTIPLIER:2,POLL_INTERVAL_MS:5e3};function th(t){return t instanceof Error?t.message:typeof t=="object"&&t!==null&&"message"in t?String(t.message):typeof t=="string"?t:JSON.stringify(t)}function tme(t){let e=th(t);if(typeof t=="object"&&t!==null&&"retryable"in t&&t.retryable===!0)return!0;if(hYe.some(r=>e.includes(r)))return!1;let n=typeof t=="object"&&t!==null&&"name"in t?String(t.name):"";return fYe.some(r=>e.includes(r)||n.includes(r))}function nme(t){let e=th(t).toLowerCase();return gYe.some(n=>e.includes(n.toLowerCase()))}function ot(t){(process.env.AII_DEBUG||process.env.AII_LOOP_DEBUG)&&console.error(t)}var Dd=class{config;agentController;session;state;effectiveMaxIterations;printer;durationExpired=!1;record;loopsDir;isResumed=!1;startIteration=1;initialTokensIn;initialTokensOut;initialCost;consecutiveFailedIterations=0;circuitState="closed";circuitWaitMs=Id.INITIAL_WAIT_MS;processingQueue=!1;pausePromise=null;pauseResolver=null;pauseAutoResumeTimeout=null;pauseToastId=null;stoppingToastId=null;pendingNote=null;noteToastId=null;uiRefs=null;constructor(e,n,r,s,o){this.config=e,this.agentController=n,this.session=r,this.printer=s??console.log,this.effectiveMaxIterations=e.maxIterations>0?Math.min(e.maxIterations,hn.HARD_MAX_ITERATIONS):hn.HARD_MAX_ITERATIONS,process.env.AII_DEBUG&&console.error(`[loop] config.maxIterations=${e.maxIterations}, effectiveMaxIterations=${this.effectiveMaxIterations}`),this.initialTokensIn=r.stats.tokensIn,this.initialTokensOut=r.stats.tokensOut,this.initialCost=r.stats.totalCost,this.loopsDir=D$(r.projectPath);let i=o?.carry;if(this.state={iteration:i?.iteration??0,config:this.config,totalCost:i?.totalCost??0,totalInputTokens:i?.totalInputTokens??0,totalOutputTokens:i?.totalOutputTokens??0,totalToolCalls:i?.totalToolCalls??0,startTime:Date.now()-(i?.elapsedWallMs??0),phase:"running",pauseUntil:null,totalPauseMs:i?.totalPauseMs??0,pauseStartTime:null,lastAgentOutput:"",iterationCosts:i?[...i.iterationCosts]:[],iterationTokens:i?[...i.iterationTokens]:[],lastIterationHadToolCalls:!0,consecutiveNoToolCallIterations:i?.consecutiveNoToolCallIterations??0,capacityWarningsIssued:new Set(i?.capacityWarningsIssued??[]),userNotes:i?[...i.userNotes]:[]},i?.lastVerifyOutput&&(this.state.lastVerifyOutput={...i.lastVerifyOutput,durationMs:0}),this.startIteration=(i?.iteration??0)+1,o){let a=o.config;e.budgetUsd!==a.budgetUsd&&this.state.capacityWarningsIssued.delete("budget"),e.durationSeconds!==a.durationSeconds&&this.state.capacityWarningsIssued.delete("duration"),e.inputTokensLimit!==a.inputTokensLimit&&this.state.capacityWarningsIssued.delete("input_tokens"),e.outputTokensLimit!==a.outputTokensLimit&&this.state.capacityWarningsIssued.delete("output_tokens"),this.record={...o,config:e,pid:process.pid,status:"running",updatedAt:new Date().toISOString()},this.isResumed=!0}else this.record={version:1,id:Xv(),status:"running",pid:process.pid,projectRoot:Zf(r.projectPath),cwd:r.projectPath,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),config:e,carry:this.buildCarry()};process.env.AII_LOOP_DEBUG&&(console.error("[LOOP-DEBUG] LoopController initialized with session stats:"),console.error(` initial: tokensIn=${this.initialTokensIn}, tokensOut=${this.initialTokensOut}, totalCost=${this.initialCost}`))}buildCarry(){let e=this.state.lastVerifyOutput;return{iteration:this.state.iteration,totalCost:this.state.totalCost,totalInputTokens:this.state.totalInputTokens,totalOutputTokens:this.state.totalOutputTokens,totalToolCalls:this.state.totalToolCalls,iterationCosts:[...this.state.iterationCosts],iterationTokens:[...this.state.iterationTokens],consecutiveNoToolCallIterations:this.state.consecutiveNoToolCallIterations,capacityWarningsIssued:[...this.state.capacityWarningsIssued],userNotes:[...this.state.userNotes],lastVerifyOutput:e?{passed:e.passed,exitCode:e.exitCode,stdout:e.stdout.slice(-4096),stderr:e.stderr.slice(-4096)}:null,elapsedWallMs:Date.now()-this.state.startTime,totalPauseMs:this.state.totalPauseMs}}checkpoint(e,n){this.record={...this.record,status:e,exitReason:n??this.record.exitReason,pid:e==="running"?process.pid:void 0,updatedAt:new Date().toISOString(),carry:this.buildCarry()},x$(this.record,this.loopsDir)}getLoopRecordId(){return this.record.id}getPhase(){return this.state.phase}transition(e){let n=this.state.phase;({running:["paused","stopping","aborted"],paused:["running","stopping","aborted"],stopping:["aborted"],aborted:[]})[n].includes(e)&&(this.state.phase=e)}finalizePause(){this.state.pauseStartTime&&(this.state.totalPauseMs+=Date.now()-this.state.pauseStartTime,this.state.pauseStartTime=null),this.state.pauseUntil=null,this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null)}resolvePausePromise(){this.pauseResolver&&(this.pauseResolver(),this.pauseResolver=null,this.pausePromise=null)}enterPause(e){e?this.state.pauseUntil=Date.now()+e*1e3:this.state.pauseUntil=null,this.pausePromise=new Promise(n=>{this.pauseResolver=n}),this.transition("paused"),e&&(this.pauseAutoResumeTimeout=setTimeout(()=>{this.resumeFromPause("auto")},e*1e3)),tt().setLoopPaused(!0,this.state.pauseUntil)}resumeFromPause(e){this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null),this.state.pauseStartTime&&(this.state.totalPauseMs+=Date.now()-this.state.pauseStartTime,this.state.pauseStartTime=null),this.state.pauseUntil=null,this.transition("running"),tt().setLoopPaused(!1,null),this.pauseToastId!==null&&(He().clearToast(this.pauseToastId),this.pauseToastId=null);let n=e==="auto"?"\u25C6 Loop resumed (auto)":"\u25C6 Loop resumed";this.printer($.success(n),{toast:!0}),this.resolvePausePromise()}updatePause(e){this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null),e?(this.state.pauseUntil=Date.now()+e*1e3,this.pauseAutoResumeTimeout=setTimeout(()=>{this.resumeFromPause("auto")},e*1e3)):this.state.pauseUntil=null,tt().setLoopPaused(!0,this.state.pauseUntil)}isPauseRequested(){return this.getPhase()==="paused"}async waitForResume(){let n=null;return n=setInterval(()=>{try{this.agentController.ping()}catch{}},3e4),this.pausePromise&&await this.pausePromise,n&&clearInterval(n),this.getPhase()==="aborted"||this.getPhase()==="stopping"?"aborted":"resumed"}onPauseEntered(){this.state.pauseStartTime=Date.now(),tt().setThinking(!1),tt().setStreaming(!1),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.state.pauseUntil?(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused"),{toast:!0,persistent:!0,expiresAt:this.state.pauseUntil})):(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused \u2014 type /resume to continue"),{toast:!0,persistent:!0}))}onPauseExited(){tt().setThinking(!0)}clearStoppingToast(){this.stoppingToastId!==null&&(He().clearToast(this.stoppingToastId),this.stoppingToastId=null)}getPendingNote(){return this.pendingNote}onNoteInjected(){let e=this.pendingNote;this.pendingNote=null,this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),e&&this.echoUserInput(e)}echoUserInput(e){if(this.uiRefs?.isUIInitialized()){try{this.uiRefs.getUI().displayUserMessage(e,{preserveStream:!0})}catch(n){ot(`[loop] echo failed (non-fatal): ${n}`)}return}for(let[n,r]of e.split(`
|
|
4011
|
-
`).entries())this.printer((n===0?"> ":" ")+r)}async run(){if(this.isResumed){let F=this.checkLimits();if(F){this.checkpoint("stopped",F),tk(this.record.id,this.loopsDir);let Y={success:!1,iterations:this.state.iteration,totalCost:this.state.totalCost,totalInputTokens:this.state.totalInputTokens,totalOutputTokens:this.state.totalOutputTokens,totalToolCalls:this.state.totalToolCalls,durationMs:Date.now()-this.state.startTime,exitReason:F,consecutiveFailures:0};return Kv(Y,this.config,this.printer,this.buildResumeHint(F)),Y}this.checkpoint("running")}else try{this.record=O$(this.record,this.loopsDir);let F=(await Promise.resolve().then(()=>(ct(),po))).getConfigManager().get("loops.keep"),Y=typeof F=="number"&&Number.isFinite(F)?F:I$;L$(Y,this.loopsDir)}catch(F){ot(`[loop] registry create/prune failed (non-fatal): ${F}`)}let e=()=>{ot("[loop] Interrupt handler called (Esc)"),this.getPhase()==="paused"&&this.finalizePause(),this.transition("aborted"),tt().setLoopPaused(!1,null),ot(`[loop] state.phase set to ${this.getPhase()}`),this.agentController.interrupt(),this.resolvePausePromise()}
|
|
4010
|
+
`)}):r()}}im();SP();eh();Si();Vl();la();var fYe=["WebSocket disconnected unexpectedly","ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","socket hang up","WebSocket was closed","WebSocket error","StallTimeout","No response for","fetch failed","Failed to fetch","AbnormalDisconnect","unexpected EOF","connection reset by peer","LLM call failed","HTTP request failed","server error","502 Bad Gateway","503 Service Unavailable","504 Gateway Timeout","overloaded"],hYe=["status 401","status 403","authentication_error","Authentication Fails","api key","API key","Invalid API key","invalid_api_key","Unauthorized","Forbidden","model not found","invalid model","does not exist"],gYe=["maximum context length","context_length_exceeded","reduce the length of the messages","maximum number of tokens","token limit exceeded","context window"],Id={THRESHOLD:3,INITIAL_WAIT_MS:12e4,MAX_WAIT_MS:9e5,MULTIPLIER:2,POLL_INTERVAL_MS:5e3};function th(t){return t instanceof Error?t.message:typeof t=="object"&&t!==null&&"message"in t?String(t.message):typeof t=="string"?t:JSON.stringify(t)}function tme(t){let e=th(t);if(typeof t=="object"&&t!==null&&"retryable"in t&&t.retryable===!0)return!0;if(hYe.some(r=>e.includes(r)))return!1;let n=typeof t=="object"&&t!==null&&"name"in t?String(t.name):"";return fYe.some(r=>e.includes(r)||n.includes(r))}function nme(t){let e=th(t).toLowerCase();return gYe.some(n=>e.includes(n.toLowerCase()))}function ot(t){(process.env.AII_DEBUG||process.env.AII_LOOP_DEBUG)&&console.error(t)}var Dd=class{config;agentController;session;state;effectiveMaxIterations;printer;durationExpired=!1;record;loopsDir;isResumed=!1;startIteration=1;initialTokensIn;initialTokensOut;initialCost;consecutiveFailedIterations=0;circuitState="closed";circuitWaitMs=Id.INITIAL_WAIT_MS;processingQueue=!1;pausePromise=null;pauseResolver=null;pauseAutoResumeTimeout=null;pauseToastId=null;stoppingToastId=null;pendingNote=null;noteToastId=null;uiRefs=null;loopInterruptHandler=null;constructor(e,n,r,s,o){this.config=e,this.agentController=n,this.session=r,this.printer=s??console.log,this.effectiveMaxIterations=e.maxIterations>0?Math.min(e.maxIterations,hn.HARD_MAX_ITERATIONS):hn.HARD_MAX_ITERATIONS,process.env.AII_DEBUG&&console.error(`[loop] config.maxIterations=${e.maxIterations}, effectiveMaxIterations=${this.effectiveMaxIterations}`),this.initialTokensIn=r.stats.tokensIn,this.initialTokensOut=r.stats.tokensOut,this.initialCost=r.stats.totalCost,this.loopsDir=D$(r.projectPath);let i=o?.carry;if(this.state={iteration:i?.iteration??0,config:this.config,totalCost:i?.totalCost??0,totalInputTokens:i?.totalInputTokens??0,totalOutputTokens:i?.totalOutputTokens??0,totalToolCalls:i?.totalToolCalls??0,startTime:Date.now()-(i?.elapsedWallMs??0),phase:"running",pauseUntil:null,totalPauseMs:i?.totalPauseMs??0,pauseStartTime:null,lastAgentOutput:"",iterationCosts:i?[...i.iterationCosts]:[],iterationTokens:i?[...i.iterationTokens]:[],lastIterationHadToolCalls:!0,consecutiveNoToolCallIterations:i?.consecutiveNoToolCallIterations??0,capacityWarningsIssued:new Set(i?.capacityWarningsIssued??[]),userNotes:i?[...i.userNotes]:[]},i?.lastVerifyOutput&&(this.state.lastVerifyOutput={...i.lastVerifyOutput,durationMs:0}),this.startIteration=(i?.iteration??0)+1,o){let a=o.config;e.budgetUsd!==a.budgetUsd&&this.state.capacityWarningsIssued.delete("budget"),e.durationSeconds!==a.durationSeconds&&this.state.capacityWarningsIssued.delete("duration"),e.inputTokensLimit!==a.inputTokensLimit&&this.state.capacityWarningsIssued.delete("input_tokens"),e.outputTokensLimit!==a.outputTokensLimit&&this.state.capacityWarningsIssued.delete("output_tokens"),this.record={...o,config:e,pid:process.pid,status:"running",updatedAt:new Date().toISOString()},this.isResumed=!0}else this.record={version:1,id:Xv(),status:"running",pid:process.pid,projectRoot:Zf(r.projectPath),cwd:r.projectPath,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),config:e,carry:this.buildCarry()};process.env.AII_LOOP_DEBUG&&(console.error("[LOOP-DEBUG] LoopController initialized with session stats:"),console.error(` initial: tokensIn=${this.initialTokensIn}, tokensOut=${this.initialTokensOut}, totalCost=${this.initialCost}`))}buildCarry(){let e=this.state.lastVerifyOutput;return{iteration:this.state.iteration,totalCost:this.state.totalCost,totalInputTokens:this.state.totalInputTokens,totalOutputTokens:this.state.totalOutputTokens,totalToolCalls:this.state.totalToolCalls,iterationCosts:[...this.state.iterationCosts],iterationTokens:[...this.state.iterationTokens],consecutiveNoToolCallIterations:this.state.consecutiveNoToolCallIterations,capacityWarningsIssued:[...this.state.capacityWarningsIssued],userNotes:[...this.state.userNotes],lastVerifyOutput:e?{passed:e.passed,exitCode:e.exitCode,stdout:e.stdout.slice(-4096),stderr:e.stderr.slice(-4096)}:null,elapsedWallMs:Date.now()-this.state.startTime,totalPauseMs:this.state.totalPauseMs}}checkpoint(e,n){this.record={...this.record,status:e,exitReason:n??this.record.exitReason,pid:e==="running"?process.pid:void 0,updatedAt:new Date().toISOString(),carry:this.buildCarry()},x$(this.record,this.loopsDir)}getLoopRecordId(){return this.record.id}getPhase(){return this.state.phase}reinstallInterruptHandler(){this.loopInterruptHandler&&this.uiRefs?.isUIInitialized()&&this.uiRefs.getUI().setInterruptCallback(this.loopInterruptHandler)}transition(e){let n=this.state.phase;({running:["paused","stopping","aborted"],paused:["running","stopping","aborted"],stopping:["aborted"],aborted:[]})[n].includes(e)&&(this.state.phase=e)}finalizePause(){this.state.pauseStartTime&&(this.state.totalPauseMs+=Date.now()-this.state.pauseStartTime,this.state.pauseStartTime=null),this.state.pauseUntil=null,this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null)}resolvePausePromise(){this.pauseResolver&&(this.pauseResolver(),this.pauseResolver=null,this.pausePromise=null)}enterPause(e){e?this.state.pauseUntil=Date.now()+e*1e3:this.state.pauseUntil=null,this.pausePromise=new Promise(n=>{this.pauseResolver=n}),this.transition("paused"),e&&(this.pauseAutoResumeTimeout=setTimeout(()=>{this.resumeFromPause("auto")},e*1e3)),tt().setLoopPaused(!0,this.state.pauseUntil)}resumeFromPause(e){this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null),this.state.pauseStartTime&&(this.state.totalPauseMs+=Date.now()-this.state.pauseStartTime,this.state.pauseStartTime=null),this.state.pauseUntil=null,this.transition("running"),tt().setLoopPaused(!1,null),this.pauseToastId!==null&&(He().clearToast(this.pauseToastId),this.pauseToastId=null);let n=e==="auto"?"\u25C6 Loop resumed (auto)":"\u25C6 Loop resumed";this.printer($.success(n),{toast:!0}),this.resolvePausePromise()}updatePause(e){this.pauseAutoResumeTimeout&&(clearTimeout(this.pauseAutoResumeTimeout),this.pauseAutoResumeTimeout=null),e?(this.state.pauseUntil=Date.now()+e*1e3,this.pauseAutoResumeTimeout=setTimeout(()=>{this.resumeFromPause("auto")},e*1e3)):this.state.pauseUntil=null,tt().setLoopPaused(!0,this.state.pauseUntil)}isPauseRequested(){return this.getPhase()==="paused"}async waitForResume(){let n=null;return n=setInterval(()=>{try{this.agentController.ping()}catch{}},3e4),this.pausePromise&&await this.pausePromise,n&&clearInterval(n),this.getPhase()==="aborted"||this.getPhase()==="stopping"?"aborted":"resumed"}onPauseEntered(){this.state.pauseStartTime=Date.now(),tt().setThinking(!1),tt().setStreaming(!1),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.state.pauseUntil?(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused"),{toast:!0,persistent:!0,expiresAt:this.state.pauseUntil})):(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused \u2014 type /resume to continue"),{toast:!0,persistent:!0}))}onPauseExited(){tt().setThinking(!0)}clearStoppingToast(){this.stoppingToastId!==null&&(He().clearToast(this.stoppingToastId),this.stoppingToastId=null)}getPendingNote(){return this.pendingNote}onNoteInjected(){let e=this.pendingNote;this.pendingNote=null,this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),e&&this.echoUserInput(e)}echoUserInput(e){if(this.uiRefs?.isUIInitialized()){try{this.uiRefs.getUI().displayUserMessage(e,{preserveStream:!0})}catch(n){ot(`[loop] echo failed (non-fatal): ${n}`)}return}for(let[n,r]of e.split(`
|
|
4011
|
+
`).entries())this.printer((n===0?"> ":" ")+r)}async run(){if(this.isResumed){let F=this.checkLimits();if(F){this.checkpoint("stopped",F),tk(this.record.id,this.loopsDir);let Y={success:!1,iterations:this.state.iteration,totalCost:this.state.totalCost,totalInputTokens:this.state.totalInputTokens,totalOutputTokens:this.state.totalOutputTokens,totalToolCalls:this.state.totalToolCalls,durationMs:Date.now()-this.state.startTime,exitReason:F,consecutiveFailures:0};return Kv(Y,this.config,this.printer,this.buildResumeHint(F)),Y}this.checkpoint("running")}else try{this.record=O$(this.record,this.loopsDir);let F=(await Promise.resolve().then(()=>(ct(),po))).getConfigManager().get("loops.keep"),Y=typeof F=="number"&&Number.isFinite(F)?F:I$;L$(Y,this.loopsDir)}catch(F){ot(`[loop] registry create/prune failed (non-fatal): ${F}`)}let e=()=>{ot("[loop] Interrupt handler called (Esc)"),this.getPhase()==="paused"&&this.finalizePause(),this.transition("aborted"),tt().setLoopPaused(!1,null),ot(`[loop] state.phase set to ${this.getPhase()}`),this.agentController.interrupt(),this.resolvePausePromise()};this.loopInterruptHandler=e;let{isUIInitialized:n,getUI:r}=await Promise.resolve().then(()=>(ln(),Pi));if(this.uiRefs={isUIInitialized:n,getUI:r},n()){let F=r();ot("[loop] UI is initialized, registering interrupt callback"),F.setInterruptCallback(e)}else ot("[loop] WARNING: UI not initialized - Esc key will not work!");let s=null;try{let{useInputStore:F}=await Promise.resolve().then(()=>(Wl(),xm));s=F.subscribe(Y=>{Y.typeAheadQueue.length>0&&this.processQueuedMessages()}),ot("[loop] Type-ahead queue subscription registered")}catch{ot("[loop] WARNING: Could not subscribe to type-ahead queue")}try{let{getCommandMenuStore:F}=await Promise.resolve().then(()=>(ew(),VM));F().setCommands([{name:"pause",description:"Pause the loop (optional duration: 30s, 5m, 2h)"},{name:"resume",description:"Resume the paused loop"},{name:"stop",description:"Stop the loop gracefully after current turn"},{name:"note",description:"Inject a note immediately (between tool calls)"},{name:"inject",description:"Alias for /note \u2014 inject a note now"},{name:"now",description:"Alias for /note \u2014 removing in a future version"},{name:"stats",description:"Show loop statistics"}]),ot("[loop] Command menu populated with loop commands")}catch{ot("[loop] WARNING: Could not populate command menu")}this.agentController.use(Vpe(this)),this.agentController.use(Qv(this));let o=null;if(this.config.durationSeconds>0){let F=Date.now()-this.state.startTime,Y=Math.max(0,this.config.durationSeconds*1e3-F);Y<=2147483647&&(o=setTimeout(()=>{this.durationExpired=!0,this.getPhase()==="paused"&&this.finalizePause(),this.transition("aborted"),tt().setLoopPaused(!1,null),this.agentController.interrupt(),this.resolvePausePromise()},Y))}let i="max_iterations";this.agentController.setLoopMode(!0),tt().startLoop(this.state.startTime,this.config.maxIterations??0),this.isResumed&&(tt().setLoopIteration(this.state.iteration),tt().updateLoopStats(this.state.totalInputTokens,this.state.totalOutputTokens,this.state.totalCost,this.state.totalToolCalls)),tt().setLoopDurationSeconds(this.config.durationSeconds),v$(this.config,this.printer,this.isResumed?{shortId:Wa(this.record.id),iteration:this.state.iteration,maxIterations:this.config.maxIterations,spentUsd:this.state.totalCost,budgetUsd:this.config.budgetUsd}:void 0),this.agentController.resetInterrupt();let a=this.session.mode;this.session.mode="auto";let l=this.state.totalInputTokens,c=this.state.totalOutputTokens,u=this.state.totalCost,d=this.state.totalToolCalls,p=0,h=0,f=0,g=0,_=(F,Y,z,K)=>{let q=Y-z,J=z;p+=q,h+=J,f+=K,tt().updateLoopStats(l+p,c+h,u+f,d+g)},E=()=>{g++,tt().updateLoopStats(l+p,c+h,u+f,d+g)};this.agentController.on("iterationUsage",_),this.agentController.on("toolCall",E);let y=()=>{};try{y=Hpe(),ot(`[loop] Starting: effectiveMaxIterations=${this.effectiveMaxIterations}`);for(let F=this.startIteration;F<=this.effectiveMaxIterations;F++){if(ot(`[loop] >>> Iteration ${F}/${this.effectiveMaxIterations}`),this.getPhase()==="aborted"||this.agentController.isInterrupted())if(this.agentController.isPauseRequested()&&this.getPhase()!=="aborted")ot("[loop] Stale compaction flag at iteration start \u2014 resetting"),this.agentController.resetInterrupt();else if(this.agentController.isInterrupted()&&!this.durationExpired){i="user_abort",this.printer(m.red(`
|
|
4012
4012
|
Loop aborted by user (Esc)
|
|
4013
|
-
`));break}else{i=this.durationExpired?"duration_exceeded":"user_abort";break}if(this.getPhase()==="stopping"){i="graceful_stop",this.clearStoppingToast(),this.printer($.success(" \u25C6 Loop stopped gracefully by user (/stop)"));break}if(this.getPhase()==="paused"){this.state.pauseStartTime=Date.now(),tt().setThinking(!1),tt().setStreaming(!1),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.state.pauseUntil?(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused"),{toast:!0,persistent:!0,expiresAt:this.state.pauseUntil})):(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused \u2014 type /resume to continue"),{toast:!0,persistent:!0}));let Q=null;if(process.stdin.isTTY)try{let{useInputStore:ie}=await Promise.resolve().then(()=>(Wl(),xm)),ae=ie.getState();Q=Re=>{let he=Re.toString();if(he===""&&process.exit(0),he!=="\x1B"){if(he==="\r"){let te=ae.getText().trim();if(te){let xe=zm(te);if(xe&&xe.noteText){let at=xe.noteText,Yt=process.stdout.columns||80,tr=Math.floor(Yt*.618)-16,Qt=at.replace(/\n/g," "),Ur=Qt.length>tr?Qt.slice(0,tr)+"\u2026":Qt;He().showToast($.success(`\u25C6 Injecting: "${Ur}"`),!0),ae.enqueueTypeAhead({silent:!0})}else te.startsWith("/")&&!te.includes(`
|
|
4013
|
+
`));break}else{i=this.durationExpired?"duration_exceeded":"user_abort";break}if(this.getPhase()==="stopping"){i="graceful_stop",this.clearStoppingToast(),this.printer($.success(" \u25C6 Loop stopped gracefully by user (/stop)"));break}if(this.getPhase()==="paused"){this.uiRefs?.isUIInitialized()&&this.uiRefs.getUI().clearInterruptCallback(),this.state.pauseStartTime=Date.now(),tt().setThinking(!1),tt().setStreaming(!1),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.state.pauseUntil?(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused"),{toast:!0,persistent:!0,expiresAt:this.state.pauseUntil})):(this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop paused \u2014 type /resume to continue"),{toast:!0,persistent:!0}));let Q=null;if(process.stdin.isTTY)try{let{useInputStore:ie}=await Promise.resolve().then(()=>(Wl(),xm)),ae=ie.getState();Q=Re=>{let he=Re.toString();if(he===""&&process.exit(0),he!=="\x1B"){if(he==="\r"){let te=ae.getText().trim();if(te){let xe=zm(te);if(xe&&xe.noteText){let at=xe.noteText,Yt=process.stdout.columns||80,tr=Math.floor(Yt*.618)-16,Qt=at.replace(/\n/g," "),Ur=Qt.length>tr?Qt.slice(0,tr)+"\u2026":Qt;He().showToast($.success(`\u25C6 Injecting: "${Ur}"`),!0),ae.enqueueTypeAhead({silent:!0})}else te.startsWith("/")&&!te.includes(`
|
|
4014
4014
|
`)?ae.enqueueTypeAhead({silent:!0}):ae.enqueueTypeAhead()}return}if(he===`
|
|
4015
4015
|
`){ae.newLine();return}if(he==="\x7F"||he==="\b"){ae.deleteChar();return}if(he==="\x1B[A"){ae.moveCursor("up");return}if(he==="\x1B[B"){ae.moveCursor("down");return}if(he==="\x1B[C"){ae.moveCursor("right");return}if(he==="\x1B[D"){ae.moveCursor("left");return}if(he===""){ae.undo();return}if(he===""){ae.redo();return}if(he===""){ae.hasQueuedMessages()&&!ae.getText().trim()?ae.clearTypeAheadQueue():ae.clear();return}if(!he.startsWith("\x1B"))for(let te of Array.from(he)){let xe=te.codePointAt(0)??0;(xe>=32&&xe<=126||xe>=128)&&ae.insertChar(te)}}},process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",Q)}catch{}if(await this.pausePromise,Q&&process.stdin.removeListener("data",Q),this.getPhase()==="stopping"){i="graceful_stop",this.clearStoppingToast(),this.printer($.success(" \u25C6 Loop stopped gracefully by user (/stop)"));break}if(this.getPhase()==="aborted"){i=this.durationExpired?"duration_exceeded":"user_abort";break}}this.state.iteration=F,this.agentController.setCurrentIteration(F),tt().setLoopIteration(F),p=0,h=0,f=0,g=0;let Y=!1;this.pendingNote&&(this.state.userNotes.unshift(this.pendingNote),this.pendingNote=null,this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),Y=!0);let z=this.buildIterationPrompt(),K=null;this.state.userNotes.length>0&&(K=this.state.userNotes.shift(),Y||He().clearFirstPersistent()),this.clearSessionMessages();let q;try{({reanchorRenderState:q}=await Promise.resolve().then(()=>(Zr(),qs)))}catch{}if(q)try{q()}catch(Q){ot(`[loop] re-anchor failed (non-fatal): ${Q}`)}try{Ne.getInstance().pruneStaleEntries(),Ao().pruneTranscripts()}catch(Q){ot(`[loop] prune step failed (non-fatal): ${Q}`)}K&&this.echoUserInput(K);let J=this.session.stats.toolCalls,re=this.session.stats.tokensIn,ge=this.session.stats.tokensOut,oe=this.session.stats.totalCost;try{await this.runWithRetry(z),this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),this.consecutiveFailedIterations=0,this.circuitState!=="closed"&&(this.printer(m.green("\u2713 Provider recovered \u2014 resuming loop."),{toast:!0}),this.circuitState="closed",this.circuitWaitMs=Id.INITIAL_WAIT_MS);{let Q=this.session.stats.totalCost-oe,ie=this.session.stats.tokensIn-re,ae=this.session.stats.tokensOut-ge,Re=this.session.stats.toolCalls-J;this.state.iterationCosts.push(Q),this.state.iterationTokens.push({input:ie,output:ae}),this.state.totalCost+=Q,this.state.totalInputTokens+=ie,this.state.totalOutputTokens+=ae,this.state.totalToolCalls+=Re,l=this.state.totalInputTokens,c=this.state.totalOutputTokens,u=this.state.totalCost,d=this.state.totalToolCalls,tt().updateLoopStats(this.state.totalInputTokens,this.state.totalOutputTokens,this.state.totalCost,this.state.totalToolCalls)}}catch(Q){if(this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),ot(`[loop] Iteration ${F} caught error: ${th(Q)}`),ot(`[loop] state.phase=${this.getPhase()}, agentController.isInterrupted()=${this.agentController.isInterrupted()}, durationExpired=${this.durationExpired}`),this.agentController.isInterrupted()&&!this.durationExpired&&!this.agentController.isPauseRequested()){this.transition("aborted"),i="user_abort",ot("[loop] Agent interrupted by user - aborting loop"),this.printer(m.red(`
|
|
4016
4016
|
Loop aborted by user (Esc)
|
|
4017
4017
|
`));break}if(this.agentController.isPauseRequested()&&(ot("[loop] Compaction interrupt at iteration catch \u2014 resetting"),this.agentController.resetInterrupt()),this.getPhase()==="aborted"){i=this.durationExpired?"duration_exceeded":"user_abort",ot(`[loop] Aborting loop due to: ${i}`),this.printer(m.red(`
|
|
4018
4018
|
Loop aborted (${i})
|
|
4019
|
-
`));break}if(nme(Q)){this.printer(m.yellow(` \u26A0 Iteration ${F} hit context limit \u2014 continuing with fresh context`)),this.agentController.resetInterrupt(),this.clearSessionMessages(),this.consecutiveFailedIterations=0;continue}if(!tme(Q))throw Q;if(this.consecutiveFailedIterations++,this.consecutiveFailedIterations>=Id.THRESHOLD&&this.circuitState==="closed"&&(this.circuitState="open",this.circuitWaitMs=Id.INITIAL_WAIT_MS),this.circuitState==="open"||this.circuitState==="half_open"){F--,this.circuitState==="half_open"&&(this.circuitWaitMs=Math.min(this.circuitWaitMs*Id.MULTIPLIER,Id.MAX_WAIT_MS),this.circuitState="open");let ie=this.circuitWaitMs/1e3,ae=Math.round(ie/60);this.printer(m.yellow(` \u26A0 Provider unavailable \u2014 pausing for ${ae}m (${this.consecutiveFailedIterations} consecutive failures). Loop will auto-resume when provider returns.`)),this.printer(m.dim(" Press Esc to abort.")),ot(`[loop] Circuit breaker OPEN: waiting ${this.circuitWaitMs}ms`);let Re=Date.now()+this.circuitWaitMs;for(;Date.now()<Re&&(await new Promise(he=>setTimeout(he,Id.POLL_INTERVAL_MS)),!(this.getPhase()==="aborted"||this.getPhase()==="stopping")););if(this.getPhase()==="aborted"||this.getPhase()==="stopping"){i=this.getPhase()==="stopping"?"graceful_stop":this.durationExpired?"duration_exceeded":"user_abort",this.clearStoppingToast(),ot(`[loop] Aborted during circuit breaker wait: ${i}`),this.printer(m.red(`
|
|
4019
|
+
`));break}if(this.getPhase()==="stopping"){i="graceful_stop",this.clearStoppingToast(),ot("[loop] Graceful stop after iteration error"),this.printer($.success(" \u25C6 Loop stopped gracefully by user (/stop)"));break}if(nme(Q)){this.printer(m.yellow(` \u26A0 Iteration ${F} hit context limit \u2014 continuing with fresh context`)),this.agentController.resetInterrupt(),this.clearSessionMessages(),this.consecutiveFailedIterations=0;continue}if(!tme(Q))throw Q;if(this.consecutiveFailedIterations++,this.consecutiveFailedIterations>=Id.THRESHOLD&&this.circuitState==="closed"&&(this.circuitState="open",this.circuitWaitMs=Id.INITIAL_WAIT_MS),this.circuitState==="open"||this.circuitState==="half_open"){F--,this.circuitState==="half_open"&&(this.circuitWaitMs=Math.min(this.circuitWaitMs*Id.MULTIPLIER,Id.MAX_WAIT_MS),this.circuitState="open");let ie=this.circuitWaitMs/1e3,ae=Math.round(ie/60);this.reinstallInterruptHandler(),this.printer(m.yellow(` \u26A0 Provider unavailable \u2014 pausing for ${ae}m (${this.consecutiveFailedIterations} consecutive failures). Loop will auto-resume when provider returns.`)),this.printer(m.dim(" Press Esc to abort.")),ot(`[loop] Circuit breaker OPEN: waiting ${this.circuitWaitMs}ms`);let Re=Date.now()+this.circuitWaitMs;for(;Date.now()<Re&&(await new Promise(he=>setTimeout(he,Id.POLL_INTERVAL_MS)),!(this.getPhase()==="aborted"||this.getPhase()==="stopping")););if(this.getPhase()==="aborted"||this.getPhase()==="stopping"){i=this.getPhase()==="stopping"?"graceful_stop":this.durationExpired?"duration_exceeded":"user_abort",this.clearStoppingToast(),ot(`[loop] Aborted during circuit breaker wait: ${i}`),this.printer(m.red(`
|
|
4020
4020
|
Loop aborted during pause (Esc/Ctrl+C)
|
|
4021
|
-
`));break}this.circuitState="half_open",this.printer(m.dim(" Probing provider...")),this.agentController.resetInterrupt(),this.clearSessionMessages();continue}else{let ie=Math.min(2e3*Math.pow(2,this.consecutiveFailedIterations-1),6e4),ae=ie/1e3;if(this.printer(m.yellow(` \u26A0 Iteration ${F} failed after retries: ${th(Q)}`)),this.printer(m.dim(` Waiting ${ae}s before next iteration (backoff attempt ${this.consecutiveFailedIterations})...`)),ot(`[loop] Iteration ${F} failed, backing off ${ie}ms before retry`),await new Promise(Re=>setTimeout(Re,ie)),this.getPhase()==="aborted"||this.getPhase()==="stopping"){i=this.getPhase()==="stopping"?"graceful_stop":this.durationExpired?"duration_exceeded":"user_abort",this.clearStoppingToast(),ot(`[loop] Aborted during backoff: ${i}`),this.printer(m.red(`
|
|
4021
|
+
`));break}this.circuitState="half_open",this.printer(m.dim(" Probing provider...")),this.agentController.resetInterrupt(),this.clearSessionMessages();continue}else{let ie=Math.min(2e3*Math.pow(2,this.consecutiveFailedIterations-1),6e4),ae=ie/1e3;if(this.reinstallInterruptHandler(),this.printer(m.yellow(` \u26A0 Iteration ${F} failed after retries: ${th(Q)}`)),this.printer(m.dim(` Waiting ${ae}s before next iteration (backoff attempt ${this.consecutiveFailedIterations})...`)),ot(`[loop] Iteration ${F} failed, backing off ${ie}ms before retry`),await new Promise(Re=>setTimeout(Re,ie)),this.getPhase()==="aborted"||this.getPhase()==="stopping"){i=this.getPhase()==="stopping"?"graceful_stop":this.durationExpired?"duration_exceeded":"user_abort",this.clearStoppingToast(),ot(`[loop] Aborted during backoff: ${i}`),this.printer(m.red(`
|
|
4022
4022
|
Loop aborted during backoff (Esc/Ctrl+C)
|
|
4023
4023
|
`));break}this.agentController.resetInterrupt(),this.clearSessionMessages();continue}}let Oe=this.session.stats.toolCalls-J;this.state.lastAgentOutput=this.getLastAssistantText();let M=Oe>0;if(this.state.lastIterationHadToolCalls=M,M?this.state.consecutiveNoToolCallIterations=0:(this.state.consecutiveNoToolCallIterations++,this.state.consecutiveNoToolCallIterations>=hn.NO_TOOL_CALL_WARN_THRESHOLD&&k$(this.state.consecutiveNoToolCallIterations,this.printer),this.printer(m.dim(" Auto-recovering \u2014 starting next iteration"))),this.getPhase()==="aborted"){i="user_abort";break}if(await this.processQueuedMessages(),this.getPhase()==="stopping"){i="graceful_stop",this.clearStoppingToast(),this.printer($.success(" \u25C6 Loop stopped gracefully by user (/stop)"));break}if(Qf(this.config)){let Q=!1;this.config.completionPromise&&(Q=T$(this.state.lastAgentOutput,this.config.completionPromise));let ie=!1;if(this.config.verifyCommand){Vv(this.state,"running_verify",this.printer);let Re=w$(this.config.verifyCommand,this.session.projectPath,this.config.verifyTimeoutMs??hn.DEFAULT_VERIFY_TIMEOUT_MS);this.state.lastVerifyOutput=Re,ie=Re.passed,Vv(this.state,ie?"verify_passed":"verify_failed",this.printer)}let ae=this.checkCompletion(Q,ie);if(ae){i=ae;break}}let H=this.checkLimits();if(H){process.env.AII_DEBUG&&console.error(`[loop] Limit exceeded: ${H}`),i=H,this.checkpoint("running");break}this.checkpoint("running"),ot(`[loop] <<< Iteration ${F} complete`)}ot(`[loop] Exited: completed all ${this.effectiveMaxIterations} iterations`)}catch(F){let Y=typeof F=="object"&&F!==null&&"name"in F&&F.name==="AgentInterrupt";this.getPhase()==="aborted"?i=this.durationExpired?"duration_exceeded":"user_abort":Y||(i="error",this.printer(m.red(` Loop error: ${th(F)}`)))}finally{this.agentController.removeListener("iterationUsage",_),this.agentController.removeListener("toolCall",E),s&&(s(),ot("[loop] Type-ahead queue subscription removed")),o&&clearTimeout(o),this.pauseAutoResumeTimeout&&clearTimeout(this.pauseAutoResumeTimeout),this.state.pauseStartTime&&(this.state.totalPauseMs+=Date.now()-this.state.pauseStartTime,this.state.pauseStartTime=null),tt().setLoopPaused(!1,null),this.session.mode=a,this.agentController.setLoopMode(!1),this.agentController.clearMiddleware(),this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),this.pendingNote&&(this.pendingNote=null,this.printer($.dim("\u25C6 Note discarded \u2014 loop is stopping."),{toast:!0}));try{let{useInputStore:z}=await Promise.resolve().then(()=>(Wl(),xm)),K=z.getState();K.hasQueuedMessages()&&(K.clearTypeAheadQueue(),this.printer($.dim("\u25C6 Queued input discarded \u2014 loop ended."),{toast:!0}))}catch{}if(this.state.userNotes.length>0){for(let z=0;z<this.state.userNotes.length;z++)He().clearFirstPersistent();this.state.userNotes=[],this.printer($.dim("\u25C6 Queued input discarded \u2014 loop ended."),{toast:!0})}let{isUIInitialized:F,getUI:Y}=await Promise.resolve().then(()=>(ln(),Pi));if(F()){let z=Y();ot("[loop] Clearing interrupt callback - restoring normal input mode"),z.clearInterruptCallback()}y()}let S=this.session.stats.tokensIn-this.initialTokensIn,T=this.session.stats.tokensOut-this.initialTokensOut,C=this.session.stats.totalCost-this.initialCost,v=tt(),A=Math.max(S,v.loopTotalInputTokens),I=Math.max(T,v.loopTotalOutputTokens),D=Math.max(C,v.loopCost);process.env.AII_LOOP_DEBUG&&(console.error("[LOOP-DEBUG] Loop ending, final state:"),console.error(` state.totalCost=${this.state.totalCost} (from per-iteration accumulation)`),console.error(` state.totalInputTokens=${this.state.totalInputTokens}`),console.error(` state.totalOutputTokens=${this.state.totalOutputTokens}`),console.error(` session.stats: tokensIn=${this.session.stats.tokensIn}, tokensOut=${this.session.stats.tokensOut}, totalCost=${this.session.stats.totalCost}`),console.error(` initial: tokensIn=${this.initialTokensIn}, tokensOut=${this.initialTokensOut}, totalCost=${this.initialCost}`),console.error(` loop delta: tokensIn=${A}, tokensOut=${I}, totalCost=${D}`),console.error(" iterationCosts array:",this.state.iterationCosts),console.error(" iterationTokens array:",this.state.iterationTokens));let x=Date.now()-this.state.startTime,B={success:["completion_promise","verification_passed","both_passed"].includes(i),exitReason:i,iterations:this.state.iteration,totalCost:D,totalInputTokens:A,totalOutputTokens:I,durationMs:x,finalVerification:this.state.lastVerifyOutput,totalToolCalls:Math.max(this.state.totalToolCalls,v.loopToolCalls),consecutiveFailures:this.consecutiveFailedIterations,...this.state.totalPauseMs>0?{totalPauseMs:this.state.totalPauseMs,activeExecutionMs:x-this.state.totalPauseMs}:{}};this.state.totalCost=Math.max(this.state.totalCost,B.totalCost),this.state.totalInputTokens=Math.max(this.state.totalInputTokens,B.totalInputTokens),this.state.totalOutputTokens=Math.max(this.state.totalOutputTokens,B.totalOutputTokens),this.state.totalToolCalls=Math.max(this.state.totalToolCalls,B.totalToolCalls);let U=this.buildResumeHint(i);this.checkpoint(B.success?"completed":"stopped",i),tk(this.record.id,this.loopsDir);try{let{getConfigManager:F}=await Promise.resolve().then(()=>(ct(),po));if((F().getConfig().subagent?.notifications?.in_loop??"final")!=="suppress"){let{Notifier:z}=await Promise.resolve().then(()=>(ZL(),_ae));await z.notifyLoopEnd({success:i!=="error",iterations:this.state.iteration,durationMs:x,summary:`${i} \xB7 ${this.state.iteration} iters${U?` \xB7 resume ${Wa(this.record.id)}`:""}`})}}catch{}return Kv(B,this.config,this.printer,U),B}buildResumeHint(e){if(["completion_promise","verification_passed","both_passed"].includes(e))return;let n=`/loop resume ${Wa(this.record.id)}`;switch(e){case"budget_exceeded":return`${n} --budget ${Math.max(Math.ceil(this.config.budgetUsd*2),Math.ceil(this.state.totalCost)+1)}`;case"max_iterations":{if(this.state.iteration>=hn.HARD_MAX_ITERATIONS)return;let r=Math.min((this.config.maxIterations>0?this.config.maxIterations:this.state.iteration)*2,hn.HARD_MAX_ITERATIONS);return`${n} --max ${r}`}case"duration_exceeded":{let r=Math.ceil((Date.now()-this.state.startTime)/6e4),s=Math.max(1,Math.ceil(this.config.durationSeconds*2/60),r+1);return`${n} --duration ${s}m`}case"input_tokens_exceeded":return`${n} --input-tokens-limit ${Math.max(this.config.inputTokensLimit*2,this.state.totalInputTokens+1)}`;case"output_tokens_exceeded":return`${n} --output-tokens-limit ${Math.max(this.config.outputTokensLimit*2,this.state.totalOutputTokens+1)}`;default:{let r=[];return this.config.maxIterations>0&&r.push(`${Math.max(0,this.config.maxIterations-this.state.iteration)} iterations left`),this.config.budgetUsd>0&&r.push(`~$${Math.max(0,this.config.budgetUsd-this.state.totalCost).toFixed(2)} left`),r.length>0?`${n} \u2014 ${r.join(" + ")}`:n}}}checkCapacityWarnings(){let e=[];if(this.config.durationSeconds>0&&!this.state.capacityWarningsIssued.has("duration")){let r=(Date.now()-this.state.startTime)/1e3,s=r/this.config.durationSeconds;if(s>=.9){let o=Math.max(0,this.config.durationSeconds-r);e.push(`\u26A0\uFE0F TIME WARNING: ${o.toFixed(0)}s remaining (${(s*100).toFixed(0)}% used). Prepare to wrap up gracefully.`),this.state.capacityWarningsIssued.add("duration")}}if(this.config.budgetUsd>0&&!this.state.capacityWarningsIssued.has("budget")){let r=this.state.totalCost/this.config.budgetUsd;if(r>=.9){let s=Math.max(0,this.config.budgetUsd-this.state.totalCost);e.push(`\u26A0\uFE0F BUDGET WARNING: $${s.toFixed(2)} remaining (${(r*100).toFixed(0)}% used). Prepare to wrap up gracefully.`),this.state.capacityWarningsIssued.add("budget")}}if(this.config.inputTokensLimit>0&&!this.state.capacityWarningsIssued.has("input_tokens")){let r=this.state.totalInputTokens/this.config.inputTokensLimit;if(r>=.9){let s=Math.max(0,this.config.inputTokensLimit-this.state.totalInputTokens);e.push(`\u26A0\uFE0F INPUT TOKENS WARNING: ${s.toLocaleString()} remaining (${(r*100).toFixed(0)}% used). Prepare to wrap up gracefully.`),this.state.capacityWarningsIssued.add("input_tokens")}}if(this.config.outputTokensLimit>0&&!this.state.capacityWarningsIssued.has("output_tokens")){let r=this.state.totalOutputTokens/this.config.outputTokensLimit;if(r>=.9){let s=Math.max(0,this.config.outputTokensLimit-this.state.totalOutputTokens);e.push(`\u26A0\uFE0F OUTPUT TOKENS WARNING: ${s.toLocaleString()} remaining (${(r*100).toFixed(0)}% used). Prepare to wrap up gracefully.`),this.state.capacityWarningsIssued.add("output_tokens")}}return e}buildIterationPrompt(){return Qf(this.config)?this.buildTaskPrompt():this.buildActivityPrompt()}buildTaskPrompt(){let e=[],n=this.config.maxIterations>0?`${this.state.iteration} of ${this.config.maxIterations}`:`${this.state.iteration}`;if(e.push(`You are in iteration ${n} of an autonomous coding loop.
|
|
4024
4024
|
`),this.config.prompt&&e.push(`TASK: ${this.config.prompt}
|
|
@@ -4035,7 +4035,7 @@ Additional rules:
|
|
|
4035
4035
|
`));let n=this.checkCapacityWarnings();return n.length>0&&(e.push("\u2550".repeat(60)),e.push(...n),e.push("SUNSET STAGE: Loop will terminate soon. Focus on wrapping up gracefully:"),e.push("- Save your current work"),e.push("- Update any status files or memory"),e.push("- Ensure external systems are in a stable state"),e.push("\u2550".repeat(60)),e.push("")),e.push("IMPORTANT: Every response MUST include at least one tool call."),e.push("Do not summarize, do not ask questions, do not produce text-only responses."),e.push("If unsure what to do, read your instruction files."),this.state.userNotes.length>0&&(e.push(""),e.push("USER NOTE (typed by the user during loop execution):"),e.push(`- ${this.state.userNotes[0]}`),this.state.userNotes.length>1&&e.push(`(${this.state.userNotes.length-1} more note(s) queued for subsequent iterations)`),e.push("Take this note into account for this iteration.")),e.join(`
|
|
4036
4036
|
`)}checkLimits(){return this.config.durationSeconds>0&&(Date.now()-this.state.startTime)/1e3>=this.config.durationSeconds?"duration_exceeded":bl(this.state.totalCost,this.config.budgetUsd)?"budget_exceeded":this.config.inputTokensLimit>0&&this.state.totalInputTokens>=this.config.inputTokensLimit?"input_tokens_exceeded":this.config.outputTokensLimit>0&&this.state.totalOutputTokens>=this.config.outputTokensLimit?"output_tokens_exceeded":null}clearSessionMessages(){this.session.messages=[]}async processQueuedMessages(){if(!this.processingQueue){this.processingQueue=!0;try{let{useInputStore:e}=await Promise.resolve().then(()=>(Wl(),xm)),n=e.getState();if(!n.hasQueuedMessages())return;for(;n.hasQueuedMessages();){let r=n.dequeueTypeAhead();if(!r?.trim())continue;let s=r.trim(),o=zm(s);if(s==="/stop"){for(this.getPhase()==="paused"&&(this.finalizePause(),this.transition("running"),tt().setLoopPaused(!1,null),this.resolvePausePromise()),this.transition("stopping"),this.stoppingToastId=He().nextId,this.printer($.success("\u25C6 Stopping after current turn completes..."),{toast:!0,persistent:!0}),this.pendingNote&&(this.pendingNote=null,this.noteToastId!==null&&(He().clearToast(this.noteToastId),this.noteToastId=null),this.printer($.dim("\u25C6 Note discarded \u2014 loop is stopping."),{toast:!0}));n.hasQueuedMessages();){let a=n.dequeueTypeAhead()?.trim()??"",l=a.startsWith("/")&&!a.includes(`
|
|
4037
4037
|
`)&&!zm(a)?.noteText;a&&!l&&(He().clearFirstPersistent(),this.printer($.dim("\u25C6 Note discarded \u2014 loop is stopping."),{toast:!0}))}return}else if(s==="/resume")this.getPhase()==="paused"?this.resumeFromPause("manual"):this.getPhase()==="stopping"?this.printer($.dim("\u25C6 Loop is stopping \u2014 cannot resume"),{toast:!0}):this.printer($.dim("\u25C6 Loop is not paused"),{toast:!0});else if(s.startsWith("/pause")){if(this.getPhase()==="stopping")this.printer($.dim("\u25C6 Loop is stopping \u2014 cannot pause"),{toast:!0});else if(this.getPhase()==="paused"){let i=s.slice(6).trim();if(i){let a=y$(i);a===0?this.printer($.dim(`\u25C6 Invalid duration: ${i} (use e.g. 30s, 5m, 2h)`),{toast:!0}):(this.updatePause(a),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Pause updated"),{toast:!0,persistent:!0,expiresAt:this.state.pauseUntil}))}else this.updatePause(),this.pauseToastId!==null&&He().clearToast(this.pauseToastId),this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Pause updated \u2014 indefinite, type /resume to continue"),{toast:!0,persistent:!0})}else if(this.getPhase()==="running"){let i=s.slice(6).trim();if(i){let a=y$(i);a===0?this.printer($.dim(`\u25C6 Invalid duration: ${i} (use e.g. 30s, 5m, 2h)`),{toast:!0}):(this.enterPause(a),this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop pausing \u2014 will pause after current tool completes"),{toast:!0,persistent:!0}))}else this.enterPause(),this.pauseToastId=He().nextId,this.printer($.success("\u25C6 Loop pausing \u2014 will pause after current tool completes"),{toast:!0,persistent:!0})}}else if(s==="/stats"||s==="/status")Wpe(this.state,this.state.totalToolCalls,this.consecutiveFailedIterations,this.printer);else if(o){let i=o.noteText;if(!i)this.printer($.dim(`\u25C6 ${o.prefix} requires a message (usage: ${o.prefix} <text>)`),{toast:!0});else{this.noteToastId!==null&&He().clearToast(this.noteToastId),this.pendingNote=i;let l=[...He().toasts].reverse().find(c=>c.persistent);this.noteToastId=l?.id??null}}else if(s.startsWith("/")&&!s.includes(`
|
|
4038
|
-
`)){let i=s.split(/\s+/)[0],a=Array.from(i).slice(0,24).join("").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"");i==="/loop"?this.printer($.dim("\u25C6 A loop is already running \u2014 /stop it first to start a new one."),{toast:!0}):this.printer($.dim(`\u25C6 "${a}" isn't a loop command \u2014 /note /inject /pause /resume /stop /stats only; /stop to run other commands.`),{toast:!0})}else s&&this.state.userNotes.push(s)}}finally{this.processingQueue=!1}}}getLastAssistantText(){let e=this.session.messages.filter(r=>r.role==="assistant");if(e.length===0)return"";let n=e[e.length-1];return typeof n.content=="string"?n.content:""}async runWithRetry(e){let r=0;for(;;){r++;try{await this.agentController.run(e,this.session);return}catch(s){if(this.getPhase()==="aborted")throw s;if(this.agentController.isPauseRequested()){ot("[loop] Context compaction interrupted iteration \u2014 restarting"),this.printer(m.dim(" Context compacted \u2014 restarting iteration...")),this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages();continue}if(nme(s)){ot("[loop] Context overflow detected \u2014 clearing context and retrying"),this.printer(m.yellow(" \u26A0 Context window full \u2014 restarting iteration with fresh context")),this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages();continue}if(!tme(s)||this.checkLimits())throw s;if(r>=10)throw this.printer(m.yellow(" \u26A0 Max retries (10) exceeded for this iteration")),s;let o=Math.min(2e3*Math.pow(2,r-1),3e4);if(this.printer(m.yellow(` \u26A0 Connection lost: ${th(s)}`)),this.printer(m.dim(` Retrying in ${o/1e3}s (attempt ${r}/10)...`)),ot(`[loop] Before backoff sleep: state.phase=${this.getPhase()}`),await new Promise(i=>setTimeout(i,o)),ot(`[loop] After backoff sleep: state.phase=${this.getPhase()}`),this.getPhase()==="aborted")throw s;this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages()}}}checkCompletion(e,n){let r=!!this.config.completionPromise,s=!!this.config.verifyCommand;return r&&s?e&&n?"both_passed":null:r&&e?"completion_promise":s&&n?"verification_passed":null}};Uy();Xf();function ome(t){t.register({name:"loop",description:"Start autonomous agent loop (all options optional)",usage:'/loop ["<prompt>"] [--max <N>] [--promise "<string>"] [--verify "<cmd>"] [--budget <$N>] [--duration <N>[s|m|h]]',handler:async(e,n)=>{if(e.trim()==="help"||e.trim()==="--help"||e.trim()==="-h")return{continue:!0,handled:!0,output:[j().accent.bold("Ralph Wiggum Loop - Autonomous Agent Loop"),"",m.yellow("Usage:"),' /loop ["<prompt>"] [options]',"",m.yellow("Options:")," --max <N> Maximum iterations (default: unlimited, hard cap: 1000)",' --promise "<string>" Completion string to detect in agent output',' --verify "<command>" Shell command that must exit 0 for completion'," --budget <$N> Cost budget in USD (estimated)"," --input-tokens-limit <N> Input token limit (exact)"," --output-tokens-limit <N> Output token limit (exact)"," --duration <N>[s|m|h] Maximum duration (seconds/minutes/hours)"," --time <N>[s|m|h] Alias for --duration","",m.yellow("Modes:")," \u2022 With --verify/--promise: Task completion mode (loop until criteria met)"," \u2022 Without: AGENTS.md-driven continuous activity (loop until Ctrl+C)","",m.yellow("Subcommands:")," /loop list Show saved loops in this project with status"," /loop resume <id> Resume a stopped/interrupted loop by its #id"," (add --max/--budget/--duration/... to raise a limit;"," --force to override a live-process lock)","",m.yellow("Examples:")," /loop # Continuous AGENTS.md-driven activity",' /loop "fix the tests" --verify "npm test" # Loop until tests pass'," /loop --budget $5 --max 20 # Limited by cost and iterations"," /loop --duration 5m # Run for 5 minutes"," /loop list # List saved loops (canceled, stopped, completed\u2026)"," /loop resume k3x9 --budget 10 # Resume a saved loop, raising its budget","",m.yellow("Using with Skills:")," To use loop with a skill: invoke the skill first, then start /loop without prompt",m.dim(" (The loop prompt is for task descriptions, not skill invocations)"),"",m.yellow("Limits:")," \u2022 Press Ctrl+C to abort at any time"," \u2022 Sunset warnings at 90% of any capacity limit"," \u2022 All permissions auto-approved during loop"].join(`
|
|
4038
|
+
`)){let i=s.split(/\s+/)[0],a=Array.from(i).slice(0,24).join("").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"");i==="/loop"?this.printer($.dim("\u25C6 A loop is already running \u2014 /stop it first to start a new one."),{toast:!0}):this.printer($.dim(`\u25C6 "${a}" isn't a loop command \u2014 /note /inject /pause /resume /stop /stats only; /stop to run other commands.`),{toast:!0})}else s&&this.state.userNotes.push(s)}}finally{this.processingQueue=!1}}}getLastAssistantText(){let e=this.session.messages.filter(r=>r.role==="assistant");if(e.length===0)return"";let n=e[e.length-1];return typeof n.content=="string"?n.content:""}async runWithRetry(e){let r=0;for(;;){r++;try{await this.agentController.run(e,this.session);return}catch(s){if(this.getPhase()==="aborted"||this.getPhase()==="stopping")throw s;if(this.agentController.isPauseRequested()){ot("[loop] Context compaction interrupted iteration \u2014 restarting"),this.printer(m.dim(" Context compacted \u2014 restarting iteration...")),this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages();continue}if(nme(s)){ot("[loop] Context overflow detected \u2014 clearing context and retrying"),this.printer(m.yellow(" \u26A0 Context window full \u2014 restarting iteration with fresh context")),this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages();continue}if(!tme(s)||this.checkLimits())throw s;if(r>=10)throw this.printer(m.yellow(" \u26A0 Max retries (10) exceeded for this iteration")),s;let o=Math.min(2e3*Math.pow(2,r-1),3e4);if(this.reinstallInterruptHandler(),this.printer(m.yellow(` \u26A0 Connection lost: ${th(s)}`)),this.printer(m.dim(` Retrying in ${o/1e3}s (attempt ${r}/10)...`)),ot(`[loop] Before backoff sleep: state.phase=${this.getPhase()}`),await new Promise(i=>setTimeout(i,o)),ot(`[loop] After backoff sleep: state.phase=${this.getPhase()}`),this.getPhase()==="aborted"||this.getPhase()==="stopping")throw s;this.agentController.resetInterrupt(),this.agentController.markSkipInitialDraw(),this.clearSessionMessages()}}}checkCompletion(e,n){let r=!!this.config.completionPromise,s=!!this.config.verifyCommand;return r&&s?e&&n?"both_passed":null:r&&e?"completion_promise":s&&n?"verification_passed":null}};Uy();Xf();function ome(t){t.register({name:"loop",description:"Start autonomous agent loop (all options optional)",usage:'/loop ["<prompt>"] [--max <N>] [--promise "<string>"] [--verify "<cmd>"] [--budget <$N>] [--duration <N>[s|m|h]]',handler:async(e,n)=>{if(e.trim()==="help"||e.trim()==="--help"||e.trim()==="-h")return{continue:!0,handled:!0,output:[j().accent.bold("Ralph Wiggum Loop - Autonomous Agent Loop"),"",m.yellow("Usage:"),' /loop ["<prompt>"] [options]',"",m.yellow("Options:")," --max <N> Maximum iterations (default: unlimited, hard cap: 1000)",' --promise "<string>" Completion string to detect in agent output',' --verify "<command>" Shell command that must exit 0 for completion'," --budget <$N> Cost budget in USD (estimated)"," --input-tokens-limit <N> Input token limit (exact)"," --output-tokens-limit <N> Output token limit (exact)"," --duration <N>[s|m|h] Maximum duration (seconds/minutes/hours)"," --time <N>[s|m|h] Alias for --duration","",m.yellow("Modes:")," \u2022 With --verify/--promise: Task completion mode (loop until criteria met)"," \u2022 Without: AGENTS.md-driven continuous activity (loop until Ctrl+C)","",m.yellow("Subcommands:")," /loop list Show saved loops in this project with status"," /loop resume <id> Resume a stopped/interrupted loop by its #id"," (add --max/--budget/--duration/... to raise a limit;"," --force to override a live-process lock)","",m.yellow("Examples:")," /loop # Continuous AGENTS.md-driven activity",' /loop "fix the tests" --verify "npm test" # Loop until tests pass'," /loop --budget $5 --max 20 # Limited by cost and iterations"," /loop --duration 5m # Run for 5 minutes"," /loop list # List saved loops (canceled, stopped, completed\u2026)"," /loop resume k3x9 --budget 10 # Resume a saved loop, raising its budget","",m.yellow("Using with Skills:")," To use loop with a skill: invoke the skill first, then start /loop without prompt",m.dim(" (The loop prompt is for task descriptions, not skill invocations)"),"",m.yellow("Limits:")," \u2022 Press Ctrl+C to abort at any time"," \u2022 Sunset warnings at 90% of any capacity limit"," \u2022 All permissions auto-approved during loop"].join(`
|
|
4039
4039
|
`)};if(!t.agentController)return{continue:!0,handled:!0,output:m.red("Loop unavailable: agent controller not initialized")};let r,s,o;{let{routeLoopArgs:d,resolveResumeTarget:p,formatLoopList:h}=await Promise.resolve().then(()=>(U$(),$$)),{resolveLoopsDir:f,listLoops:g,claimLoop:_}=await Promise.resolve().then(()=>(eh(),rk)),E=e.trim().split(/\s+/).filter(Boolean),y=d(E);if(y?.sub==="list"){let S=h(g(f(n.projectPath)));return{continue:!0,handled:!0,output:["",m.yellow(" Saved loops:"),...S,""].join(`
|
|
4040
4040
|
`)}}if(y?.sub==="resume"){let S=f(n.projectPath),T=p(y.rest,S,n.projectPath);if(T.kind==="usage"){let C=h(g(S),!0);return{continue:!0,handled:!0,output:["",m.yellow(" Resumable loops:"),...C,"",m.dim(" Usage: /loop resume <id> [--max N] [--budget N] [--duration Nm] [--force]"),""].join(`
|
|
4041
4041
|
`)}}if(T.kind==="refuse")return{continue:!0,handled:!0,output:m.yellow(`\u25C6 ${T.message}`)};if(T.kind==="resume"){if(!_(T.record.id,process.pid,S,T.force))return{continue:!0,handled:!0,output:m.yellow("\u25C6 This loop is being resumed by another aii process.")};r=T.record,s=T.config,T.force?o="Resuming with --force (live-pid check overridden).":T.cwdNotice&&(o=T.cwdNotice)}else o=T.notice}}let i="";if(n.goal?.status==="active"||n.goal?.status==="waiting"){let{goalReducer:d}=await Promise.resolve().then(()=>(Tl(),aG)),p=d(n.goal,{type:"pause"});p.changed&&(n.goal=p.goal,t.agentController?.setActiveGoalText(null),i=m.dim("\u25CE Goal auto-paused for the loop \u2014 /goal resume afterwards.")+`
|
|
@@ -4381,10 +4381,10 @@ ${n.yellow("CONFIG FILE:")}
|
|
|
4381
4381
|
.aii/settings.json Project config (committed, restrict-only)
|
|
4382
4382
|
.aii/settings.local.json Your local overrides (gitignored)
|
|
4383
4383
|
${n.gray("Skip both for a session with: aii --no-project-config")}
|
|
4384
|
-
`)}import*as Hi from"fs";_n();async function Afe(t,e){let n=as({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),r=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?r.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):r.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?r.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):r.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await oVe(o.api.url);r.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let l=`${e.getConfigDir()}/mcp_servers.json`;if(Hi.existsSync(l))try{let h=Hi.readFileSync(l,"utf-8"),f=JSON.parse(h),g=Object.keys(f.mcpServers??{}).length;g>0?r.push({name:"MCP Servers",status:"ok",message:`${g} configured`}):r.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{r.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else r.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(Uv())try{let{execSync:h}=await import("child_process"),g=h("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);r.push({name:"Docker",status:"ok",message:g?`v${g[1]}`:"Installed"})}catch{r.push({name:"Docker",status:"ok",message:"Installed"})}else r.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});Uv()?Bv()?r.push({name:"Docker Daemon",status:"ok",message:"Running"}):r.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):r.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?r.push({name:"Node.js",status:"ok",message:c}):r.push({name:"Node.js",status:"error",message:`${c} (requires >= 18)`});let d=await iVe();r.push(...d),console.log(n.formatHealthCheck(r,Zc)),r.some(h=>h.status==="error")&&process.exit(1)}async function oVe(t){try{let e=new AbortController,n=setTimeout(()=>e.abort(),3e3),r=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(n),r.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${r.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function iVe(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(fs(),Rb)),n=`${e()}/skills`;if(!Hi.existsSync(n))return t;let r=Hi.readdirSync(n,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${n}/${s.name}/SKILL.md`;Hi.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(()=>(It(),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=`${n}/${a}`;Hi.existsSync(l)&&Hi.existsSync(`${l}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}ye();_n();import{execSync as c5}from"node:child_process";var Nk="@aiiware/aii";async function Ife(t){let e=t.args||[],n=t.subcommand||e[0]||"";if(t.flags.help||n==="help"||n==="--help"||e.includes("--help")){let r="0.21.
|
|
4385
|
-
`),await aVe(n)}async function aVe(t){let e="0.21.
|
|
4384
|
+
`)}import*as Hi from"fs";_n();async function Afe(t,e){let n=as({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),r=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?r.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):r.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?r.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):r.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await oVe(o.api.url);r.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let l=`${e.getConfigDir()}/mcp_servers.json`;if(Hi.existsSync(l))try{let h=Hi.readFileSync(l,"utf-8"),f=JSON.parse(h),g=Object.keys(f.mcpServers??{}).length;g>0?r.push({name:"MCP Servers",status:"ok",message:`${g} configured`}):r.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{r.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else r.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(Uv())try{let{execSync:h}=await import("child_process"),g=h("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);r.push({name:"Docker",status:"ok",message:g?`v${g[1]}`:"Installed"})}catch{r.push({name:"Docker",status:"ok",message:"Installed"})}else r.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});Uv()?Bv()?r.push({name:"Docker Daemon",status:"ok",message:"Running"}):r.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):r.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let c=process.version;parseInt(c.slice(1).split(".")[0],10)>=18?r.push({name:"Node.js",status:"ok",message:c}):r.push({name:"Node.js",status:"error",message:`${c} (requires >= 18)`});let d=await iVe();r.push(...d),console.log(n.formatHealthCheck(r,Zc)),r.some(h=>h.status==="error")&&process.exit(1)}async function oVe(t){try{let e=new AbortController,n=setTimeout(()=>e.abort(),3e3),r=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(n),r.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${r.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function iVe(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(fs(),Rb)),n=`${e()}/skills`;if(!Hi.existsSync(n))return t;let r=Hi.readdirSync(n,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${n}/${s.name}/SKILL.md`;Hi.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(()=>(It(),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=`${n}/${a}`;Hi.existsSync(l)&&Hi.existsSync(`${l}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}ye();_n();import{execSync as c5}from"node:child_process";var Nk="@aiiware/aii";async function Ife(t){let e=t.args||[],n=t.subcommand||e[0]||"";if(t.flags.help||n==="help"||n==="--help"||e.includes("--help")){let r="0.21.8";console.log(""),console.log($.logo(" Install")),console.log(""),console.log(` Current version: ${$.model(r)}`),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(n==="skill"){console.log("Skill installation coming soon. For now use: /skills install owner/repo");return}if(n==="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
|
|
4385
|
+
`),await aVe(n)}async function aVe(t){let e="0.21.8",n=t&&t!=="latest"?t:"";if(console.log(""),n){console.log(`\u{1FABC} Installing Aii CLI v${n}...`),console.log("");try{c5(`npm install -g ${Nk}@${n}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4386
4386
|
\u274C Failed to install v${n}`),console.error(` Try manually: npm install -g ${Nk}@${n}`),process.exit(1)}}else{console.log("\u{1FABC} Updating Aii CLI to latest..."),console.log(` Current version: ${e}`),console.log("");try{c5(`npm install -g ${Nk}@latest`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4387
|
-
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${Nk}@latest`),process.exit(1)}}try{let r=c5("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(r===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${r}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}ye();var Dfe="0.21.
|
|
4387
|
+
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${Nk}@latest`),process.exit(1)}}try{let r=c5("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(r===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${r}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}ye();var Dfe="0.21.8";function u5(t){let n=!t.flags.noColors?m:{cyan:r=>r,yellow:r=>r,gray:r=>r,green:r=>r};console.log(`
|
|
4388
4388
|
${n.cyan("AII")} - AI-powered CLI assistant v${Dfe}
|
|
4389
4389
|
|
|
4390
4390
|
${n.yellow("USAGE:")}
|