@aiiware/aii 0.25.14 → 0.25.15
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 +9 -9
- package/bin/aii-host-worker.mjs +2 -2
- package/package.json +1 -1
package/bin/aii
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* @aiiware/aii v0.25.
|
|
3
|
+
* @aiiware/aii v0.25.15
|
|
4
4
|
*
|
|
5
5
|
* AI-powered CLI assistant for terminal productivity
|
|
6
6
|
*
|
|
@@ -82,7 +82,7 @@ ${i}`;return}if(xv(e,s,_Je)){EJe(e,o)&&(r.retry=e.toString("utf8",o));return}if(
|
|
|
82
82
|
`)}var iZe,rb,x,rt=w(()=>{"use strict";Te();iZe={debug:!1,colors:!0,emojis:!0},rb={...iZe};x={debug:K,info:Zae,warn:ece,error:tce,success:rce,formatError:Zv,configure:Xv}});var D$={};ce(D$,{completionWithin:()=>qc});async function qc(t,e){let r;try{return await Promise.race([t.then(()=>"settled",()=>"failed"),new Promise(n=>{r=setTimeout(()=>n("timeout"),e)})])}finally{r&&clearTimeout(r)}}var vm=w(()=>{"use strict"});async function sce(t,e,r=3e3){let n=!1;if(await Promise.race([t.close().then(()=>{n=!0}),new Promise(s=>setTimeout(s,r).unref())]),!n&&e!==null)try{process.kill(e,"SIGKILL")}catch{}}async function eD(t,e,r=3e3){let{completionWithin:n}=await Promise.resolve().then(()=>(vm(),D$)),s=await n(t.close(),r);if(s!=="settled"&&e!==null)try{process.kill(e,"SIGKILL")}catch{}return s}var sb=w(()=>{"use strict"});var R$,js,p_=w(()=>{"use strict";sb();R$=500,js=3e3+R$+500});function cZe(t,e){Dm.set(t,e),K(`Cleanup registered: ${t}`)}function lZe(t,e){tD.set(t,e),K(`Cleanup registered (final): ${t}`)}function uZe(t,e){let r=[...Dm].filter(([n])=>n!==t);Dm=new Map([[t,e],...r]),K(`Cleanup registered (first): ${t}`)}function dZe(t){Dm.delete(t),tD.delete(t),K(`Cleanup unregistered: ${t}`)}async function ice(){return O$?(K("Cleanup already in progress \u2014 joining"),N$??Promise.resolve()):(O$=!0,N$=pZe(),N$)}async function pZe(){K(`Running ${Dm.size} cleanup callbacks`);let t=[];for(let[e,r]of[...Dm,...tD])try{K(`Running cleanup: ${e}`),await r()}catch(n){let s=n instanceof Error?n:new Error(String(n));t.push(s),K(`Cleanup error in ${e}: ${s.message}`)}Dm.clear(),tD.clear(),f_(),t.length>0?K(`Cleanup completed with ${t.length} error(s)`):K("Cleanup completed successfully")}function f_(){try{process.stdout.isTTY&&process.stdout.write("\x1B[?25h"),process.stdin.isTTY&&process.stdin.isRaw&&process.stdin.setRawMode(!1),process.stdout.isTTY&&process.stdout.write("\x1B[0m")}catch{}}function fZe(){return O$}function ace(){if(oce)return;oce=!0,process.stdout.on("error",s=>{if(s.code==="EPIPE"||s.code==="ERR_STREAM_DESTROYED"){K(`stdout ${s.code} - pipe closed`);return}throw s}),process.stderr.on("error",s=>{if(s.code==="EPIPE"||s.code==="ERR_STREAM_DESTROYED"){K(`stderr ${s.code} - pipe closed`);return}throw s});let t=0,e=null,r=()=>Promise.race([ice(),new Promise(s=>setTimeout(s,js).unref())]),n=async(s,o=!1)=>{K(`Received ${s}`),o&&(f_(),process.exit(130)),await r(),f_();let i=s==="SIGINT"?130:143;process.exit(i)};process.on("SIGINT",()=>{if(t++,e&&clearTimeout(e),e=setTimeout(()=>{t=0},1e3),t>=2){try{process.stderr.isTTY&&process.stderr.write(`
|
|
83
83
|
`)}catch{}n("SIGINT",!0);return}n("SIGINT")}),process.on("SIGTERM",()=>{n("SIGTERM")}),process.on("uncaughtException",s=>{(async()=>{let o=s;if(o.code==="EPIPE"||o.code==="ERR_STREAM_DESTROYED"){K(`Ignoring ${o.code} error (broken pipe)`);return}console.error(`
|
|
84
84
|
Uncaught exception:`,s.message),K(`Uncaught exception: ${s.stack}`),await r(),f_(),process.exit(1)})()}),process.on("unhandledRejection",s=>{(async()=>(console.error(`
|
|
85
|
-
Unhandled rejection:`,s),K(`Unhandled rejection: ${s}`),await r(),f_(),process.exit(1)))()}),K("Signal handlers registered")}var O$,Dm,tD,oce,N$,nt,Oi=w(()=>{"use strict";rt();p_();O$=!1,Dm=new Map,tD=new Map,oce=!1;N$=null;nt={register:cZe,registerFirst:uZe,registerFinal:lZe,unregister:dZe,cleanup:ice,isShuttingDown:fZe,restoreTerminal:f_}});import cce from"node:fs";import ob from"node:path";import{createHash as mZe,randomUUID as lce}from"node:crypto";import{homedir as hZe}from"node:os";function Rm(t){return uce.get(t)}function gZe(t,e,r,n,s,o,i){let a="prepared",c="session-startup-"+r.record.runtimeId,l={session:t,inference:e,owner:r,persistence:n,resumed:o,abort(){a==="prepared"&&(a="aborted",nt.unregister(c),r.release())},async commit(u){if(a!=="prepared"||!r.active)throw new ge("runtime_active","Session startup is no longer active");let d=go(ob.join(s,"owners",t.id+".owner"));if(d.nonce!==r.record.nonce||d.pid!==r.record.pid)throw new ge("runtime_active","Ownership changed");a="committing",nt.unregister(c);let p={provider:u.provider,model:u.model,openrouterProvider:u.openrouterProvider};Object.assign(e,p),Object.assign(t,p),Object.assign(i.getConfig().llm,p),Sm(i,e),t.remoteConversation.inference=e;let f;try{f=await qv(s,t.id),await n.save(t),await ZS(f),a="committed"}catch(m){throw a="failed",t.remoteConversation.syncUnavailable=!0,f&&await n.save(t,{updateCurrent:!1}).catch(()=>{}),m}}};return nt.registerFirst(c,()=>l.abort()),l}async function rD(t,e,r={}){let n=cce.realpathSync(r.cwd??process.cwd()),s=r.sessionsDir??ep(),o=new wm(s),i=r.identityDir??ob.join(hZe(),".aii","identities"),a=y$(i,"installation"),c=y$(i,"workspace-"+mZe("sha256").update(n).digest("hex")),l=lce(),u=e.continueId;if(!u&&e.continue)try{u=go(ob.join(s,"current.json")).id}catch{throw new ge("context_unavailable","No saved current session")}let d=u?void 0:bs({projectPath:n,reasoningEffort:t.getConfig().llm.reasoning_effort});u??=d.id,Tm(s,u);let p=Rae(ob.join(s,"owners"),u,{runtimeId:l,installationId:a,canonicalWorkspace:n},()=>{try{Tm(s,u);let f=go(ob.join(s,u+".json")).remoteConversation;return!f?.turn?.executionDirty&&!f?.syncUnavailable}catch{return!1}});try{let f=d??await o.loadExact(u);if(cce.realpathSync(f.projectPath)!==n)throw new ge("wrong_workspace",`Run from ${f.projectPath}`);let m=f.remoteConversation;if(m&&(m.installationId!==a||m.workspaceIdentity!==c||m.canonicalWorkspace!==n))throw new ge("wrong_installation_or_workspace");if(m?.origin==="web-device")throw new ge("context_unavailable","Resume this hosted conversation from its connected computer in AiiCloud");if(m?.syncUnavailable)throw new ge("sync_unavailable");if(m?.turn?.executionDirty)throw new ge("execution_unresolved");if(!d&&e.remoteControl&&!m)throw new ge("context_unavailable","This legacy snapshot has no verified Cloud binding; resume privately without --remote-control");let h=await t_(t,e,m?.inference??(d?void 0:{backend:f.connectionMode==="cloud"?"cloud":"server",endpoint:t.getConfig().api.url,model:f.model,provider:f.provider,openrouterProvider:f.openrouterProvider,reasoningEffort:f.reasoningEffort})),A=m?.logicalSessionId??lce();f.remoteConversation=m??{schema:1,origin:"cli",installationId:a,workspaceIdentity:c,logicalSessionId:A,deviceId:A,canonicalWorkspace:n,inference:h,revision:0,checkpointId:Kl(),exposure:{fromRevision:0},pendingOutcomes:[]},f.remoteConversation.inference=h,f.remoteConversation.lastRuntimeId=l,f.remote={armed:!1,state:"off",deviceId:A},f.permissionCache.clear(),Object.assign(f,{model:h.model,provider:h.provider,openrouterProvider:h.openrouterProvider,reasoningEffort:h.reasoningEffort,connectionMode:h.backend==="cloud"?"cloud":"local"});let _=gZe(f,h,p,o,s,!d,t);return uce.set(e,_),_}catch(f){throw p.release(),f}}var uce,x$=w(()=>{"use strict";zv();KS();Ao();hu();n_();sn();Oi();uce=new WeakMap});import*as zc from"fs";import{randomUUID as AZe}from"crypto";function xi(t,e,r=384){let n=`${t}.${process.pid}.${AZe()}.tmp`;try{zc.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),zc.renameSync(n,t)}catch(s){try{zc.unlinkSync(n)}catch{}throw s}}function Ks(t,e=448){zc.mkdirSync(t,{recursive:!0,mode:e});let r=Zd(t);if(r!==null){x.debug(`ensureDirSecure: refusing to chmod ${t} \u2014 that is ${r}, and tightening it would lock out every other process that reads it.`);return}try{zc.chmodSync(t,e)}catch{}}var Wc=w(()=>{"use strict";rt();JS()});function B$(t,e){try{let r=t?.replace(/^v/,"")||"0.0.0",n=e?.replace(/^v/,"")||"0.0.0",s=r.split(".").map(Number),o=n.split(".").map(Number),i=Math.max(s.length,o.length);for(;s.length<i;)s.push(0);for(;o.length<i;)o.push(0);for(let a=0;a<i;a++){if(s[a]<o[a])return!0;if(s[a]>o[a])return!1}return!1}catch{return!1}}function pce(t){return t?!B$(t,_Ze):!1}var _o,_Ze,nD=w(()=>{"use strict";_o="v0.5.
|
|
85
|
+
Unhandled rejection:`,s),K(`Unhandled rejection: ${s}`),await r(),f_(),process.exit(1)))()}),K("Signal handlers registered")}var O$,Dm,tD,oce,N$,nt,Oi=w(()=>{"use strict";rt();p_();O$=!1,Dm=new Map,tD=new Map,oce=!1;N$=null;nt={register:cZe,registerFirst:uZe,registerFinal:lZe,unregister:dZe,cleanup:ice,isShuttingDown:fZe,restoreTerminal:f_}});import cce from"node:fs";import ob from"node:path";import{createHash as mZe,randomUUID as lce}from"node:crypto";import{homedir as hZe}from"node:os";function Rm(t){return uce.get(t)}function gZe(t,e,r,n,s,o,i){let a="prepared",c="session-startup-"+r.record.runtimeId,l={session:t,inference:e,owner:r,persistence:n,resumed:o,abort(){a==="prepared"&&(a="aborted",nt.unregister(c),r.release())},async commit(u){if(a!=="prepared"||!r.active)throw new ge("runtime_active","Session startup is no longer active");let d=go(ob.join(s,"owners",t.id+".owner"));if(d.nonce!==r.record.nonce||d.pid!==r.record.pid)throw new ge("runtime_active","Ownership changed");a="committing",nt.unregister(c);let p={provider:u.provider,model:u.model,openrouterProvider:u.openrouterProvider};Object.assign(e,p),Object.assign(t,p),Object.assign(i.getConfig().llm,p),Sm(i,e),t.remoteConversation.inference=e;let f;try{f=await qv(s,t.id),await n.save(t),await ZS(f),a="committed"}catch(m){throw a="failed",t.remoteConversation.syncUnavailable=!0,f&&await n.save(t,{updateCurrent:!1}).catch(()=>{}),m}}};return nt.registerFirst(c,()=>l.abort()),l}async function rD(t,e,r={}){let n=cce.realpathSync(r.cwd??process.cwd()),s=r.sessionsDir??ep(),o=new wm(s),i=r.identityDir??ob.join(hZe(),".aii","identities"),a=y$(i,"installation"),c=y$(i,"workspace-"+mZe("sha256").update(n).digest("hex")),l=lce(),u=e.continueId;if(!u&&e.continue)try{u=go(ob.join(s,"current.json")).id}catch{throw new ge("context_unavailable","No saved current session")}let d=u?void 0:bs({projectPath:n,reasoningEffort:t.getConfig().llm.reasoning_effort});u??=d.id,Tm(s,u);let p=Rae(ob.join(s,"owners"),u,{runtimeId:l,installationId:a,canonicalWorkspace:n},()=>{try{Tm(s,u);let f=go(ob.join(s,u+".json")).remoteConversation;return!f?.turn?.executionDirty&&!f?.syncUnavailable}catch{return!1}});try{let f=d??await o.loadExact(u);if(cce.realpathSync(f.projectPath)!==n)throw new ge("wrong_workspace",`Run from ${f.projectPath}`);let m=f.remoteConversation;if(m&&(m.installationId!==a||m.workspaceIdentity!==c||m.canonicalWorkspace!==n))throw new ge("wrong_installation_or_workspace");if(m?.origin==="web-device")throw new ge("context_unavailable","Resume this hosted conversation from its connected computer in AiiCloud");if(m?.syncUnavailable)throw new ge("sync_unavailable");if(m?.turn?.executionDirty)throw new ge("execution_unresolved");if(!d&&e.remoteControl&&!m)throw new ge("context_unavailable","This legacy snapshot has no verified Cloud binding; resume privately without --remote-control");let h=await t_(t,e,m?.inference??(d?void 0:{backend:f.connectionMode==="cloud"?"cloud":"server",endpoint:t.getConfig().api.url,model:f.model,provider:f.provider,openrouterProvider:f.openrouterProvider,reasoningEffort:f.reasoningEffort})),A=m?.logicalSessionId??lce();f.remoteConversation=m??{schema:1,origin:"cli",installationId:a,workspaceIdentity:c,logicalSessionId:A,deviceId:A,canonicalWorkspace:n,inference:h,revision:0,checkpointId:Kl(),exposure:{fromRevision:0},pendingOutcomes:[]},f.remoteConversation.inference=h,f.remoteConversation.lastRuntimeId=l,f.remote={armed:!1,state:"off",deviceId:A},f.permissionCache.clear(),Object.assign(f,{model:h.model,provider:h.provider,openrouterProvider:h.openrouterProvider,reasoningEffort:h.reasoningEffort,connectionMode:h.backend==="cloud"?"cloud":"local"});let _=gZe(f,h,p,o,s,!d,t);return uce.set(e,_),_}catch(f){throw p.release(),f}}var uce,x$=w(()=>{"use strict";zv();KS();Ao();hu();n_();sn();Oi();uce=new WeakMap});import*as zc from"fs";import{randomUUID as AZe}from"crypto";function xi(t,e,r=384){let n=`${t}.${process.pid}.${AZe()}.tmp`;try{zc.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),zc.renameSync(n,t)}catch(s){try{zc.unlinkSync(n)}catch{}throw s}}function Ks(t,e=448){zc.mkdirSync(t,{recursive:!0,mode:e});let r=Zd(t);if(r!==null){x.debug(`ensureDirSecure: refusing to chmod ${t} \u2014 that is ${r}, and tightening it would lock out every other process that reads it.`);return}try{zc.chmodSync(t,e)}catch{}}var Wc=w(()=>{"use strict";rt();JS()});function B$(t,e){try{let r=t?.replace(/^v/,"")||"0.0.0",n=e?.replace(/^v/,"")||"0.0.0",s=r.split(".").map(Number),o=n.split(".").map(Number),i=Math.max(s.length,o.length);for(;s.length<i;)s.push(0);for(;o.length<i;)o.push(0);for(let a=0;a<i;a++){if(s[a]<o[a])return!0;if(s[a]>o[a])return!1}return!1}catch{return!1}}function pce(t){return t?!B$(t,_Ze):!1}var _o,_Ze,nD=w(()=>{"use strict";_o="v0.5.71",_Ze="v0.5.40"});import{execSync as yn,spawn as EZe}from"node:child_process";import{mkdtempSync as yZe,writeFileSync as CZe,rmSync as m_}from"node:fs";import{tmpdir as SZe}from"node:os";import{join as fce}from"node:path";import{createHash as bZe}from"node:crypto";import*as Ace from"node:readline";function oD(){try{return yn("docker --version",{timeout:5e3,stdio:"pipe"}),!0}catch{return!1}}function iD(){try{return yn("docker info",{timeout:5e3,stdio:"pipe"}),!0}catch{if(process.platform==="linux")try{return yn("sudo -n docker info",{timeout:5e3,stdio:"pipe"}),!0}catch{return!1}return!1}}async function sD(t){let e=Date.now();for(;Date.now()-e<t;){if(iD())return;await new Promise(r=>setTimeout(r,2e3))}throw new Cn("Docker daemon did not start within timeout.","macOS: open -a Docker","Linux: sudo systemctl start docker",...Vc)}async function IZe(){let t=process.platform;if(t==="darwin"){try{yn("open -a Docker",{timeout:5e3,stdio:"pipe"})}catch{throw new Cn("Failed to start Docker Desktop.","Start Docker Desktop manually from Applications.",...Vc)}await sD(6e4)}else if(t==="linux"){try{yn("sudo systemctl start docker",{timeout:15e3,stdio:"pipe"})}catch{throw new Cn("Docker daemon is not running.","sudo systemctl start docker",...Vc)}await sD(15e3)}else throw t==="win32"?(process.stderr.write(`
|
|
86
86
|
\u26A0 Windows support is experimental. For best results, use WSL2.
|
|
87
87
|
`),process.stderr.write(` Need help? X/Twitter: @aii_dev | Email: support@aiiware.com
|
|
88
88
|
|
|
@@ -352,7 +352,7 @@ shutting down\u2026 (Ctrl+C again to force)
|
|
|
352
352
|
`),zfe="CODEX_ENTITLEMENT_DENIED:",Pat=["\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
|
`),I8=[{prefix:xat,wall:Bat},{prefix:Mat,wall:Lat},{prefix:zfe,wall:Pat}],Fat="PROVIDER_AUTH_REJECTED:",Qat="upstream 401 Unauthorized:",Uat=`${Fat} ${Qat}`,$at=/"status":\s*401\b|token_expired/;VR="\u25D0 Your provider credential was rejected upstream \u2014 expired, rotated, or invalid. Sign-in lanes: aii login --status \xB7 API keys: aii setup";T8="\u25D0 Your sign-in token was refreshed mid-turn \u2014 retry this step (autonomous runs retry automatically).",Gat=[ER,MG,VR,T8];Hat="Note: Z.ai limits Coding Plans to their officially supported tools; Aii isn't listed yet.",Yat={zai:"glm"};oI={xai:{tier:"sanctioned",kind:"oauth",description:"SuperGrok / X Premium"},glm:{tier:"unofficial",kind:"plan-key",disclosure:"notice",notice:Hat,description:"GLM Coding Plan (flat-rate)"},claude:{tier:"blocked",wall:Nat},openai:{tier:"unofficial",kind:"oauth",disclosure:"consent",consentCopy:Hde,description:"ChatGPT subscription (Codex)"},google:{tier:"blocked",wall:Oat}},qat={sanctioned:"sanctioned",unofficial:"unofficial (explicit consent required)",blocked:"blocked (provider terms)",unavailable:"unavailable (pending provider sanction)"},w8="Other providers use API keys \u2014 aii setup.",k8="Sign in: aii login --provider xai \xB7 status: aii login --status"});function V_(t,e){let r=typeof t=="object"&&t!==null?t:{},n=r.error,s="",o=typeof r.error_description=="string"?r.error_description:"";if(typeof n=="string")s=n;else if(typeof n=="object"&&n!==null){let c=n;s=[c.code,c.type,c.error].find(l=>typeof l=="string")??"",!o&&typeof c.message=="string"&&(o=c.message)}let i=[s,o].filter(c=>c.length>0),a=i.length>0?i.join(": "):`HTTP ${e}`;return{code:s,detail:oe(a).slice(0,160)}}function jfe(t){return t.code==="invalid_grant"||/invalid_grant/i.test(t.detail)}var ZR=w(()=>{"use strict";Ot()});import{execFileSync as D8}from"node:child_process";function N8(t){if(!t)return!1;try{let e=new URL(t).protocol;return e==="https:"||e==="http:"}catch{return!1}}function O8(t){N8(t)&&(process.platform==="darwin"?D8("open",[t],{stdio:"ignore"}):process.platform==="win32"?D8("cmd",["/c","start","",t],{stdio:"ignore"}):D8("xdg-open",[t],{stdio:"ignore"}))}function R8(t){if(t?.aborted)throw new di}async function eh(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 Kfe(t,e={}){let r=e.fetchImpl??fetch,n=e.openBrowser??O8,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,_)=>eh(r,A,_,c);R8(a);let u;try{u=await l(t.deviceEndpoint,{client_id:t.clientId,scope:t.scopes})}catch(A){throw A.name==="AbortError"?new cr(`Sign-in unreachable (${new URL(t.deviceEndpoint).hostname} timed out). Check your network and retry.`):A}if(!u.ok)throw new cr(`Device authorization failed to start (HTTP ${u.status}).`);let d;try{d=JSON.parse(u.text)}catch{throw new cr("Device authorization returned an unreadable response.")}if(!d.device_code||!d.user_code||!d.verification_uri)throw new cr("Device authorization response is missing required fields.");if(!N8(d.verification_uri))throw new cr("Sign-in aborted: the provider returned a suspicious verification URL \u2014 refusing to open or display it.");let p=N8(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??Vat)*1e3,m=Number.isFinite(d.expires_in)&&d.expires_in>0?d.expires_in:Wat,h=o()+m*1e3;for(;;){R8(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(V_(_,A.status).code||void 0){case"authorization_pending":break;case"slow_down":f+=jat;break;case"access_denied":throw new cr("Sign-in declined in the browser \u2014 nothing was saved.");case"expired_token":throw new cr("The sign-in code expired. Run the command again to retry.");case void 0:break;default:throw new cr(`Sign-in failed (${oe(String(_.error))}${_.error_description?`: ${oe(String(_.error_description))}`:""}).`)}}catch(A){if(A instanceof cr||A instanceof di)throw A}if(o()>=h)throw new cr("Timed out waiting for sign-in. Run the command again to retry.");await s(f),R8(a)}}var cr,di,Wat,Vat,jat,eN=w(()=>{"use strict";ZR();Ot();cr=class extends Error{constructor(e){super(e),this.name="ProviderAuthError"}},di=class extends Error{constructor(e="Sign-in cancelled \u2014 nothing was saved."){super(e),this.name="ProviderAuthCancelled"}},Wat=300,Vat=5,jat=5e3});function eme(t,e){Jfe.has(e)||(Jfe.add(e),t(e))}function Xfe(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 tN(t,e,r={},n=gp){let s=r.now??(()=>Date.now());if(!e||typeof e.access_token!="string"||e.access_token.length===0)throw new cr("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(Xfe(e.access_token)?.exp);i=Number.isFinite(c)&&c>o?c:o+Jat}let a;if(e.id_token){let c=Xfe(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 Zfe(t,e,r){await t.setSecret(r.keys.dead,"1"),await t.setSecret(r.keys.access,""),await t.setSecret(r.keys.expiry,""),eme(e,r.pl04Line)}async function th(t,e={},r={},n=gp){let s=e.now??(()=>Date.now()),o=e.print??(E=>process.stdout.write(E+`
|
|
355
|
-
`)),i=n.provider==="openai"?"OpenAI":"xAI";if(t.getSecret(n.keys.dead)==="1")return eme(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-Kat&&!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 Zfe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await eh(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 cr(`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 tN(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};let _=V_(A,h.status);if(jfe(_))return await Zfe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new cr(`Could not refresh your ${i} sign-in (${_.detail}). Run aii login --provider ${n.provider} to reconnect.`)}var Kat,Jat,Jfe,iI=w(()=>{"use strict";eN();ai();ai();Ot();ZR();Kat=120,Jat=3600,Jfe=new Set});function aI(t){return t?t===VR||z_(t)?!0:jR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function tme(t){if(t)try{let e=he();return e.reloadSecretsSync(),ape().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function rN(t=gp,e){let r=x8.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=he();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await th(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(()=>{x8.delete(t.provider)});return x8.set(t.provider,n),n}var x8,B8=w(()=>{"use strict";Xe();iI();W_();O_();rt();O_();x8=new Map});function rme(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function nN(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:rme(t.protocol_version)}}function sN(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 rh(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 oN(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function M8(t){return t==null||typeof t=="object"}function aN(t){switch(t.type){case"tool_request":return M8(t.input);case"mcp_tool_request":return M8(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&M8(r.input))}default:return!0}}function cN(t){return rme(t)>2?"hard":"compatible"}function lN(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 ws,nme,sme,iN,vu=w(()=>{"use strict";ws=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};nme=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"]),sme=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"]),iN=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function ome(t,e){e?nh.set(t,e):nh.delete(t)}function Gi(t,e){e?uN.add(t):uN.delete(t)}function P8(t,e){e?L8.set(t,e):L8.delete(t)}function ame(t,e){ime.set(t,e)}function cme(t,e){return ime.get(t)?.(e)??!1}function lme(t){let e=nh.get(t);e&&!e.attempted&&!e.blocked&&F8(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),nh.delete(t)}function F8(t,e){let r=nh.get(t);r&&Q8(r,e)}function Q8(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 nh,uN,L8,$i,dN,pN,fN,pi,ime,Hi=w(()=>{"use strict";nh=new WeakMap,uN=new WeakSet,L8=new WeakMap,$i=t=>nh.get(t);dN=t=>uN.has(t);pN=t=>nh.has(t)||uN.has(t),fN=t=>L8.get(t);pi=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},ime=new WeakMap});import{createHash as Xat}from"node:crypto";function oct(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Zat.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function ict(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=>sct.includes(o)))}function ume(t,e){return U8(t,e)===null}function U8(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return ect.test(r)?rct.test(r)?"substitution":nct.test(r)?"chained":"redirection":tct.test(r)?"injection-flag":ict(r)?"second-action":null}function act(t){try{return String(t)}catch{return"~unstringifiable"}}function j_(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=>j_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${j_(c,e)}=>${j_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>j_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${act(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${j_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function $8(t){return Xat("sha256").update(j_(t??{},new WeakSet)).digest("hex").slice(0,16)}function G8(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return oct(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Pt(s,r,n);return o.ok?`${t}:${rs(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${$8(e)}`}function dme(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?G8(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Zat,ect,tct,rct,nct,sct,H8=w(()=>{"use strict";ns();Zat=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),ect=/[;&|<>`\n]|\$\(/,tct=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,rct=/[`]|\$\(/,nct=/[;&|\n]/,sct=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function mN(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function Y8(t,e){return t!==void 0&&t>=0&&t<e?t:0}function pme(t,e){return{selectedIndex:Y8(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var q8=w(()=>{"use strict"});var cct,lct,uct,dct,pct,fct,mct,sh,hN,vp,z8=w(()=>{"use strict";Te();cct={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")}},lct={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")}},uct={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")}},dct={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")}},pct={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")}},fct={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")}},mct={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}},sh={classic:cct,brand:lct,teal:uct,indigo:dct,forest:pct,amber:fct,grayscale:mct},hN="classic",vp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var oh={};ce(oh,{BAND_STYLE_INFO:()=>cI,BAND_STYLE_ORDER:()=>Dp,DEFAULT_BAND_STYLE:()=>V8,ThemeManager:()=>Ya,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>J_,resolveBandBg:()=>K_});function K_(t,e){let r=cI[t];if(r.blend===null)return hct;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,W8[0])<<16|i(s>>8&255,W8[1])<<8|i(s&255,W8[2])).toString(16).padStart(6,"0")}function J(){return Ya.getInstance().getColors()}function $e(){return Ya.getInstance().getAccentColorName()}function J_(){return Ya.getInstance().getUserInputTextColorName()}var Dp,cI,V8,W8,hct,Ya,Rp=w(()=>{"use strict";z8();Xe();Dp=["subtle","themed","neutral","bold"],cI={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"}},V8="themed",W8=[20,22,27],hct="#262C34";Ya=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=sh[hN]}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=sh[e];if(!r){let n=vp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in sh}getAvailableThemes(){return vp.map(e=>sh[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=he().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=V8,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${Dp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return Dp.includes(e)}reset(){this.activeTheme=sh[hN],this.bandStyle=null}}});var zt=w(()=>{"use strict";z8();Rp()});import{resolve as gct}from"path";function Act(){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 lI(){return j8===null&&(j8=Act()),j8}function _ct(){return process.platform==="darwin"?"Cmd":"Ctrl"}function mme(){return fme||!lI()?"":(fme=!0,` (${_ct()}+Click to open)`)}function Ect(t,e){return lI()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function hme(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(!lI())return J().filePath(o);let i=J().accent(o),c=`file://${gct(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Ect(i,c)}var j8,fme,gme=w(()=>{"use strict";zt();j8=null,fme=!1});function yct(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 Cct(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 Tn(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;Cct(s)||(yct(s)?r+=2:r+=1)}return r}function nl(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Tn(s);if(r+o>e)break;n+=s,r+=o}return n}var ih=w(()=>{"use strict"});function J8(t){return t.replace(K8,"")}function Sct(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function qa(t){return J8(oe(Sct(t??"")))}var K8,Np=w(()=>{"use strict";Ot();K8=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var yme={};ce(yme,{VERSION:()=>ah,colors:()=>P,formatCode:()=>Oct,formatPath:()=>Eme,getActionIndicator:()=>Nct,padEndAnsi:()=>Lct,printDivider:()=>_me,printError:()=>Dct,printExitSummary:()=>Z8,printHeader:()=>Rct,printSuccess:()=>kct,printToolResultCompact:()=>za,printWarning:()=>vct,shortenPath:()=>Bct});function bct(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 wct(t){return Tct.test(t)}function za(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?P.success("\u25CF"):P.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=bct(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=qa(d),f=Tn(t)+6+i,m=Math.max(Ict,(a.columns||80)-f),A=Tn(p)>m?nl(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!wct(e)&&_;if(E){let C=e.match(/:(\d+)$/),T=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=Eme(k,T,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?P.dim(mme()):"",S=o&&!y&&!Ame?P.dim(" (ctrl+o to expand)"):"";if(S&&(Ame=!0),n){let C=r?P.dim:P.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",T=r?P.dim:P.error;s(T(`\u2514 ${C}`)+y+S)}}function kct(t){console.log(P.success("\u2713 ")+t)}function vct(t){console.log(P.warning("\u26A0 ")+t)}function Dct(t){console.log(P.error("\u2717 ")+t)}function _me(t=60){console.log(P.dim("\u2500".repeat(t)))}function Rct(t){console.log(P.logo(t)),_me(t.length)}function Nct(t){return P.thinking(`[${t}]`)}function Eme(t,e,r){if(lI())return hme(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}`),P.filePath(r??s)}function Oct(t){return P.code(t)}function xct(){return process.stdout.columns||80}function Bct(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 Mct(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Lct(t,e){let r=Mct(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function Pct(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 X8(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Z8(t){let e=xct(),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=>P.border("\u2502")+" "+s(A,n)+" "+P.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=P.dim(A.padEnd(15))+_,T=P.dim(E.padEnd(15))+y;return o(s(C,S)+T)},a=Pct(t.durationSeconds),c=X8(t.tokensIn),l=X8(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(P.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(P.logo("Session complete. \u{1FABC}"))),console.log(P.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(P.logo("Session Summary"))),console.log(o(P.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(P.logo("Token Usage"))),console.log(o(P.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(P.dim("Cached".padEnd(15))+`${X8(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?P.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(P.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(P.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(P.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(P.dim("Model: ")+P.model(d))),console.log(P.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var ah,P,Ict,Tct,Ame,Br=w(()=>{"use strict";Te();gme();zt();ih();Np();ah="0.25.14",P={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}};Ict=24,Tct=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Ame=!1});var t4={};ce(t4,{MAX_RETAINED_TOASTS:()=>e4,MAX_VISIBLE_TOASTS:()=>uI,getNotificationStore:()=>at,useNotificationStore:()=>Hn});import{create as Fct}from"zustand";function Cme(t){return t.length<=e4?t:t.slice(-e4)}var uI,e4,Hn,at,sl=w(()=>{"use strict";uI=5,e4=200;Hn=Fct((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:Cme([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Cme([...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,uI),overflowCount:()=>Math.max(0,e().toasts.length-uI)}));Object.defineProperty(Hn,"toast",{get:()=>{let t=Hn.getState().toasts;return t.length>0?t[t.length-1]:null}});at=Hn.getState});var bme={};ce(bme,{getUserEchoSink:()=>r4,setUserEchoSink:()=>Qct});function Qct(t){Sme=t}function r4(){return Sme}var Sme,n4=w(()=>{"use strict";Sme=null});import{create as Uct}from"zustand";var Ime,ch,gN=w(()=>{"use strict";sl();n4();Ime=Uct((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&&at().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=r4();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),ch=Ime.getState});import{create as $ct}from"zustand";var X_,wn,lh=w(()=>{"use strict";X_=null,wn=$ct((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}),X_!==null&&clearInterval(X_),X_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{X_!==null&&(clearInterval(X_),X_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var AN={};ce(AN,{getUIStore:()=>Ke,useUIStore:()=>wo});import{create as Gct}from"zustand";var Tme,wo,Ke,Op=w(()=>{"use strict";Tme={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},wo=Gct(t=>({...Tme,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(Tme)})),Ke=wo.getState});var dI={};ce(dI,{getInputStore:()=>Z_,useInputStore:()=>ss});import{create as Hct}from"zustand";var wme,Yct,qct,ss,Z_,Du=w(()=>{"use strict";Te();sl();Op();wme={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},Yct=100,qct=50,ss=Hct((t,e)=>({...wme,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 eme(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-Kat&&!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 Zfe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await eh(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 cr(`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 tN(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};let _=V_(A,h.status);if(jfe(_))return await Zfe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new cr(`Could not refresh your ${i} sign-in (${_.detail}). Run aii login --provider ${n.provider} to reconnect.`)}var Kat,Jat,Jfe,iI=w(()=>{"use strict";eN();ai();ai();Ot();ZR();Kat=120,Jat=3600,Jfe=new Set});function aI(t){return t?t===VR||z_(t)?!0:jR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function tme(t){if(t)try{let e=he();return e.reloadSecretsSync(),ape().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function rN(t=gp,e){let r=x8.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=he();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await th(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(()=>{x8.delete(t.provider)});return x8.set(t.provider,n),n}var x8,B8=w(()=>{"use strict";Xe();iI();W_();O_();rt();O_();x8=new Map});function rme(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function nN(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:rme(t.protocol_version)}}function sN(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 rh(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 oN(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function M8(t){return t==null||typeof t=="object"}function aN(t){switch(t.type){case"tool_request":return M8(t.input);case"mcp_tool_request":return M8(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&M8(r.input))}default:return!0}}function cN(t){return rme(t)>2?"hard":"compatible"}function lN(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 ws,nme,sme,iN,vu=w(()=>{"use strict";ws=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};nme=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"]),sme=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"]),iN=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function ome(t,e){e?nh.set(t,e):nh.delete(t)}function Gi(t,e){e?uN.add(t):uN.delete(t)}function P8(t,e){e?L8.set(t,e):L8.delete(t)}function ame(t,e){ime.set(t,e)}function cme(t,e){return ime.get(t)?.(e)??!1}function lme(t){let e=nh.get(t);e&&!e.attempted&&!e.blocked&&F8(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),nh.delete(t)}function F8(t,e){let r=nh.get(t);r&&Q8(r,e)}function Q8(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 nh,uN,L8,$i,dN,pN,fN,pi,ime,Hi=w(()=>{"use strict";nh=new WeakMap,uN=new WeakSet,L8=new WeakMap,$i=t=>nh.get(t);dN=t=>uN.has(t);pN=t=>nh.has(t)||uN.has(t),fN=t=>L8.get(t);pi=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},ime=new WeakMap});import{createHash as Xat}from"node:crypto";function oct(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Zat.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function ict(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=>sct.includes(o)))}function ume(t,e){return U8(t,e)===null}function U8(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return ect.test(r)?rct.test(r)?"substitution":nct.test(r)?"chained":"redirection":tct.test(r)?"injection-flag":ict(r)?"second-action":null}function act(t){try{return String(t)}catch{return"~unstringifiable"}}function j_(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=>j_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${j_(c,e)}=>${j_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>j_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${act(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${j_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function $8(t){return Xat("sha256").update(j_(t??{},new WeakSet)).digest("hex").slice(0,16)}function G8(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return oct(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Pt(s,r,n);return o.ok?`${t}:${rs(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${$8(e)}`}function dme(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?G8(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Zat,ect,tct,rct,nct,sct,H8=w(()=>{"use strict";ns();Zat=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),ect=/[;&|<>`\n]|\$\(/,tct=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,rct=/[`]|\$\(/,nct=/[;&|\n]/,sct=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function mN(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function Y8(t,e){return t!==void 0&&t>=0&&t<e?t:0}function pme(t,e){return{selectedIndex:Y8(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var q8=w(()=>{"use strict"});var cct,lct,uct,dct,pct,fct,mct,sh,hN,vp,z8=w(()=>{"use strict";Te();cct={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")}},lct={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")}},uct={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")}},dct={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")}},pct={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")}},fct={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")}},mct={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}},sh={classic:cct,brand:lct,teal:uct,indigo:dct,forest:pct,amber:fct,grayscale:mct},hN="classic",vp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var oh={};ce(oh,{BAND_STYLE_INFO:()=>cI,BAND_STYLE_ORDER:()=>Dp,DEFAULT_BAND_STYLE:()=>V8,ThemeManager:()=>Ya,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>J_,resolveBandBg:()=>K_});function K_(t,e){let r=cI[t];if(r.blend===null)return hct;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,W8[0])<<16|i(s>>8&255,W8[1])<<8|i(s&255,W8[2])).toString(16).padStart(6,"0")}function J(){return Ya.getInstance().getColors()}function $e(){return Ya.getInstance().getAccentColorName()}function J_(){return Ya.getInstance().getUserInputTextColorName()}var Dp,cI,V8,W8,hct,Ya,Rp=w(()=>{"use strict";z8();Xe();Dp=["subtle","themed","neutral","bold"],cI={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"}},V8="themed",W8=[20,22,27],hct="#262C34";Ya=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=sh[hN]}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=sh[e];if(!r){let n=vp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in sh}getAvailableThemes(){return vp.map(e=>sh[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=he().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=V8,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${Dp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return Dp.includes(e)}reset(){this.activeTheme=sh[hN],this.bandStyle=null}}});var zt=w(()=>{"use strict";z8();Rp()});import{resolve as gct}from"path";function Act(){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 lI(){return j8===null&&(j8=Act()),j8}function _ct(){return process.platform==="darwin"?"Cmd":"Ctrl"}function mme(){return fme||!lI()?"":(fme=!0,` (${_ct()}+Click to open)`)}function Ect(t,e){return lI()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function hme(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(!lI())return J().filePath(o);let i=J().accent(o),c=`file://${gct(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Ect(i,c)}var j8,fme,gme=w(()=>{"use strict";zt();j8=null,fme=!1});function yct(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 Cct(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 Tn(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;Cct(s)||(yct(s)?r+=2:r+=1)}return r}function nl(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Tn(s);if(r+o>e)break;n+=s,r+=o}return n}var ih=w(()=>{"use strict"});function J8(t){return t.replace(K8,"")}function Sct(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function qa(t){return J8(oe(Sct(t??"")))}var K8,Np=w(()=>{"use strict";Ot();K8=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var yme={};ce(yme,{VERSION:()=>ah,colors:()=>P,formatCode:()=>Oct,formatPath:()=>Eme,getActionIndicator:()=>Nct,padEndAnsi:()=>Lct,printDivider:()=>_me,printError:()=>Dct,printExitSummary:()=>Z8,printHeader:()=>Rct,printSuccess:()=>kct,printToolResultCompact:()=>za,printWarning:()=>vct,shortenPath:()=>Bct});function bct(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 wct(t){return Tct.test(t)}function za(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?P.success("\u25CF"):P.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=bct(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=qa(d),f=Tn(t)+6+i,m=Math.max(Ict,(a.columns||80)-f),A=Tn(p)>m?nl(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!wct(e)&&_;if(E){let C=e.match(/:(\d+)$/),T=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=Eme(k,T,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?P.dim(mme()):"",S=o&&!y&&!Ame?P.dim(" (ctrl+o to expand)"):"";if(S&&(Ame=!0),n){let C=r?P.dim:P.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",T=r?P.dim:P.error;s(T(`\u2514 ${C}`)+y+S)}}function kct(t){console.log(P.success("\u2713 ")+t)}function vct(t){console.log(P.warning("\u26A0 ")+t)}function Dct(t){console.log(P.error("\u2717 ")+t)}function _me(t=60){console.log(P.dim("\u2500".repeat(t)))}function Rct(t){console.log(P.logo(t)),_me(t.length)}function Nct(t){return P.thinking(`[${t}]`)}function Eme(t,e,r){if(lI())return hme(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}`),P.filePath(r??s)}function Oct(t){return P.code(t)}function xct(){return process.stdout.columns||80}function Bct(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 Mct(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Lct(t,e){let r=Mct(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function Pct(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 X8(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Z8(t){let e=xct(),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=>P.border("\u2502")+" "+s(A,n)+" "+P.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=P.dim(A.padEnd(15))+_,T=P.dim(E.padEnd(15))+y;return o(s(C,S)+T)},a=Pct(t.durationSeconds),c=X8(t.tokensIn),l=X8(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(P.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(P.logo("Session complete. \u{1FABC}"))),console.log(P.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(P.logo("Session Summary"))),console.log(o(P.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(P.logo("Token Usage"))),console.log(o(P.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(P.dim("Cached".padEnd(15))+`${X8(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?P.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(P.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(P.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(P.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(P.dim("Model: ")+P.model(d))),console.log(P.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var ah,P,Ict,Tct,Ame,Br=w(()=>{"use strict";Te();gme();zt();ih();Np();ah="0.25.15",P={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}};Ict=24,Tct=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Ame=!1});var t4={};ce(t4,{MAX_RETAINED_TOASTS:()=>e4,MAX_VISIBLE_TOASTS:()=>uI,getNotificationStore:()=>at,useNotificationStore:()=>Hn});import{create as Fct}from"zustand";function Cme(t){return t.length<=e4?t:t.slice(-e4)}var uI,e4,Hn,at,sl=w(()=>{"use strict";uI=5,e4=200;Hn=Fct((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:Cme([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Cme([...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,uI),overflowCount:()=>Math.max(0,e().toasts.length-uI)}));Object.defineProperty(Hn,"toast",{get:()=>{let t=Hn.getState().toasts;return t.length>0?t[t.length-1]:null}});at=Hn.getState});var bme={};ce(bme,{getUserEchoSink:()=>r4,setUserEchoSink:()=>Qct});function Qct(t){Sme=t}function r4(){return Sme}var Sme,n4=w(()=>{"use strict";Sme=null});import{create as Uct}from"zustand";var Ime,ch,gN=w(()=>{"use strict";sl();n4();Ime=Uct((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&&at().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=r4();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),ch=Ime.getState});import{create as $ct}from"zustand";var X_,wn,lh=w(()=>{"use strict";X_=null,wn=$ct((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}),X_!==null&&clearInterval(X_),X_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{X_!==null&&(clearInterval(X_),X_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var AN={};ce(AN,{getUIStore:()=>Ke,useUIStore:()=>wo});import{create as Gct}from"zustand";var Tme,wo,Ke,Op=w(()=>{"use strict";Tme={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},wo=Gct(t=>({...Tme,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(Tme)})),Ke=wo.getState});var dI={};ce(dI,{getInputStore:()=>Z_,useInputStore:()=>ss});import{create as Hct}from"zustand";var wme,Yct,qct,ss,Z_,Du=w(()=>{"use strict";Te();sl();Op();wme={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},Yct=100,qct=50,ss=Hct((t,e)=>({...wme,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>qct&&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=wo.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;Hn.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:[]}),Hn.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(`
|
|
@@ -4308,7 +4308,7 @@ User: ${e}`}async function V5t(t,e,r){if(t.authType==="oauth_bearer"){let o=Qa(t
|
|
|
4308
4308
|
`))):(console.log(` Connection: ${g.red("Unreachable")} (${e})`),console.log(g.gray(` The cloud could not be reached. Try again shortly.
|
|
4309
4309
|
`))),process.exitCode=1}}function d8e(){console.log(g.bold(`
|
|
4310
4310
|
aii cloud \u2014 manage your account and workspaces
|
|
4311
|
-
`)),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 mX=w(()=>{"use strict";Te();Hc();Di();HGe();MC();zGe();jGe();bJ();a8e();l8e();FC();Oi();$a();kP()});var m8e={};ce(m8e,{handleUpgrade:()=>hGt});import{execSync as pGt,execFileSync as fGt}from"node:child_process";async function hGt(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!mGt.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.
|
|
4311
|
+
`)),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 mX=w(()=>{"use strict";Te();Hc();Di();HGe();MC();zGe();jGe();bJ();a8e();l8e();FC();Oi();$a();kP()});var m8e={};ce(m8e,{handleUpgrade:()=>hGt});import{execSync as pGt,execFileSync as fGt}from"node:child_process";async function hGt(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!mGt.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.15",s=r?`${f8e}@${r}`:`${f8e}@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=fGt(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??"")}
|
|
4312
4312
|
${String(i.stderr??"")}`.trim():"";a.trim()&&console.error(a.trim()),/ETARGET|notarget/i.test(a)?console.error(`
|
|
4313
4313
|
That version is not on your npm mirror yet \u2014 freshly published versions can take a
|
|
4314
4314
|
minute or two to replicate. Wait a moment and re-run: aii upgrade`):/EACCES|EPERM|permission denied/i.test(a)?console.error(`
|
|
@@ -4337,7 +4337,7 @@ Upgrade failed.`),console.error(` Manual: npm install -g ${s}`),process.exit(1)
|
|
|
4337
4337
|
${t}
|
|
4338
4338
|
</context>
|
|
4339
4339
|
|
|
4340
|
-
${e}`:e}Om();var dD=[{name:"config",tier:ve.LOCAL},{name:"help",tier:ve.LOCAL},{name:"version",tier:ve.LOCAL},{name:"doctor",tier:ve.LOCAL},{name:"mcp",tier:ve.LOCAL},{name:"prompt",tier:ve.LOCAL},{name:"stats",tier:ve.LOCAL},{name:"history",tier:ve.LOCAL},{name:"query",tier:ve.SERVER},{name:"chat",tier:ve.SERVER},{name:"run",tier:ve.SERVER},{name:"agent",tier:ve.SERVER},{name:"loop",tier:ve.SERVER},{name:"telegram",tier:ve.SERVER},{name:"sessions",tier:ve.LOCAL},{name:"goals",tier:ve.LOCAL},{name:"install",tier:ve.LOCAL},{name:"worktree",tier:ve.LOCAL},{name:"soul",tier:ve.LOCAL},{name:"skill",tier:ve.LOCAL},{name:"plugin",tier:ve.LOCAL},{name:"persona",tier:ve.LOCAL},{name:"cloud",tier:ve.LOCAL},{name:"login",tier:ve.LOCAL},{name:"upgrade",tier:ve.LOCAL}];function set(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!==ve.LOCAL&&r.tier!==ve.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 oet=set(dD);function Uce(t){return oet.get(t)?.tier}var U6t=Object.fromEntries(dD.map(t=>[t.name,t.tier]));function $ce(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 Hce=new Set(dD.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),iet="0.25.14",aet=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"]),g_=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 cet(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(aet.has(o)){s===-1&&g_.has(o)&&r++;continue}e.push(n)}return e}var Gce=/^[a-z0-9_]{2,40}$/i;function Yce(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&g_.has(r)&&e++;continue}return r}}function uet(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&g_.has(t[e])&&e++}return-1}function det(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("=")&&g_.has(r)&&e++;continue}return!0}return!1}function pet(t){let e=Yce(t);if(e!==void 0&&e!=="agent"&&Hce.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(g_.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("-")&&Gce.test(a)&&(det(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"),Gce.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 fet(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 met(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 qce(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 het(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 get(){let t=new Fce;return t.name("aii").description("AI-powered CLI assistant").version(iet,"-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 zce(t){let e=$ce(t,g_),r=pet(e.argv),n=r.argv,s=uet(n),o=s>=0&&Yce(n)===void 0?n.slice(0,s):n,i=get();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&Hce.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof X$&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof X$&&m.code==="commander.help"))throw m;l=cet(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:fet(u.maxTurns),maxBudgetUsd:het(u.maxBudgetUsd),reconnectWindow:met(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;Z$()&&(p=await Qce()),(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}}fD();Om();gD();function jce(t){let e=Uce(t.command)??ve.SERVER;switch(t.command){case"config":return Aet(t);case"mcp":return _et(t);case"prompt":return Eet(t);case"stats":return yet(t);case"history":return Cet(t);case"doctor":return{tier:ve.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:ve.LOCAL,handler:"goals",params:{}};case"install":return{tier:ve.LOCAL,handler:"install",params:{}};case"chat":return{tier:ve.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return Iet(t);case"agent":return{tier:ve.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":{let r=[...t.subcommand?[t.subcommand]:[],...t.args??[]];return lb(r)?.sub==="status"?{tier:ve.LOCAL,handler:"loop-status",params:{}}:{tier:ve.SERVER,handler:"loop",params:{}}}case"telegram":return{tier:ve.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:ve.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:ve.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:ve.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:ve.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:ve.LOCAL,handler:"login",params:{}};case"skill":return{tier:ve.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:ve.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:ve.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:ve.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:ve.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:ve.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Aet(t){let e=t.subcommand??t.args[0]??"show";return{tier:ve.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function _et(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Eet(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function yet(t){let e=t.subcommand??t.args[0];return{tier:ve.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Cet(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var bet=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function Iet(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(bet.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:ve.SERVER,handler:"run",params:{operation:n}}}Om();Xe();IR();$a();li();Te();Om();wh();import{createInterface as ZUt}from"readline";import{spawn as e9t}from"child_process";Te();import SP from"node:process";import VQe from"node:process";import EP from"node:process";var jPt=(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);!KPt(s,o)&&n||Object.defineProperty(t,r,o)},KPt=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)},JPt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},XPt=(t,e)=>`/* Wrapped ${t}*/
|
|
4340
|
+
${e}`:e}Om();var dD=[{name:"config",tier:ve.LOCAL},{name:"help",tier:ve.LOCAL},{name:"version",tier:ve.LOCAL},{name:"doctor",tier:ve.LOCAL},{name:"mcp",tier:ve.LOCAL},{name:"prompt",tier:ve.LOCAL},{name:"stats",tier:ve.LOCAL},{name:"history",tier:ve.LOCAL},{name:"query",tier:ve.SERVER},{name:"chat",tier:ve.SERVER},{name:"run",tier:ve.SERVER},{name:"agent",tier:ve.SERVER},{name:"loop",tier:ve.SERVER},{name:"telegram",tier:ve.SERVER},{name:"sessions",tier:ve.LOCAL},{name:"goals",tier:ve.LOCAL},{name:"install",tier:ve.LOCAL},{name:"worktree",tier:ve.LOCAL},{name:"soul",tier:ve.LOCAL},{name:"skill",tier:ve.LOCAL},{name:"plugin",tier:ve.LOCAL},{name:"persona",tier:ve.LOCAL},{name:"cloud",tier:ve.LOCAL},{name:"login",tier:ve.LOCAL},{name:"upgrade",tier:ve.LOCAL}];function set(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!==ve.LOCAL&&r.tier!==ve.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 oet=set(dD);function Uce(t){return oet.get(t)?.tier}var U6t=Object.fromEntries(dD.map(t=>[t.name,t.tier]));function $ce(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 Hce=new Set(dD.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),iet="0.25.15",aet=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"]),g_=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 cet(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(aet.has(o)){s===-1&&g_.has(o)&&r++;continue}e.push(n)}return e}var Gce=/^[a-z0-9_]{2,40}$/i;function Yce(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&g_.has(r)&&e++;continue}return r}}function uet(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&g_.has(t[e])&&e++}return-1}function det(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("=")&&g_.has(r)&&e++;continue}return!0}return!1}function pet(t){let e=Yce(t);if(e!==void 0&&e!=="agent"&&Hce.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(g_.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("-")&&Gce.test(a)&&(det(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"),Gce.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 fet(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 met(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 qce(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 het(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 get(){let t=new Fce;return t.name("aii").description("AI-powered CLI assistant").version(iet,"-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 zce(t){let e=$ce(t,g_),r=pet(e.argv),n=r.argv,s=uet(n),o=s>=0&&Yce(n)===void 0?n.slice(0,s):n,i=get();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&Hce.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof X$&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof X$&&m.code==="commander.help"))throw m;l=cet(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:fet(u.maxTurns),maxBudgetUsd:het(u.maxBudgetUsd),reconnectWindow:met(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;Z$()&&(p=await Qce()),(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}}fD();Om();gD();function jce(t){let e=Uce(t.command)??ve.SERVER;switch(t.command){case"config":return Aet(t);case"mcp":return _et(t);case"prompt":return Eet(t);case"stats":return yet(t);case"history":return Cet(t);case"doctor":return{tier:ve.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:ve.LOCAL,handler:"goals",params:{}};case"install":return{tier:ve.LOCAL,handler:"install",params:{}};case"chat":return{tier:ve.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return Iet(t);case"agent":return{tier:ve.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":{let r=[...t.subcommand?[t.subcommand]:[],...t.args??[]];return lb(r)?.sub==="status"?{tier:ve.LOCAL,handler:"loop-status",params:{}}:{tier:ve.SERVER,handler:"loop",params:{}}}case"telegram":return{tier:ve.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:ve.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:ve.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:ve.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:ve.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:ve.LOCAL,handler:"login",params:{}};case"skill":return{tier:ve.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:ve.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:ve.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:ve.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:ve.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:ve.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function Aet(t){let e=t.subcommand??t.args[0]??"show";return{tier:ve.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function _et(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function Eet(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function yet(t){let e=t.subcommand??t.args[0];return{tier:ve.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function Cet(t){let e=t.subcommand??t.args[0]??"list";return{tier:ve.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var bet=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function Iet(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(bet.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:ve.SERVER,handler:"run",params:{operation:n}}}Om();Xe();IR();$a();li();Te();Om();wh();import{createInterface as ZUt}from"readline";import{spawn as e9t}from"child_process";Te();import SP from"node:process";import VQe from"node:process";import EP from"node:process";var jPt=(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);!KPt(s,o)&&n||Object.defineProperty(t,r,o)},KPt=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)},JPt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},XPt=(t,e)=>`/* Wrapped ${t}*/
|
|
4341
4341
|
${e}`,ZPt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),eFt=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),tFt=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=XPt.bind(null,n,e.toString());Object.defineProperty(s,"name",eFt);let{writable:o,enumerable:i,configurable:a}=ZPt;Object.defineProperty(t,"toString",{value:s,writable:o,enumerable:i,configurable:a})};function m7(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let s of Reflect.ownKeys(e))jPt(t,e,s,r);return JPt(t,e),tFt(t,e,n),t}var gP=new WeakMap,HQe=(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(gP.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 m7(o,t),gP.set(o,n),o};HQe.callCount=t=>{if(!gP.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return gP.get(t)};var YQe=HQe;var Pg=[];Pg.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Pg.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Pg.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var AP=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",h7=Symbol.for("signal-exit emitter"),g7=globalThis,rFt=Object.defineProperty.bind(Object),A7=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(g7[h7])return g7[h7];rFt(g7,h7,{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}},_P=class{},nFt=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),_7=class extends _P{onExit(){return()=>{}}load(){}unload(){}},E7=class extends _P{#e=y7.platform==="win32"?"SIGINT":"SIGHUP";#t=new A7;#r;#s;#o;#n={};#i=!1;constructor(e){super(),this.#r=e,this.#n={};for(let r of Pg)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(!AP(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 Pg)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,Pg.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 AP(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"&&AP(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)}},y7=globalThis.process,{onExit:qQe,load:ZEr,unload:eyr}=nFt(AP(y7)?new E7(y7):new _7);var zQe=EP.stderr.isTTY?EP.stderr:EP.stdout.isTTY?EP.stdout:void 0,sFt=zQe?YQe(()=>{qQe(()=>{zQe.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},WQe=sFt;var yP=!1,mC={};mC.show=(t=VQe.stderr)=>{t.isTTY&&(yP=!1,t.write("\x1B[?25h"))};mC.hide=(t=VQe.stderr)=>{t.isTTY&&(WQe(),yP=!0,t.write("\x1B[?25l"))};mC.toggle=(t,e)=>{t!==void 0&&(yP=t),yP?mC.show(e):mC.hide(e)};var C7=mC;var $w=er(S7(),1);Te();import Ec from"node:process";function b7(){return Ec.platform!=="win32"?Ec.env.TERM!=="linux":!!Ec.env.CI||!!Ec.env.WT_SESSION||!!Ec.env.TERMINUS_SUBLIME||Ec.env.ConEmuTask==="{cmd::Cmder}"||Ec.env.TERM_PROGRAM==="Terminus-Sublime"||Ec.env.TERM_PROGRAM==="vscode"||Ec.env.TERM==="xterm-256color"||Ec.env.TERM==="alacritty"||Ec.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var iFt={info:g.blue("\u2139"),success:g.green("\u2714"),warning:g.yellow("\u26A0"),error:g.red("\u2716")},aFt={info:g.blue("i"),success:g.green("\u221A"),warning:g.yellow("\u203C"),error:g.red("\xD7")},cFt=b7()?iFt:aFt,Uw=cFt;_N();var lFt=uh();function I7(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(lFt,"")}o4();function T7({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import XQe from"node:process";function w7(){let{env:t}=XQe,{TERM:e,TERM_PROGRAM:r}=t;return XQe.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 Ll from"node:process";var uFt=3,k7=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(){Ll.platform==="win32"||!Ll.stdin.isTTY||(Ll.stdin.setRawMode(!0),Ll.stdin.on("data",this.#s),Ll.stdin.resume())}#r(){Ll.stdin.isTTY&&(Ll.stdin.off("data",this.#s),Ll.stdin.pause(),Ll.stdin.setRawMode(!1))}#s(e){e[0]===uFt&&Ll.emit("SIGINT")}},dFt=new k7,v7=dFt;var pFt=er(S7(),1),D7=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:SP.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:T7({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,SP.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(!w7())this.#i=$w.default.line;else if(e===void 0)this.#i=$w.default.dots;else if(e!=="default"&&$w.default[e])this.#i=$w.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 I7(s).split(`
|
|
4342
4342
|
`))this.#r+=Math.max(1,Math.ceil(eE(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&&C7.hide(this.#a),this.#n.discardStdin&&SP.stdin.isTTY&&(this.#t=!0,v7.start()),this.render(),this.#l=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#a.write(`- ${this.text}
|
|
4343
4343
|
`),this)}stop(){return this.#u?(clearInterval(this.#l),this.#l=void 0,this.#s=0,this.clear(),this.#n.hideCursor&&C7.show(this.#a),this.#n.discardStdin&&SP.stdin.isTTY&&this.#t&&(v7.stop(),this.#t=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Uw.success,text:e})}fail(e){return this.stopAndPersist({symbol:Uw.error,text:e})}warn(e){return this.stopAndPersist({symbol:Uw.warning,text:e})}info(e){return this.stopAndPersist({symbol:Uw.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+`
|
|
@@ -4347,7 +4347,7 @@ ${e}`,ZPt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),eFt=Obj
|
|
|
4347
4347
|
`+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(`
|
|
4348
4348
|
`)}formatConfig(e){let r=[];r.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,P.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(`
|
|
4349
4349
|
`)}formatHealthCheck(e,r){let n=[],s=r?`Aii Doctor v${r}`:"Aii Doctor";n.push(this.color(s,P.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(`
|
|
4350
|
-
`)}};function $o(t={}){return new B7(t)}Xs();yi();Te();wh();import*as s2e from"readline";Xs();is();yi();Wc();import*as Ea from"fs";import*as IP from"path";import*as ZQe from"os";var Hw=IP.join(ZQe.homedir(),".aii","conversations"),M7=IP.join(Hw,"current.json");function TP(){Ea.existsSync(Hw)||Ea.mkdirSync(Hw,{recursive:!0,mode:448});try{Ea.chmodSync(Hw,448)}catch{}}function hFt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gFt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function e2e(t){return IP.join(Hw,`${t}.json`)}function t2e(){TP();try{if(Ea.existsSync(M7)){let t=Ea.readFileSync(M7,"utf-8"),e=JSON.parse(t),r=e2e(e.id);if(Ea.existsSync(r)){let n=Ea.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return r2e()}function r2e(){TP();let t={id:hFt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Yw(t),AFt(t.id),t}function Yw(t){if(TP(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=gFt(r.content))}t.updatedAt=Date.now();let e=e2e(t.id);xi(e,JSON.stringify(t,null,2))}function AFt(t){TP(),xi(M7,JSON.stringify({id:t}))}function n2e(){return r2e()}gg();var _Ft="0.25.
|
|
4350
|
+
`)}};function $o(t={}){return new B7(t)}Xs();yi();Te();wh();import*as s2e from"readline";Xs();is();yi();Wc();import*as Ea from"fs";import*as IP from"path";import*as ZQe from"os";var Hw=IP.join(ZQe.homedir(),".aii","conversations"),M7=IP.join(Hw,"current.json");function TP(){Ea.existsSync(Hw)||Ea.mkdirSync(Hw,{recursive:!0,mode:448});try{Ea.chmodSync(Hw,448)}catch{}}function hFt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gFt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function e2e(t){return IP.join(Hw,`${t}.json`)}function t2e(){TP();try{if(Ea.existsSync(M7)){let t=Ea.readFileSync(M7,"utf-8"),e=JSON.parse(t),r=e2e(e.id);if(Ea.existsSync(r)){let n=Ea.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return r2e()}function r2e(){TP();let t={id:hFt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Yw(t),AFt(t.id),t}function Yw(t){if(TP(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=gFt(r.content))}t.updatedAt=Date.now();let e=e2e(t.id);xi(e,JSON.stringify(t,null,2))}function AFt(t){TP(),xi(M7,JSON.stringify({id:t}))}function n2e(){return r2e()}gg();var _Ft="0.25.15",L7=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=t2e(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=$o({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()}),Yw(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(`
|
|
4351
4351
|
\u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(g.red(`
|
|
4352
4352
|
\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(),Yw(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=s2e.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(`
|
|
4353
4353
|
`).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 Zn(n.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",i=On(this.parsed.flags.model??""),a=gs(i||void 0,r.llm.provider),c=tn(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 xr(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let p=Pl(!this.parsed.flags.noAnimations);p.start("");let f=Fl({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:$s.getInstance().getSoulName()},A=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,_=new vo({url:A}),E="",y=!1;try{let S=await _.executeRequest(h,{onToken:T=>{E+=T,y=!0,f.onToken(T)}});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()}),Yw(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=n2e(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
|
|
@@ -4523,10 +4523,10 @@ ${r.yellow("CONFIG FILE:")}
|
|
|
4523
4523
|
.aii/settings.json Project config (committed, restrict-only)
|
|
4524
4524
|
.aii/settings.local.json Your local overrides (gitignored)
|
|
4525
4525
|
${r.gray("Skip both for a session with: aii --no-project-config")}
|
|
4526
|
-
`)}import*as zl from"fs";Br();aD();async function J5e(t,e){let r=$o({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 v9t(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(zl.existsSync(c))try{let f=zl.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(oD())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)"});oD()?iD()?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 D9t();n.push(...d),console.log(r.formatHealthCheck(n,ah)),n.some(f=>f.status==="error")&&process.exit(1)}async function v9t(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 D9t(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(fi(),XN)),r=`${e()}/skills`;if(!zl.existsSync(r))return t;let n=zl.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;zl.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(()=>(ir(),dr));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}`;zl.existsSync(c)&&zl.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}Te();Br();import{execSync as OJ}from"node:child_process";var oQ="@aiiware/aii";async function X5e(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.
|
|
4527
|
-
`),await R9t(r)}async function R9t(t){let e="0.25.
|
|
4526
|
+
`)}import*as zl from"fs";Br();aD();async function J5e(t,e){let r=$o({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 v9t(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(zl.existsSync(c))try{let f=zl.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(oD())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)"});oD()?iD()?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 D9t();n.push(...d),console.log(r.formatHealthCheck(n,ah)),n.some(f=>f.status==="error")&&process.exit(1)}async function v9t(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 D9t(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(fi(),XN)),r=`${e()}/skills`;if(!zl.existsSync(r))return t;let n=zl.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;zl.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(()=>(ir(),dr));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}`;zl.existsSync(c)&&zl.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}Te();Br();import{execSync as OJ}from"node:child_process";var oQ="@aiiware/aii";async function X5e(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.15";console.log(""),console.log(P.logo(" Install")),console.log(""),console.log(` Current version: ${P.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
|
|
4527
|
+
`),await R9t(r)}async function R9t(t){let e="0.25.15",r=t&&t!=="latest"?t:"";if(console.log(""),r){console.log(`\u{1FABC} Installing Aii CLI v${r}...`),console.log("");try{OJ(`npm install -g ${oQ}@${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4528
4528
|
\u274C Failed to install v${r}`),console.error(` Try manually: npm install -g ${oQ}@${r}`),process.exit(1)}}else{console.log("\u{1FABC} Updating Aii CLI to latest..."),console.log(` Current version: ${e}`),console.log("");try{OJ(`npm install -g ${oQ}@latest`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4529
|
-
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${oQ}@latest`),process.exit(1)}}try{let n=OJ("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.")}}Te();var Z5e="0.25.
|
|
4529
|
+
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${oQ}@latest`),process.exit(1)}}try{let n=OJ("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.")}}Te();var Z5e="0.25.15";function xJ(t){let r=!t.flags.noColors?g:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
|
|
4530
4530
|
${r.cyan("AII")} - AI-powered CLI assistant v${Z5e}
|
|
4531
4531
|
|
|
4532
4532
|
${r.yellow("USAGE:")}
|
package/bin/aii-host-worker.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* @aiiware/aii v0.25.
|
|
3
|
+
* @aiiware/aii v0.25.15
|
|
4
4
|
*
|
|
5
5
|
* AI-powered CLI assistant for terminal productivity
|
|
6
6
|
*
|
|
@@ -918,7 +918,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),F=M,W=q);let pe={code:
|
|
|
918
918
|
shutting down\u2026 (Ctrl+C again to force)
|
|
919
919
|
`)}catch{}},300);e.unref?.(),_ge().finally(()=>{clearTimeout(e),process.exit(LE)})}function Trt(){let e=process.env.AII_TRACE?.trim().toLowerCase();if(e){if(e==="0"||e==="false"||e==="off"||e==="no")return!1;if(e==="1"||e==="true"||e==="on"||e==="yes")return!0}try{if(Ye().getConfig()?.trace?.enabled===!1)return!1}catch{}return!0}function yge(t,e={}){if(!Trt())return null;try{let r=new OU(t,e);for(let n of QE)n.deref()||QE.delete(n);return r.registerSelf(QE),Age||(Age=!0,ME.registerFinal("trace-writer-flush",()=>Ege())),r}catch{return null}}var yrt,RU,NU,Srt,Crt,mge,brt,QE,H0,Age,Irt,PE,LE,vU,OU,BU=I(()=>{"use strict";l_();uge();tr();pge();tg();tg();yrt=10*1024*1024,RU=4096,NU=16*1024,Srt=8*1024,Crt=1e3,mge="[withheld: sensitive path]";brt=["content","new_string","old_string","text","replacement","data"];QE=new Set,H0=new Set,Age=!1,Irt=250;PE=null,LE=0,vU=!1;OU=class{baseDir;maxFileBytes;redactorFactory;isSensitive;clock;sessionId=null;cwd=process.cwd();turnId=null;redact=e=>e;bytesWritten=0;inert=!1;opened=!1;textBuffer="";textTimer=null;withheldCallIds=new Set;knownCallIds=new Set;pendingSensitive=0;chain=Promise.resolve();emitterRef=null;handlers=[];selfRef=null;registry=null;constructor(e,r={}){this.baseDir=r.baseDir??Qs(),this.maxFileBytes=r.maxFileBytes??yrt,this.redactorFactory=r.redactor??(()=>cge()),this.isSensitive=r.isSensitivePath??lge,this.clock=r.clock??Date.now,this.subscribe(e)}subscribe(e){this.emitterRef=e;let r=(n,i)=>{this.handlers.push([n,i]),e.on(n,i)};r("turnStart",(n,i,s,o,a,c)=>{if(typeof s=="string"&&s.startsWith("subagent_")){this.inert=!0;return}this.sessionId&&this.sessionId!==s&&(this.opened=!1,this.bytesWritten=0,this.inert=!1),this.sessionId=s,this.cwd=c||process.cwd(),this.turnId=n,this.redact=this.redactorFactory(),this.write({type:"turn_start",turn_id:n,session_id:s,provider:o,model:a,cwd:c,input:yl(this.redact(i??""),NU)})}),r("turnEnd",(n,i,s,o)=>{this.flushText(),this.write({type:"turn_end",turn_id:n,status:i,duration_ms:s,final_answer:o===null?null:yl(this.redact(o),NU)}),this.turnId=null}),r("stateChange",n=>{this.flushText(),this.write({type:"state",state:n})}),r("paused",()=>{this.flushText(),this.write({type:"paused"})}),r("token",n=>{if(this.textBuffer+=n,Buffer.byteLength(this.textBuffer,"utf8")>=Srt){this.flushText();return}this.textTimer||(this.textTimer=setTimeout(()=>this.flushText(),Crt),this.textTimer.unref?.())}),r("toolCall",(n,i,s)=>{this.flushText();let o=this.argsTouchSensitivePath(i);o&&(s&&this.withheldCallIds.add(s),this.pendingSensitive++),this.knownCallIds.add(s??""),this.write({type:"tool_call",call_id:s??null,name:n,args:this.serializeArgs(i,o)})}),r("toolResultCompleted",(n,i,s,o,a)=>{this.flushText(),this.redact=this.redactorFactory();let c=a??n,l=c?this.knownCallIds.has(c):!1,u=(c?this.withheldCallIds.has(c):!1)||!l&&this.pendingSensitive>0;this.write({type:"tool_result",call_id:c??null,local_call_id:n??null,name:i,success:s?.success??!1,duration_ms:typeof o=="number"?o:null,output:u?mge:yl(this.redact(s?.output??""),RU),error:s?.error?yl(this.redact(s.error),RU):void 0}),c&&this.withheldCallIds.delete(c)&&(this.pendingSensitive=Math.max(0,this.pendingSensitive-1)),c&&this.knownCallIds.delete(c)}),r("iterationUsage",(n,i,s,o)=>{this.write({type:"usage",scope:"iteration",iteration:n,input_tokens:i,output_tokens:s,cost_usd:o})}),r("usage",(n,i,s)=>{this.write({type:"usage",scope:"turn",input_tokens:n,output_tokens:i,cost_usd:s})}),r("connEvent",n=>{this.flushText(),n.errorClass!==void 0&&(this.redact=this.redactorFactory());let i={lost:"conn_lost",retry:"conn_retry",restored:"conn_restored",abandoned:"window_abandoned"}[n.kind];i&&this.write({type:i,...n.errorClass!==void 0?{error_class:yl(this.redact(gge(n.errorClass)),200)}:{},...n.attempt!==void 0?{attempt:n.attempt}:{},...n.elapsedMs!==void 0?{elapsed_ms:n.elapsedMs}:{},...n.outageMs!==void 0?{outage_ms:n.outageMs}:{},...n.reason!==void 0?{reason:n.reason}:{},...n.spentMs!==void 0?{spent_ms:n.spentMs}:{},...n.madeProgress!==void 0?{made_progress:n.madeProgress}:{}})}),r("loopEnd",n=>{this.flushText(),this.write({type:"loop_end",status:n.status,exit_reason:yl(this.redact(gge(n.exitReason)),100),iterations:n.iterations,duration_ms:n.durationMs})})}argsTouchSensitivePath(e){if(!e)return!1;for(let[r,n]of Object.entries(e))if(typeof n=="string"&&/path|file|dir/i.test(r)&&this.isSensitive(n,this.cwd))return!0;return!1}serializeArgs(e,r){if(!e)return"{}";let n=(o,a)=>{if(r&&a!==void 0&&brt.includes(a))return mge;if(typeof o=="string")return this.redact(o);if(Array.isArray(o))return o.map(c=>n(c));if(o&&typeof o=="object"){let c={};for(let[l,u]of Object.entries(o))c[l]=n(u,l);return c}return o},i=n(e),s;try{s=JSON.stringify(i)??"{}"}catch{s='"[unserializable args]"'}return yl(this.redact(s),RU)}flushText(){if(this.textTimer&&(clearTimeout(this.textTimer),this.textTimer=null),!this.textBuffer)return;let e=this.textBuffer;this.textBuffer="",this.write({type:"text",content:yl(this.redact(e),NU)})}write(e){if(!(this.inert||!this.sessionId))try{this.writeUnsafe(e)}catch{this.inert=!0}}writeUnsafe(e){let r=JSON.stringify({ts:new Date(this.clock()).toISOString(),...this.turnId?{turn_id:this.turnId}:{},...e})+`
|
|
920
920
|
`,n=Buffer.byteLength(r,"utf8");if(this.bytesWritten+n>this.maxFileBytes){this.inert=!0;let i=JSON.stringify({ts:new Date(this.clock()).toISOString(),type:"truncated",reason:"size-cap"})+`
|
|
921
|
-
`;this.enqueue(i);return}this.bytesWritten+=n,this.enqueue(r)}enqueue(e){let r=this.sessionId;r&&(this.chain=this.chain.then(async()=>{try{let n=JM(r,this.baseDir);if(!this.opened){if(await Art(hge(n),{recursive:!0,mode:448}),await fge(hge(n),448).catch(()=>{}),Ert(n)){await fge(n,384);try{this.bytesWritten+=(await _rt(n)).size}catch{}}this.opened=!0}await grt(n,e,{mode:384})}catch{this.inert=!0}}))}async flushNow(){this.flushText(),await this.chain}closeOpenTurnAbandoned(){this.turnId&&(this.flushText(),this.write({type:"turn_end",turn_id:this.turnId,status:"abandoned",duration_ms:null,final_answer:null}),this.turnId=null)}detach(){for(let[r,n]of this.handlers)this.emitterRef?.removeListener(r,n);this.handlers=[],this.flushText(),this.textTimer&&(clearTimeout(this.textTimer),this.textTimer=null),this.inert=!0;let e=this.chain;H0.add(e),Promise.resolve(e).catch(()=>{}).finally(()=>{H0.delete(e)}),this.selfRef&&(this.registry?.delete(this.selfRef),this.selfRef=null,this.registry=null)}registerSelf(e){this.selfRef=new WeakRef(this),this.registry=e,e.add(this.selfRef)}}});import{resolve as wrt}from"path";function krt(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",i=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||i||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function UE(){return xU===null&&(xU=krt()),xU}function Rrt(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Cge(){return Sge||!UE()?"":(Sge=!0,` (${Rrt()}+Click to open)`)}function Nrt(t,e){return UE()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function bge(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",i=t;n&&t.startsWith(n)&&(i="~"+t.slice(n.length));let s=r??(e?`${i}:${e}`:i);if(!UE())return vt().filePath(s);let o=vt().accent(s),c=`file://${wrt(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Nrt(o,c)}var xU,Sge,Ige=I(()=>{"use strict";Dn();xU=null,Sge=!1});var Rge={};nt(Rge,{VERSION:()=>vrt,colors:()=>Qe,formatCode:()=>Urt,formatPath:()=>kge,getActionIndicator:()=>Frt,padEndAnsi:()=>Hrt,printDivider:()=>wge,printError:()=>Qrt,printExitSummary:()=>zrt,printHeader:()=>Prt,printSuccess:()=>Mrt,printToolResultCompact:()=>Uh,printWarning:()=>Lrt,shortenPath:()=>$rt});function Drt(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 xrt(t){return Brt.test(t)}function Uh(t,e,r=!0,n,i=console.log,s=!0,o=0,a=process.stdout){let c=r?Qe.success("\u25CF"):Qe.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=Drt(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=Fs(d),f=Dr(t)+6+o,h=Math.max(Ort,(a.columns||80)-f),g=Dr(p)>h?bo(p,h-1).replace(/\u200D+$/,"")+"\u2026":p,A=a===process.stdout?!0:a.isTTY===!0,_=u&&!xrt(e)&&A;if(_){let b=e.match(/:(\d+)$/),T=b?parseInt(b[1],10):void 0,k=b?e.replace(/:(\d+)$/,""):e;g=kge(k,T,g)}i(`${c} ${O.bold(t)}(${g})`);let y=s&&_?Qe.dim(Cge()):"",C=s&&!y&&!Tge?Qe.dim(" (ctrl+o to expand)"):"";if(C&&(Tge=!0),n){let b=r?Qe.dim:Qe.error;i(b(`\u2514 ${n}`)+y+C)}else{let b=r?"(No content)":"(Error)",T=r?Qe.dim:Qe.error;i(T(`\u2514 ${b}`)+y+C)}}function Mrt(t){console.log(Qe.success("\u2713 ")+t)}function Lrt(t){console.log(Qe.warning("\u26A0 ")+t)}function Qrt(t){console.log(Qe.error("\u2717 ")+t)}function wge(t=60){console.log(Qe.dim("\u2500".repeat(t)))}function Prt(t){console.log(Qe.logo(t)),wge(t.length)}function Frt(t){return Qe.thinking(`[${t}]`)}function kge(t,e,r){if(UE())return bge(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",i=t;return n&&t.startsWith(n)&&(i="~"+t.slice(n.length)),e&&(i+=`:${e}`),Qe.filePath(r??i)}function Urt(t){return Qe.code(t)}function Grt(){return process.stdout.columns||80}function $rt(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let i=n.split("/").filter(o=>o.length>0);if(i.length>=2){let o=i.slice(-2).join("/");if(o.length<=e-4)return".../"+o}return".../"+(i[i.length-1]||i[i.length-2])}function Yrt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Hrt(t,e){let r=Yrt(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function qrt(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 MU(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function zrt(t){let e=Grt(),r=Math.min(e-2,76),n=r-4,i=(g,A)=>{let _=g.replace(/\x1b\[[0-9;]*m/g,"").length;return g+" ".repeat(Math.max(0,A-_))},s=g=>Qe.border("\u2502")+" "+i(g,n)+" "+Qe.border("\u2502"),o=(g,A,_,y)=>{let C=Math.floor(n/2),b=Qe.dim(g.padEnd(15))+A,T=Qe.dim(_.padEnd(15))+y;return s(i(b,C)+T)},a=qrt(t.durationSeconds),c=MU(t.tokensIn),l=MU(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(Qe.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(s(Qe.logo("Session complete. \u{1FABC}"))),console.log(Qe.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(s(Qe.logo("Session Summary"))),console.log(s(Qe.dim("\u2500".repeat(15)))),console.log(o("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(o("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(s("")),console.log(s(Qe.logo("Token Usage"))),console.log(s(Qe.dim("\u2500".repeat(11)))),console.log(o("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let g=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(s(Qe.dim("Cached".padEnd(15))+`${MU(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?Qe.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(s(Qe.dim("Cost".padEnd(15))+u+h)),console.log(s(""));let m=(g,A)=>g.length>A?`${g.slice(0,Math.max(0,A-1))}\u2026`:g;if(t.goalLine){let g=t.goalLine.replace(/^Goal:\s*/,"");console.log(s(Qe.dim("Goal: ")+m(g,n-6)))}t.goalResumeLine&&console.log(s(Qe.dim(m(` ${t.goalResumeLine}`,n)))),console.log(s(Qe.dim("Model: ")+Qe.model(d))),console.log(Qe.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var vrt,Qe,Ort,Brt,Tge,GE=I(()=>{"use strict";ys();Ige();Dn();Bu();xf();vrt="0.25.
|
|
921
|
+
`;this.enqueue(i);return}this.bytesWritten+=n,this.enqueue(r)}enqueue(e){let r=this.sessionId;r&&(this.chain=this.chain.then(async()=>{try{let n=JM(r,this.baseDir);if(!this.opened){if(await Art(hge(n),{recursive:!0,mode:448}),await fge(hge(n),448).catch(()=>{}),Ert(n)){await fge(n,384);try{this.bytesWritten+=(await _rt(n)).size}catch{}}this.opened=!0}await grt(n,e,{mode:384})}catch{this.inert=!0}}))}async flushNow(){this.flushText(),await this.chain}closeOpenTurnAbandoned(){this.turnId&&(this.flushText(),this.write({type:"turn_end",turn_id:this.turnId,status:"abandoned",duration_ms:null,final_answer:null}),this.turnId=null)}detach(){for(let[r,n]of this.handlers)this.emitterRef?.removeListener(r,n);this.handlers=[],this.flushText(),this.textTimer&&(clearTimeout(this.textTimer),this.textTimer=null),this.inert=!0;let e=this.chain;H0.add(e),Promise.resolve(e).catch(()=>{}).finally(()=>{H0.delete(e)}),this.selfRef&&(this.registry?.delete(this.selfRef),this.selfRef=null,this.registry=null)}registerSelf(e){this.selfRef=new WeakRef(this),this.registry=e,e.add(this.selfRef)}}});import{resolve as wrt}from"path";function krt(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",i=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||i||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function UE(){return xU===null&&(xU=krt()),xU}function Rrt(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Cge(){return Sge||!UE()?"":(Sge=!0,` (${Rrt()}+Click to open)`)}function Nrt(t,e){return UE()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function bge(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",i=t;n&&t.startsWith(n)&&(i="~"+t.slice(n.length));let s=r??(e?`${i}:${e}`:i);if(!UE())return vt().filePath(s);let o=vt().accent(s),c=`file://${wrt(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Nrt(o,c)}var xU,Sge,Ige=I(()=>{"use strict";Dn();xU=null,Sge=!1});var Rge={};nt(Rge,{VERSION:()=>vrt,colors:()=>Qe,formatCode:()=>Urt,formatPath:()=>kge,getActionIndicator:()=>Frt,padEndAnsi:()=>Hrt,printDivider:()=>wge,printError:()=>Qrt,printExitSummary:()=>zrt,printHeader:()=>Prt,printSuccess:()=>Mrt,printToolResultCompact:()=>Uh,printWarning:()=>Lrt,shortenPath:()=>$rt});function Drt(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 xrt(t){return Brt.test(t)}function Uh(t,e,r=!0,n,i=console.log,s=!0,o=0,a=process.stdout){let c=r?Qe.success("\u25CF"):Qe.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=Drt(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=Fs(d),f=Dr(t)+6+o,h=Math.max(Ort,(a.columns||80)-f),g=Dr(p)>h?bo(p,h-1).replace(/\u200D+$/,"")+"\u2026":p,A=a===process.stdout?!0:a.isTTY===!0,_=u&&!xrt(e)&&A;if(_){let b=e.match(/:(\d+)$/),T=b?parseInt(b[1],10):void 0,k=b?e.replace(/:(\d+)$/,""):e;g=kge(k,T,g)}i(`${c} ${O.bold(t)}(${g})`);let y=s&&_?Qe.dim(Cge()):"",C=s&&!y&&!Tge?Qe.dim(" (ctrl+o to expand)"):"";if(C&&(Tge=!0),n){let b=r?Qe.dim:Qe.error;i(b(`\u2514 ${n}`)+y+C)}else{let b=r?"(No content)":"(Error)",T=r?Qe.dim:Qe.error;i(T(`\u2514 ${b}`)+y+C)}}function Mrt(t){console.log(Qe.success("\u2713 ")+t)}function Lrt(t){console.log(Qe.warning("\u26A0 ")+t)}function Qrt(t){console.log(Qe.error("\u2717 ")+t)}function wge(t=60){console.log(Qe.dim("\u2500".repeat(t)))}function Prt(t){console.log(Qe.logo(t)),wge(t.length)}function Frt(t){return Qe.thinking(`[${t}]`)}function kge(t,e,r){if(UE())return bge(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",i=t;return n&&t.startsWith(n)&&(i="~"+t.slice(n.length)),e&&(i+=`:${e}`),Qe.filePath(r??i)}function Urt(t){return Qe.code(t)}function Grt(){return process.stdout.columns||80}function $rt(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let i=n.split("/").filter(o=>o.length>0);if(i.length>=2){let o=i.slice(-2).join("/");if(o.length<=e-4)return".../"+o}return".../"+(i[i.length-1]||i[i.length-2])}function Yrt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function Hrt(t,e){let r=Yrt(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function qrt(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 MU(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function zrt(t){let e=Grt(),r=Math.min(e-2,76),n=r-4,i=(g,A)=>{let _=g.replace(/\x1b\[[0-9;]*m/g,"").length;return g+" ".repeat(Math.max(0,A-_))},s=g=>Qe.border("\u2502")+" "+i(g,n)+" "+Qe.border("\u2502"),o=(g,A,_,y)=>{let C=Math.floor(n/2),b=Qe.dim(g.padEnd(15))+A,T=Qe.dim(_.padEnd(15))+y;return s(i(b,C)+T)},a=qrt(t.durationSeconds),c=MU(t.tokensIn),l=MU(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(Qe.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(s(Qe.logo("Session complete. \u{1FABC}"))),console.log(Qe.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(s(Qe.logo("Session Summary"))),console.log(s(Qe.dim("\u2500".repeat(15)))),console.log(o("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(o("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(s("")),console.log(s(Qe.logo("Token Usage"))),console.log(s(Qe.dim("\u2500".repeat(11)))),console.log(o("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let g=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(s(Qe.dim("Cached".padEnd(15))+`${MU(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?Qe.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(s(Qe.dim("Cost".padEnd(15))+u+h)),console.log(s(""));let m=(g,A)=>g.length>A?`${g.slice(0,Math.max(0,A-1))}\u2026`:g;if(t.goalLine){let g=t.goalLine.replace(/^Goal:\s*/,"");console.log(s(Qe.dim("Goal: ")+m(g,n-6)))}t.goalResumeLine&&console.log(s(Qe.dim(m(` ${t.goalResumeLine}`,n)))),console.log(s(Qe.dim("Model: ")+Qe.model(d))),console.log(Qe.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var vrt,Qe,Ort,Brt,Tge,GE=I(()=>{"use strict";ys();Ige();Dn();Bu();xf();vrt="0.25.15",Qe={get logo(){return vt().accent.bold},get prompt(){return vt().accent.bold},get model(){return vt().accent},get success(){return vt().success},get warning(){return vt().warning},get error(){return vt().error},get thinking(){return vt().dim},get filePath(){return vt().filePath},get code(){return vt().code},get muted(){return vt().muted},get dim(){return vt().dim},get safe(){return vt().success},get risky(){return vt().warning},get destructive(){return vt().error},get border(){return vt().accent},get bannerBorder(){return vt().accent}};Ort=24,Brt=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Tge=!1});function vge(){Nge=Date.now()}function Dge(){return Nge}var Nge,LU=I(()=>{"use strict";Nge=Date.now()});function Oge(t){if(t==="\r")return!0;if(t.length===1){let e=t.charCodeAt(0);return e>=32&&e<=126}return!1}var Bge=I(()=>{"use strict"});function xge(t,e){return t==="\x1B"?e?null:"esc":t===""?e?null:"ctrl_c":!e&&Oge(t)?"typed":null}var Mge=I(()=>{"use strict";Bge()});function Lge(t){for(let e of Wrt)if(t===e||t.startsWith(e+" "))return{prefix:e,noteText:t.slice(e.length).trim()};return null}var Wrt,Qge=I(()=>{"use strict";Wrt=["/note","/inject","/now"]});function Pge(t){let{permanentContent:e,frozenCount:r,showWelcome:n,headerKey:i,staticEpoch:s}=t,o=r!==null?e.slice(0,r):e;return[...n&&s===0?[{id:`__header__:welcome:${i}`,type:"welcome",line:""},{id:`__header__:spacer:${i}`,type:"spacer",line:""}]:[],...o.map(a=>({id:a.id,type:"content",line:a.line}))]}var Fge=I(()=>{"use strict"});import{useEffect as Uge}from"react";function Gge(){let t=ss(i=>i.peekOpen),e=ss(i=>i.peekIndex),r=ss(i=>i.results),n=ri(i=>i.renderEpoch);return Uge(()=>{if(!xE())return;let i=t&&e>=0?r[e]:void 0;t&&i?QU(Xee(i,e,r.length,process.stdout.rows||24,process.stdout.columns||80)):q0()},[t,e,r,n]),Uge(()=>()=>q0(),[]),null}var $ge=I(()=>{"use strict";Bh();U0();_d();rw()});function Vrt(){return process.stdin.listenerCount("data")}function $E(t){if(!process.env.AII_DEBUG&&!process.env.AII_LOOP_DEBUG)return;let e=Vrt();e>1&&console.error(`[input] WARNING: ${e} stdin 'data' listeners live (${t}) \u2014 MF-1 double-listener class`)}var Yge=I(()=>{"use strict"});var Jge={};nt(Jge,{App:()=>jge,DialogKeyHandler:()=>Wge,FeedbackKeyHandler:()=>Vge,QuestionDialogKeyHandler:()=>Kge,default:()=>tnt});import{jsx as qr,jsxs as PU,Fragment as Krt}from"react/jsx-runtime";import jrt,{useEffect as Cd,useCallback as Gh,useState as Xa,useRef as rn,useMemo as Hge}from"react";import{Box as $h,Text as FU,Static as Jrt}from"ink";import{useShallow as Sd}from"zustand/react/shallow";function Xrt({onInterrupt:t}){let e=rn(t);return e.current=t,Cd(()=>{if(!process.stdin.isTTY)return;process.stdin.resume();let r=n=>{vge();let i=n.toString();if(i===""){Ln.getState().dropRemote();return}if(En.getState().active){let d=wo().loopMode,p=xge(i,d);if(p&&En.getState().release(p),i==="\x1B"&&!d)return}let o=b0(),a=()=>{let d=Nh().getText();d.startsWith("/")&&!d.includes(`
|
|
922
922
|
`)&&!d.includes(" ")?(o.isVisible||o.show(),o.setFilter(d)):o.isVisible&&o.hide()},c=()=>{let d=o.getSelected();if(!d)return!1;let p=Nh();p.clear();for(let f of`/${d.name} `)p.insertChar(f);return o.hide(),!0};if(i==="\x1B"){if(o.isVisible){o.hide();return}e.current();return}if(i===""){FE(0);return}if(i===""){let d=md();if(d.peekOpen){d.closePeek();return}let p=Al();p.nodes.length>0||p.transcripts.size>0?p.toggleExpanded():d.togglePeek();return}let l=md();if(l.peekOpen){if(i==="\x1B[A"){l.navigatePeek("prev");return}if(i==="\x1B[B"){l.navigatePeek("next");return}}let u=Nh();if(i===" "){o.isVisible&&c();return}if(i==="\r"){if(o.isVisible){c();return}let d=u.getText().trim();if(!d)return;let p=wo().loopMode,f=Lge(d);if(f){let h=f.noteText;if(!h){Bo().showToast(Qe.dim(`\u25C6 ${f.prefix} requires a message (usage: ${f.prefix} <text>)`)),u.clear();return}if(!p){let y=SU();y.noteToastId!==null&&Bo().clearToast(y.noteToastId),y.setPendingNote(h);let C=process.stdout.columns||80,b=Math.floor(C*.618)-16,T=h.replace(/\n/g," "),k=T.length>b?T.slice(0,b)+"\u2026":T,w=Bo(),D=w.nextId;w.showToast(Qe.success(`\u25C6 Injecting: "${k}"`),!0),y.setNoteToastId(D),u.clear();return}let m=process.stdout.columns||80,g=Math.floor(m*.618)-16,A=h.replace(/\n/g," "),_=A.length>g?A.slice(0,g)+"\u2026":A;Bo().showToast(Qe.success(`\u25C6 Injecting: "${_}"`),!0),u.enqueueTypeAhead({silent:!0});return}if(p&&(d==="/pause"||d.startsWith("/pause ")||d==="/resume"||d==="/stop")){let h=d.startsWith("/pause")?"Pausing":d==="/resume"?"Resuming":"Stopping";Bo().showToast(Qe.success(`\u25C6 ${h}...`)),u.enqueueTypeAhead({silent:!0});return}if(p&&d.startsWith("/")&&!d.includes(`
|
|
923
923
|
`)){u.enqueueTypeAhead({silent:!0});return}u.enqueueTypeAhead();return}if(i===`
|
|
924
924
|
`){o.hide(),u.newLine();return}if(i==="\x7F"||i==="\b"){u.deleteChar(),a();return}if(i==="\x1B[A"){if(o.isVisible){o.moveUp();return}u.moveCursor("up");return}if(i==="\x1B[B"){if(o.isVisible){o.moveDown();return}u.moveCursor("down");return}if(i==="\x1B[C"){u.moveCursor("right");return}if(i==="\x1B[D"){u.moveCursor("left");return}if(i===""){u.undo();return}if(i===""){u.redo();return}if(i===""){u.hasQueuedMessages()&&!u.getText().trim()?u.clearTypeAheadQueue():u.clear(),o.hide();return}if(!i.startsWith("\x1B")){for(let d of Array.from(i))if(d===`
|