@aiiware/aii 0.25.7 → 0.25.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/aii +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.8
|
|
4
4
|
*
|
|
5
5
|
* AI-powered CLI assistant for terminal productivity
|
|
6
6
|
*
|
|
@@ -82,7 +82,7 @@ ${i}`;return}if(sv(e,s,Zje)){e7e(e,o)&&(r.retry=e.toString("utf8",o));return}if(
|
|
|
82
82
|
`)}var $Ke,RS,x,et=T(()=>{"use strict";we();$Ke={debug:!1,colors:!0,emojis:!0},RS={...$Ke};x={debug:K,info:Rie,warn:Nie,error:Oie,success:xie,formatError:Sv,configure:Cv}});var w9={};de(w9,{completionWithin:()=>Pc});async function Pc(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 lm=T(()=>{"use strict"});async function Mie(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 bv(t,e,r=3e3){let{completionWithin:n}=await Promise.resolve().then(()=>(lm(),w9)),s=await n(t.close(),r);if(s!=="settled"&&e!==null)try{process.kill(e,"SIGKILL")}catch{}return s}var OS=T(()=>{"use strict"});var k9,zs,YA=T(()=>{"use strict";OS();k9=500,zs=3e3+k9+500});function HKe(t,e){um.set(t,e),K(`Cleanup registered: ${t}`)}function YKe(t,e){Iv.set(t,e),K(`Cleanup registered (final): ${t}`)}function qKe(t,e){let r=[...um].filter(([n])=>n!==t);um=new Map([[t,e],...r]),K(`Cleanup registered (first): ${t}`)}function zKe(t){um.delete(t),Iv.delete(t),K(`Cleanup unregistered: ${t}`)}async function Pie(){return D9?(K("Cleanup already in progress \u2014 joining"),v9??Promise.resolve()):(D9=!0,v9=WKe(),v9)}async function WKe(){K(`Running ${um.size} cleanup callbacks`);let t=[];for(let[e,r]of[...um,...Iv])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}`)}um.clear(),Iv.clear(),qA(),t.length>0?K(`Cleanup completed with ${t.length} error(s)`):K("Cleanup completed successfully")}function qA(){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 VKe(){return D9}function Fie(){if(Lie)return;Lie=!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([Pie(),new Promise(s=>setTimeout(s,zs).unref())]),n=async(s,o=!1)=>{K(`Received ${s}`),o&&(qA(),process.exit(130)),await r(),qA();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(),qA(),process.exit(1)})()}),process.on("unhandledRejection",s=>{(async()=>(console.error(`
|
|
85
|
-
Unhandled rejection:`,s),K(`Unhandled rejection: ${s}`),await r(),qA(),process.exit(1)))()}),K("Signal handlers registered")}var D9,um,Iv,Lie,v9,st,Ti=T(()=>{"use strict";et();YA();D9=!1,um=new Map,Iv=new Map,Lie=!1;v9=null;st={register:HKe,registerFirst:qKe,registerFinal:YKe,unregister:zKe,cleanup:Pie,isShuttingDown:VKe,restoreTerminal:qA}});import Qie from"node:fs";import xS from"node:path";import{createHash as jKe,randomUUID as Uie}from"node:crypto";import{homedir as KKe}from"node:os";function dm(t){return $ie.get(t)}function JKe(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",st.unregister(c),r.release())},async commit(u){if(a!=="prepared"||!r.active)throw new Ae("runtime_active","Session startup is no longer active");let d=fo(xS.join(s,"owners",t.id+".owner"));if(d.nonce!==r.record.nonce||d.pid!==r.record.pid)throw new Ae("runtime_active","Ownership changed");a="committing",st.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),nm(i,e),t.remoteConversation.inference=e;let f;try{f=await mv(s,t.id),await n.save(t),await kS(f),a="committed"}catch(m){throw a="failed",t.remoteConversation.syncUnavailable=!0,f&&await n.save(t,{updateCurrent:!1}).catch(()=>{}),m}}};return st.registerFirst(c,()=>l.abort()),l}async function Tv(t,e,r={}){let n=Qie.realpathSync(r.cwd??process.cwd()),s=r.sessionsDir??Ld(),o=new am(s),i=r.identityDir??xS.join(KKe(),".aii","identities"),a=A9(i,"installation"),c=A9(i,"workspace-"+jKe("sha256").update(n).digest("hex")),l=Uie(),u=e.continueId;if(!u&&e.continue)try{u=fo(xS.join(s,"current.json")).id}catch{throw new Ae("context_unavailable","No saved current session")}let d=u?void 0:Es({projectPath:n,reasoningEffort:t.getConfig().llm.reasoning_effort});u??=d.id,im(s,u);let p=aie(xS.join(s,"owners"),u,{runtimeId:l,installationId:a,canonicalWorkspace:n},()=>{try{im(s,u);let f=fo(xS.join(s,u+".json")).remoteConversation;return!f?.turn?.executionDirty&&!f?.syncUnavailable}catch{return!1}});try{let f=d??await o.loadExact(u);if(Qie.realpathSync(f.projectPath)!==n)throw new Ae("wrong_workspace",`Run from ${f.projectPath}`);let m=f.remoteConversation;if(m&&(m.installationId!==a||m.workspaceIdentity!==c||m.canonicalWorkspace!==n))throw new Ae("wrong_installation_or_workspace");if(m?.origin==="web-device")throw new Ae("context_unavailable","Resume this hosted conversation from its connected computer in AiiCloud");if(m?.syncUnavailable)throw new Ae("sync_unavailable");if(m?.turn?.executionDirty)throw new Ae("execution_unresolved");if(!d&&e.remoteControl&&!m)throw new Ae("context_unavailable","This legacy snapshot has no verified Cloud binding; resume privately without --remote-control");let h=await xA(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??Uie();f.remoteConversation=m??{schema:1,origin:"cli",installationId:a,workspaceIdentity:c,logicalSessionId:A,deviceId:A,canonicalWorkspace:n,inference:h,revision:0,checkpointId:Ql(),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 _=JKe(f,h,p,o,s,!d,t);return $ie.set(e,_),_}catch(f){throw p.release(),f}}var $ie,R9=T(()=>{"use strict";hv();IS();mo();ru();MA();gn();Ti();$ie=new WeakMap});import*as Fc from"fs";import{randomUUID as XKe}from"crypto";function wi(t,e,r=384){let n=`${t}.${process.pid}.${XKe()}.tmp`;try{Fc.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),Fc.renameSync(n,t)}catch(s){try{Fc.unlinkSync(n)}catch{}throw s}}function Ws(t,e=448){Fc.mkdirSync(t,{recursive:!0,mode:e});let r=Md(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{Fc.chmodSync(t,e)}catch{}}var Qc=T(()=>{"use strict";et();TS()});function N9(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 Hie(t){return t?!N9(t,ZKe):!1}var ho,ZKe,wv=T(()=>{"use strict";ho="v0.5.
|
|
85
|
+
Unhandled rejection:`,s),K(`Unhandled rejection: ${s}`),await r(),qA(),process.exit(1)))()}),K("Signal handlers registered")}var D9,um,Iv,Lie,v9,st,Ti=T(()=>{"use strict";et();YA();D9=!1,um=new Map,Iv=new Map,Lie=!1;v9=null;st={register:HKe,registerFirst:qKe,registerFinal:YKe,unregister:zKe,cleanup:Pie,isShuttingDown:VKe,restoreTerminal:qA}});import Qie from"node:fs";import xS from"node:path";import{createHash as jKe,randomUUID as Uie}from"node:crypto";import{homedir as KKe}from"node:os";function dm(t){return $ie.get(t)}function JKe(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",st.unregister(c),r.release())},async commit(u){if(a!=="prepared"||!r.active)throw new Ae("runtime_active","Session startup is no longer active");let d=fo(xS.join(s,"owners",t.id+".owner"));if(d.nonce!==r.record.nonce||d.pid!==r.record.pid)throw new Ae("runtime_active","Ownership changed");a="committing",st.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),nm(i,e),t.remoteConversation.inference=e;let f;try{f=await mv(s,t.id),await n.save(t),await kS(f),a="committed"}catch(m){throw a="failed",t.remoteConversation.syncUnavailable=!0,f&&await n.save(t,{updateCurrent:!1}).catch(()=>{}),m}}};return st.registerFirst(c,()=>l.abort()),l}async function Tv(t,e,r={}){let n=Qie.realpathSync(r.cwd??process.cwd()),s=r.sessionsDir??Ld(),o=new am(s),i=r.identityDir??xS.join(KKe(),".aii","identities"),a=A9(i,"installation"),c=A9(i,"workspace-"+jKe("sha256").update(n).digest("hex")),l=Uie(),u=e.continueId;if(!u&&e.continue)try{u=fo(xS.join(s,"current.json")).id}catch{throw new Ae("context_unavailable","No saved current session")}let d=u?void 0:Es({projectPath:n,reasoningEffort:t.getConfig().llm.reasoning_effort});u??=d.id,im(s,u);let p=aie(xS.join(s,"owners"),u,{runtimeId:l,installationId:a,canonicalWorkspace:n},()=>{try{im(s,u);let f=fo(xS.join(s,u+".json")).remoteConversation;return!f?.turn?.executionDirty&&!f?.syncUnavailable}catch{return!1}});try{let f=d??await o.loadExact(u);if(Qie.realpathSync(f.projectPath)!==n)throw new Ae("wrong_workspace",`Run from ${f.projectPath}`);let m=f.remoteConversation;if(m&&(m.installationId!==a||m.workspaceIdentity!==c||m.canonicalWorkspace!==n))throw new Ae("wrong_installation_or_workspace");if(m?.origin==="web-device")throw new Ae("context_unavailable","Resume this hosted conversation from its connected computer in AiiCloud");if(m?.syncUnavailable)throw new Ae("sync_unavailable");if(m?.turn?.executionDirty)throw new Ae("execution_unresolved");if(!d&&e.remoteControl&&!m)throw new Ae("context_unavailable","This legacy snapshot has no verified Cloud binding; resume privately without --remote-control");let h=await xA(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??Uie();f.remoteConversation=m??{schema:1,origin:"cli",installationId:a,workspaceIdentity:c,logicalSessionId:A,deviceId:A,canonicalWorkspace:n,inference:h,revision:0,checkpointId:Ql(),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 _=JKe(f,h,p,o,s,!d,t);return $ie.set(e,_),_}catch(f){throw p.release(),f}}var $ie,R9=T(()=>{"use strict";hv();IS();mo();ru();MA();gn();Ti();$ie=new WeakMap});import*as Fc from"fs";import{randomUUID as XKe}from"crypto";function wi(t,e,r=384){let n=`${t}.${process.pid}.${XKe()}.tmp`;try{Fc.writeFileSync(n,e,{encoding:"utf-8",mode:r,flag:"wx"}),Fc.renameSync(n,t)}catch(s){try{Fc.unlinkSync(n)}catch{}throw s}}function Ws(t,e=448){Fc.mkdirSync(t,{recursive:!0,mode:e});let r=Md(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{Fc.chmodSync(t,e)}catch{}}var Qc=T(()=>{"use strict";et();TS()});function N9(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 Hie(t){return t?!N9(t,ZKe):!1}var ho,ZKe,wv=T(()=>{"use strict";ho="v0.5.56",ZKe="v0.5.40"});import{execSync as An,spawn as eJe}from"node:child_process";import{mkdtempSync as tJe,writeFileSync as rJe,rmSync as zA}from"node:fs";import{tmpdir as nJe}from"node:os";import{join as Yie}from"node:path";import{createHash as sJe}from"node:crypto";import*as Vie from"node:readline";function vv(){try{return An("docker --version",{timeout:5e3,stdio:"pipe"}),!0}catch{return!1}}function Dv(){try{return An("docker info",{timeout:5e3,stdio:"pipe"}),!0}catch{if(process.platform==="linux")try{return An("sudo -n docker info",{timeout:5e3,stdio:"pipe"}),!0}catch{return!1}return!1}}async function kv(t){let e=Date.now();for(;Date.now()-e<t;){if(Dv())return;await new Promise(r=>setTimeout(r,2e3))}throw new _n("Docker daemon did not start within timeout.","macOS: open -a Docker","Linux: sudo systemctl start docker",...Uc)}async function oJe(){let t=process.platform;if(t==="darwin"){try{An("open -a Docker",{timeout:5e3,stdio:"pipe"})}catch{throw new _n("Failed to start Docker Desktop.","Start Docker Desktop manually from Applications.",...Uc)}await kv(6e4)}else if(t==="linux"){try{An("sudo systemctl start docker",{timeout:15e3,stdio:"pipe"})}catch{throw new _n("Docker daemon is not running.","sudo systemctl start docker",...Uc)}await kv(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
|
`),bpe="CODEX_ENTITLEMENT_DENIED:",got=["\u25A0 OpenAI accepted your sign-in but declined Codex access for your current plan."," OpenAI decides which ChatGPT subscription tiers may use Codex sign-in \u2014 this is not an Aii bug."," Today: paste an OpenAI API key instead (aii setup \u2192 OpenAI) \xB7 keep the sign-in; it activates if OpenAI enables your tier."].join(`
|
|
353
353
|
`),CG=[{prefix:pot,wall:fot},{prefix:mot,wall:hot},{prefix:bpe,wall:got}],Aot="PROVIDER_AUTH_REJECTED:",_ot="upstream 401 Unauthorized:",Eot=`${Aot} ${_ot}`,yot=/"status":\s*401\b|token_expired/;mR="\u25D0 Your provider credential was rejected upstream \u2014 expired, rotated, or invalid. Sign-in lanes: aii login --status \xB7 API keys: aii setup";SG="\u25D0 Your sign-in token was refreshed mid-turn \u2014 retry this step (autonomous runs retry automatically).",Cot=[QD,O5,mR,SG];Sot="Note: Z.ai limits Coding Plans to their officially supported tools; Aii isn't listed yet.",bot={zai:"glm"};Ob={xai:{tier:"sanctioned",kind:"oauth",description:"SuperGrok / X Premium"},glm:{tier:"unofficial",kind:"plan-key",disclosure:"notice",notice:Sot,description:"GLM Coding Plan (flat-rate)"},claude:{tier:"blocked",wall:uot},openai:{tier:"unofficial",kind:"oauth",disclosure:"consent",consentCopy:yue,description:"ChatGPT subscription (Codex)"},google:{tier:"blocked",wall:dot}},Iot={sanctioned:"sanctioned",unofficial:"unofficial (explicit consent required)",blocked:"blocked (provider terms)",unavailable:"unavailable (pending provider sanction)"},bG="Other providers use API keys \u2014 aii setup.",IG="Sign in: aii login --provider xai \xB7 status: aii login --status"});import{execFileSync as wG}from"node:child_process";function vG(t){if(!t)return!1;try{let e=new URL(t).protocol;return e==="https:"||e==="http:"}catch{return!1}}function DG(t){vG(t)&&(process.platform==="darwin"?wG("open",[t],{stdio:"ignore"}):process.platform==="win32"?wG("cmd",["/c","start","",t],{stdio:"ignore"}):wG("xdg-open",[t],{stdio:"ignore"}))}function kG(t){if(t?.aborted)throw new ni}async function Mm(t,e,r,n){let s=new AbortController,o=setTimeout(()=>s.abort(),n);try{let i=await t(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(r).toString(),signal:s.signal}),a=await i.text();return{ok:i.ok,status:i.status,text:a}}finally{clearTimeout(o)}}async function wpe(t,e={}){let r=e.fetchImpl??fetch,n=e.openBrowser??DG,s=e.sleep??(A=>new Promise(_=>setTimeout(_,A))),o=e.now??(()=>Date.now()),i=e.print??(A=>process.stdout.write(A+`
|
|
354
354
|
`)),a=e.signal,c=e.requestTimeoutMs??1e4,l=(A,_)=>Mm(r,A,_,c);kG(a);let u;try{u=await l(t.deviceEndpoint,{client_id:t.clientId,scope:t.scopes})}catch(A){throw A.name==="AbortError"?new ir(`Sign-in unreachable (${new URL(t.deviceEndpoint).hostname} timed out). Check your network and retry.`):A}if(!u.ok)throw new ir(`Device authorization failed to start (HTTP ${u.status}).`);let d;try{d=JSON.parse(u.text)}catch{throw new ir("Device authorization returned an unreadable response.")}if(!d.device_code||!d.user_code||!d.verification_uri)throw new ir("Device authorization response is missing required fields.");if(!vG(d.verification_uri))throw new ir("Sign-in aborted: the provider returned a suspicious verification URL \u2014 refusing to open or display it.");let p=vG(d.verification_uri_complete)?d.verification_uri_complete:d.verification_uri;i(`\u2192 Opening ${oe(d.verification_uri)} in your browser${t.label?` (${t.label})`:""}`),i(`\u2192 If asked, enter the code: ${oe(d.user_code)}`),i("\u2192 Waiting for you to approve in the browser \u2026 (Ctrl+C to cancel)"),i(""),i(" Only enter this code if you started 'aii login' yourself \u2014 never from a link someone sent you.");try{n(p)}catch{i(" (Could not open a browser here \u2014 open the URL above on any device.)")}let f=Math.max(1,d.interval??kot)*1e3,m=Number.isFinite(d.expires_in)&&d.expires_in>0?d.expires_in:wot,h=o()+m*1e3;for(;;){kG(a);try{let A=await l(t.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:d.device_code,client_id:t.clientId}),_;try{_=JSON.parse(A.text)}catch{_={}}if(A.ok&&typeof _.access_token=="string"&&_.access_token.length>0)return _;switch(_.error){case"authorization_pending":break;case"slow_down":f+=vot;break;case"access_denied":throw new ir("Sign-in declined in the browser \u2014 nothing was saved.");case"expired_token":throw new ir("The sign-in code expired. Run the command again to retry.");case void 0:break;default:throw new ir(`Sign-in failed (${oe(String(_.error))}${_.error_description?`: ${oe(String(_.error_description))}`:""}).`)}}catch(A){if(A instanceof ir||A instanceof ni)throw A}if(o()>=h)throw new ir("Timed out waiting for sign-in. Run the command again to retry.");await s(f),kG(a)}}var ir,ni,wot,kot,vot,ER=T(()=>{"use strict";Mt();ir=class extends Error{constructor(e){super(e),this.name="ProviderAuthError"}},ni=class extends Error{constructor(e="Sign-in cancelled \u2014 nothing was saved."){super(e),this.name="ProviderAuthCancelled"}},wot=300,kot=5,vot=5e3});function Rpe(t,e){kpe.has(e)||(kpe.add(e),t(e))}function vpe(t){try{let e=t.split(".");return e.length!==3?void 0:JSON.parse(Buffer.from(e[1],"base64url").toString("utf-8"))}catch{return}}async function yR(t,e,r={},n=Zd){let s=r.now??(()=>Date.now());if(!e||typeof e.access_token!="string"||e.access_token.length===0)throw new ir("Refusing to persist an incomplete token response.");let o=s()/1e3,i;if(typeof e.expires_in=="number"&&Number.isFinite(e.expires_in)&&e.expires_in>0)i=o+e.expires_in;else{let c=Number(vpe(e.access_token)?.exp);i=Number.isFinite(c)&&c>o?c:o+Rot}let a;if(e.id_token){let c=vpe(e.id_token),l=c?.email??c?.preferred_username??c?.sub;if(typeof l=="string"){let u=oe(l).trim();u&&(a=u)}}await t.setSecret(n.keys.access,e.access_token),e.refresh_token&&await t.setSecret(n.keys.refresh,e.refresh_token),await t.setSecret(n.keys.expiry,String(i)),await t.setSecret(n.keys.refreshedAt,String(o)),a&&await t.setSecret(n.keys.account,a),t.getSecret(n.keys.dead)&&await t.setSecret(n.keys.dead,"")}async function Dpe(t,e,r){await t.setSecret(r.keys.dead,"1"),await t.setSecret(r.keys.access,""),await t.setSecret(r.keys.expiry,""),Rpe(e,r.pl04Line)}async function Lm(t,e={},r={},n=Zd){let s=e.now??(()=>Date.now()),o=e.print??(_=>process.stdout.write(_+`
|
|
355
|
-
`)),i=n.provider==="openai"?"OpenAI":"xAI";if(t.getSecret(n.keys.dead)==="1")return Rpe(o,n.pl04Line),{status:"dead"};let a=t.getSecret(n.keys.access),c=t.getSecret(n.keys.refresh);if(!a&&!c)return{status:"none"};let l=s()/1e3,u=Number(t.getSecret(n.keys.expiry)),d=!!a&&Number.isFinite(u)&&l<u;if(!!a&&Number.isFinite(u)&&l<u-Dot&&!r.force)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};if(!c)return d?{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)}:(await Dpe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await Mm(f,n.tokenEndpoint,{grant_type:"refresh_token",refresh_token:c,client_id:n.clientId},m)}catch{if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (network error). Check your connection and retry.`)}let A;try{A=JSON.parse(h.text)}catch{A={}}if(h.ok&&typeof A.access_token=="string"&&A.access_token.length>0)return await yR(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};if(A.error==="invalid_grant")return await Dpe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (${A.error?oe(String(A.error)):`HTTP ${h.status}`}).`)}var Dot,Rot,kpe,xb=T(()=>{"use strict";ER();Oi();Oi();Mt();Dot=120,Rot=3600,kpe=new Set});function Bb(t){return t?t===mR||I_(t)?!0:hR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function Npe(t){if(t)try{let e=Te();return e.reloadSecretsSync(),Fue().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function CR(t=Zd,e){let r=RG.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=Te();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await Lm(s,{print:()=>{}},{force:!0},t);return i.status==="ok"?{status:"ok",accessToken:i.accessToken}:i.status==="dead"?{status:"dead"}:{status:"unavailable"}}catch{return{status:"unavailable"}}})().finally(()=>{RG.delete(t.provider)});return RG.set(t.provider,n),n}var RG,NG=T(()=>{"use strict";ht();xb();T_();u_();et();u_();RG=new Map});function Ope(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function SR(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:Ope(t.protocol_version)}}function bR(t){if(typeof t!="object"||t===null||typeof t.type=="string")return null;let e=t.error;return typeof e!="string"||e===""?null:{unknown_model:"That model is not available on AiiCloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --inference server.",insufficient_credits:"Out of AiiCloud credits.",quota_exceeded:"Daily free-tier budget reached on AiiCloud.",quota_check_failed:"AiiCloud could not verify your quota \u2014 please retry.",worker_unavailable:"AiiCloud is temporarily unavailable \u2014 please retry, or run with --inference server."}[e]??`AiiCloud error: ${e}`}function Pm(t){switch((t??"").toLowerCase()){case"quota_exceeded":case"insufficient_credits":return"budget_exhausted";case"worker_unavailable":case"quota_check_failed":return"transient";default:return"fatal"}}function IR(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function OG(t){return t==null||typeof t=="object"}function wR(t){switch(t.type){case"tool_request":return OG(t.input);case"mcp_tool_request":return OG(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&OG(r.input))}default:return!0}}function kR(t){return Ope(t)>2?"hard":"compatible"}function vR(t){return`This Aii Server speaks protocol v${t}, but your CLI speaks v2. Some responses may not work correctly. Update with: aii upgrade`}var bs,xpe,Bpe,TR,hu=T(()=>{"use strict";bs=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};xpe=new Set(["token","complete","error","purpose_ack","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),Bpe=new Set(["session_started","turn_ready","token","iteration_tokens_usage","tool_request","tool_batch_request","tool_status","complete","error","mcp_tools_loaded","permission_request","permission_resolution","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),TR=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function Mpe(t,e){e?Fm.set(t,e):Fm.delete(t)}function Qi(t,e){e?DR.add(t):DR.delete(t)}function BG(t,e){e?xG.set(t,e):xG.delete(t)}function Ppe(t,e){Lpe.set(t,e)}function Fpe(t,e){return Lpe.get(t)?.(e)??!1}function Qpe(t){let e=Fm.get(t);e&&!e.attempted&&!e.blocked&&MG(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),Fm.delete(t)}function MG(t,e){let r=Fm.get(t);r&&LG(r,e)}function LG(t,e){t.started||t.attempted||(t.blocked=!0,t.send({type:"session_prompt_execution",task_id:t.taskId,device_id:t.deviceId,prompt_id:t.promptId,execution_state:"not_run",execution_reason:e}))}var Fm,DR,xG,Fi,RR,NR,OR,si,Lpe,Ui=T(()=>{"use strict";Fm=new WeakMap,DR=new WeakSet,xG=new WeakMap,Fi=t=>Fm.get(t);RR=t=>DR.has(t);NR=t=>Fm.has(t)||DR.has(t),OR=t=>xG.get(t);si=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},Lpe=new WeakMap});import{createHash as Not}from"node:crypto";function Fot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Oot.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function Qot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=0;for(;r<e.length&&(e[r]==="sudo"||e[r]==="env"||/^\w+=/.test(e[r]));)r++;let n=e[r]?e[r].split("/").pop()??"":"",s=e[r+1]??"";return!!(n==="xargs"||n==="make"||n==="git"&&s==="config"||(n==="docker"||n==="podman")&&(s==="run"||s==="exec"||s==="create")||n==="find"&&e.some(o=>Pot.includes(o)))}function Upe(t,e){return PG(t,e)===null}function PG(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return xot.test(r)?Mot.test(r)?"substitution":Lot.test(r)?"chained":"redirection":Bot.test(r)?"injection-flag":Qot(r)?"second-action":null}function Uot(t){try{return String(t)}catch{return"~unstringifiable"}}function w_(t,e){if(t===null)return"null";let r=typeof t;if(r==="undefined")return"~undef";if(r==="bigint")return`~big:${t.toString()}`;if(r==="number"){let n=t;return Number.isFinite(n)?JSON.stringify(n):`~num:${String(n)}`}if(r==="boolean"||r==="string")return JSON.stringify(t);if(r==="function"||r==="symbol")return`~${r}`;if(typeof t=="object"){let n=t;if(e.has(n))return"~cycle";e.add(n);try{if(Array.isArray(n))return`[${n.map(a=>w_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${w_(c,e)}=>${w_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>w_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${Uot(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${w_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function FG(t){return Not("sha256").update(w_(t??{},new WeakSet)).digest("hex").slice(0,16)}function QG(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return Fot(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Lt(s,r,n);return o.ok?`${t}:${Kn(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${FG(e)}`}function $pe(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?QG(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Oot,xot,Bot,Mot,Lot,Pot,UG=T(()=>{"use strict";Jn();Oot=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),xot=/[;&|<>`\n]|\$\(/,Bot=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,Mot=/[`]|\$\(/,Lot=/[;&|\n]/,Pot=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function xR(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function $G(t,e){return t!==void 0&&t>=0&&t<e?t:0}function Gpe(t,e){return{selectedIndex:$G(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var GG=T(()=>{"use strict"});var $ot,Got,Hot,Yot,qot,zot,Wot,Qm,BR,dp,HG=T(()=>{"use strict";we();$ot={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:g.hex("#3B82F6"),userInput:g.hex("#3B82F6"),userInputText:g.hex("#93C5FD"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#A855F7"),link:g.hex("#3B82F6").underline,heading:g.hex("#A855F7").bold,filePath:g.hex("#3B82F6"),indicator:g.hex("#3B82F6")}},Got={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#4E6BF5"),userInput:g.hex("#4E6BF5"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#4E6BF5"),link:g.hex("#4E6BF5").underline,heading:g.hex("#4E6BF5").bold,filePath:g.hex("#4E6BF5"),indicator:g.hex("#4E6BF5")}},Hot={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:g.hex("#00BCD4"),userInput:g.hex("#00BCD4"),userInputText:g.hex("#67E8F9"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#00BCD4"),link:g.hex("#00BCD4").underline,heading:g.hex("#00BCD4").bold,filePath:g.hex("#00BCD4"),indicator:g.hex("#00BCD4")}},Yot={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#6B8AFF"),userInput:g.hex("#6B8AFF"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#6B8AFF"),link:g.hex("#6B8AFF").underline,heading:g.hex("#6B8AFF").bold,filePath:g.hex("#6B8AFF"),indicator:g.hex("#6B8AFF")}},qot={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:g.hex("#22C55E"),userInput:g.hex("#22C55E"),userInputText:g.hex("#86EFAC"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#22C55E"),link:g.hex("#22C55E").underline,heading:g.hex("#22C55E").bold,filePath:g.hex("#22C55E"),indicator:g.hex("#22C55E")}},zot={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:g.hex("#F59E0B"),userInput:g.hex("#F59E0B"),userInputText:g.hex("#FCD34D"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#F59E0B"),link:g.hex("#F59E0B").underline,heading:g.hex("#F59E0B").bold,filePath:g.hex("#F59E0B"),indicator:g.hex("#F59E0B")}},Wot={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:g.reset,userInput:g.reset,userInputText:g.hex("#CBD5E1"),success:g.reset,warning:g.reset,error:g.bold,muted:g.dim,dim:g.dim,code:g.reset,link:g.underline,heading:g.bold,filePath:g.reset,indicator:g.bold}},Qm={classic:$ot,brand:Got,teal:Hot,indigo:Yot,forest:qot,amber:zot,grayscale:Wot},BR="classic",dp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Um={};de(Um,{BAND_STYLE_INFO:()=>Mb,BAND_STYLE_ORDER:()=>pp,DEFAULT_BAND_STYLE:()=>qG,ThemeManager:()=>Ua,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>v_,resolveBandBg:()=>k_});function k_(t,e){let r=Mb[t];if(r.blend===null)return Vot;let n=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(n.replace("#",""),16),o=r.blend,i=(a,c)=>Math.round(a*o+c*(1-o));return"#"+(i(s>>16&255,YG[0])<<16|i(s>>8&255,YG[1])<<8|i(s&255,YG[2])).toString(16).padStart(6,"0")}function J(){return Ua.getInstance().getColors()}function $e(){return Ua.getInstance().getAccentColorName()}function v_(){return Ua.getInstance().getUserInputTextColorName()}var pp,Mb,qG,YG,Vot,Ua,fp=T(()=>{"use strict";HG();ht();pp=["subtle","themed","neutral","bold"],Mb={subtle:{blend:.16,description:"Faint theme tint \u2014 quietest"},themed:{blend:.28,description:"Theme-tinted band (default)"},neutral:{blend:null,description:"Fixed neutral gray (theme-independent)"},bold:{blend:.4,description:"Strong theme tint \u2014 selection-like"}},qG="themed",YG=[20,22,27],Vot="#262C34";Ua=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Qm[BR]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=Qm[e];if(!r){let n=dp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in Qm}getAvailableThemes(){return dp.map(e=>Qm[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Te().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=qG,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${pp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return pp.includes(e)}reset(){this.activeTheme=Qm[BR],this.bandStyle=null}}});var Yt=T(()=>{"use strict";HG();fp()});import{resolve as jot}from"path";function Kot(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return process.stdout.isTTY?e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function Lb(){return zG===null&&(zG=Kot()),zG}function Jot(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Ype(){return Hpe||!Lb()?"":(Hpe=!0,` (${Jot()}+Click to open)`)}function Xot(t,e){return Lb()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function qpe(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",s=t;n&&t.startsWith(n)&&(s="~"+t.slice(n.length));let o=r??(e?`${s}:${e}`:s);if(!Lb())return J().filePath(o);let i=J().accent(o),c=`file://${jot(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Xot(i,c)}var zG,Hpe,zpe=T(()=>{"use strict";Yt();zG=null,Hpe=!1});function Zot(t){return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=183984&&t<=191471||t>=196608&&t<=201551||t>=63744&&t<=64255||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12784&&t<=12799||t>=44032&&t<=55215||t>=4352&&t<=4607||t>=12592&&t<=12687||t>=65280&&t<=65519&&(t>=65281&&t<=65376||t>=65504&&t<=65510)||t>=12288&&t<=12351||t>=12800&&t<=13055||t>=13056&&t<=13311||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=128512&&t<=128591||t>=128640&&t<=128767||t>=129648&&t<=129791||t>=9984&&t<=10175||t>=9728&&t<=9983}function eit(t){return t<32&&t!==9||t===127||t>=768&&t<=879||t>=6832&&t<=6911||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65056&&t<=65071||t===8203||t===8204||t===8205||t===65279||t>=65024&&t<=65039||t>=917760&&t<=917999}function Sn(t){let e=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),r=0;for(let n of e){let s=n.codePointAt(0)??0;eit(s)||(Zot(s)?r+=2:r+=1)}return r}function Vc(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Sn(s);if(r+o>e)break;n+=s,r+=o}return n}var $m=T(()=>{"use strict"});function VG(t){return t.replace(WG,"")}function tit(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function $a(t){return VG(oe(tit(t??"")))}var WG,mp=T(()=>{"use strict";Mt();WG=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var Kpe={};de(Kpe,{VERSION:()=>Gm,colors:()=>F,formatCode:()=>dit,formatPath:()=>jpe,getActionIndicator:()=>uit,padEndAnsi:()=>hit,printDivider:()=>Vpe,printError:()=>cit,printExitSummary:()=>KG,printHeader:()=>lit,printSuccess:()=>iit,printToolResultCompact:()=>Ga,printWarning:()=>ait,shortenPath:()=>fit});function rit(t){return t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-zA-Z]:\\/.test(t)||/\.(ts|tsx|js|jsx|json|md|py|go|rs|java|c|cpp|h|hpp|css|scss|html|xml|yaml|yml|toml|sh|bash|zsh)$/.test(t)||/^src\//.test(t)||/^lib\//.test(t)||/^test[s]?\//.test(t)}function oit(t){return sit.test(t)}function Ga(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?F.success("\u25CF"):F.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=rit(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=$a(d),f=Sn(t)+6+i,m=Math.max(nit,(a.columns||80)-f),A=Sn(p)>m?Vc(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!oit(e)&&_;if(E){let C=e.match(/:(\d+)$/),w=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=jpe(k,w,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?F.dim(Ype()):"",S=o&&!y&&!Wpe?F.dim(" (ctrl+o to expand)"):"";if(S&&(Wpe=!0),n){let C=r?F.dim:F.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",w=r?F.dim:F.error;s(w(`\u2514 ${C}`)+y+S)}}function iit(t){console.log(F.success("\u2713 ")+t)}function ait(t){console.log(F.warning("\u26A0 ")+t)}function cit(t){console.log(F.error("\u2717 ")+t)}function Vpe(t=60){console.log(F.dim("\u2500".repeat(t)))}function lit(t){console.log(F.logo(t)),Vpe(t.length)}function uit(t){return F.thinking(`[${t}]`)}function jpe(t,e,r){if(Lb())return qpe(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",s=t;return n&&t.startsWith(n)&&(s="~"+t.slice(n.length)),e&&(s+=`:${e}`),F.filePath(r??s)}function dit(t){return F.code(t)}function pit(){return process.stdout.columns||80}function fit(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function mit(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hit(t,e){let r=mit(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function git(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function jG(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function KG(t){let e=pit(),r=Math.min(e-2,76),n=r-4,s=(A,_)=>{let E=A.replace(/\x1b\[[0-9;]*m/g,"").length;return A+" ".repeat(Math.max(0,_-E))},o=A=>F.border("\u2502")+" "+s(A,n)+" "+F.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=F.dim(A.padEnd(15))+_,w=F.dim(E.padEnd(15))+y;return o(s(C,S)+w)},a=git(t.durationSeconds),c=jG(t.tokensIn),l=jG(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601\uFE0F Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(F.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(F.logo("Session complete. \u{1FABC}"))),console.log(F.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(F.logo("Session Summary"))),console.log(o(F.dim("\u2500".repeat(15)))),console.log(i("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(i("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(F.logo("Token Usage"))),console.log(o(F.dim("\u2500".repeat(11)))),console.log(i("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let A=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(F.dim("Cached".padEnd(15))+`${jG(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?F.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(F.dim("Cost".padEnd(15))+u+m)),console.log(o(""));let h=(A,_)=>A.length>_?`${A.slice(0,Math.max(0,_-1))}\u2026`:A;if(t.goalLine){let A=t.goalLine.replace(/^Goal:\s*/,"");console.log(o(F.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(F.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(F.dim("Model: ")+F.model(d))),console.log(F.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Gm,F,nit,sit,Wpe,Qr=T(()=>{"use strict";we();zpe();Yt();$m();mp();Gm="0.25.7",F={get logo(){return J().accent.bold},get prompt(){return J().accent.bold},get model(){return J().accent},get success(){return J().success},get warning(){return J().warning},get error(){return J().error},get thinking(){return J().dim},get filePath(){return J().filePath},get code(){return J().code},get muted(){return J().muted},get dim(){return J().dim},get safe(){return J().success},get risky(){return J().warning},get destructive(){return J().error},get border(){return J().accent},get bannerBorder(){return J().accent}};nit=24,sit=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Wpe=!1});var XG={};de(XG,{MAX_RETAINED_TOASTS:()=>JG,MAX_VISIBLE_TOASTS:()=>Pb,getNotificationStore:()=>ot,useNotificationStore:()=>Fn});import{create as Ait}from"zustand";function Jpe(t){return t.length<=JG?t:t.slice(-JG)}var Pb,JG,Fn,ot,jc=T(()=>{"use strict";Pb=5,JG=200;Fn=Ait((t,e)=>({toasts:[],nextId:1,showToast:(r,n=!1,s)=>{t(o=>{let i={id:o.nextId,text:r,persistent:n,expiresAt:s};if(!n){let c=o.toasts.filter(l=>l.persistent);return{toasts:Jpe([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Jpe([...a,i]),nextId:o.nextId+1}})},clearToast:r=>{t(n=>r===void 0?{toasts:[]}:{toasts:n.toasts.filter(s=>s.id!==r)})},clearPersistent:()=>{t(r=>({toasts:r.toasts.filter(n=>!n.persistent)}))},clearFirstPersistent:()=>{t(r=>{let n=r.toasts.findIndex(s=>s.persistent);return n===-1?r:{toasts:[...r.toasts.slice(0,n),...r.toasts.slice(n+1)]}})},reset:()=>t({toasts:[],nextId:1}),visibleToasts:()=>e().toasts.slice(0,Pb),overflowCount:()=>Math.max(0,e().toasts.length-Pb)}));Object.defineProperty(Fn,"toast",{get:()=>{let t=Fn.getState().toasts;return t.length>0?t[t.length-1]:null}});ot=Fn.getState});var Zpe={};de(Zpe,{getUserEchoSink:()=>ZG,setUserEchoSink:()=>_it});function _it(t){Xpe=t}function ZG(){return Xpe}var Xpe,e8=T(()=>{"use strict";Xpe=null});import{create as Eit}from"zustand";var efe,Hm,MR=T(()=>{"use strict";jc();e8();efe=Eit((t,e)=>({pendingNote:null,pendingOrigin:"keyboard",noteToastId:null,setPendingNote:r=>t({pendingNote:r,pendingOrigin:"keyboard",onRemoteConsume:void 0}),offerRemoteNote:(r,n)=>e().pendingNote?!1:(t({pendingNote:r,pendingOrigin:"remote",onRemoteConsume:n}),!0),setNoteToastId:r=>t({noteToastId:r}),getPendingNote:()=>e().pendingNote,onNoteInjected:()=>{let r=e().pendingNote,n=e().pendingOrigin;r&&n==="remote"&&e().onRemoteConsume?.();let s=e().noteToastId;if(s!==null&&ot().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=ZG();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),Hm=efe.getState});import{create as yit}from"zustand";var D_,cn,Ym=T(()=>{"use strict";D_=null,cn=yit((t,e)=>({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:null,begin:r=>{t({active:!0,startedAt:Date.now(),bgAgentCount:r,elapsedSec:0,lastRelease:null}),D_!==null&&clearInterval(D_),D_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{D_!==null&&(clearInterval(D_),D_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var LR={};de(LR,{getUIStore:()=>yt,useUIStore:()=>bo});import{create as Cit}from"zustand";var tfe,bo,yt,hp=T(()=>{"use strict";tfe={mode:"welcome",agentMode:"normal",status:"",isThinking:!1,isStreaming:!1,currentIteration:0,iterationStartTime:Date.now(),iterationTokens:0,contextPercent:0,contextLevel:"normal",contextTokens:0,contextLimit:2e5,sessionCost:0,freeBudgetRemaining:null,freeBudgetResetAt:null,goalSegment:"",goalTurnActive:!1,sessionTokensIn:0,sessionCachedTokens:0,provider:"",model:"",reasoningEffort:"",openrouterProvider:"",connectionMode:"local",projectPath:process.cwd(),branch:void 0,worktreeName:void 0,baseBranch:void 0,soulName:"",personaName:"",toolsCount:0,mcpServersCount:0,mcpFailedCount:0,contextFilesCount:0,skillsCount:0,sessionStartTime:Date.now(),agentExecMs:0,agentTurnStartTime:null,renderEpoch:0,loopMode:!1,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0},bo=Cit(t=>({...tfe,setMode:e=>t({mode:e}),setAgentMode:e=>t({agentMode:e}),setStatus:e=>t({status:e}),setThinking:e=>t({isThinking:e}),setStreaming:e=>t(r=>{if(e&&!r.agentTurnStartTime)return{isStreaming:e,agentTurnStartTime:Date.now()};if(!e&&r.agentTurnStartTime){let n=Date.now()-r.agentTurnStartTime;return{isStreaming:e,agentExecMs:r.agentExecMs+n,agentTurnStartTime:null}}return{isStreaming:e}}),incrementIteration:()=>t(e=>({currentIteration:e.currentIteration+1,iterationStartTime:Date.now(),iterationTokens:0})),addIterationTokens:e=>t(r=>({iterationTokens:r.iterationTokens+e})),setIterationTokens:e=>t({iterationTokens:e}),updateContext:(e,r)=>{let n=r>0?Math.round(e/r*100):0,s=n>=90?"critical":n>=70?"warning":"normal";t({contextTokens:e,contextLimit:r,contextPercent:n,contextLevel:s})},updateSession:e=>t(e),updateResources:e=>t(e),setLoopMode:e=>t(e?{loopMode:e}:{loopMode:e,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0}),startLoop:(e,r)=>t({loopStartTime:e,loopMaxIterations:r,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0}),updateLoopStats:(e,r,n,s)=>t({loopTotalInputTokens:e,loopTotalOutputTokens:r,loopCost:n,loopToolCalls:s}),setLoopIteration:e=>t({loopCurrentIteration:e}),setLoopPaused:(e,r)=>t({loopPaused:e,loopPauseUntil:r}),setLoopDurationSeconds:e=>t({loopDurationSeconds:e}),incrementRenderEpoch:()=>t(e=>({renderEpoch:e.renderEpoch+1})),reset:()=>t(tfe)})),yt=bo.getState});var Fb={};de(Fb,{getInputStore:()=>R_,useInputStore:()=>Xn});import{create as Sit}from"zustand";var rfe,bit,Iit,Xn,R_,gu=T(()=>{"use strict";we();jc();hp();rfe={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},bit=100,Iit=50,Xn=Sit((t,e)=>({...rfe,insertChar:r=>{e().saveSnapshot(),t(s=>{let o=[...s.lines],i=o[s.cursorLine];return o[s.cursorLine]=i.slice(0,s.cursorCol)+r+i.slice(s.cursorCol),{lines:o,cursorCol:s.cursorCol+r.length,redoStack:[]}})},deleteChar:()=>{let r=e();r.cursorCol===0&&r.cursorLine===0||(r.saveSnapshot(),t(n=>{let s=[...n.lines];if(n.cursorCol>0){let o=s[n.cursorLine];return s[n.cursorLine]=o.slice(0,n.cursorCol-1)+o.slice(n.cursorCol),{lines:s,cursorCol:n.cursorCol-1,redoStack:[]}}else if(n.cursorLine>0){let o=s[n.cursorLine-1],i=s[n.cursorLine];return s[n.cursorLine-1]=o+i,s.splice(n.cursorLine,1),{lines:s,cursorLine:n.cursorLine-1,cursorCol:o.length,redoStack:[]}}return n}))},newLine:()=>{e().saveSnapshot(),t(n=>{let s=[...n.lines],o=s[n.cursorLine],i=o.slice(0,n.cursorCol),a=o.slice(n.cursorCol);return s[n.cursorLine]=i,s.splice(n.cursorLine+1,0,a),{lines:s,cursorLine:n.cursorLine+1,cursorCol:0,redoStack:[]}})},moveCursor:r=>{t(n=>{switch(r){case"left":if(n.cursorCol>0)return{cursorCol:n.cursorCol-1};if(n.cursorLine>0)return{cursorLine:n.cursorLine-1,cursorCol:n.lines[n.cursorLine-1].length};break;case"right":if(n.cursorCol<n.lines[n.cursorLine].length)return{cursorCol:n.cursorCol+1};if(n.cursorLine<n.lines.length-1)return{cursorLine:n.cursorLine+1,cursorCol:0};break;case"up":if(n.cursorLine>0){let s=n.cursorLine-1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break;case"down":if(n.cursorLine<n.lines.length-1){let s=n.cursorLine+1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break}return n})},setText:r=>{let n=r.split(`
|
|
355
|
+
`)),i=n.provider==="openai"?"OpenAI":"xAI";if(t.getSecret(n.keys.dead)==="1")return Rpe(o,n.pl04Line),{status:"dead"};let a=t.getSecret(n.keys.access),c=t.getSecret(n.keys.refresh);if(!a&&!c)return{status:"none"};let l=s()/1e3,u=Number(t.getSecret(n.keys.expiry)),d=!!a&&Number.isFinite(u)&&l<u;if(!!a&&Number.isFinite(u)&&l<u-Dot&&!r.force)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};if(!c)return d?{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)}:(await Dpe(t,o,n),{status:"dead"});let f=e.fetchImpl??fetch,m=e.requestTimeoutMs??1e4,h;try{h=await Mm(f,n.tokenEndpoint,{grant_type:"refresh_token",refresh_token:c,client_id:n.clientId},m)}catch{if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (network error). Check your connection and retry.`)}let A;try{A=JSON.parse(h.text)}catch{A={}}if(h.ok&&typeof A.access_token=="string"&&A.access_token.length>0)return await yR(t,A,e,n),{status:"ok",accessToken:A.access_token,account:t.getSecret(n.keys.account)};if(A.error==="invalid_grant")return await Dpe(t,o,n),{status:"dead"};if(d)return{status:"ok",accessToken:a,account:t.getSecret(n.keys.account)};throw new ir(`Could not refresh your ${i} sign-in (${A.error?oe(String(A.error)):`HTTP ${h.status}`}).`)}var Dot,Rot,kpe,xb=T(()=>{"use strict";ER();Oi();Oi();Mt();Dot=120,Rot=3600,kpe=new Set});function Bb(t){return t?t===mR||I_(t)?!0:hR(t)?!1:/\b401\b|unauthoriz/i.test(t):!1}function Npe(t){if(t)try{let e=Te();return e.reloadSecretsSync(),Fue().find(r=>e.getSecret(r.keys.access)===t)}catch{return}}async function CR(t=Zd,e){let r=RG.get(t.provider);if(r)return r;K(`reactive-401: refreshing ${t.provider} lane`);let n=(async()=>{try{let s=Te();s.reloadSecretsSync();let o=s.getSecret(t.keys.access);if(e&&o&&o!==e)return{status:"ok",accessToken:o};let i=await Lm(s,{print:()=>{}},{force:!0},t);return i.status==="ok"?{status:"ok",accessToken:i.accessToken}:i.status==="dead"?{status:"dead"}:{status:"unavailable"}}catch{return{status:"unavailable"}}})().finally(()=>{RG.delete(t.provider)});return RG.set(t.provider,n),n}var RG,NG=T(()=>{"use strict";ht();xb();T_();u_();et();u_();RG=new Map});function Ope(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:1}function SR(t,e){if(typeof t!="object"||t===null)return{kind:"malformed",reason:"frame is not an object"};let r=t.type;return typeof r!="string"?{kind:"malformed",reason:'frame has no string "type"'}:e.has(r)?{kind:"ok",frame:t}:{kind:"unknown",type:r,protocolVersion:Ope(t.protocol_version)}}function bR(t){if(typeof t!="object"||t===null||typeof t.type=="string")return null;let e=t.error;return typeof e!="string"||e===""?null:{unknown_model:"That model is not available on AiiCloud. Pick a model from your cloud dashboard (cloud.aiiware.com) or run with --inference server.",insufficient_credits:"Out of AiiCloud credits.",quota_exceeded:"Daily free-tier budget reached on AiiCloud.",quota_check_failed:"AiiCloud could not verify your quota \u2014 please retry.",worker_unavailable:"AiiCloud is temporarily unavailable \u2014 please retry, or run with --inference server."}[e]??`AiiCloud error: ${e}`}function Pm(t){switch((t??"").toLowerCase()){case"quota_exceeded":case"insufficient_credits":return"budget_exhausted";case"worker_unavailable":case"quota_check_failed":return"transient";default:return"fatal"}}function IR(t){if(!t)return null;try{let e=JSON.parse(t);if(e&&typeof e.error=="string")return e.error}catch{}return t}function OG(t){return t==null||typeof t=="object"}function wR(t){switch(t.type){case"tool_request":return OG(t.input);case"mcp_tool_request":return OG(t.params);case"tool_batch_request":{let e=t.tools;return e==null||Array.isArray(e)&&e.every(r=>r==null||typeof r=="object"&&OG(r.input))}default:return!0}}function kR(t){return Ope(t)>2?"hard":"compatible"}function vR(t){return`This Aii Server speaks protocol v${t}, but your CLI speaks v2. Some responses may not work correctly. Update with: aii upgrade`}var bs,xpe,Bpe,TR,hu=T(()=>{"use strict";bs=class extends Error{wireCode;origin;code="CLOUD_EXHAUSTED";constructor(e,r){super("cloud_exhausted"),this.wireCode=e,this.origin=r,this.name="CloudExhaustedError"}};xpe=new Set(["token","complete","error","purpose_ack","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),Bpe=new Set(["session_started","turn_ready","token","iteration_tokens_usage","tool_request","tool_batch_request","tool_status","complete","error","mcp_tools_loaded","permission_request","permission_resolution","mcp_query_tools","mcp_tool_request","reasoning","reasoning_label","web_search_started","web_search_completed","follow_ups","task.step.updated","task.artifact.added"]),TR=new Set(["tool_request","tool_batch_request","mcp_tool_request"])});function Mpe(t,e){e?Fm.set(t,e):Fm.delete(t)}function Qi(t,e){e?DR.add(t):DR.delete(t)}function BG(t,e){e?xG.set(t,e):xG.delete(t)}function Ppe(t,e){Lpe.set(t,e)}function Fpe(t,e){return Lpe.get(t)?.(e)??!1}function Qpe(t){let e=Fm.get(t);e&&!e.attempted&&!e.blocked&&MG(t,"preflight_rejected"),e&&e.send({type:"session_prompt_complete",task_id:e.taskId,device_id:e.deviceId,prompt_id:e.promptId}),Fm.delete(t)}function MG(t,e){let r=Fm.get(t);r&&LG(r,e)}function LG(t,e){t.started||t.attempted||(t.blocked=!0,t.send({type:"session_prompt_execution",task_id:t.taskId,device_id:t.deviceId,prompt_id:t.promptId,execution_state:"not_run",execution_reason:e}))}var Fm,DR,xG,Fi,RR,NR,OR,si,Lpe,Ui=T(()=>{"use strict";Fm=new WeakMap,DR=new WeakSet,xG=new WeakMap,Fi=t=>Fm.get(t);RR=t=>DR.has(t);NR=t=>Fm.has(t)||DR.has(t),OR=t=>xG.get(t);si=class extends Error{retryable=!1;constructor(e){super(e),this.name="RemoteExecutionError"}},Lpe=new WeakMap});import{createHash as Not}from"node:crypto";function Fot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=e[0]??"",n=Oot.has(r)?2:1;return`bash:${e.slice(0,n).join(" ")}`}function Qot(t){let e=t.trim().split(/\s+/).filter(Boolean),r=0;for(;r<e.length&&(e[r]==="sudo"||e[r]==="env"||/^\w+=/.test(e[r]));)r++;let n=e[r]?e[r].split("/").pop()??"":"",s=e[r+1]??"";return!!(n==="xargs"||n==="make"||n==="git"&&s==="config"||(n==="docker"||n==="podman")&&(s==="run"||s==="exec"||s==="create")||n==="find"&&e.some(o=>Pot.includes(o)))}function Upe(t,e){return PG(t,e)===null}function PG(t,e){if(t!=="Bash")return null;let r=typeof e.command=="string"?e.command:"";return xot.test(r)?Mot.test(r)?"substitution":Lot.test(r)?"chained":"redirection":Bot.test(r)?"injection-flag":Qot(r)?"second-action":null}function Uot(t){try{return String(t)}catch{return"~unstringifiable"}}function w_(t,e){if(t===null)return"null";let r=typeof t;if(r==="undefined")return"~undef";if(r==="bigint")return`~big:${t.toString()}`;if(r==="number"){let n=t;return Number.isFinite(n)?JSON.stringify(n):`~num:${String(n)}`}if(r==="boolean"||r==="string")return JSON.stringify(t);if(r==="function"||r==="symbol")return`~${r}`;if(typeof t=="object"){let n=t;if(e.has(n))return"~cycle";e.add(n);try{if(Array.isArray(n))return`[${n.map(a=>w_(a,e)).join(",")}]`;let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)return n instanceof Map?`~map:[${[...n.entries()].map(([c,l])=>`${w_(c,e)}=>${w_(l,e)}`).sort().join(",")}]`:n instanceof Set?`~set:[${[...n.values()].map(c=>w_(c,e)).sort().join(",")}]`:`~exotic:${Object.prototype.toString.call(n)}:${Uot(n)}`;let o=Object.getOwnPropertySymbols(n).map(a=>a.toString()).sort().join(",");return`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${w_(n[a],e)}`).join(",")}${o?`|sym:${o}`:""}}`}finally{e.delete(n)}}return"~unknown"}function FG(t){return Not("sha256").update(w_(t??{},new WeakSet)).digest("hex").slice(0,16)}function QG(t,e,r,n){if(t==="Bash"){let s=typeof e.command=="string"?e.command:"";return Fot(s)}if(t==="Write"||t==="Edit"){let s=typeof e.file_path=="string"?e.file_path:"";if(!s)return`${t}:`;let o=Lt(s,r,n);return o.ok?`${t}:${Kn(o.resolved)}`:`${t}:invalid:${s}`}return`${t}:${FG(e)}`}function $pe(t,e,r,n){return t==="Bash"||t==="Write"||t==="Edit"?QG(t,e,r,n).replace(/^bash:/,""):`${t} (these exact arguments)`}var Oot,xot,Bot,Mot,Lot,Pot,UG=T(()=>{"use strict";Jn();Oot=new Set(["git","npm","yarn","pnpm","make","docker","env","sudo","xargs","find","ssh","bash","sh","node","python","python3"]),xot=/[;&|<>`\n]|\$\(/,Bot=/(^|\s)(-c|--config|-e|-o)(=|\s|$)/,Mot=/[`]|\$\(/,Lot=/[;&|\n]/,Pot=["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprintf"]});function xR(t){let e=t.findIndex(r=>r.value==="no");return e>=0?e:0}function $G(t,e){return t!==void 0&&t>=0&&t<e?t:0}function Gpe(t,e){return{selectedIndex:$G(t?.defaultIndex,t?.options?.length??e),scrollOffset:0,isScrollMode:!1,isFeedbackMode:!1,feedbackText:""}}var GG=T(()=>{"use strict"});var $ot,Got,Hot,Yot,qot,zot,Wot,Qm,BR,dp,HG=T(()=>{"use strict";we();$ot={name:"classic",label:"Classic",description:"Aii jellyfish blue-purple (default)",accentColorName:"#3B82F6",userInputTextColorName:"#93C5FD",colors:{accent:g.hex("#3B82F6"),userInput:g.hex("#3B82F6"),userInputText:g.hex("#93C5FD"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#A855F7"),link:g.hex("#3B82F6").underline,heading:g.hex("#A855F7").bold,filePath:g.hex("#3B82F6"),indicator:g.hex("#3B82F6")}},Got={name:"brand",label:"Brand",description:"aiiware.com official palette",accentColorName:"#4E6BF5",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#4E6BF5"),userInput:g.hex("#4E6BF5"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#4E6BF5"),link:g.hex("#4E6BF5").underline,heading:g.hex("#4E6BF5").bold,filePath:g.hex("#4E6BF5"),indicator:g.hex("#4E6BF5")}},Hot={name:"teal",label:"Teal",description:"Original teal accent",accentColorName:"#00BCD4",userInputTextColorName:"#67E8F9",colors:{accent:g.hex("#00BCD4"),userInput:g.hex("#00BCD4"),userInputText:g.hex("#67E8F9"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#00BCD4"),link:g.hex("#00BCD4").underline,heading:g.hex("#00BCD4").bold,filePath:g.hex("#00BCD4"),indicator:g.hex("#00BCD4")}},Yot={name:"indigo",label:"Indigo",description:"Bright periwinkle-blue",accentColorName:"#6B8AFF",userInputTextColorName:"#A5B4FC",colors:{accent:g.hex("#6B8AFF"),userInput:g.hex("#6B8AFF"),userInputText:g.hex("#A5B4FC"),success:g.hex("#28CA41"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#6B8AFF"),link:g.hex("#6B8AFF").underline,heading:g.hex("#6B8AFF").bold,filePath:g.hex("#6B8AFF"),indicator:g.hex("#6B8AFF")}},qot={name:"forest",label:"Forest",description:"Natural green",accentColorName:"#22C55E",userInputTextColorName:"#86EFAC",colors:{accent:g.hex("#22C55E"),userInput:g.hex("#22C55E"),userInputText:g.hex("#86EFAC"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#22C55E"),link:g.hex("#22C55E").underline,heading:g.hex("#22C55E").bold,filePath:g.hex("#22C55E"),indicator:g.hex("#22C55E")}},zot={name:"amber",label:"Amber",description:"Warm orange-gold",accentColorName:"#F59E0B",userInputTextColorName:"#FCD34D",colors:{accent:g.hex("#F59E0B"),userInput:g.hex("#F59E0B"),userInputText:g.hex("#FCD34D"),success:g.hex("#22C55E"),warning:g.hex("#EAB308"),error:g.hex("#EF4444"),muted:g.hex("#94A3B8"),dim:g.dim,code:g.hex("#F59E0B"),link:g.hex("#F59E0B").underline,heading:g.hex("#F59E0B").bold,filePath:g.hex("#F59E0B"),indicator:g.hex("#F59E0B")}},Wot={name:"grayscale",label:"Grayscale",description:"Accessible, no colors",accentColorName:"white",userInputTextColorName:"#CBD5E1",colors:{accent:g.reset,userInput:g.reset,userInputText:g.hex("#CBD5E1"),success:g.reset,warning:g.reset,error:g.bold,muted:g.dim,dim:g.dim,code:g.reset,link:g.underline,heading:g.bold,filePath:g.reset,indicator:g.bold}},Qm={classic:$ot,brand:Got,teal:Hot,indigo:Yot,forest:qot,amber:zot,grayscale:Wot},BR="classic",dp=["classic","brand","teal","indigo","forest","amber","grayscale"]});var Um={};de(Um,{BAND_STYLE_INFO:()=>Mb,BAND_STYLE_ORDER:()=>pp,DEFAULT_BAND_STYLE:()=>qG,ThemeManager:()=>Ua,getAccentColorName:()=>$e,getThemeColors:()=>J,getUserInputTextColorName:()=>v_,resolveBandBg:()=>k_});function k_(t,e){let r=Mb[t];if(r.blend===null)return Vot;let n=/^#[0-9a-fA-F]{6}$/.test(e)?e:"#8B98A9",s=parseInt(n.replace("#",""),16),o=r.blend,i=(a,c)=>Math.round(a*o+c*(1-o));return"#"+(i(s>>16&255,YG[0])<<16|i(s>>8&255,YG[1])<<8|i(s&255,YG[2])).toString(16).padStart(6,"0")}function J(){return Ua.getInstance().getColors()}function $e(){return Ua.getInstance().getAccentColorName()}function v_(){return Ua.getInstance().getUserInputTextColorName()}var pp,Mb,qG,YG,Vot,Ua,fp=T(()=>{"use strict";HG();ht();pp=["subtle","themed","neutral","bold"],Mb={subtle:{blend:.16,description:"Faint theme tint \u2014 quietest"},themed:{blend:.28,description:"Theme-tinted band (default)"},neutral:{blend:null,description:"Fixed neutral gray (theme-independent)"},bold:{blend:.4,description:"Strong theme tint \u2014 selection-like"}},qG="themed",YG=[20,22,27],Vot="#262C34";Ua=class t{static instance=null;activeTheme;bandStyle=null;constructor(){this.activeTheme=Qm[BR]}static getInstance(){return t.instance||(t.instance=new t),t.instance}getTheme(){return this.activeTheme}getColors(){return this.activeTheme.colors}getThemeName(){return this.activeTheme.name}setTheme(e){let r=Qm[e];if(!r){let n=dp.join(", ");throw new Error(`Unknown theme: "${e}". Available themes: ${n}`)}this.activeTheme=r}isValidTheme(e){return e in Qm}getAvailableThemes(){return dp.map(e=>Qm[e])}getAccentColorName(){return this.activeTheme.accentColorName}getUserInputTextColorName(){return this.activeTheme.userInputTextColorName}getBandStyle(){if(this.bandStyle)return this.bandStyle;try{let e=Te().get("theme_band");if(e&&this.isValidBandStyle(e))return this.bandStyle=e,this.bandStyle}catch{}return this.bandStyle=qG,this.bandStyle}setBandStyle(e){if(!this.isValidBandStyle(e))throw new Error(`Unknown band style: "${e}". Available: ${pp.join(", ")}`);this.bandStyle=e}isValidBandStyle(e){return pp.includes(e)}reset(){this.activeTheme=Qm[BR],this.bandStyle=null}}});var Yt=T(()=>{"use strict";HG();fp()});import{resolve as jot}from"path";function Kot(){let t=process.env.TERM??"",e=process.env.TERM_PROGRAM??"",r=process.env.COLORTERM??"",n=process.env.WT_SESSION??"",s=process.env.VSCODE_INJECTION??process.env.TERM_PROGRAM==="vscode";return process.stdout.isTTY?e==="iTerm.app"||e==="Hyper"||e==="vscode"||e==="WezTerm"||e==="Alacritty"||n||s||t.includes("xterm-256color")||t.includes("screen-256color")||t.includes("tmux")||t==="xterm-kitty"||r==="truecolor"?!0:t!=="dumb":!1}function Lb(){return zG===null&&(zG=Kot()),zG}function Jot(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Ype(){return Hpe||!Lb()?"":(Hpe=!0,` (${Jot()}+Click to open)`)}function Xot(t,e){return Lb()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function qpe(t,e,r){let n=process.env.HOME??process.env.USERPROFILE??"",s=t;n&&t.startsWith(n)&&(s="~"+t.slice(n.length));let o=r??(e?`${s}:${e}`:s);if(!Lb())return J().filePath(o);let i=J().accent(o),c=`file://${jot(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Xot(i,c)}var zG,Hpe,zpe=T(()=>{"use strict";Yt();zG=null,Hpe=!1});function Zot(t){return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=183984&&t<=191471||t>=196608&&t<=201551||t>=63744&&t<=64255||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12784&&t<=12799||t>=44032&&t<=55215||t>=4352&&t<=4607||t>=12592&&t<=12687||t>=65280&&t<=65519&&(t>=65281&&t<=65376||t>=65504&&t<=65510)||t>=12288&&t<=12351||t>=12800&&t<=13055||t>=13056&&t<=13311||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=128512&&t<=128591||t>=128640&&t<=128767||t>=129648&&t<=129791||t>=9984&&t<=10175||t>=9728&&t<=9983}function eit(t){return t<32&&t!==9||t===127||t>=768&&t<=879||t>=6832&&t<=6911||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65056&&t<=65071||t===8203||t===8204||t===8205||t===65279||t>=65024&&t<=65039||t>=917760&&t<=917999}function Sn(t){let e=t.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),r=0;for(let n of e){let s=n.codePointAt(0)??0;eit(s)||(Zot(s)?r+=2:r+=1)}return r}function Vc(t,e){if(e<=0)return"";let r=0,n="";for(let s of t){let o=Sn(s);if(r+o>e)break;n+=s,r+=o}return n}var $m=T(()=>{"use strict"});function VG(t){return t.replace(WG,"")}function tit(t){return t.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g," \u23CE ").replace(/\t+/g," ")}function $a(t){return VG(oe(tit(t??"")))}var WG,mp=T(()=>{"use strict";Mt();WG=/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/g});var Kpe={};de(Kpe,{VERSION:()=>Gm,colors:()=>F,formatCode:()=>dit,formatPath:()=>jpe,getActionIndicator:()=>uit,padEndAnsi:()=>hit,printDivider:()=>Vpe,printError:()=>cit,printExitSummary:()=>KG,printHeader:()=>lit,printSuccess:()=>iit,printToolResultCompact:()=>Ga,printWarning:()=>ait,shortenPath:()=>fit});function rit(t){return t.startsWith("/")||t.startsWith("~/")||t.startsWith("./")||t.startsWith("../")||/^[a-zA-Z]:\\/.test(t)||/\.(ts|tsx|js|jsx|json|md|py|go|rs|java|c|cpp|h|hpp|css|scss|html|xml|yaml|yml|toml|sh|bash|zsh)$/.test(t)||/^src\//.test(t)||/^lib\//.test(t)||/^test[s]?\//.test(t)}function oit(t){return sit.test(t)}function Ga(t,e,r=!0,n,s=console.log,o=!0,i=0,a=process.stdout){let c=r?F.success("\u25CF"):F.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=rit(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=$a(d),f=Sn(t)+6+i,m=Math.max(nit,(a.columns||80)-f),A=Sn(p)>m?Vc(p,m-1).replace(/\u200D+$/,"")+"\u2026":p,_=a===process.stdout?!0:a.isTTY===!0,E=u&&!oit(e)&&_;if(E){let C=e.match(/:(\d+)$/),w=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;A=jpe(k,w,A)}s(`${c} ${g.bold(t)}(${A})`);let y=o&&E?F.dim(Ype()):"",S=o&&!y&&!Wpe?F.dim(" (ctrl+o to expand)"):"";if(S&&(Wpe=!0),n){let C=r?F.dim:F.error;s(C(`\u2514 ${n}`)+y+S)}else{let C=r?"(No content)":"(Error)",w=r?F.dim:F.error;s(w(`\u2514 ${C}`)+y+S)}}function iit(t){console.log(F.success("\u2713 ")+t)}function ait(t){console.log(F.warning("\u26A0 ")+t)}function cit(t){console.log(F.error("\u2717 ")+t)}function Vpe(t=60){console.log(F.dim("\u2500".repeat(t)))}function lit(t){console.log(F.logo(t)),Vpe(t.length)}function uit(t){return F.thinking(`[${t}]`)}function jpe(t,e,r){if(Lb())return qpe(t,e,r);let n=process.env.HOME??process.env.USERPROFILE??"",s=t;return n&&t.startsWith(n)&&(s="~"+t.slice(n.length)),e&&(s+=`:${e}`),F.filePath(r??s)}function dit(t){return F.code(t)}function pit(){return process.stdout.columns||80}function fit(t,e=40){let r=process.env.HOME??process.env.USERPROFILE??"",n=t;if(r&&t.startsWith(r)&&(n="~"+t.slice(r.length)),n.length<=e)return n;let s=n.split("/").filter(i=>i.length>0);if(s.length>=2){let i=s.slice(-2).join("/");if(i.length<=e-4)return".../"+i}return".../"+(s[s.length-1]||s[s.length-2])}function mit(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hit(t,e){let r=mit(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function git(t){if(t<60)return`${t}s`;let e=Math.floor(t/60),r=t%60;return r>0?`${e}m ${r}s`:`${e}m`}function jG(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function KG(t){let e=pit(),r=Math.min(e-2,76),n=r-4,s=(A,_)=>{let E=A.replace(/\x1b\[[0-9;]*m/g,"").length;return A+" ".repeat(Math.max(0,_-E))},o=A=>F.border("\u2502")+" "+s(A,n)+" "+F.border("\u2502"),i=(A,_,E,y)=>{let S=Math.floor(n/2),C=F.dim(A.padEnd(15))+_,w=F.dim(E.padEnd(15))+y;return o(s(C,S)+w)},a=git(t.durationSeconds),c=jG(t.tokensIn),l=jG(t.tokensOut),u=`$${t.totalCost.toFixed(4)}`,d=t.cloud?`\u2601\uFE0F Cloud \xB7 ${t.model}`:`${t.provider}/${t.model.replace("claude-","").replace("-latest","")}`;console.log(""),console.log(F.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(o(F.logo("Session complete. \u{1FABC}"))),console.log(F.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(o(F.logo("Session Summary"))),console.log(o(F.dim("\u2500".repeat(15)))),console.log(i("Duration",a,"Tool Calls",t.toolCalls.toString())),console.log(i("Turns",t.turns.toString(),"Files Modified",t.filesModified.toString())),console.log(o("")),console.log(o(F.logo("Token Usage"))),console.log(o(F.dim("\u2500".repeat(11)))),console.log(i("Input",c,"Output",l));let p=t.cachedTokens??0;if(p>0){let A=Math.min(100,Math.round(100*p/Math.max(1,t.tokensIn)));console.log(o(F.dim("Cached".padEnd(15))+`${jG(p)} (${A}%)`))}let f=t.cacheSavings??0,m=f>0?F.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(o(F.dim("Cost".padEnd(15))+u+m)),console.log(o(""));let h=(A,_)=>A.length>_?`${A.slice(0,Math.max(0,_-1))}\u2026`:A;if(t.goalLine){let A=t.goalLine.replace(/^Goal:\s*/,"");console.log(o(F.dim("Goal: ")+h(A,n-6)))}t.goalResumeLine&&console.log(o(F.dim(h(` ${t.goalResumeLine}`,n)))),console.log(o(F.dim("Model: ")+F.model(d))),console.log(F.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var Gm,F,nit,sit,Wpe,Qr=T(()=>{"use strict";we();zpe();Yt();$m();mp();Gm="0.25.8",F={get logo(){return J().accent.bold},get prompt(){return J().accent.bold},get model(){return J().accent},get success(){return J().success},get warning(){return J().warning},get error(){return J().error},get thinking(){return J().dim},get filePath(){return J().filePath},get code(){return J().code},get muted(){return J().muted},get dim(){return J().dim},get safe(){return J().success},get risky(){return J().warning},get destructive(){return J().error},get border(){return J().accent},get bannerBorder(){return J().accent}};nit=24,sit=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Wpe=!1});var XG={};de(XG,{MAX_RETAINED_TOASTS:()=>JG,MAX_VISIBLE_TOASTS:()=>Pb,getNotificationStore:()=>ot,useNotificationStore:()=>Fn});import{create as Ait}from"zustand";function Jpe(t){return t.length<=JG?t:t.slice(-JG)}var Pb,JG,Fn,ot,jc=T(()=>{"use strict";Pb=5,JG=200;Fn=Ait((t,e)=>({toasts:[],nextId:1,showToast:(r,n=!1,s)=>{t(o=>{let i={id:o.nextId,text:r,persistent:n,expiresAt:s};if(!n){let c=o.toasts.filter(l=>l.persistent);return{toasts:Jpe([...c,i]),nextId:o.nextId+1}}let a=o.toasts.filter(c=>c.persistent);return{toasts:Jpe([...a,i]),nextId:o.nextId+1}})},clearToast:r=>{t(n=>r===void 0?{toasts:[]}:{toasts:n.toasts.filter(s=>s.id!==r)})},clearPersistent:()=>{t(r=>({toasts:r.toasts.filter(n=>!n.persistent)}))},clearFirstPersistent:()=>{t(r=>{let n=r.toasts.findIndex(s=>s.persistent);return n===-1?r:{toasts:[...r.toasts.slice(0,n),...r.toasts.slice(n+1)]}})},reset:()=>t({toasts:[],nextId:1}),visibleToasts:()=>e().toasts.slice(0,Pb),overflowCount:()=>Math.max(0,e().toasts.length-Pb)}));Object.defineProperty(Fn,"toast",{get:()=>{let t=Fn.getState().toasts;return t.length>0?t[t.length-1]:null}});ot=Fn.getState});var Zpe={};de(Zpe,{getUserEchoSink:()=>ZG,setUserEchoSink:()=>_it});function _it(t){Xpe=t}function ZG(){return Xpe}var Xpe,e8=T(()=>{"use strict";Xpe=null});import{create as Eit}from"zustand";var efe,Hm,MR=T(()=>{"use strict";jc();e8();efe=Eit((t,e)=>({pendingNote:null,pendingOrigin:"keyboard",noteToastId:null,setPendingNote:r=>t({pendingNote:r,pendingOrigin:"keyboard",onRemoteConsume:void 0}),offerRemoteNote:(r,n)=>e().pendingNote?!1:(t({pendingNote:r,pendingOrigin:"remote",onRemoteConsume:n}),!0),setNoteToastId:r=>t({noteToastId:r}),getPendingNote:()=>e().pendingNote,onNoteInjected:()=>{let r=e().pendingNote,n=e().pendingOrigin;r&&n==="remote"&&e().onRemoteConsume?.();let s=e().noteToastId;if(s!==null&&ot().clearToast(s),t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0}),r){let o=ZG();if(o)try{o(r,n)}catch{}}},reset:()=>t({pendingNote:null,noteToastId:null,pendingOrigin:"keyboard",onRemoteConsume:void 0})})),Hm=efe.getState});import{create as yit}from"zustand";var D_,cn,Ym=T(()=>{"use strict";D_=null,cn=yit((t,e)=>({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:null,begin:r=>{t({active:!0,startedAt:Date.now(),bgAgentCount:r,elapsedSec:0,lastRelease:null}),D_!==null&&clearInterval(D_),D_=setInterval(()=>{let n=e();!n.active||n.startedAt===null||t({elapsedSec:Math.floor((Date.now()-n.startedAt)/1e3)})},1e3)},release:r=>{D_!==null&&(clearInterval(D_),D_=null),t({active:!1,startedAt:null,bgAgentCount:0,elapsedSec:0,lastRelease:r})},setCount:r=>t({bgAgentCount:r})}))});var LR={};de(LR,{getUIStore:()=>yt,useUIStore:()=>bo});import{create as Cit}from"zustand";var tfe,bo,yt,hp=T(()=>{"use strict";tfe={mode:"welcome",agentMode:"normal",status:"",isThinking:!1,isStreaming:!1,currentIteration:0,iterationStartTime:Date.now(),iterationTokens:0,contextPercent:0,contextLevel:"normal",contextTokens:0,contextLimit:2e5,sessionCost:0,freeBudgetRemaining:null,freeBudgetResetAt:null,goalSegment:"",goalTurnActive:!1,sessionTokensIn:0,sessionCachedTokens:0,provider:"",model:"",reasoningEffort:"",openrouterProvider:"",connectionMode:"local",projectPath:process.cwd(),branch:void 0,worktreeName:void 0,baseBranch:void 0,soulName:"",personaName:"",toolsCount:0,mcpServersCount:0,mcpFailedCount:0,contextFilesCount:0,skillsCount:0,sessionStartTime:Date.now(),agentExecMs:0,agentTurnStartTime:null,renderEpoch:0,loopMode:!1,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0},bo=Cit(t=>({...tfe,setMode:e=>t({mode:e}),setAgentMode:e=>t({agentMode:e}),setStatus:e=>t({status:e}),setThinking:e=>t({isThinking:e}),setStreaming:e=>t(r=>{if(e&&!r.agentTurnStartTime)return{isStreaming:e,agentTurnStartTime:Date.now()};if(!e&&r.agentTurnStartTime){let n=Date.now()-r.agentTurnStartTime;return{isStreaming:e,agentExecMs:r.agentExecMs+n,agentTurnStartTime:null}}return{isStreaming:e}}),incrementIteration:()=>t(e=>({currentIteration:e.currentIteration+1,iterationStartTime:Date.now(),iterationTokens:0})),addIterationTokens:e=>t(r=>({iterationTokens:r.iterationTokens+e})),setIterationTokens:e=>t({iterationTokens:e}),updateContext:(e,r)=>{let n=r>0?Math.round(e/r*100):0,s=n>=90?"critical":n>=70?"warning":"normal";t({contextTokens:e,contextLimit:r,contextPercent:n,contextLevel:s})},updateSession:e=>t(e),updateResources:e=>t(e),setLoopMode:e=>t(e?{loopMode:e}:{loopMode:e,loopStartTime:null,loopMaxIterations:0,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0,loopPaused:!1,loopPauseUntil:null,loopDurationSeconds:0}),startLoop:(e,r)=>t({loopStartTime:e,loopMaxIterations:r,loopTotalInputTokens:0,loopTotalOutputTokens:0,loopCost:0,loopToolCalls:0,loopCurrentIteration:0}),updateLoopStats:(e,r,n,s)=>t({loopTotalInputTokens:e,loopTotalOutputTokens:r,loopCost:n,loopToolCalls:s}),setLoopIteration:e=>t({loopCurrentIteration:e}),setLoopPaused:(e,r)=>t({loopPaused:e,loopPauseUntil:r}),setLoopDurationSeconds:e=>t({loopDurationSeconds:e}),incrementRenderEpoch:()=>t(e=>({renderEpoch:e.renderEpoch+1})),reset:()=>t(tfe)})),yt=bo.getState});var Fb={};de(Fb,{getInputStore:()=>R_,useInputStore:()=>Xn});import{create as Sit}from"zustand";var rfe,bit,Iit,Xn,R_,gu=T(()=>{"use strict";we();jc();hp();rfe={lines:[""],cursorLine:0,cursorCol:0,typeAheadBuffer:"",isTypeAheadActive:!1,typeAheadQueue:[],history:[],historyIndex:-1,undoStack:[],redoStack:[]},bit=100,Iit=50,Xn=Sit((t,e)=>({...rfe,insertChar:r=>{e().saveSnapshot(),t(s=>{let o=[...s.lines],i=o[s.cursorLine];return o[s.cursorLine]=i.slice(0,s.cursorCol)+r+i.slice(s.cursorCol),{lines:o,cursorCol:s.cursorCol+r.length,redoStack:[]}})},deleteChar:()=>{let r=e();r.cursorCol===0&&r.cursorLine===0||(r.saveSnapshot(),t(n=>{let s=[...n.lines];if(n.cursorCol>0){let o=s[n.cursorLine];return s[n.cursorLine]=o.slice(0,n.cursorCol-1)+o.slice(n.cursorCol),{lines:s,cursorCol:n.cursorCol-1,redoStack:[]}}else if(n.cursorLine>0){let o=s[n.cursorLine-1],i=s[n.cursorLine];return s[n.cursorLine-1]=o+i,s.splice(n.cursorLine,1),{lines:s,cursorLine:n.cursorLine-1,cursorCol:o.length,redoStack:[]}}return n}))},newLine:()=>{e().saveSnapshot(),t(n=>{let s=[...n.lines],o=s[n.cursorLine],i=o.slice(0,n.cursorCol),a=o.slice(n.cursorCol);return s[n.cursorLine]=i,s.splice(n.cursorLine+1,0,a),{lines:s,cursorLine:n.cursorLine+1,cursorCol:0,redoStack:[]}})},moveCursor:r=>{t(n=>{switch(r){case"left":if(n.cursorCol>0)return{cursorCol:n.cursorCol-1};if(n.cursorLine>0)return{cursorLine:n.cursorLine-1,cursorCol:n.lines[n.cursorLine-1].length};break;case"right":if(n.cursorCol<n.lines[n.cursorLine].length)return{cursorCol:n.cursorCol+1};if(n.cursorLine<n.lines.length-1)return{cursorLine:n.cursorLine+1,cursorCol:0};break;case"up":if(n.cursorLine>0){let s=n.cursorLine-1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break;case"down":if(n.cursorLine<n.lines.length-1){let s=n.cursorLine+1,o=Math.min(n.cursorCol,n.lines[s].length);return{cursorLine:s,cursorCol:o}}break}return n})},setText:r=>{let n=r.split(`
|
|
356
356
|
`);t({lines:n,cursorLine:n.length-1,cursorCol:n[n.length-1].length,undoStack:[],redoStack:[]})},clear:()=>{t({lines:[""],cursorLine:0,cursorCol:0,undoStack:[],redoStack:[]})},saveSnapshot:()=>{t(r=>{let n={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol},s=[...r.undoStack,n];return s.length>Iit&&s.shift(),{undoStack:s}})},undo:()=>{t(r=>{if(r.undoStack.length===0)return r;let n=[...r.undoStack],s=n.pop(),o={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol};return{lines:s.lines,cursorLine:s.cursorLine,cursorCol:s.cursorCol,undoStack:n,redoStack:[...r.redoStack,o]}})},redo:()=>{t(r=>{if(r.redoStack.length===0)return r;let n=[...r.redoStack],s=n.pop(),o={lines:[...r.lines],cursorLine:r.cursorLine,cursorCol:r.cursorCol};return{lines:s.lines,cursorLine:s.cursorLine,cursorCol:s.cursorCol,undoStack:[...r.undoStack,o],redoStack:n}})},appendTypeAhead:r=>{t(n=>({typeAheadBuffer:n.typeAheadBuffer+r}))},getAndClearTypeAhead:()=>{let r=e().typeAheadBuffer;return t({typeAheadBuffer:""}),r},setTypeAheadActive:r=>{t({isTypeAheadActive:r})},enqueueTypeAhead:r=>{let n=e(),s=n.lines.join(`
|
|
357
357
|
`);if(s.trim()&&(n.addToHistory(s),t(o=>({typeAheadQueue:[...o.typeAheadQueue,{text:s,origin:"keyboard"}],lines:[""],cursorLine:0,cursorCol:0,undoStack:[],redoStack:[]})),!r?.silent)){let o=bo.getState().loopMode,i=o?"\u25C6 Queued for next iteration (/note injects now): ":"\u25C6 Queued: ",a=o?52:12,c=process.stdout.columns||80,l=Math.max(12,Math.floor(c*.618)-a),u=s.replace(/\n/g," "),d=u.length>l?u.slice(0,l)+"\u2026":u;Fn.getState().showToast(g.green(`${i}"${d}"`),!0)}},setRemoteDropHandler:r=>t({remoteDropHandler:r}),enqueueRemote:r=>e().typeAheadQueue.filter(n=>n.origin==="remote").length>=128?!1:(t(n=>({typeAheadQueue:[...n.typeAheadQueue,r]})),!0),dropRemote:(r,n="ctrl_x")=>{let s=e().typeAheadQueue.find(o=>o.origin==="remote"&&(!r||o.promptId===r));return s?(t(o=>({typeAheadQueue:o.typeAheadQueue.filter(i=>i!==s)})),e().remoteDropHandler?.(s,n),!0):!1},dropAllRemote:r=>{let n=e().typeAheadQueue.filter(s=>s.origin==="remote");t(s=>({typeAheadQueue:s.typeAheadQueue.filter(o=>o.origin!=="remote")}));for(let s of n)e().remoteDropHandler?.(s,r)},dequeueTypeAhead:()=>{let r=e().typeAheadQueue;if(r.length===0)return null;let[n,...s]=r;return t({typeAheadQueue:s}),n},hasQueuedMessages:()=>e().typeAheadQueue.length>0,clearTypeAheadQueue:(r="ctrl_u")=>{e().dropAllRemote(r),t({typeAheadQueue:[]}),Fn.getState().clearPersistent()},historyUp:()=>{t(r=>{if(r.history.length===0)return r;let n=r.historyIndex===-1?r.history.length-1:Math.max(0,r.historyIndex-1),o=r.history[n].split(`
|
|
358
358
|
`);return{historyIndex:n,lines:o,cursorLine:o.length-1,cursorCol:o[o.length-1].length}})},historyDown:()=>{t(r=>{if(r.historyIndex===-1)return r;let n=r.historyIndex+1;if(n>=r.history.length)return{historyIndex:-1,lines:[""],cursorLine:0,cursorCol:0};let o=r.history[n].split(`
|
|
@@ -4292,7 +4292,7 @@ User: ${e}`}async function FUt(t,e,r){if(t.authType==="oauth_bearer"){let o=Ma(t
|
|
|
4292
4292
|
`))):(console.log(` Connection: ${g.red("Unreachable")} (${e})`),console.log(g.gray(` The cloud could not be reached. Try again shortly.
|
|
4293
4293
|
`))),process.exitCode=1}}function z$e(){console.log(g.bold(`
|
|
4294
4294
|
aii cloud \u2014 manage your account and workspaces
|
|
4295
|
-
`)),console.log(" aii cloud login Sign in to AiiCloud (verifies an existing sign-in;"),console.log(" --force re-authenticates)"),console.log(" aii cloud status Show connection + credit balance"),console.log(" aii cloud workspace list | add <path> | remove <label|path>"),console.log(g.gray("\n Start `aii --remote-control` to continue a conversation in AiiCloud\n and host new web conversations while Aii is running.\n Choose inference independently with `--inference cloud|server`.\n"))}var YK=T(()=>{"use strict";we();Mc();Si();I$e();lC();k$e();R$e();tK();G$e();Y$e();pC();Ti();Pa();UL()});var j$e={};de(j$e,{handleUpgrade:()=>o9t});import{execSync as r9t,execFileSync as n9t}from"node:child_process";async function o9t(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!s9t.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.
|
|
4295
|
+
`)),console.log(" aii cloud login Sign in to AiiCloud (verifies an existing sign-in;"),console.log(" --force re-authenticates)"),console.log(" aii cloud status Show connection + credit balance"),console.log(" aii cloud workspace list | add <path> | remove <label|path>"),console.log(g.gray("\n Start `aii --remote-control` to continue a conversation in AiiCloud\n and host new web conversations while Aii is running.\n Choose inference independently with `--inference cloud|server`.\n"))}var YK=T(()=>{"use strict";we();Mc();Si();I$e();lC();k$e();R$e();tK();G$e();Y$e();pC();Ti();Pa();UL()});var j$e={};de(j$e,{handleUpgrade:()=>o9t});import{execSync as r9t,execFileSync as n9t}from"node:child_process";async function o9t(t){let e=t.subcommand??t.args[0]??null;if(e!==null&&e!=="latest"&&!s9t.test(e))throw new Error(`Invalid version '${e}' \u2014 expected e.g. 0.23.3`);let r=e==="latest"?null:e,n="0.25.8",s=r?`${V$e}@${r}`:`${V$e}@latest`;console.log(""),console.log(r?`Upgrading Aii CLI to v${r}...`:"Upgrading Aii CLI to latest..."),console.log(` Current version: ${n}`),console.log("");try{let o=process.platform==="win32"?"npm.cmd":"npm",i=n9t(o,["install","-g",s],{encoding:"utf-8",timeout:12e4,stdio:"pipe"});i.trim()&&console.log(i.trim())}catch(o){let i=o,a=o instanceof Error?`${String(i.stdout??"")}
|
|
4296
4296
|
${String(i.stderr??"")}`.trim():"";a.trim()&&console.error(a.trim()),/ETARGET|notarget/i.test(a)?console.error(`
|
|
4297
4297
|
That version is not on your npm mirror yet \u2014 freshly published versions can take a
|
|
4298
4298
|
minute or two to replicate. Wait a moment and re-run: aii upgrade`):/EACCES|EPERM|permission denied/i.test(a)?console.error(`
|
|
@@ -4321,7 +4321,7 @@ Upgrade failed.`),console.error(` Manual: npm install -g ${s}`),process.exit(1)
|
|
|
4321
4321
|
${t}
|
|
4322
4322
|
</context>
|
|
4323
4323
|
|
|
4324
|
-
${e}`:e}fm();var Bv=[{name:"config",tier:De.LOCAL},{name:"help",tier:De.LOCAL},{name:"version",tier:De.LOCAL},{name:"doctor",tier:De.LOCAL},{name:"mcp",tier:De.LOCAL},{name:"prompt",tier:De.LOCAL},{name:"stats",tier:De.LOCAL},{name:"history",tier:De.LOCAL},{name:"query",tier:De.SERVER},{name:"chat",tier:De.SERVER},{name:"run",tier:De.SERVER},{name:"agent",tier:De.SERVER},{name:"loop",tier:De.SERVER},{name:"telegram",tier:De.SERVER},{name:"sessions",tier:De.LOCAL},{name:"goals",tier:De.LOCAL},{name:"install",tier:De.LOCAL},{name:"worktree",tier:De.LOCAL},{name:"soul",tier:De.LOCAL},{name:"skill",tier:De.LOCAL},{name:"plugin",tier:De.LOCAL},{name:"persona",tier:De.LOCAL},{name:"cloud",tier:De.LOCAL},{name:"login",tier:De.LOCAL},{name:"upgrade",tier:De.LOCAL}];function QJe(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==De.LOCAL&&r.tier!==De.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var UJe=QJe(Bv);function Aae(t){return UJe.get(t)?.tier}var w4t=Object.fromEntries(Bv.map(t=>[t.name,t.tier]));function _ae(t,e){let r=t.slice(0,2),n,s,o,i;for(let a=2;a<t.length;a++){let c=t[a],[l]=c.split("=",1);if(c==="--"){r.push(...t.slice(a));break}if(l==="--remote"||l==="--local")throw new Error(`${l} was removed. Use ${l==="--remote"?"--remote-control":"--inference server"}.`);if(l==="--remote-control"){if(c!==l)throw new Error("--remote-control does not take a value.");o=!0;continue}if(l==="--inference"){let u=c.includes("=")?c.slice(c.indexOf("=")+1):t[++a];if(u!=="cloud"&&u!=="server")throw new Error("--inference must be cloud or server.");if(s&&s!==u)throw new Error("Choose one --inference backend.");s=u;continue}if(e.has(l)){r.push(c),!c.includes("=")&&a+1<t.length&&r.push(t[++a]);continue}if(!c.startsWith("-"))if(n){if(n==="cloud"){if(c==="connect")throw new Error("aii cloud connect was removed. Start aii --remote-control; inference is selected independently with --inference cloud|server.");n="cloud-action"}else if(n==="run"){if(c==="git"&&["commit","pr"].includes(t[a+1])){r.push(c,t[++a]),n="owned-operation";continue}r.push(...t.slice(a));break}else if(i)throw new Error("Resume the session first, then type your prompt.")}else{if(n=c,n==="mcp"){r.push(...t.slice(a));break}if(n==="resume"){let u=t[++a];if(!u||!/^[A-Za-z0-9_-][A-Za-z0-9_.-]{3,63}$/.test(u)||u.includes(".."))throw new Error("Usage: aii resume <exact-session-id> [--remote-control]");i=u;continue}}r.push(c)}return{argv:r,inference:s,remoteControl:o,resumeId:i}}var yae=new Set(Bv.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),$Je="0.25.7",GJe=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--trust-source","--offline","-D","--direct","-i","--interactive","-c","--continue-chat","-n","--new-chat","--auto","--auto-background-timeout","--no-colors","--colors","--no-emojis","--emojis","--no-animations","--animations","--no-streaming","--streaming","--show-tokens","--show-cost","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--bare","--show-tools","--append-system-prompt","--append-system-prompt-file","--reconnect-window","--continue","--signature","--no-signature","--no-project-config","--project-config","--inference","--remote-control","-h","--help","-V","--version"]),VA=new Set(["--inference","--model","--openrouter-provider","--host","-c","--continue-chat","--auto-background-timeout","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--append-system-prompt","--append-system-prompt-file","--signature","--reconnect-window"]);function HJe(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(n==="--"){e.push(...t.slice(r+1));break}let s=n.indexOf("="),o=s>0?n.slice(0,s):n;if(GJe.has(o)){s===-1&&VA.has(o)&&r++;continue}e.push(n)}return e}var Eae=/^[a-z0-9_]{2,40}$/i;function Cae(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return r}}function YJe(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&VA.has(t[e])&&e++}return-1}function qJe(t){for(let e=0;e<t.length;e++){let r=t[e];if(r==="--")return e+1<t.length;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return!0}return!1}function zJe(t){let e=Cae(t);if(e!==void 0&&e!=="agent"&&yae.has(e))return{argv:t};let r=t.slice(0,2),n,s;for(let o=2;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(VA.has(i.split("=",1)[0])){r.push(i),!i.includes("=")&&o+1<t.length&&r.push(t[++o]);continue}if(i==="--continue"){r.push(i);let a=t[o+1];n===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&Eae.test(a)&&(qJe(t.slice(o+2))?s=`--continue ${a} \u2026: ambiguous \u2014 quote the text (aii --continue "${a} \u2026") to run it as a prompt, or run \`aii --continue ${a}\` alone to resume that session.`:(n=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);r.push("--continue"),Eae.test(a)?n===void 0&&(n=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}r.push(i)}return{argv:r,continueId:n,error:s}}function WJe(t){if(t===void 0)return;let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`Invalid --max-turns "${t}": expected a non-negative integer`);return e}function VJe(t){if(t===void 0)return;let e=/^\d+$/.test(t.trim())?Number(t.trim()):NaN;if(!Number.isInteger(e)||e<0||e>3600){let r=t.replace(/[\x00-\x1F\x7F-\x9F]/g,"").slice(0,40);throw new Error(`Invalid --reconnect-window "${r}": expected an integer 0\u20133600 (seconds)`)}return e}function Sae(t){if(t===void 0)return;let e=t.trim();if(!/^\d+$/.test(e))return;let r=Number(e);return Number.isInteger(r)&&r>=0&&r<=3600?r:void 0}function jJe(t){if(t===void 0)return;let e=Number(t);if(!Number.isFinite(e)||e<0)throw new Error(`Invalid --max-budget-usd "${t}": expected a non-negative number`);return e}function KJe(){let t=new hae;return t.name("aii").description("AI-powered CLI assistant").version($Je,"-V, --version","Show version number").helpOption(!1).enablePositionalOptions().argument("[query...]","Natural language query").option("--clean","Clean output mode (just the result)").option("--standard","Standard output mode (result + metrics)").option("--thinking","Currently identical to --standard \u2014 no extra reasoning is surfaced").option("-v, --verbose","--thinking plus an end-of-run token/cost/tool line (one-shot agent runs)").option("-d, --debug","Debug output").option("--model <model>","Override LLM model (e.g., ollama/llama3.1:8b, deepseek/deepseek-chat)").option("--openrouter-provider <slug>","Pin OpenRouter requests to a specific backend provider").option("--host <host>","Local server host:port for one-shot, -i chat, run git and prompt lanes; also opts out of AiiCloud").option("--inference <backend>","Inference backend: cloud or configured server").option("--remote-control","Continue this conversation in AiiCloud and host new web conversations").option("-y, --yes","Auto-confirm shell commands (does NOT authorise installing third-party code \u2014 use --trust-source)").option("--trust-source","Accept installing third-party code from the named source (skills, plugins and personas)").option("--offline","Skip MCP servers for this run (web tools stay available)").option("-D, --direct","Direct mode (bypass server intent recognition)").option("-i, --interactive","Force agent mode (default with no query; with a query it is still a one-shot run)").option("-c, --continue-chat <id>","DEPRECATED \u2014 no effect; the id is discarded. Use --continue <id>").option("-n, --new-chat","DEPRECATED \u2014 no effect. Use /new in-session").option("--auto","Auto-approve tool prompts (write fence, sensitive-path reads and project deny rules still apply)").option("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip this repo's config, slash commands, skills, agents and instruction files for this session: .aii/settings.json + settings.local.json (and their deny rules), project slash commands, project skills, project .aii/agents, and AGENTS.md / AII.md / CLAUDE.md. Does NOT cover .aii/hooks.json or .aii/soul.").option("--no-colors","Disable colored output (one-shot + command output; the interactive agent UI is unaffected)").option("--no-emojis","Disable emoji icons (one-shot + command output; the interactive agent UI is unaffected)").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--show-cost","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of BUILT-IN tools (comma-separated, e.g., "Read,Bash,Edit"); MCP and subagent tools are not filtered').option("--exclude-tools <list>",'Exclude BUILT-IN tools (comma-separated, e.g., "WebSearch,WebFetch"); --tools wins if both are given').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--reconnect-window <seconds>","One-shot runs: retry dropped connections for up to N seconds (default 0 = fail fast)").option("--max-budget-usd <amount>","Interactive sessions: stop before a NEW turn once cumulative est. cost reaches $amount (does not pre-empt a turn in progress)").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--show-tools","With --bare or --output-format: write the tool transcript to stderr (stdout untouched)").option("--append-system-prompt <text>","Append additive instructions to this run").option("--append-system-prompt-file <path>","Append a workspace file of additive instructions to this run").option("--continue","Resume the most recent local session of this project (conversation + goal)").option("-h, --help","Show help"),t.command("config").description("Configuration management").argument("[action]","Action: init, show, validate, set").argument("[key]","Config key (for set)").argument("[value]","Config value (for set)").allowUnknownOption().helpOption(!1).action(()=>{}),t.command("mcp").description("MCP server management").argument("[action]","Action: list, add, remove, status, etc.").argument("[rest...]","Server name and arguments").passThroughOptions().action(()=>{}),t.command("prompt").description("Prompt library").argument("[action]","Action: list, show, use, create").argument("[rest...]","Prompt name and arguments").allowUnknownOption().action(()=>{}),t.command("stats").description("Usage statistics").argument("[type]","Type: models, cost").action(()=>{}),t.command("history").description("Chat history").argument("[action]","Action: list, search, export, delete").argument("[query]","Search query or ID").action(()=>{}),t.command("doctor").description("System health check").action(()=>{}),t.command("install [target...]").description("Install or update Aii CLI, skills, or MCP servers").allowUnknownOption().helpOption(!1).action(()=>{}),t.command("chat").description("Interactive chat mode").action(()=>{}),t.command("agent").description("Interactive agent mode with tool execution").argument("[query...]","Optional query (non-interactive if provided)").action(()=>{}),t.command("loop").description("Autonomous agent loop (Ralph Wiggum pattern)").argument("[args...]","Loop arguments (prompt, --max, --verify, --budget, etc.)").allowUnknownOption().action(()=>{}),t.command("telegram").description("Telegram bot channel (chat with Aii from Telegram)").argument("[action]","Action: start, pair, status, unpair").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("sessions").description("Browse saved conversations (list, info); use server for server-managed sessions").argument("[action]","Action: list, info, server").argument("[args...]","Additional arguments (session ID, name, etc.)").allowUnknownOption().action(()=>{}),t.command("goals").description("List goals across this project's local sessions (pick one up with --continue <id>)").action(()=>{}),t.command("worktree").description("Manage git worktrees for isolated development").argument("[action]","Action: create, list, remove, clean").argument("[name]","Worktree name (for create/remove)").allowUnknownOption().action(()=>{}),t.command("soul").description("Manage agent soul (personality & identity)").argument("[action]","Action: switch, show").argument("[name]","Soul name (for switch)").allowUnknownOption().action(()=>{}),t.command("cloud").description("Manage AiiCloud account and workspaces; use aii --remote-control for web control").argument("[action]","Action: login, status, workspace, help").allowUnknownOption().action(()=>{}),t.command("login").description("Sign in to an AI provider with your subscription (e.g., xAI SuperGrok)").argument("[args...]","Flags: --provider <name>, --status, --logout").allowUnknownOption().action(()=>{}),t.command("skill").description("Manage AI skills").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("plugin").description("Manage skill plugins").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("persona").description("Manage workspace personas").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("upgrade").description("Update Aii CLI to latest version").argument("[version]","Target version (default: latest)").action(()=>{}),t.command("run").description("Run domain-specific operations").argument("<operation>","Operation (e.g., git commit)").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("help").description("display help for command").argument("[command]","Command to show help for").action(()=>{}),t.command("version").description("Show version number").action(()=>{}),t}async function bae(t){let e=_ae(t,VA),r=zJe(e.argv),n=r.argv,s=YJe(n),o=s>=0&&Cae(n)===void 0?n.slice(0,s):n,i=KJe();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&yae.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof j9&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof j9&&m.code==="commander.help"))throw m;l=HJe(n.slice(2))}let u=i.opts(),d={clean:u.clean??!1,standard:u.standard??!1,thinking:u.thinking??!1,verbose:u.verbose??!1,debug:u.debug??!1,model:u.model,host:u.host,inference:e.inference,remoteControl:e.remoteControl??!1,openrouterProvider:u.openrouterProvider,yes:u.yes??!1,trustSource:u.trustSource??!1,offline:u.offline??!1,direct:u.direct??!1,interactive:u.interactive??!1,continueChat:u.continueChat,newChat:u.newChat??!1,auto:u.auto??!1,quiet:!1,noProjectConfig:u.projectConfig===!1,autoBackgroundTimeout:(()=>{let m=parseInt(u.autoBackgroundTimeout??"120",10);return isNaN(m)||m===0?0:Math.max(30,Math.min(600,m))*1e3})(),noColors:!u.colors,noEmojis:!u.emojis,noAnimations:!u.animations,noStreaming:!u.streaming,showTools:u.showTools??!1,showTokens:u.showTokens??!1,showCost:u.showCost??!1,outputFormat:u.outputFormat,tools:u.tools,excludeTools:u.excludeTools,maxTurns:WJe(u.maxTurns),maxBudgetUsd:jJe(u.maxBudgetUsd),reconnectWindow:VJe(u.reconnectWindow),bare:u.bare??!1,appendSystemPrompt:u.appendSystemPrompt,appendSystemPromptFile:u.appendSystemPromptFile,continue:u.continue??!1,continueId:e.resumeId??r.continueId,continueIdError:r.error,help:u.help??!1,version:u.version??!1},p;K9()&&(p=await gae()),(a==="chat"||d.interactive)&&(a="agent"),a==="query"&&!l.length&&!p&&(a="agent");let f;if(a==="query"&&l.length>0)f=l.join(" ");else if(a==="agent"){let m=[];c&&m.push(c),l.length>0&&m.push(...l),m.length>0&&(f=m.join(" "))}return{command:a,subcommand:c,args:l,flags:d,stdinContent:p,query:f}}Pv();fm();function Tae(t){let e=Aae(t.command)??De.SERVER;switch(t.command){case"config":return JJe(t);case"mcp":return XJe(t);case"prompt":return ZJe(t);case"stats":return eXe(t);case"history":return tXe(t);case"doctor":return{tier:De.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:De.LOCAL,handler:"goals",params:{}};case"install":return{tier:De.LOCAL,handler:"install",params:{}};case"chat":return{tier:De.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return nXe(t);case"agent":return{tier:De.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:De.SERVER,handler:"loop",params:{}};case"telegram":return{tier:De.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:De.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:De.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:De.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:De.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:De.LOCAL,handler:"login",params:{}};case"skill":return{tier:De.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:De.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:De.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:De.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:De.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:De.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function JJe(t){let e=t.subcommand??t.args[0]??"show";return{tier:De.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function XJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function ZJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function eXe(t){let e=t.subcommand??t.args[0];return{tier:De.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function tXe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var rXe=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function nXe(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(rXe.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:De.SERVER,handler:"run",params:{operation:n}}}fm();ht();YD();Pa();ti();we();fm();ih();import{createInterface as qFt}from"readline";import{spawn as zFt}from"child_process";we();import ML from"node:process";import EFe from"node:process";import OL from"node:process";var EMt=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let s=Object.getOwnPropertyDescriptor(t,r),o=Object.getOwnPropertyDescriptor(e,r);!yMt(s,o)&&n||Object.defineProperty(t,r,o)},yMt=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},CMt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},SMt=(t,e)=>`/* Wrapped ${t}*/
|
|
4324
|
+
${e}`:e}fm();var Bv=[{name:"config",tier:De.LOCAL},{name:"help",tier:De.LOCAL},{name:"version",tier:De.LOCAL},{name:"doctor",tier:De.LOCAL},{name:"mcp",tier:De.LOCAL},{name:"prompt",tier:De.LOCAL},{name:"stats",tier:De.LOCAL},{name:"history",tier:De.LOCAL},{name:"query",tier:De.SERVER},{name:"chat",tier:De.SERVER},{name:"run",tier:De.SERVER},{name:"agent",tier:De.SERVER},{name:"loop",tier:De.SERVER},{name:"telegram",tier:De.SERVER},{name:"sessions",tier:De.LOCAL},{name:"goals",tier:De.LOCAL},{name:"install",tier:De.LOCAL},{name:"worktree",tier:De.LOCAL},{name:"soul",tier:De.LOCAL},{name:"skill",tier:De.LOCAL},{name:"plugin",tier:De.LOCAL},{name:"persona",tier:De.LOCAL},{name:"cloud",tier:De.LOCAL},{name:"login",tier:De.LOCAL},{name:"upgrade",tier:De.LOCAL}];function QJe(t){let e=new Map;for(let r of t){if(!r.name)throw new Error("CLI command descriptor is missing a name");if(r.tier!==De.LOCAL&&r.tier!==De.SERVER)throw new Error(`CLI command "${r.name}" has an invalid tier: ${String(r.tier)}`);for(let n of[r.name,...r.aliases??[]]){if(e.has(n))throw new Error(`Duplicate CLI command name/alias: "${n}"`);e.set(n,r)}}return e}var UJe=QJe(Bv);function Aae(t){return UJe.get(t)?.tier}var w4t=Object.fromEntries(Bv.map(t=>[t.name,t.tier]));function _ae(t,e){let r=t.slice(0,2),n,s,o,i;for(let a=2;a<t.length;a++){let c=t[a],[l]=c.split("=",1);if(c==="--"){r.push(...t.slice(a));break}if(l==="--remote"||l==="--local")throw new Error(`${l} was removed. Use ${l==="--remote"?"--remote-control":"--inference server"}.`);if(l==="--remote-control"){if(c!==l)throw new Error("--remote-control does not take a value.");o=!0;continue}if(l==="--inference"){let u=c.includes("=")?c.slice(c.indexOf("=")+1):t[++a];if(u!=="cloud"&&u!=="server")throw new Error("--inference must be cloud or server.");if(s&&s!==u)throw new Error("Choose one --inference backend.");s=u;continue}if(e.has(l)){r.push(c),!c.includes("=")&&a+1<t.length&&r.push(t[++a]);continue}if(!c.startsWith("-"))if(n){if(n==="cloud"){if(c==="connect")throw new Error("aii cloud connect was removed. Start aii --remote-control; inference is selected independently with --inference cloud|server.");n="cloud-action"}else if(n==="run"){if(c==="git"&&["commit","pr"].includes(t[a+1])){r.push(c,t[++a]),n="owned-operation";continue}r.push(...t.slice(a));break}else if(i)throw new Error("Resume the session first, then type your prompt.")}else{if(n=c,n==="mcp"){r.push(...t.slice(a));break}if(n==="resume"){let u=t[++a];if(!u||!/^[A-Za-z0-9_-][A-Za-z0-9_.-]{3,63}$/.test(u)||u.includes(".."))throw new Error("Usage: aii resume <exact-session-id> [--remote-control]");i=u;continue}}r.push(c)}return{argv:r,inference:s,remoteControl:o,resumeId:i}}var yae=new Set(Bv.filter(t=>t.name!=="query").flatMap(t=>[t.name,...t.aliases??[]])),$Je="0.25.8",GJe=new Set(["--clean","--standard","--thinking","-v","--verbose","-d","--debug","--model","--openrouter-provider","--host","-y","--yes","--trust-source","--offline","-D","--direct","-i","--interactive","-c","--continue-chat","-n","--new-chat","--auto","--auto-background-timeout","--no-colors","--colors","--no-emojis","--emojis","--no-animations","--animations","--no-streaming","--streaming","--show-tokens","--show-cost","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--bare","--show-tools","--append-system-prompt","--append-system-prompt-file","--reconnect-window","--continue","--signature","--no-signature","--no-project-config","--project-config","--inference","--remote-control","-h","--help","-V","--version"]),VA=new Set(["--inference","--model","--openrouter-provider","--host","-c","--continue-chat","--auto-background-timeout","--output-format","--tools","--exclude-tools","--max-turns","--max-budget-usd","--append-system-prompt","--append-system-prompt-file","--signature","--reconnect-window"]);function HJe(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(n==="--"){e.push(...t.slice(r+1));break}let s=n.indexOf("="),o=s>0?n.slice(0,s):n;if(GJe.has(o)){s===-1&&VA.has(o)&&r++;continue}e.push(n)}return e}var Eae=/^[a-z0-9_]{2,40}$/i;function Cae(t){for(let e=2;e<t.length;e++){let r=t[e];if(r==="--")return;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return r}}function YJe(t){for(let e=2;e<t.length;e++){if(t[e]==="--")return e;!t[e].includes("=")&&VA.has(t[e])&&e++}return-1}function qJe(t){for(let e=0;e<t.length;e++){let r=t[e];if(r==="--")return e+1<t.length;if(r.startsWith("-")){!r.includes("=")&&VA.has(r)&&e++;continue}return!0}return!1}function zJe(t){let e=Cae(t);if(e!==void 0&&e!=="agent"&&yae.has(e))return{argv:t};let r=t.slice(0,2),n,s;for(let o=2;o<t.length;o++){let i=t[o];if(i==="--"){r.push(...t.slice(o));break}if(VA.has(i.split("=",1)[0])){r.push(i),!i.includes("=")&&o+1<t.length&&r.push(t[++o]);continue}if(i==="--continue"){r.push(i);let a=t[o+1];n===void 0&&s===void 0&&a!==void 0&&!a.startsWith("-")&&Eae.test(a)&&(qJe(t.slice(o+2))?s=`--continue ${a} \u2026: ambiguous \u2014 quote the text (aii --continue "${a} \u2026") to run it as a prompt, or run \`aii --continue ${a}\` alone to resume that session.`:(n=a,o++));continue}if(i.startsWith("--continue=")){let a=i.slice(11);r.push("--continue"),Eae.test(a)?n===void 0&&(n=a):s=`--continue=${a}: not a session id (2-40 letters/digits/underscores). \`aii goals\` lists this project's sessions.`;continue}r.push(i)}return{argv:r,continueId:n,error:s}}function WJe(t){if(t===void 0)return;let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error(`Invalid --max-turns "${t}": expected a non-negative integer`);return e}function VJe(t){if(t===void 0)return;let e=/^\d+$/.test(t.trim())?Number(t.trim()):NaN;if(!Number.isInteger(e)||e<0||e>3600){let r=t.replace(/[\x00-\x1F\x7F-\x9F]/g,"").slice(0,40);throw new Error(`Invalid --reconnect-window "${r}": expected an integer 0\u20133600 (seconds)`)}return e}function Sae(t){if(t===void 0)return;let e=t.trim();if(!/^\d+$/.test(e))return;let r=Number(e);return Number.isInteger(r)&&r>=0&&r<=3600?r:void 0}function jJe(t){if(t===void 0)return;let e=Number(t);if(!Number.isFinite(e)||e<0)throw new Error(`Invalid --max-budget-usd "${t}": expected a non-negative number`);return e}function KJe(){let t=new hae;return t.name("aii").description("AI-powered CLI assistant").version($Je,"-V, --version","Show version number").helpOption(!1).enablePositionalOptions().argument("[query...]","Natural language query").option("--clean","Clean output mode (just the result)").option("--standard","Standard output mode (result + metrics)").option("--thinking","Currently identical to --standard \u2014 no extra reasoning is surfaced").option("-v, --verbose","--thinking plus an end-of-run token/cost/tool line (one-shot agent runs)").option("-d, --debug","Debug output").option("--model <model>","Override LLM model (e.g., ollama/llama3.1:8b, deepseek/deepseek-chat)").option("--openrouter-provider <slug>","Pin OpenRouter requests to a specific backend provider").option("--host <host>","Local server host:port for one-shot, -i chat, run git and prompt lanes; also opts out of AiiCloud").option("--inference <backend>","Inference backend: cloud or configured server").option("--remote-control","Continue this conversation in AiiCloud and host new web conversations").option("-y, --yes","Auto-confirm shell commands (does NOT authorise installing third-party code \u2014 use --trust-source)").option("--trust-source","Accept installing third-party code from the named source (skills, plugins and personas)").option("--offline","Skip MCP servers for this run (web tools stay available)").option("-D, --direct","Direct mode (bypass server intent recognition)").option("-i, --interactive","Force agent mode (default with no query; with a query it is still a one-shot run)").option("-c, --continue-chat <id>","DEPRECATED \u2014 no effect; the id is discarded. Use --continue <id>").option("-n, --new-chat","DEPRECATED \u2014 no effect. Use /new in-session").option("--auto","Auto-approve tool prompts (write fence, sensitive-path reads and project deny rules still apply)").option("--auto-background-timeout <seconds>","Auto-convert foreground agents to background after N seconds (0 to disable)","120").option("--no-project-config","Skip this repo's config, slash commands, skills, agents and instruction files for this session: .aii/settings.json + settings.local.json (and their deny rules), project slash commands, project skills, project .aii/agents, and AGENTS.md / AII.md / CLAUDE.md. Does NOT cover .aii/hooks.json or .aii/soul.").option("--no-colors","Disable colored output (one-shot + command output; the interactive agent UI is unaffected)").option("--no-emojis","Disable emoji icons (one-shot + command output; the interactive agent UI is unaffected)").option("--no-animations","Disable animations").option("--no-streaming","Disable streaming").option("--show-tokens","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--show-cost","DEPRECATED \u2014 no effect. Use -v for a token/cost line").option("--output-format <format>","Output format: json or stream-json (one-shot only)").option("--tools <list>",'Allowlist of BUILT-IN tools (comma-separated, e.g., "Read,Bash,Edit"); MCP and subagent tools are not filtered').option("--exclude-tools <list>",'Exclude BUILT-IN tools (comma-separated, e.g., "WebSearch,WebFetch"); --tools wins if both are given').option("--max-turns <n>","Max ReAct iterations within a turn (0/unset = default 500)").option("--reconnect-window <seconds>","One-shot runs: retry dropped connections for up to N seconds (default 0 = fail fast)").option("--max-budget-usd <amount>","Interactive sessions: stop before a NEW turn once cumulative est. cost reaches $amount (does not pre-empt a turn in progress)").option("--bare","Result to stdout only; all status/chrome to stderr (one-shot)").option("--show-tools","With --bare or --output-format: write the tool transcript to stderr (stdout untouched)").option("--append-system-prompt <text>","Append additive instructions to this run").option("--append-system-prompt-file <path>","Append a workspace file of additive instructions to this run").option("--continue","Resume the most recent local session of this project (conversation + goal)").option("-h, --help","Show help"),t.command("config").description("Configuration management").argument("[action]","Action: init, show, validate, set").argument("[key]","Config key (for set)").argument("[value]","Config value (for set)").allowUnknownOption().helpOption(!1).action(()=>{}),t.command("mcp").description("MCP server management").argument("[action]","Action: list, add, remove, status, etc.").argument("[rest...]","Server name and arguments").passThroughOptions().action(()=>{}),t.command("prompt").description("Prompt library").argument("[action]","Action: list, show, use, create").argument("[rest...]","Prompt name and arguments").allowUnknownOption().action(()=>{}),t.command("stats").description("Usage statistics").argument("[type]","Type: models, cost").action(()=>{}),t.command("history").description("Chat history").argument("[action]","Action: list, search, export, delete").argument("[query]","Search query or ID").action(()=>{}),t.command("doctor").description("System health check").action(()=>{}),t.command("install [target...]").description("Install or update Aii CLI, skills, or MCP servers").allowUnknownOption().helpOption(!1).action(()=>{}),t.command("chat").description("Interactive chat mode").action(()=>{}),t.command("agent").description("Interactive agent mode with tool execution").argument("[query...]","Optional query (non-interactive if provided)").action(()=>{}),t.command("loop").description("Autonomous agent loop (Ralph Wiggum pattern)").argument("[args...]","Loop arguments (prompt, --max, --verify, --budget, etc.)").allowUnknownOption().action(()=>{}),t.command("telegram").description("Telegram bot channel (chat with Aii from Telegram)").argument("[action]","Action: start, pair, status, unpair").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("sessions").description("Browse saved conversations (list, info); use server for server-managed sessions").argument("[action]","Action: list, info, server").argument("[args...]","Additional arguments (session ID, name, etc.)").allowUnknownOption().action(()=>{}),t.command("goals").description("List goals across this project's local sessions (pick one up with --continue <id>)").action(()=>{}),t.command("worktree").description("Manage git worktrees for isolated development").argument("[action]","Action: create, list, remove, clean").argument("[name]","Worktree name (for create/remove)").allowUnknownOption().action(()=>{}),t.command("soul").description("Manage agent soul (personality & identity)").argument("[action]","Action: switch, show").argument("[name]","Soul name (for switch)").allowUnknownOption().action(()=>{}),t.command("cloud").description("Manage AiiCloud account and workspaces; use aii --remote-control for web control").argument("[action]","Action: login, status, workspace, help").allowUnknownOption().action(()=>{}),t.command("login").description("Sign in to an AI provider with your subscription (e.g., xAI SuperGrok)").argument("[args...]","Flags: --provider <name>, --status, --logout").allowUnknownOption().action(()=>{}),t.command("skill").description("Manage AI skills").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("plugin").description("Manage skill plugins").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("persona").description("Manage workspace personas").allowUnknownOption().passThroughOptions().action(()=>{}),t.command("upgrade").description("Update Aii CLI to latest version").argument("[version]","Target version (default: latest)").action(()=>{}),t.command("run").description("Run domain-specific operations").argument("<operation>","Operation (e.g., git commit)").argument("[args...]","Additional arguments").allowUnknownOption().action(()=>{}),t.command("help").description("display help for command").argument("[command]","Command to show help for").action(()=>{}),t.command("version").description("Show version number").action(()=>{}),t}async function bae(t){let e=_ae(t,VA),r=zJe(e.argv),n=r.argv,s=YJe(n),o=s>=0&&Cae(n)===void 0?n.slice(0,s):n,i=KJe();i.exitOverride(),i.configureOutput({writeErr:()=>{}});let a="query",c,l=[];try{i.parse(o),l=i.args;let m=i.args[0];m&&yae.has(m)&&(a=m,c=i.args[1],l=i.args.slice(2))}catch(m){if(m instanceof j9&&(m.code==="commander.version"||m.code==="commander.helpDisplayed")&&process.exit(0),e.resumeId&&!(m instanceof j9&&m.code==="commander.help"))throw m;l=HJe(n.slice(2))}let u=i.opts(),d={clean:u.clean??!1,standard:u.standard??!1,thinking:u.thinking??!1,verbose:u.verbose??!1,debug:u.debug??!1,model:u.model,host:u.host,inference:e.inference,remoteControl:e.remoteControl??!1,openrouterProvider:u.openrouterProvider,yes:u.yes??!1,trustSource:u.trustSource??!1,offline:u.offline??!1,direct:u.direct??!1,interactive:u.interactive??!1,continueChat:u.continueChat,newChat:u.newChat??!1,auto:u.auto??!1,quiet:!1,noProjectConfig:u.projectConfig===!1,autoBackgroundTimeout:(()=>{let m=parseInt(u.autoBackgroundTimeout??"120",10);return isNaN(m)||m===0?0:Math.max(30,Math.min(600,m))*1e3})(),noColors:!u.colors,noEmojis:!u.emojis,noAnimations:!u.animations,noStreaming:!u.streaming,showTools:u.showTools??!1,showTokens:u.showTokens??!1,showCost:u.showCost??!1,outputFormat:u.outputFormat,tools:u.tools,excludeTools:u.excludeTools,maxTurns:WJe(u.maxTurns),maxBudgetUsd:jJe(u.maxBudgetUsd),reconnectWindow:VJe(u.reconnectWindow),bare:u.bare??!1,appendSystemPrompt:u.appendSystemPrompt,appendSystemPromptFile:u.appendSystemPromptFile,continue:u.continue??!1,continueId:e.resumeId??r.continueId,continueIdError:r.error,help:u.help??!1,version:u.version??!1},p;K9()&&(p=await gae()),(a==="chat"||d.interactive)&&(a="agent"),a==="query"&&!l.length&&!p&&(a="agent");let f;if(a==="query"&&l.length>0)f=l.join(" ");else if(a==="agent"){let m=[];c&&m.push(c),l.length>0&&m.push(...l),m.length>0&&(f=m.join(" "))}return{command:a,subcommand:c,args:l,flags:d,stdinContent:p,query:f}}Pv();fm();function Tae(t){let e=Aae(t.command)??De.SERVER;switch(t.command){case"config":return JJe(t);case"mcp":return XJe(t);case"prompt":return ZJe(t);case"stats":return eXe(t);case"history":return tXe(t);case"doctor":return{tier:De.LOCAL,handler:"doctor",params:{}};case"goals":return{tier:De.LOCAL,handler:"goals",params:{}};case"install":return{tier:De.LOCAL,handler:"install",params:{}};case"chat":return{tier:De.SERVER,handler:"chat",params:{continueChat:t.flags.continueChat}};case"run":return nXe(t);case"agent":return{tier:De.SERVER,handler:"agent",params:{interactive:!t.query}};case"loop":return{tier:De.SERVER,handler:"loop",params:{}};case"telegram":return{tier:De.SERVER,handler:"telegram",params:{action:t.subcommand??t.args[0]??"start"}};case"sessions":return{tier:De.LOCAL,handler:"sessions",params:{action:t.subcommand??t.args[0]??"list"}};case"worktree":return{tier:De.LOCAL,handler:"worktree",params:{action:t.subcommand??t.args[0]??"list",name:t.subcommand?t.args[0]:t.args[1]}};case"soul":return{tier:De.LOCAL,handler:"soul",params:{action:t.subcommand??t.args[0]??"show",name:t.subcommand?t.args[0]:t.args[1]}};case"cloud":return{tier:De.LOCAL,handler:"cloud",params:{action:t.subcommand??t.args[0]??"status"}};case"login":return{tier:De.LOCAL,handler:"login",params:{}};case"skill":return{tier:De.LOCAL,handler:"skill",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"plugin":return{tier:De.LOCAL,handler:"plugin",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"persona":return{tier:De.LOCAL,handler:"persona",params:{action:t.args[0]||"help",target:t.args[1]||null,extraArgs:t.args.slice(2)}};case"upgrade":return{tier:De.LOCAL,handler:"upgrade",params:{version:t.args[0]||null}};case"help":return{tier:De.LOCAL,handler:"help",params:{command:t.subcommand}};case"version":return{tier:De.LOCAL,handler:"version",params:{}};case"query":default:return{tier:e,handler:"query",params:{query:t.query,stdinContent:t.stdinContent}}}}function JJe(t){let e=t.subcommand??t.args[0]??"show";return{tier:De.LOCAL,handler:`config:${e}`,params:{key:t.args[0],value:t.args[1]}}}function XJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`mcp:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function ZJe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`prompt:${e}`,params:{name:t.args[0],args:t.args.slice(1)}}}function eXe(t){let e=t.subcommand??t.args[0];return{tier:De.LOCAL,handler:e?`stats:${e}`:"stats",params:{}}}function tXe(t){let e=t.subcommand??t.args[0]??"list";return{tier:De.LOCAL,handler:`history:${e}`,params:{query:t.args[0],id:t.args[0]}}}var rXe=new Set(["--inference","--model","--host","--continue-chat","-c","--signature","--base"]);function nXe(t){let e=[...t.subcommand?[t.subcommand]:[],...t.args],r=[];for(let s=0;s<e.length;s++){let o=e[s];if(rXe.has(o)){e[s+1]!==void 0&&!e[s+1].startsWith("-")&&s++;continue}o.startsWith("-")||r.push(o)}let n=r.join(" ");return{tier:De.SERVER,handler:"run",params:{operation:n}}}fm();ht();YD();Pa();ti();we();fm();ih();import{createInterface as qFt}from"readline";import{spawn as zFt}from"child_process";we();import ML from"node:process";import EFe from"node:process";import OL from"node:process";var EMt=(t,e,r,n)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;let s=Object.getOwnPropertyDescriptor(t,r),o=Object.getOwnPropertyDescriptor(e,r);!yMt(s,o)&&n||Object.defineProperty(t,r,o)},yMt=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},CMt=(t,e)=>{let r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},SMt=(t,e)=>`/* Wrapped ${t}*/
|
|
4325
4325
|
${e}`,bMt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),IMt=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),TMt=(t,e,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=SMt.bind(null,n,e.toString());Object.defineProperty(s,"name",IMt);let{writable:o,enumerable:i,configurable:a}=bMt;Object.defineProperty(t,"toString",{value:s,writable:o,enumerable:i,configurable:a})};function aj(t,e,{ignoreNonConfigurable:r=!1}={}){let{name:n}=t;for(let s of Reflect.ownKeys(e))EMt(t,e,s,r);return CMt(t,e),TMt(t,e,n),t}var DL=new WeakMap,mFe=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,n=0,s=t.displayName||t.name||"<anonymous>",o=function(...i){if(DL.set(o,++n),n===1)r=t.apply(this,i),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return aj(o,t),DL.set(o,n),o};mFe.callCount=t=>{if(!DL.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return DL.get(t)};var hFe=mFe;var _g=[];_g.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&_g.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&_g.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var RL=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",cj=Symbol.for("signal-exit emitter"),lj=globalThis,wMt=Object.defineProperty.bind(Object),uj=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(lj[cj])return lj[cj];wMt(lj,cj,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],s=n.indexOf(r);s!==-1&&(s===0&&n.length===1?n.length=0:n.splice(s,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let s=!1;for(let o of this.listeners[e])s=o(r,n)===!0||s;return e==="exit"&&(s=this.emit("afterExit",r,n)||s),s}},NL=class{},kMt=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),dj=class extends NL{onExit(){return()=>{}}load(){}unload(){}},pj=class extends NL{#e=fj.platform==="win32"?"SIGINT":"SIGHUP";#t=new uj;#r;#s;#o;#n={};#i=!1;constructor(e){super(),this.#r=e,this.#n={};for(let r of _g)this.#n[r]=()=>{let n=this.#r.listeners(r),{count:s}=this.#t,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(s+=o.__signal_exit_emitter__.count),n.length===s){this.unload();let i=this.#t.emit("exit",null,r),a=r==="SIGHUP"?this.#e:r;i||e.kill(e.pid,a)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(e,r){if(!RL(this.#r))return()=>{};this.#i===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(let e of _g)try{let r=this.#n[e];r&&this.#r.on(e,r)}catch{}this.#r.emit=(e,...r)=>this.#l(e,...r),this.#r.reallyExit=e=>this.#a(e)}}unload(){this.#i&&(this.#i=!1,_g.forEach(e=>{let r=this.#n[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,r)}catch{}}),this.#r.emit=this.#s,this.#r.reallyExit=this.#o,this.#t.count-=1)}#a(e){return RL(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#l(e,...r){let n=this.#s;if(e==="exit"&&RL(this.#r)){typeof r[0]=="number"&&(this.#r.exitCode=r[0]);let s=n.call(this.#r,e,...r);return this.#t.emit("exit",this.#r.exitCode,null),s}else return n.call(this.#r,e,...r)}},fj=globalThis.process,{onExit:gFe,load:Igr,unload:Tgr}=kMt(RL(fj)?new pj(fj):new dj);var AFe=OL.stderr.isTTY?OL.stderr:OL.stdout.isTTY?OL.stdout:void 0,vMt=AFe?hFe(()=>{gFe(()=>{AFe.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},_Fe=vMt;var xL=!1,Gy={};Gy.show=(t=EFe.stderr)=>{t.isTTY&&(xL=!1,t.write("\x1B[?25h"))};Gy.hide=(t=EFe.stderr)=>{t.isTTY&&(_Fe(),xL=!0,t.write("\x1B[?25l"))};Gy.toggle=(t,e)=>{t!==void 0&&(xL=t),xL?Gy.show(e):Gy.hide(e)};var mj=Gy;var mw=Xt(hj(),1);we();import mc from"node:process";function gj(){return mc.platform!=="win32"?mc.env.TERM!=="linux":!!mc.env.CI||!!mc.env.WT_SESSION||!!mc.env.TERMINUS_SUBLIME||mc.env.ConEmuTask==="{cmd::Cmder}"||mc.env.TERM_PROGRAM==="Terminus-Sublime"||mc.env.TERM_PROGRAM==="vscode"||mc.env.TERM==="xterm-256color"||mc.env.TERM==="alacritty"||mc.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var RMt={info:g.blue("\u2139"),success:g.green("\u2714"),warning:g.yellow("\u26A0"),error:g.red("\u2716")},NMt={info:g.blue("i"),success:g.green("\u221A"),warning:g.yellow("\u203C"),error:g.red("\xD7")},OMt=gj()?RMt:NMt,fw=OMt;PR();var xMt=qm();function Aj(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(xMt,"")}r8();function _j({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import bFe from"node:process";function Ej(){let{env:t}=bFe,{TERM:e,TERM_PROGRAM:r}=t;return bFe.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}import kl from"node:process";var BMt=3,yj=class{#e=0;start(){this.#e++,this.#e===1&&this.#t()}stop(){if(this.#e<=0)throw new Error("`stop` called more times than `start`");this.#e--,this.#e===0&&this.#r()}#t(){kl.platform==="win32"||!kl.stdin.isTTY||(kl.stdin.setRawMode(!0),kl.stdin.on("data",this.#s),kl.stdin.resume())}#r(){kl.stdin.isTTY&&(kl.stdin.off("data",this.#s),kl.stdin.pause(),kl.stdin.setRawMode(!1))}#s(e){e[0]===BMt&&kl.emit("SIGINT")}},MMt=new yj,Cj=MMt;var LMt=Xt(hj(),1),Sj=class{#e=0;#t=!1;#r=0;#s=-1;#o=0;#n;#i;#a;#l;#c;#u;#f;#m;#g;#d;#p;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#n={color:"cyan",stream:ML.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#n.color,this.spinner=this.#n.spinner,this.#c=this.#n.interval,this.#a=this.#n.stream,this.#u=typeof this.#n.isEnabled=="boolean"?this.#n.isEnabled:_j({stream:this.#a}),this.#f=typeof this.#n.isSilent=="boolean"?this.#n.isSilent:!1,this.text=this.#n.text,this.prefixText=this.#n.prefixText,this.suffixText=this.#n.suffixText,this.indent=this.#n.indent,ML.env.NODE_ENV==="test"&&(this._stream=this.#a,this._isEnabled=this.#u,Object.defineProperty(this,"_linesToClear",{get(){return this.#e},set(r){this.#e=r}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#s}}),Object.defineProperty(this,"_lineCount",{get(){return this.#r}}))}get indent(){return this.#m}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#m=e,this.#h()}get interval(){return this.#c??this.#i.interval??100}get spinner(){return this.#i}set spinner(e){if(this.#s=-1,this.#c=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#i=e}else if(!Ej())this.#i=mw.default.line;else if(e===void 0)this.#i=mw.default.dots;else if(e!=="default"&&mw.default[e])this.#i=mw.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#g}set text(e=""){this.#g=e,this.#h()}get prefixText(){return this.#d}set prefixText(e=""){this.#d=e,this.#h()}get suffixText(){return this.#p}set suffixText(e=""){this.#p=e,this.#h()}get isSpinning(){return this.#l!==void 0}#A(e=this.#d,r=" "){return typeof e=="string"&&e!==""?e+r:typeof e=="function"?e()+r:""}#_(e=this.#p,r=" "){return typeof e=="string"&&e!==""?r+e:typeof e=="function"?r+e():""}#h(){let e=this.#a.columns??80,r=this.#A(this.#d,"-"),n=this.#_(this.#p,"-"),s=" ".repeat(this.#m)+r+"--"+this.#g+"--"+n;this.#r=0;for(let o of Aj(s).split(`
|
|
4326
4326
|
`))this.#r+=Math.max(1,Math.ceil(N_(o,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#u&&!this.#f}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#u=e}get isSilent(){return this.#f}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#f=e}frame(){let e=Date.now();(this.#s===-1||e-this.#o>=this.interval)&&(this.#s=++this.#s%this.#i.frames.length,this.#o=e);let{frames:r}=this.#i,n=r[this.#s];this.color&&(n=g[this.color](n));let s=typeof this.#d=="string"&&this.#d!==""?this.#d+" ":"",o=typeof this.text=="string"?" "+this.text:"",i=typeof this.#p=="string"&&this.#p!==""?" "+this.#p:"";return s+n+o+i}clear(){if(!this.#u||!this.#a.isTTY)return this;this.#a.cursorTo(0);for(let e=0;e<this.#e;e++)e>0&&this.#a.moveCursor(0,-1),this.#a.clearLine(1);return(this.#m||this.lastIndent!==this.#m)&&this.#a.cursorTo(this.#m),this.lastIndent=this.#m,this.#e=0,this}render(){return this.#f?this:(this.clear(),this.#a.write(this.frame()),this.#e=this.#r,this)}start(e){return e&&(this.text=e),this.#f?this:this.#u?this.isSpinning?this:(this.#n.hideCursor&&mj.hide(this.#a),this.#n.discardStdin&&ML.stdin.isTTY&&(this.#t=!0,Cj.start()),this.render(),this.#l=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#a.write(`- ${this.text}
|
|
4327
4327
|
`),this)}stop(){return this.#u?(clearInterval(this.#l),this.#l=void 0,this.#s=0,this.clear(),this.#n.hideCursor&&mj.show(this.#a),this.#n.discardStdin&&ML.stdin.isTTY&&this.#t&&(Cj.stop(),this.#t=!1),this):this}succeed(e){return this.stopAndPersist({symbol:fw.success,text:e})}fail(e){return this.stopAndPersist({symbol:fw.error,text:e})}warn(e){return this.stopAndPersist({symbol:fw.warning,text:e})}info(e){return this.stopAndPersist({symbol:fw.info,text:e})}stopAndPersist(e={}){if(this.#f)return this;let r=e.prefixText??this.#d,n=this.#A(r," "),s=e.symbol??" ",o=e.text??this.text,a=typeof o=="string"?(s?" ":"")+o:"",c=e.suffixText??this.#p,l=this.#_(c," "),u=n+s+a+l+`
|
|
@@ -4331,7 +4331,7 @@ ${e}`,bMt=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),IMt=Obj
|
|
|
4331
4331
|
`+this.color(s,g.dim)}formatError(e){let r=[];return r.push(this.color(`${this.emoji("\u274C ")}${e.message}`,g.red)),e.suggestions&&e.suggestions.length>0&&(r.push(""),r.push(this.color(`${this.emoji("\u{1F4A1} ")}Solutions:`,g.yellow)),e.suggestions.forEach((n,s)=>{r.push(this.color(` ${s+1}. ${n}`,g.gray))})),r.join(`
|
|
4332
4332
|
`)}formatConfig(e){let r=[];r.push(this.color(`${this.emoji("\u{1F4CB} ")}Current AII Configuration:`,F.model)),r.push(`- Config file: ${e.configFile}`),r.push(`- Storage path: ${e.storagePath}`),e.apiUrl&&r.push(`- Aii Server: ${e.apiUrl}`);let n=e.hasApiKey?this.color("\u2713",g.green):this.color("\u2717",g.red),s=e.model.startsWith(e.provider+"/")?e.model.slice(e.provider.length+1):e.model;if(r.push(`- LLM provider: ${e.provider} (${s}) - ${n}`),e.webSearch){let o=e.webSearch.enabled?this.color("\u2713",g.green):this.color("\u2717",g.red);r.push(`- Web search: ${e.webSearch.provider??"none"} - ${o}`)}return e.issues&&e.issues.length>0&&r.push(`- Configuration issues: ${e.issues.length}`),r.join(`
|
|
4333
4333
|
`)}formatHealthCheck(e,r){let n=[],s=r?`Aii Doctor v${r}`:"Aii Doctor";n.push(this.color(s,F.model)),n.push("");let o=22;for(let c of e){let l=o-c.name.length-1,u=".".repeat(Math.max(2,l)),d,p;switch(c.status){case"ok":d="OK",p=g.green;break;case"warn":d="WARN",p=g.yellow;break;case"error":d="FAIL",p=g.red;break}let f=this.color(d,p),m=c.message?` (${c.message})`:"";n.push(` ${c.name} ${this.color(u,g.gray)} ${f}${m}`)}let i=e.filter(c=>c.status==="error").length,a=e.filter(c=>c.status==="warn").length;return n.push(""),i>0?n.push(` ${this.color(`${i} check${i>1?"s":""} failed.`,g.red)}`):a>0?n.push(` ${this.color("All checks passed with warnings.",g.yellow)}`):n.push(` ${this.color("All checks passed.",g.green)}`),n.join(`
|
|
4334
|
-
`)}};function Lo(t={}){return new kj(t)}js();fi();we();ih();import*as DFe from"readline";js();es();fi();Qc();import*as ga from"fs";import*as PL from"path";import*as IFe from"os";var gw=PL.join(IFe.homedir(),".aii","conversations"),vj=PL.join(gw,"current.json");function FL(){ga.existsSync(gw)||ga.mkdirSync(gw,{recursive:!0,mode:448});try{ga.chmodSync(gw,448)}catch{}}function QMt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function UMt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function TFe(t){return PL.join(gw,`${t}.json`)}function wFe(){FL();try{if(ga.existsSync(vj)){let t=ga.readFileSync(vj,"utf-8"),e=JSON.parse(t),r=TFe(e.id);if(ga.existsSync(r)){let n=ga.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return kFe()}function kFe(){FL();let t={id:QMt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Aw(t),$Mt(t.id),t}function Aw(t){if(FL(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=UMt(r.content))}t.updatedAt=Date.now();let e=TFe(t.id);wi(e,JSON.stringify(t,null,2))}function $Mt(t){FL(),wi(vj,JSON.stringify({id:t}))}function vFe(){return kFe()}Jh();var GMt="0.25.
|
|
4334
|
+
`)}};function Lo(t={}){return new kj(t)}js();fi();we();ih();import*as DFe from"readline";js();es();fi();Qc();import*as ga from"fs";import*as PL from"path";import*as IFe from"os";var gw=PL.join(IFe.homedir(),".aii","conversations"),vj=PL.join(gw,"current.json");function FL(){ga.existsSync(gw)||ga.mkdirSync(gw,{recursive:!0,mode:448});try{ga.chmodSync(gw,448)}catch{}}function QMt(){return`conv_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function UMt(t){let r=t.trim().replace(/\s+/g," ");return r.length>50&&(r=r.substring(0,50).trim()+"..."),r}function TFe(t){return PL.join(gw,`${t}.json`)}function wFe(){FL();try{if(ga.existsSync(vj)){let t=ga.readFileSync(vj,"utf-8"),e=JSON.parse(t),r=TFe(e.id);if(ga.existsSync(r)){let n=ga.readFileSync(r,"utf-8");return JSON.parse(n)}}}catch{}return kFe()}function kFe(){FL();let t={id:QMt(),title:"New Conversation",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return Aw(t),$Mt(t.id),t}function Aw(t){if(FL(),t.title==="New Conversation"&&t.messages.length>0){let r=t.messages.find(n=>n.role==="user");r&&(t.title=UMt(r.content))}t.updatedAt=Date.now();let e=TFe(t.id);wi(e,JSON.stringify(t,null,2))}function $Mt(t){FL(),wi(vj,JSON.stringify({id:t}))}function vFe(){return kFe()}Jh();var GMt="0.25.8",Dj=class{configManager;parsed;running=!1;conversation;stats;formatter;effectiveProvider="";constructor(e,r){this.parsed=e,this.configManager=r,this.conversation=wFe(),this.stats={startTime:Date.now(),totalRequests:0,cumulativeTokens:0,cumulativeCost:0},this.formatter=Lo({colors:!e.flags.noColors,emojis:!e.flags.noEmojis})}async start(){for(this.running=!0,this.displayWelcome();this.running;)try{let e=await this.getUserInput();if(!e.trim()||await this.handleSpecialCommands(e))continue;this.conversation.messages.push({role:"user",content:e,timestamp:Date.now()}),Aw(this.conversation),await this.processWithContext(e)}catch(e){if(e instanceof Error&&e.message==="EXIT")break;if(e instanceof Error&&e.message==="INTERRUPTED"){console.log(`
|
|
4335
4335
|
\u26A0\uFE0F Interrupted. Type /exit to quit or continue chatting.`);continue}console.error(g.red(`
|
|
4336
4336
|
\u274C Error: ${e instanceof Error?e.message:String(e)}`)),this.conversation.messages.length>0&&this.conversation.messages[this.conversation.messages.length-1].role==="user"&&(this.conversation.messages.pop(),Aw(this.conversation))}}displayWelcome(){console.log("\u{1FABC} Entering interactive mode."),console.log(""),console.log("Controls:"),console.log(" \u2022 Enter - Send message"),console.log(" \u2022 End with \\ - Multi-line mode"),console.log(" \u2022 /exit - Quit chat"),console.log(" \u2022 /help - Show all commands"),console.log("")}getUserInput(){return new Promise((e,r)=>{let n=DFe.createInterface({input:process.stdin,output:process.stdout}),s=[],o=!1,i=()=>{o=!0,n.close()},a=c=>{n.question(c,l=>{if(s.length===0&&l.trim().startsWith("/")){i(),e(l.trim());return}l.endsWith("\\")?(s.push(l.slice(0,-1)),a(" ")):(s.push(l),i(),e(s.join(`
|
|
4337
4337
|
`).trim()))})};n.on("SIGINT",()=>{i(),r(new Error("INTERRUPTED"))}),n.on("close",()=>{o||r(new Error("EXIT"))}),a("> ")})}async handleSpecialCommands(e){let r=e.trim().toLowerCase();if(r.startsWith("/"))r=r.slice(1);else return!1;switch(r){case"exit":case"quit":return await this.handleExit(),!0;case"help":return this.displayHelp(),!0;case"clear":case"new":return this.clearConversation(),!0;case"history":return this.displayConversationHistory(),!0;case"stats":return this.displayStats(),!0;case"version":return this.displayVersion(),!0;default:return console.log(g.yellow(`Unknown command: /${r}. Type /help for available commands.`)),console.log(""),!0}}async processWithContext(e){let r=await this.configManager.load(),n=this.configManager.validate();if(!n.valid)throw new Vn(n.issues.join(", "));let o=this.configManager.getServerApiKey()||"aii_sk_7WyvfQ0PRzufJ1G66Qn8Sm4gW9Tealpo6vOWDDUeiv4",i=vn(this.parsed.flags.model??""),a=us(i||void 0,r.llm.provider),c=Xr(i||r.llm.model,a);this.effectiveProvider=a;let l=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,u=await Rt(a,this.configManager,{serverBaseUrl:l,serverApiKey:o}),d=u?.key;if(!d)throw new Rr(`Missing API key for provider: ${a}`);this.stats.totalRequests++;let p=vl(!this.parsed.flags.noAnimations);p.start("");let f=Dl({spinner:p,enabled:!this.parsed.flags.noStreaming}),m=this.conversation.messages.slice(-21,-1).map(S=>({role:S.role,content:S.content})),h={api_key:o,system_prompt:null,user_prompt:e,user_message:e,output_mode:"CLEAN",streaming:!this.parsed.flags.noStreaming,model:c,llm_provider:a,llm_api_key:d,provider_api_key:d,...u?.authType?{auth_type:u.authType}:{},...u?.accountId?{account_id:u.accountId}:{},client_type:"cli",offline:this.parsed.flags.offline,conversation_history:m.length>0?m:void 0,soul:Fs.getInstance().getSoulName()},A=this.parsed.flags.host?`http://${this.parsed.flags.host}`:r.api.url,_=new Io({url:A}),E="",y=!1;try{let S=await _.executeRequest(h,{onToken:w=>{E+=w,y=!0,f.onToken(w)}});f.flush();let C=S.result||E;!y&&C&&console.log(C),console.log(""),S.metadata&&this.displayExecutionSummary(S.metadata),C&&(this.conversation.messages.push({role:"assistant",content:C,timestamp:Date.now()}),Aw(this.conversation))}catch(S){throw p.stop(!0),S}finally{_.disconnect()}}displayExecutionSummary(e){let r=e.cost||0,n=e.tokens_in||0,s=e.tokens_out||0,o=n+s;this.stats.cumulativeTokens+=o,this.stats.cumulativeCost+=r;let i=e.provider,a=!i;console.log(this.formatter.formatExecutionSummary({provider:i||this.effectiveProvider,providerInferred:a,model:e.model,tokens_in:n,tokens_out:s,cost:r,execution_time:e.execution_time})),console.log("")}clearConversation(){this.conversation=vFe(),console.clear(),this.displayWelcome()}displayConversationHistory(){if(this.conversation.messages.length===0){console.log(`
|
|
@@ -4507,10 +4507,10 @@ ${r.yellow("CONFIG FILE:")}
|
|
|
4507
4507
|
.aii/settings.json Project config (committed, restrict-only)
|
|
4508
4508
|
.aii/settings.local.json Your local overrides (gitignored)
|
|
4509
4509
|
${r.gray("Skip both for a session with: aii --no-project-config")}
|
|
4510
|
-
`)}import*as Ml from"fs";Qr();Rv();async function O9e(t,e){let r=Lo({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await yQt(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(Ml.existsSync(c))try{let f=Ml.readFileSync(c,"utf-8"),m=JSON.parse(f),h=Object.keys(m.mcpServers??{}).length;h>0?n.push({name:"MCP Servers",status:"ok",message:`${h} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(vv())try{let{execSync:f}=await import("child_process"),h=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:h?`v${h[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});vv()?Dv()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let l=process.version;parseInt(l.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:l}):n.push({name:"Node.js",status:"error",message:`${l} (requires >= 18)`});let d=await CQt();n.push(...d),console.log(r.formatHealthCheck(n,Gm)),n.some(f=>f.status==="error")&&process.exit(1)}async function yQt(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function CQt(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(oi(),hN)),r=`${e()}/skills`;if(!Ml.existsSync(r))return t;let n=Ml.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;Ml.existsSync(o)||t.push({name:"Skill Shadow",status:"warn",message:`~/.aii/skills/${s.name}/ has no SKILL.md \u2014 may shadow other skills`})}try{let{PersonaManager:s}=await Promise.resolve().then(()=>(sr(),lr));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",c=`${r}/${a}`;Ml.existsSync(c)&&Ml.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}we();Qr();import{execSync as uK}from"node:child_process";var rF="@aiiware/aii";async function x9e(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.25.
|
|
4511
|
-
`),await SQt(r)}async function SQt(t){let e="0.25.
|
|
4510
|
+
`)}import*as Ml from"fs";Qr();Rv();async function O9e(t,e){let r=Lo({colors:!t.flags.noColors,emojis:!t.flags.noEmojis}),n=[],s=`${e.getConfigDir()}/config.yaml`;e.configExists()?n.push({name:"Config",status:"ok",message:s.replace(process.env.HOME||"","~")}):n.push({name:"Config",status:"warn",message:"Not found (using defaults)"});let o=await e.load();e.getApiKey()?n.push({name:"API Key",status:"ok",message:`${o.llm.provider}:${o.llm.model.replace(`${o.llm.provider}/`,"")}`}):n.push({name:"API Key",status:"error",message:`Not configured for ${o.llm.provider}`});let a=await yQt(o.api.url);n.push({name:"Aii Server",status:a.ok?"ok":"error",message:a.message});let c=`${e.getConfigDir()}/mcp_servers.json`;if(Ml.existsSync(c))try{let f=Ml.readFileSync(c,"utf-8"),m=JSON.parse(f),h=Object.keys(m.mcpServers??{}).length;h>0?n.push({name:"MCP Servers",status:"ok",message:`${h} configured`}):n.push({name:"MCP Servers",status:"warn",message:"Not configured"})}catch{n.push({name:"MCP Servers",status:"warn",message:"Invalid config"})}else n.push({name:"MCP Servers",status:"warn",message:"Not configured"});if(vv())try{let{execSync:f}=await import("child_process"),h=f("docker --version",{timeout:5e3,encoding:"utf-8"}).trim().match(/Docker version ([\d.]+)/);n.push({name:"Docker",status:"ok",message:h?`v${h[1]}`:"Installed"})}catch{n.push({name:"Docker",status:"ok",message:"Installed"})}else n.push({name:"Docker",status:"error",message:"Not installed (brew install --cask docker)"});vv()?Dv()?n.push({name:"Docker Daemon",status:"ok",message:"Running"}):n.push({name:"Docker Daemon",status:"error",message:"Not running (open -a Docker)"}):n.push({name:"Docker Daemon",status:"warn",message:"N/A (Docker not installed)"});let l=process.version;parseInt(l.slice(1).split(".")[0],10)>=18?n.push({name:"Node.js",status:"ok",message:l}):n.push({name:"Node.js",status:"error",message:`${l} (requires >= 18)`});let d=await CQt();n.push(...d),console.log(r.formatHealthCheck(n,Gm)),n.some(f=>f.status==="error")&&process.exit(1)}async function yQt(t){try{let e=new AbortController,r=setTimeout(()=>e.abort(),3e3),n=await fetch(`${t}/api/status`,{signal:e.signal});if(clearTimeout(r),n.ok){let s=new URL(t);return{ok:!0,message:`${s.hostname}:${s.port||26169}`}}else return{ok:!1,message:`Not responding (${n.status})`}}catch(e){return e instanceof Error&&e.name==="AbortError"?{ok:!1,message:"Connection timeout"}:{ok:!1,message:"Not running"}}}async function CQt(){let t=[];try{let{getAiiHome:e}=await Promise.resolve().then(()=>(oi(),hN)),r=`${e()}/skills`;if(!Ml.existsSync(r))return t;let n=Ml.readdirSync(r,{withFileTypes:!0});for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=`${r}/${s.name}/SKILL.md`;Ml.existsSync(o)||t.push({name:"Skill Shadow",status:"warn",message:`~/.aii/skills/${s.name}/ has no SKILL.md \u2014 may shadow other skills`})}try{let{PersonaManager:s}=await Promise.resolve().then(()=>(sr(),lr));if(s.hasInstance()&&s.getInstance().isActive()){let o=s.getInstance().getActive();if(o)for(let i of o.skillPaths){let a=i.split("/").pop()||"",c=`${r}/${a}`;Ml.existsSync(c)&&Ml.existsSync(`${c}/SKILL.md`)&&t.push({name:"Skill Shadow",status:"ok",message:`"${a}" user-authored shadows persona-bundled (intentional?)`})}}}catch{}}catch{}return t}we();Qr();import{execSync as uK}from"node:child_process";var rF="@aiiware/aii";async function x9e(t){let e=t.args||[],r=t.subcommand||e[0]||"";if(t.flags.help||r==="help"||r==="--help"||e.includes("--help")){let n="0.25.8";console.log(""),console.log(F.logo(" Install")),console.log(""),console.log(` Current version: ${F.model(n)}`),console.log(""),console.log(g.yellow(" USAGE:")),console.log(` ${g.green("aii install")} Update to latest version`),console.log(` ${g.green("aii install <version>")} Install specific version`),console.log(` ${g.green("aii install skill <src>")} Install a skill package ${g.dim("(coming soon)")}`),console.log(` ${g.green("aii install mcp <name>")} Install an MCP server ${g.dim("(coming soon)")}`),console.log(""),console.log(g.yellow(" EXAMPLES:")),console.log(` ${g.green("aii install")} ${g.dim("# Self-update to latest")}`),console.log(` ${g.green("aii install 0.13.10")} ${g.dim("# Pin to specific version")}`),console.log("");return}if(r==="skill"){console.log("Skill installation coming soon. For now use: /skills install owner/repo");return}if(r==="mcp"){console.log("MCP installation coming soon. For now use: aii mcp install <server>");return}console.log("\x1B[33m\u26A0 `aii install` for self-update is deprecated. Use `aii upgrade` instead.\x1B[0m"),console.log(`\x1B[33m This alias will be removed in v0.16.x.\x1B[0m
|
|
4511
|
+
`),await SQt(r)}async function SQt(t){let e="0.25.8",r=t&&t!=="latest"?t:"";if(console.log(""),r){console.log(`\u{1FABC} Installing Aii CLI v${r}...`),console.log("");try{uK(`npm install -g ${rF}@${r}`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4512
4512
|
\u274C Failed to install v${r}`),console.error(` Try manually: npm install -g ${rF}@${r}`),process.exit(1)}}else{console.log("\u{1FABC} Updating Aii CLI to latest..."),console.log(` Current version: ${e}`),console.log("");try{uK(`npm install -g ${rF}@latest`,{stdio:"inherit",timeout:12e4})}catch{console.error(`
|
|
4513
|
-
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${rF}@latest`),process.exit(1)}}try{let n=uK("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}we();var B9e="0.25.
|
|
4513
|
+
\u274C Failed to update Aii CLI`),console.error(` Try manually: npm install -g ${rF}@latest`),process.exit(1)}}try{let n=uK("aii --version 2>/dev/null",{encoding:"utf-8",timeout:1e4,stdio:"pipe"}).trim();console.log(""),console.log(n===e?`\u2713 Aii CLI is already up to date (${e})`:`\u2713 Aii CLI updated: ${e} \u2192 ${n}`)}catch{console.log(""),console.log("\u2713 Aii CLI installed. Restart your terminal to use the new version.")}}we();var B9e="0.25.8";function dK(t){let r=!t.flags.noColors?g:{cyan:n=>n,yellow:n=>n,gray:n=>n,green:n=>n};console.log(`
|
|
4514
4514
|
${r.cyan("AII")} - AI-powered CLI assistant v${B9e}
|
|
4515
4515
|
|
|
4516
4516
|
${r.yellow("USAGE:")}
|
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.8
|
|
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,z=H);let ue={code:
|
|
|
918
918
|
shutting down\u2026 (Ctrl+C again to force)
|
|
919
919
|
`)}catch{}},300);e.unref?.(),qme().finally(()=>{clearTimeout(e),process.exit(OE)})}function Ktt(){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($e().getConfig()?.trace?.enabled===!1)return!1}catch{}return!0}function Wme(t,e={}){if(!Ktt())return null;try{let r=new EU(t,e);for(let n of BE)n.deref()||BE.delete(n);return r.registerSelf(BE),Hme||(Hme=!0,DE.registerFinal("trace-writer-flush",()=>zme())),r}catch{return null}}var Htt,mU,gU,qtt,ztt,$me,Wtt,BE,Q0,Hme,Vtt,xE,OE,AU,EU,yU=I(()=>{"use strict";o_();Qme();tr();Fme();tg();tg();Htt=10*1024*1024,mU=4096,gU=16*1024,qtt=8*1024,ztt=1e3,$me="[withheld: sensitive path]";Wtt=["content","new_string","old_string","text","replacement","data"];BE=new Set,Q0=new Set,Hme=!1,Vtt=250;xE=null,OE=0,AU=!1;EU=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??Ls(),this.maxFileBytes=r.maxFileBytes??Htt,this.redactorFactory=r.redactor??(()=>Mme()),this.isSensitive=r.isSensitivePath??Lme,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:El(this.redact(i??""),gU)})}),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:El(this.redact(o),gU)}),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")>=qtt){this.flushText();return}this.textTimer||(this.textTimer=setTimeout(()=>this.flushText(),ztt),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?$me:El(this.redact(s?.output??""),mU),error:s?.error?El(this.redact(s.error),mU):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:El(this.redact(Yme(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:El(this.redact(Yme(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&&Wtt.includes(a))return $me;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 El(this.redact(s),mU)}flushText(){if(this.textTimer&&(clearTimeout(this.textTimer),this.textTimer=null),!this.textBuffer)return;let e=this.textBuffer;this.textBuffer="",this.write({type:"text",content:El(this.redact(e),gU)})}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=GM(r,this.baseDir);if(!this.opened){if(await Gtt(Gme(n),{recursive:!0,mode:448}),await Ume(Gme(n),448).catch(()=>{}),Ytt(n)){await Ume(n,384);try{this.bytesWritten+=(await $tt(n)).size}catch{}}this.opened=!0}await Utt(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;Q0.add(e),Promise.resolve(e).catch(()=>{}).finally(()=>{Q0.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 jtt}from"path";function Jtt(){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 LE(){return SU===null&&(SU=Jtt()),SU}function Xtt(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Kme(){return Vme||!LE()?"":(Vme=!0,` (${Xtt()}+Click to open)`)}function Ztt(t,e){return LE()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function jme(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(!LE())return vt().filePath(s);let o=vt().accent(s),c=`file://${jtt(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Ztt(o,c)}var SU,Vme,Jme=I(()=>{"use strict";Dn();SU=null,Vme=!1});var tge={};rt(tge,{VERSION:()=>ert,colors:()=>Le,formatCode:()=>urt,formatPath:()=>ege,getActionIndicator:()=>lrt,padEndAnsi:()=>hrt,printDivider:()=>Zme,printError:()=>art,printExitSummary:()=>grt,printHeader:()=>crt,printSuccess:()=>srt,printToolResultCompact:()=>Uh,printWarning:()=>ort,shortenPath:()=>prt});function trt(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 irt(t){return nrt.test(t)}function Uh(t,e,r=!0,n,i=console.log,s=!0,o=0,a=process.stdout){let c=r?Le.success("\u25CF"):Le.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=trt(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=Ps(d),f=vr(t)+6+o,h=Math.max(rrt,(a.columns||80)-f),g=vr(p)>h?Co(p,h-1).replace(/\u200D+$/,"")+"\u2026":p,A=a===process.stdout?!0:a.isTTY===!0,_=u&&!irt(e)&&A;if(_){let C=e.match(/:(\d+)$/),T=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;g=ege(k,T,g)}i(`${c} ${O.bold(t)}(${g})`);let y=s&&_?Le.dim(Kme()):"",b=s&&!y&&!Xme?Le.dim(" (ctrl+o to expand)"):"";if(b&&(Xme=!0),n){let C=r?Le.dim:Le.error;i(C(`\u2514 ${n}`)+y+b)}else{let C=r?"(No content)":"(Error)",T=r?Le.dim:Le.error;i(T(`\u2514 ${C}`)+y+b)}}function srt(t){console.log(Le.success("\u2713 ")+t)}function ort(t){console.log(Le.warning("\u26A0 ")+t)}function art(t){console.log(Le.error("\u2717 ")+t)}function Zme(t=60){console.log(Le.dim("\u2500".repeat(t)))}function crt(t){console.log(Le.logo(t)),Zme(t.length)}function lrt(t){return Le.thinking(`[${t}]`)}function ege(t,e,r){if(LE())return jme(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}`),Le.filePath(r??i)}function urt(t){return Le.code(t)}function drt(){return process.stdout.columns||80}function prt(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 frt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hrt(t,e){let r=frt(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function mrt(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 CU(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function grt(t){let e=drt(),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=>Le.border("\u2502")+" "+i(g,n)+" "+Le.border("\u2502"),o=(g,A,_,y)=>{let b=Math.floor(n/2),C=Le.dim(g.padEnd(15))+A,T=Le.dim(_.padEnd(15))+y;return s(i(C,b)+T)},a=mrt(t.durationSeconds),c=CU(t.tokensIn),l=CU(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(Le.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(s(Le.logo("Session complete. \u{1FABC}"))),console.log(Le.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(s(Le.logo("Session Summary"))),console.log(s(Le.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(Le.logo("Token Usage"))),console.log(s(Le.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(Le.dim("Cached".padEnd(15))+`${CU(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?Le.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(s(Le.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(Le.dim("Goal: ")+m(g,n-6)))}t.goalResumeLine&&console.log(s(Le.dim(m(` ${t.goalResumeLine}`,n)))),console.log(s(Le.dim("Model: ")+Le.model(d))),console.log(Le.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var ert,Le,rrt,nrt,Xme,QE=I(()=>{"use strict";ys();Jme();Dn();Bu();xf();ert="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=GM(r,this.baseDir);if(!this.opened){if(await Gtt(Gme(n),{recursive:!0,mode:448}),await Ume(Gme(n),448).catch(()=>{}),Ytt(n)){await Ume(n,384);try{this.bytesWritten+=(await $tt(n)).size}catch{}}this.opened=!0}await Utt(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;Q0.add(e),Promise.resolve(e).catch(()=>{}).finally(()=>{Q0.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 jtt}from"path";function Jtt(){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 LE(){return SU===null&&(SU=Jtt()),SU}function Xtt(){return process.platform==="darwin"?"Cmd":"Ctrl"}function Kme(){return Vme||!LE()?"":(Vme=!0,` (${Xtt()}+Click to open)`)}function Ztt(t,e){return LE()?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}function jme(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(!LE())return vt().filePath(s);let o=vt().accent(s),c=`file://${jtt(t)}`;return e!==void 0&&e>0&&(c+=`#L${e}`),Ztt(o,c)}var SU,Vme,Jme=I(()=>{"use strict";Dn();SU=null,Vme=!1});var tge={};rt(tge,{VERSION:()=>ert,colors:()=>Le,formatCode:()=>urt,formatPath:()=>ege,getActionIndicator:()=>lrt,padEndAnsi:()=>hrt,printDivider:()=>Zme,printError:()=>art,printExitSummary:()=>grt,printHeader:()=>crt,printSuccess:()=>srt,printToolResultCompact:()=>Uh,printWarning:()=>ort,shortenPath:()=>prt});function trt(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 irt(t){return nrt.test(t)}function Uh(t,e,r=!0,n,i=console.log,s=!0,o=0,a=process.stdout){let c=r?Le.success("\u25CF"):Le.error("\u25CF"),l=process.env.HOME??process.env.USERPROFILE??"",u=trt(e),d=u&&l&&e.startsWith(l+"/")?"~"+e.slice(l.length):e,p=Ps(d),f=vr(t)+6+o,h=Math.max(rrt,(a.columns||80)-f),g=vr(p)>h?Co(p,h-1).replace(/\u200D+$/,"")+"\u2026":p,A=a===process.stdout?!0:a.isTTY===!0,_=u&&!irt(e)&&A;if(_){let C=e.match(/:(\d+)$/),T=C?parseInt(C[1],10):void 0,k=C?e.replace(/:(\d+)$/,""):e;g=ege(k,T,g)}i(`${c} ${O.bold(t)}(${g})`);let y=s&&_?Le.dim(Kme()):"",b=s&&!y&&!Xme?Le.dim(" (ctrl+o to expand)"):"";if(b&&(Xme=!0),n){let C=r?Le.dim:Le.error;i(C(`\u2514 ${n}`)+y+b)}else{let C=r?"(No content)":"(Error)",T=r?Le.dim:Le.error;i(T(`\u2514 ${C}`)+y+b)}}function srt(t){console.log(Le.success("\u2713 ")+t)}function ort(t){console.log(Le.warning("\u26A0 ")+t)}function art(t){console.log(Le.error("\u2717 ")+t)}function Zme(t=60){console.log(Le.dim("\u2500".repeat(t)))}function crt(t){console.log(Le.logo(t)),Zme(t.length)}function lrt(t){return Le.thinking(`[${t}]`)}function ege(t,e,r){if(LE())return jme(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}`),Le.filePath(r??i)}function urt(t){return Le.code(t)}function drt(){return process.stdout.columns||80}function prt(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 frt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function hrt(t,e){let r=frt(t),n=Math.max(0,e-r);return t+" ".repeat(n)}function mrt(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 CU(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function grt(t){let e=drt(),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=>Le.border("\u2502")+" "+i(g,n)+" "+Le.border("\u2502"),o=(g,A,_,y)=>{let b=Math.floor(n/2),C=Le.dim(g.padEnd(15))+A,T=Le.dim(_.padEnd(15))+y;return s(i(C,b)+T)},a=mrt(t.durationSeconds),c=CU(t.tokensIn),l=CU(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(Le.border("\u250C"+"\u2500".repeat(r-2)+"\u2510")),console.log(s(Le.logo("Session complete. \u{1FABC}"))),console.log(Le.border("\u251C"+"\u2500".repeat(r-2)+"\u2524")),console.log(s(Le.logo("Session Summary"))),console.log(s(Le.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(Le.logo("Token Usage"))),console.log(s(Le.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(Le.dim("Cached".padEnd(15))+`${CU(p)} (${g}%)`))}let f=t.cacheSavings??0,h=f>0?Le.dim(` \xB7 saved ~$${f.toFixed(4)} by prompt caching`):"";console.log(s(Le.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(Le.dim("Goal: ")+m(g,n-6)))}t.goalResumeLine&&console.log(s(Le.dim(m(` ${t.goalResumeLine}`,n)))),console.log(s(Le.dim("Model: ")+Le.model(d))),console.log(Le.border("\u2514"+"\u2500".repeat(r-2)+"\u2518")),console.log("")}var ert,Le,rrt,nrt,Xme,QE=I(()=>{"use strict";ys();Jme();Dn();Bu();xf();ert="0.25.8",Le={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}};rrt=24,nrt=/[\x00-\x1F\x7F-\x9F\u2028\u2029\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\u200B-\u200D\u2060\uFEFF\u00AD]/;Xme=!1});function nge(){rge=Date.now()}function ige(){return rge}var rge,bU=I(()=>{"use strict";rge=Date.now()});function sge(t){if(t==="\r")return!0;if(t.length===1){let e=t.charCodeAt(0);return e>=32&&e<=126}return!1}var oge=I(()=>{"use strict"});function age(t){for(let e of Art)if(t===e||t.startsWith(e+" "))return{prefix:e,noteText:t.slice(e.length).trim()};return null}var Art,cge=I(()=>{"use strict";Art=["/note","/inject","/now"]});function lge(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 uge=I(()=>{"use strict"});import{useEffect as dge}from"react";function pge(){let t=ss(i=>i.peekOpen),e=ss(i=>i.peekIndex),r=ss(i=>i.results),n=ri(i=>i.renderEpoch);return dge(()=>{if(!vE())return;let i=t&&e>=0?r[e]:void 0;t&&i?IU(Tee(i,e,r.length,process.stdout.rows||24,process.stdout.columns||80)):P0()},[t,e,r,n]),dge(()=>()=>P0(),[]),null}var fge=I(()=>{"use strict";Bh();B0();_d();KT()});function _rt(){return process.stdin.listenerCount("data")}function PE(t){if(!process.env.AII_DEBUG&&!process.env.AII_LOOP_DEBUG)return;let e=_rt();e>1&&console.error(`[input] WARNING: ${e} stdin 'data' listeners live (${t}) \u2014 MF-1 double-listener class`)}var hge=I(()=>{"use strict"});var Cge={};rt(Cge,{App:()=>Sge,DialogKeyHandler:()=>_ge,FeedbackKeyHandler:()=>Ege,QuestionDialogKeyHandler:()=>yge,default:()=>Trt});import{jsx as qr,jsxs as TU,Fragment as Ert}from"react/jsx-runtime";import yrt,{useEffect as Cd,useCallback as Gh,useState as Ja,useRef as nn,useMemo as mge}from"react";import{Box as $h,Text as wU,Static as Srt}from"ink";import{useShallow as Sd}from"zustand/react/shallow";function Crt({onInterrupt:t}){let e=nn(t);return e.current=t,Cd(()=>{if(!process.stdin.isTTY)return;process.stdin.resume();let r=n=>{nge();let i=n.toString();if(i===""){Ln.getState().dropRemote();return}if(tn.getState().active){if(i==="\x1B"){tn.getState().release("esc");return}i===""?tn.getState().release("ctrl_c"):sge(i)&&tn.getState().release("typed")}let o=g0(),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===""){ME(0);return}if(i===""){let d=md();if(d.peekOpen){d.closePeek();return}let p=gl();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=Na().loopMode,f=age(d);if(f){let h=f.noteText;if(!h){Do().showToast(Le.dim(`\u25C6 ${f.prefix} requires a message (usage: ${f.prefix} <text>)`)),u.clear();return}if(!p){let y=cU();y.noteToastId!==null&&Do().clearToast(y.noteToastId),y.setPendingNote(h);let b=process.stdout.columns||80,C=Math.floor(b*.618)-16,T=h.replace(/\n/g," "),k=T.length>C?T.slice(0,C)+"\u2026":T,w=Do(),D=w.nextId;w.showToast(Le.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;Do().showToast(Le.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";Do().showToast(Le.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===`
|