@aiiware/aii 0.25.5 → 0.25.6
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 +11 -11
- package/bin/aii-host-worker.mjs +5 -5
- 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.25.
|
|
3
|
+
* @aiiware/aii v0.25.6
|
|
4
4
|
*
|
|
5
5
|
* AI-powered CLI assistant for terminal productivity
|
|
6
6
|
*
|
|
@@ -352,7 +352,7 @@ shutting down\u2026 (Ctrl+C again to force)
|
|
|
352
352
|
`),bpe="CODEX_ENTITLEMENT_DENIED:",got=["\u25A0 OpenAI accepted your sign-in but declined Codex access for your current plan."," OpenAI decides which ChatGPT subscription tiers may use Codex sign-in \u2014 this is not an Aii bug."," Today: paste an OpenAI API key instead (aii setup \u2192 OpenAI) \xB7 keep the sign-in; it activates if OpenAI enables your tier."].join(`
|
|
353
353
|
`),CG=[{prefix:pot,wall:fot},{prefix:mot,wall:hot},{prefix:bpe,wall:got}],Aot="PROVIDER_AUTH_REJECTED:",_ot="upstream 401 Unauthorized:",Eot=`${Aot} ${_ot}`,yot=/"status":\s*401\b|token_expired/;mR="\u25D0 Your provider credential was rejected upstream \u2014 expired, rotated, or invalid. Sign-in lanes: aii login --status \xB7 API keys: aii setup";SG="\u25D0 Your sign-in token was refreshed mid-turn \u2014 retry this step (autonomous runs retry automatically).",Cot=[QD,O5,mR,SG];Sot="Note: Z.ai limits Coding Plans to their officially supported tools; Aii isn't listed yet.",bot={zai:"glm"};Ob={xai:{tier:"sanctioned",kind:"oauth",description:"SuperGrok / X Premium"},glm:{tier:"unofficial",kind:"plan-key",disclosure:"notice",notice:Sot,description:"GLM Coding Plan (flat-rate)"},claude:{tier:"blocked",wall:uot},openai:{tier:"unofficial",kind:"oauth",disclosure:"consent",consentCopy:yue,description:"ChatGPT subscription (Codex)"},google:{tier:"blocked",wall:dot}},Iot={sanctioned:"sanctioned",unofficial:"unofficial (explicit consent required)",blocked:"blocked (provider terms)",unavailable:"unavailable (pending provider sanction)"},bG="Other providers use API keys \u2014 aii setup.",IG="Sign in: aii login --provider xai \xB7 status: aii login --status"});import{execFileSync as wG}from"node:child_process";function vG(t){if(!t)return!1;try{let e=new URL(t).protocol;return e==="https:"||e==="http:"}catch{return!1}}function DG(t){vG(t)&&(process.platform==="darwin"?wG("open",[t],{stdio:"ignore"}):process.platform==="win32"?wG("cmd",["/c","start","",t],{stdio:"ignore"}):wG("xdg-open",[t],{stdio:"ignore"}))}function kG(t){if(t?.aborted)throw new ni}async function Mm(t,e,r,n){let s=new AbortController,o=setTimeout(()=>s.abort(),n);try{let i=await t(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(r).toString(),signal:s.signal}),a=await i.text();return{ok:i.ok,status:i.status,text:a}}finally{clearTimeout(o)}}async function wpe(t,e={}){let r=e.fetchImpl??fetch,n=e.openBrowser??DG,s=e.sleep??(A=>new Promise(_=>setTimeout(_,A))),o=e.now??(()=>Date.now()),i=e.print??(A=>process.stdout.write(A+`
|
|
354
354
|
`)),a=e.signal,c=e.requestTimeoutMs??1e4,l=(A,_)=>Mm(r,A,_,c);kG(a);let u;try{u=await l(t.deviceEndpoint,{client_id:t.clientId,scope:t.scopes})}catch(A){throw A.name==="AbortError"?new ir(`Sign-in unreachable (${new URL(t.deviceEndpoint).hostname} timed out). Check your network and retry.`):A}if(!u.ok)throw new ir(`Device authorization failed to start (HTTP ${u.status}).`);let d;try{d=JSON.parse(u.text)}catch{throw new ir("Device authorization returned an unreadable response.")}if(!d.device_code||!d.user_code||!d.verification_uri)throw new ir("Device authorization response is missing required fields.");if(!vG(d.verification_uri))throw new ir("Sign-in aborted: the provider returned a suspicious verification URL \u2014 refusing to open or display it.");let p=vG(d.verification_uri_complete)?d.verification_uri_complete:d.verification_uri;i(`\u2192 Opening ${oe(d.verification_uri)} in your browser${t.label?` (${t.label})`:""}`),i(`\u2192 If asked, enter the code: ${oe(d.user_code)}`),i("\u2192 Waiting for you to approve in the browser \u2026 (Ctrl+C to cancel)"),i(""),i(" Only enter this code if you started 'aii login' yourself \u2014 never from a link someone sent you.");try{n(p)}catch{i(" (Could not open a browser here \u2014 open the URL above on any device.)")}let f=Math.max(1,d.interval??kot)*1e3,m=Number.isFinite(d.expires_in)&&d.expires_in>0?d.expires_in:wot,h=o()+m*1e3;for(;;){kG(a);try{let A=await l(t.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:d.device_code,client_id:t.clientId}),_;try{_=JSON.parse(A.text)}catch{_={}}if(A.ok&&typeof _.access_token=="string"&&_.access_token.length>0)return _;switch(_.error){case"authorization_pending":break;case"slow_down":f+=vot;break;case"access_denied":throw new ir("Sign-in declined in the browser \u2014 nothing was saved.");case"expired_token":throw new ir("The sign-in code expired. Run the command again to retry.");case void 0:break;default:throw new ir(`Sign-in failed (${oe(String(_.error))}${_.error_description?`: ${oe(String(_.error_description))}`:""}).`)}}catch(A){if(A instanceof ir||A instanceof ni)throw A}if(o()>=h)throw new ir("Timed out waiting for sign-in. Run the command again to retry.");await s(f),kG(a)}}var ir,ni,wot,kot,vot,ER=T(()=>{"use strict";Mt();ir=class extends Error{constructor(e){super(e),this.name="ProviderAuthError"}},ni=class extends Error{constructor(e="Sign-in cancelled \u2014 nothing was saved."){super(e),this.name="ProviderAuthCancelled"}},wot=300,kot=5,vot=5e3});function Rpe(t,e){kpe.has(e)||(kpe.add(e),t(e))}function vpe(t){try{let e=t.split(".");return e.length!==3?void 0:JSON.parse(Buffer.from(e[1],"base64url").toString("utf-8"))}catch{return}}async function yR(t,e,r={},n=Zd){let s=r.now??(()=>Date.now());if(!e||typeof e.access_token!="string"||e.access_token.length===0)throw new ir("Refusing to persist an incomplete token response.");let o=s()/1e3,i;if(typeof e.expires_in=="number"&&Number.isFinite(e.expires_in)&&e.expires_in>0)i=o+e.expires_in;else{let c=Number(vpe(e.access_token)?.exp);i=Number.isFinite(c)&&c>o?c:o+Rot}let a;if(e.id_token){let c=vpe(e.id_token),l=c?.email??c?.preferred_username??c?.sub;if(typeof l=="string"){let u=oe(l).trim();u&&(a=u)}}await t.setSecret(n.keys.access,e.access_token),e.refresh_token&&await t.setSecret(n.keys.refresh,e.refresh_token),await t.setSecret(n.keys.expiry,String(i)),await t.setSecret(n.keys.refreshedAt,String(o)),a&&await t.setSecret(n.keys.account,a),t.getSecret(n.keys.dead)&&await t.setSecret(n.keys.dead,"")}async function Dpe(t,e,r){await t.setSecret(r.keys.dead,"1"),await t.setSecret(r.keys.access,""),await t.setSecret(r.keys.expiry,""),Rpe(e,r.pl04Line)}async function Lm(t,e={},r={},n=Zd){let s=e.now??(()=>Date.now()),o=e.print??(_=>process.stdout.write(_+`
|
|
355
|
-
`)),i=n.provider==="openai"?"OpenAI":"xAI";if(t.getSecret(n.keys.dead)==="1")return Rpe(o,n.pl04Line),{status:"dead"};let a=t.getSecret(n.keys.access),c=t.getSecret(n.keys.refresh);if(!a&&!c)return{status:"none"};let l=s()/1e3,u=Number(t.getSecret(n.keys.expiry)),d=!!a&&Number.isFinite(u)&&l<u;if(!!a&&Number.isFinite(u)&&l<u-Dot&&!r.force)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};if(!c)return d?{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)}:(await Dpe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await Mm(f,n.tokenEndpoint,{grant_type:"refresh_token",refresh_token:c,client_id:n.clientId},m)}catch{if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (network error). Check your connection and retry.`)}let A;try{A=JSON.parse(h.text)}catch{A={}}if(h.ok&&typeof A.access_token=="string"&&A.access_token.length>0)return await yR(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};if(A.error==="invalid_grant")return await Dpe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (${A.error?oe(String(A.error)):`HTTP ${h.status}`}).`)}var Dot,Rot,kpe,xb=T(()=>{"use strict";ER();Oi();Oi();Mt();Dot=120,Rot=3600,kpe=new Set});function Bb(t){return t?t===mR||I_(t)?!0:hR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function Npe(t){if(t)try{let e=Te();return e.reloadSecretsSync(),Fue().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function CR(t=Zd,e){let r=RG.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=Te();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await Lm(s,{print:()=>{}},{force:!0},t);return i.status==="ok"?{status:"ok",accessToken:i.accessToken}:i.status==="dead"?{status:"dead"}:{status:"unavailable"}}catch{return{status:"unavailable"}}})().finally(()=>{RG.delete(t.provider)});return RG.set(t.provider,n),n}var RG,NG=T(()=>{"use strict";ht();xb();T_();u_();et();u_();RG=new Map});function Ope(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function SR(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:Ope(t.protocol_version)}}function bR(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 AiiCloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --inference server.",insufficient_credits:"Out of AiiCloud credits.",quota_exceeded:"Daily free-tier budget reached on AiiCloud.",quota_check_failed:"AiiCloud could not verify your quota \u2014 please retry.",worker_unavailable:"AiiCloud is temporarily unavailable \u2014 please retry, or run with --inference server."}[e]??`AiiCloud error: ${e}`}function Pm(t){switch((t??"").toLowerCase()){case"quota_exceeded":case"insufficient_credits":return"budget_exhausted";case"worker_unavailable":case"quota_check_failed":return"transient";default:return"fatal"}}function IR(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function OG(t){return t==null||typeof t=="object"}function wR(t){switch(t.type){case"tool_request":return OG(t.input);case"mcp_tool_request":return OG(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&OG(r.input))}default:return!0}}function kR(t){return Ope(t)>2?"hard":"compatible"}function vR(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 bs,xpe,Bpe,TR,hu=T(()=>{"use strict";bs=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};xpe=new Set(["token","complete","error","purpose_ack","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),Bpe=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"]),TR=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function Mpe(t,e){e?Fm.set(t,e):Fm.delete(t)}function Qi(t,e){e?DR.add(t):DR.delete(t)}function BG(t,e){e?xG.set(t,e):xG.delete(t)}function Ppe(t,e){Lpe.set(t,e)}function Fpe(t,e){return Lpe.get(t)?.(e)??!1}function Qpe(t){let e=Fm.get(t);e&&!e.attempted&&!e.blocked&&MG(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),Fm.delete(t)}function MG(t,e){let r=Fm.get(t);r&&LG(r,e)}function LG(t,e){t.started||t.attempted||(t.blocked=!0,t.send({type:"session_prompt_execution",task_id:t.taskId,device_id:t.deviceId,prompt_id:t.promptId,execution_state:"not_run",execution_reason:e}))}var Fm,DR,xG,Fi,RR,NR,OR,si,Lpe,Ui=T(()=>{"use strict";Fm=new WeakMap,DR=new WeakSet,xG=new WeakMap,Fi=t=>Fm.get(t);RR=t=>DR.has(t);NR=t=>Fm.has(t)||DR.has(t),OR=t=>xG.get(t);si=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},Lpe=new WeakMap});import{createHash as Not}from"node:crypto";function Fot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Oot.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function Qot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=0;for(;r<e.length&&(e[r]==="sudo"||e[r]==="env"||/^\w+=/.test(e[r]));)r++;let n=e[r]?e[r].split("/").pop()??"":"",s=e[r+1]??"";return!!(n==="xargs"||n==="make"||n==="git"&&s==="config"||(n==="docker"||n==="podman")&&(s==="run"||s==="exec"||s==="create")||n==="find"&&e.some(o=>Pot.includes(o)))}function Upe(t,e){return PG(t,e)===null}function PG(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return xot.test(r)?Mot.test(r)?"substitution":Lot.test(r)?"chained":"redirection":Bot.test(r)?"injection-flag":Qot(r)?"second-action":null}function Uot(t){try{return String(t)}catch{return"~unstringifiable"}}function w_(t,e){if(t===null)return"null";let r=typeof t;if(r==="undefined")return"~undef";if(r==="bigint")return`~big:${t.toString()}`;if(r==="number"){let n=t;return Number.isFinite(n)?JSON.stringify(n):`~num:${String(n)}`}if(r==="boolean"||r==="string")return JSON.stringify(t);if(r==="function"||r==="symbol")return`~${r}`;if(typeof t=="object"){let n=t;if(e.has(n))return"~cycle";e.add(n);try{if(Array.isArray(n))return`[${n.map(a=>w_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${w_(c,e)}=>${w_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>w_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${Uot(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${w_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function FG(t){return Not("sha256").update(w_(t??{},new WeakSet)).digest("hex").slice(0,16)}function QG(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return Fot(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Lt(s,r,n);return o.ok?`${t}:${Kn(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${FG(e)}`}function $pe(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?QG(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Oot,xot,Bot,Mot,Lot,Pot,UG=T(()=>{"use strict";Jn();Oot=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),xot=/[;&|<>`\n]|\$\(/,Bot=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,Mot=/[`]|\$\(/,Lot=/[;&|\n]/,Pot=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function xR(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function $G(t,e){return t!==void 0&&t>=0&&t<e?t:0}function Gpe(t,e){return{selectedIndex:$G(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var GG=T(()=>{"use strict"});var $ot,Got,Hot,Yot,qot,zot,Wot,Qm,BR,dp,HG=T(()=>{"use strict";we();$ot={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:g.hex("#3B82F6"),userInput:g.hex("#3B82F6"),userInputText:g.hex("#93C5FD"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#A855F7"),link:g.hex("#3B82F6").underline,heading:g.hex("#A855F7").bold,filePath:g.hex("#3B82F6"),indicator:g.hex("#3B82F6")}},Got={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#4E6BF5"),userInput:g.hex("#4E6BF5"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#4E6BF5"),link:g.hex("#4E6BF5").underline,heading:g.hex("#4E6BF5").bold,filePath:g.hex("#4E6BF5"),indicator:g.hex("#4E6BF5")}},Hot={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:g.hex("#00BCD4"),userInput:g.hex("#00BCD4"),userInputText:g.hex("#67E8F9"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#00BCD4"),link:g.hex("#00BCD4").underline,heading:g.hex("#00BCD4").bold,filePath:g.hex("#00BCD4"),indicator:g.hex("#00BCD4")}},Yot={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#6B8AFF"),userInput:g.hex("#6B8AFF"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#6B8AFF"),link:g.hex("#6B8AFF").underline,heading:g.hex("#6B8AFF").bold,filePath:g.hex("#6B8AFF"),indicator:g.hex("#6B8AFF")}},qot={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:g.hex("#22C55E"),userInput:g.hex("#22C55E"),userInputText:g.hex("#86EFAC"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#22C55E"),link:g.hex("#22C55E").underline,heading:g.hex("#22C55E").bold,filePath:g.hex("#22C55E"),indicator:g.hex("#22C55E")}},zot={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:g.hex("#F59E0B"),userInput:g.hex("#F59E0B"),userInputText:g.hex("#FCD34D"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#F59E0B"),link:g.hex("#F59E0B").underline,heading:g.hex("#F59E0B").bold,filePath:g.hex("#F59E0B"),indicator:g.hex("#F59E0B")}},Wot={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:g.reset,userInput:g.reset,userInputText:g.hex("#CBD5E1"),success:g.reset,warning:g.reset,error:g.bold,muted:g.dim,dim:g.dim,code:g.reset,link:g.underline,heading:g.bold,filePath:g.reset,indicator:g.bold}},Qm={classic:$ot,brand:Got,teal:Hot,indigo:Yot,forest:qot,amber:zot,grayscale:Wot},BR="classic",dp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Um={};de(Um,{BAND_STYLE_INFO:()=>Mb,BAND_STYLE_ORDER:()=>pp,DEFAULT_BAND_STYLE:()=>qG,ThemeManager:()=>Ua,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>v_,resolveBandBg:()=>k_});function k_(t,e){let r=Mb[t];if(r.blend===null)return Vot;let n=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(n.replace("#",""),16),o=r.blend,i=(a,c)=>Math.round(a*o+c*(1-o));return"#"+(i(s>>16&255,YG[0])<<16|i(s>>8&255,YG[1])<<8|i(s&255,YG[2])).toString(16).padStart(6,"0")}function J(){return Ua.getInstance().getColors()}function $e(){return Ua.getInstance().getAccentColorName()}function v_(){return Ua.getInstance().getUserInputTextColorName()}var pp,Mb,qG,YG,Vot,Ua,fp=T(()=>{"use strict";HG();ht();pp=["subtle","themed","neutral","bold"],Mb={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"}},qG="themed",YG=[20,22,27],Vot="#262C34";Ua=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Qm[BR]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=Qm[e];if(!r){let n=dp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in Qm}getAvailableThemes(){return dp.map(e=>Qm[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Te().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=qG,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${pp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return pp.includes(e)}reset(){this.activeTheme=Qm[BR],this.bandStyle=null}}});var Yt=T(()=>{"use strict";HG();fp()});import{resolve as jot}from"path";function Kot(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return process.stdout.isTTY?e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function Lb(){return zG===null&&(zG=Kot()),zG}function Jot(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Ype(){return Hpe||!Lb()?"":(Hpe=!0,` (${Jot()}+Click to open)`)}function Xot(t,e){return Lb()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function qpe(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",s=t;n&&t.startsWith(n)&&(s="~"+t.slice(n.length));let o=r??(e?`${s}:${e}`:s);if(!Lb())return J().filePath(o);let i=J().accent(o),c=`file://${jot(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Xot(i,c)}var zG,Hpe,zpe=T(()=>{"use strict";Yt();zG=null,Hpe=!1});function Zot(t){return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=183984&&t<=191471||t>=196608&&t<=201551||t>=63744&&t<=64255||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12784&&t<=12799||t>=44032&&t<=55215||t>=4352&&t<=4607||t>=12592&&t<=12687||t>=65280&&t<=65519&&(t>=65281&&t<=65376||t>=65504&&t<=65510)||t>=12288&&t<=12351||t>=12800&&t<=13055||t>=13056&&t<=13311||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=128512&&t<=128591||t>=128640&&t<=128767||t>=129648&&t<=129791||t>=9984&&t<=10175||t>=9728&&t<=9983}function eit(t){return t<32&&t!==9||t===127||t>=768&&t<=879||t>=6832&&t<=6911||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65056&&t<=65071||t===8203||t===8204||t===8205||t===65279||t>=65024&&t<=65039||t>=917760&&t<=917999}function Sn(t){let e=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),r=0;for(let n of e){let s=n.codePointAt(0)??0;eit(s)||(Zot(s)?r+=2:r+=1)}return r}function Vc(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Sn(s);if(r+o>e)break;n+=s,r+=o}return n}var $m=T(()=>{"use strict"});function VG(t){return t.replace(WG,"")}function tit(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function $a(t){return VG(oe(tit(t??"")))}var WG,mp=T(()=>{"use strict";Mt();WG=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var Kpe={};de(Kpe,{VERSION:()=>Gm,colors:()=>F,formatCode:()=>dit,formatPath:()=>jpe,getActionIndicator:()=>uit,padEndAnsi:()=>hit,printDivider:()=>Vpe,printError:()=>cit,printExitSummary:()=>KG,printHeader:()=>lit,printSuccess:()=>iit,printToolResultCompact:()=>Ga,printWarning:()=>ait,shortenPath:()=>fit});function rit(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 oit(t){return sit.test(t)}function Ga(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?F.success("\u25CF"):F.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=rit(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=$a(d),f=Sn(t)+6+i,m=Math.max(nit,(a.columns||80)-f),A=Sn(p)>m?Vc(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!oit(e)&&_;if(E){let C=e.match(/:(\d+)$/),w=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=jpe(k,w,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?F.dim(Ype()):"",S=o&&!y&&!Wpe?F.dim(" (ctrl+o to expand)"):"";if(S&&(Wpe=!0),n){let C=r?F.dim:F.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",w=r?F.dim:F.error;s(w(`\u2514 ${C}`)+y+S)}}function iit(t){console.log(F.success("\u2713 ")+t)}function ait(t){console.log(F.warning("\u26A0 ")+t)}function cit(t){console.log(F.error("\u2717 ")+t)}function Vpe(t=60){console.log(F.dim("\u2500".repeat(t)))}function lit(t){console.log(F.logo(t)),Vpe(t.length)}function uit(t){return F.thinking(`[${t}]`)}function jpe(t,e,r){if(Lb())return qpe(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",s=t;return n&&t.startsWith(n)&&(s="~"+t.slice(n.length)),e&&(s+=`:${e}`),F.filePath(r??s)}function dit(t){return F.code(t)}function pit(){return process.stdout.columns||80}function fit(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function mit(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hit(t,e){let r=mit(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function git(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function jG(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function KG(t){let e=pit(),r=Math.min(e-2,76),n=r-4,s=(A,_)=>{let E=A.replace(/\x1b\[[0-9;]*m/g,"").length;return A+" ".repeat(Math.max(0,_-E))},o=A=>F.border("\u2502")+" "+s(A,n)+" "+F.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=F.dim(A.padEnd(15))+_,w=F.dim(E.padEnd(15))+y;return o(s(C,S)+w)},a=git(t.durationSeconds),c=jG(t.tokensIn),l=jG(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(F.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(F.logo("Session complete. \u{1FABC}"))),console.log(F.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(F.logo("Session Summary"))),console.log(o(F.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(F.logo("Token Usage"))),console.log(o(F.dim("\u2500".repeat(11)))),console.log(i("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let A=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(F.dim("Cached".padEnd(15))+`${jG(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?F.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(F.dim("Cost".padEnd(15))+u+m)),console.log(o(""));let h=(A,_)=>A.length>_?`${A.slice(0,Math.max(0,_-1))}\u2026`:A;if(t.goalLine){let A=t.goalLine.replace(/^Goal:\s*/,"");console.log(o(F.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(F.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(F.dim("Model: ")+F.model(d))),console.log(F.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Gm,F,nit,sit,Wpe,Qr=T(()=>{"use strict";we();zpe();Yt();$m();mp();Gm="0.25.5",F={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}};nit=24,sit=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Wpe=!1});var XG={};de(XG,{MAX_RETAINED_TOASTS:()=>JG,MAX_VISIBLE_TOASTS:()=>Pb,getNotificationStore:()=>ot,useNotificationStore:()=>Fn});import{create as Ait}from"zustand";function Jpe(t){return t.length<=JG?t:t.slice(-JG)}var Pb,JG,Fn,ot,jc=T(()=>{"use strict";Pb=5,JG=200;Fn=Ait((t,e)=>({toasts:[],nextId:1,showToast:(r,n=!1,s)=>{t(o=>{let i={id:o.nextId,text:r,persistent:n,expiresAt:s};if(!n){let c=o.toasts.filter(l=>l.persistent);return{toasts:Jpe([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Jpe([...a,i]),nextId:o.nextId+1}})},clearToast:r=>{t(n=>r===void 0?{toasts:[]}:{toasts:n.toasts.filter(s=>s.id!==r)})},clearPersistent:()=>{t(r=>({toasts:r.toasts.filter(n=>!n.persistent)}))},clearFirstPersistent:()=>{t(r=>{let n=r.toasts.findIndex(s=>s.persistent);return n===-1?r:{toasts:[...r.toasts.slice(0,n),...r.toasts.slice(n+1)]}})},reset:()=>t({toasts:[],nextId:1}),visibleToasts:()=>e().toasts.slice(0,Pb),overflowCount:()=>Math.max(0,e().toasts.length-Pb)}));Object.defineProperty(Fn,"toast",{get:()=>{let t=Fn.getState().toasts;return t.length>0?t[t.length-1]:null}});ot=Fn.getState});var Zpe={};de(Zpe,{getUserEchoSink:()=>ZG,setUserEchoSink:()=>_it});function _it(t){Xpe=t}function ZG(){return Xpe}var Xpe,e8=T(()=>{"use strict";Xpe=null});import{create as Eit}from"zustand";var efe,Hm,MR=T(()=>{"use strict";jc();e8();efe=Eit((t,e)=>({pendingNote:null,pendingOrigin:"keyboard",noteToastId:null,setPendingNote:r=>t({pendingNote:r,pendingOrigin:"keyboard",onRemoteConsume:void 0}),offerRemoteNote:(r,n)=>e().pendingNote?!1:(t({pendingNote:r,pendingOrigin:"remote",onRemoteConsume:n}),!0),setNoteToastId:r=>t({noteToastId:r}),getPendingNote:()=>e().pendingNote,onNoteInjected:()=>{let r=e().pendingNote,n=e().pendingOrigin;r&&n==="remote"&&e().onRemoteConsume?.();let s=e().noteToastId;if(s!==null&&ot().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=ZG();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),Hm=efe.getState});import{create as yit}from"zustand";var D_,cn,Ym=T(()=>{"use strict";D_=null,cn=yit((t,e)=>({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:null,begin:r=>{t({active:!0,startedAt:Date.now(),bgAgentCount:r,elapsedSec:0,lastRelease:null}),D_!==null&&clearInterval(D_),D_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{D_!==null&&(clearInterval(D_),D_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var LR={};de(LR,{getUIStore:()=>yt,useUIStore:()=>bo});import{create as Cit}from"zustand";var tfe,bo,yt,hp=T(()=>{"use strict";tfe={mode:"welcome",agentMode:"normal",status:"",isThinking:!1,isStreaming:!1,currentIteration:0,iterationStartTime:Date.now(),iterationTokens:0,contextPercent:0,contextLevel:"normal",contextTokens:0,contextLimit:2e5,sessionCost:0,freeBudgetRemaining:null,freeBudgetResetAt:null,goalSegment:"",goalTurnActive:!1,sessionTokensIn:0,sessionCachedTokens:0,provider:"",model:"",reasoningEffort:"",openrouterProvider:"",connectionMode:"local",projectPath:process.cwd(),branch:void 0,worktreeName:void 0,baseBranch:void 0,soulName:"",personaName:"",toolsCount:0,mcpServersCount:0,mcpFailedCount:0,contextFilesCount:0,skillsCount:0,sessionStartTime:Date.now(),agentExecMs:0,agentTurnStartTime:null,renderEpoch:0,loopMode:!1,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0},bo=Cit(t=>({...tfe,setMode:e=>t({mode:e}),setAgentMode:e=>t({agentMode:e}),setStatus:e=>t({status:e}),setThinking:e=>t({isThinking:e}),setStreaming:e=>t(r=>{if(e&&!r.agentTurnStartTime)return{isStreaming:e,agentTurnStartTime:Date.now()};if(!e&&r.agentTurnStartTime){let n=Date.now()-r.agentTurnStartTime;return{isStreaming:e,agentExecMs:r.agentExecMs+n,agentTurnStartTime:null}}return{isStreaming:e}}),incrementIteration:()=>t(e=>({currentIteration:e.currentIteration+1,iterationStartTime:Date.now(),iterationTokens:0})),addIterationTokens:e=>t(r=>({iterationTokens:r.iterationTokens+e})),setIterationTokens:e=>t({iterationTokens:e}),updateContext:(e,r)=>{let n=r>0?Math.round(e/r*100):0,s=n>=90?"critical":n>=70?"warning":"normal";t({contextTokens:e,contextLimit:r,contextPercent:n,contextLevel:s})},updateSession:e=>t(e),updateResources:e=>t(e),setLoopMode:e=>t(e?{loopMode:e}:{loopMode:e,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0}),startLoop:(e,r)=>t({loopStartTime:e,loopMaxIterations:r,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0}),updateLoopStats:(e,r,n,s)=>t({loopTotalInputTokens:e,loopTotalOutputTokens:r,loopCost:n,loopToolCalls:s}),setLoopIteration:e=>t({loopCurrentIteration:e}),setLoopPaused:(e,r)=>t({loopPaused:e,loopPauseUntil:r}),setLoopDurationSeconds:e=>t({loopDurationSeconds:e}),incrementRenderEpoch:()=>t(e=>({renderEpoch:e.renderEpoch+1})),reset:()=>t(tfe)})),yt=bo.getState});var Fb={};de(Fb,{getInputStore:()=>R_,useInputStore:()=>Xn});import{create as Sit}from"zustand";var rfe,bit,Iit,Xn,R_,gu=T(()=>{"use strict";we();jc();hp();rfe={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},bit=100,Iit=50,Xn=Sit((t,e)=>({...rfe,insertChar:r=>{e().saveSnapshot(),t(s=>{let o=[...s.lines],i=o[s.cursorLine];return o[s.cursorLine]=i.slice(0,s.cursorCol)+r+i.slice(s.cursorCol),{lines:o,cursorCol:s.cursorCol+r.length,redoStack:[]}})},deleteChar:()=>{let r=e();r.cursorCol===0&&r.cursorLine===0||(r.saveSnapshot(),t(n=>{let s=[...n.lines];if(n.cursorCol>0){let o=s[n.cursorLine];return s[n.cursorLine]=o.slice(0,n.cursorCol-1)+o.slice(n.cursorCol),{lines:s,cursorCol:n.cursorCol-1,redoStack:[]}}else if(n.cursorLine>0){let o=s[n.cursorLine-1],i=s[n.cursorLine];return s[n.cursorLine-1]=o+i,s.splice(n.cursorLine,1),{lines:s,cursorLine:n.cursorLine-1,cursorCol:o.length,redoStack:[]}}return n}))},newLine:()=>{e().saveSnapshot(),t(n=>{let s=[...n.lines],o=s[n.cursorLine],i=o.slice(0,n.cursorCol),a=o.slice(n.cursorCol);return s[n.cursorLine]=i,s.splice(n.cursorLine+1,0,a),{lines:s,cursorLine:n.cursorLine+1,cursorCol:0,redoStack:[]}})},moveCursor:r=>{t(n=>{switch(r){case"left":if(n.cursorCol>0)return{cursorCol:n.cursorCol-1};if(n.cursorLine>0)return{cursorLine:n.cursorLine-1,cursorCol:n.lines[n.cursorLine-1].length};break;case"right":if(n.cursorCol<n.lines[n.cursorLine].length)return{cursorCol:n.cursorCol+1};if(n.cursorLine<n.lines.length-1)return{cursorLine:n.cursorLine+1,cursorCol:0};break;case"up":if(n.cursorLine>0){let s=n.cursorLine-1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break;case"down":if(n.cursorLine<n.lines.length-1){let s=n.cursorLine+1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break}return n})},setText:r=>{let n=r.split(`
|
|
355
|
+
`)),i=n.provider==="openai"?"OpenAI":"xAI";if(t.getSecret(n.keys.dead)==="1")return Rpe(o,n.pl04Line),{status:"dead"};let a=t.getSecret(n.keys.access),c=t.getSecret(n.keys.refresh);if(!a&&!c)return{status:"none"};let l=s()/1e3,u=Number(t.getSecret(n.keys.expiry)),d=!!a&&Number.isFinite(u)&&l<u;if(!!a&&Number.isFinite(u)&&l<u-Dot&&!r.force)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};if(!c)return d?{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)}:(await Dpe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await Mm(f,n.tokenEndpoint,{grant_type:"refresh_token",refresh_token:c,client_id:n.clientId},m)}catch{if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (network error). Check your connection and retry.`)}let A;try{A=JSON.parse(h.text)}catch{A={}}if(h.ok&&typeof A.access_token=="string"&&A.access_token.length>0)return await yR(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};if(A.error==="invalid_grant")return await Dpe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (${A.error?oe(String(A.error)):`HTTP ${h.status}`}).`)}var Dot,Rot,kpe,xb=T(()=>{"use strict";ER();Oi();Oi();Mt();Dot=120,Rot=3600,kpe=new Set});function Bb(t){return t?t===mR||I_(t)?!0:hR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function Npe(t){if(t)try{let e=Te();return e.reloadSecretsSync(),Fue().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function CR(t=Zd,e){let r=RG.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=Te();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await Lm(s,{print:()=>{}},{force:!0},t);return i.status==="ok"?{status:"ok",accessToken:i.accessToken}:i.status==="dead"?{status:"dead"}:{status:"unavailable"}}catch{return{status:"unavailable"}}})().finally(()=>{RG.delete(t.provider)});return RG.set(t.provider,n),n}var RG,NG=T(()=>{"use strict";ht();xb();T_();u_();et();u_();RG=new Map});function Ope(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function SR(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:Ope(t.protocol_version)}}function bR(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 AiiCloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --inference server.",insufficient_credits:"Out of AiiCloud credits.",quota_exceeded:"Daily free-tier budget reached on AiiCloud.",quota_check_failed:"AiiCloud could not verify your quota \u2014 please retry.",worker_unavailable:"AiiCloud is temporarily unavailable \u2014 please retry, or run with --inference server."}[e]??`AiiCloud error: ${e}`}function Pm(t){switch((t??"").toLowerCase()){case"quota_exceeded":case"insufficient_credits":return"budget_exhausted";case"worker_unavailable":case"quota_check_failed":return"transient";default:return"fatal"}}function IR(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function OG(t){return t==null||typeof t=="object"}function wR(t){switch(t.type){case"tool_request":return OG(t.input);case"mcp_tool_request":return OG(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&OG(r.input))}default:return!0}}function kR(t){return Ope(t)>2?"hard":"compatible"}function vR(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 bs,xpe,Bpe,TR,hu=T(()=>{"use strict";bs=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};xpe=new Set(["token","complete","error","purpose_ack","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),Bpe=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"]),TR=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function Mpe(t,e){e?Fm.set(t,e):Fm.delete(t)}function Qi(t,e){e?DR.add(t):DR.delete(t)}function BG(t,e){e?xG.set(t,e):xG.delete(t)}function Ppe(t,e){Lpe.set(t,e)}function Fpe(t,e){return Lpe.get(t)?.(e)??!1}function Qpe(t){let e=Fm.get(t);e&&!e.attempted&&!e.blocked&&MG(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),Fm.delete(t)}function MG(t,e){let r=Fm.get(t);r&&LG(r,e)}function LG(t,e){t.started||t.attempted||(t.blocked=!0,t.send({type:"session_prompt_execution",task_id:t.taskId,device_id:t.deviceId,prompt_id:t.promptId,execution_state:"not_run",execution_reason:e}))}var Fm,DR,xG,Fi,RR,NR,OR,si,Lpe,Ui=T(()=>{"use strict";Fm=new WeakMap,DR=new WeakSet,xG=new WeakMap,Fi=t=>Fm.get(t);RR=t=>DR.has(t);NR=t=>Fm.has(t)||DR.has(t),OR=t=>xG.get(t);si=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},Lpe=new WeakMap});import{createHash as Not}from"node:crypto";function Fot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Oot.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function Qot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=0;for(;r<e.length&&(e[r]==="sudo"||e[r]==="env"||/^\w+=/.test(e[r]));)r++;let n=e[r]?e[r].split("/").pop()??"":"",s=e[r+1]??"";return!!(n==="xargs"||n==="make"||n==="git"&&s==="config"||(n==="docker"||n==="podman")&&(s==="run"||s==="exec"||s==="create")||n==="find"&&e.some(o=>Pot.includes(o)))}function Upe(t,e){return PG(t,e)===null}function PG(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return xot.test(r)?Mot.test(r)?"substitution":Lot.test(r)?"chained":"redirection":Bot.test(r)?"injection-flag":Qot(r)?"second-action":null}function Uot(t){try{return String(t)}catch{return"~unstringifiable"}}function w_(t,e){if(t===null)return"null";let r=typeof t;if(r==="undefined")return"~undef";if(r==="bigint")return`~big:${t.toString()}`;if(r==="number"){let n=t;return Number.isFinite(n)?JSON.stringify(n):`~num:${String(n)}`}if(r==="boolean"||r==="string")return JSON.stringify(t);if(r==="function"||r==="symbol")return`~${r}`;if(typeof t=="object"){let n=t;if(e.has(n))return"~cycle";e.add(n);try{if(Array.isArray(n))return`[${n.map(a=>w_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${w_(c,e)}=>${w_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>w_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${Uot(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${w_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function FG(t){return Not("sha256").update(w_(t??{},new WeakSet)).digest("hex").slice(0,16)}function QG(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return Fot(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Lt(s,r,n);return o.ok?`${t}:${Kn(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${FG(e)}`}function $pe(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?QG(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Oot,xot,Bot,Mot,Lot,Pot,UG=T(()=>{"use strict";Jn();Oot=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),xot=/[;&|<>`\n]|\$\(/,Bot=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,Mot=/[`]|\$\(/,Lot=/[;&|\n]/,Pot=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function xR(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function $G(t,e){return t!==void 0&&t>=0&&t<e?t:0}function Gpe(t,e){return{selectedIndex:$G(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var GG=T(()=>{"use strict"});var $ot,Got,Hot,Yot,qot,zot,Wot,Qm,BR,dp,HG=T(()=>{"use strict";we();$ot={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:g.hex("#3B82F6"),userInput:g.hex("#3B82F6"),userInputText:g.hex("#93C5FD"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#A855F7"),link:g.hex("#3B82F6").underline,heading:g.hex("#A855F7").bold,filePath:g.hex("#3B82F6"),indicator:g.hex("#3B82F6")}},Got={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#4E6BF5"),userInput:g.hex("#4E6BF5"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#4E6BF5"),link:g.hex("#4E6BF5").underline,heading:g.hex("#4E6BF5").bold,filePath:g.hex("#4E6BF5"),indicator:g.hex("#4E6BF5")}},Hot={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:g.hex("#00BCD4"),userInput:g.hex("#00BCD4"),userInputText:g.hex("#67E8F9"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#00BCD4"),link:g.hex("#00BCD4").underline,heading:g.hex("#00BCD4").bold,filePath:g.hex("#00BCD4"),indicator:g.hex("#00BCD4")}},Yot={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#6B8AFF"),userInput:g.hex("#6B8AFF"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#6B8AFF"),link:g.hex("#6B8AFF").underline,heading:g.hex("#6B8AFF").bold,filePath:g.hex("#6B8AFF"),indicator:g.hex("#6B8AFF")}},qot={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:g.hex("#22C55E"),userInput:g.hex("#22C55E"),userInputText:g.hex("#86EFAC"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#22C55E"),link:g.hex("#22C55E").underline,heading:g.hex("#22C55E").bold,filePath:g.hex("#22C55E"),indicator:g.hex("#22C55E")}},zot={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:g.hex("#F59E0B"),userInput:g.hex("#F59E0B"),userInputText:g.hex("#FCD34D"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#F59E0B"),link:g.hex("#F59E0B").underline,heading:g.hex("#F59E0B").bold,filePath:g.hex("#F59E0B"),indicator:g.hex("#F59E0B")}},Wot={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:g.reset,userInput:g.reset,userInputText:g.hex("#CBD5E1"),success:g.reset,warning:g.reset,error:g.bold,muted:g.dim,dim:g.dim,code:g.reset,link:g.underline,heading:g.bold,filePath:g.reset,indicator:g.bold}},Qm={classic:$ot,brand:Got,teal:Hot,indigo:Yot,forest:qot,amber:zot,grayscale:Wot},BR="classic",dp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Um={};de(Um,{BAND_STYLE_INFO:()=>Mb,BAND_STYLE_ORDER:()=>pp,DEFAULT_BAND_STYLE:()=>qG,ThemeManager:()=>Ua,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>v_,resolveBandBg:()=>k_});function k_(t,e){let r=Mb[t];if(r.blend===null)return Vot;let n=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(n.replace("#",""),16),o=r.blend,i=(a,c)=>Math.round(a*o+c*(1-o));return"#"+(i(s>>16&255,YG[0])<<16|i(s>>8&255,YG[1])<<8|i(s&255,YG[2])).toString(16).padStart(6,"0")}function J(){return Ua.getInstance().getColors()}function $e(){return Ua.getInstance().getAccentColorName()}function v_(){return Ua.getInstance().getUserInputTextColorName()}var pp,Mb,qG,YG,Vot,Ua,fp=T(()=>{"use strict";HG();ht();pp=["subtle","themed","neutral","bold"],Mb={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"}},qG="themed",YG=[20,22,27],Vot="#262C34";Ua=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Qm[BR]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=Qm[e];if(!r){let n=dp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in Qm}getAvailableThemes(){return dp.map(e=>Qm[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Te().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=qG,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${pp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return pp.includes(e)}reset(){this.activeTheme=Qm[BR],this.bandStyle=null}}});var Yt=T(()=>{"use strict";HG();fp()});import{resolve as jot}from"path";function Kot(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return process.stdout.isTTY?e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function Lb(){return zG===null&&(zG=Kot()),zG}function Jot(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Ype(){return Hpe||!Lb()?"":(Hpe=!0,` (${Jot()}+Click to open)`)}function Xot(t,e){return Lb()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function qpe(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",s=t;n&&t.startsWith(n)&&(s="~"+t.slice(n.length));let o=r??(e?`${s}:${e}`:s);if(!Lb())return J().filePath(o);let i=J().accent(o),c=`file://${jot(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Xot(i,c)}var zG,Hpe,zpe=T(()=>{"use strict";Yt();zG=null,Hpe=!1});function Zot(t){return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=183984&&t<=191471||t>=196608&&t<=201551||t>=63744&&t<=64255||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12784&&t<=12799||t>=44032&&t<=55215||t>=4352&&t<=4607||t>=12592&&t<=12687||t>=65280&&t<=65519&&(t>=65281&&t<=65376||t>=65504&&t<=65510)||t>=12288&&t<=12351||t>=12800&&t<=13055||t>=13056&&t<=13311||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=128512&&t<=128591||t>=128640&&t<=128767||t>=129648&&t<=129791||t>=9984&&t<=10175||t>=9728&&t<=9983}function eit(t){return t<32&&t!==9||t===127||t>=768&&t<=879||t>=6832&&t<=6911||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65056&&t<=65071||t===8203||t===8204||t===8205||t===65279||t>=65024&&t<=65039||t>=917760&&t<=917999}function Sn(t){let e=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),r=0;for(let n of e){let s=n.codePointAt(0)??0;eit(s)||(Zot(s)?r+=2:r+=1)}return r}function Vc(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Sn(s);if(r+o>e)break;n+=s,r+=o}return n}var $m=T(()=>{"use strict"});function VG(t){return t.replace(WG,"")}function tit(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function $a(t){return VG(oe(tit(t??"")))}var WG,mp=T(()=>{"use strict";Mt();WG=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var Kpe={};de(Kpe,{VERSION:()=>Gm,colors:()=>F,formatCode:()=>dit,formatPath:()=>jpe,getActionIndicator:()=>uit,padEndAnsi:()=>hit,printDivider:()=>Vpe,printError:()=>cit,printExitSummary:()=>KG,printHeader:()=>lit,printSuccess:()=>iit,printToolResultCompact:()=>Ga,printWarning:()=>ait,shortenPath:()=>fit});function rit(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 oit(t){return sit.test(t)}function Ga(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?F.success("\u25CF"):F.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=rit(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=$a(d),f=Sn(t)+6+i,m=Math.max(nit,(a.columns||80)-f),A=Sn(p)>m?Vc(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!oit(e)&&_;if(E){let C=e.match(/:(\d+)$/),w=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=jpe(k,w,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?F.dim(Ype()):"",S=o&&!y&&!Wpe?F.dim(" (ctrl+o to expand)"):"";if(S&&(Wpe=!0),n){let C=r?F.dim:F.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",w=r?F.dim:F.error;s(w(`\u2514 ${C}`)+y+S)}}function iit(t){console.log(F.success("\u2713 ")+t)}function ait(t){console.log(F.warning("\u26A0 ")+t)}function cit(t){console.log(F.error("\u2717 ")+t)}function Vpe(t=60){console.log(F.dim("\u2500".repeat(t)))}function lit(t){console.log(F.logo(t)),Vpe(t.length)}function uit(t){return F.thinking(`[${t}]`)}function jpe(t,e,r){if(Lb())return qpe(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",s=t;return n&&t.startsWith(n)&&(s="~"+t.slice(n.length)),e&&(s+=`:${e}`),F.filePath(r??s)}function dit(t){return F.code(t)}function pit(){return process.stdout.columns||80}function fit(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function mit(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hit(t,e){let r=mit(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function git(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function jG(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function KG(t){let e=pit(),r=Math.min(e-2,76),n=r-4,s=(A,_)=>{let E=A.replace(/\x1b\[[0-9;]*m/g,"").length;return A+" ".repeat(Math.max(0,_-E))},o=A=>F.border("\u2502")+" "+s(A,n)+" "+F.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=F.dim(A.padEnd(15))+_,w=F.dim(E.padEnd(15))+y;return o(s(C,S)+w)},a=git(t.durationSeconds),c=jG(t.tokensIn),l=jG(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(F.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(F.logo("Session complete. \u{1FABC}"))),console.log(F.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(F.logo("Session Summary"))),console.log(o(F.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(F.logo("Token Usage"))),console.log(o(F.dim("\u2500".repeat(11)))),console.log(i("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let A=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(F.dim("Cached".padEnd(15))+`${jG(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?F.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(F.dim("Cost".padEnd(15))+u+m)),console.log(o(""));let h=(A,_)=>A.length>_?`${A.slice(0,Math.max(0,_-1))}\u2026`:A;if(t.goalLine){let A=t.goalLine.replace(/^Goal:\s*/,"");console.log(o(F.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(F.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(F.dim("Model: ")+F.model(d))),console.log(F.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Gm,F,nit,sit,Wpe,Qr=T(()=>{"use strict";we();zpe();Yt();$m();mp();Gm="0.25.6",F={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}};nit=24,sit=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Wpe=!1});var XG={};de(XG,{MAX_RETAINED_TOASTS:()=>JG,MAX_VISIBLE_TOASTS:()=>Pb,getNotificationStore:()=>ot,useNotificationStore:()=>Fn});import{create as Ait}from"zustand";function Jpe(t){return t.length<=JG?t:t.slice(-JG)}var Pb,JG,Fn,ot,jc=T(()=>{"use strict";Pb=5,JG=200;Fn=Ait((t,e)=>({toasts:[],nextId:1,showToast:(r,n=!1,s)=>{t(o=>{let i={id:o.nextId,text:r,persistent:n,expiresAt:s};if(!n){let c=o.toasts.filter(l=>l.persistent);return{toasts:Jpe([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Jpe([...a,i]),nextId:o.nextId+1}})},clearToast:r=>{t(n=>r===void 0?{toasts:[]}:{toasts:n.toasts.filter(s=>s.id!==r)})},clearPersistent:()=>{t(r=>({toasts:r.toasts.filter(n=>!n.persistent)}))},clearFirstPersistent:()=>{t(r=>{let n=r.toasts.findIndex(s=>s.persistent);return n===-1?r:{toasts:[...r.toasts.slice(0,n),...r.toasts.slice(n+1)]}})},reset:()=>t({toasts:[],nextId:1}),visibleToasts:()=>e().toasts.slice(0,Pb),overflowCount:()=>Math.max(0,e().toasts.length-Pb)}));Object.defineProperty(Fn,"toast",{get:()=>{let t=Fn.getState().toasts;return t.length>0?t[t.length-1]:null}});ot=Fn.getState});var Zpe={};de(Zpe,{getUserEchoSink:()=>ZG,setUserEchoSink:()=>_it});function _it(t){Xpe=t}function ZG(){return Xpe}var Xpe,e8=T(()=>{"use strict";Xpe=null});import{create as Eit}from"zustand";var efe,Hm,MR=T(()=>{"use strict";jc();e8();efe=Eit((t,e)=>({pendingNote:null,pendingOrigin:"keyboard",noteToastId:null,setPendingNote:r=>t({pendingNote:r,pendingOrigin:"keyboard",onRemoteConsume:void 0}),offerRemoteNote:(r,n)=>e().pendingNote?!1:(t({pendingNote:r,pendingOrigin:"remote",onRemoteConsume:n}),!0),setNoteToastId:r=>t({noteToastId:r}),getPendingNote:()=>e().pendingNote,onNoteInjected:()=>{let r=e().pendingNote,n=e().pendingOrigin;r&&n==="remote"&&e().onRemoteConsume?.();let s=e().noteToastId;if(s!==null&&ot().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=ZG();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),Hm=efe.getState});import{create as yit}from"zustand";var D_,cn,Ym=T(()=>{"use strict";D_=null,cn=yit((t,e)=>({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:null,begin:r=>{t({active:!0,startedAt:Date.now(),bgAgentCount:r,elapsedSec:0,lastRelease:null}),D_!==null&&clearInterval(D_),D_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{D_!==null&&(clearInterval(D_),D_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var LR={};de(LR,{getUIStore:()=>yt,useUIStore:()=>bo});import{create as Cit}from"zustand";var tfe,bo,yt,hp=T(()=>{"use strict";tfe={mode:"welcome",agentMode:"normal",status:"",isThinking:!1,isStreaming:!1,currentIteration:0,iterationStartTime:Date.now(),iterationTokens:0,contextPercent:0,contextLevel:"normal",contextTokens:0,contextLimit:2e5,sessionCost:0,freeBudgetRemaining:null,freeBudgetResetAt:null,goalSegment:"",goalTurnActive:!1,sessionTokensIn:0,sessionCachedTokens:0,provider:"",model:"",reasoningEffort:"",openrouterProvider:"",connectionMode:"local",projectPath:process.cwd(),branch:void 0,worktreeName:void 0,baseBranch:void 0,soulName:"",personaName:"",toolsCount:0,mcpServersCount:0,mcpFailedCount:0,contextFilesCount:0,skillsCount:0,sessionStartTime:Date.now(),agentExecMs:0,agentTurnStartTime:null,renderEpoch:0,loopMode:!1,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0},bo=Cit(t=>({...tfe,setMode:e=>t({mode:e}),setAgentMode:e=>t({agentMode:e}),setStatus:e=>t({status:e}),setThinking:e=>t({isThinking:e}),setStreaming:e=>t(r=>{if(e&&!r.agentTurnStartTime)return{isStreaming:e,agentTurnStartTime:Date.now()};if(!e&&r.agentTurnStartTime){let n=Date.now()-r.agentTurnStartTime;return{isStreaming:e,agentExecMs:r.agentExecMs+n,agentTurnStartTime:null}}return{isStreaming:e}}),incrementIteration:()=>t(e=>({currentIteration:e.currentIteration+1,iterationStartTime:Date.now(),iterationTokens:0})),addIterationTokens:e=>t(r=>({iterationTokens:r.iterationTokens+e})),setIterationTokens:e=>t({iterationTokens:e}),updateContext:(e,r)=>{let n=r>0?Math.round(e/r*100):0,s=n>=90?"critical":n>=70?"warning":"normal";t({contextTokens:e,contextLimit:r,contextPercent:n,contextLevel:s})},updateSession:e=>t(e),updateResources:e=>t(e),setLoopMode:e=>t(e?{loopMode:e}:{loopMode:e,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0}),startLoop:(e,r)=>t({loopStartTime:e,loopMaxIterations:r,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0}),updateLoopStats:(e,r,n,s)=>t({loopTotalInputTokens:e,loopTotalOutputTokens:r,loopCost:n,loopToolCalls:s}),setLoopIteration:e=>t({loopCurrentIteration:e}),setLoopPaused:(e,r)=>t({loopPaused:e,loopPauseUntil:r}),setLoopDurationSeconds:e=>t({loopDurationSeconds:e}),incrementRenderEpoch:()=>t(e=>({renderEpoch:e.renderEpoch+1})),reset:()=>t(tfe)})),yt=bo.getState});var Fb={};de(Fb,{getInputStore:()=>R_,useInputStore:()=>Xn});import{create as Sit}from"zustand";var rfe,bit,Iit,Xn,R_,gu=T(()=>{"use strict";we();jc();hp();rfe={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},bit=100,Iit=50,Xn=Sit((t,e)=>({...rfe,insertChar:r=>{e().saveSnapshot(),t(s=>{let o=[...s.lines],i=o[s.cursorLine];return o[s.cursorLine]=i.slice(0,s.cursorCol)+r+i.slice(s.cursorCol),{lines:o,cursorCol:s.cursorCol+r.length,redoStack:[]}})},deleteChar:()=>{let r=e();r.cursorCol===0&&r.cursorLine===0||(r.saveSnapshot(),t(n=>{let s=[...n.lines];if(n.cursorCol>0){let o=s[n.cursorLine];return s[n.cursorLine]=o.slice(0,n.cursorCol-1)+o.slice(n.cursorCol),{lines:s,cursorCol:n.cursorCol-1,redoStack:[]}}else if(n.cursorLine>0){let o=s[n.cursorLine-1],i=s[n.cursorLine];return s[n.cursorLine-1]=o+i,s.splice(n.cursorLine,1),{lines:s,cursorLine:n.cursorLine-1,cursorCol:o.length,redoStack:[]}}return n}))},newLine:()=>{e().saveSnapshot(),t(n=>{let s=[...n.lines],o=s[n.cursorLine],i=o.slice(0,n.cursorCol),a=o.slice(n.cursorCol);return s[n.cursorLine]=i,s.splice(n.cursorLine+1,0,a),{lines:s,cursorLine:n.cursorLine+1,cursorCol:0,redoStack:[]}})},moveCursor:r=>{t(n=>{switch(r){case"left":if(n.cursorCol>0)return{cursorCol:n.cursorCol-1};if(n.cursorLine>0)return{cursorLine:n.cursorLine-1,cursorCol:n.lines[n.cursorLine-1].length};break;case"right":if(n.cursorCol<n.lines[n.cursorLine].length)return{cursorCol:n.cursorCol+1};if(n.cursorLine<n.lines.length-1)return{cursorLine:n.cursorLine+1,cursorCol:0};break;case"up":if(n.cursorLine>0){let s=n.cursorLine-1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break;case"down":if(n.cursorLine<n.lines.length-1){let s=n.cursorLine+1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break}return n})},setText:r=>{let n=r.split(`
|
|
356
356
|
`);t({lines:n,cursorLine:n.length-1,cursorCol:n[n.length-1].length,undoStack:[],redoStack:[]})},clear:()=>{t({lines:[""],cursorLine:0,cursorCol:0,undoStack:[],redoStack:[]})},saveSnapshot:()=>{t(r=>{let n={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol},s=[...r.undoStack,n];return s.length>Iit&&s.shift(),{undoStack:s}})},undo:()=>{t(r=>{if(r.undoStack.length===0)return r;let n=[...r.undoStack],s=n.pop(),o={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol};return{lines:s.lines,cursorLine:s.cursorLine,cursorCol:s.cursorCol,undoStack:n,redoStack:[...r.redoStack,o]}})},redo:()=>{t(r=>{if(r.redoStack.length===0)return r;let n=[...r.redoStack],s=n.pop(),o={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol};return{lines:s.lines,cursorLine:s.cursorLine,cursorCol:s.cursorCol,undoStack:[...r.undoStack,o],redoStack:n}})},appendTypeAhead:r=>{t(n=>({typeAheadBuffer:n.typeAheadBuffer+r}))},getAndClearTypeAhead:()=>{let r=e().typeAheadBuffer;return t({typeAheadBuffer:""}),r},setTypeAheadActive:r=>{t({isTypeAheadActive:r})},enqueueTypeAhead:r=>{let n=e(),s=n.lines.join(`
|
|
357
357
|
`);if(s.trim()&&(n.addToHistory(s),t(o=>({typeAheadQueue:[...o.typeAheadQueue,{text:s,origin:"keyboard"}],lines:[""],cursorLine:0,cursorCol:0,undoStack:[],redoStack:[]})),!r?.silent)){let o=bo.getState().loopMode,i=o?"\u25C6 Queued for next iteration (/note injects now): ":"\u25C6 Queued: ",a=o?52:12,c=process.stdout.columns||80,l=Math.max(12,Math.floor(c*.618)-a),u=s.replace(/\n/g," "),d=u.length>l?u.slice(0,l)+"\u2026":u;Fn.getState().showToast(g.green(`${i}"${d}"`),!0)}},setRemoteDropHandler:r=>t({remoteDropHandler:r}),enqueueRemote:r=>e().typeAheadQueue.filter(n=>n.origin==="remote").length>=128?!1:(t(n=>({typeAheadQueue:[...n.typeAheadQueue,r]})),!0),dropRemote:(r,n="ctrl_x")=>{let s=e().typeAheadQueue.find(o=>o.origin==="remote"&&(!r||o.promptId===r));return s?(t(o=>({typeAheadQueue:o.typeAheadQueue.filter(i=>i!==s)})),e().remoteDropHandler?.(s,n),!0):!1},dropAllRemote:r=>{let n=e().typeAheadQueue.filter(s=>s.origin==="remote");t(s=>({typeAheadQueue:s.typeAheadQueue.filter(o=>o.origin!=="remote")}));for(let s of n)e().remoteDropHandler?.(s,r)},dequeueTypeAhead:()=>{let r=e().typeAheadQueue;if(r.length===0)return null;let[n,...s]=r;return t({typeAheadQueue:s}),n},hasQueuedMessages:()=>e().typeAheadQueue.length>0,clearTypeAheadQueue:(r="ctrl_u")=>{e().dropAllRemote(r),t({typeAheadQueue:[]}),Fn.getState().clearPersistent()},historyUp:()=>{t(r=>{if(r.history.length===0)return r;let n=r.historyIndex===-1?r.history.length-1:Math.max(0,r.historyIndex-1),o=r.history[n].split(`
|
|
358
358
|
`);return{historyIndex:n,lines:o,cursorLine:o.length-1,cursorCol:o[o.length-1].length}})},historyDown:()=>{t(r=>{if(r.historyIndex===-1)return r;let n=r.historyIndex+1;if(n>=r.history.length)return{historyIndex:-1,lines:[""],cursorLine:0,cursorCol:0};let o=r.history[n].split(`
|
|
@@ -587,7 +587,7 @@ When reviewing code:
|
|
|
587
587
|
- \u{1F7E2} **Positive**: Good patterns, well-written code
|
|
588
588
|
|
|
589
589
|
Now review the code based on the given task.`});function $b(t){switch(t){case"explore":return $R;case"plan":return GR;case"review":return HR;default:return}}var h8=T(()=>{"use strict";p8();f8();m8();p8();f8();m8()});function g8(t,e){let r=t.remoteConversation,n=r?.binding;if(!(!t.remote?.armed||!n||n.gatewayOrigin!==e||!Pl.test(n.taskId)||!/^\d+$/.test(n.accountId)||!r?.lastRuntimeId||r.syncUnavailable))return{sessionId:t.id,taskId:n.taskId,accountId:n.accountId,origin:e,runtime:r.lastRuntimeId,exposure:r.exposure?.fromRevision??0}}function bfe(t,e,r={}){let n=new URL(Mn(t));if(n.username||n.password||!["https:","http:"].includes(n.protocol)||n.protocol!=="https:"&&!Jo(n.hostname))throw new Error(Sfe);let s=n.origin,o,i=new Map;return{available:a=>!!e&&!!g8(a,s),forTurn(a,c){let l=g8(a,s);if(!e||!l)return;let u=JSON.stringify(l),d=`${a.id}:${c}`;o!==d&&(o=d,i=new Map);let p=i,f=m=>{if(m?.aborted||o!==d||JSON.stringify(g8(a,s))!==u)throw new Error(Sfe)};return{assertCurrent:f,async publish(m,h){f(h);let A=JSON.stringify([l.origin,l.accountId,l.taskId,m.filename,m.sha256]),_=p.get(A);_||(_=Promise.resolve().then(async()=>{f(h);let y=AbortSignal.any([AbortSignal.timeout(r.timeoutMs??15e3),...h?[h]:[]]);try{let S=await(r.fetch??lt)(`${s}/v1/chats/${l.taskId}/artifacts`,{method:"POST",redirect:"error",signal:y,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:m.filename,mime:"text/html",kind:"html",content:m.content})});if(!S.body)throw new Error(YR);let C=S.body.getReader(),w=[],k=0;try{for(;;){let{done:D,value:N}=await C.read();if(D)break;if(k+=N.byteLength,k>16384)throw new Error(YR);w.push(N)}}finally{await C.cancel().catch(()=>{})}f(h);let v=JSON.parse(Buffer.concat(w).toString("utf8"));if(!S.ok||typeof v.artifact_id!="string"||!Pl.test(v.artifact_id))throw new Error(YR);return{filename:m.filename,artifactId:v.artifact_id,bytes:m.bytes,sha256:m.sha256}}catch{throw new Error(YR)}}),p.set(A,_));let E=await _;return f(h),E}}}}}var YR,Sfe,A8,_8=T(()=>{"use strict";Bn();Si();gn();YR="AiiCloud preview publication was not confirmed. Check this conversation before trying again.",Sfe="AiiCloud preview is unavailable for this conversation.";A8=`# AiiCloud HTML preview
|
|
590
|
-
|
|
590
|
+
Use preview_file when the user explicitly asks to show or preview a named local HTML file, or after you have created or updated a standalone HTML website or interactive visualization to fulfill their current request. This includes approved designs and continuations of an earlier request; do not require a separate request to show the file or artifact panel. Call with the deliverable's file_path after final writes and verification, before claiming delivery. Respect explicit local-only or no-upload instructions. Do not upload unrelated existing files, repository HTML fixtures, supporting assets, or every modified HTML file. The tool transfers the complete unchanged file privately to this conversation's artifact panel, independently of your reply. Do not retranscribe the source into your reply or invent upload commands. Report an unavailable, denied, failed or unconfirmed preview honestly while preserving the local file; do not retry an unconfirmed publication in the same turn.`});function qR(t){if(t===void 0||t==="")return;if(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/.test(t))return JSON.stringify({only:[t]});if(t.length>8192)throw new Error("Invalid provider routing");let e;try{e=JSON.parse(t)}catch{throw new Error("Invalid provider routing")}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid provider routing");let r=["only","order","ignore","quantizations"],n=["allow_fallbacks","require_parameters"];for(let[s,o]of Object.entries(e))if(r.includes(s)){if(!Array.isArray(o)||o.length>32||o.some(i=>typeof i!="string"||!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/.test(i)))throw new Error("Invalid provider routing")}else if(n.includes(s)){if(typeof o!="boolean")throw new Error("Invalid provider routing")}else if(s==="data_collection"){if(!["allow","deny"].includes(o))throw new Error("Invalid provider routing")}else if(s==="sort"){if(!["price","throughput","latency"].includes(o))throw new Error("Invalid provider routing")}else throw new Error("Invalid provider routing");return t}var E8=T(()=>{"use strict"});function Qit(t,e){if(!(!Hb(t)||t.provenance!=="provider_reported"||!zR(t.input_tokens)||!zR(t.output_tokens))&&!(t.cached_input_tokens!==void 0&&(!zR(t.cached_input_tokens)||t.cached_input_tokens>t.input_tokens))&&!(t.cache_creation_tokens!==void 0&&!zR(t.cache_creation_tokens))&&!(t.provider_reported_cost_usd!==void 0&&!y8(t.provider_reported_cost_usd))&&!(e!==void 0&&!y8(e)))return{inputTokens:t.input_tokens,outputTokens:t.output_tokens,...t.cached_input_tokens!==void 0?{cachedInputTokens:t.cached_input_tokens}:{},...e!==void 0?{costUsd:e}:t.provider_reported_cost_usd!==void 0?{costUsd:t.provider_reported_cost_usd}:{}}}async function Uit(t){if(!t.body)throw new ln("invalid_response");let e=t.body.getReader(),r=[],n=0;try{for(;;){let i=await e.read();if(i.done)break;if(n+=i.value.byteLength,n>Pit)throw new ln("response_too_large");r.push(i.value)}let s=Buffer.concat(r),o=s.toString("utf8");if(!Buffer.from(o).equals(s))throw new ln("invalid_response");return JSON.parse(o)}finally{await e.cancel().catch(()=>{}),e.releaseLock()}}async function Ife(t,e){let r=e.selection;if(!r||!Gb(r.model)||!Gb(r.provider)||r.endpoint!==t.baseUrl||r.backend==="cloud"!=!!t.cloudApiKey)throw new ln("selection_changed");if(typeof e.content!="string"||!e.content.trim()||Buffer.byteLength(e.content)>Lit||Buffer.from(e.content).toString("utf8")!==e.content||!Number.isInteger(e.maxTokens)||e.maxTokens<1||e.maxTokens>4096)throw new ln("invalid_request");let n=r.backend==="cloud";if(!n&&(t.providerAuthType||t.providerAccountId||!["openrouter","deepseek"].includes(r.provider)))throw new ln("unsupported_credential_or_provider");let s=n?void 0:qR(r.openrouterProvider);if(s&&r.provider!=="openrouter")throw new ln("invalid_provider_routing");let o=n?{model:r.model,content:e.content,max_tokens:e.maxTokens}:{purpose:"context_summary",content:e.content,max_tokens:e.maxTokens,llm_provider:r.provider,model:r.model,...t.providerApiKey?{provider_api_key:t.providerApiKey}:{},...s?{openrouter_provider:s}:{}},i=new AbortController,a=()=>i.abort();e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&i.abort();let c=setTimeout(a,9e4);c.unref();try{let l=await lt(t.baseUrl+(n?"/v1/context/summarize":"/v0/reason"),{method:"POST",redirect:"error",signal:i.signal,headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${t.cloudApiKey}`}:{"Aii-API-Key":t.apiKey}},body:JSON.stringify(o)}),u=await Uit(l);if(!Hb(u)||u.protocol!=="context_summary_v1")throw new ln(l.status===404?"unsupported":"invalid_response");let d=n?u.route:u.selected;if(!Hb(d)||!Gb(d.provider)||!Gb(d.model)||(n?u.model!==r.model||typeof u.operation_id!="string"||!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(u.operation_id):d.provider!==r.provider||d.model!==r.model))throw new ln("identity_mismatch");let p=u.observed,f=Hb(p)&&p.model===d.model&&Gb(p.generation_id),m=u.consumption==="known"&&f?Qit(u.usage,n&&u.settlement==="settled"?u.cost_usd:void 0):void 0,h=n&&(u.settlement!=="settled"||!y8(u.cost_usd))?void 0:m;if(!l.ok||u.outcome!=="usable"||!h||u.finish_reason!=="stop"||h.outputTokens>e.maxTokens||typeof u.summary!="string"||!u.summary.trim()||Buffer.byteLength(u.summary)>Fit||Buffer.from(u.summary).toString("utf8")!==u.summary){let A=["unsupported_model","unsupported_provider","invalid_request","provider_unavailable","provider_rejected","identity_mismatch","missing_usage","accounting_unknown","settlement_unconfirmed","output_truncated","unusable_output","request_unconfirmed"],_=Hb(u.error)&&typeof u.error.code=="string"&&A.includes(u.error.code)?u.error.code:"unusable_response";throw new ln(_,h)}return{summary:u.summary,tokensUsed:h.inputTokens+h.outputTokens,accounting:h}}catch(l){throw l instanceof ln?l:new ln(i.signal.aborted?"request_unconfirmed":"transport_unconfirmed")}finally{clearTimeout(c),e.signal?.removeEventListener("abort",a)}}var ln,Lit,Pit,Fit,Hb,Gb,zR,y8,WR=T(()=>{"use strict";Bn();E8();ln=class extends Error{code;accounting;constructor(e,r){super(`Context compaction unavailable (${e}); original history retained.`),this.code=e,this.accounting=r,this.name="ContextSummaryError"}},Lit=1024*1024,Pit=1024*1024,Fit=64*1024,Hb=t=>!!t&&typeof t=="object"&&!Array.isArray(t),Gb=t=>typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$/.test(t),zR=t=>Number.isSafeInteger(t)&&t>=0&&t<=1e9,y8=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1e6});function Yb(t,e){return{backend:t.remoteConversation?.inference.backend??(t.connectionMode==="cloud"?"cloud":"server"),endpoint:t.remoteConversation?.inference.endpoint??e,provider:t.provider,model:t.model,...t.openrouterProvider!==void 0?{openrouterProvider:t.openrouterProvider}:{}}}function Tfe(t,e,r,n){return{get baseUrl(){return e.baseUrl},async summarize(s){let o=t(),i=Yb(o,e.baseUrl);if(await n?.(),s.signal?.aborted)throw new ln("request_unconfirmed");if(o!==t()||JSON.stringify(i)!==JSON.stringify(Yb(o,e.baseUrl)))throw new ln("selection_changed");try{let a=await e.summarize({...s,model:i.model,selection:i});return a.accounting&&r?.(o,a.accounting),a}catch(a){throw a instanceof ln&&a.accounting&&r?.(o,a.accounting),a}}}}var C8=T(()=>{"use strict";WR()});function L_(t){return Ap.has(t)}function zm(t){S8.add(t),t.remoteConversation&&(t.remoteConversation.syncUnavailable=!0,t.remoteConversation.turn&&(t.remoteConversation.turn.executionDirty=!0))}function $it(t){if(S8.has(t))throw new Ae("sync_unavailable")}function b8(t){if(S8.has(t)||t.remoteConversation?.syncUnavailable)throw new Ae("sync_unavailable")}async function P_(t){for(;Ap.has(t);)await Ap.get(t);b8(t)}function wfe(t,e){let r=JSON.stringify(t.messages),n=t.id,s=JSON.stringify(Yb(t,e));return()=>{if(t.id!==n||JSON.stringify(t.messages)!==r||JSON.stringify(Yb(t,e))!==s)throw new Error("Context changed during compaction")}}async function kfe(t,e,r,n,s){b8(t);let o=()=>{if($it(t),s(),!e.isPreparedSummaryCurrent(r))throw new Error("Context changed during compaction")};o();let i=[{role:"system",content:`=== CONVERSATION SUMMARY (older turns) ===
|
|
591
591
|
${r.summary}
|
|
592
592
|
=== END SUMMARY ===`,timestamp:Date.now()},...r.recent.map(c=>({role:c.role,content:c.content,timestamp:c.timestamp??Date.now()}))],a=await n.commitPrepared(t,{messages:i,validate:o,apply:()=>{let c=e.applyPreparedSummary(r,!1);return t.messages=i,t.contextState=e.getState(),c},uncertain:()=>zm(t)});return e.notifySummaryCommitted(a),a}async function vfe(t,e){for(;Ap.has(t);)await Ap.get(t);b8(t);let r,n=new Promise(s=>{r=s});Ap.set(t,n);try{return await e()}finally{Ap.get(t)===n&&Ap.delete(t),r()}}var Ap,S8,qb=T(()=>{"use strict";C8();gn();Ap=new WeakMap,S8=new WeakSet});function Dfe(t,e){I8.set(t,{...e,depth:0})}async function VR(t,e,r){await P_(t);let n=I8.get(t),s=t.remoteConversation;if(!n||!s||n.depth)return r();if(s.turn?.executionDirty&&(s.turn.state==="unconfirmed"||!n.quiescent()))throw new Ae("execution_unresolved");n.depth++,s.turn={turnId:Ql(),runtimeId:s.lastRuntimeId,state:"prepared",executionDirty:!0,inferenceStarted:!1,...Fi(t)?{promptId:Fi(t).promptId}:{}};let o=!1,i,a;try{try{s.inference={...s.inference,model:t.model,provider:t.provider,openrouterProvider:t.openrouterProvider,reasoningEffort:t.reasoningEffort},await n.persistence.save(t,{updateCurrent:n.updateCurrent}),await n.observation?.begin(e,Fi(t),n.dispatchId?.()),i=await r()}catch(c){o=!0,a=c}Fi(t)?.uncertain&&(s.turn.state="unconfirmed"),s.inference={...s.inference,model:t.model,provider:t.provider,openrouterProvider:t.openrouterProvider,reasoningEffort:t.reasoningEffort},s.turn.state!=="unconfirmed"&&(s.turn.state=o||n.failed()?"failed":"completed"),s.turn.executionDirty=s.turn.state==="unconfirmed"||!!s.syncUnavailable||!n.quiescent();try{await n.persistence.save(t,{updateCurrent:n.updateCurrent}),await n.observation?.finish(n.answer(),o||n.failed())}catch(c){throw s.turn.executionDirty=!0,s.syncUnavailable=!0,await n.persistence.save(t,{updateCurrent:n.updateCurrent}).catch(()=>{}),c}if(await n.checkpoint?.(),o)throw a;return i}finally{n.depth--}}async function Rfe(t){await I8.get(t)?.checkpoint?.()}var I8,jR=T(()=>{"use strict";qb();Ui();gn();I8=new WeakMap});function Wb(t){let e=n=>n.replace(/\[/g,"(").replace(/\]/g,")"),r=t;for(let n of Yit)r=r.split(n).join(e(n));return r}function zit(t){return Wb(t).replace(/[\r\n\t\v\f\u2028\u2029]+/g," ").slice(0,qit)}function Kc(t,e){let{open:r,close:n,preamble:s}=Au[e.kind],o=e.source?` (source: ${zit(e.source)})`:"";return[r,s+o,"",Wb(t),n].join(`
|
|
593
593
|
`)}function xfe(t,e){let{open:r,close:n}=Au[e];return[r,Wb(t),n].join(`
|
|
@@ -610,7 +610,7 @@ ${e.tail}`:"";return`[verify] The completion claim failed verification (\`${oe(t
|
|
|
610
610
|
\u26A1 goal turns auto-approve (workspace-fenced) \u2014 your own prompts unchanged \xB7 /goal edit --no-auto to keep approvals`:"";return`\u25CE Goal set${W8(r)} (this session) \xB7 ${s}${n}${o}
|
|
611
611
|
/goal to view \xB7 cap anytime: /goal edit --auto-turns <n> \xB7 ${i} \xB7 --max-time <dur> \xB7 /goal pause`+a}function aN(t,e){return!e||e.status!=="active"||e.autoApproveTurns===!1?null:t==="interactive"||t==="normal"||t==="acceptEdits"?t:null}function K8(t){let e=t.autoTurnCap===0?"\u221E":String(t.autoTurnCap);return`\u25CE goal started \u2014 working toward the objective (turn ${t.autoTurns}/${e})`}function J8(t,e){let r=t.autoTurnCap===0?"\u221E":String(t.autoTurnCap),n=!e&&t.spentUsd>0?` \xB7 $${t.spentUsd.toFixed(2)}`:"";return`\u25CE goal check \u2014 objective not yet met \u2192 continuing (turn ${t.autoTurns}/${r}${n})`}function X8(t,e){let r=!e&&t.spentUsd>0?` \xB7 $${t.spentUsd.toFixed(2)}`:"",n=t.verifyCommands.length>0?` \xB7 verified: ${$_(t.verifyCommands)} \u2713`:"";return`\u25CE GOAL COMPLETE${t.verifyCommands.length===0&&t.proofExpected?" (self-declared, unverified)":""} \u2014 evidence: ${qa(t.evidence??"")}${n}
|
|
612
612
|
${t.autoTurns} turns \xB7 ${Gi(t.timeUsedMs)} \xB7 ${F_(t.tokensUsed)} tokens${r}`}function Z8(t){return`\u25CE GOAL BLOCKED \u2014 ${qa(t.blockedReason??"no reason given")}
|
|
613
|
-
Continuation suspended \xB7 /goal resume after providing input, /goal edit to revise, /goal clear`}function Km(t,e){switch(e){case"budget":return`\u25CE Goal budget reached (${t.budgetUsd!==null?`$${t.budgetUsd.toFixed(2)}`:""}) \u2014 progress summarized above \xB7 /goal edit --budget <usd> to raise`;case"time":return`\u25CE Goal time limit reached (${Gi(t.maxTimeMs??0)}) \u2014 progress summarized above \xB7 /goal edit --max-time <dur> to raise`;case"tokens":return`\u25CE Goal token limit reached (${F_(t.maxTokens??0)}) \u2014 progress summarized above \xB7 /goal edit --max-tokens <n> to raise`;case"cap":return`\u25CE Goal turn cap reached (${t.autoTurnCap}) \u2014 progress summarized above \xB7 /goal resume to continue`}}function Kb(t,e,r){let n=!e&&t.spentUsd>0?` \xB7 $${t.spentUsd.toFixed(2)}`:"",s=t.status!=="complete"&&r?`${W8(r)} \xB7 "${jm(t.text,40)}"`:"";return`Goal: ${t.status}${s} \xB7 ${t.autoTurns} turns \xB7 ${Gi(t.timeUsedMs)} \xB7 ${F_(t.tokensUsed)} tokens${n}`}function o4(t,e){return!e||t.status==="complete"?null:`pick up later: aii --continue ${e} (aii goals to list)`}var Zit,eat,tat,rat,Qfe,KR,nat,sat,oat,eN,x8,B8,M8,L8,Q_,P8,F8,Q8,tN,G8,sN,oN,Gfe,H8,cN,lN,e4,t4,r4,n4,s4,uN,Ep=T(()=>{"use strict";PA();Vm();Mt();jb();Zit=["paused","blocked","budget_limited","complete","waiting"];eat=/^GOAL (COMPLETE|BLOCKED|WAITING)\s*(?:[—–-]|:)\s*(.*)$/,tat=/^resume\s+in\s+(\d+)([smh])\s*(?:(?:[—–-]|:)\s*(.*))?$/i,rat=/^evidence:\s*/i,Qfe=1024,KR="met|complete|completed|achieved|done|reached|satisfied|fulfilled|finished",nat=new RegExp(`\\b(not\\s+(yet\\s+)?(${KR})|goal\\s+is\\s+not\\s+(yet\\s+)?(${KR})|isn'?t\\s+(yet\\s+)?(${KR}))`,"i"),sat=4096,oat=new RegExp(`\\bgoal\\s+(is\\s+not|isn['\u2019]?t)\\s+(yet\\s+)?(${KR})\\b`,"i");eN="[goal] The goal is still active. First check the evidence against the goal\u2019s verification surface. If met, declare as your final line: GOAL COMPLETE \u2014 evidence: <what you verified>. Otherwise take the next most useful action toward the goal \u2014 if details are unspecified, choose sensibly yourself and proceed. Declare GOAL BLOCKED \u2014 <blocker + next input needed> only when progress is truly impossible without the user.",x8='\u25CE goal check \u2014 completion needs proof: run a concrete check now, or arm one with /goal edit --verify "<cmd>" (runs on your shell at completion \u2014 review it first)',B8='[goal] You declared the goal complete but ran no verification. Run a concrete check that proves the objective is met (a test, a build, a command whose output demonstrates success) and cite its result as your evidence. If you cannot run one this turn, state the exact command you recommend the user arm via `/goal edit --verify "<cmd>"`. If the goal genuinely has no runnable check (a docs or explanation task), say so and re-declare GOAL COMPLETE \u2014 evidence: <why no check applies>.',M8="\u25CE goal check \u2014 that looks self-resolvable; attempting an alternative approach (blocked attempt 1/2)",L8="[goal] You reported GOAL BLOCKED, but this looks resolvable without the user. Attempt a genuinely different approach \u2014 a different tool, file, or strategy. Only re-declare GOAL BLOCKED if you hit the SAME wall that truly requires something only the user can provide (credentials, access, a decision you cannot make). If the wall is a time window, declare GOAL WAITING \u2014 resume in <duration> \u2014 <reason> instead.",Q_="[goal] The wait elapsed. Re-check the time-gated condition and continue toward the goal. If the window is still closed, declare GOAL WAITING again with a fresh duration.",P8='\u25CE goal check \u2014 GOAL WAITING needs "resume in <N>s|m|h \u2014 <reason>"; goal stays active',F8="\u25CE goal check \u2014 3 consecutive waits with no work between; auto-continue paused (/goal resume)",Q8="\u25CE goal wait elapsed \u2014 input not observable here; goal paused (/goal resume)",tN="\u25CE goal wake yielded to your input \u2014 continues after your next message (/goal resume to go now)";G8="[goal] A limit was reached and work is stopping now. Do not start new substantive work. In three short lines, hand off cleanly: Progress: <what is verifiably done, citing the check result below if present>. Remaining: <what is left>. Next: <the single next action to resume with>.",sN="[goal] The objective was just changed by the user. The new objective (in the active_goal block) SUPERSEDES the previous one. Abandon any work that only served the prior objective; re-orient to the new one.",oN="\u25CE goal check \u2014 objective changed \u2192 abandoning work that only served the prior goal",Gfe=/[\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2069\uFEFF\uFFF9-\uFFFB]/g,H8="goal_draft";cN="\u26A0 no bound set \u2014 the \u25CE segment shows progress; Esc pauses anytime \xB7 cap with /goal edit --auto-turns <n>";lN="\u25CE goal check \u2014 the last turn errored; auto-continue paused (/goal resume to retry)",e4="\u25CE goal check \u2014 no tool activity last turn; auto-continue paused (type to hand back, or /goal resume)",t4="\u25CE goal check \u2014 the agent declared GOAL COMPLETE without evidence; goal stays active",r4="\u25CE goal check \u2014 the agent declared GOAL COMPLETE but its own evidence says the goal is not met; goal stays active",n4='\u25CE goal check \u2014 a goal with no turn cap won\u2019t self-complete on an unverified claim; continuing. Arm /goal edit --verify "<cmd>", cap with /goal edit --auto-turns <n>, or /goal clear when you\u2019re satisfied.',s4="[goal] You declared the goal complete but ran no verification, and this is an uncapped unattended goal, so an unverified self-declaration cannot end it. If a concrete check exists, run it now and cite the result. If the goal is genuinely complete with no runnable check, do NOT repeat your summary \u2014 stop and let the user confirm (they can /goal clear or arm --verify).",uN="\u25CE goal paused \u2014 server-session mode (`/goal resume` after returning to a local session)"});var zfe,Wfe=T(()=>{"use strict";zfe={maxIterations:500,maxTokensPerTurn:1e5,streamOutput:!0,autoApprove:!1,showThinking:!1,stallTimeoutMs:3e5}});function aat(){return[{name:"task",description:"Delegate a task to a specialized subagent that runs autonomously with its own tools and context window. Available subagents: explore (fast codebase exploration \u2014 read-only, cheap model), plan (architecture and implementation planning \u2014 read-only), review (code quality analysis and bug detection \u2014 read-only). IMPORTANT: When the user asks you to analyze, explore, review, or plan across a codebase, prefer this tool over doing the work yourself. Use explore for multi-directory or multi-package searches. Use plan for architecture decisions requiring deep analysis. Use review for code quality checks. The subagent runs and returns its complete findings in the tool result \u2014 use those findings directly, do not re-explore the same files afterward.",input_schema:{type:"object",properties:{subagent:{type:"string",description:'Name of the subagent to spawn (e.g., "explore", "plan", "review")'},prompt:{type:"string",description:"Task description for the subagent. Be specific about what you want to find or accomplish."}},required:["subagent","prompt"]}},{name:"todo_write",description:"Create a task plan before starting multi-step work (3+ steps). Call with an array of tasks, each having subject (imperative) and activeForm (continuous). Always call BEFORE starting execution. Pass append: true to add tasks to existing plan.",input_schema:{type:"object",properties:{tasks:{type:"array",description:"Tasks to create. Each needs subject (imperative form) and activeForm (present continuous form)."},append:{type:"boolean",description:"Append to existing tasks instead of replacing. Default: false."}},required:["tasks"]}},{name:"task_update",description:"Update a task status or fields. Mark tasks in_progress before starting, completed after finishing. Keep ONE task in_progress at a time.",input_schema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "task-1")'},status:{type:"string",description:"New status: pending, in_progress, completed"},subject:{type:"string",description:"Updated title"},activeForm:{type:"string",description:"Updated spinner text"},owner:{type:"string",description:"Subagent name"},blockedBy:{type:"array",description:"Task IDs this depends on"}},required:["id"]}},{name:"task_list",description:"List all current tasks with status. Read-only \u2014 use to check progress.",input_schema:{type:"object",properties:{}}},{name:"ask_user_question",description:`Pause execution and ask the user a multiple-choice question. Use when there are multiple valid approaches and you need a decision (e.g., choosing between architectural patterns, UX approaches, or files to modify). Provide 2-4 options with descriptions. Always allow "Other" so the user isn't boxed in. Returns the selected label or "[Other]: <text>" for free-form answers. Do NOT use for trivial questions or yes/no confirmations.`,input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"},description:{type:"string",description:"Optional context shown below the question"},options:{type:"array",description:'Array of 1-9 options. Each entry is an object with a required "label" string and optional "description" string.',minItems:1,maxItems:9,items:{type:"object",properties:{label:{type:"string",description:'Short title shown in the option list (e.g., "PostgreSQL")'},description:{type:"string",description:"Optional one-line tradeoff or explanation"}},required:["label"]}},allowOther:{type:"boolean",description:'Allow free-form "Other" input. Default: true.'}},required:["question","options"]}}]}function cat(){return[{name:"edit_file",description:"Perform an exact string replacement in a memory file.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the memory file to modify"},old_string:{type:"string",description:"The exact text to replace"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"Replace all occurrences; default false"}},required:["file_path","old_string","new_string"]}}]}function Vfe(t,e,r){if(t)return cat();let n=e?[]:aat();return r&&n.push({name:"preview_file",description:"Show the requested local HTML file privately in this AiiCloud conversation. Transfers the complete file without copying source into the response. Use only for an explicit named-file preview request.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Path to the requested .html or .htm file, at most 1 MiB."}},required:["file_path"]}}),n.length?n:void 0}var jfe=T(()=>{"use strict"});var Kfe,Jfe=T(()=>{"use strict";Kfe={baseUrl:"http://localhost:26169",apiKey:"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",reconnectAttempts:5,reconnectDelayMs:1e3,timeout:3e4}});function yp(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Xfe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Zfe(t){return{cachedTokens:yp(t.cached_tokens),cacheWriteTokens:yp(t.cache_write_tokens),costSavingsUsd:Xfe(t.cost_savings_usd),billedInputTokens:yp(t.input_tokens)}}function eme(t){let e={inputTokens:t.input_tokens??0,outputTokens:t.output_tokens??0,cost:t.cost_usd??0},r=yp(t.turn_input_tokens),n=yp(t.turn_output_tokens),s=yp(t.turn_cost_usd);return r===void 0||n===void 0||s===void 0?e:{...e,extras:{cachedTokens:yp(t.turn_cached_tokens),cacheWriteTokens:yp(t.turn_cache_write_tokens),costSavingsUsd:Xfe(t.turn_cost_savings_usd),turnInputTokens:r,turnOutputTokens:n,turnCostUsd:s}}}var tme=T(()=>{"use strict"});import{homedir as lat}from"os";import{join as uat}from"path";function Ts(){return process.env.AII_HOME||uat(lat(),".aii")}var dN=T(()=>{"use strict"});var hN={};de(hN,{ACTIVE_PERSONA_FILE:()=>Xb,BUILT_IN_SKILLS_CACHE_DIR:()=>l4,CACHE_DIR:()=>Jb,DEFAULT_PERSONA:()=>Zb,MAX_DESCRIPTION_LENGTH:()=>mN,MAX_PERSONA_NAME_LENGTH:()=>fN,ORPHANED_AT_FILE:()=>Sp,PACK_META_FILE:()=>G_,PERSONAS_CACHE_DIR:()=>a4,PERSONA_CUSTOMIZATIONS_FILE:()=>pN,PERSONA_MANIFEST:()=>Nr,PERSONA_NAME_PATTERN:()=>d4,SKILLPACK_MANIFEST:()=>pat,SKILLS_CACHE_DIR:()=>i4,SOULS_CACHE_DIR:()=>c4,SOUL_TO_PERSONA_MAP:()=>H_,UNIVERSAL_SKILLS_DIR:()=>u4,getAiiHome:()=>Ts});import{homedir as dat}from"os";import{join as Cp}from"path";var Jb,i4,a4,c4,l4,Xb,pN,u4,Nr,pat,G_,Sp,fN,mN,d4,Zb,H_,oi=T(()=>{"use strict";dN();dN();Jb=()=>Cp(Ts(),"cache"),i4=()=>Cp(Jb(),"skills"),a4=()=>Cp(Jb(),"personas"),c4=()=>Cp(Jb(),"souls"),l4=()=>Cp(Jb(),"built-in-skills"),Xb=()=>Cp(Ts(),"active-persona.json"),pN=()=>Cp(Ts(),"persona-customizations.json"),u4=()=>process.env.AII_UNIVERSAL_SKILLS_DIR||Cp(dat(),".agents","skills"),Nr="persona.json",pat="skillpack.json",G_=".aii-pack-meta.json",Sp=".orphaned_at",fN=64,mN=1024,d4=/^[a-z0-9-]+\/[a-z0-9-]+$/,Zb="aiiware/thinker",H_={thinker:"aiiware/thinker",doer:"aiiware/doer",coder:"aiiware/coder"}});import{readdir as fat,stat as rme}from"fs/promises";import{join as Y_,resolve as mat}from"path";import{homedir as nme}from"os";function sme(t){return t.startsWith("~")?Y_(nme(),t.slice(1)):mat(t)}async function bn(t){try{return(await rme(t)).isDirectory()}catch{return!1}}async function Jc(t){try{return(await rme(t)).isFile()}catch{return!1}}async function eI(t){let e=sme(t);if(!await bn(e))return[];let r=[];try{let n=await fat(e,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=Y_(e,s.name),i=Y_(o,qr);await Jc(i)&&r.push(o)}}catch{return[]}return r}function bp(t){return Y_(t,KD)}function Ip(){return Y_(nme(),JD)}function gN(t){let e=t.split("/");return e[e.length-1]||""}function p4(){return u4()}async function AN(t,e){let[r,n,s]=await Promise.all([eI(bp(t)),eI(Ip()),eI(p4())]),o=[];if(e)for(let i of e){let a=Y_(i,qr);await Jc(a)&&o.push(i)}return{project:r,user:n,personaBundled:o,universal:s}}var Jm=T(()=>{"use strict";So();oi()});function f4(t){return t?Eu.ALL_ARGS.test(t)||Eu.INDEXED_ARGS.test(t)||Eu.SHORTHAND.test(t):!1}function tI(t){if(!t||t.trim()==="")return[];let e=[],r="",n=null,s=0;for(;s<t.length;){let o=t[s];if(n){if(o==="\\"&&s+1<t.length){let i=t[s+1];if(i===n||i==="\\"){r+=i,s+=2;continue}}o===n?n=null:r+=o}else o==='"'||o==="'"?n=o:o===" "||o===" "?r&&(e.push(r),r=""):r+=o;s++}return r&&e.push(r),e}function rI(t,e,r){if(!t)return t;Eu.ALL_ARGS.lastIndex=0,Eu.INDEXED_ARGS.lastIndex=0,Eu.SHORTHAND.lastIndex=0;let n=f4(t),s=t;return s=s.replace(Eu.ALL_ARGS,e),s=s.replace(Eu.INDEXED_ARGS,(o,i)=>{let a=parseInt(i,10);return r[a]??""}),s=s.replace(Eu.SHORTHAND,(o,i)=>{let a=parseInt(i,10);return r[a]??""}),!n&&e.trim()&&(s=`${s.trimEnd()}
|
|
613
|
+
Continuation suspended \xB7 /goal resume after providing input, /goal edit to revise, /goal clear`}function Km(t,e){switch(e){case"budget":return`\u25CE Goal budget reached (${t.budgetUsd!==null?`$${t.budgetUsd.toFixed(2)}`:""}) \u2014 progress summarized above \xB7 /goal edit --budget <usd> to raise`;case"time":return`\u25CE Goal time limit reached (${Gi(t.maxTimeMs??0)}) \u2014 progress summarized above \xB7 /goal edit --max-time <dur> to raise`;case"tokens":return`\u25CE Goal token limit reached (${F_(t.maxTokens??0)}) \u2014 progress summarized above \xB7 /goal edit --max-tokens <n> to raise`;case"cap":return`\u25CE Goal turn cap reached (${t.autoTurnCap}) \u2014 progress summarized above \xB7 /goal resume to continue`}}function Kb(t,e,r){let n=!e&&t.spentUsd>0?` \xB7 $${t.spentUsd.toFixed(2)}`:"",s=t.status!=="complete"&&r?`${W8(r)} \xB7 "${jm(t.text,40)}"`:"";return`Goal: ${t.status}${s} \xB7 ${t.autoTurns} turns \xB7 ${Gi(t.timeUsedMs)} \xB7 ${F_(t.tokensUsed)} tokens${n}`}function o4(t,e){return!e||t.status==="complete"?null:`pick up later: aii --continue ${e} (aii goals to list)`}var Zit,eat,tat,rat,Qfe,KR,nat,sat,oat,eN,x8,B8,M8,L8,Q_,P8,F8,Q8,tN,G8,sN,oN,Gfe,H8,cN,lN,e4,t4,r4,n4,s4,uN,Ep=T(()=>{"use strict";PA();Vm();Mt();jb();Zit=["paused","blocked","budget_limited","complete","waiting"];eat=/^GOAL (COMPLETE|BLOCKED|WAITING)\s*(?:[—–-]|:)\s*(.*)$/,tat=/^resume\s+in\s+(\d+)([smh])\s*(?:(?:[—–-]|:)\s*(.*))?$/i,rat=/^evidence:\s*/i,Qfe=1024,KR="met|complete|completed|achieved|done|reached|satisfied|fulfilled|finished",nat=new RegExp(`\\b(not\\s+(yet\\s+)?(${KR})|goal\\s+is\\s+not\\s+(yet\\s+)?(${KR})|isn'?t\\s+(yet\\s+)?(${KR}))`,"i"),sat=4096,oat=new RegExp(`\\bgoal\\s+(is\\s+not|isn['\u2019]?t)\\s+(yet\\s+)?(${KR})\\b`,"i");eN="[goal] The goal is still active. First check the evidence against the goal\u2019s verification surface. If met, declare as your final line: GOAL COMPLETE \u2014 evidence: <what you verified>. Otherwise take the next most useful action toward the goal \u2014 if details are unspecified, choose sensibly yourself and proceed. Declare GOAL BLOCKED \u2014 <blocker + next input needed> only when progress is truly impossible without the user.",x8='\u25CE goal check \u2014 completion needs proof: run a concrete check now, or arm one with /goal edit --verify "<cmd>" (runs on your shell at completion \u2014 review it first)',B8='[goal] You declared the goal complete but ran no verification. Run a concrete check that proves the objective is met (a test, a build, a command whose output demonstrates success) and cite its result as your evidence. If you cannot run one this turn, state the exact command you recommend the user arm via `/goal edit --verify "<cmd>"`. If the goal genuinely has no runnable check (a docs or explanation task), say so and re-declare GOAL COMPLETE \u2014 evidence: <why no check applies>.',M8="\u25CE goal check \u2014 that looks self-resolvable; attempting an alternative approach (blocked attempt 1/2)",L8="[goal] You reported GOAL BLOCKED, but this looks resolvable without the user. Attempt a genuinely different approach \u2014 a different tool, file, or strategy. Only re-declare GOAL BLOCKED if you hit the SAME wall that truly requires something only the user can provide (credentials, access, a decision you cannot make). If the wall is a time window, declare GOAL WAITING \u2014 resume in <duration> \u2014 <reason> instead.",Q_="[goal] The wait elapsed. Re-check the time-gated condition and continue toward the goal. If the window is still closed, declare GOAL WAITING again with a fresh duration.",P8='\u25CE goal check \u2014 GOAL WAITING needs "resume in <N>s|m|h \u2014 <reason>"; goal stays active',F8="\u25CE goal check \u2014 3 consecutive waits with no work between; auto-continue paused (/goal resume)",Q8="\u25CE goal wait elapsed \u2014 input not observable here; goal paused (/goal resume)",tN="\u25CE goal wake yielded to your input \u2014 continues after your next message (/goal resume to go now)";G8="[goal] A limit was reached and work is stopping now. Do not start new substantive work. In three short lines, hand off cleanly: Progress: <what is verifiably done, citing the check result below if present>. Remaining: <what is left>. Next: <the single next action to resume with>.",sN="[goal] The objective was just changed by the user. The new objective (in the active_goal block) SUPERSEDES the previous one. Abandon any work that only served the prior objective; re-orient to the new one.",oN="\u25CE goal check \u2014 objective changed \u2192 abandoning work that only served the prior goal",Gfe=/[\u061C\u200B-\u200F\u202A-\u202E\u2060-\u2069\uFEFF\uFFF9-\uFFFB]/g,H8="goal_draft";cN="\u26A0 no bound set \u2014 the \u25CE segment shows progress; Esc pauses anytime \xB7 cap with /goal edit --auto-turns <n>";lN="\u25CE goal check \u2014 the last turn errored; auto-continue paused (/goal resume to retry)",e4="\u25CE goal check \u2014 no tool activity last turn; auto-continue paused (type to hand back, or /goal resume)",t4="\u25CE goal check \u2014 the agent declared GOAL COMPLETE without evidence; goal stays active",r4="\u25CE goal check \u2014 the agent declared GOAL COMPLETE but its own evidence says the goal is not met; goal stays active",n4='\u25CE goal check \u2014 a goal with no turn cap won\u2019t self-complete on an unverified claim; continuing. Arm /goal edit --verify "<cmd>", cap with /goal edit --auto-turns <n>, or /goal clear when you\u2019re satisfied.',s4="[goal] You declared the goal complete but ran no verification, and this is an uncapped unattended goal, so an unverified self-declaration cannot end it. If a concrete check exists, run it now and cite the result. If the goal is genuinely complete with no runnable check, do NOT repeat your summary \u2014 stop and let the user confirm (they can /goal clear or arm --verify).",uN="\u25CE goal paused \u2014 server-session mode (`/goal resume` after returning to a local session)"});var zfe,Wfe=T(()=>{"use strict";zfe={maxIterations:500,maxTokensPerTurn:1e5,streamOutput:!0,autoApprove:!1,showThinking:!1,stallTimeoutMs:3e5}});function aat(){return[{name:"task",description:"Delegate a task to a specialized subagent that runs autonomously with its own tools and context window. Available subagents: explore (fast codebase exploration \u2014 read-only, cheap model), plan (architecture and implementation planning \u2014 read-only), review (code quality analysis and bug detection \u2014 read-only). IMPORTANT: When the user asks you to analyze, explore, review, or plan across a codebase, prefer this tool over doing the work yourself. Use explore for multi-directory or multi-package searches. Use plan for architecture decisions requiring deep analysis. Use review for code quality checks. The subagent runs and returns its complete findings in the tool result \u2014 use those findings directly, do not re-explore the same files afterward.",input_schema:{type:"object",properties:{subagent:{type:"string",description:'Name of the subagent to spawn (e.g., "explore", "plan", "review")'},prompt:{type:"string",description:"Task description for the subagent. Be specific about what you want to find or accomplish."}},required:["subagent","prompt"]}},{name:"todo_write",description:"Create a task plan before starting multi-step work (3+ steps). Call with an array of tasks, each having subject (imperative) and activeForm (continuous). Always call BEFORE starting execution. Pass append: true to add tasks to existing plan.",input_schema:{type:"object",properties:{tasks:{type:"array",description:"Tasks to create. Each needs subject (imperative form) and activeForm (present continuous form)."},append:{type:"boolean",description:"Append to existing tasks instead of replacing. Default: false."}},required:["tasks"]}},{name:"task_update",description:"Update a task status or fields. Mark tasks in_progress before starting, completed after finishing. Keep ONE task in_progress at a time.",input_schema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "task-1")'},status:{type:"string",description:"New status: pending, in_progress, completed"},subject:{type:"string",description:"Updated title"},activeForm:{type:"string",description:"Updated spinner text"},owner:{type:"string",description:"Subagent name"},blockedBy:{type:"array",description:"Task IDs this depends on"}},required:["id"]}},{name:"task_list",description:"List all current tasks with status. Read-only \u2014 use to check progress.",input_schema:{type:"object",properties:{}}},{name:"ask_user_question",description:`Pause execution and ask the user a multiple-choice question. Use when there are multiple valid approaches and you need a decision (e.g., choosing between architectural patterns, UX approaches, or files to modify). Provide 2-4 options with descriptions. Always allow "Other" so the user isn't boxed in. Returns the selected label or "[Other]: <text>" for free-form answers. Do NOT use for trivial questions or yes/no confirmations.`,input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"},description:{type:"string",description:"Optional context shown below the question"},options:{type:"array",description:'Array of 1-9 options. Each entry is an object with a required "label" string and optional "description" string.',minItems:1,maxItems:9,items:{type:"object",properties:{label:{type:"string",description:'Short title shown in the option list (e.g., "PostgreSQL")'},description:{type:"string",description:"Optional one-line tradeoff or explanation"}},required:["label"]}},allowOther:{type:"boolean",description:'Allow free-form "Other" input. Default: true.'}},required:["question","options"]}}]}function cat(){return[{name:"edit_file",description:"Perform an exact string replacement in a memory file.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the memory file to modify"},old_string:{type:"string",description:"The exact text to replace"},new_string:{type:"string",description:"The replacement text"},replace_all:{type:"boolean",description:"Replace all occurrences; default false"}},required:["file_path","old_string","new_string"]}}]}function Vfe(t,e,r){if(t)return cat();let n=e?[]:aat();return r&&n.push({name:"preview_file",description:"Show a local HTML file privately in this AiiCloud conversation. Use for an explicitly requested named-file preview or the standalone HTML deliverable created or updated for the current user request, including approved designs and continuations. Call after final writes and verification. Respect local-only or no-upload instructions; do not upload unrelated files, repository fixtures, supporting assets, or every modified HTML file. Transfers the complete unchanged file without copying source into the response or inventing upload commands. Report unavailable, denied, failed or unconfirmed previews honestly; preserve the local file and do not retry an unconfirmed publication in the same turn.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Path to the requested .html or .htm file, at most 1 MiB."}},required:["file_path"]}}),n.length?n:void 0}var jfe=T(()=>{"use strict"});var Kfe,Jfe=T(()=>{"use strict";Kfe={baseUrl:"http://localhost:26169",apiKey:"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",reconnectAttempts:5,reconnectDelayMs:1e3,timeout:3e4}});function yp(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Xfe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Zfe(t){return{cachedTokens:yp(t.cached_tokens),cacheWriteTokens:yp(t.cache_write_tokens),costSavingsUsd:Xfe(t.cost_savings_usd),billedInputTokens:yp(t.input_tokens)}}function eme(t){let e={inputTokens:t.input_tokens??0,outputTokens:t.output_tokens??0,cost:t.cost_usd??0},r=yp(t.turn_input_tokens),n=yp(t.turn_output_tokens),s=yp(t.turn_cost_usd);return r===void 0||n===void 0||s===void 0?e:{...e,extras:{cachedTokens:yp(t.turn_cached_tokens),cacheWriteTokens:yp(t.turn_cache_write_tokens),costSavingsUsd:Xfe(t.turn_cost_savings_usd),turnInputTokens:r,turnOutputTokens:n,turnCostUsd:s}}}var tme=T(()=>{"use strict"});import{homedir as lat}from"os";import{join as uat}from"path";function Ts(){return process.env.AII_HOME||uat(lat(),".aii")}var dN=T(()=>{"use strict"});var hN={};de(hN,{ACTIVE_PERSONA_FILE:()=>Xb,BUILT_IN_SKILLS_CACHE_DIR:()=>l4,CACHE_DIR:()=>Jb,DEFAULT_PERSONA:()=>Zb,MAX_DESCRIPTION_LENGTH:()=>mN,MAX_PERSONA_NAME_LENGTH:()=>fN,ORPHANED_AT_FILE:()=>Sp,PACK_META_FILE:()=>G_,PERSONAS_CACHE_DIR:()=>a4,PERSONA_CUSTOMIZATIONS_FILE:()=>pN,PERSONA_MANIFEST:()=>Nr,PERSONA_NAME_PATTERN:()=>d4,SKILLPACK_MANIFEST:()=>pat,SKILLS_CACHE_DIR:()=>i4,SOULS_CACHE_DIR:()=>c4,SOUL_TO_PERSONA_MAP:()=>H_,UNIVERSAL_SKILLS_DIR:()=>u4,getAiiHome:()=>Ts});import{homedir as dat}from"os";import{join as Cp}from"path";var Jb,i4,a4,c4,l4,Xb,pN,u4,Nr,pat,G_,Sp,fN,mN,d4,Zb,H_,oi=T(()=>{"use strict";dN();dN();Jb=()=>Cp(Ts(),"cache"),i4=()=>Cp(Jb(),"skills"),a4=()=>Cp(Jb(),"personas"),c4=()=>Cp(Jb(),"souls"),l4=()=>Cp(Jb(),"built-in-skills"),Xb=()=>Cp(Ts(),"active-persona.json"),pN=()=>Cp(Ts(),"persona-customizations.json"),u4=()=>process.env.AII_UNIVERSAL_SKILLS_DIR||Cp(dat(),".agents","skills"),Nr="persona.json",pat="skillpack.json",G_=".aii-pack-meta.json",Sp=".orphaned_at",fN=64,mN=1024,d4=/^[a-z0-9-]+\/[a-z0-9-]+$/,Zb="aiiware/thinker",H_={thinker:"aiiware/thinker",doer:"aiiware/doer",coder:"aiiware/coder"}});import{readdir as fat,stat as rme}from"fs/promises";import{join as Y_,resolve as mat}from"path";import{homedir as nme}from"os";function sme(t){return t.startsWith("~")?Y_(nme(),t.slice(1)):mat(t)}async function bn(t){try{return(await rme(t)).isDirectory()}catch{return!1}}async function Jc(t){try{return(await rme(t)).isFile()}catch{return!1}}async function eI(t){let e=sme(t);if(!await bn(e))return[];let r=[];try{let n=await fat(e,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=Y_(e,s.name),i=Y_(o,qr);await Jc(i)&&r.push(o)}}catch{return[]}return r}function bp(t){return Y_(t,KD)}function Ip(){return Y_(nme(),JD)}function gN(t){let e=t.split("/");return e[e.length-1]||""}function p4(){return u4()}async function AN(t,e){let[r,n,s]=await Promise.all([eI(bp(t)),eI(Ip()),eI(p4())]),o=[];if(e)for(let i of e){let a=Y_(i,qr);await Jc(a)&&o.push(i)}return{project:r,user:n,personaBundled:o,universal:s}}var Jm=T(()=>{"use strict";So();oi()});function f4(t){return t?Eu.ALL_ARGS.test(t)||Eu.INDEXED_ARGS.test(t)||Eu.SHORTHAND.test(t):!1}function tI(t){if(!t||t.trim()==="")return[];let e=[],r="",n=null,s=0;for(;s<t.length;){let o=t[s];if(n){if(o==="\\"&&s+1<t.length){let i=t[s+1];if(i===n||i==="\\"){r+=i,s+=2;continue}}o===n?n=null:r+=o}else o==='"'||o==="'"?n=o:o===" "||o===" "?r&&(e.push(r),r=""):r+=o;s++}return r&&e.push(r),e}function rI(t,e,r){if(!t)return t;Eu.ALL_ARGS.lastIndex=0,Eu.INDEXED_ARGS.lastIndex=0,Eu.SHORTHAND.lastIndex=0;let n=f4(t),s=t;return s=s.replace(Eu.ALL_ARGS,e),s=s.replace(Eu.INDEXED_ARGS,(o,i)=>{let a=parseInt(i,10);return r[a]??""}),s=s.replace(Eu.SHORTHAND,(o,i)=>{let a=parseInt(i,10);return r[a]??""}),!n&&e.trim()&&(s=`${s.trimEnd()}
|
|
614
614
|
|
|
615
615
|
**Arguments:** ${e}`),s}var Eu,m4=T(()=>{"use strict";Eu={ALL_ARGS:/\$ARGUMENTS(?!\[)/g,INDEXED_ARGS:/\$ARGUMENTS\[(\d+)\]/g,SHORTHAND:/\$(\d+)/g}});var cme={};de(cme,{DEFAULT_BRANCH:()=>EN,GITHUB_API_BASE:()=>_N,GITHUB_CONTENTS_MAX_ENTRIES:()=>g4,GITHUB_RAW_BASE:()=>A4,assertGitHubHost:()=>sI,buildApiContentsUrl:()=>_4,buildRawUrl:()=>Yi,encodeRepoPath:()=>Hi,extractSkillName:()=>W_,fetchGitHubFile:()=>yu,fetchGitHubFileBytes:()=>z_,getGitHubAuthHeaders:()=>Xm,isGitHubAuthHost:()=>ame,listGitHubDirectory:()=>E4,listGitHubDirectoryContents:()=>za,parseGitHubSource:()=>nI,resolveGitHubCommitSha:()=>Zm,stripMdFilename:()=>h4});function nI(t){if(!t||typeof t!="string")return{success:!1,error:"Source must be a non-empty string"};let e=t.trim();return e.startsWith("github:")&&(e=e.slice(7)),e.startsWith("https://")||e.startsWith("http://")?e.startsWith("https://github.com/")?hat(e):{success:!1,error:"URL must be from github.com"}:gat(e)}function hat(t){try{let e=new URL(t);if(e.hostname!=="github.com")return{success:!1,error:"URL must be from github.com"};let r=e.pathname.split("/").filter(Boolean);if(r.length<2)return{success:!1,error:"URL must include owner and repository"};let n=r[0],s=r[1];if(r.length>=4&&(r[2]==="tree"||r[2]==="blob")){let o=r[3],i=r.slice(4).join("/");if(!i)return{success:!0,source:{owner:n,repo:s,skillPath:"",ref:o}};let a=h4(i);return{success:!0,source:{owner:n,repo:s,skillPath:a,ref:o}}}if(r.length>=3){let o=r.slice(2).join("/"),i=h4(o);return{success:!0,source:{owner:n,repo:s,skillPath:i}}}return{success:!0,source:{owner:n,repo:s,skillPath:""}}}catch{return{success:!1,error:"Invalid URL format"}}}function gat(t){let e,r=t,n=t.lastIndexOf("@");if(n>0&&(e=t.slice(n+1),r=t.slice(0,n),!e))return{success:!1,error:"Version after @ cannot be empty"};let s=r.split("/").filter(Boolean);if(s.length<2)return{success:!1,error:"Source must be in format: owner/repo or owner/repo/skill-path (at least 2 parts)"};let o=s[0],i=s[1],a=s.slice(2).join("/");return ome(o)?ome(i)?{success:!0,source:{owner:o,repo:i,skillPath:a,ref:e}}:{success:!1,error:`Invalid repository name: ${i}`}:{success:!1,error:`Invalid owner name: ${o}`}}function ome(t){return/^[a-zA-Z0-9][-a-zA-Z0-9._]*$/.test(t)&&t.length<=100}function ame(t){try{let e=new URL(t);return e.protocol==="https:"&&ime.has(e.hostname)}catch{return!1}}function sI(t){let e;try{e=new URL(t)}catch{throw new Error(`github: refusing malformed URL ${JSON.stringify(t)}`)}if(e.protocol!=="https:")throw new Error(`github: refusing non-HTTPS scheme ${e.protocol}`);if(!ime.has(e.hostname))throw new Error(`github: refusing host ${e.hostname} \u2014 the GitHub token is only ever sent to GitHub`)}function Xm(t){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,r={"User-Agent":"aii-cli"};return e&&ame(t)&&(r.Authorization=`Bearer ${e}`),r}async function Zm(t,e,r){try{let n=`${_N}/repos/${t}/${e}/commits/${encodeURIComponent(r)}`,s=new AbortController,o=setTimeout(()=>s.abort(),15e3),i=await fetch(n,{signal:s.signal,headers:{...Xm(n),Accept:"application/vnd.github.v3+json"}});if(clearTimeout(o),!i.ok)return;let a=await i.json();return typeof a.sha=="string"&&/^[0-9a-f]{40}$/i.test(a.sha)?a.sha:void 0}catch{return}}function h4(t){if(!t)return"";let e=t.split("/");return e[e.length-1].toLowerCase().endsWith(".md")?e.slice(0,-1).join("/"):t}function Hi(t){return t.split("/").map(encodeURIComponent).join("/")}function Yi(t,e){let r=t.ref||EN,n=t.skillPath?`${t.skillPath}/${e}`:e;return`${A4}/${Hi(t.owner)}/${Hi(t.repo)}/${Hi(r)}/${Hi(n)}`}function _4(t){let e=t.ref||EN,r=t.skillPath||"";return`${_N}/repos/${Hi(t.owner)}/${Hi(t.repo)}/contents/${Hi(r)}?ref=${encodeURIComponent(e)}`}async function yu(t,e={}){let{timeout:r=1e4,skipAuth:n=!1}=e;try{sI(t)}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}try{let s=new AbortController,o=setTimeout(()=>s.abort(),r),i=n?{"User-Agent":"aii-cli"}:Xm(t),a=await fetch(t,{signal:s.signal,headers:{...i,Accept:"text/plain"}});return clearTimeout(o),a.ok?{success:!0,content:await a.text()}:a.status===404?{success:!1,error:"File not found"}:a.status===401||a.status===403?a.headers.get("x-ratelimit-remaining")==="0"?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits"}:{success:!1,error:q_()?"GITHUB_TOKEN may be expired or invalid \u2014 try unsetting it for public repos":"Access denied \u2014 set GITHUB_TOKEN for private repos"}:a.status===429?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits"}:{success:!1,error:`HTTP ${a.status}: ${a.statusText}`}}catch(s){if(!n&&q_()&&s instanceof Error){let o=s.cause;if(o&&(o.code==="ECONNRESET"||o.code==="ECONNREFUSED"||String(o.message||"").includes("socket disconnected")))return yu(t,{timeout:r,skipAuth:!0})}return s instanceof Error?s.name==="AbortError"?{success:!1,error:"Request timed out"}:{success:!1,error:s.message}:{success:!1,error:"Unknown fetch error"}}}function q_(){return!!(process.env.GITHUB_TOKEN||process.env.GH_TOKEN)}async function z_(t,e={}){let{timeout:r=1e4,skipAuth:n=!1}=e;try{sI(t)}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}try{let s=new AbortController,o=setTimeout(()=>s.abort(),r),i=n?{"User-Agent":"aii-cli"}:Xm(t),a=await fetch(t,{signal:s.signal,headers:{...i,Accept:"application/octet-stream"}});return clearTimeout(o),a.ok?{success:!0,bytes:Buffer.from(await a.arrayBuffer())}:a.status===404?{success:!1,error:"File not found"}:a.status===401||a.status===403?a.headers.get("x-ratelimit-remaining")==="0"?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits"}:{success:!1,error:q_()?"GITHUB_TOKEN may be expired or invalid \u2014 try unsetting it for public repos":"Access denied \u2014 set GITHUB_TOKEN for private repos"}:a.status===429?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits"}:{success:!1,error:`HTTP ${a.status}: ${a.statusText}`}}catch(s){if(!n&&q_()&&s instanceof Error){let o=s.cause;if(o&&(o.code==="ECONNRESET"||o.code==="ECONNREFUSED"||String(o.message||"").includes("socket disconnected")))return z_(t,{timeout:r,skipAuth:!0})}return s instanceof Error?s.name==="AbortError"?{success:!1,error:"Request timed out"}:{success:!1,error:s.message}:{success:!1,error:"Unknown fetch error"}}}async function E4(t,e={}){let r=await za(t,e);return r.success?{success:!0,files:r.entries?.map(s=>s.name)}:{success:!1,error:r.error}}async function za(t,e={}){let{timeout:r=1e4,skipAuth:n=!1}=e,s=_4(t);try{let o=new AbortController,i=setTimeout(()=>o.abort(),r),a=n?{"User-Agent":"aii-cli"}:Xm(s),c=await fetch(s,{signal:o.signal,headers:{...a,Accept:"application/vnd.github.v3+json"}});if(clearTimeout(i),!c.ok)return c.status===404?{success:!1,error:"Directory not found",notFound:!0,status:404}:c.status===401||c.status===403?c.headers.get("x-ratelimit-remaining")==="0"?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits",status:c.status}:{success:!1,error:q_()?"GITHUB_TOKEN may be expired or invalid \u2014 try unsetting it for public repos":"Access denied \u2014 set GITHUB_TOKEN for private repos",status:c.status}:c.status===429?{success:!1,error:"GitHub API rate limit exceeded \u2014 set GITHUB_TOKEN or GH_TOKEN for higher limits",status:429}:{success:!1,error:`HTTP ${c.status}: ${c.statusText}`,status:c.status};let l=await c.json();return Array.isArray(l)?l.length>=g4?{success:!1,error:`Directory listing hit the GitHub Contents API cap of ${g4} entries \u2014 the listing may be truncated, so the install was refused rather than risk a partial tree`}:{success:!0,entries:l.map(d=>({name:d.name,type:d.type==="dir"?"dir":"file",downloadUrl:d.download_url}))}:{success:!1,error:"Unexpected API response format"}}catch(o){if(!n&&q_()&&o instanceof Error){let i=o.cause;if(i&&(i.code==="ECONNRESET"||i.code==="ECONNREFUSED"||String(i.message||"").includes("socket disconnected")))return za(t,{timeout:r,skipAuth:!0})}return o instanceof Error?o.name==="AbortError"?{success:!1,error:"Request timed out"}:{success:!1,error:o.message}:{success:!1,error:"Unknown fetch error"}}}function W_(t,e){let r=t.split("/").filter(Boolean),n=r[r.length-1];return n||e||"skill"}var A4,_N,EN,ime,g4,V_=T(()=>{"use strict";A4="https://raw.githubusercontent.com",_N="https://api.github.com",EN="main";ime=new Set(["api.github.com","raw.githubusercontent.com","codeload.github.com"]);g4=1e3});var lme=T(()=>{"use strict";Jm();m4();V_()});import{createHash as _at}from"node:crypto";import{readdirSync as Eat,readFileSync as yat}from"node:fs";import{join as Cat}from"node:path";function oI(t){return t.normalize("NFKC").toLowerCase()}function CN(t){let e=new Set(yN.map(oI)),r=[],n=0;for(let s of t){let o=oI(s.path.split("/").pop()??s.path);if(e.has(o)){n++;continue}r.push(s)}return{writable:r,dropped:n}}function Wa(t,e){let r=new Set([...yN,...e?.exclude??[]]),n={},s=(o,i)=>{let a=Eat(o,{withFileTypes:!0}).sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);for(let c of a){if(r.has(c.name)||c.isSymbolicLink())continue;let l=Cat(o,c.name),u=i?`${i}/${c.name}`:c.name;c.isDirectory()?s(l,u):c.isFile()&&(n[u]=_at("sha256").update(yat(l)).digest("hex"))}};return s(t,""),n}function eh(t,e,r){if(e===void 0)return{ok:!0,mismatched:[],missing:[],extra:[],skipped:!0};let n=Wa(t,r),s=[],o=[],i=[];for(let[c,l]of Object.entries(e))c in n?n[c]!==l&&s.push(c):o.push(c);for(let c of Object.keys(n))c in e||i.push(c);return{ok:s.length===0&&o.length===0&&i.length===0,mismatched:s.sort(),missing:o.sort(),extra:i.sort(),skipped:!1}}var yN,th=T(()=>{"use strict";oi();yN=[G_,Sp,".aii-skill-meta.json"]});var iI,y4=T(()=>{"use strict";iI=class t{skills=new Map;byName=new Map;discoveredAt=0;static SOURCE_PRIORITY=["project-command","project","persona-bundled","plugin","user","universal","built-in","remote"];register(e){this.skills.set(e.id,e);let r=this.byName.get(e.name);if(!r)this.byName.set(e.name,e.id);else{let n=this.skills.get(r);n&&this.hasHigherPriority(e.source,n.source)&&this.byName.set(e.name,e.id)}this.discoveredAt=Date.now()}getByName(e){let r=this.skills.get(e);if(r)return r;let n=this.byName.get(e);if(n)return this.skills.get(n)}getByNameOrAmbiguous(e){let r=this.skills.get(e);if(r)return{type:"found",skill:r};let n=Array.from(this.skills.values()).filter(o=>o.name===e);if(n.length===0)return{type:"not_found"};if(n.length===1)return{type:"found",skill:n[0]};if(new Set(n.filter(o=>o.id.includes(":")).map(o=>o.id.split(":")[0])).size<=1){let o=this.byName.get(e);return{type:"found",skill:o?this.skills.get(o):n[0]}}return{type:"ambiguous",candidates:n}}getById(e){return this.skills.get(e)}getAll(){let e=new Set(this.byName.values());return Array.from(this.skills.values()).filter(r=>e.has(r.id))}getAllIncludingShadowed(){return Array.from(this.skills.values())}getUserInvocable(){return this.getAll().filter(e=>e.userInvocable)}getModelInvocable(){return this.getAll().filter(e=>e.modelInvocable)}getBySource(){let e={"project-command":[],project:[],user:[],"persona-bundled":[],universal:[],"built-in":[],plugin:[],remote:[]};for(let r of this.skills.values())e[r.source].push(r);return e}getNames(){return Array.from(this.byName.keys())}has(e){return this.byName.has(e)}get size(){return this.skills.size}get uniqueNameCount(){return this.byName.size}remove(e){let r=this.skills.get(e);if(!r||(this.skills.delete(e),this.byName.get(r.name)!==e))return;let n;for(let s of this.skills.values())s.name===r.name&&(!n||this.hasHigherPriority(s.source,n.source))&&(n=s);n?this.byName.set(r.name,n.id):this.byName.delete(r.name)}clear(){this.skills.clear(),this.byName.clear(),this.discoveredAt=0}getState(){return{skills:new Map(this.skills),byName:new Map(this.byName),discoveredAt:this.discoveredAt}}hasHigherPriority(e,r){let n=t.SOURCE_PRIORITY.indexOf(e),s=t.SOURCE_PRIORITY.indexOf(r);return n<s}}});function C4(t,e){let r=e??new Mi,n=[],s="built-in";for(let{name:o,content:i}of ume)try{let a=r.parse(i),c=a.frontmatter?.name;if(c&&c!==o){console.warn(`Built-in skill name mismatch: expected '${o}', got '${c}'`);continue}let l={id:`${s}:${o}`,name:o,description:a.frontmatter?.description??r.extractFirstParagraph(a.body),source:s,path:`built-in://${o}/SKILL.md`,directory:`built-in://${o}`,userInvocable:a.frontmatter?.["user-invocable"]!==!1,modelInvocable:a.frontmatter?.["disable-model-invocation"]!==!0,loaded:!0,content:a.body,allowedTools:r.parseAllowedTools(a.frontmatter?.["allowed-tools"]),license:a.frontmatter?.license,compatibility:a.frontmatter?.compatibility,argumentHint:a.frontmatter?.["argument-hint"]};t.register(l),n.push(l)}catch(a){console.warn(`Error loading built-in skill '${o}':`,a instanceof Error?a.message:String(a))}return n}var Sat,bat,Iat,Tat,ume,S4=T(()=>{"use strict";f_();Sat=`---
|
|
616
616
|
name: commit
|
|
@@ -1272,7 +1272,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Se=$,Z=z);let ze={code
|
|
|
1272
1272
|
`;if(E===u)return;let y=E.split(`
|
|
1273
1273
|
`),S=zhe(i.rows);y=Whe(y,S);let C="\x1B[0m"+y.join(`
|
|
1274
1274
|
`),w=y.length,k=0;if(l>0){let v=jI(i.rows);k=vO(l,v),i.write(a.eraseLines(k)),i.write("\x1B[0m")}if(i.write(C),ty()){let v=i.rows||0,D=k>=v-2?" DANGER":"";q1(`render caller=${_??"-"} prevLC=${l} newLC=${w} erase=${k} rows=${v}${D}`)}u=E,l=w};h.clear=()=>{if(l>0){let A=jI(i.rows);i.write(a.eraseLines(vO(l,A))),i.write("\x1B[0m")}u="",l=0},h.done=()=>{u="",l=0},XY=()=>{u="",l=0,s.lastOutput=""},ZY=()=>{h.clear(),s.lastOutput=""},vB=A=>{if(Wu){i.write(Zhe),i.write(A);return}Wu=!0,s.throttledLog&&typeof s.throttledLog.cancel=="function"&&s.throttledLog.cancel(),i.write(Jhe),i.write(A)},DB=()=>{if(Wu)if(Wu=!1,i.write(Xhe),m){if(l>0){let _=jI(i.rows);i.write(a.eraseLines(vO(l,_))),i.write("\x1B[0m")}u="",l=0,i.write("\x1B[0m"),i.write(m),m="";let A=o(s.rootNode);h(A.output,"peek-resume"),s.lastOutput=A.output}else s.lastOutput="",s.onRender()},s.log=h,s.throttledLog=bB(h,void 0,{leading:!0,trailing:!0}),s.onRender=()=>{if(s.isUnmounted)return;let{output:A,outputHeight:_,staticOutput:E}=o(s.rootNode),y=E&&E!==`
|
|
1275
|
-
`;if(Wu){y&&E!==d&&(d=E,m+=E),s.lastOutput=A;return}if(s.options.debug){y&&(s.fullStaticOutput+=E),i.write(s.fullStaticOutput+A);return}if(y&&E!==d){if(d=E,p)f+=E;else{p=!0,f=E;let S=l;typeof s.throttledLog.cancel=="function"&&s.throttledLog.cancel(),Promise.resolve().then(()=>{Math.max(l,S)>0&&(i.write(a.eraseLines(Vhe(l,S,i.rows))),i.write("\x1B[0m")),u="",l=0,i.write("\x1B[0m"),i.write(f);let w=o(s.rootNode);h(w.output,"batched-static"),s.lastOutput=w.output,f="",p=!1})}s.lastOutput=A;return}if(p){s.lastOutput=A;return}A!==s.lastOutput&&s.throttledLog(A),s.lastOutput=A},s.rootNode.onRender=bB(s.onRender,32,{leading:!0,trailing:!0}),s.rootNode.onImmediateRender=s.onRender,c&&typeof c.clear=="function"&&(c.clear(),s.lastOutput="",s.onRender()),IB=!0,ty()&&q1(`startup patchInstalled=true rows=${process.stdout.rows||0} cols=${process.stdout.columns||0}`)}else IB=!1,ty()&&q1("startup patchInstalled=false reason=no-ink-instance \u2014 clearTerminal overflow path active; re-anchor will be a no-op")}catch{IB=!1,ty()&&q1("startup patchInstalled=false reason=patch-threw \u2014 clearTerminal overflow path active; re-anchor will be a no-op")}return os&&os.waitUntilExit().then(()=>{}).catch(()=>{}),rc&&(process.stdout.removeListener("resize",rc),rc=null),rc=()=>{yDe();try{Vu().incrementRenderEpoch()}catch{}},process.stdout.on("resize",rc),()=>{rc&&(process.stdout.removeListener("resize",rc),rc=null),os&&(os.unmount(),os=null),process.stdout.write("\x1B[?25h")}}function oy(t){if(!os||!ny||!sy)return;ry={...ry,...t};let e=ny,{App:r}=sy;os.rerender(e.createElement(r,ry))}function Qh(t){Vu().mode!==t&&Vu().setMode(t)}function gIt(t,e){let r=Vu();t&&r.incrementIteration(),r.setThinking(t),e&&r.setStatus(e)}function AIt(t){t||hDe(),Vu().setStreaming(t)}function hDe(){if(nc&&(clearTimeout(nc),nc=null),Fh){let t=Fh;Fh="",RB().appendAndFlush(t)}}function EIt(t){Fh+=t,nc||(nc=setTimeout(hDe,_It))}function yIt(){let t=Fh;Fh="",nc&&(clearTimeout(nc),nc=null),RB().flushAndCommitToStatic(t)}function CIt(){Fh="",nc&&(clearTimeout(nc),nc=null),RB().clear()}function SIt(t,e){Vu().updateContext(t,e)}function gDe(t,e,r={}){setTimeout(()=>{r.shouldRender&&!r.shouldRender()||(oy({permissionDialog:{toolName:t,description:e,details:r.details,showDiff:r.showDiff,options:r.options,onResult:r.onResult,requestId:r.requestId,defaultIndex:r.defaultIndex}}),Qh("dialog"))},50)}function bIt(t,e,r,n,s,o,i,a){return new Promise(c=>{if(o&&YY.has(o)){c("no");return}o&&YY.add(o);let l=!1,u=(f,m)=>{if(l)return!1;l=!0;let h=p.active();if(o&&(YY.delete(o),TB.get(o)===u&&TB.delete(o)),i?.removeEventListener("abort",d),h){try{_De()}catch{}try{a?.onSettled?.({result:f,source:m})}catch{}}return c(f),p.release(),!0},d=()=>{u("no","system")},p=kO(()=>{if(!l){if(i?.aborted){u("no","system");return}o&&TB.set(o,u);try{a?.onReady?.()}catch{u("no","system")}if(!l){if(!tq()){o||u("no","system");return}gDe(t,e,{details:r,showDiff:n,options:s,requestId:o,defaultIndex:a?.defaultIndex,shouldRender:()=>!l&&p.active(),onResult:f=>u(f,"terminal")})}}});if(i?.aborted){u("no","system");return}i?.addEventListener("abort",d,{once:!0}),p.start()})}function eq(t,e){let r=TB.get(t);if(r)return r(e,"portal");let n=ry.permissionDialog;return ADe(n,t)?(n.onResult?.(e),!0):!1}function ADe(t,e){return!!t&&t.requestId===e}function _De(){oy({permissionDialog:void 0}),Vu().isStreaming?Qh("streaming"):Qh("input")}function IIt(t,e,r,n=!0,s){return Yhe(t,e,r,n,{available:tq,hide:EDe,mount:(o,i)=>{oy({questionDialog:{question:t,description:r,options:o,allowOther:n,onResult:i}}),Qh("dialog")}},s)}function EDe(){oy({questionDialog:void 0}),Vu().isStreaming?Qh("streaming"):Qh("input")}function yDe(){XY&&XY()}function TIt(){if(ZY){ZY();return}!mDe&&ty()&&(mDe=!0,q1("WARN reanchorRenderState() called but onRender patch not installed \u2014 re-anchor is a no-op (footer-at-top guard inactive)"))}function H1(){return IB}function UY(t){vB?.(t)}function yB(){DB?.()}function tq(){return os!==null}function wIt(){rc&&(process.stdout.removeListener("resize",rc),rc=null),Wu&&(process.stdout.write("\x1B[?1049l"),Wu=!1),vB=null,DB=null,os&&(os.unmount(),os=null),process.stdout.write("\x1B[?25h")}async function kIt(){os&&await os.waitUntilExit()}function vIt(){return new aIt}function DIt(t){os&&oy({onInterrupt:t??void 0})}var os,wB,ny,sy,kB,qY,zY,WY,VY,jY,KY,bB,JY,XY,ZY,mDe,Wu,vB,DB,IB,SB,rc,ry,Fh,nc,_It,TB,YY,Os=T(()=>{"use strict";sH();qhe();jhe();DO();os=null,wB=null,ny=null,sy=null,kB=null,qY=null,zY=null,WY=null,VY=null,jY=null,KY=null,bB=null,JY=null,XY=null,ZY=null,mDe=!1,Wu=!1,vB=null,DB=null,IB=!1;rc=null,ry={};Fh="",nc=null,_It=50;TB=new Map,YY=new Set});import{randomUUID as RIt}from"node:crypto";var iy,CDe=T(()=>{"use strict";VI();zr();iy=class extends Xe{name="AskUserQuestion";get description(){return`Pause execution and ask the user a multiple-choice question. Use when there are multiple valid approaches and you need the user's decision before proceeding. Provide 2-4 options with descriptions. Always allow "Other" so the user isn't boxed in. Returns the user's selected label or "[Other]: <text>" for free-form answers.`}permissionLevel="SAFE";inputSchema={type:"object",properties:{question:{type:"string",description:"The question to ask the user"},description:{type:"string",description:"Optional context shown below the question"},options:{type:"array",description:"Array of 1-9 options. Each entry has a label (required) and description (optional)."},allowOther:{type:"boolean",description:'Allow free-form "Other" input. Default: true.',default:!0}},required:["question","options"]};async execute(e,r){let n=e._callId||`askuserquestion_${Date.now()}`,s=this.validateRequired(e,["question","options"]);if(s)return this.error(n,s);if(!Vi(e.question,Number.MAX_SAFE_INTEGER))return this.error(n,"question must be a non-empty string");let o=e.question;if(e.description!==void 0&&!Vi(e.description,Number.MAX_SAFE_INTEGER,!1))return this.error(n,"description must be plain text");if(e.allowOther!==void 0&&typeof e.allowOther!="boolean")return this.error(n,"allowOther must be boolean");let i=e.description,a=e.options,c=e.allowOther!==!1;if(!Array.isArray(a)||a.length===0)return this.error(n,"options must be a non-empty array");if(a.length>9)return this.error(n,"options cannot exceed 9 (1-9 number key shortcuts)");let l=[];for(let d=0;d<a.length;d++){let p=a[d];if(!p||typeof p!="object")return this.error(n,`Option ${d+1}: must be an object with a "label" field`);if(!Vi(p.label,Number.MAX_SAFE_INTEGER))return this.error(n,`Option ${d+1}: missing required field "label"`);if(p.description!==void 0&&!Vi(p.description,Number.MAX_SAFE_INTEGER,!1))return this.error(n,`Option ${d+1}: description must be plain text`);l.push({label:p.label,description:typeof p.description=="string"?p.description:void 0})}let{showQuestionDialogAsync:u}=await Promise.resolve().then(()=>(Os(),ui));try{let d=await u(o,l,i,c,{signal:r.abortSignal,hooks:r.question,requestId:RIt()});return d.type==="option"?this.success(n,d.label):d.type==="other"?this.success(n,`[Other]: ${d.text}`):this.error(n,"User cancelled the question")}catch(d){let p=d instanceof Error?d.message:String(d);return this.error(n,`Failed to show question dialog: ${p}`)}}formatAction(e){let r=e.question??"";return r.length>60?r.slice(0,57)+"...":r}}});var rq=T(()=>{"use strict";CDe()});function Kp(t){let e=vo(),r=ch(),n=new Set(t.disallowedTools??[]);if(!t.preserveTaskTools){let o=["Task","TaskOutput","TaskStop","TaskContinue"];for(let i of o)n.add(i)}let s=e.getAll();for(let o of s){let i=o.definition.name;n.has(i)||t.allowedTools&&!t.allowedTools.includes(i)||r.register(o)}return r}var NB=T(()=>{"use strict";Jp()});import{constants as nq}from"node:fs";import{open as NIt,realpath as sq,stat as SDe}from"node:fs/promises";import OIt from"node:path";import{createHash as xIt}from"node:crypto";var oq,OB,bDe=T(()=>{"use strict";zr();Jn();oq=1024*1024,OB=class extends Xe{name="Preview";description="Show a named local HTML file privately in the current AiiCloud conversation. Use only when the user asks to show or preview that file. Transfers the unchanged file; do not copy its source into the reply.";permissionLevel="SAFE";inputSchema={type:"object",properties:{file_path:{type:"string",description:"Path to the requested .html or .htm file (at most 1 MiB)."}},required:["file_path"]};async execute(e,r){let n=typeof e._callId=="string"?e._callId:"preview",s=e.file_path;if(typeof s!="string"||!s||s.length>4096||s.includes("\0"))return this.error(n,"Preview requires a valid file_path.");if(!r.preview)return this.error(n,"Preview requires an active AiiCloud remote-control conversation.");let o=an(r),i=Lt(s,o,{tempDir:r.session.tempDir});if(!i.ok)return this.error(n,"Preview cannot resolve this file path.");if(!/\.html?$/i.test(i.resolved))return this.error(n,"Preview supports .html and .htm files only.");try{r.preview.assertCurrent(r.abortSignal);let a=await sq(i.resolved);if(a!==r.previewReadPath)throw new Error("The preview file changed after its permission check.");let c={workspaceRoot:r.session.projectPath,base:o,op:"read",tempDir:r.session.tempDir},l=Cn(i.resolved,c),u=await SDe(a,{bigint:!0});if(!u.isFile()||u.size<=0n||u.size>BigInt(oq))throw new Error("Preview requires a nonempty regular HTML file up to 1 MiB.");r.preview.assertCurrent(r.abortSignal);let d=await NIt(a,nq.O_RDONLY|nq.O_NONBLOCK|nq.O_NOFOLLOW),p,f;try{let A=await d.stat({bigint:!0});if(!A.isFile()||A.dev!==u.dev||A.ino!==u.ino||await sq(i.resolved)!==a||Cn(i.resolved,c)!==l)throw new Error("The preview file changed while opening; try again.");f=Buffer.alloc(oq+1);let _=0;for(;_<f.length;){r.preview.assertCurrent(r.abortSignal);let S=await d.read(f,_,f.length-_,_);if(!S.bytesRead)break;_+=S.bytesRead}let E=await d.stat({bigint:!0}),y=await SDe(a,{bigint:!0});if(_<=0||_>oq)throw new Error("Preview requires a nonempty regular HTML file up to 1 MiB.");if(A.size!==BigInt(_)||E.size!==A.size||E.mtimeNs!==A.mtimeNs||E.ctimeNs!==A.ctimeNs||y.dev!==A.dev||y.ino!==A.ino||y.size!==E.size||y.mtimeNs!==E.mtimeNs||y.ctimeNs!==E.ctimeNs||await sq(i.resolved)!==a)throw new Error("The preview file changed while reading; try again.");if(f=f.subarray(0,_),p=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(f),!Buffer.from(p,"utf8").equals(f))throw new Error("Preview requires valid UTF-8.")}finally{await d.close()}r.preview.assertCurrent(r.abortSignal);let m=OIt.basename(i.resolved);if(Buffer.byteLength(m,"utf8")>255||/[\\\x00-\x1f\x7f]/.test(m))throw new Error("Preview requires a printable filename without backslashes, at most 255 UTF-8 bytes.");let h=await r.preview.publish({filename:m,content:p,bytes:f.length,sha256:xIt("sha256").update(f).digest("hex")},r.abortSignal);return this.success(n,JSON.stringify(h))}catch(a){let c=a instanceof Error&&/^(Preview |The preview file |AiiCloud preview )/.test(a.message)?a.message:"Preview could not read or publish this HTML file.";return this.error(n,c)}}formatAction(e){return typeof e.file_path=="string"?e.file_path:""}}});function iq(){let t=[...CI(),new OB,...bI(),...b3(),new II,new iE,new aE,new pE,new fE,new mE,new hE,new _E,new EE,new yE,new iy];if(me.hasInstance()){let e=me.getInstance(),r=new Va(e);t.push(wN(e,r))}return t}function vo(){let t=ch();return t.registerAll(iq()),t}var Jp=T(()=>{"use strict";zr();qN();jN();JN();ZN();I3();gE();gE();gE();gE();rH();rq();NB();N4();jN();bDe();JN();ZN();I3();gE();rH();rq();qN();ii()});var BIt,MIt,LIt,PIt,jr,ay=T(()=>{"use strict";BIt={text:4,code:3,mixed:3.5,json:2.8},MIt=1.1,LIt=[/\bfunction\b|\bconst\b|\blet\b|\bvar\b|\bclass\b|\bimport\b|\bexport\b/,/\bdef\b|\bclass\b|\bimport\b|\bfrom\b|\bif __name__/,/\{\s*\n|\}\s*\n|=>\s*\{|\)\s*\{/,/;\s*\n|;\s*$/m,/^\s*(\/\/|#|\/\*|\*)/m],PIt=[/^\s*\{[\s\S]*\}\s*$/,/^\s*\[[\s\S]*\]\s*$/,/"[^"]+"\s*:/],jr=class t{static count(e,r){if(!e||e.length===0)return 0;let n=r??t.detectContentType(e),s=BIt[n],o=e.length/s;return Math.ceil(o*MIt)}static detectContentType(e){for(let n of PIt)if(n.test(e))return"json";let r=0;for(let n of LIt)n.test(e)&&r++;return r>=2?"code":r>=1?"mixed":"text"}static tokenizeMessage(e,r,n){return{role:e,content:r,tokens:t.count(r)+4,timestamp:n}}static countMessages(e){let r=0;for(let n of e)r+=t.count(n.content)+4;return r}static calculateBreakdown(e,r,n,s){let o=typeof r=="string"?r:JSON.stringify(r),i=t.count(e,"text"),a=t.count(o,"json"),c=t.countMessages(n),l=s?t.count(s,"text"):0;return{systemPrompt:i,toolDefinitions:a,conversation:c,summary:l,total:i+a+c+l}}static estimateSystemPromptTokens(){return 2500}static estimateToolDefinitionTokens(e){return e*200}static formatTokens(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString()}static calculatePercentage(e,r){return r<=0?0:Math.min(100,Math.round(e/r*100))}}});var FIt,cy,aq=T(()=>{"use strict";FIt={model:void 0,maxSummaryTokens:4096},cy=class{client;config;sessionModel=null;constructor(e,r){this.client=e,this.config={...FIt,...r}}setSessionModel(e){this.sessionModel=e}getModel(){return this.config.model??this.sessionModel??void 0}async summarize(e,r){if(e.length===0)return"No previous conversation history.";if(!this.client)throw new Error("Context compaction unavailable: no selected summarizer");let n=await this.client.summarize({content:this.formatConversationHistory(e),maxTokens:this.config.maxSummaryTokens??4096,model:this.getModel(),signal:r});if(typeof n.summary!="string"||!n.summary.trim())throw new Error("Context compaction returned no complete summary");return n.summary}formatConversationHistory(e){return e.map(r=>`${r.role==="user"?"User":r.role==="assistant"?"Assistant":r.role==="system"?"System":"Tool"}: ${r.content}`).join(`
|
|
1275
|
+
`;if(Wu){y&&E!==d&&(d=E,m+=E),s.lastOutput=A;return}if(s.options.debug){y&&(s.fullStaticOutput+=E),i.write(s.fullStaticOutput+A);return}if(y&&E!==d){if(d=E,p)f+=E;else{p=!0,f=E;let S=l;typeof s.throttledLog.cancel=="function"&&s.throttledLog.cancel(),Promise.resolve().then(()=>{Math.max(l,S)>0&&(i.write(a.eraseLines(Vhe(l,S,i.rows))),i.write("\x1B[0m")),u="",l=0,i.write("\x1B[0m"),i.write(f);let w=o(s.rootNode);h(w.output,"batched-static"),s.lastOutput=w.output,f="",p=!1})}s.lastOutput=A;return}if(p){s.lastOutput=A;return}A!==s.lastOutput&&s.throttledLog(A),s.lastOutput=A},s.rootNode.onRender=bB(s.onRender,32,{leading:!0,trailing:!0}),s.rootNode.onImmediateRender=s.onRender,c&&typeof c.clear=="function"&&(c.clear(),s.lastOutput="",s.onRender()),IB=!0,ty()&&q1(`startup patchInstalled=true rows=${process.stdout.rows||0} cols=${process.stdout.columns||0}`)}else IB=!1,ty()&&q1("startup patchInstalled=false reason=no-ink-instance \u2014 clearTerminal overflow path active; re-anchor will be a no-op")}catch{IB=!1,ty()&&q1("startup patchInstalled=false reason=patch-threw \u2014 clearTerminal overflow path active; re-anchor will be a no-op")}return os&&os.waitUntilExit().then(()=>{}).catch(()=>{}),rc&&(process.stdout.removeListener("resize",rc),rc=null),rc=()=>{yDe();try{Vu().incrementRenderEpoch()}catch{}},process.stdout.on("resize",rc),()=>{rc&&(process.stdout.removeListener("resize",rc),rc=null),os&&(os.unmount(),os=null),process.stdout.write("\x1B[?25h")}}function oy(t){if(!os||!ny||!sy)return;ry={...ry,...t};let e=ny,{App:r}=sy;os.rerender(e.createElement(r,ry))}function Qh(t){Vu().mode!==t&&Vu().setMode(t)}function gIt(t,e){let r=Vu();t&&r.incrementIteration(),r.setThinking(t),e&&r.setStatus(e)}function AIt(t){t||hDe(),Vu().setStreaming(t)}function hDe(){if(nc&&(clearTimeout(nc),nc=null),Fh){let t=Fh;Fh="",RB().appendAndFlush(t)}}function EIt(t){Fh+=t,nc||(nc=setTimeout(hDe,_It))}function yIt(){let t=Fh;Fh="",nc&&(clearTimeout(nc),nc=null),RB().flushAndCommitToStatic(t)}function CIt(){Fh="",nc&&(clearTimeout(nc),nc=null),RB().clear()}function SIt(t,e){Vu().updateContext(t,e)}function gDe(t,e,r={}){setTimeout(()=>{r.shouldRender&&!r.shouldRender()||(oy({permissionDialog:{toolName:t,description:e,details:r.details,showDiff:r.showDiff,options:r.options,onResult:r.onResult,requestId:r.requestId,defaultIndex:r.defaultIndex}}),Qh("dialog"))},50)}function bIt(t,e,r,n,s,o,i,a){return new Promise(c=>{if(o&&YY.has(o)){c("no");return}o&&YY.add(o);let l=!1,u=(f,m)=>{if(l)return!1;l=!0;let h=p.active();if(o&&(YY.delete(o),TB.get(o)===u&&TB.delete(o)),i?.removeEventListener("abort",d),h){try{_De()}catch{}try{a?.onSettled?.({result:f,source:m})}catch{}}return c(f),p.release(),!0},d=()=>{u("no","system")},p=kO(()=>{if(!l){if(i?.aborted){u("no","system");return}o&&TB.set(o,u);try{a?.onReady?.()}catch{u("no","system")}if(!l){if(!tq()){o||u("no","system");return}gDe(t,e,{details:r,showDiff:n,options:s,requestId:o,defaultIndex:a?.defaultIndex,shouldRender:()=>!l&&p.active(),onResult:f=>u(f,"terminal")})}}});if(i?.aborted){u("no","system");return}i?.addEventListener("abort",d,{once:!0}),p.start()})}function eq(t,e){let r=TB.get(t);if(r)return r(e,"portal");let n=ry.permissionDialog;return ADe(n,t)?(n.onResult?.(e),!0):!1}function ADe(t,e){return!!t&&t.requestId===e}function _De(){oy({permissionDialog:void 0}),Vu().isStreaming?Qh("streaming"):Qh("input")}function IIt(t,e,r,n=!0,s){return Yhe(t,e,r,n,{available:tq,hide:EDe,mount:(o,i)=>{oy({questionDialog:{question:t,description:r,options:o,allowOther:n,onResult:i}}),Qh("dialog")}},s)}function EDe(){oy({questionDialog:void 0}),Vu().isStreaming?Qh("streaming"):Qh("input")}function yDe(){XY&&XY()}function TIt(){if(ZY){ZY();return}!mDe&&ty()&&(mDe=!0,q1("WARN reanchorRenderState() called but onRender patch not installed \u2014 re-anchor is a no-op (footer-at-top guard inactive)"))}function H1(){return IB}function UY(t){vB?.(t)}function yB(){DB?.()}function tq(){return os!==null}function wIt(){rc&&(process.stdout.removeListener("resize",rc),rc=null),Wu&&(process.stdout.write("\x1B[?1049l"),Wu=!1),vB=null,DB=null,os&&(os.unmount(),os=null),process.stdout.write("\x1B[?25h")}async function kIt(){os&&await os.waitUntilExit()}function vIt(){return new aIt}function DIt(t){os&&oy({onInterrupt:t??void 0})}var os,wB,ny,sy,kB,qY,zY,WY,VY,jY,KY,bB,JY,XY,ZY,mDe,Wu,vB,DB,IB,SB,rc,ry,Fh,nc,_It,TB,YY,Os=T(()=>{"use strict";sH();qhe();jhe();DO();os=null,wB=null,ny=null,sy=null,kB=null,qY=null,zY=null,WY=null,VY=null,jY=null,KY=null,bB=null,JY=null,XY=null,ZY=null,mDe=!1,Wu=!1,vB=null,DB=null,IB=!1;rc=null,ry={};Fh="",nc=null,_It=50;TB=new Map,YY=new Set});import{randomUUID as RIt}from"node:crypto";var iy,CDe=T(()=>{"use strict";VI();zr();iy=class extends Xe{name="AskUserQuestion";get description(){return`Pause execution and ask the user a multiple-choice question. Use when there are multiple valid approaches and you need the user's decision before proceeding. Provide 2-4 options with descriptions. Always allow "Other" so the user isn't boxed in. Returns the user's selected label or "[Other]: <text>" for free-form answers.`}permissionLevel="SAFE";inputSchema={type:"object",properties:{question:{type:"string",description:"The question to ask the user"},description:{type:"string",description:"Optional context shown below the question"},options:{type:"array",description:"Array of 1-9 options. Each entry has a label (required) and description (optional)."},allowOther:{type:"boolean",description:'Allow free-form "Other" input. Default: true.',default:!0}},required:["question","options"]};async execute(e,r){let n=e._callId||`askuserquestion_${Date.now()}`,s=this.validateRequired(e,["question","options"]);if(s)return this.error(n,s);if(!Vi(e.question,Number.MAX_SAFE_INTEGER))return this.error(n,"question must be a non-empty string");let o=e.question;if(e.description!==void 0&&!Vi(e.description,Number.MAX_SAFE_INTEGER,!1))return this.error(n,"description must be plain text");if(e.allowOther!==void 0&&typeof e.allowOther!="boolean")return this.error(n,"allowOther must be boolean");let i=e.description,a=e.options,c=e.allowOther!==!1;if(!Array.isArray(a)||a.length===0)return this.error(n,"options must be a non-empty array");if(a.length>9)return this.error(n,"options cannot exceed 9 (1-9 number key shortcuts)");let l=[];for(let d=0;d<a.length;d++){let p=a[d];if(!p||typeof p!="object")return this.error(n,`Option ${d+1}: must be an object with a "label" field`);if(!Vi(p.label,Number.MAX_SAFE_INTEGER))return this.error(n,`Option ${d+1}: missing required field "label"`);if(p.description!==void 0&&!Vi(p.description,Number.MAX_SAFE_INTEGER,!1))return this.error(n,`Option ${d+1}: description must be plain text`);l.push({label:p.label,description:typeof p.description=="string"?p.description:void 0})}let{showQuestionDialogAsync:u}=await Promise.resolve().then(()=>(Os(),ui));try{let d=await u(o,l,i,c,{signal:r.abortSignal,hooks:r.question,requestId:RIt()});return d.type==="option"?this.success(n,d.label):d.type==="other"?this.success(n,`[Other]: ${d.text}`):this.error(n,"User cancelled the question")}catch(d){let p=d instanceof Error?d.message:String(d);return this.error(n,`Failed to show question dialog: ${p}`)}}formatAction(e){let r=e.question??"";return r.length>60?r.slice(0,57)+"...":r}}});var rq=T(()=>{"use strict";CDe()});function Kp(t){let e=vo(),r=ch(),n=new Set(t.disallowedTools??[]);if(!t.preserveTaskTools){let o=["Task","TaskOutput","TaskStop","TaskContinue"];for(let i of o)n.add(i)}let s=e.getAll();for(let o of s){let i=o.definition.name;n.has(i)||t.allowedTools&&!t.allowedTools.includes(i)||r.register(o)}return r}var NB=T(()=>{"use strict";Jp()});import{constants as nq}from"node:fs";import{open as NIt,realpath as sq,stat as SDe}from"node:fs/promises";import OIt from"node:path";import{createHash as xIt}from"node:crypto";var oq,OB,bDe=T(()=>{"use strict";zr();Jn();oq=1024*1024,OB=class extends Xe{name="Preview";description="Show a local HTML file privately in the current AiiCloud conversation. Use for an explicitly requested named-file preview or the standalone HTML deliverable created or updated for the current user request, including approved designs and continuations. Call after final writes and verification. Respect local-only or no-upload instructions; do not upload unrelated files, repository fixtures, supporting assets, or every modified HTML file. Transfers the complete unchanged file; do not copy source into the reply or invent upload commands. Report unavailable, denied, failed or unconfirmed previews honestly; preserve the local file and do not retry an unconfirmed publication in the same turn.";permissionLevel="SAFE";inputSchema={type:"object",properties:{file_path:{type:"string",description:"Path to the requested .html or .htm file (at most 1 MiB)."}},required:["file_path"]};async execute(e,r){let n=typeof e._callId=="string"?e._callId:"preview",s=e.file_path;if(typeof s!="string"||!s||s.length>4096||s.includes("\0"))return this.error(n,"Preview requires a valid file_path.");if(!r.preview)return this.error(n,"Preview requires an active AiiCloud remote-control conversation.");let o=an(r),i=Lt(s,o,{tempDir:r.session.tempDir});if(!i.ok)return this.error(n,"Preview cannot resolve this file path.");if(!/\.html?$/i.test(i.resolved))return this.error(n,"Preview supports .html and .htm files only.");try{r.preview.assertCurrent(r.abortSignal);let a=await sq(i.resolved);if(a!==r.previewReadPath)throw new Error("The preview file changed after its permission check.");let c={workspaceRoot:r.session.projectPath,base:o,op:"read",tempDir:r.session.tempDir},l=Cn(i.resolved,c),u=await SDe(a,{bigint:!0});if(!u.isFile()||u.size<=0n||u.size>BigInt(oq))throw new Error("Preview requires a nonempty regular HTML file up to 1 MiB.");r.preview.assertCurrent(r.abortSignal);let d=await NIt(a,nq.O_RDONLY|nq.O_NONBLOCK|nq.O_NOFOLLOW),p,f;try{let A=await d.stat({bigint:!0});if(!A.isFile()||A.dev!==u.dev||A.ino!==u.ino||await sq(i.resolved)!==a||Cn(i.resolved,c)!==l)throw new Error("The preview file changed while opening; try again.");f=Buffer.alloc(oq+1);let _=0;for(;_<f.length;){r.preview.assertCurrent(r.abortSignal);let S=await d.read(f,_,f.length-_,_);if(!S.bytesRead)break;_+=S.bytesRead}let E=await d.stat({bigint:!0}),y=await SDe(a,{bigint:!0});if(_<=0||_>oq)throw new Error("Preview requires a nonempty regular HTML file up to 1 MiB.");if(A.size!==BigInt(_)||E.size!==A.size||E.mtimeNs!==A.mtimeNs||E.ctimeNs!==A.ctimeNs||y.dev!==A.dev||y.ino!==A.ino||y.size!==E.size||y.mtimeNs!==E.mtimeNs||y.ctimeNs!==E.ctimeNs||await sq(i.resolved)!==a)throw new Error("The preview file changed while reading; try again.");if(f=f.subarray(0,_),p=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(f),!Buffer.from(p,"utf8").equals(f))throw new Error("Preview requires valid UTF-8.")}finally{await d.close()}r.preview.assertCurrent(r.abortSignal);let m=OIt.basename(i.resolved);if(Buffer.byteLength(m,"utf8")>255||/[\\\x00-\x1f\x7f]/.test(m))throw new Error("Preview requires a printable filename without backslashes, at most 255 UTF-8 bytes.");let h=await r.preview.publish({filename:m,content:p,bytes:f.length,sha256:xIt("sha256").update(f).digest("hex")},r.abortSignal);return this.success(n,JSON.stringify(h))}catch(a){let c=a instanceof Error&&/^(Preview |The preview file |AiiCloud preview )/.test(a.message)?a.message:"Preview could not read or publish this HTML file.";return this.error(n,c)}}formatAction(e){return typeof e.file_path=="string"?e.file_path:""}}});function iq(){let t=[...CI(),new OB,...bI(),...b3(),new II,new iE,new aE,new pE,new fE,new mE,new hE,new _E,new EE,new yE,new iy];if(me.hasInstance()){let e=me.getInstance(),r=new Va(e);t.push(wN(e,r))}return t}function vo(){let t=ch();return t.registerAll(iq()),t}var Jp=T(()=>{"use strict";zr();qN();jN();JN();ZN();I3();gE();gE();gE();gE();rH();rq();NB();N4();jN();bDe();JN();ZN();I3();gE();rH();rq();qN();ii()});var BIt,MIt,LIt,PIt,jr,ay=T(()=>{"use strict";BIt={text:4,code:3,mixed:3.5,json:2.8},MIt=1.1,LIt=[/\bfunction\b|\bconst\b|\blet\b|\bvar\b|\bclass\b|\bimport\b|\bexport\b/,/\bdef\b|\bclass\b|\bimport\b|\bfrom\b|\bif __name__/,/\{\s*\n|\}\s*\n|=>\s*\{|\)\s*\{/,/;\s*\n|;\s*$/m,/^\s*(\/\/|#|\/\*|\*)/m],PIt=[/^\s*\{[\s\S]*\}\s*$/,/^\s*\[[\s\S]*\]\s*$/,/"[^"]+"\s*:/],jr=class t{static count(e,r){if(!e||e.length===0)return 0;let n=r??t.detectContentType(e),s=BIt[n],o=e.length/s;return Math.ceil(o*MIt)}static detectContentType(e){for(let n of PIt)if(n.test(e))return"json";let r=0;for(let n of LIt)n.test(e)&&r++;return r>=2?"code":r>=1?"mixed":"text"}static tokenizeMessage(e,r,n){return{role:e,content:r,tokens:t.count(r)+4,timestamp:n}}static countMessages(e){let r=0;for(let n of e)r+=t.count(n.content)+4;return r}static calculateBreakdown(e,r,n,s){let o=typeof r=="string"?r:JSON.stringify(r),i=t.count(e,"text"),a=t.count(o,"json"),c=t.countMessages(n),l=s?t.count(s,"text"):0;return{systemPrompt:i,toolDefinitions:a,conversation:c,summary:l,total:i+a+c+l}}static estimateSystemPromptTokens(){return 2500}static estimateToolDefinitionTokens(e){return e*200}static formatTokens(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString()}static calculatePercentage(e,r){return r<=0?0:Math.min(100,Math.round(e/r*100))}}});var FIt,cy,aq=T(()=>{"use strict";FIt={model:void 0,maxSummaryTokens:4096},cy=class{client;config;sessionModel=null;constructor(e,r){this.client=e,this.config={...FIt,...r}}setSessionModel(e){this.sessionModel=e}getModel(){return this.config.model??this.sessionModel??void 0}async summarize(e,r){if(e.length===0)return"No previous conversation history.";if(!this.client)throw new Error("Context compaction unavailable: no selected summarizer");let n=await this.client.summarize({content:this.formatConversationHistory(e),maxTokens:this.config.maxSummaryTokens??4096,model:this.getModel(),signal:r});if(typeof n.summary!="string"||!n.summary.trim())throw new Error("Context compaction returned no complete summary");return n.summary}formatConversationHistory(e){return e.map(r=>`${r.role==="user"?"User":r.role==="assistant"?"Assistant":r.role==="system"?"System":"Tool"}: ${r.content}`).join(`
|
|
1276
1276
|
|
|
1277
1277
|
`)}hasClient(){return this.client!==null}}});import{EventEmitter as QIt}from"events";function cq(t,e,r,n,s){return new xB(t,e,r,n,s)}var xB,IDe=T(()=>{"use strict";aO();ay();Mp();WR();aq();xB=class extends QIt{config;modelInfoCache;currentModel;thresholds;summarizer;messages=[];summary=null;summaryTokens=0;summarizedTurnCount=0;systemPromptTokens=0;toolDefinitionsTokens=0;serverReportedInputTokens=0;warningShown=!1;isSummarizing=!1;summarizationAborted=!1;generation=0;preparation;committing=!1;constructor(e,r,n,s,o){super(),this.config={...DI,...s},this.currentModel=e,this.modelInfoCache=ws.getInstance(r,n),this.thresholds=RI,this.summarizer=new cy(o??null),this.summarizer.setSessionModel(e)}setSummarizerClient(e){this.summarizer=new cy(e),this.summarizer.setSessionModel(this.currentModel)}async initialize(){await this.modelInfoCache.initialize(),this.thresholds=this.modelInfoCache.getThresholds(this.currentModel)}setModel(e){this.generation++,this.currentModel=e,this.thresholds=this.modelInfoCache.getThresholds(e),this.warningShown=!1,this.summarizer.setSessionModel(e),this.emit("stateChange",this.getState())}setSystemPromptTokens(e){this.systemPromptTokens=e}setToolDefinitionsTokens(e){this.toolDefinitionsTokens=e}restoreMessages(e){this.generation++;let r=e[0],n=r?.role==="system"&&r.content.startsWith(`=== CONVERSATION SUMMARY (older turns) ===
|
|
1278
1278
|
`)?r.content.slice(43).replace(/\n=== END SUMMARY ===$/,""):null;this.summary=n,this.summaryTokens=n?jr.count(n):0,this.messages=e.slice(n===null?0:1).map(s=>jr.tokenizeMessage(s.role,s.content,Date.now()))}addMessage(e,r){let n=jr.tokenizeMessage(e,r,Date.now());this.messages.push(n),this.checkThresholds()}updateFromServerUsage(e){this.serverReportedInputTokens=e,this.checkThresholds()}getState(){let e=this.getTokenBreakdown(),r=this.calculateUsagePercent(e.total),n=this.determineStatus();return{tokens:e,model:this.currentModel,thresholds:this.thresholds,usagePercent:r,status:n,hasSummary:this.summary!==null,turnCount:this.messages.filter(s=>s.role==="user").length,summarizedTurnCount:this.summarizedTurnCount}}getTokenBreakdown(){let e=this.messages.reduce((s,o)=>s+o.tokens,0),r=this.systemPromptTokens+this.toolDefinitionsTokens+e+this.summaryTokens,n=this.serverReportedInputTokens>0?this.serverReportedInputTokens:r;return{systemPrompt:this.systemPromptTokens,toolDefinitions:this.toolDefinitionsTokens,conversation:e,summary:this.summaryTokens,total:n}}calculateUsagePercent(e){let n=this.getModelInfo()?.contextLength??this.thresholds.usableContext;return n<=0?0:Math.min(1,e/n)}determineStatus(){let e=this.getModelInfo();if(!e)return process.env.AII_DEBUG&&console.error(`[DEBUG] determineStatus: No model info for "${this.currentModel}"`),"normal";let r=this.getTokenBreakdown();if(this.serverReportedInputTokens===0)return process.env.AII_DEBUG&&console.error(`[DEBUG] determineStatus: skipping threshold check \u2014 no server-reported tokens yet (local estimate: ${r.total})`),"normal";let n=r.total/e.contextLength;return process.env.AII_DEBUG&&r.total>1e4&&console.error(`[DEBUG] determineStatus: tokens=${r.total}, contextLength=${e.contextLength}, rawPercent=${(n*100).toFixed(1)}%, thresholds=[warn=${(this.thresholds.warning*100).toFixed(0)}%, crit=${(this.thresholds.critical*100).toFixed(0)}%, overflow=${(this.thresholds.overflow*100).toFixed(0)}%]`),n>=this.thresholds.overflow?"overflow":n>=this.thresholds.critical?"critical":n>=this.thresholds.warning?"warning":"normal"}checkThresholds(){let e=this.getState();this.emit("stateChange",e),e.status==="warning"&&!this.warningShown&&(this.warningShown=!0,this.emit("warning",e)),(e.status==="critical"||e.status==="overflow")&&this.emit("critical",e)}needsSummarization(){let e=this.getState();return e.status==="critical"||e.status==="overflow"}isSummarizationInProgress(){return this.isSummarizing}abortSummarization(){this.isSummarizing&&!this.committing&&(this.preparation?.abort(),this.summarizationAborted=!0)}summarizationFailure;getSummarizationFailure(){return this.summarizationFailure}async performSummarization(e={}){if(this.isSummarizing)return null;this.summarizationFailure=void 0;let r=structuredClone(this.messages),n=this.getMessagesToSummarize().length;if(!n)return null;let s={generation:this.generation,fingerprint:this.contextFingerprint(),recent:r.slice(n),summary:"",turnsSummarized:r.slice(0,n).filter(c=>c.role==="user").length,beforeTokens:this.getTokenBreakdown().total},o=this.summary;this.isSummarizing=!0,this.summarizationAborted=!1;let i=new AbortController;this.preparation=i;let a;this.emit("summarizationStart");try{let c=o?[jr.tokenizeMessage("system",o,Date.now()),...r.slice(0,n)]:r.slice(0,n),l=new Promise((p,f)=>{a=setTimeout(()=>{i.abort(),f(new Error("Context compaction preparation timed out"))},e.timeoutMs??9e4),a.unref()}),u,d=this.summarizer.summarize(c,i.signal);try{s.summary=await Promise.race([d,l])}catch(p){u=p}finally{clearTimeout(a),this.preparation=void 0}if(i.signal.aborted&&await d.catch(()=>{}),this.committing=!0,await e.settle?.(),u)throw u;return i.signal.aborted||this.summarizationAborted||!this.isPreparedSummaryCurrent(s)?null:(this.committing=!0,e.commit?await e.commit(s):this.applyPreparedSummary(s))}catch(c){return this.summarizationFailure=c instanceof ln?c.message:"Context compaction did not commit; original history retained.",this.emit("summarizationError",new Error(this.summarizationFailure)),null}finally{clearTimeout(a),this.preparation=void 0,this.committing=!1,this.isSummarizing=!1}}contextFingerprint(){return JSON.stringify([this.currentModel,this.summary,this.messages])}isPreparedSummaryCurrent(e){return e.generation===this.generation&&e.fingerprint===this.contextFingerprint()}applyPreparedSummary(e,r=!0){if(!this.isPreparedSummaryCurrent(e))throw new Error("Context changed during compaction");return this.applySummarization(e.summary,e.turnsSummarized,e.recent,e.beforeTokens,r)}hasSummarizerClient(){return this.summarizer.hasClient()}getMessagesToSummarize(){let e=this.config.recentTokensTarget,r=0,n=0;for(let s=this.messages.length-1;s>=0;s--)if(r+=this.messages[s].tokens,r>=e){n=s;break}return n===0&&this.messages.length>=2&&this.needsSummarization()?(n=this.messages.length<=3?this.messages.length-1:Math.floor(this.messages.length/2),process.env.AII_DEBUG&&console.error(`[DEBUG] getMessagesToSummarize: Using fallback split at index ${n} (${this.messages.length} total messages)`)):n===0&&this.messages.length===1&&this.needsSummarization()&&process.env.AII_DEBUG&&(console.error("[DEBUG] getMessagesToSummarize: Mid-turn scenario - only 1 local message, server reports overflow"),console.error(`[DEBUG] - Local messages: ${this.messages.length}, Server tokens: ${this.serverReportedInputTokens}`)),this.messages.slice(0,n)}getRecentMessages(){let e=this.config.recentTokensTarget,r=0,n=0;for(let s=this.messages.length-1;s>=0;s--)if(r+=this.messages[s].tokens,r>=e){n=s;break}return n===0&&this.messages.length>=2&&this.needsSummarization()&&(n=this.messages.length<=3?this.messages.length-1:Math.floor(this.messages.length/2)),this.messages.slice(n)}getOverlapMessages(){let e=this.getMessagesToSummarize(),r=this.config.overlapTokens,n=0,s=[];for(let o=e.length-1;o>=0;o--){let i=e[o];if(n+i.tokens>r)break;s.unshift(i),n+=i.tokens}return s}applySummarization(e,r,n=this.getRecentMessages(),s=this.getTokenBreakdown().total,o=!0){this.summary=e,this.summaryTokens=jr.count(e),this.summarizedTurnCount+=r,this.messages=n,this.serverReportedInputTokens=0;let i=this.getTokenBreakdown().total,a=s-i,c={summary:e,summaryTokens:this.summaryTokens,turnsSummarized:r,tokensSaved:a,newUsagePercent:this.getState().usagePercent};return this.warningShown=!1,o&&this.notifySummaryCommitted(c),c}notifySummaryCommitted(e){for(let r of this.listeners("summarizationComplete"))try{r(e)}catch{}}buildHybridContext(){return this.summary?{type:"hybrid",summary:this.summary,overlap:this.getOverlapMessages(),recent:this.getRecentMessages(),totalTokens:this.summaryTokens+this.getOverlapMessages().reduce((e,r)=>e+r.tokens,0)+this.getRecentMessages().reduce((e,r)=>e+r.tokens,0)}:{type:"full",recent:this.messages,totalTokens:this.getTokenBreakdown().conversation}}formatContextForServer(){let e=this.buildHybridContext(),r=[];e.type==="hybrid"&&e.summary&&(r.push("=== CONVERSATION SUMMARY ==="),r.push(e.summary),r.push(""),r.push("=== RECENT CONVERSATION ==="));for(let n of e.recent){let s=n.role==="user"?"User":n.role==="assistant"?"Assistant":n.role==="system"?"System":"Tool";r.push(`${s}: ${n.content}`)}return r.join(`
|
|
@@ -4292,7 +4292,7 @@ User: ${e}`}async function FUt(t,e,r){if(t.authType==="oauth_bearer"){let o=Ma(t
|
|
|
4292
4292
|
`))):(console.log(` Connection: ${g.red("Unreachable")} (${e})`),console.log(g.gray(` The cloud could not be reached. Try again shortly.
|
|
4293
4293
|
`))),process.exitCode=1}}function z$e(){console.log(g.bold(`
|
|
4294
4294
|
aii cloud \u2014 manage your account and workspaces
|
|
4295
|
-
`)),console.log(" aii cloud login Sign in to AiiCloud (verifies an existing sign-in;"),console.log(" --force re-authenticates)"),console.log(" aii cloud status Show connection + credit balance"),console.log(" aii cloud workspace list | add <path> | remove <label|path>"),console.log(g.gray("\n Start `aii --remote-control` to continue a conversation in AiiCloud\n and host new web conversations while Aii is running.\n Choose inference independently with `--inference cloud|server`.\n"))}var YK=T(()=>{"use strict";we();Mc();Si();I$e();lC();k$e();R$e();tK();G$e();Y$e();pC();Ti();Pa();UL()});var j$e={};de(j$e,{handleUpgrade:()=>o9t});import{execSync as r9t,execFileSync as n9t}from"node:child_process";async function o9t(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!s9t.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.
|
|
4295
|
+
`)),console.log(" aii cloud login Sign in to AiiCloud (verifies an existing sign-in;"),console.log(" --force re-authenticates)"),console.log(" aii cloud status Show connection + credit balance"),console.log(" aii cloud workspace list | add <path> | remove <label|path>"),console.log(g.gray("\n Start `aii --remote-control` to continue a conversation in AiiCloud\n and host new web conversations while Aii is running.\n Choose inference independently with `--inference cloud|server`.\n"))}var YK=T(()=>{"use strict";we();Mc();Si();I$e();lC();k$e();R$e();tK();G$e();Y$e();pC();Ti();Pa();UL()});var j$e={};de(j$e,{handleUpgrade:()=>o9t});import{execSync as r9t,execFileSync as n9t}from"node:child_process";async function o9t(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!s9t.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.6",s=r?`${V$e}@${r}`:`${V$e}@latest`;console.log(""),console.log(r?`Upgrading Aii CLI to v${r}...`:"Upgrading Aii CLI to latest..."),console.log(` Current version: ${n}`),console.log("");try{let o=process.platform==="win32"?"npm.cmd":"npm",i=n9t(o,["install","-g",s],{encoding:"utf-8",timeout:12e4,stdio:"pipe"});i.trim()&&console.log(i.trim())}catch(o){let i=o,a=o instanceof Error?`${String(i.stdout??"")}
|
|
4296
4296
|
${String(i.stderr??"")}`.trim():"";a.trim()&&console.error(a.trim()),/ETARGET|notarget/i.test(a)?console.error(`
|
|
4297
4297
|
That version is not on your npm mirror yet \u2014 freshly published versions can take a
|
|
4298
4298
|
minute or two to replicate. Wait a moment and re-run: aii upgrade`):/EACCES|EPERM|permission denied/i.test(a)?console.error(`
|
|
@@ -4321,7 +4321,7 @@ Upgrade failed.`),console.error(` Manual: npm install -g ${s}`),process.exit(1)
|
|
|
4321
4321
|
${t}
|
|
4322
4322
|
</context>
|
|
4323
4323
|
|
|
4324
|
-
${e}`:e}fm();var Bv=[{name:"config",tier:De.LOCAL},{name:"help",tier:De.LOCAL},{name:"version",tier:De.LOCAL},{name:"doctor",tier:De.LOCAL},{name:"mcp",tier:De.LOCAL},{name:"prompt",tier:De.LOCAL},{name:"stats",tier:De.LOCAL},{name:"history",tier:De.LOCAL},{name:"query",tier:De.SERVER},{name:"chat",tier:De.SERVER},{name:"run",tier:De.SERVER},{name:"agent",tier:De.SERVER},{name:"loop",tier:De.SERVER},{name:"telegram",tier:De.SERVER},{name:"sessions",tier:De.LOCAL},{name:"goals",tier:De.LOCAL},{name:"install",tier:De.LOCAL},{name:"worktree",tier:De.LOCAL},{name:"soul",tier:De.LOCAL},{name:"skill",tier:De.LOCAL},{name:"plugin",tier:De.LOCAL},{name:"persona",tier:De.LOCAL},{name:"cloud",tier:De.LOCAL},{name:"login",tier:De.LOCAL},{name:"upgrade",tier:De.LOCAL}];function QJe(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==De.LOCAL&&r.tier!==De.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var UJe=QJe(Bv);function Aae(t){return UJe.get(t)?.tier}var w4t=Object.fromEntries(Bv.map(t=>[t.name,t.tier]));function _ae(t,e){let r=t.slice(0,2),n,s,o,i;for(let a=2;a<t.length;a++){let c=t[a],[l]=c.split("=",1);if(c==="--"){r.push(...t.slice(a));break}if(l==="--remote"||l==="--local")throw new Error(`${l} was removed. Use ${l==="--remote"?"--remote-control":"--inference server"}.`);if(l==="--remote-control"){if(c!==l)throw new Error("--remote-control does not take a value.");o=!0;continue}if(l==="--inference"){let u=c.includes("=")?c.slice(c.indexOf("=")+1):t[++a];if(u!=="cloud"&&u!=="server")throw new Error("--inference must be cloud or server.");if(s&&s!==u)throw new Error("Choose one --inference backend.");s=u;continue}if(e.has(l)){r.push(c),!c.includes("=")&&a+1<t.length&&r.push(t[++a]);continue}if(!c.startsWith("-"))if(n){if(n==="cloud"){if(c==="connect")throw new Error("aii cloud connect was removed. Start aii --remote-control; inference is selected independently with --inference cloud|server.");n="cloud-action"}else if(n==="run"){if(c==="git"&&["commit","pr"].includes(t[a+1])){r.push(c,t[++a]),n="owned-operation";continue}r.push(...t.slice(a));break}else if(i)throw new Error("Resume the session first, then type your prompt.")}else{if(n=c,n==="mcp"){r.push(...t.slice(a));break}if(n==="resume"){let u=t[++a];if(!u||!/^[A-Za-z0-9_-][A-Za-z0-9_.-]{3,63}$/.test(u)||u.includes(".."))throw new Error("Usage: aii resume <exact-session-id> [--remote-control]");i=u;continue}}r.push(c)}return{argv:r,inference:s,remoteControl:o,resumeId:i}}var yae=new Set(Bv.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),$Je="0.25.5",GJe=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--trust-source","--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","--show-tools","--append-system-prompt","--append-system-prompt-file","--reconnect-window","--continue","--signature","--no-signature","--no-project-config","--project-config","--inference","--remote-control","-h","--help","-V","--version"]),VA=new Set(["--inference","--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","--reconnect-window"]);function HJe(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(n==="--"){e.push(...t.slice(r+1));break}let s=n.indexOf("="),o=s>0?n.slice(0,s):n;if(GJe.has(o)){s===-1&&VA.has(o)&&r++;continue}e.push(n)}return e}var Eae=/^[a-z0-9_]{2,40}$/i;function Cae(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return r}}function YJe(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&VA.has(t[e])&&e++}return-1}function qJe(t){for(let e=0;e<t.length;e++){let r=t[e];if(r==="--")return e+1<t.length;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return!0}return!1}function zJe(t){let e=Cae(t);if(e!==void 0&&e!=="agent"&&yae.has(e))return{argv:t};let r=t.slice(0,2),n,s;for(let o=2;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(VA.has(i.split("=",1)[0])){r.push(i),!i.includes("=")&&o+1<t.length&&r.push(t[++o]);continue}if(i==="--continue"){r.push(i);let a=t[o+1];n===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&Eae.test(a)&&(qJe(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.`:(n=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);r.push("--continue"),Eae.test(a)?n===void 0&&(n=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}r.push(i)}return{argv:r,continueId:n,error:s}}function WJe(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 VJe(t){if(t===void 0)return;let e=/^\d+$/.test(t.trim())?Number(t.trim()):NaN;if(!Number.isInteger(e)||e<0||e>3600){let r=t.replace(/[\x00-\x1F\x7F-\x9F]/g,"").slice(0,40);throw new Error(`Invalid --reconnect-window "${r}": expected an integer 0\u20133600 (seconds)`)}return e}function Sae(t){if(t===void 0)return;let e=t.trim();if(!/^\d+$/.test(e))return;let r=Number(e);return Number.isInteger(r)&&r>=0&&r<=3600?r:void 0}function jJe(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 KJe(){let t=new hae;return t.name("aii").description("AI-powered CLI assistant").version($Je,"-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","Currently identical to --standard \u2014 no extra reasoning is surfaced").option("-v, --verbose","--thinking plus an end-of-run token/cost/tool line (one-shot agent runs)").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>","Local server host:port for one-shot, -i chat, run git and prompt lanes; also opts out of AiiCloud").option("--inference <backend>","Inference backend: cloud or configured server").option("--remote-control","Continue this conversation in AiiCloud and host new web conversations").option("-y, --yes","Auto-confirm shell commands (does NOT authorise installing third-party code \u2014 use --trust-source)").option("--trust-source","Accept installing third-party code from the named source (skills, plugins and personas)").option("--offline","Skip MCP servers for this run (web tools stay available)").option("-D, --direct","Direct mode (bypass server intent recognition)").option("-i, --interactive","Force agent mode (default with no query; with a query it is still a one-shot run)").option("-c, --continue-chat <id>","DEPRECATED \u2014 no effect; the id is discarded. Use --continue <id>").option("-n, --new-chat","DEPRECATED \u2014 no effect. Use /new in-session").option("--auto","Auto-approve tool prompts (write fence, sensitive-path reads and project deny rules still apply)").option("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip this repo's config, slash commands, skills, agents and instruction files for this session: .aii/settings.json + settings.local.json (and their deny rules), project slash commands, project skills, project .aii/agents, and AGENTS.md / AII.md / CLAUDE.md. Does NOT cover .aii/hooks.json or .aii/soul.").option("--no-colors","Disable colored output (one-shot + command output; the interactive agent UI is unaffected)").option("--no-emojis","Disable emoji icons (one-shot + command output; the interactive agent UI is unaffected)").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--show-cost","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of BUILT-IN tools (comma-separated, e.g., "Read,Bash,Edit"); MCP and subagent tools are not filtered').option("--exclude-tools <list>",'Exclude BUILT-IN tools (comma-separated, e.g., "WebSearch,WebFetch"); --tools wins if both are given').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--reconnect-window <seconds>","One-shot runs: retry dropped connections for up to N seconds (default 0 = fail fast)").option("--max-budget-usd <amount>","Interactive sessions: stop before a NEW turn once cumulative est. cost reaches $amount (does not pre-empt a turn in progress)").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--show-tools","With --bare or --output-format: write the tool transcript to stderr (stdout untouched)").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("Browse saved conversations (list, info); use server for server-managed sessions").argument("[action]","Action: list, info, server").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 AiiCloud account and workspaces; use aii --remote-control for web control").argument("[action]","Action: login, status, workspace, help").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 bae(t){let e=_ae(t,VA),r=zJe(e.argv),n=r.argv,s=YJe(n),o=s>=0&&Cae(n)===void 0?n.slice(0,s):n,i=KJe();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&yae.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof j9&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof j9&&m.code==="commander.help"))throw m;l=HJe(n.slice(2))}let u=i.opts(),d={clean:u.clean??!1,standard:u.standard??!1,thinking:u.thinking??!1,verbose:u.verbose??!1,debug:u.debug??!1,model:u.model,host:u.host,inference:e.inference,remoteControl:e.remoteControl??!1,openrouterProvider:u.openrouterProvider,yes:u.yes??!1,trustSource:u.trustSource??!1,offline:u.offline??!1,direct:u.direct??!1,interactive:u.interactive??!1,continueChat:u.continueChat,newChat:u.newChat??!1,auto:u.auto??!1,quiet:!1,noProjectConfig:u.projectConfig===!1,autoBackgroundTimeout:(()=>{let m=parseInt(u.autoBackgroundTimeout??"120",10);return isNaN(m)||m===0?0:Math.max(30,Math.min(600,m))*1e3})(),noColors:!u.colors,noEmojis:!u.emojis,noAnimations:!u.animations,noStreaming:!u.streaming,showTools:u.showTools??!1,showTokens:u.showTokens??!1,showCost:u.showCost??!1,outputFormat:u.outputFormat,tools:u.tools,excludeTools:u.excludeTools,maxTurns:WJe(u.maxTurns),maxBudgetUsd:jJe(u.maxBudgetUsd),reconnectWindow:VJe(u.reconnectWindow),bare:u.bare??!1,appendSystemPrompt:u.appendSystemPrompt,appendSystemPromptFile:u.appendSystemPromptFile,continue:u.continue??!1,continueId:e.resumeId??r.continueId,continueIdError:r.error,help:u.help??!1,version:u.version??!1},p;K9()&&(p=await gae()),(a==="chat"||d.interactive)&&(a="agent"),a==="query"&&!l.length&&!p&&(a="agent");let f;if(a==="query"&&l.length>0)f=l.join(" ");else if(a==="agent"){let m=[];c&&m.push(c),l.length>0&&m.push(...l),m.length>0&&(f=m.join(" "))}return{command:a,subcommand:c,args:l,flags:d,stdinContent:p,query:f}}Pv();fm();function Tae(t){let e=Aae(t.command)??De.SERVER;switch(t.command){case"config":return JJe(t);case"mcp":return XJe(t);case"prompt":return ZJe(t);case"stats":return eXe(t);case"history":return tXe(t);case"doctor":return{tier:De.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:De.LOCAL,handler:"goals",params:{}};case"install":return{tier:De.LOCAL,handler:"install",params:{}};case"chat":return{tier:De.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return nXe(t);case"agent":return{tier:De.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:De.SERVER,handler:"loop",params:{}};case"telegram":return{tier:De.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:De.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:De.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:De.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:De.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:De.LOCAL,handler:"login",params:{}};case"skill":return{tier:De.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:De.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:De.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:De.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:De.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:De.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function JJe(t){let e=t.subcommand??t.args[0]??"show";return{tier:De.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function XJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function ZJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function eXe(t){let e=t.subcommand??t.args[0];return{tier:De.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function tXe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var rXe=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function nXe(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(rXe.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:De.SERVER,handler:"run",params:{operation:n}}}fm();ht();YD();Pa();ti();we();fm();ih();import{createInterface as qFt}from"readline";import{spawn as zFt}from"child_process";we();import ML from"node:process";import EFe from"node:process";import OL from"node:process";var EMt=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let s=Object.getOwnPropertyDescriptor(t,r),o=Object.getOwnPropertyDescriptor(e,r);!yMt(s,o)&&n||Object.defineProperty(t,r,o)},yMt=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)},CMt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},SMt=(t,e)=>`/* Wrapped ${t}*/
|
|
4324
|
+
${e}`:e}fm();var Bv=[{name:"config",tier:De.LOCAL},{name:"help",tier:De.LOCAL},{name:"version",tier:De.LOCAL},{name:"doctor",tier:De.LOCAL},{name:"mcp",tier:De.LOCAL},{name:"prompt",tier:De.LOCAL},{name:"stats",tier:De.LOCAL},{name:"history",tier:De.LOCAL},{name:"query",tier:De.SERVER},{name:"chat",tier:De.SERVER},{name:"run",tier:De.SERVER},{name:"agent",tier:De.SERVER},{name:"loop",tier:De.SERVER},{name:"telegram",tier:De.SERVER},{name:"sessions",tier:De.LOCAL},{name:"goals",tier:De.LOCAL},{name:"install",tier:De.LOCAL},{name:"worktree",tier:De.LOCAL},{name:"soul",tier:De.LOCAL},{name:"skill",tier:De.LOCAL},{name:"plugin",tier:De.LOCAL},{name:"persona",tier:De.LOCAL},{name:"cloud",tier:De.LOCAL},{name:"login",tier:De.LOCAL},{name:"upgrade",tier:De.LOCAL}];function QJe(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==De.LOCAL&&r.tier!==De.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var UJe=QJe(Bv);function Aae(t){return UJe.get(t)?.tier}var w4t=Object.fromEntries(Bv.map(t=>[t.name,t.tier]));function _ae(t,e){let r=t.slice(0,2),n,s,o,i;for(let a=2;a<t.length;a++){let c=t[a],[l]=c.split("=",1);if(c==="--"){r.push(...t.slice(a));break}if(l==="--remote"||l==="--local")throw new Error(`${l} was removed. Use ${l==="--remote"?"--remote-control":"--inference server"}.`);if(l==="--remote-control"){if(c!==l)throw new Error("--remote-control does not take a value.");o=!0;continue}if(l==="--inference"){let u=c.includes("=")?c.slice(c.indexOf("=")+1):t[++a];if(u!=="cloud"&&u!=="server")throw new Error("--inference must be cloud or server.");if(s&&s!==u)throw new Error("Choose one --inference backend.");s=u;continue}if(e.has(l)){r.push(c),!c.includes("=")&&a+1<t.length&&r.push(t[++a]);continue}if(!c.startsWith("-"))if(n){if(n==="cloud"){if(c==="connect")throw new Error("aii cloud connect was removed. Start aii --remote-control; inference is selected independently with --inference cloud|server.");n="cloud-action"}else if(n==="run"){if(c==="git"&&["commit","pr"].includes(t[a+1])){r.push(c,t[++a]),n="owned-operation";continue}r.push(...t.slice(a));break}else if(i)throw new Error("Resume the session first, then type your prompt.")}else{if(n=c,n==="mcp"){r.push(...t.slice(a));break}if(n==="resume"){let u=t[++a];if(!u||!/^[A-Za-z0-9_-][A-Za-z0-9_.-]{3,63}$/.test(u)||u.includes(".."))throw new Error("Usage: aii resume <exact-session-id> [--remote-control]");i=u;continue}}r.push(c)}return{argv:r,inference:s,remoteControl:o,resumeId:i}}var yae=new Set(Bv.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),$Je="0.25.6",GJe=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--trust-source","--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","--show-tools","--append-system-prompt","--append-system-prompt-file","--reconnect-window","--continue","--signature","--no-signature","--no-project-config","--project-config","--inference","--remote-control","-h","--help","-V","--version"]),VA=new Set(["--inference","--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","--reconnect-window"]);function HJe(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(n==="--"){e.push(...t.slice(r+1));break}let s=n.indexOf("="),o=s>0?n.slice(0,s):n;if(GJe.has(o)){s===-1&&VA.has(o)&&r++;continue}e.push(n)}return e}var Eae=/^[a-z0-9_]{2,40}$/i;function Cae(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return r}}function YJe(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&VA.has(t[e])&&e++}return-1}function qJe(t){for(let e=0;e<t.length;e++){let r=t[e];if(r==="--")return e+1<t.length;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return!0}return!1}function zJe(t){let e=Cae(t);if(e!==void 0&&e!=="agent"&&yae.has(e))return{argv:t};let r=t.slice(0,2),n,s;for(let o=2;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(VA.has(i.split("=",1)[0])){r.push(i),!i.includes("=")&&o+1<t.length&&r.push(t[++o]);continue}if(i==="--continue"){r.push(i);let a=t[o+1];n===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&Eae.test(a)&&(qJe(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.`:(n=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);r.push("--continue"),Eae.test(a)?n===void 0&&(n=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}r.push(i)}return{argv:r,continueId:n,error:s}}function WJe(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 VJe(t){if(t===void 0)return;let e=/^\d+$/.test(t.trim())?Number(t.trim()):NaN;if(!Number.isInteger(e)||e<0||e>3600){let r=t.replace(/[\x00-\x1F\x7F-\x9F]/g,"").slice(0,40);throw new Error(`Invalid --reconnect-window "${r}": expected an integer 0\u20133600 (seconds)`)}return e}function Sae(t){if(t===void 0)return;let e=t.trim();if(!/^\d+$/.test(e))return;let r=Number(e);return Number.isInteger(r)&&r>=0&&r<=3600?r:void 0}function jJe(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 KJe(){let t=new hae;return t.name("aii").description("AI-powered CLI assistant").version($Je,"-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","Currently identical to --standard \u2014 no extra reasoning is surfaced").option("-v, --verbose","--thinking plus an end-of-run token/cost/tool line (one-shot agent runs)").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>","Local server host:port for one-shot, -i chat, run git and prompt lanes; also opts out of AiiCloud").option("--inference <backend>","Inference backend: cloud or configured server").option("--remote-control","Continue this conversation in AiiCloud and host new web conversations").option("-y, --yes","Auto-confirm shell commands (does NOT authorise installing third-party code \u2014 use --trust-source)").option("--trust-source","Accept installing third-party code from the named source (skills, plugins and personas)").option("--offline","Skip MCP servers for this run (web tools stay available)").option("-D, --direct","Direct mode (bypass server intent recognition)").option("-i, --interactive","Force agent mode (default with no query; with a query it is still a one-shot run)").option("-c, --continue-chat <id>","DEPRECATED \u2014 no effect; the id is discarded. Use --continue <id>").option("-n, --new-chat","DEPRECATED \u2014 no effect. Use /new in-session").option("--auto","Auto-approve tool prompts (write fence, sensitive-path reads and project deny rules still apply)").option("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip this repo's config, slash commands, skills, agents and instruction files for this session: .aii/settings.json + settings.local.json (and their deny rules), project slash commands, project skills, project .aii/agents, and AGENTS.md / AII.md / CLAUDE.md. Does NOT cover .aii/hooks.json or .aii/soul.").option("--no-colors","Disable colored output (one-shot + command output; the interactive agent UI is unaffected)").option("--no-emojis","Disable emoji icons (one-shot + command output; the interactive agent UI is unaffected)").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--show-cost","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of BUILT-IN tools (comma-separated, e.g., "Read,Bash,Edit"); MCP and subagent tools are not filtered').option("--exclude-tools <list>",'Exclude BUILT-IN tools (comma-separated, e.g., "WebSearch,WebFetch"); --tools wins if both are given').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--reconnect-window <seconds>","One-shot runs: retry dropped connections for up to N seconds (default 0 = fail fast)").option("--max-budget-usd <amount>","Interactive sessions: stop before a NEW turn once cumulative est. cost reaches $amount (does not pre-empt a turn in progress)").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--show-tools","With --bare or --output-format: write the tool transcript to stderr (stdout untouched)").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("Browse saved conversations (list, info); use server for server-managed sessions").argument("[action]","Action: list, info, server").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 AiiCloud account and workspaces; use aii --remote-control for web control").argument("[action]","Action: login, status, workspace, help").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 bae(t){let e=_ae(t,VA),r=zJe(e.argv),n=r.argv,s=YJe(n),o=s>=0&&Cae(n)===void 0?n.slice(0,s):n,i=KJe();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&yae.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof j9&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof j9&&m.code==="commander.help"))throw m;l=HJe(n.slice(2))}let u=i.opts(),d={clean:u.clean??!1,standard:u.standard??!1,thinking:u.thinking??!1,verbose:u.verbose??!1,debug:u.debug??!1,model:u.model,host:u.host,inference:e.inference,remoteControl:e.remoteControl??!1,openrouterProvider:u.openrouterProvider,yes:u.yes??!1,trustSource:u.trustSource??!1,offline:u.offline??!1,direct:u.direct??!1,interactive:u.interactive??!1,continueChat:u.continueChat,newChat:u.newChat??!1,auto:u.auto??!1,quiet:!1,noProjectConfig:u.projectConfig===!1,autoBackgroundTimeout:(()=>{let m=parseInt(u.autoBackgroundTimeout??"120",10);return isNaN(m)||m===0?0:Math.max(30,Math.min(600,m))*1e3})(),noColors:!u.colors,noEmojis:!u.emojis,noAnimations:!u.animations,noStreaming:!u.streaming,showTools:u.showTools??!1,showTokens:u.showTokens??!1,showCost:u.showCost??!1,outputFormat:u.outputFormat,tools:u.tools,excludeTools:u.excludeTools,maxTurns:WJe(u.maxTurns),maxBudgetUsd:jJe(u.maxBudgetUsd),reconnectWindow:VJe(u.reconnectWindow),bare:u.bare??!1,appendSystemPrompt:u.appendSystemPrompt,appendSystemPromptFile:u.appendSystemPromptFile,continue:u.continue??!1,continueId:e.resumeId??r.continueId,continueIdError:r.error,help:u.help??!1,version:u.version??!1},p;K9()&&(p=await gae()),(a==="chat"||d.interactive)&&(a="agent"),a==="query"&&!l.length&&!p&&(a="agent");let f;if(a==="query"&&l.length>0)f=l.join(" ");else if(a==="agent"){let m=[];c&&m.push(c),l.length>0&&m.push(...l),m.length>0&&(f=m.join(" "))}return{command:a,subcommand:c,args:l,flags:d,stdinContent:p,query:f}}Pv();fm();function Tae(t){let e=Aae(t.command)??De.SERVER;switch(t.command){case"config":return JJe(t);case"mcp":return XJe(t);case"prompt":return ZJe(t);case"stats":return eXe(t);case"history":return tXe(t);case"doctor":return{tier:De.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:De.LOCAL,handler:"goals",params:{}};case"install":return{tier:De.LOCAL,handler:"install",params:{}};case"chat":return{tier:De.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return nXe(t);case"agent":return{tier:De.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:De.SERVER,handler:"loop",params:{}};case"telegram":return{tier:De.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:De.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:De.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:De.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:De.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:De.LOCAL,handler:"login",params:{}};case"skill":return{tier:De.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:De.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:De.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:De.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:De.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:De.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function JJe(t){let e=t.subcommand??t.args[0]??"show";return{tier:De.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function XJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function ZJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function eXe(t){let e=t.subcommand??t.args[0];return{tier:De.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function tXe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var rXe=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function nXe(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(rXe.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:De.SERVER,handler:"run",params:{operation:n}}}fm();ht();YD();Pa();ti();we();fm();ih();import{createInterface as qFt}from"readline";import{spawn as zFt}from"child_process";we();import ML from"node:process";import EFe from"node:process";import OL from"node:process";var EMt=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let s=Object.getOwnPropertyDescriptor(t,r),o=Object.getOwnPropertyDescriptor(e,r);!yMt(s,o)&&n||Object.defineProperty(t,r,o)},yMt=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)},CMt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},SMt=(t,e)=>`/* Wrapped ${t}*/
|
|
4325
4325
|
${e}`,bMt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),IMt=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),TMt=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=SMt.bind(null,n,e.toString());Object.defineProperty(s,"name",IMt);let{writable:o,enumerable:i,configurable:a}=bMt;Object.defineProperty(t,"toString",{value:s,writable:o,enumerable:i,configurable:a})};function aj(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let s of Reflect.ownKeys(e))EMt(t,e,s,r);return CMt(t,e),TMt(t,e,n),t}var DL=new WeakMap,mFe=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,n=0,s=t.displayName||t.name||"<anonymous>",o=function(...i){if(DL.set(o,++n),n===1)r=t.apply(this,i),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return aj(o,t),DL.set(o,n),o};mFe.callCount=t=>{if(!DL.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return DL.get(t)};var hFe=mFe;var _g=[];_g.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&_g.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&_g.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var RL=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",cj=Symbol.for("signal-exit emitter"),lj=globalThis,wMt=Object.defineProperty.bind(Object),uj=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(lj[cj])return lj[cj];wMt(lj,cj,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],s=n.indexOf(r);s!==-1&&(s===0&&n.length===1?n.length=0:n.splice(s,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let s=!1;for(let o of this.listeners[e])s=o(r,n)===!0||s;return e==="exit"&&(s=this.emit("afterExit",r,n)||s),s}},NL=class{},kMt=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),dj=class extends NL{onExit(){return()=>{}}load(){}unload(){}},pj=class extends NL{#e=fj.platform==="win32"?"SIGINT":"SIGHUP";#t=new uj;#r;#s;#o;#n={};#i=!1;constructor(e){super(),this.#r=e,this.#n={};for(let r of _g)this.#n[r]=()=>{let n=this.#r.listeners(r),{count:s}=this.#t,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(s+=o.__signal_exit_emitter__.count),n.length===s){this.unload();let i=this.#t.emit("exit",null,r),a=r==="SIGHUP"?this.#e:r;i||e.kill(e.pid,a)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(e,r){if(!RL(this.#r))return()=>{};this.#i===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(let e of _g)try{let r=this.#n[e];r&&this.#r.on(e,r)}catch{}this.#r.emit=(e,...r)=>this.#l(e,...r),this.#r.reallyExit=e=>this.#a(e)}}unload(){this.#i&&(this.#i=!1,_g.forEach(e=>{let r=this.#n[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,r)}catch{}}),this.#r.emit=this.#s,this.#r.reallyExit=this.#o,this.#t.count-=1)}#a(e){return RL(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#l(e,...r){let n=this.#s;if(e==="exit"&&RL(this.#r)){typeof r[0]=="number"&&(this.#r.exitCode=r[0]);let s=n.call(this.#r,e,...r);return this.#t.emit("exit",this.#r.exitCode,null),s}else return n.call(this.#r,e,...r)}},fj=globalThis.process,{onExit:gFe,load:Igr,unload:Tgr}=kMt(RL(fj)?new pj(fj):new dj);var AFe=OL.stderr.isTTY?OL.stderr:OL.stdout.isTTY?OL.stdout:void 0,vMt=AFe?hFe(()=>{gFe(()=>{AFe.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},_Fe=vMt;var xL=!1,Gy={};Gy.show=(t=EFe.stderr)=>{t.isTTY&&(xL=!1,t.write("\x1B[?25h"))};Gy.hide=(t=EFe.stderr)=>{t.isTTY&&(_Fe(),xL=!0,t.write("\x1B[?25l"))};Gy.toggle=(t,e)=>{t!==void 0&&(xL=t),xL?Gy.show(e):Gy.hide(e)};var mj=Gy;var mw=Xt(hj(),1);we();import mc from"node:process";function gj(){return mc.platform!=="win32"?mc.env.TERM!=="linux":!!mc.env.CI||!!mc.env.WT_SESSION||!!mc.env.TERMINUS_SUBLIME||mc.env.ConEmuTask==="{cmd::Cmder}"||mc.env.TERM_PROGRAM==="Terminus-Sublime"||mc.env.TERM_PROGRAM==="vscode"||mc.env.TERM==="xterm-256color"||mc.env.TERM==="alacritty"||mc.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var RMt={info:g.blue("\u2139"),success:g.green("\u2714"),warning:g.yellow("\u26A0"),error:g.red("\u2716")},NMt={info:g.blue("i"),success:g.green("\u221A"),warning:g.yellow("\u203C"),error:g.red("\xD7")},OMt=gj()?RMt:NMt,fw=OMt;PR();var xMt=qm();function Aj(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(xMt,"")}r8();function _j({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import bFe from"node:process";function Ej(){let{env:t}=bFe,{TERM:e,TERM_PROGRAM:r}=t;return bFe.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}import kl from"node:process";var BMt=3,yj=class{#e=0;start(){this.#e++,this.#e===1&&this.#t()}stop(){if(this.#e<=0)throw new Error("`stop` called more times than `start`");this.#e--,this.#e===0&&this.#r()}#t(){kl.platform==="win32"||!kl.stdin.isTTY||(kl.stdin.setRawMode(!0),kl.stdin.on("data",this.#s),kl.stdin.resume())}#r(){kl.stdin.isTTY&&(kl.stdin.off("data",this.#s),kl.stdin.pause(),kl.stdin.setRawMode(!1))}#s(e){e[0]===BMt&&kl.emit("SIGINT")}},MMt=new yj,Cj=MMt;var LMt=Xt(hj(),1),Sj=class{#e=0;#t=!1;#r=0;#s=-1;#o=0;#n;#i;#a;#l;#c;#u;#f;#m;#g;#d;#p;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#n={color:"cyan",stream:ML.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#n.color,this.spinner=this.#n.spinner,this.#c=this.#n.interval,this.#a=this.#n.stream,this.#u=typeof this.#n.isEnabled=="boolean"?this.#n.isEnabled:_j({stream:this.#a}),this.#f=typeof this.#n.isSilent=="boolean"?this.#n.isSilent:!1,this.text=this.#n.text,this.prefixText=this.#n.prefixText,this.suffixText=this.#n.suffixText,this.indent=this.#n.indent,ML.env.NODE_ENV==="test"&&(this._stream=this.#a,this._isEnabled=this.#u,Object.defineProperty(this,"_linesToClear",{get(){return this.#e},set(r){this.#e=r}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#s}}),Object.defineProperty(this,"_lineCount",{get(){return this.#r}}))}get indent(){return this.#m}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.#m=e,this.#h()}get interval(){return this.#c??this.#i.interval??100}get spinner(){return this.#i}set spinner(e){if(this.#s=-1,this.#c=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#i=e}else if(!Ej())this.#i=mw.default.line;else if(e===void 0)this.#i=mw.default.dots;else if(e!=="default"&&mw.default[e])this.#i=mw.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.#h()}get prefixText(){return this.#d}set prefixText(e=""){this.#d=e,this.#h()}get suffixText(){return this.#p}set suffixText(e=""){this.#p=e,this.#h()}get isSpinning(){return this.#l!==void 0}#A(e=this.#d,r=" "){return typeof e=="string"&&e!==""?e+r:typeof e=="function"?e()+r:""}#_(e=this.#p,r=" "){return typeof e=="string"&&e!==""?r+e:typeof e=="function"?r+e():""}#h(){let e=this.#a.columns??80,r=this.#A(this.#d,"-"),n=this.#_(this.#p,"-"),s=" ".repeat(this.#m)+r+"--"+this.#g+"--"+n;this.#r=0;for(let o of Aj(s).split(`
|
|
4326
4326
|
`))this.#r+=Math.max(1,Math.ceil(N_(o,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#u&&!this.#f}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#u=e}get isSilent(){return this.#f}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#f=e}frame(){let e=Date.now();(this.#s===-1||e-this.#o>=this.interval)&&(this.#s=++this.#s%this.#i.frames.length,this.#o=e);let{frames:r}=this.#i,n=r[this.#s];this.color&&(n=g[this.color](n));let s=typeof this.#d=="string"&&this.#d!==""?this.#d+" ":"",o=typeof this.text=="string"?" "+this.text:"",i=typeof this.#p=="string"&&this.#p!==""?" "+this.#p:"";return s+n+o+i}clear(){if(!this.#u||!this.#a.isTTY)return this;this.#a.cursorTo(0);for(let e=0;e<this.#e;e++)e>0&&this.#a.moveCursor(0,-1),this.#a.clearLine(1);return(this.#m||this.lastIndent!==this.#m)&&this.#a.cursorTo(this.#m),this.lastIndent=this.#m,this.#e=0,this}render(){return this.#f?this:(this.clear(),this.#a.write(this.frame()),this.#e=this.#r,this)}start(e){return e&&(this.text=e),this.#f?this:this.#u?this.isSpinning?this:(this.#n.hideCursor&&mj.hide(this.#a),this.#n.discardStdin&&ML.stdin.isTTY&&(this.#t=!0,Cj.start()),this.render(),this.#l=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#a.write(`- ${this.text}
|
|
4327
4327
|
`),this)}stop(){return this.#u?(clearInterval(this.#l),this.#l=void 0,this.#s=0,this.clear(),this.#n.hideCursor&&mj.show(this.#a),this.#n.discardStdin&&ML.stdin.isTTY&&this.#t&&(Cj.stop(),this.#t=!1),this):this}succeed(e){return this.stopAndPersist({symbol:fw.success,text:e})}fail(e){return this.stopAndPersist({symbol:fw.error,text:e})}warn(e){return this.stopAndPersist({symbol:fw.warning,text:e})}info(e){return this.stopAndPersist({symbol:fw.info,text:e})}stopAndPersist(e={}){if(this.#f)return this;let r=e.prefixText??this.#d,n=this.#A(r," "),s=e.symbol??" ",o=e.text??this.text,a=typeof o=="string"?(s?" ":"")+o:"",c=e.suffixText??this.#p,l=this.#_(c," "),u=n+s+a+l+`
|
|
@@ -4331,7 +4331,7 @@ ${e}`,bMt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),IMt=Obj
|
|
|
4331
4331
|
`+this.color(s,g.dim)}formatError(e){let r=[];return r.push(this.color(`${this.emoji("\u274C ")}${e.message}`,g.red)),e.suggestions&&e.suggestions.length>0&&(r.push(""),r.push(this.color(`${this.emoji("\u{1F4A1} ")}Solutions:`,g.yellow)),e.suggestions.forEach((n,s)=>{r.push(this.color(` ${s+1}. ${n}`,g.gray))})),r.join(`
|
|
4332
4332
|
`)}formatConfig(e){let r=[];r.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,F.model)),r.push(`- Config file: ${e.configFile}`),r.push(`- Storage path: ${e.storagePath}`),e.apiUrl&&r.push(`- Aii Server: ${e.apiUrl}`);let n=e.hasApiKey?this.color("\u2713",g.green):this.color("\u2717",g.red),s=e.model.startsWith(e.provider+"/")?e.model.slice(e.provider.length+1):e.model;if(r.push(`- LLM provider: ${e.provider} (${s}) - ${n}`),e.webSearch){let o=e.webSearch.enabled?this.color("\u2713",g.green):this.color("\u2717",g.red);r.push(`- Web search: ${e.webSearch.provider??"none"} - ${o}`)}return e.issues&&e.issues.length>0&&r.push(`- Configuration issues: ${e.issues.length}`),r.join(`
|
|
4333
4333
|
`)}formatHealthCheck(e,r){let n=[],s=r?`Aii Doctor v${r}`:"Aii Doctor";n.push(this.color(s,F.model)),n.push("");let o=22;for(let c of e){let l=o-c.name.length-1,u=".".repeat(Math.max(2,l)),d,p;switch(c.status){case"ok":d="OK",p=g.green;break;case"warn":d="WARN",p=g.yellow;break;case"error":d="FAIL",p=g.red;break}let f=this.color(d,p),m=c.message?` (${c.message})`:"";n.push(` ${c.name} ${this.color(u,g.gray)} ${f}${m}`)}let i=e.filter(c=>c.status==="error").length,a=e.filter(c=>c.status==="warn").length;return n.push(""),i>0?n.push(` ${this.color(`${i} check${i>1?"s":""} failed.`,g.red)}`):a>0?n.push(` ${this.color("All checks passed with warnings.",g.yellow)}`):n.push(` ${this.color("All checks passed.",g.green)}`),n.join(`
|
|
4334
|
-
`)}};function Lo(t={}){return new kj(t)}js();fi();we();ih();import*as DFe from"readline";js();es();fi();Qc();import*as ga from"fs";import*as PL from"path";import*as IFe from"os";var gw=PL.join(IFe.homedir(),".aii","conversations"),vj=PL.join(gw,"current.json");function FL(){ga.existsSync(gw)||ga.mkdirSync(gw,{recursive:!0,mode:448});try{ga.chmodSync(gw,448)}catch{}}function QMt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function UMt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function TFe(t){return PL.join(gw,`${t}.json`)}function wFe(){FL();try{if(ga.existsSync(vj)){let t=ga.readFileSync(vj,"utf-8"),e=JSON.parse(t),r=TFe(e.id);if(ga.existsSync(r)){let n=ga.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return kFe()}function kFe(){FL();let t={id:QMt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Aw(t),$Mt(t.id),t}function Aw(t){if(FL(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=UMt(r.content))}t.updatedAt=Date.now();let e=TFe(t.id);wi(e,JSON.stringify(t,null,2))}function $Mt(t){FL(),wi(vj,JSON.stringify({id:t}))}function vFe(){return kFe()}Jh();var GMt="0.25.
|
|
4334
|
+
`)}};function Lo(t={}){return new kj(t)}js();fi();we();ih();import*as DFe from"readline";js();es();fi();Qc();import*as ga from"fs";import*as PL from"path";import*as IFe from"os";var gw=PL.join(IFe.homedir(),".aii","conversations"),vj=PL.join(gw,"current.json");function FL(){ga.existsSync(gw)||ga.mkdirSync(gw,{recursive:!0,mode:448});try{ga.chmodSync(gw,448)}catch{}}function QMt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function UMt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function TFe(t){return PL.join(gw,`${t}.json`)}function wFe(){FL();try{if(ga.existsSync(vj)){let t=ga.readFileSync(vj,"utf-8"),e=JSON.parse(t),r=TFe(e.id);if(ga.existsSync(r)){let n=ga.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return kFe()}function kFe(){FL();let t={id:QMt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Aw(t),$Mt(t.id),t}function Aw(t){if(FL(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=UMt(r.content))}t.updatedAt=Date.now();let e=TFe(t.id);wi(e,JSON.stringify(t,null,2))}function $Mt(t){FL(),wi(vj,JSON.stringify({id:t}))}function vFe(){return kFe()}Jh();var GMt="0.25.6",Dj=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=wFe(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=Lo({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()}),Aw(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(`
|
|
4335
4335
|
\u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(g.red(`
|
|
4336
4336
|
\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(),Aw(this.conversation))}}displayWelcome(){console.log("\u{1FABC} Entering interactive mode."),console.log(""),console.log("Controls:"),console.log(" \u2022 Enter - Send message"),console.log(" \u2022 End with \\ - Multi-line mode"),console.log(" \u2022 /exit - Quit chat"),console.log(" \u2022 /help - Show all commands"),console.log("")}getUserInput(){return new Promise((e,r)=>{let n=DFe.createInterface({input:process.stdin,output:process.stdout}),s=[],o=!1,i=()=>{o=!0,n.close()},a=c=>{n.question(c,l=>{if(s.length===0&&l.trim().startsWith("/")){i(),e(l.trim());return}l.endsWith("\\")?(s.push(l.slice(0,-1)),a(" ")):(s.push(l),i(),e(s.join(`
|
|
4337
4337
|
`).trim()))})};n.on("SIGINT",()=>{i(),r(new Error("INTERRUPTED"))}),n.on("close",()=>{o||r(new Error("EXIT"))}),a("> ")})}async handleSpecialCommands(e){let r=e.trim().toLowerCase();if(r.startsWith("/"))r=r.slice(1);else return!1;switch(r){case"exit":case"quit":return await this.handleExit(),!0;case"help":return this.displayHelp(),!0;case"clear":case"new":return this.clearConversation(),!0;case"history":return this.displayConversationHistory(),!0;case"stats":return this.displayStats(),!0;case"version":return this.displayVersion(),!0;default:return console.log(g.yellow(`Unknown command: /${r}. Type /help for available commands.`)),console.log(""),!0}}async processWithContext(e){let r=await this.configManager.load(),n=this.configManager.validate();if(!n.valid)throw new Vn(n.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",i=vn(this.parsed.flags.model??""),a=us(i||void 0,r.llm.provider),c=Xr(i||r.llm.model,a);this.effectiveProvider=a;let l=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,u=await Rt(a,this.configManager,{serverBaseUrl:l,serverApiKey:o}),d=u?.key;if(!d)throw new Rr(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let p=vl(!this.parsed.flags.noAnimations);p.start("");let f=Dl({spinner:p,enabled:!this.parsed.flags.noStreaming}),m=this.conversation.messages.slice(-21,-1).map(S=>({role:S.role,content:S.content})),h={api_key:o,system_prompt:null,user_prompt:e,user_message:e,output_mode:"CLEAN",streaming:!this.parsed.flags.noStreaming,model:c,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:m.length>0?m:void 0,soul:Fs.getInstance().getSoulName()},A=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,_=new Io({url:A}),E="",y=!1;try{let S=await _.executeRequest(h,{onToken:w=>{E+=w,y=!0,f.onToken(w)}});f.flush();let C=S.result||E;!y&&C&&console.log(C),console.log(""),S.metadata&&this.displayExecutionSummary(S.metadata),C&&(this.conversation.messages.push({role:"assistant",content:C,timestamp:Date.now()}),Aw(this.conversation))}catch(S){throw p.stop(!0),S}finally{_.disconnect()}}displayExecutionSummary(e){let r=e.cost||0,n=e.tokens_in||0,s=e.tokens_out||0,o=n+s;this.stats.cumulativeTokens+=o,this.stats.cumulativeCost+=r;let i=e.provider,a=!i;console.log(this.formatter.formatExecutionSummary({provider:i||this.effectiveProvider,providerInferred:a,model:e.model,tokens_in:n,tokens_out:s,cost:r,execution_time:e.execution_time})),console.log("")}clearConversation(){this.conversation=vFe(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
|
|
@@ -4507,10 +4507,10 @@ ${r.yellow("CONFIG FILE:")}
|
|
|
4507
4507
|
.aii/settings.json Project config (committed, restrict-only)
|
|
4508
4508
|
.aii/settings.local.json Your local overrides (gitignored)
|
|
4509
4509
|
${r.gray("Skip both for a session with: aii --no-project-config")}
|
|
4510
|
-
`)}import*as Ml from"fs";Qr();Rv();async function O9e(t,e){let r=Lo({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await yQt(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(Ml.existsSync(c))try{let f=Ml.readFileSync(c,"utf-8"),m=JSON.parse(f),h=Object.keys(m.mcpServers??{}).length;h>0?n.push({name:"MCP Servers",status:"ok",message:`${h} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(vv())try{let{execSync:f}=await import("child_process"),h=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:h?`v${h[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});vv()?Dv()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let l=process.version;parseInt(l.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:l}):n.push({name:"Node.js",status:"error",message:`${l} (requires >= 18)`});let d=await CQt();n.push(...d),console.log(r.formatHealthCheck(n,Gm)),n.some(f=>f.status==="error")&&process.exit(1)}async function yQt(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function CQt(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(oi(),hN)),r=`${e()}/skills`;if(!Ml.existsSync(r))return t;let n=Ml.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;Ml.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(()=>(sr(),lr));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",c=`${r}/${a}`;Ml.existsSync(c)&&Ml.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}we();Qr();import{execSync as uK}from"node:child_process";var rF="@aiiware/aii";async function x9e(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.25.
|
|
4511
|
-
`),await SQt(r)}async function SQt(t){let e="0.25.
|
|
4510
|
+
`)}import*as Ml from"fs";Qr();Rv();async function O9e(t,e){let r=Lo({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await yQt(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(Ml.existsSync(c))try{let f=Ml.readFileSync(c,"utf-8"),m=JSON.parse(f),h=Object.keys(m.mcpServers??{}).length;h>0?n.push({name:"MCP Servers",status:"ok",message:`${h} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(vv())try{let{execSync:f}=await import("child_process"),h=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:h?`v${h[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});vv()?Dv()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let l=process.version;parseInt(l.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:l}):n.push({name:"Node.js",status:"error",message:`${l} (requires >= 18)`});let d=await CQt();n.push(...d),console.log(r.formatHealthCheck(n,Gm)),n.some(f=>f.status==="error")&&process.exit(1)}async function yQt(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function CQt(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(oi(),hN)),r=`${e()}/skills`;if(!Ml.existsSync(r))return t;let n=Ml.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;Ml.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(()=>(sr(),lr));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",c=`${r}/${a}`;Ml.existsSync(c)&&Ml.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}we();Qr();import{execSync as uK}from"node:child_process";var rF="@aiiware/aii";async function x9e(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.25.6";console.log(""),console.log(F.logo(" Install")),console.log(""),console.log(` Current version: ${F.model(n)}`),console.log(""),console.log(g.yellow(" USAGE:")),console.log(` ${g.green("aii install")} Update to latest version`),console.log(` ${g.green("aii install <version>")} Install specific version`),console.log(` ${g.green("aii install skill <src>")} Install a skill package ${g.dim("(coming soon)")}`),console.log(` ${g.green("aii install mcp <name>")} Install an MCP server ${g.dim("(coming soon)")}`),console.log(""),console.log(g.yellow(" EXAMPLES:")),console.log(` ${g.green("aii install")} ${g.dim("# Self-update to latest")}`),console.log(` ${g.green("aii install 0.13.10")} ${g.dim("# Pin to specific version")}`),console.log("");return}if(r==="skill"){console.log("Skill installation coming soon. For now use: /skills install owner/repo");return}if(r==="mcp"){console.log("MCP installation coming soon. For now use: aii mcp install <server>");return}console.log("\x1B[33m\u26A0 `aii install` for self-update is deprecated. Use `aii upgrade` instead.\x1B[0m"),console.log(`\x1B[33m This alias will be removed in v0.16.x.\x1B[0m
|
|
4511
|
+
`),await SQt(r)}async function SQt(t){let e="0.25.6",r=t&&t!=="latest"?t:"";if(console.log(""),r){console.log(`\u{1FABC} Installing Aii CLI v${r}...`),console.log("");try{uK(`npm install -g ${rF}@${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4512
4512
|
\u274C Failed to install v${r}`),console.error(` Try manually: npm install -g ${rF}@${r}`),process.exit(1)}}else{console.log("\u{1FABC} Updating Aii CLI to latest..."),console.log(` Current version: ${e}`),console.log("");try{uK(`npm install -g ${rF}@latest`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4513
|
-
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${rF}@latest`),process.exit(1)}}try{let n=uK("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}we();var B9e="0.25.
|
|
4513
|
+
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${rF}@latest`),process.exit(1)}}try{let n=uK("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}we();var B9e="0.25.6";function dK(t){let r=!t.flags.noColors?g:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
|
|
4514
4514
|
${r.cyan("AII")} - AI-powered CLI assistant v${B9e}
|
|
4515
4515
|
|
|
4516
4516
|
${r.yellow("USAGE:")}
|