@kodax-ai/kodax 0.7.43 → 0.7.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/chunks/{chunk-YMRZBS4G.js → chunk-35BDEEC5.js} +1 -1
  3. package/dist/chunks/{chunk-7G5PSL6C.js → chunk-4YPL2UVZ.js} +253 -235
  4. package/dist/chunks/chunk-DI2G3YWL.js +31 -0
  5. package/dist/chunks/chunk-HHQ7YTGM.js +425 -0
  6. package/dist/chunks/chunk-QHILHQBB.js +519 -0
  7. package/dist/chunks/{chunk-IYSK7LUK.js → chunk-RUDYNAK7.js} +1 -1
  8. package/dist/chunks/{compaction-config-3E57ABCT.js → compaction-config-NAPRF7XR.js} +1 -1
  9. package/dist/chunks/{construction-bootstrap-JR63KI5N.js → construction-bootstrap-PHTGBRNU.js} +1 -1
  10. package/dist/chunks/dist-CCYBJJZY.js +2 -0
  11. package/dist/chunks/{dist-XANXEVTU.js → dist-RHIHZAYX.js} +1 -1
  12. package/dist/chunks/{utils-HQ2QCKJA.js → utils-TV3UYCHQ.js} +1 -1
  13. package/dist/index.d.ts +8 -8
  14. package/dist/index.js +2 -2
  15. package/dist/kodax_cli.js +624 -589
  16. package/dist/provider-capabilities.json +167 -0
  17. package/dist/sdk-agent.d.ts +62 -7
  18. package/dist/sdk-agent.js +1 -1
  19. package/dist/sdk-coding.d.ts +367 -13
  20. package/dist/sdk-coding.js +1 -1
  21. package/dist/sdk-llm.d.ts +1 -1
  22. package/dist/sdk-llm.js +1 -1
  23. package/dist/sdk-mcp.js +1 -1
  24. package/dist/sdk-repl.d.ts +6 -6
  25. package/dist/sdk-repl.js +1 -1
  26. package/dist/sdk-session.d.ts +2 -2
  27. package/dist/sdk-session.js +1 -1
  28. package/dist/sdk-skills.js +1 -1
  29. package/dist/types-chunks/{bash-prefix-extractor.d-DMrGImMl.d.ts → bash-prefix-extractor.d-DdoSeghD.d.ts} +417 -5
  30. package/dist/types-chunks/file-tracker.d-DOfaoCbJ.d.ts +633 -0
  31. package/dist/types-chunks/{resolver.d-CA68_NeH.d.ts → resolver.d-B7ZnVuuf.d.ts} +16 -13
  32. package/dist/types-chunks/{storage.d-DPAEX7zS.d.ts → storage.d-DFD9ln5c.d.ts} +1 -1
  33. package/dist/types-chunks/{file-tracker.d-zaLZeNBK.d.ts → types.d-DM8zEJgF.d.ts} +1029 -535
  34. package/dist/types-chunks/{types.d-mM8vqvhT.d.ts → types.d-HBbWT-iA.d.ts} +41 -3
  35. package/dist/types-chunks/{utils.d-DkLZD_wa.d.ts → utils.d-C5fzCE9W.d.ts} +3 -3
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-K75O2CAE.js +0 -31
  38. package/dist/chunks/chunk-UG4262JI.js +0 -502
  39. package/dist/chunks/chunk-VHKAJDQD.js +0 -425
  40. package/dist/chunks/dist-KWHUKXEL.js +0 -2
  41. package/dist/types-chunks/types.d-CKJtjo-6.d.ts +0 -1127
@@ -1,502 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{A as kx,B as Rx,C as Ex,a as te,c as pa,j as Ri,k as Vn,l as Ei,m as xo,n as vx,o as Ix,p as $l,q as cm,r as Ll,s as lm,t as um,u as dm,w as ga,x as fm,y as gr,z as wo}from"./chunk-YMRZBS4G.js";import{a as Ol}from"./chunk-IYSK7LUK.js";import{n as Mx,o as Ax,p as _x}from"./chunk-EVIDQWMF.js";import{$ as cx,Ba as dx,Dd as bx,Gd as Pl,Hc as ma,P as sx,Q as Al,Qb as gx,S as fa,Sc as xx,T as ax,Tc as wx,Vc as am,Wc as Sx,Xc as Tx,c as rm,d as ua,e as Ky,g as im,hd as Cx,jc as hx,kc as yx,nb as pr,qa as lx,ra as sm,sa as ux,sb as _l,vb as fx,xb as mx,zb as px}from"./chunk-7G5PSL6C.js";import{Q as Rl,aa as jy,ca as nm,da as Gy,j as mo,qa as po,ra as xi,sa as wi}from"./chunk-K75O2CAE.js";import{$b as Ti,Bb as Zy,Cb as ex,Db as tx,Ic as ix,Qb as mr,Ra as Vy,Rb as ho,Wa as El,Wb as nx,Ya as zy,ab as Xy,bb as Yy,cb as qy,db as Qy,fb as Jy,hc as hn,jc as Et,k as go,lc as Ci,mc as bi,nc as rx,pc as vi,qc as Ii,rc as ki,sc as Ml,tc as yo,uc as ox,va as Si,wa as gn,xc as om,yc as da,za as Kn}from"./chunk-VHKAJDQD.js";import{a as i,b as tm,c as jI}from"./chunk-V4WSBIXB.js";var CS=tm((VW,TS)=>{"use strict";TS.exports=i(function(t){return t.map(function(n){return n===""?"''":n&&typeof n=="object"?n.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(n)&&!/'/.test(n)?"'"+n.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(n)?'"'+n.replace(/(["\\$`!])/g,"\\$1")+'"':String(n).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")},"quote")});var MS=tm((XW,ES)=>{"use strict";var RS="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",bS=new RegExp("^"+RS+"$"),vS="|&;()<> \\t",SM='"((\\\\"|[^"])*?)"',TM="'((\\\\'|[^'])*?)'",CM=/^#$/,IS="'",kS='"',ip="$",Ao="",bM=4294967296;for(sp=0;sp<4;sp++)Ao+=(bM*Math.random()).toString(16);var sp,vM=new RegExp("^"+Ao);function IM(e,t){for(var n=t.lastIndex,r=[],o;o=t.exec(e);)r.push(o),t.lastIndex===o.index&&(t.lastIndex+=1);return t.lastIndex=n,r}i(IM,"matchAll");function kM(e,t,n){var r=typeof e=="function"?e(n):e[n];return typeof r>"u"&&n!=""?r="":typeof r>"u"&&(r="$"),typeof r=="object"?t+Ao+JSON.stringify(r)+Ao:t+r}i(kM,"getVar");function RM(e,t,n){n||(n={});var r=n.escape||"\\",o="(\\"+r+`['"`+vS+`]|[^\\s'"`+vS+"])+",s=new RegExp(["("+RS+")","("+o+"|"+SM+"|"+TM+")+"].join("|"),"g"),a=IM(e,s);if(a.length===0)return[];t||(t={});var c=!1;return a.map(function(l){var d=l[0];if(!d||c)return;if(bS.test(d))return{op:d};var m=!1,p=!1,g="",x=!1,y;function T(){y+=1;var O,P,D=d.charAt(y);if(D==="{"){if(y+=1,d.charAt(y)==="}")throw new Error("Bad substitution: "+d.slice(y-2,y+1));if(O=d.indexOf("}",y),O<0)throw new Error("Bad substitution: "+d.slice(y));P=d.slice(y,O),y=O}else if(/[*@#?$!_-]/.test(D))P=D,y+=1;else{var L=d.slice(y);O=L.match(/[^\w\d_]/),O?(P=L.slice(0,O.index),y+=O.index-1):(P=L,y=d.length)}return kM(t,"",P)}for(i(T,"parseEnvVar"),y=0;y<d.length;y++){var w=d.charAt(y);if(x=x||!m&&(w==="*"||w==="?"),p)g+=w,p=!1;else if(m)w===m?m=!1:m==IS?g+=w:w===r?(y+=1,w=d.charAt(y),w===kS||w===r||w===ip?g+=w:g+=r+w):w===ip?g+=T():g+=w;else if(w===kS||w===IS)m=w;else{if(bS.test(w))return{op:d};if(CM.test(w)){c=!0;var v={comment:e.slice(l.index+y+1)};return g.length?[g,v]:[v]}else w===r?p=!0:w===ip?g+=T():g+=w}}return x?{op:"glob",pattern:g}:g}).reduce(function(l,d){return typeof d>"u"?l:l.concat(d)},[])}i(RM,"parseInternal");ES.exports=i(function(t,n,r){var o=RM(t,n,r);return typeof n!="function"?o:o.reduce(function(s,a){if(typeof a=="object")return s.concat(a);var c=a.split(RegExp("("+Ao+".*?"+Ao+")","g"));return c.length===1?s.concat(c[0]):s.concat(c.filter(Boolean).map(function(l){return vM.test(l)?JSON.parse(l.split(Ao)[1]):l}))},[])},"parse")});var AS=tm(ap=>{"use strict";ap.quote=CS();ap.parse=MS()});import{spawnSync as GI}from"node:child_process";function Dl(e){return e==="1"||e?.toLowerCase()==="true"}i(Dl,"isTruthyEnv");function Px(e){return e==="0"||e?.toLowerCase()==="false"}i(Px,"isFalseyEnv");function Mi(e=process.env){return e.TERM_PROGRAM?.toLowerCase()==="vscode"||!!e.VSCODE_GIT_IPC_HANDLE||!!e.VSCODE_INJECTION}i(Mi,"isVsCodeTerminalHostEnv");function Ai(e={}){let t=e.env??process.env;return(e.platform??process.platform)==="win32"||!!t.WT_SESSION}i(Ai,"hasCursorUpViewportYankRisk");function KI(e){return!!(e.SSH_CONNECTION||e.SSH_CLIENT||e.SSH_TTY)}i(KI,"isSshSession");function ha(e={}){let t=e.env??process.env;return Dl(t.KODAX_FULLSCREEN)?!1:(e.platform??process.platform)==="win32"&&KI(t)}i(ha,"isRemoteConptyHost");function _i(e={}){let t=e.env??process.env;return Ai(e)||Mi(t)}i(_i,"hasMainScreenRenderScrollRisk");function VI(e){if(!e.TMUX||e.TERM_PROGRAM!=="iTerm.app")return!1;let t=e.TERM??"";return!t.startsWith("screen")&&!t.startsWith("tmux")}i(VI,"isTmuxControlModeEnvHeuristic");var hr;function ya(e={}){if(typeof e.tmuxControlMode=="boolean")return e.tmuxControlMode;let t=e.env??process.env,n=e.platform??process.platform;if(n==="win32")return!1;if(VI(t))return!0;if(!(t===process.env&&n===process.platform))return!1;if(hr!==void 0||(hr=!1,!t.TMUX)||t.TERM_PROGRAM&&t.TERM_PROGRAM!=="iTerm.app")return hr;try{let o=GI("tmux",["display-message","-p","#{client_control_mode}"],{encoding:"utf8",timeout:2e3});o.status===0&&(hr=o.stdout.trim()==="1")}catch{hr=!1}return hr}i(ya,"isTmuxControlMode");function mm(){hr=void 0}i(mm,"resetTmuxControlModeProbeForTesting");function So(e={}){let t=e.env??process.env,n=e.isTTY??process.stdout.isTTY===!0,r=e.rawModeSupported??(process.stdin.isTTY===!0&&typeof process.stdin.setRawMode=="function");return!n||!r||t.TERM==="dumb"||t.CI==="true"?"unsupported_control_host":ya(e)?"tmux_control_mode":Mi(t)?"xtermjs_host":ha(e)?"remote_conpty_host":Ai(e)?"degraded_vt":"native_vt"}i(So,"detectTerminalRenderHost");var To=So;function Pi(e={}){let t=e.env??process.env;if(Dl(t.KODAX_FORCE_INK))return"legacy";let n=t.KODAX_TUI_RENDERER?.trim().toLowerCase();return n==="legacy"||n==="owned"||n==="auto"?n:"auto"}i(Pi,"resolveConfiguredTuiRendererMode");function Co(e={}){let t=Pi(e);if(t==="legacy"||t==="owned")return t;let n=So(e);return n==="unsupported_control_host"||n==="tmux_control_mode"?"legacy":"owned"}i(Co,"resolveEffectiveTuiRendererMode");function Nl(e={}){let t=e.env??process.env;if(Dl(t.KODAX_FORCE_CLASSIC_REPL))return"classic";let n=Pi({env:t});if(n==="legacy"||n==="owned")return"ink";let r=So(e);return r==="unsupported_control_host"||r==="tmux_control_mode"?"classic":"ink"}i(Nl,"resolveInteractiveSurfacePreference");var $x={enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!0};function bo(e,t="owned",n={}){let r=n.env??process.env;return Px(r.KODAX_FULLSCREEN)?$x:zI(e,t)}i(bo,"resolveFullscreenPolicy");function zI(e,t){if(t==="legacy")switch(e){case"native_vt":return{enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!0,transcriptSpinnerAnimation:!0};case"xtermjs_host":case"degraded_vt":case"remote_conpty_host":return{enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!1};default:return{enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!1}}switch(e){case"native_vt":return{enabled:!0,promptShell:"virtual",transcriptShell:"virtual",mouseWheel:!0,mouseClicks:!0,streamingPreview:!0,transcriptSpinnerAnimation:!0};case"xtermjs_host":return{enabled:!0,promptShell:"virtual",transcriptShell:"virtual",mouseWheel:!0,mouseClicks:!0,streamingPreview:!0,transcriptSpinnerAnimation:!0};case"degraded_vt":return{enabled:!0,promptShell:"virtual",transcriptShell:"virtual",mouseWheel:!0,mouseClicks:!0,streamingPreview:!0,transcriptSpinnerAnimation:!0};case"remote_conpty_host":return $x;default:return{enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!1}}}i(zI,"buildFullscreenPolicy");function $i(e,t={}){let n=t.rendererMode??"owned",r=bo(e,n,{env:t.env}),o=e!=="unsupported_control_host"&&e!=="tmux_control_mode";return{profile:e,ownsViewportByDefault:r.enabled&&r.promptShell==="virtual",supportsMouseTracking:r.mouseWheel||r.mouseClicks,bufferingMode:r.streamingPreview?"live":"buffered-fallback",supportsFullscreenLayout:r.enabled,supportsOverlaySurface:r.enabled,supportsSelection:o,supportsCopyOnSelect:!1,supportsWheelHistory:r.mouseWheel,supportsViewportChrome:r.enabled,supportsSearchViewport:r.enabled,supportsStickyPrompt:r.enabled}}i($i,"getTerminalHostCapabilities");function Bl(e={}){return Co(e)==="owned"}i(Bl,"isOwnedRendererPreferred");function Hl(e={}){let t=e.env??process.env;return Dl(t.KODAX_FORCE_CLASSIC_REPL)&&!Px(t.KODAX_FORCE_CLASSIC_REPL)}i(Hl,"isClassicReplForced");var Li=class{static{i(this,"LRUCache")}capacity;cache;constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let n=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,n),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(t,n)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}},pm=1,gm=2,XI=1e3,Lx;function Fl(){if(!(typeof Intl>"u"||typeof Intl.Segmenter!="function"))return Lx??=new Intl.Segmenter("en",{granularity:"grapheme"}),Lx}i(Fl,"getGraphemeSegmenter");function rn(e){if(!e)return 0;let t=Fl();if(t){let n=0;for(let r of t.segment(e))n++;return n}return[...e].length}i(rn,"getCodePointLength");function zn(e){if(!e)return!1;let t=e.codePointAt(0);return t===void 0?!1:t>=19968&&t<=40959||t>=13312&&t<=19903||t>=63744&&t<=64255||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=44032&&t<=55215||t>=12288&&t<=12351||t>=65280&&t<=65519||t>=128512&&t<=128591||t>=127744&&t<=128511||t>=128640&&t<=128767||t>=127456&&t<=127487||t>=9728&&t<=9983||t>=9984&&t<=10175||t>=129280&&t<=129535||t>=129536&&t<=129647||t>=129648&&t<=129791}i(zn,"isWideChar");function Xn(e){if(!e)return 0;let t=0,n=Fl();if(n)for(let r of n.segment(e))t+=zn(r.segment)?gm:pm;else for(let r of e)t+=zn(r)?gm:pm;return t}i(Xn,"getVisualWidth");function YI(e,t){if(!e||t<0)return"";let n=Fl();if(n){let o=0;for(let s of n.segment(e)){if(o===t)return s.segment;o++}return""}let r=[...e];return t>=r.length?"":r[t]}i(YI,"getCharAtCodePoint");function Vt(e){if(!e)return[];let t=Fl();if(t){let n=[];for(let r of t.segment(e))n.push(r.segment);return n}return[...e]}i(Vt,"splitByCodePoints");function qI(e,t,n){return Vt(e).slice(t,n).join("")}i(qI,"sliceByCodePoints");function Ox(e,t){let n=Math.max(0,t),r=Vt(e),o=0,s=0;for(;o<r.length;){let a=zn(r[o])?gm:pm;if(s+a>n)break;s+=a,o++}return{before:r.slice(0,o).join(""),current:r[o]??"",after:r.slice(o+1).join("")}}i(Ox,"splitAtVisualColumn");function xa(e,t,n=!1){if(!e||t<=0)return"";let r="\u2026",s=n?t-1:t,a="",c=0,l=Vt(e);for(let d of l){let m=zn(d)?2:1;if(c+m>s)break;a+=d,c+=m}return n&&a.length<e.length&&(a+=r),a}i(xa,"truncateByVisualWidth");var hm=new Li(XI);function ym(e){let t=hm.get(e);if(t!==void 0)return t;let n=Xn(e);return hm.set(e,n),n}i(ym,"getVisualWidthCached");function zt(e,t,n,r){let o=[],s=[],a=[];for(let c=0;c<e.length;c++){let l=e[c]||"";if(s[c]=[],l.length===0){o.push("");let p=o.length-1;s[c].push([p,0]),a.push([c,0]);continue}let d=0,m=Vt(l);for(;d<m.length;){let p="",g=0,x=d,y=-1;for(let T=d;T<m.length;T++){let w=m[T],v=zn(w)?2:1;if(g+v>t){y>=0&&T-d>0?(p=m.slice(d,y).join(""),g=m.slice(d,y).reduce((O,P)=>O+(zn(P)?2:1),0),x=y):p.length===0&&v>t&&(p=w,g=v,x=T+1);break}p+=w,g+=v,x=T+1,w===" "&&(y=T+1)}if(p.length>0||o.length===0){let T=d,w=o.length;o.push(p),s[c].push([w,T]),a.push([c,T])}d=x}}return{visualLines:o,logicalToVisualMap:s,visualToLogicalMap:a}}i(zt,"calculateVisualLayout");function xm(e,t){let{logicalToVisualMap:n,visualLines:r}=e;if(r.length===0)return[0,0];let[o,s]=t,a=n[o];if(!a||a.length===0)return[0,0];let c;for(let[x,y]of a)if(y<=s)c=[x,y];else break;let[l,d]=c??a[0],m=r[l]??"",p=Math.max(0,s-d),g=Xn(qI(m,0,p));return[l,g]}i(xm,"calculateVisualCursorFromLayout");var wm={name:"dark",colors:{primary:"#01A4FF",secondary:"#8B5CF6",accent:"#F59E0B",text:"#CCCCCC",dim:"#666666",thinking:"#A3ADC2",success:"#19C37D",warning:"#FF9F43",error:"#FF5F56",info:"#01A4FF",hint:"#8B5CF6",background:"#0D0D0D",inputBackground:"#1A1A1A"},symbols:{prompt:">",success:"\u2713",error:"\u2717",warning:"!",spinner:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]}},Dx={name:"minimal",colors:{primary:"#01A4FF",secondary:"#8B5CF6",accent:"#F59E0B",text:"#CCCCCC",dim:"#666666",thinking:"#A3ADC2",success:"#19C37D",warning:"#FF9F43",error:"#FF5F56",info:"#01A4FF",hint:"#8B5CF6",background:"#0D0D0D",inputBackground:"#1A1A1A"},symbols:{prompt:"$",success:"+",error:"-",warning:"?",spinner:["-","\\","|","/"]}};var Nx={dark:wm,minimal:Dx};function ne(e="dark"){return Nx[e]??wm}i(ne,"getTheme");function ND(){return Object.keys(Nx)}i(ND,"getThemeNames");import{jsx as Yt,jsxs as xn,Fragment as oM}from"react/jsx-runtime";import{useMemo as yu}from"react";import{jsx as sS}from"react/jsx-runtime";import{createContext as LE,useContext as Eo,useEffect as Xi,useMemo as iS,useState as OE,useCallback as aS,useRef as uu}from"react";import{Stream as uE}from"node:stream";import{openSync as dE,writeSync as zw}from"node:fs";import{performance as fE}from"node:perf_hooks";import{tmpdir as mE}from"node:os";import{join as pE}from"node:path";import Sm,{forwardRef as ZI,useContext as ek}from"react";import{createContext as QI}from"react";var Oi=QI({isScreenReaderEnabled:!1});import{createContext as JI}from"react";var Wl=JI(void 0);var Bx=ZI(({children:e,backgroundColor:t,"aria-label":n,"aria-hidden":r,"aria-role":o,"aria-state":s,...a},c)=>{let{isScreenReaderEnabled:l}=ek(Oi),d=n?Sm.createElement("ink-text",null,n):void 0;if(l&&r)return null;let m=Sm.createElement("ink-box",{ref:c,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:0,flexShrink:1,...a,backgroundColor:t,overflowX:a.overflowX??a.overflow??"visible",overflowY:a.overflowY??a.overflow??"visible"},internal_accessibility:{role:o,state:s}},l&&d?d:e);return t?Sm.createElement(Wl.Provider,{value:t},m):m});Bx.displayName="Box";var yn=Bx;import ok,{useContext as Hx}from"react";import Di from"chalk";import Dr from"chalk";var tk=/^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/,nk=/^ansi256\(\s?(\d+)\s?\)$/;function rk(e){return e in Dr}i(rk,"isNamedColor");function Pn(e,t,n){if(!t)return e;if(rk(t)){let r=Dr;if(n==="foreground")return r[t]?.(e)??e;let o=`bg${t[0].toUpperCase()+t.slice(1)}`;return r[o]?.(e)??e}if(t.startsWith("#"))return n==="foreground"?Dr.hex(t)(e):Dr.bgHex(t)(e);if(t.startsWith("ansi256")){let r=nk.exec(t);if(!r)return e;let o=Number(r[1]);return n==="foreground"?Dr.ansi256(o)(e):Dr.bgAnsi256(o)(e)}if(t.startsWith("rgb")){let r=tk.exec(t);if(!r)return e;let o=Number(r[1]),s=Number(r[2]),a=Number(r[3]);return n==="foreground"?Dr.rgb(o,s,a)(e):Dr.bgRgb(o,s,a)(e)}return e}i(Pn,"colorize");function Xt({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:o=!1,underline:s=!1,strikethrough:a=!1,inverse:c=!1,wrap:l="wrap",children:d,"aria-label":m,"aria-hidden":p=!1}){let{isScreenReaderEnabled:g}=Hx(Oi),x=Hx(Wl),y=g&&m?m:d;if(y==null)return null;let T=i(w=>{let v=w;n&&(v=Di.dim(v)),e&&(v=Pn(v,e,"foreground"));let O=t??x;return O&&(v=Pn(v,O,"background")),r&&(v=Di.bold(v)),o&&(v=Di.italic(v)),s&&(v=Di.underline(v)),a&&(v=Di.strikethrough(v)),c&&(v=Di.inverse(v)),v},"transform");return g&&p?null:ok.createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:l},internal_transform:T},g&&m?m:d)}i(Xt,"Text");import ik,{useLayoutEffect as sk,useMemo as Fx,useState as ak}from"react";function Tm({items:e,children:t,style:n}){let[r,o]=ak(0),s=Fx(()=>e.slice(r),[e,r]);sk(()=>{o(e.length)},[e.length]);let a=s.map((l,d)=>t(l,r+d)),c=Fx(()=>({position:"absolute",flexDirection:"column",...n}),[n]);return ik.createElement("ink-box",{internal_static:!0,style:c},a)}i(Tm,"Static");import zi from"node:process";import Gw from"react";import{throttle as KR}from"es-toolkit/compat";import Sr from"ansi-escapes";import Hr from"is-in-ci";import VR from"auto-bind";import{onExit as zR}from"signal-exit";import XR from"patch-console";import{LegacyRoot as YR,ConcurrentRoot as qR}from"react-reconciler/constants.js";import QR from"yoga-layout";import JR from"wrap-ansi";import ZR from"terminal-size";import ck from"node:process";var Ul=i(()=>ck.env.DEV==="true","isDev");import Ok from"react-reconciler";import{DefaultEventPriority as Dk,NoEventPriority as nw}from"react-reconciler/constants.js";import*as Nr from"scheduler";import Jx from"yoga-layout";import{createContext as Nk}from"react";import bk from"yoga-layout";import lk from"widest-line";var Wx=new Map,uk=i(e=>{if(e.length===0)return{width:0,height:0};let t=Wx.get(e);if(t)return t;let n=lk(e),r=e.split(`
3
- `).length,o={width:n,height:r};return Wx.set(e,o),o},"measureText"),Cm=uk;import dk from"wrap-ansi";import fk from"cli-truncate";var Ux={},mk=i((e,t,n)=>{let r=e+String(t)+String(n),o=Ux[r];if(o)return o;let s=e;if(n==="wrap"&&(s=dk(e,t,{trim:!1,hard:!0})),n.startsWith("truncate")){let a="end";n==="truncate-middle"&&(a="middle"),n==="truncate-start"&&(a="start"),s=fk(e,t,{position:a})}return Ux[r]=s,s},"wrapText"),jl=mk;var pk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=63},"isCsiParameterCharacter"),gk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isCsiIntermediateCharacter"),hk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=64&&t<=126},"isCsiFinalCharacter"),Kx=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isEscapeIntermediateCharacter"),yk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=126},"isEscapeFinalCharacter"),Vx=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=128&&t<=159},"isC1ControlCharacter"),jx=i((e,t)=>{let n=t;for(;n<e.length;){let c=e[n];if(!pk(c))break;n++}let r=e.slice(t,n),o=n;for(;n<e.length;){let c=e[n];if(!gk(c))break;n++}let s=e.slice(o,n),a=e[n];if(!(a===void 0||!hk(a)))return{endIndex:n+1,parameterString:r,intermediateString:s,finalCharacter:a}},"readCsiSequence"),Gx=i((e,t,n)=>{for(let r=t;r<e.length;r++){let o=e[r];if(n&&o==="\x07"||o==="\x9C")return r+1;if(o==="\x1B"){let s=e[r+1];if(s==="\x1B"){r++;continue}if(s==="\\")return r+2}}},"findControlStringTerminatorIndex"),xk=i((e,t)=>{let n=t;for(;n<e.length;){let s=e[n];if(!Kx(s))break;n++}let r=e.slice(t,n),o=e[n];if(!(o===void 0||!yk(o)))return{endIndex:n+1,intermediateString:r,finalCharacter:o}},"readEscapeSequence"),wk=i(e=>{switch(e){case"]":return{type:"osc",allowBellTerminator:!0};case"P":return{type:"dcs",allowBellTerminator:!1};case"^":return{type:"pm",allowBellTerminator:!1};case"_":return{type:"apc",allowBellTerminator:!1};case"X":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromEscapeIntroducer"),Sk=i(e=>{switch(e){case"\x9D":return{type:"osc",allowBellTerminator:!0};case"\x90":return{type:"dcs",allowBellTerminator:!1};case"\x9E":return{type:"pm",allowBellTerminator:!1};case"\x9F":return{type:"apc",allowBellTerminator:!1};case"\x98":return{type:"sos",allowBellTerminator:!1};default:return}},"getControlStringFromC1Introducer"),bm=i(e=>{if(e.includes("\x1B"))return!0;for(let t of e)if(Vx(t))return!0;return!1},"hasAnsiControlCharacters"),Ni=i((e,t,n,r)=>(r>n&&e.push({type:"text",value:t.slice(n,r)}),e.push({type:"invalid",value:t.slice(r)}),e),"malformedFromIndex"),zx=i(e=>{if(!bm(e))return[{type:"text",value:e}];let t=[],n=0;for(let r=0;r<e.length;){let o=e[r];if(o===void 0)break;if(o==="\x1B"){let a=e[r+1];if(a===void 0)return Ni(t,e,n,r);if(a==="["){let d=jx(e,r+2);if(d===void 0)return Ni(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"csi",value:e.slice(r,d.endIndex),parameterString:d.parameterString,intermediateString:d.intermediateString,finalCharacter:d.finalCharacter}),r=d.endIndex,n=r;continue}let c=wk(a);if(c!==void 0){let d=Gx(e,r+2,c.allowBellTerminator);if(d===void 0)return Ni(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:c.type,value:e.slice(r,d)}),r=d,n=r;continue}let l=xk(e,r+1);if(l===void 0){if(Kx(a))return Ni(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),r++,n=r;continue}r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"esc",value:e.slice(r,l.endIndex),intermediateString:l.intermediateString,finalCharacter:l.finalCharacter}),r=l.endIndex,n=r;continue}if(o==="\x9B"){let a=jx(e,r+1);if(a===void 0)return Ni(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"csi",value:e.slice(r,a.endIndex),parameterString:a.parameterString,intermediateString:a.intermediateString,finalCharacter:a.finalCharacter}),r=a.endIndex,n=r;continue}let s=Sk(o);if(s!==void 0){let a=Gx(e,r+1,s.allowBellTerminator);if(a===void 0)return Ni(t,e,n,r);r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:s.type,value:e.slice(r,a)}),r=a,n=r;continue}if(o==="\x9C"){r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"st",value:o}),r++,n=r;continue}if(Vx(o)){r>n&&t.push({type:"text",value:e.slice(n,r)}),t.push({type:"c1",value:o}),r++,n=r;continue}r++}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t},"tokenizeAnsi");var Tk=/^[\d:;]*$/,Ck=i(e=>{if(!bm(e))return e;let t="";for(let n of zx(e)){if(n.type==="text"||n.type==="osc"){t+=n.value;continue}n.type==="csi"&&n.finalCharacter==="m"&&n.intermediateString===""&&Tk.test(n.parameterString)&&(t+=n.value)}return t},"sanitizeAnsi"),Xx=Ck;var Yx=i(e=>{let t="";for(let n=0;n<e.childNodes.length;n++){let r=e.childNodes[n];if(r===void 0)continue;let o="";r.nodeName==="#text"?o=r.nodeValue:((r.nodeName==="ink-text"||r.nodeName==="ink-virtual-text")&&(o=Yx(r)),o.length>0&&typeof r.internal_transform=="function"&&(o=r.internal_transform(o,n))),t+=o}return Xx(t)},"squashTextNodes"),wa=Yx;var Gl=i(e=>{let t={nodeName:e,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:e==="ink-virtual-text"?void 0:bk.Node.create(),internal_accessibility:{}};return e==="ink-text"&&t.yogaNode?.setMeasureFunc(vk.bind(null,t)),t},"createNode"),Kl=i((e,t)=>{t.parentNode&&Sa(t.parentNode,t),t.parentNode=e,e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount()),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Vl(e)},"appendChildNode"),vm=i((e,t,n)=>{t.parentNode&&Sa(t.parentNode,t),t.parentNode=e;let r=e.childNodes.indexOf(n);r>=0?(e.childNodes.splice(r,0,t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,r)):(e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount())),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Vl(e)},"insertBeforeNode"),Sa=i((e,t)=>{t.yogaNode&&t.parentNode?.yogaNode?.removeChild(t.yogaNode),t.parentNode=void 0;let n=e.childNodes.indexOf(t);n>=0&&e.childNodes.splice(n,1),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&Vl(e)},"removeChildNode"),Im=i((e,t,n)=>{if(t==="internal_accessibility"){e.internal_accessibility=n;return}e.attributes[t]=n},"setAttribute"),km=i((e,t)=>{e.style=t},"setStyle"),qx=i(e=>{let t={nodeName:"#text",nodeValue:e,yogaNode:void 0,parentNode:void 0,style:{}};return Ta(t,e),t},"createTextNode"),vk=i(function(e,t){let n=e.nodeName==="#text"?e.nodeValue:wa(e),r=Cm(n);if(r.width<=t||r.width>=1&&t>0&&t<1)return r;let o=e.style?.textWrap??"wrap",s=jl(n,t,o);return Cm(s)},"measureTextNode"),Qx=i(e=>{if(e?.parentNode)return e.yogaNode??Qx(e.parentNode)},"findClosestYogaNode"),Vl=i(e=>{Qx(e)?.markDirty()},"markNodeAsDirty"),Ta=i((e,t)=>{typeof t!="string"&&(t=String(t)),e.nodeValue=t,Vl(e)},"setTextNodeValue");import he from"yoga-layout";var kk=i((e,t)=>{"position"in t&&e.setPositionType(t.position==="absolute"?he.POSITION_TYPE_ABSOLUTE:he.POSITION_TYPE_RELATIVE),"top"in t&&e.setPosition(he.EDGE_TOP,t.top??0),"bottom"in t&&e.setPosition(he.EDGE_BOTTOM,t.bottom??0),"left"in t&&e.setPosition(he.EDGE_LEFT,t.left??0),"right"in t&&e.setPosition(he.EDGE_RIGHT,t.right??0)},"applyPositionStyles"),Rk=i((e,t)=>{"margin"in t&&e.setMargin(he.EDGE_ALL,t.margin??0),"marginX"in t&&e.setMargin(he.EDGE_HORIZONTAL,t.marginX??0),"marginY"in t&&e.setMargin(he.EDGE_VERTICAL,t.marginY??0),"marginLeft"in t&&e.setMargin(he.EDGE_START,t.marginLeft||0),"marginRight"in t&&e.setMargin(he.EDGE_END,t.marginRight||0),"marginTop"in t&&e.setMargin(he.EDGE_TOP,t.marginTop||0),"marginBottom"in t&&e.setMargin(he.EDGE_BOTTOM,t.marginBottom||0)},"applyMarginStyles"),Ek=i((e,t)=>{"padding"in t&&e.setPadding(he.EDGE_ALL,t.padding??0),"paddingX"in t&&e.setPadding(he.EDGE_HORIZONTAL,t.paddingX??0),"paddingY"in t&&e.setPadding(he.EDGE_VERTICAL,t.paddingY??0),"paddingLeft"in t&&e.setPadding(he.EDGE_LEFT,t.paddingLeft||0),"paddingRight"in t&&e.setPadding(he.EDGE_RIGHT,t.paddingRight||0),"paddingTop"in t&&e.setPadding(he.EDGE_TOP,t.paddingTop||0),"paddingBottom"in t&&e.setPadding(he.EDGE_BOTTOM,t.paddingBottom||0)},"applyPaddingStyles"),Mk=i((e,t)=>{"flexGrow"in t&&e.setFlexGrow(t.flexGrow??0),"flexShrink"in t&&e.setFlexShrink(typeof t.flexShrink=="number"?t.flexShrink:1),"flexWrap"in t&&(t.flexWrap==="nowrap"&&e.setFlexWrap(he.WRAP_NO_WRAP),t.flexWrap==="wrap"&&e.setFlexWrap(he.WRAP_WRAP),t.flexWrap==="wrap-reverse"&&e.setFlexWrap(he.WRAP_WRAP_REVERSE)),"flexDirection"in t&&(t.flexDirection==="row"&&e.setFlexDirection(he.FLEX_DIRECTION_ROW),t.flexDirection==="row-reverse"&&e.setFlexDirection(he.FLEX_DIRECTION_ROW_REVERSE),t.flexDirection==="column"&&e.setFlexDirection(he.FLEX_DIRECTION_COLUMN),t.flexDirection==="column-reverse"&&e.setFlexDirection(he.FLEX_DIRECTION_COLUMN_REVERSE)),"flexBasis"in t&&(typeof t.flexBasis=="number"?e.setFlexBasis(t.flexBasis):typeof t.flexBasis=="string"?e.setFlexBasisPercent(Number.parseInt(t.flexBasis,10)):e.setFlexBasis(Number.NaN)),"alignItems"in t&&((t.alignItems==="stretch"||!t.alignItems)&&e.setAlignItems(he.ALIGN_STRETCH),t.alignItems==="flex-start"&&e.setAlignItems(he.ALIGN_FLEX_START),t.alignItems==="center"&&e.setAlignItems(he.ALIGN_CENTER),t.alignItems==="flex-end"&&e.setAlignItems(he.ALIGN_FLEX_END)),"alignSelf"in t&&((t.alignSelf==="auto"||!t.alignSelf)&&e.setAlignSelf(he.ALIGN_AUTO),t.alignSelf==="flex-start"&&e.setAlignSelf(he.ALIGN_FLEX_START),t.alignSelf==="center"&&e.setAlignSelf(he.ALIGN_CENTER),t.alignSelf==="flex-end"&&e.setAlignSelf(he.ALIGN_FLEX_END)),"justifyContent"in t&&((t.justifyContent==="flex-start"||!t.justifyContent)&&e.setJustifyContent(he.JUSTIFY_FLEX_START),t.justifyContent==="center"&&e.setJustifyContent(he.JUSTIFY_CENTER),t.justifyContent==="flex-end"&&e.setJustifyContent(he.JUSTIFY_FLEX_END),t.justifyContent==="space-between"&&e.setJustifyContent(he.JUSTIFY_SPACE_BETWEEN),t.justifyContent==="space-around"&&e.setJustifyContent(he.JUSTIFY_SPACE_AROUND),t.justifyContent==="space-evenly"&&e.setJustifyContent(he.JUSTIFY_SPACE_EVENLY))},"applyFlexStyles"),Ak=i((e,t)=>{"width"in t&&(typeof t.width=="number"?e.setWidth(t.width):typeof t.width=="string"?e.setWidthPercent(Number.parseInt(t.width,10)):e.setWidthAuto()),"height"in t&&(typeof t.height=="number"?e.setHeight(t.height):typeof t.height=="string"?e.setHeightPercent(Number.parseInt(t.height,10)):e.setHeightAuto()),"minWidth"in t&&(typeof t.minWidth=="string"?e.setMinWidthPercent(Number.parseInt(t.minWidth,10)):e.setMinWidth(t.minWidth??0)),"minHeight"in t&&(typeof t.minHeight=="string"?e.setMinHeightPercent(Number.parseInt(t.minHeight,10)):e.setMinHeight(t.minHeight??0))},"applyDimensionStyles"),_k=i((e,t)=>{"display"in t&&e.setDisplay(t.display==="flex"?he.DISPLAY_FLEX:he.DISPLAY_NONE)},"applyDisplayStyles"),Pk=i((e,t)=>{if("borderStyle"in t){let n=t.borderStyle?1:0;t.borderTop!==!1&&e.setBorder(he.EDGE_TOP,n),t.borderBottom!==!1&&e.setBorder(he.EDGE_BOTTOM,n),t.borderLeft!==!1&&e.setBorder(he.EDGE_LEFT,n),t.borderRight!==!1&&e.setBorder(he.EDGE_RIGHT,n)}},"applyBorderStyles"),$k=i((e,t)=>{"gap"in t&&e.setGap(he.GUTTER_ALL,t.gap??0),"columnGap"in t&&e.setGap(he.GUTTER_COLUMN,t.columnGap??0),"rowGap"in t&&e.setGap(he.GUTTER_ROW,t.rowGap??0)},"applyGapStyles"),Lk=i((e,t={})=>{kk(e,t),Rk(e,t),Ek(e,t),Mk(e,t),Ak(e,t),_k(e,t),Pk(e,t),$k(e,t)},"styles"),Rm=Lk;if(Ul())try{await import("./devtools-EYGFOXEU.js")}catch(e){if(e.code==="ERR_MODULE_NOT_FOUND")console.warn(`
4
- The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
5
- but this failed as it was not installed. Debugging with React Devtools requires it.
6
-
7
- To install use this command:
8
-
9
- $ npm install --save-dev react-devtools-core
10
- `.trim()+`
11
- `);else throw e}var Zx=i((e,t)=>{if(e===t)return;if(!e)return t;let n={},r=!1;for(let o of Object.keys(e))(!t||!Object.hasOwn(t,o))&&(n[o]=void 0,r=!0);if(t)for(let o of Object.keys(t))t[o]!==e[o]&&(n[o]=t[o],r=!0);return r?n:void 0},"diff"),ew=i(e=>{e?.unsetMeasureFunc(),e?.freeRecursive()},"cleanupYogaNode"),zl=nw,Em,tw={name:void 0,version:void 0},yr=Ok({getRootHostContext:i(()=>({isInsideText:!1}),"getRootHostContext"),prepareForCommit:i(()=>null,"prepareForCommit"),preparePortalMount:i(()=>null,"preparePortalMount"),clearContainer:i(()=>!1,"clearContainer"),resetAfterCommit(e){if(typeof e.onComputeLayout=="function"&&e.onComputeLayout(),e.isStaticDirty){e.isStaticDirty=!1,typeof e.onImmediateRender=="function"&&e.onImmediateRender();return}typeof e.onRender=="function"&&e.onRender()},getChildHostContext(e,t){let n=e.isInsideText,r=t==="ink-text"||t==="ink-virtual-text";return n===r?e:{isInsideText:r}},shouldSetTextContent:i(()=>!1,"shouldSetTextContent"),createInstance(e,t,n,r){if(r.isInsideText&&e==="ink-box")throw new Error("<Box> can\u2019t be nested inside <Text> component");let o=e==="ink-text"&&r.isInsideText?"ink-virtual-text":e,s=Gl(o);for(let[a,c]of Object.entries(t))if(a!=="children"){if(a==="style"){km(s,c),s.yogaNode&&Rm(s.yogaNode,c);continue}if(a==="internal_transform"){s.internal_transform=c;continue}if(a==="internal_static"){Em=n,s.internal_static=!0,n.isStaticDirty=!0,n.staticNode=s;continue}Im(s,a,c)}return s},createTextInstance(e,t,n){if(!n.isInsideText)throw new Error(`Text string "${e}" must be rendered inside <Text> component`);return qx(e)},resetTextContent(){},hideTextInstance(e){Ta(e,"")},unhideTextInstance(e,t){Ta(e,t)},getPublicInstance:i(e=>e,"getPublicInstance"),hideInstance(e){e.yogaNode?.setDisplay(Jx.DISPLAY_NONE)},unhideInstance(e){e.yogaNode?.setDisplay(Jx.DISPLAY_FLEX)},appendInitialChild:Kl,appendChild:Kl,insertBefore:vm,finalizeInitialChildren(){return!1},isPrimaryRenderer:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,scheduleCallback:Nr.unstable_scheduleCallback,cancelCallback:Nr.unstable_cancelCallback,shouldYield:Nr.unstable_shouldYield,now:Nr.unstable_now,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},getInstanceFromNode:i(()=>null,"getInstanceFromNode"),prepareScopeUpdate(){},getInstanceFromScope:i(()=>null,"getInstanceFromScope"),appendChildToContainer:Kl,insertInContainerBefore:vm,removeChildFromContainer(e,t){Sa(e,t),ew(t.yogaNode)},commitUpdate(e,t,n,r){Em&&e.internal_static&&(Em.isStaticDirty=!0);let o=Zx(n,r),s=Zx(n.style,r.style);if(!(!o&&!s)){if(o)for(let[a,c]of Object.entries(o)){if(a==="style"){km(e,c);continue}if(a==="internal_transform"){e.internal_transform=c;continue}if(a==="internal_static"){e.internal_static=!0;continue}Im(e,a,c)}s&&e.yogaNode&&Rm(e.yogaNode,s)}},commitTextUpdate(e,t,n){Ta(e,n)},removeChild(e,t){Sa(e,t),ew(t.yogaNode)},setCurrentUpdatePriority(e){zl=e},getCurrentUpdatePriority:i(()=>zl,"getCurrentUpdatePriority"),resolveUpdatePriority(){return zl!==nw?zl:Dk},maySuspendCommit(){return!0},NotPendingTransition:void 0,HostTransitionContext:Nk(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},rendererPackageName:tw.name,rendererVersion:tw.version});import Uk from"widest-line";import jk from"indent-string";import Bi from"yoga-layout";import Xl from"yoga-layout";var Bk=i(e=>e.getComputedWidth()-e.getComputedPadding(Xl.EDGE_LEFT)-e.getComputedPadding(Xl.EDGE_RIGHT)-e.getComputedBorder(Xl.EDGE_LEFT)-e.getComputedBorder(Xl.EDGE_RIGHT),"getMaxWidth"),rw=Bk;import Hk from"cli-boxes";import Yl from"chalk";var Fk=i((e,t,n,r)=>{if(n.style.borderStyle){let o=n.yogaNode.getComputedWidth(),s=n.yogaNode.getComputedHeight(),a=typeof n.style.borderStyle=="string"?Hk[n.style.borderStyle]:n.style.borderStyle,c=n.style.borderTopColor??n.style.borderColor,l=n.style.borderBottomColor??n.style.borderColor,d=n.style.borderLeftColor??n.style.borderColor,m=n.style.borderRightColor??n.style.borderColor,p=n.style.borderTopDimColor??n.style.borderDimColor,g=n.style.borderBottomDimColor??n.style.borderDimColor,x=n.style.borderLeftDimColor??n.style.borderDimColor,y=n.style.borderRightDimColor??n.style.borderDimColor,T=n.style.borderTop!==!1,w=n.style.borderBottom!==!1,v=n.style.borderLeft!==!1,O=n.style.borderRight!==!1,P=o-(v?1:0)-(O?1:0),D=T?Pn((v?a.topLeft:"")+a.top.repeat(P)+(O?a.topRight:""),c,"foreground"):void 0;T&&p&&(D=Yl.dim(D));let L=s;T&&(L-=1),w&&(L-=1);let X=(Pn(a.left,d,"foreground")+`
12
- `).repeat(L);x&&(X=Yl.dim(X));let I=(Pn(a.right,m,"foreground")+`
13
- `).repeat(L);y&&(I=Yl.dim(I));let ie=w?Pn((v?a.bottomLeft:"")+a.bottom.repeat(P)+(O?a.bottomRight:""),l,"foreground"):void 0;w&&g&&(ie=Yl.dim(ie));let Te=T?1:0;D&&r.write(e,t,D,{transformers:[]}),v&&r.write(e,t+Te,X,{transformers:[]}),O&&r.write(e+o-1,t+Te,I,{transformers:[]}),ie&&r.write(e,t+s-1,ie,{transformers:[]})}},"renderBorder"),ow=Fk;var Wk=i((e,t,n,r)=>{if(!n.style.backgroundColor)return;let o=n.yogaNode.getComputedWidth(),s=n.yogaNode.getComputedHeight(),a=n.style.borderStyle&&n.style.borderLeft!==!1?1:0,c=n.style.borderStyle&&n.style.borderRight!==!1?1:0,l=n.style.borderStyle&&n.style.borderTop!==!1?1:0,d=n.style.borderStyle&&n.style.borderBottom!==!1?1:0,m=o-a-c,p=s-l-d;if(!(m>0&&p>0))return;let g=Pn(" ".repeat(m),n.style.backgroundColor,"background");for(let x=0;x<p;x++)r.write(e+a,t+l+x,g,{transformers:[]})},"renderBackground"),iw=Wk;var Gk=i((e,t)=>{let n=e.childNodes[0]?.yogaNode;if(n){let r=n.getComputedLeft(),o=n.getComputedTop();t=`
14
- `.repeat(o)+jk(t,r)}return t},"applyPaddingToText"),ql=i((e,t={})=>{if(t.skipStaticElements&&e.internal_static||e.yogaNode?.getDisplay()===Bi.DISPLAY_NONE)return"";let n="";if(e.nodeName==="ink-text")n=wa(e);else if(e.nodeName==="ink-box"||e.nodeName==="ink-root"){let r=e.style.flexDirection==="row"||e.style.flexDirection==="row-reverse"?" ":`
15
- `;n=(e.style.flexDirection==="row-reverse"||e.style.flexDirection==="column-reverse"?[...e.childNodes].reverse():[...e.childNodes]).map(s=>ql(s,{parentRole:e.internal_accessibility?.role,skipStaticElements:t.skipStaticElements})).filter(Boolean).join(r)}if(e.internal_accessibility){let{role:r,state:o}=e.internal_accessibility;if(o){let a=Object.keys(o).filter(c=>o[c]).join(", ");a&&(n=`(${a}) ${n}`)}r&&r!==t.parentRole&&(n=`${r}: ${n}`)}return n},"renderNodeToScreenReaderOutput"),sw=i((e,t,n)=>{let{offsetX:r=0,offsetY:o=0,transformers:s=[],skipStaticElements:a}=n;if(a&&e.internal_static)return;let{yogaNode:c}=e;if(c){if(c.getDisplay()===Bi.DISPLAY_NONE)return;let l=r+c.getComputedLeft(),d=o+c.getComputedTop(),m=s;if(typeof e.internal_transform=="function"&&(m=[e.internal_transform,...s]),e.nodeName==="ink-text"){let g=wa(e);if(g.length>0){let x=Uk(g),y=rw(c);if(x>y){let T=e.style.textWrap??"wrap";g=jl(g,y,T)}g=Gk(e,g),t.write(l,d,g,{transformers:m})}return}let p=!1;if(e.nodeName==="ink-box"){iw(l,d,e,t),ow(l,d,e,t);let g=e.style.overflowX==="hidden"||e.style.overflow==="hidden",x=e.style.overflowY==="hidden"||e.style.overflow==="hidden";if(g||x){let y=g?l+c.getComputedBorder(Bi.EDGE_LEFT):void 0,T=g?l+c.getComputedWidth()-c.getComputedBorder(Bi.EDGE_RIGHT):void 0,w=x?d+c.getComputedBorder(Bi.EDGE_TOP):void 0,v=x?d+c.getComputedHeight()-c.getComputedBorder(Bi.EDGE_BOTTOM):void 0;t.clip({x1:y,x2:T,y1:w,y2:v}),p=!0}}if(e.nodeName==="ink-root"||e.nodeName==="ink-box"){for(let g of e.childNodes)sw(g,t,{offsetX:l,offsetY:d,transformers:m,skipStaticElements:a});p&&t.unclip()}}},"renderNodeToOutput"),Mm=sw;import Kk from"slice-ansi";import Vk from"string-width";import{styledCharsFromTokens as zk,styledCharsToString as Xk,tokenize as Yk}from"@alcalzone/ansi-tokenize";var Am=class{static{i(this,"OutputCaches")}widths=new Map;blockWidths=new Map;styledChars=new Map;getStyledChars(t){let n=this.styledChars.get(t);return n===void 0&&(n=zk(Yk(t)),this.styledChars.set(t,n)),n}getStringWidth(t){let n=this.widths.get(t);return n===void 0&&(n=Vk(t),this.widths.set(t,n)),n}getWidestLine(t){let n=this.blockWidths.get(t);if(n===void 0){let r=0;for(let o of t.split(`
16
- `))r=Math.max(r,this.getStringWidth(o));n=r,this.blockWidths.set(t,n)}return n}},Hi=class{static{i(this,"Output")}width;height;operations=[];caches=new Am;constructor(t){let{width:n,height:r}=t;this.width=n,this.height=r}write(t,n,r,o){let{transformers:s}=o;r&&this.operations.push({type:"write",x:t,y:n,text:r,transformers:s})}clip(t){this.operations.push({type:"clip",clip:t})}unclip(){this.operations.push({type:"unclip"})}getGrid(){let t=[];for(let r=0;r<this.height;r++){let o=[];for(let s=0;s<this.width;s++)o.push({type:"char",value:" ",fullWidth:!1,styles:[]});t.push(o)}let n=[];for(let r of this.operations)if(r.type==="clip"&&n.push(r.clip),r.type==="unclip"&&n.pop(),r.type==="write"){let{text:o,transformers:s}=r,{x:a,y:c}=r,l=o.split(`
17
- `),d=n.at(-1);if(d){let p=typeof d?.x1=="number"&&typeof d?.x2=="number",g=typeof d?.y1=="number"&&typeof d?.y2=="number";if(p){let x=this.caches.getWidestLine(o);if(a+x<d.x1||a>d.x2)continue}if(g){let x=l.length;if(c+x<d.y1||c>d.y2)continue}if(p&&(l=l.map(x=>{let y=a<d.x1?d.x1-a:0,T=this.caches.getStringWidth(x),w=a+T>d.x2?d.x2-a:T;return Kk(x,y,w)}),a<d.x1&&(a=d.x1)),g){let x=c<d.y1?d.y1-c:0,y=l.length,T=c+y>d.y2?d.y2-c:y;l=l.slice(x,T),c<d.y1&&(c=d.y1)}}let m=0;for(let[p,g]of l.entries()){let x=t[c+m];if(!x)continue;for(let w of s)g=w(g,p);let y=this.caches.getStyledChars(g),T=a;for(let w of y){x[T]=w;let v=Math.max(1,this.caches.getStringWidth(w.value));if(v>1)for(let O=1;O<v;O++)x[T+O]={type:"char",value:"",fullWidth:!1,styles:w.styles};T+=v}m++}}return t}get(){let t=this.getGrid();return{output:t.map(r=>{let o=r.filter(s=>s!==void 0);return Xk(o).trimEnd()}).join(`
18
- `),height:t.length}}};var xr={Single:0,Wide:1,SpacerTail:2},vo={char:" ",width:xr.Single,style:"",hyperlink:void 0};function aw(e,t){if(e<0||t<0)throw new RangeError(`Screen dimensions must be non-negative (got width=${e}, height=${t})`);let n=new Array(e*t).fill(vo);return{width:e,height:t,cells:n}}i(aw,"createScreen");function Fi(e,t,n){if(!(t<0||n<0||t>=e.width||n>=e.height))return e.cells[n*e.width+t]}i(Fi,"cellAt");function cw(e,t){if(e<0||t<0)throw new RangeError(`Screen dimensions must be non-negative (got width=${e}, height=${t})`);let n=new Array(e*t).fill(vo),r=!1;return{width:e,height:t,setCellAt(o,s,a){if(r)throw new Error("ScreenBuilder.setCellAt called after build()");if(o<0||s<0||o>=e||s>=t)throw new RangeError(`ScreenBuilder.setCellAt out of bounds: (${o}, ${s}) on ${e}x${t}`);n[s*e+o]=a},build(){if(r)throw new Error("ScreenBuilder.build called twice");return r=!0,{width:e,height:t,cells:n}}}}i(cw,"createScreenBuilder");function*Ql(e,t){let n=Math.max(e.width,t.width),r=Math.max(e.height,t.height);for(let o=0;o<r;o++)for(let s=0;s<n;s++){let a=Fi(e,s,o),c=Fi(t,s,o);qk(a,c)||(yield{x:s,y:o,prev:a,next:c})}}i(Ql,"diffEach");function qk(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.char===t.char&&e.width===t.width&&e.style===t.style&&e.hyperlink===t.hyperlink}i(qk,"cellsEqual");var _m="\x1B]8;";function Qk(e){return e.endsWith("\x07")?e.slice(0,-1):e}i(Qk,"stripOsc8Terminator");function Jk(e){if(!e.startsWith(_m))return;let t=e.slice(_m.length),n=t.indexOf(";");if(n<0)return;let r=t.slice(n+1),o=Qk(r);return o.length>0?o:void 0}i(Jk,"parseOsc8Url");function Zk(e){if(e.value==="")return{char:"",width:xr.SpacerTail,style:"",hyperlink:void 0};let t="",n;for(let r of e.styles)if(r.code.startsWith(_m)){let o=Jk(r.code);o!==void 0&&(n=o)}else t+=r.code;return{char:e.value,width:e.fullWidth?xr.Wide:xr.Single,style:t,hyperlink:n}}i(Zk,"styledCharToCell");function lw(e){let t=e.getGrid(),n=e.width,r=e.height,o=cw(n,r),s=Math.min(t.length,r);for(let a=0;a<s;a++){let c=t[a];if(!c)continue;let l=Math.min(c.length,n);for(let d=0;d<l;d++){let m=c[d];if(!m)continue;let p=Zk(m);p.char===vo.char&&p.width===vo.width&&p.style===vo.style&&p.hyperlink===vo.hyperlink||o.setCellAt(d,a,p)}}return o.build()}i(lw,"outputToScreen");var eR=i((e,t,n)=>{if(e.yogaNode){if(t){let p=ql(e,{skipStaticElements:!0}),g=p===""?0:p.split(`
19
- `).length,x="";return e.staticNode&&(x=ql(e.staticNode,{skipStaticElements:!1})),{output:p,outputHeight:g,staticOutput:x?`${x}
20
- `:"",frame:void 0}}let r=new Hi({width:e.yogaNode.getComputedWidth(),height:e.yogaNode.getComputedHeight()});Mm(e,r,{skipStaticElements:!0});let o;e.staticNode?.yogaNode&&(o=new Hi({width:e.staticNode.yogaNode.getComputedWidth(),height:e.staticNode.yogaNode.getComputedHeight()}),Mm(e.staticNode,o,{skipStaticElements:!1}));let{output:s,height:a}=r.get(),c=lw(r),l=n?.columns??e.yogaNode.getComputedWidth(),d=n?.rows??e.yogaNode.getComputedHeight(),m={screen:c,viewport:{width:l,height:d},cursor:{x:0,y:c.height,visible:!0}};return{output:s,outputHeight:a,staticOutput:o?`${o.get().output}
21
- `:"",frame:m}}return{output:"",outputHeight:0,staticOutput:"",frame:void 0}},"renderer"),uw=eR;function Yn(...e){if(e.length===0)return"\x1B[";if(e.length===1)return`\x1B[${e[0]}`;let t=e.slice(0,-1),n=e[e.length-1];return`\x1B[${t.join(";")}${n}`}i(Yn,"csi");function dw(e=1){return e===0?"":Yn(e,"A")}i(dw,"cursorUp");function tR(e=1){return e===0?"":Yn(e,"B")}i(tR,"cursorDown");function nR(e=1){return e===0?"":Yn(e,"C")}i(nR,"cursorForward");function rR(e=1){return e===0?"":Yn(e,"D")}i(rR,"cursorBack");function fw(e){return Yn(e,"G")}i(fw,"cursorTo");var oR=Yn("G"),mw=Yn("H");function pw(e,t){let n="";return e<0?n+=rR(-e):e>0&&(n+=nR(e)),t<0?n+=dw(-t):t>0&&(n+=tR(t)),n}i(pw,"cursorMove");var iR=Yn(2,"K");function gw(e){if(e<=0)return"";let t="";for(let n=0;n<e;n++)t+=iR,n<e-1&&(t+=dw(1));return t+=oR,t}i(gw,"eraseLines");var vB=Yn("r"),Jl=Yn(0,"m");function hw(e){return`\x1B]${e.join(";")}\x07`}i(hw,"osc");function sR(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}i(sR,"osc8Id");function Ca(e,t){if(!e)return ba;let n={id:sR(e),...t??{}},r=Object.entries(n).map(([o,s])=>`${o}=${s}`).join(":");return hw(["8",r,e])}i(Ca,"link");var ba=hw(["8","",""]);function Pm(e){let{screen:t}=e;if(t.width===0||t.height===0)return[];let n=[],r="",o;for(let s=0;s<t.height;s++){let a="";for(let c=0;c<t.width;c++){let l=Fi(t,c,s);!l||l.width===xr.SpacerTail||(l.hyperlink!==o&&(o!==void 0&&(a+=ba),l.hyperlink!==void 0&&(a+=Ca(l.hyperlink)),o=l.hyperlink),l.style!==r&&(r!==""&&(a+=Jl),l.style!==""&&(a+=l.style),r=l.style),a+=l.char)}o!==void 0&&(a+=ba,o=void 0),r!==""&&(a+=Jl,r=""),n.push(a.trimEnd())}return[{type:"stdout",content:n.join(`
22
- `)}]}i(Pm,"renderFullFrame");var aR=Object.freeze([]),cR=Object.freeze([]);function Wi(e,t){if(e===t)return{patches:aR,current:e};let n=[];return e!==""&&n.push({type:"stdout",content:Jl}),t!==""&&n.push({type:"stdout",content:t}),{patches:n,current:t}}i(Wi,"transitionStyle");function Zl(e,t){let n=Wi(e,t),r="";for(let o of n.patches)o.type==="stdout"&&(r+=o.content);return{str:r,current:n.current}}i(Zl,"transitionStyleStr");function Io(e,t){if(e===t)return{patches:cR,current:e};let n=[];return e!==void 0&&n.push({type:"stdout",content:ba}),t!==void 0&&n.push({type:"stdout",content:Ca(t)}),{patches:n,current:t}}i(Io,"transitionHyperlink");function yw(e){let t=e.codePointAt(0);if(t===void 0)return!1;if(t>=129648&&t<=129791||t>=129792&&t<=130047)return!0;if(e.length>=2){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)===65039)return!0}return!1}i(yw,"needsWidthCompensation");var Ui=class{static{i(this,"VirtualScreen")}viewportWidth;cursor;diff;_cursorMut;_diffMut=[];constructor(t,n){this.viewportWidth=n,this._cursorMut={x:t.x,y:t.y},this.cursor=this._cursorMut,this.diff=this._diffMut}txn(t){let[n,r]=t(this.cursor);for(let o of n)this._diffMut.push(o);this._cursorMut.x+=r.dx,this._cursorMut.y+=r.dy}},Br={type:"carriageReturn"},va={type:"stdout",content:`
23
- `};function eu(e,t,n){let r=t.width===xr.Wide?2:1,o=e.viewportWidth,s=!1;return e.txn(a=>{let c=a.x;if(r===2&&c<o){let m=t.char.length>2?o:o+1;if(c+2>=m)return[[],{dx:0,dy:0}]}let l=[];n.length>0&&l.push({type:"stdout",content:n});let d=r===2&&yw(t.char);return d&&c+1<o&&(l.push({type:"cursorTo",col:c+2}),l.push({type:"stdout",content:" "}),l.push({type:"cursorTo",col:c+1})),l.push({type:"stdout",content:t.char}),d&&l.push({type:"cursorTo",col:c+r+1}),s=!0,c>=o?[l,{dx:r-c,dy:1}]:[l,{dx:r,dy:0}]}),s}i(eu,"writeCellWithStyleStr");function Ia(e,t,n){e.txn(r=>{let o=t-r.x,s=n-r.y;return r.x>=e.viewportWidth?[[Br,{type:"cursorMove",x:t,y:s}],{dx:o,dy:s}]:s!==0?[[Br,{type:"cursorMove",x:t,y:s}],{dx:o,dy:s}]:[[{type:"cursorMove",x:o,y:s}],{dx:o,dy:s}]})}i(Ia,"moveCursorTo");function tu(e,t,n,r){let o="",s;for(let a=n;a<r;a++){if(e.cursor.y<a){let d=a-e.cursor.y;e.txn(m=>{let p=new Array(1+d);p[0]=Br;for(let g=0;g<d;g++)p[1+g]=va;return[p,{dx:-m.x,dy:d}]})}for(let d=0;d<t.screen.width;d++){let m=Fi(t.screen,d,a);if(!m||m.width===xr.SpacerTail||m.char===" "&&m.style===""&&m.hyperlink===void 0)continue;Ia(e,d,a);let p=Io(s,m.hyperlink);for(let x of p.patches)e.txn(()=>[[x],{dx:0,dy:0}]);s=p.current;let g=Zl(o,m.style);eu(e,m,g.str)&&(o=g.current)}let c=Wi(o,"");for(let d of c.patches)e.txn(()=>[[d],{dx:0,dy:0}]);o=c.current;let l=Io(s,void 0);for(let d of l.patches)e.txn(()=>[[d],{dx:0,dy:0}]);s=l.current,e.txn(d=>[[Br,va],{dx:-d.x,dy:1}])}if(o!==""||s!==void 0){let a=Wi(o,"");for(let l of a.patches)e.txn(()=>[[l],{dx:0,dy:0}]);let c=Io(s,void 0);for(let l of c.patches)e.txn(()=>[[l],{dx:0,dy:0}])}}i(tu,"renderFrameSlice");function $m(e,t){let n="";for(let r=0;r<e.width;r++){let o=Fi(e,r,t);n+=o?.char??" "}return n.trimEnd()}i($m,"readLine");function nu(e,t){let n=new Ui({x:0,y:0},e.viewport.width);tu(n,e,0,e.screen.height);let r=[{type:"clearTerminal",reason:t}];for(let o of n.diff)r.push(o);return r}i(nu,"fullResetSequence_CAUSES_FLICKER");function Lm(e,t){let n=e.cursor.y>=e.screen.height,r=t.screen.height>e.screen.height,o=t.screen.height<e.screen.height,s=n&&e.screen.height>=e.viewport.height,a=t.screen.height<=e.viewport.height,c=s?1:0;return{viewportY:r?Math.max(0,e.screen.height-e.viewport.height+c):Math.max(e.screen.height,t.screen.height)-t.viewport.height+c,cursorAtBottom:n,growing:r,shrinking:o,prevHadScrollback:s,nextFitsViewport:a}}i(Lm,"computeViewportState");function xw(e,t,n){if(t.viewport.height<e.viewport.height||e.viewport.width!==0&&t.viewport.width!==e.viewport.width)return{reset:!0,reason:"resize"};let r=Lm(e,t);if(r.prevHadScrollback&&r.nextFitsViewport&&r.shrinking)return{reset:!0,reason:"offscreen"};if(e.screen.height>=e.viewport.height&&e.screen.height>0&&r.cursorAtBottom&&!r.growing){let s=e.screen.height-e.viewport.height+1;for(let a of Ql(e.screen,t.screen))if(a.y<s)return{reset:!0,reason:"offscreen",trigger:{y:a.y,prevLine:n(e.screen,a.y),nextLine:n(t.screen,a.y)}}}return r.shrinking&&e.screen.height-t.screen.height>e.viewport.height?{reset:!0,reason:"offscreen"}:{reset:!1}}i(xw,"shouldFullReset");function ww(e,t,n){return!!(t&&t.width===2||e&&e.width===2&&!t||t&&n&&!e)}i(ww,"shouldSkipDiff");var ru=class{static{i(this,"LogUpdate")}options;constructor(t){this.options=t}render(t,n){if(!this.options.isTTY)return Pm(n);let r=xw(t,n,$m);return r.reset?nu(n,r.reason):fR(t,n)}reset(){}};function Om(e,t){for(let n of t)e.txn(()=>[[n],{dx:0,dy:0}])}i(Om,"emitPatches");function Sw(e,t,n){if(t!==""){let r=Wi(t,"");Om(e,r.patches)}if(n!==void 0){let r=Io(n,void 0);Om(e,r.patches)}return{style:"",hyperlink:void 0}}i(Sw,"resetStyleAndHyperlink");function lR(e,t,n){let r=t.screen.height-n.screen.height;e.txn(o=>[[{type:"clear",count:r},{type:"cursorMove",x:0,y:-1}],{dx:-o.x,dy:-r}])}i(lR,"applyShrink");function uR(e,t,n,r){let o="",s,a=!1;for(let c of Ql(t.screen,n.screen)){let{x:l,y:d,prev:m,next:p}=c;if(r.growing&&d>=t.screen.height)continue;let g=!!(p&&p.char===" "&&p.style===""&&p.hyperlink===void 0);if(!ww(m,p,g)){if(d<r.viewportY){a=!0;break}if(Ia(e,l,d),p){let x=Io(s,p.hyperlink);Om(e,x.patches),s=x.current;let y=Zl(o,p.style);eu(e,p,y.str)&&(o=y.current)}else if(m){let x=Sw(e,o,s);o=x.style,s=x.hyperlink,e.txn(()=>[[{type:"stdout",content:" "}],{dx:1,dy:0}])}}}return{currentStyle:o,currentHyperlink:s,needsFullReset:a}}i(uR,"diffPass");function dR(e,t){t.cursor.y>=t.screen.height?e.txn(n=>{let r=t.cursor.y-n.y;if(r>0){let s=new Array(1+r);s[0]=Br;for(let a=0;a<r;a++)s[1+a]=va;return[s,{dx:-n.x,dy:r}]}let o=t.cursor.y-n.y;return o!==0||n.x!==t.cursor.x?[[Br,{type:"cursorMove",x:t.cursor.x,y:o}],{dx:t.cursor.x-n.x,dy:o}]:[[],{dx:0,dy:0}]}):Ia(e,t.cursor.x,t.cursor.y)}i(dR,"restoreCursor");function fR(e,t){let n=Lm(e,t),r=new Ui(e.cursor,t.viewport.width);n.shrinking&&lR(r,e,t);let o=uR(r,e,t,n);return o.needsFullReset?nu(t,"offscreen"):(Sw(r,o.currentStyle,o.currentHyperlink),n.growing&&tu(r,t,e.screen.height,t.screen.height),dR(r,t),r.diff)}i(fR,"renderIncremental");var mR="\x1B[?25l",pR="\x1B[?25h",gR=`\x1B[2J${mw}`;function hR(e){switch(e.type){case"stdout":return e.content;case"carriageReturn":return"\r";case"cursorHide":return mR;case"cursorShow":return pR;case"cursorMove":return pw(e.x,e.y);case"cursorTo":return fw(e.col);case"clear":return gw(e.count);case"clearTerminal":return gR;case"hyperlink":return Ca(e.uri)}}i(hR,"patchToBytes");function ou(e,t){let n="";for(let r of t)n+=hR(r);n.length>0&&e.write(n)}i(ou,"applyDiff");function Tw(e,t){if(t===void 0)return!1;let n=e.cellLogUpdate.render(e.prevFrame,t);return ou(e.stdout,n),e.prevFrame=t,!0}i(Tw,"applyCellFrame");function ka(e,t){return{screen:aw(0,0),viewport:{width:t,height:e},cursor:{x:0,y:0,visible:!0}}}i(ka,"emptyFrame");import yR from"is-in-ci";var ji="\x1B[?2026h",ko="\x1B[?2026l";function Gi(e){return"isTTY"in e&&e.isTTY===!0&&!yR}i(Gi,"shouldSynchronize");var xR=new WeakMap,Cw=xR;import{EventEmitter as BR}from"node:events";import HR from"node:process";import Ro,{useState as Bm,useRef as Ki,useCallback as ft,useMemo as Vi,useEffect as Fw}from"react";import FR from"cli-cursor";var wR=i(e=>e>=48&&e<=63,"isCsiParameterByte"),SR=i(e=>e>=32&&e<=47,"isCsiIntermediateByte"),vw=i(e=>e>=64&&e<=126,"isCsiFinalByte");function TR(e,t,n){let r=t+n+1,o=r;for(;o<e.length;o+=1){let s=e.codePointAt(o);if(s===void 0)return"pending";if(!(wR(s)||SR(s))&&!(s===91&&o===r))return vw(s)?{sequence:e.slice(t,o+1),nextIndex:o+1}:void 0}return"pending"}i(TR,"parseCsiSequence");function CR(e,t,n){let r=t+n+2;if(r>e.length)return"pending";let o=e.codePointAt(r-1);if(!(o===void 0||!vw(o)))return{sequence:e.slice(t,r),nextIndex:r}}i(CR,"parseSs3Sequence");function bw(e,t,n){let r=e[t+n];if(r===void 0)return"pending";if(r==="[")return TR(e,t,n);if(r==="O")return CR(e,t,n)}i(bw,"parseControlSequence");function bR(e,t){let n=e.codePointAt(t+1),r=n!==void 0&&n>65535?2:1,o=t+1+r;return{sequence:e.slice(t,o),nextIndex:o}}i(bR,"parseEscapedCodePoint");function vR(e){let t=[],n=0,r=i(o=>({events:t,pending:e.slice(o)}),"pendingFrom");for(;n<e.length;){let o=e.indexOf("\x1B",n);if(o===-1)return t.push(e.slice(n)),{events:t,pending:""};if(o>n&&t.push(e.slice(n,o)),o===e.length-1)return r(o);let s=bw(e,o,1);if(s==="pending")return r(o);if(s){t.push(s.sequence),n=s.nextIndex;continue}if(e[o+1]==="\x1B"){if(o+2>=e.length)return r(o);let l=bw(e,o,2);if(l==="pending")return r(o);if(l){t.push(l.sequence),n=l.nextIndex;continue}t.push(e.slice(o,o+2)),n=o+2;continue}let c=bR(e,o);t.push(c.sequence),n=c.nextIndex}return{events:t,pending:""}}i(vR,"parseKeypresses");function iu(){let e="";return{push(t){let n=vR(e+t);return e=n.pending,n.events},hasPendingEscape(){return e.startsWith("\x1B")},flushPendingEscape(){if(!e.startsWith("\x1B"))return;let t=e;return e="",t},reset(){e=""}}}i(iu,"createInputParser");import{createContext as IR}from"react";var Iw=IR({exit(){}});Iw.displayName="InternalAppContext";var kw=Iw;import{EventEmitter as kR}from"node:events";import{createContext as RR}from"react";var ER={isTTY:!1,isRaw:!1,on(){},off(){},pause(){},resume(){},setRawMode(){}},Rw=RR({stdin:ER,internal_eventEmitter:new kR,setRawMode(){},isRawModeSupported:!1,internal_exitOnCtrlC:!0});Rw.displayName="InternalStdinContext";var Ew=Rw;import{createContext as MR}from"react";var AR={isTTY:!1,columns:80,rows:24,write(){return!0},on(){},off(){}},Mw=MR({stdout:AR,write(){}});Mw.displayName="InternalStdoutContext";var Aw=Mw;import{createContext as _R}from"react";var PR={isTTY:!1,write(){return!0},on(){},off(){}},_w=_R({stderr:PR,write(){}});_w.displayName="InternalStderrContext";var Pw=_w;import{createContext as $R}from"react";var $w=$R({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});$w.displayName="InternalFocusContext";var Lw=$w;import{createContext as LR}from"react";var Ow=LR({setCursorPosition(){}});Ow.displayName="InternalCursorContext";var Dw=Ow;import DR,{PureComponent as NR}from"react";import*as su from"node:fs";import{cwd as Hw}from"node:process";import yt from"react";import Nw from"stack-utils";import OR from"code-excerpt";var Dm=i(e=>e?.replace(`file://${Hw()}/`,""),"cleanupPath"),Bw=new Nw({cwd:Hw(),internals:Nw.nodeInternals()});function Nm({error:e}){let t=e.stack?e.stack.split(`
24
- `).slice(1):void 0,n=t?Bw.parseLine(t[0]):void 0,r=Dm(n?.file),o,s=0;if(r&&n?.line&&su.existsSync(r)){let a=su.readFileSync(r,"utf8");if(o=OR(a,n.line),o)for(let{line:c}of o)s=Math.max(s,String(c).length)}return yt.createElement(yn,{flexDirection:"column",padding:1},yt.createElement(yn,null,yt.createElement(Xt,{backgroundColor:"red",color:"white"}," ","ERROR"," "),yt.createElement(Xt,null," ",e.message)),n&&r&&yt.createElement(yn,{marginTop:1},yt.createElement(Xt,{dimColor:!0},r,":",n.line,":",n.column)),n&&o&&yt.createElement(yn,{marginTop:1,flexDirection:"column"},o.map(({line:a,value:c})=>yt.createElement(yn,{key:a},yt.createElement(yn,{width:s+1},yt.createElement(Xt,{dimColor:a!==n.line,backgroundColor:a===n.line?"red":void 0,color:a===n.line?"white":void 0,"aria-label":a===n.line?`Line ${a}, error`:`Line ${a}`},String(a).padStart(s," "),":")),yt.createElement(Xt,{key:a,backgroundColor:a===n.line?"red":void 0,color:a===n.line?"white":void 0}," "+c)))),e.stack&&yt.createElement(yn,{marginTop:1,flexDirection:"column"},e.stack.split(`
25
- `).slice(1).map(a=>{let c=Bw.parseLine(a);return c?yt.createElement(yn,{key:a},yt.createElement(Xt,{dimColor:!0},"- "),yt.createElement(Xt,{dimColor:!0,bold:!0},c.function),yt.createElement(Xt,{dimColor:!0,color:"gray","aria-label":`at ${Dm(c.file)??""} line ${c.line} column ${c.column}`}," ","(",Dm(c.file)??"",":",c.line,":",c.column,")")):yt.createElement(yn,{key:a},yt.createElement(Xt,{dimColor:!0},"- "),yt.createElement(Xt,{dimColor:!0,bold:!0},a,"\\t"," "))})))}i(Nm,"ErrorOverview");var Ra=class extends NR{static{i(this,"ErrorBoundary")}static displayName="InternalErrorBoundary";static getDerivedStateFromError(t){return{error:t}}state={error:void 0};componentDidCatch(t){this.props.onError(t)}render(){return this.state.error?DR.createElement(Nm,{error:this.state.error}):this.props.children}};var WR=" ",UR="\x1B[Z",jR="\x1B";function Ww({children:e,stdin:t,stdout:n,stderr:r,writeToStdout:o,writeToStderr:s,exitOnCtrlC:a,onExit:c,setCursorPosition:l}){let[d,m]=Bm(!0),[p,g]=Bm(void 0),[,x]=Bm([]),y=Ki(0),T=Ki(0),w=Ki(new BR);w.current.setMaxListeners(1/0);let v=Ki(void 0),O=Ki(iu()),P=Ki(void 0),D=ft(()=>{P.current&&(clearImmediate(P.current),P.current=void 0)},[]),L=t.isTTY,X=ft(()=>{v.current&&(t.removeListener("readable",v.current),v.current=void 0)},[t]),I=ft(()=>{t.setRawMode(!1),X(),t.unref(),T.current=0,O.current.reset(),D()},[t,X,D]),ie=ft(ee=>{L&&T.current>0&&I(),c(ee)},[L,I,c]),Te=ft(ee=>{if(ee===""&&a){ie();return}ee===jR&&g(A=>A&&void 0)},[a,ie]),K=ft(ee=>{Te(ee),w.current.emit("input",ee)},[Te]),q=ft(()=>{D(),P.current=setImmediate(()=>{P.current=void 0;let ee=O.current.flushPendingEscape();ee&&K(ee)})},[D,K]),M=ft(()=>{D();let ee;for(;(ee=t.read())!==null;){let A=O.current.push(ee);for(let _ of A)K(_)}O.current.hasPendingEscape()&&q()},[t,K,D,q]),C=ft(ee=>{if(!L)throw t===HR.stdin?new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
26
- Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`):new Error(`Raw mode is not supported on the stdin provided to Ink.
27
- Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(t.setEncoding("utf8"),ee){T.current===0&&(t.ref(),t.setRawMode(!0),v.current=M,t.addListener("readable",M)),T.current++;return}T.current!==0&&--T.current===0&&I()},[L,t,M,I]),Z=ft((ee,A)=>{let _=ee.findIndex(W=>W.id===A);for(let W=_+1;W<ee.length;W++){let J=ee[W];if(J?.isActive)return J.id}},[]),ke=ft((ee,A)=>{let _=ee.findIndex(W=>W.id===A);for(let W=_-1;W>=0;W--){let J=ee[W];if(J?.isActive)return J.id}},[]),ve=ft(()=>{x(ee=>(g(A=>{let _=ee.find(J=>J.isActive)?.id;return Z(ee,A)??_}),ee))},[Z]),Se=ft(()=>{x(ee=>(g(A=>{let _=ee.findLast(J=>J.isActive)?.id;return ke(ee,A)??_}),ee))},[ke]);Fw(()=>{let ee=i(_=>{!d||y.current===0||(_===WR&&ve(),_===UR&&Se())},"handleTabNavigation");w.current.on("input",ee);let A=w.current;return()=>{A.off("input",ee)}},[d,ve,Se]);let ce=ft(()=>{m(!0)},[]),De=ft(()=>{m(!1)},[]),ae=ft(ee=>{x(A=>(A.some(W=>W?.id===ee)&&g(ee),A))},[]),Y=ft((ee,{autoFocus:A})=>{x(_=>(y.current=_.length+1,[..._,{id:ee,isActive:!0}])),A&&g(_=>_??ee)},[]),Q=ft(ee=>{g(A=>A===ee?void 0:A),x(A=>{let _=A.filter(W=>W.id!==ee);return y.current=_.length,_})},[]),Ce=ft(ee=>{x(A=>A.map(_=>_.id!==ee?_:{id:ee,isActive:!0}))},[]),be=ft(ee=>{g(A=>A===ee?void 0:A),x(A=>A.map(_=>_.id!==ee?_:{id:ee,isActive:!1}))},[]);Fw(()=>()=>{FR.show(n),L&&T.current>0&&I()},[n,L,I]);let at=Vi(()=>({exit:ie}),[ie]),Re=Vi(()=>({stdin:t,setRawMode:C,isRawModeSupported:L,internal_exitOnCtrlC:a,internal_eventEmitter:w.current}),[t,C,L,a]),Ue=Vi(()=>({stdout:n,write:o}),[n,o]),xe=Vi(()=>({stderr:r,write:s}),[r,s]),kt=Vi(()=>({setCursorPosition:l}),[l]),qe=Vi(()=>({activeId:p,add:Y,remove:Q,activate:Ce,deactivate:be,enableFocus:ce,disableFocus:De,focusNext:ve,focusPrevious:Se,focus:ae}),[p,Y,Q,Ce,be,ce,De,ve,Se,ae]);return Ro.createElement(kw.Provider,{value:at},Ro.createElement(Ew.Provider,{value:Re},Ro.createElement(Aw.Provider,{value:Ue},Ro.createElement(Pw.Provider,{value:xe},Ro.createElement(Lw.Provider,{value:qe},Ro.createElement(Dw.Provider,{value:kt},Ro.createElement(Ra,{onError:ie},e)))))))}i(Ww,"App");Ww.displayName="InternalApp";var Uw=Ww;var GR={disambiguateEscapeCodes:1,reportEventTypes:2,reportAlternateKeys:4,reportAllKeysAsEscapeCodes:8,reportAssociatedText:16};function jw(e){let t=0;for(let n of e)t|=GR[n];return t}i(jw,"resolveFlags");var wr={shift:1,alt:2,ctrl:4,super:8,hyper:16,meta:32,capsLock:64,numLock:128};var au=i(()=>{},"noop"),eE=27,tE=91,nE=63,rE=117,oE=48,iE=57,sE=i(e=>e>=oE&&e<=iE,"isDigitByte"),Kw=i((e,t)=>{if(e[t]!==eE||e[t+1]!==tE||e[t+2]!==nE)return;let n=t+3,r=n;for(;n<e.length&&sE(e[n]);)n++;if(n!==r){if(n===e.length)return{state:"partial"};if(e[n]===rE)return{state:"complete",endIndex:n}}},"matchKittyQueryResponse"),aE=i(e=>{for(let t=0;t<e.length;t++)if(Kw(e,t)?.state==="complete")return!0;return!1},"hasCompleteKittyQueryResponse"),cE=i(e=>{let t=[],n=0;for(;n<e.length;){let r=Kw(e,n);if(r?.state==="complete"){n=r.endIndex+1;continue}if(r?.state==="partial")break;t.push(e[n]),n++}return t},"stripKittyQueryResponsesAndTrailingPartial"),Hm=i(e=>e instanceof Error||Object.prototype.toString.call(e)==="[object Error]","isErrorInput"),lE=class{static{i(this,"Ink")}isConcurrent;options;cursorPosition;isScreenReaderEnabled;isUnmounted;isUnmounting;lastOutput;lastOutputToRender;lastOutputHeight;lastTerminalWidth;container;rootNode;fullStaticOutput;exitPromise;exitResult;beforeExitHandler;restoreConsole;unsubscribeResize;throttledOnRender;hasPendingThrottledRender=!1;kittyProtocolEnabled=!1;cancelKittyDetection;altScreenActive=!1;shellMode;mouseTrackingActive=!1;shellTransitionPhase=void 0;cursorHidden=!1;constructor(t){VR(this),this.options=t,this.rootNode=Gl("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=t.isScreenReaderEnabled??zi.env.INK_SCREEN_READER==="true";let n=t.debug||this.isScreenReaderEnabled,r=t.maxFps??30,o=r>0?Math.max(1,Math.ceil(1e3/r)):0;if(n)this.rootNode.onRender=this.onRender,this.throttledOnRender=void 0;else{let a=KR(this.onRender,o,{leading:!0,trailing:!0});this.rootNode.onRender=()=>{this.hasPendingThrottledRender=!0,a()},this.throttledOnRender=a}this.rootNode.onImmediateRender=this.onRender,this.cellLogUpdate=new ru({isTTY:!!t.stdout.isTTY}),this.prevFrame=ka(t.stdout.rows??24,t.stdout.columns??80),this.cursorPosition=void 0,this.isUnmounted=!1,this.isUnmounting=!1,this.isConcurrent=t.concurrent??!1,this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.lastTerminalWidth=this.getTerminalWidth(),this.fullStaticOutput="",this.shellMode=t.shellMode??"virtual";let s=t.concurrent?qR:YR;this.container=yr.createContainer(this.rootNode,s,null,!1,null,"id",()=>{},()=>{},()=>{},()=>{}),this.unsubscribeExit=zR(this.unmount,{alwaysLast:!1}),Ul()&&yr.injectIntoDevTools(),t.patchConsole&&this.patchConsole(),Hr||(t.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{t.stdout.off("resize",this.resized)}),this.initKittyKeyboard()}getTerminalWidth=i(()=>this.options.stdout.columns?this.options.stdout.columns:ZR()?.columns??80,"getTerminalWidth");resized=i(()=>{let t=this.getTerminalWidth();if(t<this.lastTerminalWidth){let n=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";n.length>0&&this.options.stdout.write(n),this.lastOutput="",this.lastOutputToRender="",this.cellLogUpdate.reset(),this.prevFrame=ka(this.options.stdout.rows??24,t)}this.calculateLayout(),this.onRender(),this.lastTerminalWidth=t},"resized");resolveExitPromise=i(()=>{},"resolveExitPromise");rejectExitPromise=i(()=>{},"rejectExitPromise");unsubscribeExit=i(()=>{},"unsubscribeExit");handleAppExit=i(t=>{if(!(this.isUnmounted||this.isUnmounting)){if(Hm(t)){this.unmount(t);return}this.exitResult=t,this.unmount()}},"handleAppExit");setCursorPosition=i(t=>{if(t===void 0){this.cursorPosition=void 0;return}let n=this.getTerminalWidth(),r=this.options.stdout.rows??24;if(n<=0||r<=0){this.cursorPosition=void 0;return}let o=Math.max(0,Math.min(t.x|0,n-1)),s=Math.max(0,Math.min(t.y|0,r-1));this.cursorPosition={x:o,y:s}},"setCursorPosition");resetOutputTracking=i(()=>{this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.cursorPosition=void 0,this.invalidateCellFrame()},"resetOutputTracking");usesVirtualShellOwnership=i((t={})=>t.altScreenActive??this.altScreenActive,"usesVirtualShellOwnership");beginShellTransition(t){this.shellTransitionPhase=t}setShellMode(t,n){let r=this.shellMode,o=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.shellMode=t,this.mouseTrackingActive=a;let c=this.usesVirtualShellOwnership();(r!==t&&(s||c)||o!==a&&c)&&this.resetOutputTracking()}setAltScreenActive(t,n){let r=this.altScreenActive,o=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.altScreenActive=t,this.mouseTrackingActive=a,this.shellTransitionPhase=void 0;let c=this.usesVirtualShellOwnership();(r!==t||o!==a&&(s||c))&&this.resetOutputTracking()}clearTextSelection(){}restoreLastOutput=i(()=>{if(this.prevFrame.screen.height===0)return;let t=ka(this.options.stdout.rows??24,this.getTerminalWidth()),n=this.cellLogUpdate.render(t,this.prevFrame);ou(this.options.stdout,n)},"restoreLastOutput");shouldRestoreManagedShellAfterExternalWrite=i(()=>this.altScreenActive,"shouldRestoreManagedShellAfterExternalWrite");calculateLayout=i(()=>{let t=this.getTerminalWidth();this.rootNode.yogaNode.setWidth(t),this.rootNode.yogaNode.calculateLayout(void 0,void 0,QR.DIRECTION_LTR)},"calculateLayout");onRender=i(()=>{if(this.hasPendingThrottledRender=!1,this.isUnmounted)return;!this.cursorHidden&&!Hr&&!this.options.debug&&!this.isScreenReaderEnabled&&(this.options.stdout.write("\x1B[?25l"),this.cursorHidden=!0);let t=performance.now(),n={rows:this.options.stdout.rows??24,columns:this.getTerminalWidth()},{output:r,outputHeight:o,staticOutput:s,frame:a}=uw(this.rootNode,this.isScreenReaderEnabled,n);this.options.onRender?.({renderTime:performance.now()-t});let c=s&&s!==`
28
- `;if(this.options.debug){c&&(this.fullStaticOutput+=s),this.options.stdout.write(this.fullStaticOutput+r);return}if(Hr){c&&this.options.stdout.write(s),this.lastOutput=r,this.lastOutputToRender=r+`
29
- `,this.lastOutputHeight=o;return}if(this.isScreenReaderEnabled){let p=Gi(this.options.stdout);if(p&&this.options.stdout.write(ji),c){let y=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(y+s),this.lastOutputHeight=0}if(r===this.lastOutput&&!c){p&&this.options.stdout.write(ko);return}let g=this.getTerminalWidth(),x=JR(r,g,{trim:!1,hard:!0});if(c)this.options.stdout.write(x);else{let y=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(y+x)}this.lastOutput=r,this.lastOutputToRender=x,this.lastOutputHeight=x===""?0:x.split(`
30
- `).length,p&&this.options.stdout.write(ko);return}c&&(this.fullStaticOutput+=s);let l=this.altScreenActive,m=this.options.stdout.isTTY&&o>=this.options.stdout.rows&&l?r:r+`
31
- `;if(this.lastOutputHeight>=this.options.stdout.rows&&l){let p=Gi(this.options.stdout);p&&this.options.stdout.write(ji);let g=this.fullStaticOutput+m;if(this.altScreenActive){let x=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(x+g)}else this.options.stdout.write(Sr.clearTerminal+this.fullStaticOutput+r);this.lastOutput=r,this.lastOutputToRender=this.altScreenActive?g:m,this.lastOutputHeight=o,this.invalidateCellFrame(),p&&this.options.stdout.write(ko);return}if(c){let p=Gi(this.options.stdout);p&&this.options.stdout.write(ji);let g=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(g+s),this.invalidateCellFrame(),this.applyCellFrame(a),p&&this.options.stdout.write(ko)}else this.applyCellFrame(a);this.lastOutput=r,this.lastOutputToRender=m,this.lastOutputHeight=o},"onRender");applyCellFrame=i(t=>{let n={cellLogUpdate:this.cellLogUpdate,prevFrame:this.prevFrame,stdout:this.options.stdout},r=Tw(n,t);return this.prevFrame=n.prevFrame,r},"applyCellFrame");invalidateCellFrame=i(()=>{this.cellLogUpdate.reset(),this.prevFrame=ka(this.options.stdout.rows??24,this.getTerminalWidth())},"invalidateCellFrame");render(t){let n=Gw.createElement(Oi.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},Gw.createElement(Uw,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,exitOnCtrlC:this.options.exitOnCtrlC,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,setCursorPosition:this.setCursorPosition,onExit:this.handleAppExit},t));this.options.concurrent?yr.updateContainer(n,this.container,null,au):(yr.updateContainerSync(n,this.container,null,au),yr.flushSyncWork())}writeToStdout(t){if(this.isUnmounted)return;if(this.options.debug){this.options.stdout.write(t+this.fullStaticOutput+this.lastOutput);return}if(Hr){this.options.stdout.write(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.options.stdout.write(t),this.invalidateCellFrame();return}let n=Gi(this.options.stdout);n&&this.options.stdout.write(ji);let r=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(r+t),this.restoreLastOutput(),n&&this.options.stdout.write(ko)}writeToStderr(t){if(this.isUnmounted)return;if(this.options.debug){this.options.stderr.write(t),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(Hr){this.options.stderr.write(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.options.stderr.write(t),this.invalidateCellFrame();return}let n=Gi(this.options.stdout);n&&this.options.stdout.write(ji);let r=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";r.length>0&&this.options.stdout.write(r),this.options.stderr.write(t),this.restoreLastOutput(),n&&this.options.stdout.write(ko)}unmount(t){if(this.isUnmounted||this.isUnmounting)return;this.isUnmounting=!0,this.beforeExitHandler&&(zi.off("beforeExit",this.beforeExitHandler),this.beforeExitHandler=void 0);let n=this.options.stdout,r=!n.destroyed&&!n.writableEnded&&(n.writable??!0);if(i(d=>{typeof d.flush=="function"&&(r?d.flush():typeof d.cancel=="function"&&d.cancel())},"settleThrottle")(this.throttledOnRender??{}),r&&(!this.throttledOnRender||!this.hasPendingThrottledRender&&this.fullStaticOutput==="")&&(this.calculateLayout(),this.onRender()),this.isUnmounted=!0,this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),this.cancelKittyDetection&&this.cancelKittyDetection(),r){if(this.kittyProtocolEnabled)try{this.options.stdout.write("\x1B[<u")}catch{}Hr&&this.options.stdout.write(this.lastOutput+`
32
- `)}this.kittyProtocolEnabled=!1,this.shellTransitionPhase=void 0,this.options.concurrent?yr.updateContainer(null,this.container,null,au):(yr.updateContainerSync(null,this.container,null,au),yr.flushSyncWork()),Cw.delete(this.options.stdout);let{exitResult:s}=this,a=i(()=>{Hm(t)?this.rejectExitPromise(t):this.resolveExitPromise(s)},"resolveOrReject"),c=t!==void 0&&!Hm(t),l=n._writableState!==void 0||n.writableLength!==void 0;c?a():r&&l?this.options.stdout.write("",a):setImmediate(a)}async waitUntilExit(){return this.exitPromise||=new Promise((t,n)=>{this.resolveExitPromise=t,this.rejectExitPromise=n}),this.beforeExitHandler||(this.beforeExitHandler=()=>{this.unmount()},zi.once("beforeExit",this.beforeExitHandler)),this.exitPromise}clear(){if(!Hr&&!this.options.debug){let t=this.lastOutputHeight>0?Sr.eraseLines(this.lastOutputHeight):"";t.length>0&&this.options.stdout.write(t),this.invalidateCellFrame()}}patchConsole(){this.options.debug||(this.restoreConsole=XR((t,n)=>{t==="stdout"&&this.writeToStdout(n),t==="stderr"&&(n.startsWith("The above error occurred")||this.writeToStderr(n))}))}initKittyKeyboard(){if(!this.options.kittyKeyboard)return;let t=this.options.kittyKeyboard,n=t.mode??"auto";if(n==="disabled"||!this.options.stdin.isTTY||!this.options.stdout.isTTY)return;let r=t.flags??["disambiguateEscapeCodes"];if(n==="enabled"){this.enableKittyProtocol(r);return}let o=zi.env.TERM??"",s=zi.env.TERM_PROGRAM??"",a="KITTY_WINDOW_ID"in zi.env||o==="xterm-kitty"||s==="WezTerm"||s==="ghostty";!Hr&&a&&this.confirmKittySupport(r)}confirmKittySupport(t){let{stdin:n,stdout:r}=this.options,o=[],s=i(()=>{this.cancelKittyDetection=void 0,clearTimeout(c),n.removeListener("data",a);let l=cE(o);o=[],l.length>0&&n.unshift(Buffer.from(l))},"cleanup"),a=i(l=>{let d=typeof l=="string"?Buffer.from(l):l;for(let m of d)o.push(m);aE(o)&&(s(),this.isUnmounted||this.enableKittyProtocol(t))},"onData");n.on("data",a);let c=setTimeout(s,200);this.cancelKittyDetection=s,r.write("\x1B[?u")}enableKittyProtocol(t){this.options.stdout.write(`\x1B[>${jw(t)}u`),this.kittyProtocolEnabled=!0}},Vw=lE;var Ea=class{static{i(this,"KodaXRenderer")}engineInstance;isConcurrent;constructor(t){this.engineInstance=new Vw(t),this.isConcurrent=this.engineInstance.isConcurrent}render=i(t=>{this.engineInstance.render(t)},"render");unmount=i(t=>{this.engineInstance.unmount(t)},"unmount");waitUntilExit=i(()=>this.engineInstance.waitUntilExit(),"waitUntilExit");clear=i(()=>{this.engineInstance.clear()},"clear");setAltScreenActive=i((t,n)=>{this.engineInstance.setAltScreenActive?.(t,n)},"setAltScreenActive");setShellMode=i((t,n)=>{this.engineInstance.setShellMode?.(t,n)},"setShellMode");beginShellTransition=i(t=>{this.engineInstance.beginShellTransition?.(t)},"beginShellTransition");clearTextSelection=i(()=>{this.engineInstance.clearTextSelection?.()},"clearTextSelection")};var Fr=null;function Xw(){if(Fr===-1)return null;if(Fr!==null)return Fr;let e=process.env.KODAX_RENDER_TRACE;if(!e||e==="0"||e==="false")return Fr=-1,null;let t=e==="1"||e==="true"?pE(mE(),`kodax-render-trace-${process.pid}.log`):e;try{return Fr=dE(t,"a"),zw(Fr,`=== KODAX render trace pid=${process.pid} ${new Date().toISOString()} platform=${process.platform} node=${process.version} ===
33
- `),Fr}catch{return Fr=-1,null}}i(Xw,"resolveTraceFd");function gE(e){let t=Xw();if(t!==null)try{zw(t,e)}catch{}}i(gE,"traceLine");var cu=new WeakMap,hE={isTTY:!1,columns:80,rows:24,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")},yE={isTTY:!1,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")},xE={isTTY:!1,isRaw:!1,on:i(()=>{},"on"),off:i(()=>{},"off"),pause:i(()=>{},"pause"),resume:i(()=>{},"resume"),setRawMode:i(()=>{},"setRawMode")};function wE(e={}){return e instanceof uE?{stdout:e}:e}i(wE,"getOptions");function SE(e,t,n){let r=cu.get(e);return r?r.isConcurrent!==n&&console.warn(`Warning: render() was called with concurrent: ${n}, but the existing renderer for this stdout uses concurrent: ${r.isConcurrent}. The concurrent option only takes effect on the first render. Call unmount() first if you need to change the rendering mode.`):(r=t(),cu.set(e,r)),r}i(SE,"getInstance");function lu(e){return cu.get(e)}i(lu,"getRendererInstance");function Fm(e,t){let n={stdout:hE,stdin:xE,stderr:yE,debug:!1,exitOnCtrlC:!0,patchConsole:!1,maxFps:30,concurrent:!1,...wE(t)};if(Xw()!==null){let s=n.stdout,a=s.write.bind(s),c=0,l=0;s.write=((g,...x)=>(c+=1,l+=typeof g=="string"?Buffer.byteLength(g,"utf8"):g?.length??0,a(g,...x)));let d=0,m=0,p=n.onRender;n.onRender=g=>{let x=fE.now(),y=d===0?0:x-d,T=s,w=T.columns??0,v=T.rows??0;return gE(`frame=${m} renderTime=${g.renderTime.toFixed(2)}ms interval=${y.toFixed(2)}ms writes=${c} bytes=${l} viewport=${w}x${v}
34
- `),c=0,l=0,d=x,m+=1,p?.(g)}}let o=SE(n.stdout,()=>new Ea(n),n.concurrent??!1);return o.render(e),{rerender:o.render,unmount(){o.unmount()},waitUntilExit:o.waitUntilExit,cleanup:i(()=>{cu.delete(n.stdout)},"cleanup"),clear:o.clear}}i(Fm,"render");var Yw=yn,qw=Xt,Qw=Tm;import{Buffer as CE}from"node:buffer";var bE=/^(?:\x1b)([a-zA-Z0-9])$/,vE=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,Zw={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},eS=[...Object.values(Zw),"backspace"],IE=i(e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),"isShiftKey"),kE=i(e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),"isCtrlKey"),tS=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,RE=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,EE={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},ME={2:"insert",3:"delete",5:"pageup",6:"pagedown",7:"home",8:"end",11:"f1",12:"f2",13:"f3",14:"f4",15:"f5",17:"f6",18:"f7",19:"f8",20:"f9",21:"f10",23:"f11",24:"f12"},Jw={27:"escape",9:"tab",127:"delete",8:"backspace",57358:"capslock",57359:"scrolllock",57360:"numlock",57361:"printscreen",57362:"pause",57363:"menu",57376:"f13",57377:"f14",57378:"f15",57379:"f16",57380:"f17",57381:"f18",57382:"f19",57383:"f20",57384:"f21",57385:"f22",57386:"f23",57387:"f24"},nS=i(e=>e>=0&&e<=1114111&&!(e>=55296&&e<=57343),"isValidCodepoint"),Wm=i(e=>nS(e)?String.fromCodePoint(e):"?","safeFromCodePoint");function rS(e){return e===3?"release":e===2?"repeat":"press"}i(rS,"resolveEventType");function oS(e){return{ctrl:!!(e&wr.ctrl),shift:!!(e&wr.shift),meta:!!(e&wr.meta),option:!!(e&wr.alt),super:!!(e&wr.super),hyper:!!(e&wr.hyper),capsLock:!!(e&wr.capsLock),numLock:!!(e&wr.numLock)}}i(oS,"parseKittyModifiers");function AE(e){let t=tS.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),r=t[2]?Math.max(0,Number.parseInt(t[2],10)-1):0,o=t[3]?Number.parseInt(t[3],10):1,s=t[4];if(!nS(n))return null;let a;s&&(a=s.split(":").map(d=>Wm(Number.parseInt(d,10))).join(""));let c,l;return n===32?(c="space",l=!0):n===13?(c="return",l=!0):Jw[n]?(c=Jw[n],l=!1):n>=1&&n<=26?(c=String.fromCodePoint(n+96),l=!1):(c=Wm(n).toLowerCase(),l=!0),l&&!a&&(a=Wm(n)),{name:c,...oS(r),eventType:rS(o),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:l,text:a}}i(AE,"parseKittyKeypress");function _E(e){let t=RE.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),r=Math.max(0,Number.parseInt(t[2],10)-1),o=Number.parseInt(t[3],10),s=t[4],a=s==="~"?ME[n]:EE[s];return a?{name:a,...oS(r),eventType:rS(o),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1}:null}i(_E,"parseKittySpecialKey");var Um="\x1B[200~",PE="\x1B[201~";function $E(e){if(!e.startsWith(Um))return null;let t=e.indexOf(PE,Um.length);return t===-1?null:e.slice(Um.length,t)}i($E,"extractBracketedPaste");function jm(e=""){let t=e,n;if(CE.isBuffer(t)?t[0]>127&&t[1]===void 0?(t[0]-=128,t="\x1B"+String(t)):t=String(t):t!==void 0&&typeof t!="string"?t=String(t):t||(t=""),typeof t=="string"){let a=$E(t);if(a!==null)return{name:"paste",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t,isPaste:!0,isPrintable:!1,text:a}}let r=AE(t);if(r)return r;let o=_E(t);if(o)return o;if(tS.test(t))return{name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t,isKittyProtocol:!0,isPrintable:!1};let s={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t};if(s.sequence=s.sequence||t||s.name,t==="\r"||t==="\x1B\r")s.raw=void 0,s.name="return",s.option=t.length===2;else if(t===`
35
- `)s.name="enter";else if(t===" ")s.name="tab";else if(t==="\b"||t==="\x1B\b")s.name="backspace",s.meta=t.charAt(0)==="\x1B";else if(t==="\x7F"||t==="\x1B\x7F")s.name="delete",s.meta=t.charAt(0)==="\x1B";else if(t==="\x1B"||t==="\x1B\x1B")s.name="escape",s.meta=t.length===2;else if(t===" "||t==="\x1B ")s.name="space",s.meta=t.length===2;else if(t.length===1&&t<="")s.name=String.fromCharCode(t.charCodeAt(0)+97-1),s.ctrl=!0;else if(t.length===1&&t>="0"&&t<="9")s.name="number";else if(t.length===1&&t>="a"&&t<="z")s.name=t;else if(t.length===1&&t>="A"&&t<="Z")s.name=t.toLowerCase(),s.shift=!0;else if(n=bE.exec(t))s.meta=!0,s.shift=/^[A-Z]$/.test(n[1]??"");else if(n=vE.exec(t)){let a=[...t];a[0]==="\x1B"&&a[1]==="\x1B"&&(s.option=!0);let c=[n[1],n[2],n[4],n[6]].filter(Boolean).join(""),l=Number(n[3]||n[5]||1)-1;s.ctrl=!!(l&4),s.meta=!!(l&10),s.shift=!!(l&1),s.code=c,s.name=Zw[c]??"",s.shift=IE(c)||s.shift,s.ctrl=kE(c)||s.ctrl}return s}i(jm,"parseKeypress");var DE=50;function du(e){return{columns:e?.columns??80,rows:e?.rows??24}}i(du,"resolveTerminalSize");var Wr=LE(null),Gm={isTTY:!1,columns:80,rows:24,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")};var cS={isTTY:!1,isRaw:!1,on:i(()=>{},"on"),off:i(()=>{},"off"),pause:i(()=>{},"pause"),resume:i(()=>{},"resume"),setRawMode:i(()=>{},"setRawMode")};function NE(e){for(let t of e)if(t.rawMode)return!0;return!1}i(NE,"hasRawModeSubscribers");function BE({stdin:e,setRawMode:t,isRawModeSupported:n}){let r=new Set,o,s=!1,a=i(m=>{for(let p of r)p.listener(m)},"handleData"),c=i(()=>{if(s){try{t(!1)}catch{}s=!1}},"disableRawModeIfOwned"),l=i(()=>{o?.off?.("data",a),o=void 0,c()},"detachInput"),d=i(()=>{if(o&&o!==e&&l(),!e||r.size===0){l();return}if(o!==e&&(e.on?.("data",a),o=e),!(n&&NE(r))){c();return}if(e.isRaw===!1&&!s)try{t(!0),s=!0}catch{s=!1}},"syncInputOwnership");return{subscribe(m,p={}){let g={listener:m,rawMode:p.rawMode!==!1};return r.add(g),d(),()=>{r.delete(g),d()}},dispose(){r.clear(),l()}}}i(BE,"createTerminalInputController");var HE=i(({children:e,runtime:t})=>{let[n,r]=OE(()=>t.terminalSize);Xi(()=>{if(r(du(t.stdout)),typeof t.stdout?.on!="function"||typeof t.stdout?.off!="function")return;let c=i(()=>{r(du(t.stdout))},"handleResize");return t.stdout.on("resize",c),()=>{t.stdout.off?.("resize",c)}},[t.stdout]);let o=aS(c=>typeof t.stdout?.write!="function"?!1:(t.stdout.write(c),!0),[t.stdout]),s=iS(()=>BE({stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported}),[t.stdin,t.isRawModeSupported,t.setRawMode]);Xi(()=>()=>{s.dispose()},[s]);let a=iS(()=>({stdout:t.stdout,stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported,exit:t.exit,terminalSize:n,isTTY:t.stdout?.isTTY===!0,writeRaw:o,subscribeInput:s.subscribe}),[s.subscribe,t.exit,t.isRawModeSupported,t.setRawMode,t.stdin,t.stdout,s.subscribe,n,o]);return sS(Wr.Provider,{value:a,children:e})},"TuiRuntimeProvider");function FE(e){let t=e?.stdout??Gm,n=e?.stdin??cS,r=i(s=>{typeof n?.setRawMode=="function"&&n.setRawMode(s)},"setRawMode"),o;return{stdout:t,stdin:n,setRawMode:r,isRawModeSupported:typeof n?.setRawMode=="function",exit:i(()=>{o?.()},"exit"),terminalSize:du(t),isTTY:t?.isTTY===!0,writeRaw:i(s=>typeof t?.write!="function"?!1:(t.write(s),!0),"writeRaw"),subscribeInput:i(()=>()=>{},"subscribeInput"),attachExit(s){o=s}}}i(FE,"createRuntimeValue");function fu(e,t){let n=FE(t),r=Fm(sS(HE,{runtime:n,children:e}),t);return n.attachExit(r.unmount),r}i(fu,"render");var k=Yw,b=qw,Yi=Qw;function WE(e){let t={upArrow:e.name==="up",downArrow:e.name==="down",leftArrow:e.name==="left",rightArrow:e.name==="right",pageDown:e.name==="pagedown",pageUp:e.name==="pageup",home:e.name==="home",end:e.name==="end",return:e.name==="return",escape:e.name==="escape",ctrl:e.ctrl,shift:e.shift,tab:e.name==="tab",backspace:e.name==="backspace",delete:e.name==="delete",meta:e.meta||e.name==="escape"||e.option===!0,super:e.super??!1,hyper:e.hyper??!1,capsLock:e.capsLock??!1,numLock:e.numLock??!1,eventType:e.eventType},n="";return e.isKittyProtocol?e.isPrintable?n=e.text??e.name:e.ctrl&&e.name.length===1&&(n=e.name):e.ctrl?n=e.name:n=e.sequence,!e.isKittyProtocol&&eS.includes(e.name)&&(n=""),n.startsWith("\x1B")&&(n=n.slice(1)),n.length===1&&typeof n[0]=="string"&&/[A-Z]/.test(n[0])&&(t.shift=!0),{input:n,key:t}}i(WE,"createCompatKeypress");function mu(e,t={}){let{isActive:n=!0}=t,r=uu(e),o=uu(null),s=uu(null);Xi(()=>{r.current=e},[e]),Xi(()=>{if(!n){o.current=null,s.current&&(clearTimeout(s.current),s.current=null);return}return o.current=iu(),()=>{o.current?.reset(),o.current=null,s.current&&(clearTimeout(s.current),s.current=null)}},[n]);let a=aS(c=>{let{input:l,key:d}=WE(jm(c));l==="c"&&d.ctrl||r.current(l,d)},[]);Aa(c=>{if(!n)return;s.current&&(clearTimeout(s.current),s.current=null);let l=o.current,d=typeof c=="string"?c:c.toString("utf8"),m=l?.push(d)??[d];for(let p of m)a(p);d.length>0&&(s.current=setTimeout(()=>{let p=o.current?.flushPendingEscape();p&&a(p)},DE))},{isActive:n,rawMode:!0})}i(mu,"useInput");function qn(){return{stdout:Eo(Wr)?.stdout??Gm}}i(qn,"useStdout");function Ma(){let e=Eo(Wr),t=e?.stdin??cS,n=e?.setRawMode??(r=>{typeof t?.setRawMode=="function"&&t.setRawMode(r)});return{stdin:t,setRawMode:n,isRawModeSupported:e?.isRawModeSupported??typeof t?.setRawMode=="function"}}i(Ma,"useStdin");function Ur(){return{exit:Eo(Wr)?.exit??(()=>{})}}i(Ur,"useApp");function qi(){return Eo(Wr)?.stdout??Gm}i(qi,"useTerminalOutput");function Qi(){let e=qi();return Eo(Wr)?.terminalSize??du(e)}i(Qi,"useTerminalSize");function Ji(){let e=qi();return Eo(Wr)?.writeRaw??(n=>typeof e?.write!="function"?!1:(e.write(n),!0))}i(Ji,"useTerminalWrite");function Aa(e,t={}){let{isActive:n=!0,rawMode:r=!0}=t,o=Eo(Wr),{stdin:s,setRawMode:a,isRawModeSupported:c}=Ma(),l=uu(e);Xi(()=>{l.current=e},[e]),Xi(()=>{if(!n||!s)return;if(o)return o.subscribeInput(g=>{l.current(g)},{rawMode:r});let d=s,m=d.isRaw;r&&c&&m===!1&&a(!0);let p=i(g=>{l.current(g)},"handleData");return d.on?.("data",p),()=>{if(d.off?.("data",p),r&&c&&m===!1)try{a(!1)}catch{}}},[o,s,n,r,c,a])}i(Aa,"useTerminalInput");import{jsx as zE}from"react/jsx-runtime";import{useInsertionEffect as XE,useMemo as YE}from"react";var UE="\x1B[?1049h",jE="\x1B[?1049l";var GE="\x1B[2J",KE="\x1B[?1000h\x1B[?1002h\x1B[?1006h",VE="\x1B[?1006l\x1B[?1002l\x1B[?1000l";function pu(e={}){let t=e.mouseTracking!==!1,n=e.clearOnEnter===!0;return UE+(n?GE:"")+"\x1B[H"+(t?KE:"")}i(pu,"buildAlternateScreenEnterSequence");function gu(e={}){return(e.mouseTracking!==!1?VE:"")+jE}i(gu,"buildAlternateScreenExitSequence");var Km=i(({children:e,mouseTracking:t=!0,enabled:n=!0,clearOnEnter:r=!1})=>{let o=qi(),{rows:s}=Qi(),a=Ji(),c=YE(()=>n&&o.isTTY===!0,[n,o]);return XE(()=>{if(!c)return;let l=lu(o);if(l?.setShellMode?.("virtual",t),l?.beginShellTransition?.("enter-alt-screen"),!!a(pu({mouseTracking:t,clearOnEnter:r})))return l?.setAltScreenActive?.(!0,t),()=>{l?.beginShellTransition?.("exit-alt-screen"),l?.clearTextSelection?.(),l?.setAltScreenActive?.(!1),a(gu({mouseTracking:t}))}},[r,c,t,o,a]),zE(k,{flexDirection:"column",height:s,width:"100%",flexGrow:1,flexShrink:0,children:e})},"AlternateScreen");import{jsx as jr,jsxs as fS}from"react/jsx-runtime";import{jsx as qE}from"react/jsx-runtime";import QE,{useEffect as Vm,useImperativeHandle as JE,useMemo as ZE,useRef as zm,useCallback as Xm,useState as eM}from"react";function lS(e){let t={...e,scrollHeight:Math.max(0,Math.floor(e.scrollHeight)),viewportHeight:Math.max(0,Math.floor(e.viewportHeight)),pendingDelta:Math.floor(e.pendingDelta)};return{...t,scrollTop:Ym(t,t.scrollTop)}}i(lS,"normalizeScrollSnapshot");function uS(e,t){return e.scrollTop===t.scrollTop&&e.scrollHeight===t.scrollHeight&&e.viewportHeight===t.viewportHeight&&e.pendingDelta===t.pendingDelta&&e.clampMin===t.clampMin&&e.clampMax===t.clampMax&&e.sticky===t.sticky}i(uS,"areSnapshotsEqual");function tM(e,t){return e.start===t.start&&e.end===t.end&&e.scrollTop===t.scrollTop&&e.scrollHeight===t.scrollHeight&&e.viewportHeight===t.viewportHeight&&e.viewportTop===t.viewportTop&&e.pendingDelta===t.pendingDelta&&e.sticky===t.sticky}i(tM,"areWindowsEqual");function Ym(e,t){let n=Math.max(0,e.scrollHeight-e.viewportHeight),r=e.clampMin??0,o=e.clampMax??n;return Math.max(r,Math.min(Math.floor(t),Math.min(n,o)))}i(Ym,"clampScrollTop");function dS(e){let t=Math.max(0,e.viewportHeight),n=Ym(e,e.scrollTop),r=Math.max(0,e.scrollHeight-n),o=Math.max(0,r-t);return{start:o,end:r,scrollTop:n,scrollHeight:e.scrollHeight,viewportHeight:t,viewportTop:o,pendingDelta:e.pendingDelta,sticky:e.sticky}}i(dS,"resolveScrollWindow");function nM(e){let t=Ym(e,e.scrollTop);return Math.max(0,e.scrollHeight-e.viewportHeight-t)}i(nM,"resolveNativeScrollTop");var qm=i(({children:e,width:t,flexGrow:n=0,flexShrink:r=1,paddingTop:o=0,scrollTop:s=0,scrollHeight:a=0,viewportHeight:c=0,stickyScroll:l=!0,scrollRef:d,onScrollTopChange:m,onStickyChange:p,onWindowChange:g,renderWindow:x})=>{let y=zm(null),T=zm(new Set),w=zm(lS({scrollTop:s,scrollHeight:a,viewportHeight:c,pendingDelta:0,sticky:l})),[v,O]=eM(()=>dS(w.current)),P=Xm(()=>{for(let K of T.current)K()},[]),D=Xm((K,q=!0)=>{let M=w.current,C=lS(K),Z=dS(C);return w.current=C,O(ke=>tM(ke,Z)?ke:Z),q&&!uS(M,C)&&P(),{previous:M,snapshot:C,window:Z,changed:!uS(M,C)}},[P]);Vm(()=>{let K=w.current,q={scrollTop:s,scrollHeight:a,viewportHeight:c,pendingDelta:0,clampMin:K.clampMin,clampMax:K.clampMax,sticky:l},M=D(q);M.previous.sticky!==l&&p?.(l),M.window.scrollTop!==s&&m?.(M.window.scrollTop)},[D,p,m,a,s,l,c]);let L=Xm(()=>{let K=y.current;if(!K)return;let q=typeof K.scrollHeight=="number"?Math.max(0,Math.floor(K.scrollHeight)):void 0,M=typeof K.scrollViewportHeight=="number"?Math.max(0,Math.floor(K.scrollViewportHeight)):void 0,C=typeof K.scrollViewportTop=="number"?Math.max(0,Math.floor(K.scrollViewportTop)):void 0;if(q===void 0||M===void 0||C===void 0)return;let Z=Math.max(0,q-M-C),ke=D({...w.current,scrollTop:Z,scrollHeight:q,viewportHeight:M});ke.changed&&ke.window.scrollTop!==ke.previous.scrollTop&&m?.(ke.window.scrollTop)},[D,m]);Vm(()=>{L()},[L]);let X=ZE(()=>({scrollTo(K){let q=D({...w.current,scrollTop:K,pendingDelta:0,sticky:!1});q.previous.sticky!==!1&&p?.(!1),m?.(q.window.scrollTop)},scrollBy(K){let q=D({...w.current,scrollTop:w.current.scrollTop+K,pendingDelta:w.current.pendingDelta+Math.floor(K),sticky:!1});q.previous.sticky!==!1&&p?.(!1),m?.(q.window.scrollTop)},scrollToElement(K,q=0){let M=D({...w.current,scrollTop:K-q,pendingDelta:0,sticky:!1});M.previous.sticky!==!1&&p?.(!1),m?.(M.window.scrollTop)},scrollToBottom(){let K=D({...w.current,scrollTop:0,pendingDelta:0,sticky:!0});m?.(K.window.scrollTop),K.previous.sticky!==!0&&p?.(!0)},getScrollTop(){return w.current.scrollTop},getPendingDelta(){return w.current.pendingDelta},getScrollHeight(){return y.current?.scrollHeight??w.current.scrollHeight},getViewportHeight(){return y.current?.scrollViewportHeight??v.viewportHeight},getViewportTop(){return y.current?.scrollViewportTop??v.viewportTop},isSticky(){return w.current.sticky},subscribe(K){return T.current.add(K),()=>{T.current.delete(K)}},setClampBounds(K,q){let M=D({...w.current,clampMin:K,clampMax:q});M.window.scrollTop!==M.previous.scrollTop&&m?.(M.window.scrollTop)}}),[D,m,p]);JE(d,()=>X,[X]),Vm(()=>{g?.(v)},[g,v]);let I=x?x(v):e,ie=Math.max(0,c+o),Te=nM(w.current);return QE.createElement("ink-box",{ref:y,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:n,flexShrink:r,width:t,height:ie,paddingTop:o,overflowX:"visible",overflowY:"scroll"},scrollTop:Te,scrollHeight:w.current.scrollHeight,scrollViewportHeight:w.current.viewportHeight,scrollViewportTop:v.viewportTop,pendingScrollDelta:w.current.pendingDelta,virtualScrollWindowed:!!x,...w.current.clampMin!==void 0?{scrollClampMin:w.current.clampMin}:{},...w.current.clampMax!==void 0?{scrollClampMax:w.current.clampMax}:{},...l?{stickyScroll:!0}:{}},qE(k,{flexDirection:"column",flexGrow:1,flexShrink:0,width:"100%",children:I}))},"ScrollBox");var rM=80;function _a(e){if(!(!e?.visible||!e.label))return e.hint?`${e.label}: ${e.hint}`:e.label}i(_a,"resolveFullscreenChromeSlotText");function hu(e,t){if(!e)return 0;let n=Math.max(1,(typeof t=="number"?t:rM)-2);return Math.max(1,zt(e.split(`
36
- `),n,0,0).visualLines.length)}i(hu,"measureFullscreenChromeSlotRows");var Qm=i(({top:e,topRows:t=0,scrollable:n,renderScrollableWindow:r,bottom:o,overlay:s,stickyHeader:a,jumpToLatest:c,width:l,scrollTop:d=0,scrollHeight:m=0,viewportHeight:p=0,stickyScroll:g=!0,scrollRef:x,onScrollTopChange:y,onStickyChange:T,onWindowChange:w})=>{let v=i((Te,K)=>K?jr(k,{paddingX:1,children:jr(b,{dimColor:Te?.tone!=="accent",children:K})}):null,"renderChromeSlot"),O=_a(a),P=_a(c),D=hu(O,l),L=v(a,O),X=s?null:v(c,P),I=Math.max(0,e?t:0),ie=Math.max(0,p-D-I);return fS(k,{flexDirection:"column",width:l,flexGrow:1,flexShrink:0,children:[e?jr(k,{flexDirection:"column",flexShrink:0,children:e}):null,fS(k,{flexDirection:"column",flexGrow:1,overflowY:"hidden",children:[jr(qm,{width:l,flexGrow:1,flexShrink:1,paddingTop:D,scrollTop:d,scrollHeight:m,viewportHeight:ie,stickyScroll:g,scrollRef:x,onScrollTopChange:y,onStickyChange:T,onWindowChange:w,renderWindow:r,children:n}),L?jr(k,{position:"absolute",top:0,left:0,right:0,flexDirection:"column",children:L}):null,X?jr(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:X}):null,s?jr(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:s}):null]}),jr(k,{flexDirection:"column",flexShrink:0,children:o})]})},"FullscreenLayout");import iM from"string-width";function sM(){return Qi().columns}i(sM,"useTerminalWidth");var Jm=i(({lines:e,cursorRow:t,cursorCol:n,prompt:r=">",placeholder:o="Type your message...",focus:s=!0,terminalFocused:a=!0,isPasting:c=!1,editingMode:l="idle",theme:d="dark",width:m})=>{let p=yu(()=>ne(d),[d]),g=sM(),x=m??g,y=iM(r)+1,T=yu(()=>{let L=Math.max(20,x-y);return zt(e,L,t,n)},[e,x,t,n,y]),w=yu(()=>{if(!T)return null;let[L,X]=xm(T,[t,n]);return{row:L,col:X}},[T,t,n]),v=s&&a,O=c&&e.some(L=>L.length>0),P=T,D=w;return xn(k,{flexDirection:"column",borderStyle:"round",borderColor:p.colors.dim,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,width:m??"100%",children:[O?Yt(k,{children:Yt(b,{dimColor:!0,children:l==="pasting"?"Pasting input...":"Editing input..."})}):null,P.visualLines.length===0||P.visualLines.length===1&&P.visualLines[0]===""?xn(k,{children:[xn(b,{color:p.colors.primary,children:[r," "]}),v?xn(oM,{children:[Yt(b,{backgroundColor:p.colors.primary,color:"#000000",children:" "}),Yt(b,{dimColor:!0,children:o})]}):Yt(b,{dimColor:!0,children:o})]}):P.visualLines.map((L,X)=>{let I=X===D.row,ie=X===0?r:" ".repeat(y-1);if(I&&v){let{before:Te,current:K,after:q}=Ox(L,D.col),M=K||" ";return xn(k,{children:[xn(b,{color:p.colors.primary,children:[ie," "]}),Yt(b,{color:p.colors.text,children:Te}),Yt(b,{backgroundColor:p.colors.primary,color:"#000000",children:M}),Yt(b,{color:p.colors.text,children:q})]},X)}return xn(k,{children:[xn(b,{color:p.colors.dim,children:[ie," "]}),Yt(b,{color:p.colors.text,children:L})]},X)})]})},"TextInput"),aM=i(({value:e,cursorCol:t,prompt:n=">",placeholder:r,focus:o=!0,theme:s="dark"})=>{let a=yu(()=>ne(s),[s]);if(!e)return xn(k,{children:[xn(b,{color:a.colors.primary,children:[n," "]}),r&&Yt(b,{dimColor:!0,children:r}),o&&Yt(b,{backgroundColor:a.colors.primary,color:"#000000",children:" "})]});let c=Vt(e),l=c.slice(0,t).join(""),d=c[t]??" ",m=c.slice(t+1).join("");return xn(k,{children:[xn(b,{color:a.colors.primary,children:[n," "]}),Yt(b,{color:a.colors.text,children:l}),Yt(b,{backgroundColor:a.colors.primary,color:"#000000",children:d}),Yt(b,{color:a.colors.text,children:m})]})},"SingleLineTextInput");var Zm={"[A":{name:"up"},"[B":{name:"down"},"[C":{name:"right"},"[D":{name:"left"},"[200~":{name:"paste_start"},"[201~":{name:"paste_end"},"[Z":{name:"tab",shift:!0},"[1;2A":{name:"up",shift:!0},"[1;2B":{name:"down",shift:!0},"[1;2C":{name:"right",shift:!0},"[1;2D":{name:"left",shift:!0},"[13;2u":{name:"return",shift:!0},"[13;3u":{name:"return",meta:!0},"[13;5u":{name:"return",ctrl:!0},"[H":{name:"home"},"[F":{name:"end"},"[1~":{name:"home"},"[4~":{name:"end"},"[7~":{name:"home"},"[8~":{name:"end"},"[2~":{name:"insert"},"[3~":{name:"delete"},"[5~":{name:"pageup"},"[6~":{name:"pagedown"},"[11~":{name:"f1"},"[12~":{name:"f2"},"[13~":{name:"f3"},"[14~":{name:"f4"},"[15~":{name:"f5"},"[17~":{name:"f6"},"[18~":{name:"f7"},"[19~":{name:"f8"},"[20~":{name:"f9"},"[21~":{name:"f10"},"[23~":{name:"f11"},"[24~":{name:"f12"},OP:{name:"f1"},OQ:{name:"f2"},OR:{name:"f3"},OS:{name:"f4"},OA:{name:"up"},OB:{name:"down"},OC:{name:"right"},OD:{name:"left"},OH:{name:"home"},OF:{name:"end"}},cM=/^\x1b\[([0-9]+);?([0-9]+)?([~A-Za-z])?/,lM=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/;function uM(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"unknown"}}i(uM,"parseMouseButton");function dM(e){return{shift:(e&1)!==0,alt:(e&2)!==0,ctrl:(e&4)!==0,meta:(e&8)!==0}}i(dM,"parseModifier");function xu(e,t=!1){let n={name:"",sequence:e,ctrl:!1,meta:!1,shift:!1,insertable:!1,isPasted:!1};if(!e||e.length===0)return n;let r=e.match(lM);if(r){let[,o,s,a,c]=r,l=Number(o),d=Number(s),m=Number(a),p=l&28;return n.shift=(p&4)!==0,n.meta=(p&8)!==0,n.ctrl=(p&16)!==0,l===64?(n.name="wheelup",n.mouse={action:"wheel",button:"wheelup",row:m,column:d},n):l===65?(n.name="wheeldown",n.mouse={action:"wheel",button:"wheeldown",row:m,column:d},n):(n.name="mouse",n.mouse={action:c==="m"?"release":(l&32)!==0?"drag":"press",button:uM(l),row:m,column:d},n)}if(e===`\r
37
- `)return n.name="newline",n;if(e==="\r")return n.name=t?"newline":"return",n;if(e===`
38
- `)return n.name="newline",n;if(e===" ")return n.name="tab",n;if(e==="\b"||e==="\x7F")return n.name="backspace",n;if(e==="\x1B\b"||e==="\x1B\x7F")return n.name="backspace",n.meta=!0,n;if(e==="\x1B\r"||e===`\x1B
39
- `)return n.name=e==="\x1B\r"?"return":"enter",n.shift=!0,n;if(e==="\x1B"||e==="\x1B\x1B")return n.name="escape",n.meta=e.length===2,n;if(e===" "||e==="\x1B ")return n.name="space",n.meta=e.length===2,n.insertable=!n.meta,n;if(e.length===1&&e.charCodeAt(0)<=26)return n.name=String.fromCharCode(e.charCodeAt(0)+96),n.ctrl=!0,n;if(e.length===1&&e>="0"&&e<="9"||e.length===1&&e>="a"&&e<="z")return n.name=e,n.insertable=!0,n;if(e.length===1&&e>="A"&&e<="Z")return n.name=e.toLowerCase(),n.shift=!0,n.insertable=!0,n;if(e.length===1&&e.charCodeAt(0)>=32)return n.name=e,n.insertable=!0,n;if(e.startsWith("\x1B")){let o=e.slice(1);if(o.length===1)return n.meta=!0,o>="a"&&o<="z"?(n.name=o,n.insertable=!0):o>="A"&&o<="Z"?(n.name=o.toLowerCase(),n.shift=!0,n.insertable=!0):o.charCodeAt(0)>=32&&(n.name=o,n.insertable=!0),n;let s=e.match(cM);if(s){let[,l,d,m]=s,p=m||"~",x=Zm[o];if(x)return Object.assign(n,x),n;let y="["+l+p+"]",T=Zm[y];if(T&&T.name){if(n.name=T.name,d){let w=parseInt(d,10)-1,v=dM(w);Object.assign(n,v)}return n}}let c=Zm[o];if(c)return Object.assign(n,c),n;if(e.startsWith("\x1B\x1B")){n.meta=!0;let l="\x1B"+e.slice(2),d=xu(l);return n.name=d.name,n}}return n}i(xu,"parseKeypress");var Pa=class{static{i(this,"KeypressParser")}buffer="";listeners=[];flushing=!1;inBracketedPaste=!1;pasteAccumulator="";onKeypress(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}feed(t,n=!1){let r=typeof t=="string"?t:t.toString("utf8");this.buffer+=r,this.flushing=n,this.processBuffer()}processBuffer(){for(;this.buffer.length>0;){let t=this.extractNextSequence();if(!t){if(this.flushing&&this.buffer.length>0){let s=this.buffer;this.buffer="";let a=xu(s,this.inBracketedPaste);this.emit(a)}break}let{sequence:n,remaining:r}=t;this.buffer=r;let o=xu(n,this.inBracketedPaste);if(o.name==="paste_start"){this.inBracketedPaste=!0,this.pasteAccumulator="";continue}if(o.name==="paste_end"){this.inBracketedPaste=!1,this.flushPasteAccumulator();continue}this.emit(o)}}flushPasteAccumulator(){if(this.pasteAccumulator.length===0)return;let t={name:"paste",sequence:this.pasteAccumulator,ctrl:!1,meta:!1,shift:!1,insertable:!0,isPasted:!0};this.pasteAccumulator="";for(let n of this.listeners)n(t)}extractNextSequence(){if(this.buffer.length===0)return null;let t=this.buffer[0];if(t!=="\x1B")return t==="\r"&&this.buffer.length>=2&&this.buffer[1]===`
40
- `?{sequence:this.buffer.slice(0,2),remaining:this.buffer.slice(2)}:{sequence:this.buffer[0],remaining:this.buffer.slice(1)};if(this.buffer.length===1)return this.flushing?{sequence:this.buffer,remaining:""}:null;let n=this.buffer[1];if(n!=="["&&n!=="O")return{sequence:this.buffer.slice(0,2),remaining:this.buffer.slice(2)};if(this.buffer.startsWith("\x1B[<")){let a=3;for(;a<this.buffer.length;){let c=this.buffer[a];if(!c)break;if(c>="0"&&c<="9"||c===";"||c==="<"){a++;continue}if(c==="M"||c==="m")return a++,{sequence:this.buffer.slice(0,a),remaining:this.buffer.slice(a)};break}return this.flushing?{sequence:this.buffer,remaining:""}:null}let r=2;for(;r<this.buffer.length;){let a=this.buffer[r];if(!a)break;if(a>="0"&&a<="9"||a===";"){r++;continue}if(a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="~"){r++;break}break}let o=this.buffer[r-1];return o&&(o>="A"&&o<="Z"||o>="a"&&o<="z"||o==="~")?{sequence:this.buffer.slice(0,r),remaining:this.buffer.slice(r)}:this.flushing?{sequence:this.buffer.slice(0,r),remaining:this.buffer.slice(r)}:null}emit(t){if(this.inBracketedPaste){if(t.isPasted=!0,t.insertable){this.pasteAccumulator+=t.sequence;return}if(t.name==="newline"){this.pasteAccumulator+=`
41
- `;return}return}for(let n of this.listeners)n(t)}clear(){this.buffer=""}};function mS(e){return["up","down","left","right","home","end","insert","delete","pageup","pagedown","wheelup","wheeldown","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","tab","return","enter","backspace","escape"].includes(e.name)}i(mS,"isFunctionKey");function fM(e){return e.ctrl||e.meta||mS(e)?!1:e.sequence.length===1&&e.sequence.charCodeAt(0)>=32}i(fM,"isPrintable");function mM(e){let t=[];return e.ctrl&&t.push("Ctrl"),e.meta&&t.push("Alt"),e.shift&&t.push("Shift"),e.name?t.push(e.name.toUpperCase()):e.sequence&&t.push(e.sequence),t.join("+")}i(mM,"getKeyDisplayName");var on;(function(e){e.Idle="idle",e.Responding="responding",e.WaitingForConfirmation="waiting_for_confirmation"})(on||(on={}));var $;(function(e){e.Scheduled="scheduled",e.Validating="validating",e.AwaitingApproval="awaiting_approval",e.Executing="executing",e.Success="success",e.Error="error",e.Cancelled="cancelled"})($||($={}));var OW={[$.Scheduled]:"\u25CB",[$.Validating]:"\u25CC",[$.AwaitingApproval]:"?",[$.Executing]:"\u25CB",[$.Success]:"\u2713",[$.Error]:"\u2717",[$.Cancelled]:"-"},Nt;(function(e){e[e.Low=-100]="Low",e[e.Normal=0]="Normal",e[e.High=100]="High",e[e.Critical=200]="Critical"})(Nt||(Nt={}));var ep={streamingState:on.Idle,currentResponse:"",history:[],pendingToolCalls:[],sessionId:"",provider:"",model:"",isLoading:!1};import pM,{createContext as gM,useContext as hM,useEffect as pS,useCallback as yM,useRef as tp}from"react";var xM=50;function np(){let e=new Map,t=null,n=i(()=>(t===null&&(t=[...e.keys()].sort((r,o)=>o-r)),t),"getSortedPriorities");return{register(r,o){return e.has(r)||e.set(r,[]),e.get(r).push(o),t=null,()=>{let s=e.get(r);if(!s)return;let a=s.indexOf(o);a>=0&&s.splice(a,1),s.length===0&&e.delete(r),t=null}},dispatch(r){let o=n();for(let s of o){let a=e.get(s);if(a)for(let c=a.length-1;c>=0;c-=1){let l=a[c];if(l&&l(r)===!0)return!0}}return!1},size(){let r=0;for(let o of e.values())r+=o.length;return r}}}i(np,"createKeypressManager");var gS=gM(null);function wu({children:e,enabled:t=!0}){let{stdout:n}=qn(),r=tp(np()),o=tp(null),s=tp(null),a=yM(c=>{t&&r.current.dispatch(c)},[t]);return pS(()=>{if(!t)return;n?.write?.("\x1B[?2004h");let c=new Pa;o.current=c;let l=c.onKeypress(a);return()=>{s.current&&(clearTimeout(s.current),s.current=null),l(),o.current=null;try{n?.write?.("\x1B[?2004l")}catch{}}},[a,t,n]),Aa(c=>{t&&(s.current&&clearTimeout(s.current),o.current?.feed(c),c.length!==0&&(s.current=setTimeout(()=>{o.current?.feed("",!0)},xM)))},{isActive:t,rawMode:!0}),pM.createElement(gS.Provider,{value:r.current},e)}i(wu,"KeypressProvider");function rp(){let e=hM(gS);if(!e)throw new Error("useKeypressManager must be used within a KeypressProvider");return e}i(rp,"useKeypressManager");function sn(e,t,n=[]){let r=rp(),o=typeof e=="function",s,a,c;if(o){s=e;let l=t??{};c=l.isActive??!0;let d=l.priority;a=typeof d=="boolean"?d?Nt.High:Nt.Normal:d??Nt.Normal}else a=typeof e=="boolean"?e?Nt.High:Nt.Normal:e,s=t,c=!0;pS(()=>c?r.register(a,s):void 0,[r,a,c,...o?[]:n])}i(sn,"useKeypress");function wn(e){return t=>!(e.name!==void 0&&t.name!==e.name||e.ctrl!==void 0&&t.ctrl!==e.ctrl||e.meta!==void 0&&t.meta!==e.meta||e.shift!==void 0&&t.shift!==e.shift||e.sequence!==void 0&&t.sequence!==e.sequence||e.insertable!==void 0&&t.insertable!==e.insertable)}i(wn,"createKeyMatcher");var hS={isEnter:wn({name:"return"}),isEscape:wn({name:"escape"}),isCtrlC:wn({name:"c",ctrl:!0}),isCtrlD:wn({name:"d",ctrl:!0}),isUp:wn({name:"up"}),isDown:wn({name:"down"}),isLeft:wn({name:"left"}),isRight:wn({name:"right"}),isBackspace:wn({name:"backspace"}),isDelete:wn({name:"delete"}),isTab:wn({name:"tab"}),isShiftEnter:i(e=>e.name==="return"&&e.shift===!0,"isShiftEnter"),isCtrlEnter:i(e=>e.name==="return"&&e.ctrl===!0,"isCtrlEnter"),isInsertable:i(e=>e.insertable===!0&&!e.ctrl&&!e.meta,"isInsertable")};var $a=["plan","accept-edits","auto","auto-in-project"];function qt(e){return e==="auto"||e==="auto-in-project"}i(qt,"isAutoMode");function Zi(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}i(Zi,"permissionModeDisplayName");var wM='[deprecated] permissionMode "auto-in-project" is now an alias for "auto" (FEATURE_092, v0.7.33). The alias will be removed in v0.7.38 \u2014 please update ~/.kodax/config.json to use "auto".';function Su(e=console.warn){let t=!1;return()=>{t||(t=!0,e(wM))}}i(Su,"createAutoInProjectDeprecationEmitter");var yS=mx(),Sn=new Set(yS.filter(e=>e.sideEffect==="mutates-fs"&&e.requiredParams.includes("path")).map(e=>e.name)),xS=new Set(yS.filter(e=>e.sideEffect!=="readonly").map(e=>e.name)),wS=new Set(["npm install","npm i","npm uninstall","npm remove","npm update","npm ci","yarn add","yarn remove","yarn upgrade","pnpm add","pnpm remove","pnpm update","git clean","git reset","git checkout","git switch","git merge","git rebase","git cherry-pick","git revert","git commit","git push","git pull","rm","mv","cp","mkdir","rmdir","touch","chmod","chown","del","erase","rd","copy","move","ren","curl","wget","dd","tar","kill","pkill","killall"]),SS=new Set(["ls","cat","pwd","echo","whoami","date","which","whereis","tree","dir","type","get-childitem","get-content","select-string","get-location","where","grep","find","awk","sed","head","tail","less","more","wc","findstr","fc","git status","git diff","git log","git show","git branch","git remote","git ls-files","git rev-parse","git grep","git tag","git stash list","git describe","git config --get","node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc"]);function Mo(e){switch(e){case"plan":return new Set(["bash","write","edit","undo"]);case"accept-edits":return new Set(["bash"]);case"auto":case"auto-in-project":return new Set}}i(Mo,"computeConfirmTools");function op(e){return e!==void 0&&$a.includes(e)}i(op,"isPermissionMode");function Qn(e,t){return op(e)?e:t}i(Qn,"normalizePermissionMode");import Tu from"fs";import xt from"path";import Oa from"os";var $S=jI(AS(),1);var _S=new Set(["/dev/null","nul","NUL"]);function cp(e){return _S.has(e)||_S.has(e.toLowerCase())}i(cp,"isNullDevice");function La(e){let t=e.trim();if(!t)return{statements:[],unparseable:!1};if(t.includes("`"))return{statements:[],unparseable:!0};let n;try{n=(0,$S.parse)(t)}catch{return{statements:[],unparseable:!0}}let r=[],o=[],s=[],a=[],c=null,l=!1,d=i(()=>{(s.length>0||a.length>0)&&(o.push({argv:s,redirections:a}),s=[],a=[])},"flushStage"),m=i(p=>{d(),o.length>0&&(r.push({precedingOp:c,stages:o}),o=[]),c=p},"flushStatement");for(let p=0;p<n.length;p+=1){let g=n[p];if(typeof g=="string"){s.push(g);continue}if("op"in g){let x=g.op;if(x==="&&"||x==="||"||x===";"){m(x);continue}if(x==="|"){d();continue}if(x==="&"){let y=n[p+1];if(y!==void 0&&typeof y!="string"&&"op"in y&&(y.op===">"||y.op===">>")){let T=n[p+2];if(typeof T!="string"){l=!0,p+=1;continue}a.push(PS(`&${y.op}`,T)),p+=2;continue}l=!0;continue}if(MM(x)){let y=null,T=s[s.length-1];T!==void 0&&/^[0-9]+$/.test(T)&&(y=T,s.pop());let w=n[p+1];if(typeof w!="string"){l=!0;continue}a.push(PS(y?`${y}${x}`:x,w)),p+=1;continue}if(x==="glob"){let y=g.pattern;typeof y=="string"?s.push(y):l=!0;continue}l=!0;continue}if("comment"in g)break;l=!0}return m(null),{statements:r,unparseable:l}}i(La,"parseBashCommand");var EM=new Set([">",">>","<","<<","<<<","&>","&>>"]),LS=/^([0-9]+|&)(>>?|<<?)$/;function MM(e){return EM.has(e)||LS.test(e)}i(MM,"isRedirectionOp");function PS(e,t){let n=null,r=e,o=LS.exec(e);return o&&(n=o[1],r=o[2]),{op:e,fd:n,append:r===">>"||e==="&>>",input:r==="<"||r==="<<"||e==="<<<",target:t}}i(PS,"parseRedirection");var AM=xt.join(".agent","plan_mode_doc.md"),Cu=new Map,bu=null;function _M(e){if(!e||!e.trim())return!1;let t=e.trim().replace(/\s+/g," ").toLowerCase();for(let n of SS)if(t===n||t.startsWith(n+" ")){if(n==="sed"&&t.split(/\s+/).some(s=>s.startsWith("-i")||s==="--in-place"))return!1;if(n==="awk"){let o=t.split(/\s+/);if(o.includes("-f")||o.includes("--file"))return!1}if(["node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc","ruby","perl"].includes(n)){let o=t.split(/\s+/).slice(1);if(o.length>0&&!o.every(s=>/^(-v|--version|-h|--help)$/.test(s)))return!1}return!0}return!1}i(_M,"isSingleBashReadCommand");var PM=/^[a-zA-Z0-9]+$/;function $M(e){let t=e.trim();if(!t.endsWith("--help")||t.includes('"')||t.includes("'"))return!1;let n=!1;for(let r of t.split(/\s+/))if(r.startsWith("-"))if(r==="--help")n=!0;else return!1;else if(!PM.test(r))return!1;return n}i($M,"isHelpCommand");function $n(e){if(!e||!e.trim())return!1;if($M(e))return!0;let t=e.trim().replace(/\\\r?\n/g," "),n=La(t);if(n.unparseable||n.statements.length===0)return!1;let r=n.statements.length>1||(n.statements[0]?.stages.length??0)>1;for(let o of n.statements){if(o.precedingOp!==null&&o.precedingOp!=="&&")return!1;for(let s of o.stages){for(let c of s.redirections)if(c.input||!cp(c.target))return!1;let a=s.argv.join(" ");if(a&&!(r&&s.argv[0]?.toLowerCase()==="cd"&&s.argv.length>=2)&&!_M(a))return!1}}return!0}i($n,"isBashReadCommand");function up(e){let t=e.trim();return t?$n(t)?null:"[Blocked] Direct !command execution only supports safe read-only commands. Use the bash tool for commands that write files, invoke shells, or require confirmation.":"[Shell: No command provided]"}i(up,"getDirectShellBypassBlockReason");var DS=new Set(["remove-item","set-content","add-content","out-file","new-item","copy-item","move-item","rename-item","ni"]);function Ln(e){if(!e||!e.trim())return!1;let t=La(e);if(t.unparseable)return!1;for(let n of t.statements)for(let r of n.stages){let o=r.argv.map(s=>s.toLowerCase());if(o.length>0){let s=o[0],a=o.length>=2?`${o[0]} ${o[1]}`:null;for(let c of wS)if(c===s||a!==null&&c===a)return!0}for(let s of o)if(DS.has(s))return!0;for(let s of r.redirections)if(!s.input&&!cp(s.target))return!0}return!1}i(Ln,"isBashWriteCommand");function dp(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\((.+)\)$/);return t?{tool:t[1].toLowerCase(),pattern:t[2]}:{tool:e.toLowerCase(),pattern:null}}i(dp,"parseAllowedToolPattern");function LM(e,t){if(t==="*")return!1;if(t.endsWith(":*")){let n=t.slice(0,-2);return e.startsWith(n)}return e===t}i(LM,"matchesBashPatternLegacy");function OM(e,t){if(t==="*")return!1;if(t.endsWith(":*")){let n=t.slice(0,-2);return e===n}return e===t}i(OM,"matchesBashPatternByExtractedPrefix");async function Gr(e,t,n,r,o){if(e.toLowerCase()!=="bash")return!1;let s=t.command??"",a=[];for(let c of n){let l=dp(c);if(l.tool==="bash"){if(l.pattern===null)return!0;a.push({pattern:l.pattern})}}if(a.length===0)return!1;if(r){let c;try{c=await r.extract(s,o)}catch{return!1}if(c.kind!=="prefix")return!1;for(let{pattern:l}of a)if(l&&OM(c.value,l))return!0;return!1}for(let{pattern:c}of a)if(c&&LM(s,c))return!0;return!1}i(Gr,"isToolCallAllowed");function Iu(e,t,n){if(e.toLowerCase()!=="bash")return"";let r=t.command??"",o=r.split(" ");return o.length>1?`Bash(${o.slice(0,2).join(" ")}:*)`:`Bash(${r})`}i(Iu,"generateSavePattern");function Jn(e,t){try{let n=xt.resolve(e),r=xt.resolve(t),o=Si(),s=xt.join(r,".kodax");return es(n,s)||es(n,o)?!0:!(es(n,r)||HS().some(c=>es(n,c)))}catch{return!1}}i(Jn,"isAlwaysConfirmPath");function OS(e){return!e||e.startsWith("-")?!1:/^\.\.?[/\\]/.test(e)||e.startsWith("~/")||e.startsWith("~\\")||/^[a-zA-Z]:[/\\]/.test(e)?!0:e.startsWith("/")&&e.length>1?!(process.platform==="win32"&&DM.test(e)):!!(e.startsWith(".")&&/[/\\]/.test(e))}i(OS,"looksLikePath");var DM=/^\/[A-Za-z][A-Za-z0-9]*(?::[A-Za-z0-9]+)?$/;function NM(e){let t=[],n=/["']([^"']+)["']/g,r;for(;(r=n.exec(e))!==null;)t.push(r[1]);let o=/(?:^|\s)(\.\.?\/[^\s]+|\.\.?\\[^\s]+|[a-zA-Z]:\\[^\s]+|~\/[^\s]+|\.[^\s]*[/\\][^\s]*)/g;for(;(r=o.exec(e))!==null;)t.push(r[1]);return t}i(NM,"legacyRegexPathScan");function ku(e){let t=new Set,n=La(e);if(!n.unparseable)for(let r of n.statements)for(let o of r.stages){for(let s of o.argv)OS(s)&&t.add(s);for(let s of o.redirections)OS(s.target)&&t.add(s.target)}for(let r of NM(e))t.add(r);return Array.from(t)}i(ku,"extractPathsFromCommand");function fp(e,t){let n=ku(e);for(let r of n)if(Jn(r,t))return!0;return!1}i(fp,"isCommandOnProtectedPath");function vu(e){let t=xt.normalize(e);return process.platform==="win32"?t.toLowerCase():t}i(vu,"normalizePathForComparison");function BM(e,t){return vu(e)===vu(t)}i(BM,"pathsEqual");function es(e,t){let n=vu(e),r=vu(t);return n===r||n.startsWith(r+xt.sep)}i(es,"isPathInsideDirectory");function Ru(e,t){try{let n=xt.resolve(t),r=xt.resolve(n,BS(NS(e)));return es(r,n)}catch{return!1}}i(Ru,"isPathInsideProject");function HM(e){let t=e.match(/[A-Za-z]:[\\/][^\s;|&<>(){}'"]+|\/[^\s;|&<>(){}'"]+/g);return t?t.filter(n=>!/^(?:\/dev\/|\/proc\/)/i.test(n)):[]}i(HM,"collectAbsolutePathCandidates");function mp(e){let t=xt.resolve(e),n=Cu.get(t);if(n)return n;if(Tu.existsSync(t)){let c=Tu.realpathSync.native(t);return Cu.set(t,c),c}let r=[],o=t;for(;!Tu.existsSync(o);){let c=xt.dirname(o);if(c===o)return Cu.set(t,t),t;r.unshift(xt.basename(o)),o=c}let s=Tu.realpathSync.native(o),a=xt.join(s,...r);return Cu.set(t,a),a}i(mp,"resolveExistingPathPrefix");function NS(e){return e==="~"?Oa.homedir():e.startsWith(`~${xt.sep}`)||e.startsWith("~/")||e.startsWith("~\\")?xt.join(Oa.homedir(),e.slice(2)):e}i(NS,"expandHomeDirectory");function BS(e){let t=Oa.tmpdir(),n=[[/^%temp%/i,t],[/^%tmp%/i,t],[/^\$env:temp\b/i,t],[/^\$env:tmp\b/i,t],[/^\$tmpdir\b/i,t],[/^\$temp\b/i,t],[/^\$tmp\b/i,t]];for(let[r,o]of n)if(r.test(e))return e.replace(r,o);return e}i(BS,"expandSystemTempAlias");function FM(e,t){let n=xt.resolve(t??process.cwd()),r=BS(NS(e)),o=xt.isAbsolute(r)?xt.resolve(r):xt.resolve(n,r);return mp(o)}i(FM,"resolvePermissionPath");function HS(){if(bu)return bu;let e=new Set,t=[Oa.tmpdir(),process.env.TEMP,process.env.TMP,process.env.TMPDIR].filter(n=>typeof n=="string"&&n.trim().length>0);for(let n of t)try{e.add(mp(n))}catch{}return bu=Array.from(e),bu}i(HS,"getSystemTempDirectories");function pp(e){let t=mp(e??process.cwd());return{projectPlanDoc:xt.join(t,AM),systemTempDirs:HS()}}i(pp,"getPlanModeAllowedWritablePaths");function lp(e,t){let n=FM(e,t),{projectPlanDoc:r,systemTempDirs:o}=pp(t);return BM(n,r)?!0:o.some(s=>es(n,s))}i(lp,"isPlanModeAllowedPath");function WM(e){let{projectPlanDoc:t,systemTempDirs:n}=pp(e),r=n[0]??Oa.tmpdir();return`${t} or the system temp directory (${r})`}i(WM,"formatPlanModeAllowedLocations");var UM=new Set(["-a","--append","-i","--ignore-interrupts"]);function jM(e){let t=[];for(let n=1;n<e.argv.length;n+=1){let r=e.argv[n];UM.has(r)||r.startsWith("-")||t.push(r)}return t}i(jM,"collectTeeTargets");function GM(e){let t=[],n=1,r=!1;for(;n<e.argv.length;){let o=e.argv[n],s=o.toLowerCase();if(s==="-path"||s==="-literalpath"||s==="-destination"){let a=e.argv[n+1];if(a!==void 0&&!a.startsWith("-")){t.push(a),n+=2;continue}}!o.startsWith("-")&&!r&&(t.push(o),r=!0),n+=1}return t}i(GM,"collectPowerShellWriteTargets");function _o(e){let t=new Set,n=i(o=>{let s=o?.trim();s&&t.add(s)},"pushTarget");for(let o of ku(e))n(o);let r=La(e);if(r.unparseable)return Array.from(t);for(let o of r.statements)for(let s of o.stages){for(let c of s.redirections)c.input||n(c.target);let a=s.argv[0]?.toLowerCase();if(a){if(a==="tee")for(let c of jM(s))n(c);else if(DS.has(a))for(let c of GM(s))n(c)}}return Array.from(t)}i(_o,"collectBashWriteTargets");function gp(e,t){if(!Ln(e))return{dangerous:!1};let n=new Set([..._o(e),...HM(e)]);for(let r of n)if(!Ru(r,t))return{dangerous:!0,reason:`Command may modify file outside project: ${r}`};return{dangerous:!1}}i(gp,"getBashOutsideProjectWriteRisk");function Tr(e,t,n){let r=WM(n);if(px(e))return null;if(Sn.has(e)){let o=typeof t.path=="string"?t.path:"";return o?lp(o,n)?null:`[Blocked] Plan mode only allows file modifications in ${r}. Requested path: ${o}`:`[Blocked] Tool '${e}' is not allowed in plan mode unless it targets ${r}.`}if(e==="bash"){let o=t.command??"";if(!Ln(o))return null;let s=_o(o);if(s.length===0)return`[Blocked] Plan mode only allows bash write operations when every target is either ${r}. Could not determine a safe target from: ${o.slice(0,80)}${o.length>80?"...":""}`;let a=s.find(c=>!lp(c,n));return a?`[Blocked] Plan mode only allows bash write operations in ${r}. Blocked target: ${a}`:null}return`[Blocked] Tool '${e}' has side effects and is not permitted in plan mode. Switch to accept-edits or auto mode to use it, or work within ${r}.`}i(Tr,"getPlanModeBlockReason");import Kr from"node:path";import KM from"node:os";function ts(e,t){try{let n=Kr.resolve(e),r=Kr.resolve(t);return n===r?!0:n.startsWith(r+Kr.sep)}catch{return!1}}i(ts,"isPathUnder");function VM(){try{return Si()}catch{return}}i(VM,"safeGetAgentConfigHome");function FS(e,t){let n=VM();if(n&&ts(e,n))return"user-kodax";let r=Kr.join(Kr.resolve(t),".kodax");if(ts(e,r))return"project-kodax"}i(FS,"resolveProtectedZone");function zM(){let e=new Set;try{e.add(KM.tmpdir())}catch{}for(let t of["TEMP","TMP","TMPDIR"]){let n=process.env[t];n&&n.length>0&&e.add(n)}return Array.from(e)}i(zM,"getSystemTempDirs");var XM=new Set(["bash"]),Da={toolNames:XM,collect(e,t){let n=typeof e.input.command=="string"?e.input.command:"";if(!n||!t)return[];let r=[],o=new Set,s=new Set,a=zM(),c=Kr.resolve(t);for(let l of ku(n)){let d;try{d=Kr.resolve(t,l)}catch{continue}let m=FS(d,t);if(m){o.has(d)||(o.add(d),r.push({kind:"protected_path",path:l,zone:m}));continue}if(Jn(l,t)){let p=a.some(x=>ts(d,x)),g=ts(d,c);!p&&!g&&!s.has(d)&&(s.add(d),r.push({kind:"outside_project",path:l}))}}for(let l of _o(n)){let d;try{d=Kr.resolve(t,l)}catch{continue}FS(d,t)||ts(d,c)||a.some(g=>ts(d,g))||r.push({kind:"shell_redirect_outside",target:l})}return r}};function Ha(e){return e.type==="tool_summary"?{type:"event",text:e.text,icon:"tool"}:e}i(Ha,"seedToHistoryItem");var YM="[Thinking]",qM="[/Thinking]",QM="Untitled Session",WS=50,JM=60,jS="...",GS=["[Managed Task]","[Managed Task Protocol Retry]","Assigned native agent identity:","Tool policy:","Blocked tools:","Allowed shell patterns:","Dependency handoff artifacts:","Dependency summary preview:","Preferred agent:","Read structured bundle first:","Read human summary next:"],KS=[/(?:^|\n)You are the [^\n]+ role for a managed KodaX task\./,/(?:^|\n)Primary task:/,/(?:^|\n)Work intent:/,/(?:^|\n)Complexity:/,/(?:^|\n)Risk:/,/(?:^|\n)Harness:/,/(?:^|\n)Brainstorm required:/],ZM=/(^|\r?\n)\[Thinking\]\r?\n([\s\S]*?)\r?\n\[\/Thinking\](?=\r?\n|$)/g;function eA(e){let t=-1;for(let n of GS){let r=e.indexOf(n);r>=0&&(t===-1||r<t)&&(t=r)}for(let n of KS){let r=n.exec(e);r&&r.index>=0&&(t===-1||r.index<t)&&(t=r.index)}return t}i(eA,"findControlPlaneCutIndex");function tA(e){return GS.some(t=>e.includes(t))||KS.some(t=>t.test(e))}i(tA,"hasControlPlaneSignal");function VS(e){let t=[];for(let n of e)n&&typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&t.push(String(n.text));return t}i(VS,"collectTextBlocks");function nA(e){return typeof e=="string"?e:Array.isArray(e)?VS(e).join(`
42
- `):""}i(nA,"extractAssistantTextOnly");function Ba(e,t,n){n.trim().length!==0&&e.push({type:t,text:n})}i(Ba,"pushSeed");function US(e){return e.replace(/^\n+/,"").replace(/\n+$/,"")}i(US,"stripLegacyTagBoundaryNewlines");function rA(e){let t=e.name,n=e.input;if(!n)return`\u26A1 ${t}`;let r=t==="bash"?Na(String(n.command??"")):t==="read"||t==="write"||t==="edit"?Na(String(n.file_path??n.path??"")):t==="grep"||t==="glob"?Na(String(n.pattern??"")):t==="web_search"||t==="web_fetch"?Na(String(n.query??n.url??"")):void 0;return r?`\u26A1 ${t}(${r})`:`\u26A1 ${t}`}i(rA,"formatToolUseSummary");function Na(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}...`:n}i(Na,"truncateToolHint");function oA(e){if(!e.includes(YM)||!e.includes(qM))return e.trim().length>0?[{type:"assistant",text:e}]:[];let t=[],n=0;for(let r of e.matchAll(ZM)){let o=r.index??-1,s=r[1]??"",a=r[2]??"";if(o<0)continue;let c=o+s.length;Ba(t,"assistant",US(e.slice(n,c))),Ba(t,"thinking",a),n=o+r[0].length}return Ba(t,"assistant",US(e.slice(n))),t.length===0?e.trim().length>0?[{type:"assistant",text:e}]:[]:t}i(oA,"parseLegacyAssistantContent");function iA(e){if(typeof e=="string")return oA(e);if(!Array.isArray(e))return[];let t=[],n=[],r=i(()=>{n.length!==0&&(Ba(t,"assistant",n.join(`
43
- `)),n.length=0)},"flushAssistantBuffer");for(let o of e)if(!(!o||typeof o!="object"||!("type"in o)))switch(o.type){case"text":"text"in o&&n.push(String(o.text));break;case"thinking":r(),"thinking"in o&&Ba(t,"thinking",String(o.thinking));break;case"tool_use":if(r(),"name"in o){let s=rA(o);s&&t.push({type:"tool_summary",text:s})}break;case"tool_result":case"redacted_thinking":break;default:break}return r(),t}i(iA,"extractAssistantHistorySeeds");var sA=["You are the Scout role","You are the Generator role","You are the Planner role","You are the Evaluator role"],aA=/\r?\n?\`\`\`kodax[\w-]*[\s\S]*?\`\`\`\s*/g;function cA(e){return sA.some(t=>e.includes(t))}i(cA,"isManagedWorkerPrompt");function lA(e){return e.replace(aA,"").trim()}i(lA,"stripManagedProtocolBlocks");function Fa(e){switch(e.role){case"assistant":return iA(e.content).map(n=>({...n,text:lA(n.text)})).filter(n=>n.text.length>0);case"user":{if(e._synthetic)return[];let t=Wa(e.content);return t.trim().length===0||cA(t)?[]:[{type:"user",text:t}]}case"system":return[];default:return[]}}i(Fa,"extractHistorySeedsFromMessage");function Wa(e){return typeof e=="string"?e:Array.isArray(e)?VS(e).join(`
44
- `):""}i(Wa,"extractTextContent");function uA(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>WS?`${t.slice(0,WS)}${jS}`:t:QM}i(uA,"formatSessionTitle");function Ua(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!=="assistant")continue;let r=nA(n.content);if(r)return r}return""}i(Ua,"extractLastAssistantText");function zS(e,t,n,r){let o=[Ua(e),t.trim(),n?.trim()??"",r?.trim()??""];for(let s of o){let a=Po(s);if(a)return a}return""}i(zS,"resolveCompletedAssistantText");function Po(e){let t=e.trim();if(!t)return"";let n=eA(t);return n===0?"":(n>0?t.slice(0,n):t).trim()}i(Po,"sanitizeUserFacingAssistantText");function XS(e){let t=e.trim();return t.length>0&&Po(t).length===0&&tA(t)}i(XS,"isControlPlaneOnlyAssistantText");function ns(e){let t=e.find(r=>r.role==="user"),n=t?Wa(t.content):"";return uA(n)}i(ns,"extractTitle");function dA(e,t=JM){let n=e.replace(/\n/g," "),r=n.length>t?jS:"";return n.slice(0,t)+r}i(dA,"formatMessagePreview");import u from"chalk";import Eu from"fs";import qS from"path";var Mu=gn("config.json");function QS(){return qS.join(process.cwd(),".kodax","config.local.json")}i(QS,"getProjectConfigFile");function Au(e=process.env){let n=ja(Mu).autoMode??{},r=e.KODAX_AUTO_MODE_ENGINE?.trim(),o=r==="llm"||r==="rules"?r:void 0,s=n.engine==="llm"||n.engine==="rules"?n.engine:void 0,a=o??s??"llm",c=YS(n.classifierModel),l=YS(e.KODAX_AUTO_MODE_CLASSIFIER_MODEL),d=e.KODAX_AUTO_MODE_TIMEOUT_MS?.trim(),m=d!==void 0?Number(d):NaN,p=Number.isFinite(m)&&m>0?Math.floor(m):void 0,g=typeof n.timeoutMs=="number"&&n.timeoutMs>0?Math.floor(n.timeoutMs):void 0;return{engine:a,classifierModel:c,classifierModelEnv:l,timeoutMs:p??g}}i(Au,"loadAutoModeSettings");function YS(e){if(typeof e!="string")return;let t=e.trim();return t.length===0?void 0:t}i(YS,"nonEmptyString");function ja(e){try{if(Eu.existsSync(e))return JSON.parse(Eu.readFileSync(e,"utf-8"))}catch{}return{}}i(ja,"readJsonFile");function JS(e,t){Eu.mkdirSync(qS.dirname(e),{recursive:!0}),Eu.writeFileSync(e,JSON.stringify(t,null,2))}i(JS,"writeJsonFile");function Ga(e){let t=ja(Mu);JS(Mu,{...t,permissionMode:e})}i(Ga,"savePermissionModeUser");function rs(){let e=ja(Mu),t=ja(QS()),n=e.alwaysAllowTools??[],r=t.alwaysAllowTools??[];return[...new Set([...n,...r])]}i(rs,"loadAlwaysAllowTools");function _u(e,t,n=!1){let r=Iu(e,t,n);if(!r)return;let o=QS(),s=ja(o),a=s.alwaysAllowTools??[];a.includes(r)||JS(o,{...s,alwaysAllowTools:[...a,r]})}i(_u,"saveAlwaysAllowToolPattern");var os=class{static{i(this,"CommandRegistry")}commands=new Map;aliases=new Map;register(t){let n=t.name.toLowerCase();if(this.commands.has(n))throw new Error(`Command "${t.name}" is already registered`);if(this.aliases.has(n)){let o=this.aliases.get(n);throw new Error(`Command "${t.name}" conflicts with existing alias for "${o}"`)}let r=new Set;for(let o of t.aliases??[]){let s=o.toLowerCase();if(s!==n){if(r.has(s))throw new Error(`Alias "${o}" is duplicated within command "${t.name}"`);if(this.commands.has(s))throw new Error(`Alias "${o}" conflicts with existing command "${s}"`);if(this.aliases.has(s)){let a=this.aliases.get(s);throw new Error(`Alias "${o}" is already registered for "${a}"`)}r.add(s)}}if(this.commands.set(n,{...t,source:t.source??"builtin"}),t.aliases)for(let o of t.aliases){let s=o.toLowerCase();s!==n&&this.aliases.set(s,n)}}unregister(t){let n=t.toLowerCase(),r=this.aliases.get(n)??n;if(!this.commands.has(r))return!1;let o=this.commands.get(r);if(o?.aliases)for(let s of o.aliases)this.aliases.delete(s.toLowerCase());return this.commands.delete(r),!0}get(t){let n=t.toLowerCase(),r=this.aliases.get(n)??n;return this.commands.get(r)}has(t){let n=t.toLowerCase(),r=this.aliases.get(n)??n;return this.commands.has(r)}getAll(t){let n=new Map;for(let[r,o]of this.commands)t&&o.source!==t||n.has(r)||n.set(r,{name:o.name,aliases:o.aliases,description:o.description,source:o.source??"builtin",usage:o.usage,priority:o.priority,location:o.location,path:o.path,userInvocable:o.userInvocable,disableModelInvocation:o.disableModelInvocation,allowedTools:o.allowedTools,context:o.context,agent:o.agent,argumentHint:o.argumentHint,model:o.model});return Array.from(n.values()).sort((r,o)=>r.name.localeCompare(o.name))}getBySource(t){return this.getAll(t)}getNames(){return Array.from(this.commands.keys()).sort()}clear(){this.commands.clear(),this.aliases.clear()}get size(){return this.commands.size}get aliasCount(){return this.aliases.size}},fA=new os;import Tn from"chalk";import{Buffer as nT}from"node:buffer";import{spawn as mA}from"node:child_process";import ZS from"node:process";var $o="\x1B",pA="\x07",hp=`${$o}\\`;function eT(e,t){return e.SSH_CONNECTION?!1:t==="win32"||t==="darwin"||t==="linux"}i(eT,"shouldPreferNativeClipboard");function gA(e,t){let n=nT.from(e,"utf8").toString("base64"),r=t.TERM==="xterm-kitty"?hp:pA,o=`${$o}]52;c;${n}${r}`;return t.TMUX?`${$o}Ptmux;${o.replaceAll($o,`${$o}${$o}`)}${hp}`:t.STY?`${$o}P${o}${hp}`:o}i(gA,"buildOscSequence");async function Pu(e,t,n){return new Promise((r,o)=>{let s=mA(e,t,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),a="";s.on("error",o),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("close",c=>{if(c===0){r(!0);return}o(new Error(a.trim()||`${e} exited with code ${c??"unknown"}`))}),s.stdin?.write(n),s.stdin?.end()})}i(Pu,"execClipboardCommand");function hA(e){let t="$stream = [Console]::OpenStandardInput(); $buffer = New-Object byte[] 8192; $memory = New-Object System.IO.MemoryStream; while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { $memory.Write($buffer, 0, $read) }; $text = [System.Text.Encoding]::UTF8.GetString($memory.ToArray()); Set-Clipboard -Value $text",n=nT.from(e,"utf8");return[["powershell",["-NoProfile","-NonInteractive","-Command",t],n],["pwsh",["-NoProfile","-NonInteractive","-Command",t],n],["cmd",["/c","chcp 65001 >nul & clip"],n]]}i(hA,"buildWindowsClipboardCandidates");async function tT(e,t,n){if(t.SSH_CONNECTION)return!1;switch(n){case"win32":{let r=hA(e);for(let[o,s,a]of r)try{if(await Pu(o,s,a))return!0}catch{}return!1}case"darwin":return Pu("pbcopy",[],e);case"linux":{let r=[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]];for(let[o,s]of r)try{if(await Pu(o,s,e))return!0}catch{}return!1}default:return!1}}i(tT,"tryNativeClipboard");async function yA(e,t){if(!t.TMUX)return!1;let n=t.LC_TERMINAL==="iTerm2"?["load-buffer","-"]:["load-buffer","-w","-"];try{return await Pu("tmux",n,e)}catch{return!1}}i(yA,"tryTmuxClipboard");async function Lo(e,t={}){let n=t.env??ZS.env,r=t.platform??ZS.platform,o=e.trimEnd(),s=gA(o,n);if(!o)throw new Error("Nothing to copy.");if(eT(n,r))try{if(await tT(o,n,r))return{path:"native"}}catch{}if(await yA(o,n))return{path:"tmux-buffer"};if(t.terminalWrite?.(s))return{path:"osc52"};if(!eT(n,r))try{if(await tT(o,n,r))return{path:"native"}}catch{}throw new Error("Unable to access any clipboard path.")}i(Lo,"copyTextToClipboard");var yp={name:"copy",description:"Copy last assistant message to clipboard",usage:"/copy",handler:i(async(e,t)=>{let n=Ua(t.messages);if(!n){console.log(Tn.yellow(`
45
- No assistant message found to copy.`)),console.log(Tn.dim("The assistant needs to respond first before you can copy its message."));return}try{await Lo(n);let r=n.length>50?n.slice(0,50)+"...":n;console.log(Tn.green(`
46
- Copied to clipboard!`)),console.log(Tn.dim(`Preview: ${r}`))}catch(r){let o=r instanceof Error?r.message:String(r);console.log(Tn.red(`
47
- Failed to copy to clipboard: ${o}`)),console.log(Tn.dim("You may need to check clipboard permissions or manually copy the message."))}},"handler"),detailedHelp:i(()=>{console.log(Tn.bold(`
48
- /copy - Copy Last Assistant Message
49
- `)),console.log("Usage:"),console.log(Tn.cyan(" /copy")+` - Copy the last assistant message to clipboard
50
- `),console.log("Description:"),console.log(" This command copies the most recent assistant response to your system clipboard."),console.log(` Useful for quickly sharing or saving AI responses.
51
- `),console.log("Examples:"),console.log(Tn.dim(" User: Explain how async/await works")),console.log(Tn.dim(" AI: [responds with explanation]")),console.log(Tn.cyan(" /copy")+Tn.dim(` - Copies the explanation to clipboard
52
- `)),console.log("Notes:"),console.log(" - Only copies assistant messages, not user messages"),console.log(" - Works with both plain text and formatted responses"),console.log(" - Requires clipboard permissions on some systems")},"detailedHelp")};import*as Zn from"node:fs";import*as $u from"node:path";import we from"chalk";function xA(e){return e.runtimeInfo?.workspaceRoot??e.runtimeInfo?.executionCwd??process.cwd()}i(xA,"resolveCwd");function oT(e){let t;try{t=Zn.readdirSync(e,{withFileTypes:!0})}catch(r){return r.code!=="ENOENT"&&console.error(`[memory] failed to read memory directory ${e}:`,r),[]}let n=[];for(let r of t){if(!r.isFile()||!r.name.endsWith(".md")||r.name==="MEMORY.md")continue;let o=$u.join(e,r.name),s="",a=0;try{s=Zn.readFileSync(o,"utf-8"),a=Zn.statSync(o).mtimeMs}catch(p){console.error(`[memory] failed to read ${o}:`,p);continue}let l=Jy(s).frontmatter,d=l.name!==void 0||l.description!==void 0||l.type!==void 0,m=$u.basename(r.name,".md");n.push({filename:r.name,absPath:o,mtimeMs:a,title:l.name?.trim()||m,description:l.description?.trim()||m,type:l.type,parseOk:d})}return n}i(oT,"readTopicFiles");function wA(e){return e.map(t=>`- [${t.title}](${t.filename}) \u2014 ${t.description}`)}i(wA,"buildIndexLines");async function SA(e,t){console.log(we.cyan(`
53
- [memory] per-project memory directory`)),console.log(we.dim(` ${e}`));let n=oT(e),r=n.filter(a=>!a.parseOk);console.log(we.dim(` ${n.length} topic file${n.length===1?"":"s"}`+(r.length>0?`, ${r.length} without parsable frontmatter`:"")));let o=!1,s="";try{s=Zn.readFileSync(t,"utf-8"),o=!0}catch{o=!1}if(!o){console.log(we.yellow(`
54
- MEMORY.md does not exist yet.`)),n.length>0?console.log(we.dim(" Run `/memory rebuild` to seed it from existing topic files.")):console.log(we.dim(" The LLM will create it on first save \u2014 no action needed.")),console.log();return}console.log(we.cyan(`
55
- --- MEMORY.md ---`)),s.trim().length===0?console.log(we.dim(" (empty)")):console.log(s.trimEnd()),console.log(we.cyan(`--- end ---
56
- `))}i(SA,"listMemory");async function TA(e,t){let n=!1;try{n=Zn.statSync(e).isDirectory()}catch{n=!1}if(!n){console.log(we.yellow(`
57
- [memory] memory directory does not exist yet \u2014 nothing to rebuild.`)),console.log(we.dim(` ${e}`)),console.log(we.dim(` The LLM will create both the directory and MEMORY.md on first save.
58
- `));return}let r=oT(e);if(r.length===0){console.log(we.yellow(`
59
- [memory] no topic files found \u2014 nothing to rebuild.`)),console.log(we.dim(` ${e}
60
- `));return}let o=[...r].sort((l,d)=>d.mtimeMs-l.mtimeMs),a=wA(o).join(`
61
- `)+`
62
- `;Zn.writeFileSync(t,a,"utf-8"),console.log(we.green(`
63
- [memory] rebuilt MEMORY.md with ${o.length} entries (newest first).`)),console.log(we.dim(` ${t}`));let c=o.filter(l=>!l.parseOk);if(c.length>0){console.log(we.yellow(` ${c.length} file(s) had no parsable frontmatter \u2014 used filename as fallback:`));for(let l of c)console.log(we.dim(` - ${l.filename}`));console.log(we.dim(" Tip: add `---\\nname: ...\\ndescription: ...\\ntype: ...\\n---` at the top of those files."))}console.log()}i(TA,"rebuildMemory");function CA(e,t){console.log(we.cyan(`
64
- [memory] open these paths in your editor:`)),console.log(we.dim(" index :"),t),console.log(we.dim(" dir :"),e),console.log(we.dim(`
65
- (No in-REPL editor is provided \u2014 open the file in your usual editor.
66
- Use \`/memory rebuild\` after manual edits if you renamed any topic file.)
67
- `))}i(CA,"openMemory");function rT(){console.log(we.cyan(`
68
- /memory - Inspect or rebuild per-project memory`)),console.log(we.dim(" /memory List MEMORY.md + memory directory")),console.log(we.dim(" /memory list Same as `/memory`")),console.log(we.dim(" /memory rebuild Regenerate MEMORY.md from topic frontmatter")),console.log(we.dim(" /memory open Print paths so you can open them in your editor")),console.log(we.dim(" /memory help Show this help")),console.log()}i(rT,"printHelp");function bA(){console.log(we.bold(`
69
- /memory - Inspect or rebuild project memory
70
- `)),console.log("Usage:"),console.log(we.cyan(" /memory ")+we.dim("Show MEMORY.md + topic file count")),console.log(we.cyan(" /memory list ")+we.dim("Alias for `/memory`")),console.log(we.cyan(" /memory rebuild ")+we.dim("Regenerate MEMORY.md (newest first by mtime)")),console.log(we.cyan(" /memory open ")+we.dim("Print the index + dir paths for editor use")),console.log(we.cyan(" /memory help ")+we.dim(`Show this help
71
- `)),console.log("Description:"),console.log(we.dim(` Each project gets its own memory directory under your KodaX agent
72
- home \u2014 \`<agentConfigHome>/projects/<project-key>/memory/\`. The LLM
73
- owns reads/writes; this command is your escape hatch when the
74
- MEMORY.md index drifts from the topic files on disk.
75
- `)),console.log("Notes:"),console.log(we.dim(" \u2022 Rebuild ONLY rewrites MEMORY.md. Topic files are never touched.")),console.log(we.dim(" \u2022 Rebuild sorts entries by file mtime descending \u2014 the same")),console.log(we.dim(" natural-LRU order the LLM produces by prepending new entries.")),console.log(we.dim(" \u2022 Files missing or with malformed frontmatter still appear in")),console.log(we.dim(" the rebuilt index using their filename as fallback; the command")),console.log(we.dim(` prints a warning so you can fix the frontmatter.
76
- `))}i(bA,"printDetailedHelp");var xp={name:"memory",description:"Inspect or rebuild per-project memory (FEATURE_124)",usage:"/memory [list|rebuild|open|help]",argumentHint:"list | rebuild | open | help",handler:i(async(e,t)=>{let n=xA(t),r=Xy(n),o=Yy(n),s=(e[0]??"list").toLowerCase();if(s==="help"||s==="--help"||s==="-h"){rT();return}if(s==="list"){await SA(r,o);return}if(s==="rebuild"){await TA(r,o);return}if(s==="open"){CA(r,o);return}console.log(we.yellow(`
77
- [memory] unknown subcommand: ${s}`)),rT()},"handler"),detailedHelp:bA};import jt from"chalk";var wp={name:"new",description:"Start a new conversation session",usage:"/new",handler:i(async(e,t,n)=>{if(t.messages.length===0){console.log(jt.yellow(`
78
- Current session is already empty.`)),console.log(jt.dim("You can start a new conversation directly."));return}if(n.confirm&&!await n.confirm("Start a new session? This will clear the current conversation history.")){console.log(jt.dim(`
79
- Cancelled. Current session preserved.`));return}try{await n.saveSession(),console.log(jt.dim(`
80
- [Previous session saved]`))}catch{console.log(jt.yellow(`
81
- [Warning: Failed to save previous session]`))}n.startNewSession?.(),t.messages=[],n.clearHistory(),console.log(jt.green(`
82
- \u2713 Started new session`)),console.log(jt.dim("Conversation history cleared. Ready for a fresh start!"))},"handler"),detailedHelp:i(()=>{console.log(jt.bold(`
83
- /new - Start New Session
84
- `)),console.log("Usage:"),console.log(jt.cyan(" /new")+` - Clear current session and start fresh
85
- `),console.log("Description:"),console.log(" This command clears the current conversation history and starts a new session."),console.log(" It automatically saves the previous session before clearing."),console.log(` Useful for switching contexts or starting a new topic.
86
- `),console.log("Examples:"),console.log(jt.dim(" User: Help me refactor the authentication module")),console.log(jt.dim(" AI: [provides refactoring help]")),console.log(jt.cyan(" /new")),console.log(jt.dim(" \u2713 Started new session")),console.log(jt.dim(" User: Now I need help with database optimization")),console.log(jt.dim(` AI: [provides database help]
87
- `)),console.log("Notes:"),console.log(" \u2022 Automatically saves previous session before clearing"),console.log(" \u2022 Prompts for confirmation if there are messages in the current session"),console.log(" \u2022 Use /load to resume a previous session"),console.log(" \u2022 Use /sessions to see all saved sessions")},"detailedHelp")};function Ou(e){let t=e.match(/\r\n|\r|\n/g);return t?t.length:0}i(Ou,"getPastedTextRefNumLines");function vA(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}i(vA,"formatPastedTextRef");function IA(e,t){return`[...Truncated text #${e} +${t} lines...]`}i(IA,"formatTruncatedTextRef");var kA=/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/g;function RA(e){let t=[],n=new RegExp(kA.source,"g");for(let r of e.matchAll(n)){let o=Number.parseInt(r[2]??"0",10);!Number.isFinite(o)||o<=0||t.push({id:o,kind:r[1],match:r[0],index:r.index??0})}return t}i(RA,"parseReferences");function EA(e,t){let n=RA(e);if(n.length===0)return e;let r=i(s=>t instanceof Map?t.get(s):t[s],"getContent"),o=e;for(let s=n.length-1;s>=0;s--){let a=n[s];if(a.kind==="Image")continue;let c=r(a.id);!c||c.type!=="text"||(o=o.slice(0,a.index)+c.content+o.slice(a.index+a.match.length))}return o}i(EA,"expandPastedTextRefs");var MA=/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]$/,AA=/^\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/;function _A(e,t){if(t>=e.length)return!0;let n=e[t];return!n||/\s/.test(n)}i(_A,"isAtWordBoundaryAfter");function PA(e,t){if(t===0)return!0;let n=e[t-1];return!n||/\s/.test(n)}i(PA,"isAtWordBoundaryBefore");function Du(e,t){if(t<=0||!_A(e,t))return null;let r=e.slice(0,t).match(MA);if(!r)return null;let o=t-r[0].length,s=Number.parseInt(r[2]??"0",10);return!Number.isFinite(s)||s<=0?null:{start:o,end:t,id:s,kind:r[1]}}i(Du,"findPlaceholderBeforeCursor");function Nu(e,t){if(t>=e.length||!PA(e,t))return null;let r=e.slice(t).match(AA);if(!r)return null;let o=Number.parseInt(r[2]??"0",10);return!Number.isFinite(o)||o<=0?null:{start:t,end:t+r[0].length,id:o,kind:r[1]}}i(Nu,"findPlaceholderAfterCursor");function iT(e){return e.length>800||Ou(e)>2}i(iT,"shouldReplacePasteWithPlaceholder");function sT(e,t){if(e.length<=1e4)return{truncatedText:e,placeholderContent:""};let n=Math.floor(1e3/2),r=Math.floor(1e3/2),o=e.slice(0,n),s=e.slice(-r),a=e.slice(n,-r),c=Ou(a),l=IA(t,c);return{truncatedText:o+l+s,placeholderContent:a}}i(sT,"maybeTruncateLongInput");var Sp=class{static{i(this,"PasteStore")}contents=new Map;nextId=1;registerText(t){let n=this.nextId++,r=Ou(t);return this.contents.set(n,{id:n,type:"text",content:t}),{id:n,placeholder:vA(n,r),numLines:r}}registerTruncatedText(t){let n=this.nextId++,r=Ou(t);return this.contents.set(n,{id:n,type:"text",content:t}),{id:n,numLines:r}}adopt(t){this.contents.set(t.id,t),t.id>=this.nextId&&(this.nextId=t.id+1)}peekNextId(){return this.nextId}get(t){return this.contents.get(t)}expand(t){return EA(t,this.contents)}snapshot(){return new Map(this.contents)}restore(t){this.contents.clear();for(let[n,r]of t)this.contents.set(n,r);for(let n of t.keys())n>=this.nextId&&(this.nextId=n+1)}reset(){this.contents.clear(),this.nextId=1}size(){return this.contents.size}export(){return Array.from(this.contents.values())}},Lu=null;function aT(){return Lu===null&&(Lu=new Sp),Lu}i(aT,"getOrCreateModulePasteStore");function Bu(){return Lu??void 0}i(Bu,"getActivePasteStore");import{createHash as $A}from"node:crypto";import{mkdir as LA,readdir as OA,readFile as DA,stat as NA,unlink as BA,writeFile as HA}from"node:fs/promises";import*as Tp from"node:path";var FA="paste-cache",WA=720*60*60*1e3;function Cp(){return gn(FA)}i(Cp,"getPasteCacheDir");function cT(e){return Tp.join(Cp(),`${e}.txt`)}i(cT,"getPastePath");function lT(e){return $A("sha256").update(e).digest("hex").slice(0,16)}i(lT,"hashPastedText");async function uT(e,t){try{let n=Cp();return await LA(n,{recursive:!0}),await HA(cT(e),t,{encoding:"utf8",mode:384}),!0}catch{return!1}}i(uT,"storePastedText");async function Hu(e){try{return await DA(cT(e),{encoding:"utf8"})}catch{return null}}i(Hu,"retrievePastedText");async function dT(e=WA){let t=Cp(),n=Date.now()-e,r=0,o=0,s;try{s=await OA(t)}catch{return{scanned:r,removed:o}}for(let a of s){if(!a.endsWith(".txt"))continue;r+=1;let c=Tp.join(t,a);try{(await NA(c)).mtimeMs<n&&(await BA(c),o+=1)}catch{}}return{scanned:r,removed:o}}i(dT,"cleanupOldPastes");import*as Ep from"path";import*as fT from"os";function UA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(UA,"escapeRegExp");function jA(e,t){if(!e)return;let n=e.trim();if(!n.startsWith("/"))return;let r=new RegExp(`^/${UA(t)}(?:\\s+)?`,"i"),o=n.replace(r,"").trim();return o.length>0?o:void 0}i(jA,"deriveArgumentHintFromUsage");function bp(e,t="builtin"){return{...e,source:e.source??t,userInvocable:e.userInvocable??!0,disableModelInvocation:e.disableModelInvocation??!1,argumentHint:e.argumentHint??jA(e.usage,e.name)}}i(bp,"toCommandDefinition");function vp(e){for(let t of Ip)try{let n=bp(t,"builtin");e.register(n)}catch(n){console.error(`Failed to register command "${t.name}":`,n)}}i(vp,"registerBuiltinCommands");import*as Cr from"fs";import*as Oo from"path";function GA(e){if(Array.isArray(e))return e.map(t=>String(t).trim()).filter(t=>t.length>0);if(typeof e=="string")return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}i(GA,"normalizeAliases");function KA(e){if(e==="critical"||e==="high"||e==="medium"||e==="low")return e}i(KA,"normalizePriority");function VA(e){return{disableModelInvocation:e["disable-model-invocation"]===!0,userInvocable:e["user-invocable"]!==!1,allowedTools:ex(e["allowed-tools"]),context:e.context==="fork"?"fork":void 0,agent:typeof e.agent=="string"?e.agent:void 0,argumentHint:typeof e["argument-hint"]=="string"?e["argument-hint"]:void 0,model:typeof e.model=="string"?e.model:void 0,hooks:tx(e.hooks),frontmatter:e}}i(VA,"buildExecutionMetadata");function zA(e,t){try{let n=Cr.readFileSync(e,"utf-8"),[r,o]=Zy(n),s=r??{},a=Oo.basename(e,".md"),c=typeof s.name=="string"&&s.name.trim()?s.name.trim():a;if(!c||o.trim().length===0)return;let l=typeof s.description=="string"&&s.description.trim()?s.description.trim():`Custom command from ${t} level`;return{name:c,description:l,aliases:GA(s.aliases),priority:KA(s.priority),content:o.trim(),location:t,path:e,frontmatter:s,execution:VA(s)}}catch(n){console.error(`Error parsing command file ${e}:`,n);return}}i(zA,"parseCommandFile");function kp(e){let t=[],n=new Set;for(let r=0;r<e.length;r++){let o=e[r],s=typeof o=="string"?o:o.path,a=typeof o=="string"?r===0?"user":"project":o.location;if(!Cr.existsSync(s))continue;let c=Oo.resolve(s);try{c=Cr.realpathSync.native?.(s)??Cr.realpathSync(s)}catch{c=Oo.resolve(s)}if(!n.has(c)){n.add(c);try{let l=Cr.readdirSync(s);for(let d of l){if(!d.endsWith(".md"))continue;let m=Oo.join(s,d),p=zA(m,a);p&&t.push(p)}}catch(l){console.error(`Error scanning directory ${s}:`,l)}}}return t}i(kp,"discoverCommands");function Rp(e,t){for(let n of e)try{t.register({name:n.name,aliases:n.aliases,description:n.description,source:"extension",priority:n.priority,location:n.location,path:n.path,userInvocable:n.execution.userInvocable,disableModelInvocation:n.execution.disableModelInvocation,allowedTools:n.execution.allowedTools,context:n.execution.context,agent:n.execution.agent,argumentHint:n.execution.argumentHint,model:n.execution.model,hooks:n.execution.hooks,frontmatter:n.frontmatter,handler:i(async()=>({success:!0,invocation:{...n.execution,prompt:n.content,source:"prompt",displayName:n.name,path:n.path}}),"handler")})}catch(r){console.error(`Error registering command ${n.name}:`,r)}}i(Rp,"registerDiscoveredCommands");function mT(e,t){vp(e);try{let n=fT.homedir(),r=t??process.cwd(),o=kp([{path:Ep.join(r,".kodax","commands"),location:"project"},{path:gn("commands"),location:"user"},{path:Ep.join(n,".agents","commands"),location:"user"}]);Rp(o,e)}catch(n){console.error("Failed to discover commands:",n)}}i(mT,"registerAllCommands");import{execFile as XA}from"child_process";import YA from"fs";import Mp from"path";import{promisify as qA}from"util";var QA=qA(XA);function Vr(e){if(!(!e||!e.trim()))return Mp.resolve(e).replace(/\\/g,"/")}i(Vr,"normalizePath");async function Ka(e,t){try{let{stdout:n}=await QA("git",t,{cwd:e,windowsHide:!0,maxBuffer:1048576}),r=n.trim();return r||void 0}catch{return}}i(Ka,"gitStdout");function JA(e){let t=Vr(e);if(t)return Mp.posix.basename(t)===".git"?Mp.posix.dirname(t):t}i(JA,"deriveCanonicalRepoRoot");async function is(e={}){let t=Vr(e.cwd??process.cwd())??process.cwd().replace(/\\/g,"/"),n=Vr(await Ka(t,["rev-parse","--show-toplevel"])),r=await Ka(n??t,["rev-parse","--path-format=absolute","--git-common-dir"])??await Ka(n??t,["rev-parse","--git-common-dir"]),o=await Ka(n??t,["branch","--show-current"])??await Ka(n??t,["rev-parse","--abbrev-ref","HEAD"]);return{canonicalRepoRoot:JA(r)??n,workspaceRoot:n,executionCwd:t,branch:o&&o!=="HEAD"?o:void 0,workspaceKind:e.workspaceKind??"detected"}}i(is,"inspectWorkspaceRuntime");function Fu(e,t){return!e?.canonicalRepoRoot||!t?.canonicalRepoRoot?!1:Vr(e.canonicalRepoRoot)===Vr(t.canonicalRepoRoot)}i(Fu,"isSameCanonicalRepo");function pT(e){return!!(e?.workspaceRoot&&YA.existsSync(e.workspaceRoot))}i(pT,"workspaceExists");function Va(e){let t=Vr(e.runtimeInfo?.workspaceRoot??e.gitRoot),n=Vr(e.runtimeInfo?.executionCwd??t),r=Vr(e.runtimeInfo?.canonicalRepoRoot??t);if(!(!t&&!n&&!r))return{canonicalRepoRoot:r,workspaceRoot:t,executionCwd:n,branch:e.runtimeInfo?.branch,workspaceKind:e.runtimeInfo?.workspaceKind??"detected"}}i(Va,"resolveSessionRuntimeInfo");function Cn(e){if(!e?.workspaceRoot)return"No git workspace detected";let t=e.branch?` @ ${e.branch}`:"",n=e.workspaceKind??"detected";return`${e.workspaceRoot}${t} [${n}]`}i(Cn,"formatWorkspaceTruth");function ZA(e){return{global:e.filter(t=>t.scope==="global").length,directory:e.filter(t=>t.scope==="directory").length,project:e.filter(t=>t.scope==="project").length}}i(ZA,"summarizeAgentsFiles");function e_(e,t,n){if(!Number.isFinite(t)||t<=0||n<=0)return{...e,enabled:!0};let r=t/n*100,o=Math.max(1,Math.ceil(r)-1);return{...e,enabled:!0,triggerPercent:Math.min(e.triggerPercent,o)}}i(e_,"createManualCompactionConfig");function Ap(e){e.runtimeInfo?.workspaceRoot?console.log(u.dim(` Workspace unchanged: ${Cn(e.runtimeInfo)}`)):console.log(u.dim(" Workspace unchanged."))}i(Ap,"printWorkspaceUnchangedNote");var Ip=[{name:"help",aliases:["h","?"],description:"Show all available commands",usage:"/help [command]",handler:i(async e=>{e.length>0?d_(e[0]):u_()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
88
- /help - Show Command Help
89
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /help ")+"Show all available commands"),console.log(u.dim(" /help <command> ")+"Show detailed help for a specific command"),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /help ")+"# List all commands"),console.log(u.dim(" /help mode ")+"# Detailed help for /mode"),console.log()},"detailedHelp")},{name:"exit",aliases:["quit","q","bye"],description:"Exit interactive mode",handler:i(async(e,t,n)=>{await n.saveSession(),console.log(u.green(`
90
- Session saved. Goodbye!`)),await n.exit()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
91
- /exit - Exit Interactive Mode
92
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /exit ")+"Save session and exit"),console.log(u.dim(" /quit, /q, /bye ")+"Aliases for /exit"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Saves the current conversation session and exits interactive mode.")),console.log(u.dim(" Sessions can be resumed later with /load or CLI -c option.")),console.log(u.dim(" Exiting never removes or mutates the current workspace.")),console.log()},"detailedHelp")},{name:"clear",description:"Clear conversation history",handler:i(async(e,t,n)=>{t.messages=[],t.contextTokenSnapshot=void 0,n.clearHistory(),console.log(u.yellow(`
93
- [Conversation cleared]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
94
- /clear - Clear Conversation History
95
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /clear ")+"Clear all messages in current session"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Removes all messages from the current conversation context.")),console.log(u.dim(" Useful for starting fresh while keeping the session.")),console.log(),console.log(u.yellow(" Warning: This action cannot be undone!")),console.log()},"detailedHelp")},{name:"cost",description:"Show session cost report",usage:"/cost",handler:i(async(e,t,n)=>{let r=n.getCostReport?.();if(!r){console.log(u.dim(`
96
- [No cost data available yet]`));return}console.log(u.cyan(`
97
- `+r))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
98
- /cost - Session Cost Report
99
- `)),console.log(u.bold("Description:")),console.log(u.dim(" Shows token usage and estimated cost for the current session,")),console.log(u.dim(" broken down by provider and AMA role.")),console.log()},"detailedHelp")},{name:"paste",description:"Inspect pasted text stored in the input buffer",usage:"/paste show <id> | /paste list",argumentHint:"show <id> | list",handler:i(async e=>{let t=e[0]?.toLowerCase();if(!t||t==="help"){console.log(u.cyan(`
100
- /paste - Inspect stored paste contents`)),console.log(u.dim(" /paste list - Show all pasted text ids in this session")),console.log(u.dim(" /paste show <id> - Print the full content of paste #<id>")),console.log();return}let n=Bu();if(!n){console.log(u.yellow(`
101
- [No paste registry active]`)),console.log(u.dim(" The REPL composer is not mounted, or no paste has been captured yet."));return}if(t==="list"){let r=n.export();if(r.length===0){console.log(u.dim(`
102
- [No pasted content in this session yet]`));return}console.log(u.bold(`
103
- Pasted content in this session:
104
- `));for(let o of r){let s=o.content?.length??0,a=o.contentHash?` (hash ${o.contentHash.slice(0,8)})`:"";console.log(` ${u.cyan(`#${o.id}`)} ${o.type} ${s} chars${a}`)}console.log();return}if(t==="show"){let r=e[1],o=r?Number.parseInt(r,10):NaN;if(!Number.isFinite(o)||o<=0){console.log(u.yellow(`
105
- Usage: /paste show <id>`));return}let s=n.get(o);if(!s){console.log(u.dim(`
106
- [No paste registered with id #${o}]`));return}let a=s.content??"";if(!a&&s.contentHash){let c=await Hu(s.contentHash);c&&(a=c)}if(!a){console.log(u.yellow(`
107
- [Paste #${o} has no stored content (hash ${s.contentHash??"n/a"})]`));return}console.log(u.bold(`
108
- Pasted text #${o} (${a.length} chars):
109
- `)),console.log(a),console.log();return}console.log(u.yellow(`
110
- [Unknown /paste subcommand: ${t}]`)),console.log(u.dim(" Try /paste show <id> or /paste list"))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
111
- /paste - Inspect stored paste contents
112
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /paste list - Show all pasted text ids in this session")),console.log(u.dim(" /paste show <id> - Print the full content of paste #<id>")),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" When you paste more than ~800 chars into the input bar, KodaX")),console.log(u.dim(" replaces the pasted text with a `[Pasted text #N +K lines]` anchor")),console.log(u.dim(" to keep the UI responsive. The full content is preserved and sent")),console.log(u.dim(" to the LLM on submit. Use this command to see what was captured.")),console.log()},"detailedHelp")},{name:"compact",description:"Manually trigger context compaction",usage:"/compact [instructions]",handler:i(async(e,t,n,r)=>{try{let o=await Ol(t.gitRoot),s=r.provider,a=po(s);if(!a){console.log(u.red(`
113
- [Provider not found: ${s}]`));return}let c=e.length>0?e.join(" "):void 0,l=o.contextWindow??a.getEffectiveContextWindow?.(r.model)??a.getContextWindow?.()??2e5,d=t.contextTokenSnapshot?.currentTokens??go(t.messages),m=e_(o,d,l);console.log(u.dim(`
114
- [Compacting conversation...]`)),n.startCompacting?.();try{let p=await ix(t.messages,m,a,l,c,void 0,d,hx,yx);if(!p.compacted){console.log(u.green(`
115
- [No compaction needed]`)),console.log(u.dim(`Current token usage: ${p.tokensBefore.toLocaleString()}
116
- `));return}t.messages=p.messages,t.contextTokenSnapshot={currentTokens:p.tokensAfter,baselineEstimatedTokens:p.tokensAfter,source:"estimate"},n.onCompactStats?.({tokensBefore:p.tokensBefore,tokensAfter:p.tokensAfter}),n.clearHistory?.(),await n.saveSession(),console.log(u.green(`
117
- [Compaction complete: ${Math.round(p.tokensBefore/1e3)}k -> ${Math.round(p.tokensAfter/1e3)}k tokens, ${Math.round((1-p.tokensAfter/p.tokensBefore)*100)}% reduced]`)),console.log()}finally{n.stopCompacting?.()}}catch(o){let s=o instanceof Error?o.message:String(o);console.log(u.red(`
118
- [Compaction failed: ${s}]
119
- `))}},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
120
- /compact - Manual Context Compaction
121
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /compact ")+"Compact conversation with default instructions"),console.log(u.dim(" /compact <text> ")+"Compact with custom instructions for the summary"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Manually triggers context compaction using LLM-generated summaries.")),console.log(u.dim(" Older messages are replaced with a structured summary, keeping recent context.")),console.log(u.dim(" /compact still works even if auto-compaction is disabled or the auto threshold is not reached.")),console.log(),console.log(u.bold("What it does:")),console.log(u.dim(" 1. Protects a recent slice of context from pruning/summary")),console.log(u.dim(" 2. Generates structured summary of older messages using LLM")),console.log(u.dim(" 3. Tracks files that were read/modified in the conversation")),console.log(u.dim(" 4. Replaces old messages with summary to save tokens")),console.log(),console.log(u.bold("Configuration:")),console.log(u.dim(" Config file: ~/.kodax/config.json")),console.log(u.dim(" Settings:")),console.log(u.dim(" - compaction.triggerPercent: Usage percentage that triggers compaction")),console.log(u.dim(" - compaction.enabled: Controls auto-compaction only; /compact always remains available")),console.log(u.dim(" - compaction.contextWindow: Optional token-window override")),console.log(u.dim(" - compaction.protectionPercent / rollingSummaryPercent / pruningThresholdTokens: Advanced tuning")),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /compact ")+"# Compact with default instructions"),console.log(u.dim(" /compact focus on auth logic ")+"# Emphasize authentication in summary"),console.log(),console.log(u.dim(" See also: /help status (shows token usage)")),console.log()},"detailedHelp")},{name:"reload",description:"Reload project rules and active extensions",handler:i(async(e,t,n,r)=>{console.log(u.cyan(`
122
- Reloading project rule files and runtime extensions...
123
- `));try{let o=await n.reloadAgentsFiles?.()??[],s=ZA(o),a=pr(),c=a?ss(a).loadedExtensions.length:0,l=a?ss(a).failures.length:0,d=0,m=0;if(a){await a.reloadExtensions({continueOnError:!0});let p=ss(a);d=c||p.loadedExtensions.length,m=Math.max(0,p.failures.length-l)}if(o.length===0&&d===0){console.log(u.yellow(`No project rule files or active extensions found.
124
- `)),console.log(u.dim(" Create AGENTS.md or CLAUDE.md in your project, or load extensions with --extension.")),console.log();return}console.log(u.green(`Rules reloaded successfully:
125
- `)),s.global>0&&console.log(u.dim(` - Global: ${s.global} file(s)`)),s.directory>0&&console.log(u.dim(` - Directory: ${s.directory} file(s)`)),s.project>0&&console.log(u.dim(` - Project: ${s.project} file(s)`)),d>0&&console.log(u.dim(` - Extensions: ${d} module(s)`)),m>0&&console.log(u.yellow(` - Failures: ${m} recorded (run /extensions for details)`)),console.log(u.dim(" Updated rules will apply to subsequent requests in this session.")),console.log();return}catch(o){console.log(u.red(`Failed to reload rules.
126
- `)),console.log(u.dim(` Error: ${o instanceof Error?o.message:String(o)}`)),console.log()}},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
127
- /reload - Reload Project Rules
128
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /reload ")+"Reload project rule files and active extensions"),console.log(),console.log(u.bold("Description:")),console.log(" Reloads project-level context rules from AGENTS.md, CLAUDE.md, and .kodax/AGENTS.md files."),console.log(" If a runtime extension host is active, it also hot-reloads loaded extensions."),console.log(),console.log(u.bold("Rule Priority:")),console.log(u.dim(" 1. Global: ")+"~/.kodax/AGENTS.md"),console.log(u.dim(" 2. Directory: ")+"AGENTS.md or CLAUDE.md from project root to current directory"),console.log(u.dim(" 3. Project: ")+".kodax/AGENTS.md at the project root"),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /reload ")+"# Reload and show loaded rules"),console.log()},"detailedHelp")},{name:"extensions",aliases:["ext"],description:"Show active extension runtime diagnostics",usage:"/extensions",handler:i(async()=>{let e=pr();if(!e){console.log(u.yellow(`
129
- [No active extension runtime]
130
- `));return}let t=ss(e),n=t.tools.filter(r=>r.source.kind==="extension");if(console.log(u.bold(`
131
- Extension Runtime:
132
- `)),console.log(u.dim(` Loaded: ${t.loadedExtensions.length}`)),console.log(u.dim(` Capabilities: ${t.capabilityProviders.length}`)),console.log(u.dim(` Commands: ${t.commands.length}`)),console.log(u.dim(` Hooks: ${t.hooks.length}`)),console.log(u.dim(` Failures: ${t.failures.length}`)),console.log(u.dim(` Extension Tools: ${n.length}`)),t.defaults.activeTools!==void 0&&console.log(u.dim(` Active Tools: ${t.defaults.activeTools.join(", ")||"(none)"}`)),(t.defaults.modelSelection.provider||t.defaults.modelSelection.model)&&console.log(u.dim(` Model Override: ${t.defaults.modelSelection.provider??"(inherit)"} / ${t.defaults.modelSelection.model??"(inherit)"}`)),t.defaults.thinkingLevel&&console.log(u.dim(` Thinking: ${t.defaults.thinkingLevel}`)),console.log(),t.loadedExtensions.length>0){console.log(u.bold("Loaded Extensions:"));for(let r of t.loadedExtensions)console.log(u.dim(` - ${r.label} [${r.loadSource}] (${r.path})`));console.log()}if(t.commands.length>0){console.log(u.bold("Extension Commands:"));for(let r of t.commands){let o=r.aliases?.length?` [${r.aliases.join(", ")}]`:"";console.log(u.dim(` - /${r.name}${o} ${r.description}`))}console.log()}if(t.capabilityProviders.length>0){console.log(u.bold("Capability Providers:"));for(let r of t.capabilityProviders){let o=y_(r.metadata);console.log(u.dim(` - ${r.id} [${r.kinds.join(", ")}]${o?` ${o}`:""}`))}console.log()}if(n.length>0){console.log(u.bold("Extension Tools:"));for(let r of n){let o=r.shadowedSources.length>0?` overrides: ${r.shadowedSources.map(s=>s.label??s.id??s.kind).join(", ")}`:"";console.log(u.dim(` - ${r.name}${o}`))}console.log()}if(t.hooks.length>0){console.log(u.bold("Hook Participation:"));for(let r of t.hooks)console.log(u.dim(` - ${r.hook} [#${r.order}] ${r.source.label}`));console.log()}if(t.failures.length>0){console.log(u.bold("Recent Failures:"));for(let r of t.failures.slice(-10))console.log(u.dim(` - [${r.stage}] ${r.source.label}: ${r.target} -> ${r.message}`));console.log()}},"handler")},{name:"status",aliases:["info","ctx"],description:"Show current session status",handler:i(async(e,t,n,r)=>{await f_(t,r,e)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
133
- /status - Show Session Status
134
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /status ")+"Display current session information"),console.log(u.dim(" /status workspace ")+"Show deeper workspace/runtime details"),console.log(u.dim(" /info, /ctx ")+"Aliases for /status"),console.log(),console.log(u.bold("Displays:")),console.log(u.dim(" - Current mode (code/ask)")),console.log(u.dim(" - Session ID")),console.log(u.dim(" - Message count")),console.log(u.dim(" - Estimated token usage")),console.log(u.dim(" - Current workspace truth")),console.log(u.dim(" - Session timestamps")),console.log(u.dim(" - Repo-intelligence mode and active runtime summary")),console.log()},"detailedHelp")},{name:"mcp",description:"Show MCP server status or refresh catalogs",usage:"/mcp [status|refresh]",handler:i(async e=>{let t=pr();if(!t){console.log(u.yellow(`
135
- [No extension runtime active \u2014 MCP is not available]`));return}let r=ss(t).capabilityProviders.find(c=>c.id==="mcp");if((e[0]?.toLowerCase()??"status")==="refresh"){console.log(u.dim(`
136
- Refreshing MCP catalogs...`));try{await t.refreshCapabilityProviders("mcp"),console.log(u.green("MCP catalogs refreshed."))}catch(c){console.log(u.red(`Refresh failed: ${c instanceof Error?c.message:String(c)}`))}return}if(console.log(u.cyan(`
137
- MCP Status
138
- `)),!r){console.log(u.yellow(" No MCP provider registered.")),console.log(u.dim(` Add mcpServers to ~/.kodax/config.json to enable MCP.
139
- `));return}let a=r.metadata?.servers??[];console.log(u.dim(` Servers: ${a.length}`)),console.log();for(let c of a){let l=c.status==="ready"?u.green:c.status==="error"?u.red:u.yellow;console.log(` ${u.bold(c.serverId)} ${l(c.status)} connect=${u.dim(c.connect)}`),c.cachedAt&&console.log(u.dim(` tools=${c.tools} resources=${c.resources} prompts=${c.prompts}`)),c.lastError&&console.log(u.red(` error: ${c.lastError}`))}console.log()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
140
- /mcp - MCP Server Management
141
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /mcp ")+"Show MCP server status"),console.log(u.dim(" /mcp status ")+"Same as /mcp"),console.log(u.dim(" /mcp refresh ")+"Force-refresh all MCP server catalogs"),console.log()},"detailedHelp")},{name:"repointel",aliases:["ri"],description:"Inspect or control the repo-intelligence premium runtime",usage:"/repointel [status|mode|trace|warm|endpoint|bin]",handler:i(async(e,t,n,r)=>{let o=e[0]?.toLowerCase()??"status";if(o==="status"){let s=await fa({mode:r.repoIntelligenceMode,trace:r.repoIntelligenceTrace,probePremium:!0});wT(s);return}if(o==="warm"){let s=await ax({mode:r.repoIntelligenceMode,trace:r.repoIntelligenceTrace});l_(s);return}if(o==="mode"){if(e.length===1){console.log(u.dim(`
142
- Current repo-intelligence mode: ${u.cyan(r.repoIntelligenceMode??"auto")}`)),console.log(u.dim(`Usage: /repointel mode [auto|off|oss|premium-shared|premium-native]
143
- `));return}let s=i_(e[1]);if(!s){console.log(u.red(`
144
- [Invalid repo-intelligence mode: ${e[1]}]`)),console.log(u.dim(`Usage: /repointel mode [auto|off|oss|premium-shared|premium-native]
145
- `));return}let a=Wu({mode:s},{repoIntelligenceMode:s},n,r);br(`Repo intelligence mode: ${s}`,a);return}if(o==="trace"){let s=e[1]?.toLowerCase();if(!s){console.log(u.dim(`
146
- Current repo-intelligence trace: ${u.cyan(r.repoIntelligenceTrace?"on":"off")}`)),console.log(u.dim(`Usage: /repointel trace [on|off|toggle]
147
- `));return}let a=s_(s,r.repoIntelligenceTrace??!1);if(a===null){console.log(u.red(`
148
- [Invalid trace value: ${e[1]}]`)),console.log(u.dim(`Usage: /repointel trace [on|off|toggle]
149
- `));return}let c=Wu({trace:a},{repoIntelligenceTrace:a},n,r);br(`Repo intelligence trace: ${a?"on":"off"}`,c);return}if(o==="endpoint"){if(e.length===1){let c=await fa({mode:r.repoIntelligenceMode,trace:r.repoIntelligenceTrace});console.log(u.dim(`
150
- Current repointel endpoint: ${u.cyan(c.endpoint)}`)),console.log(u.dim(`Usage: /repointel endpoint [http://host:port|default]
151
- `));return}let s=gT(e[1]),a=Wu({endpoint:s},{repointelEndpoint:s??void 0},n,r);br(`Repointel endpoint: ${s??"default"}`,a);return}if(o==="bin"){if(e.length===1){let c=await fa({mode:r.repoIntelligenceMode,trace:r.repoIntelligenceTrace});console.log(u.dim(`
152
- Current repointel bin: ${u.cyan(c.bin)}`)),console.log(u.dim(`Usage: /repointel bin [<path-or-command>|default]
153
- `));return}let s=gT(e.slice(1).join(" ")),a=Wu({bin:s},{repointelBin:s??void 0},n,r);br(`Repointel bin: ${s??"default"}`,a);return}console.log(u.red(`
154
- [Unknown /repointel subcommand: ${e[0]}]`)),console.log(u.dim(`Usage: /repointel [status|mode|trace|warm|endpoint|bin]
155
- `))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
156
- /repointel - Repo-Intelligence Runtime Control
157
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /repointel ")+"Show current repo-intelligence and premium runtime status"),console.log(u.dim(" /repointel status ")+"Probe the local premium frontdoor and print detailed status"),console.log(u.dim(" /repointel mode auto ")+"Prefer premium-native when available, otherwise fall back to OSS"),console.log(u.dim(" /repointel mode off ")+"Strictly disable repo-intelligence working tools and auto lane for this session"),console.log(u.dim(" /repointel mode oss ")+"Force the OSS baseline only"),console.log(u.dim(" /repointel mode premium-shared ")+"Use premium without KodaX native auto lane"),console.log(u.dim(" /repointel mode premium-native ")+"Use the KodaX flagship premium path"),console.log(u.dim(" /repointel trace on|off|toggle ")+"Toggle repo-intelligence trace output"),console.log(u.dim(" /repointel endpoint http://127.0.0.1:47891")+"Override the local premium daemon endpoint"),console.log(u.dim(" /repointel endpoint default ")+"Clear the endpoint override and use the default"),console.log(u.dim(" /repointel bin repointel ")+"Use a PATH-visible repointel command"),console.log(u.dim(" /repointel bin <path> ")+"Use an explicit repointel launcher path"),console.log(u.dim(" /repointel bin default ")+"Clear the bin override and use the default command"),console.log(u.dim(" /repointel warm ")+"Try to start or warm the local premium daemon"),console.log(),console.log(u.bold("Notes:")),console.log(u.dim(" - /status now includes a compact repo-intelligence summary.")),console.log(u.dim(" - /repointel warm is operational: it can warm the premium runtime even when your current mode is oss/off.")),console.log(u.dim(" - If the local service cannot be started, KodaX will continue with the OSS baseline and this command will explain why.")),console.log()},"detailedHelp")},{name:"mode",description:"Show or switch permission mode (plan/accept-edits/auto)",usage:"/mode [plan|accept-edits|auto]",handler:i(async(e,t,n,r)=>{if(e.length===0){let s=Qn(r.permissionMode,"accept-edits")??"accept-edits";console.log(u.dim(`
158
- Current mode: ${u.cyan(s)}`)),console.log(u.dim("Usage: /mode [plan|accept-edits|auto]"));return}let o=e[0];$a.includes(o)?(r.permissionMode=o,n.setPermissionMode?.(o),Ga(o),console.log(u.cyan(`
159
- [Switched to ${o} mode] (saved)`))):console.log(u.red(`
160
- [Unknown mode: ${e[0]}. Use: plan | accept-edits | auto]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
161
- /mode - Switch Permission Mode
162
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /mode ")+"Show current permission mode"),console.log(u.dim(" /mode plan ")+"Read-only: blocks all modifications"),console.log(u.dim(" /mode accept-edits ")+"File edits auto, bash requires confirmation"),console.log(u.dim(" /mode auto ")+"LLM classifier reviews each tool call (FEATURE_092)"),console.log(u.dim(" /mode auto-in-project ")+u.gray("(deprecated alias for auto; will be removed in v0.7.38)")),console.log(),console.log(u.bold("Permission Levels:")),console.log(u.yellow(" plan ")+u.dim("- Read-only planning, no file/command modifications")),console.log(u.green(" accept-edits ")+u.dim("- File edits auto-approved, bash still requires confirmation")),console.log(u.green(" auto ")+u.dim("- LLM classifier (engine=llm, default) or rules engine reviews each call")),console.log(),console.log(u.bold("Notes:")),console.log(u.dim(" - .kodax/ directory and project-external paths always require confirmation")),console.log(u.dim(" - Mode is saved to ~/.kodax/config.json (user-level)")),console.log()},"detailedHelp")},{name:"auto-engine",description:"Show or set auto-mode classifier engine (llm | rules)",usage:"/auto-engine [llm|rules]",handler:i(async(e,t,n)=>{let r=n.getAutoModeStats?.();if(!r){console.log(u.yellow(`
163
- [auto-engine] not in auto mode \u2014 switch via /mode auto first`));return}if(e.length===0){console.log(u.dim(`
164
- Classifier engine: ${u.cyan(r.engine)}`)),console.log(u.dim(` consecutive denials: ${r.denials.consecutive}`)),console.log(u.dim(` cumulative denials: ${r.denials.cumulative}`)),console.log(u.dim(` breaker errors: ${r.breaker.timestamps.filter(s=>s>=Date.now()-600*1e3).length}`)),console.log(u.dim("Usage: /auto-engine [llm|rules]"));return}let o=e[0];if(o!=="llm"&&o!=="rules"){console.log(u.red(`
165
- [auto-engine] unknown engine "${e[0]}" \u2014 use llm or rules`));return}n.setAutoModeEngine?.(o),console.log(u.cyan(`
166
- [auto-engine] switched to ${o}`)),console.log(o==="rules"?u.dim(" every non-Tier-1 tool call now escalates to user confirmation"):u.dim(" classifier consultation resumed; threshold downgrades still apply"))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
167
- /auto-engine - Auto-Mode Classifier Engine Toggle
168
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /auto-engine ")+"Show current engine + denial/breaker counts"),console.log(u.dim(" /auto-engine llm ")+"Resume classifier consultation (default)"),console.log(u.dim(" /auto-engine rules ")+"Skip classifier; every non-Tier-1 call asks user"),console.log(),console.log(u.bold("Notes:")),console.log(u.dim(" - Only meaningful in auto mode (/mode auto).")),console.log(u.dim(" - The classifier may auto-downgrade to rules after 3 consecutive blocks,")),console.log(u.dim(" 20 cumulative blocks, or 5 errors in a 10-minute window. /auto-engine llm")),console.log(u.dim(" manually flips back to llm.")),console.log(u.dim(" - Override via env: KODAX_AUTO_MODE_ENGINE=rules.")),console.log()},"detailedHelp")},{name:"auto-denials",description:"Show auto-mode classifier denial tracker + circuit breaker stats",usage:"/auto-denials",handler:i(async(e,t,n)=>{let r=n.getAutoModeStats?.();if(!r){console.log(u.yellow(`
169
- [auto-denials] not in auto mode \u2014 switch via /mode auto first`));return}console.log(u.cyan(`
170
- [auto-mode classifier stats]`)),console.log(u.dim(` engine: ${u.cyan(r.engine)}`)),console.log(u.dim(" Denial tracker:")),console.log(u.dim(` consecutive blocks: ${r.denials.consecutive} / 3`)),console.log(u.dim(` cumulative blocks: ${r.denials.cumulative} / 20`)),console.log(u.dim(" Circuit breaker:")),console.log(u.dim(` errors in window: ${r.breaker.timestamps.filter(o=>o>=Date.now()-600*1e3).length} / 5 (10 min)`)),console.log(),r.engine==="rules"&&console.log(u.yellow(" \u21AA engine has downgraded to rules. /auto-engine llm to flip back.")),console.log()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
171
- /auto-denials - Auto-Mode Classifier Diagnostic Dump
172
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /auto-denials ")+"Print engine + tracker + breaker counters"),console.log(),console.log(u.bold("Thresholds (FEATURE_092):")),console.log(u.dim(" - 3 consecutive blocks \u2192 engine downgrade to rules")),console.log(u.dim(" - 20 cumulative blocks \u2192 engine downgrade to rules")),console.log(u.dim(" - 5 errors in 10-min \u2192 circuit breaker trips \u2192 engine downgrade")),console.log()},"detailedHelp")},{name:"save",description:"Save current session",handler:i(async(e,t,n)=>{await n.saveSession(),console.log(u.green(`
173
- [Session saved]`)),Ap(t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
174
- /save - Save Current Session
175
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /save ")+"Save current conversation to session storage"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Manually saves the current conversation session.")),console.log(u.dim(" Sessions are auto-saved after each message, but you can")),console.log(u.dim(" use this to ensure the session is persisted.")),console.log(u.dim(" Saving updates session storage only; the current workspace stays untouched.")),console.log(),console.log(u.dim(" See also: /help load, /help sessions")),console.log()},"detailedHelp")},{name:"load",aliases:["resume"],description:"Load a session",usage:"/load <session-id>",handler:i(async(e,t,n)=>{if(e.length===0){console.log(u.red(`
176
- [Usage: /load <session-id>]`)),await n.listSessions();return}await n.loadSession(e[0])==="missing"&&console.log(u.red(`
177
- [Session not found: ${e[0]}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
178
- /load - Load a Saved Session
179
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /load ")+"List available sessions"),console.log(u.dim(" /load <session-id> ")+"Load a specific session"),console.log(u.dim(" /resume <id> ")+"Alias for /load"),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /load ")+"# See all sessions"),console.log(u.dim(" /load 20260219_143052")+"# Load session by ID"),console.log(),console.log(u.bold("Workspace behavior:")),console.log(u.dim(" /load can resume sessions from sibling workspaces in the same canonical repo.")),console.log(u.dim(" If a saved workspace is unavailable, KodaX explains the fallback before loading.")),console.log(),console.log(u.dim(" See also: /help sessions, /help save")),console.log()},"detailedHelp")},{name:"tree",description:"Inspect or switch the current session tree",usage:"/tree [entry-id|label] | /tree label <entry-id|label> <name> | /tree unlabel <entry-id|label>",handler:i(async(e,t,n)=>{if(e.length===0){await n.printSessionTree?.();return}let r=e[0]?.trim().toLowerCase();if(r==="label"){if(e.length<3){console.log(u.red(`
180
- [Usage: /tree label <entry-id|label> <name>]`));return}await n.labelSessionBranch?.(e[1],e.slice(2).join(" "))||console.log(u.red(`
181
- [Tree entry not found: ${e[1]}]`));return}if(r==="unlabel"){if(e.length<2){console.log(u.red(`
182
- [Usage: /tree unlabel <entry-id|label>]`));return}await n.labelSessionBranch?.(e[1],void 0)||console.log(u.red(`
183
- [Tree entry not found: ${e[1]}]`));return}await n.switchSessionBranch?.(e[0])==="missing"&&console.log(u.red(`
184
- [Tree entry not found: ${e[0]}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
185
- /tree - Inspect Session Lineage
186
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /tree ")+"Show the current session tree"),console.log(u.dim(" /tree <entry-id|label> ")+"Jump to a previous branch point"),console.log(u.dim(" /tree label <entry-id|label> <name>")+"Attach a lightweight checkpoint label"),console.log(u.dim(" /tree unlabel <entry-id|label> ")+"Clear an existing checkpoint label"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Session history is stored as a branchable tree. Use /tree to")),console.log(u.dim(" inspect the lineage, revisit an earlier branch safely, and add")),console.log(u.dim(" bookmark-style checkpoint labels without changing git state.")),console.log()},"detailedHelp")},{name:"fork",description:"Fork the current branch into a new session",usage:"/fork [entry-id|label]",handler:i(async(e,t,n)=>{await n.forkSession?.(e[0])==="failed"&&console.log(u.red(`
187
- [Unable to fork session${e[0]?` from ${e[0]}`:""}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
188
- /fork - Export a Branch to a New Session
189
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /fork ")+"Fork from the active branch"),console.log(u.dim(" /fork <entry-id|label>")+"Fork from a selected tree node"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Creates a new session file from the selected branch so you can")),console.log(u.dim(" continue there without mutating the current session lineage.")),console.log()},"detailedHelp")},{name:"rewind",description:"Rewind the current session to a previous point",usage:"/rewind [entry-id|label]",handler:i(async(e,t,n)=>{await n.rewindSession?.(e[0])==="failed"&&console.log(u.red(`
190
- [Unable to rewind${e[0]?` to ${e[0]}`:" \u2014 no previous turn found"}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
191
- /rewind - Rewind Session to a Previous Point
192
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /rewind ")+"Rewind to the previous user input"),console.log(u.dim(" /rewind <entry-id|label>")+"Rewind to a specific tree node"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Truncates the session after the target entry. Unlike /fork,")),console.log(u.dim(" this modifies the current session in place. The rewind event")),console.log(u.dim(" is recorded in the lineage for auditability.")),console.log(),console.log(u.yellow(" \u26A0 This is irreversible. Use /fork first to preserve a copy.")),console.log()},"detailedHelp")},{name:"sessions",aliases:["ls","list"],description:"List recent sessions",handler:i(async(e,t,n)=>{await n.listSessions()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
193
- /sessions - List Saved Sessions
194
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /sessions ")+"List all saved sessions"),console.log(u.dim(" /ls, /list ")+"Aliases for /sessions"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Shows recent conversation sessions with their IDs,")),console.log(u.dim(" message counts, titles, and workspace truth. Use /load <id> to resume.")),console.log(u.dim(" This keeps sibling worktree sessions inspectable without a persistent cockpit.")),console.log(),console.log(u.dim(" See also: /help load, /help delete")),console.log()},"detailedHelp")},{name:"history",aliases:["hist"],description:"Show conversation history",handler:i(async(e,t,n)=>{n.printHistory()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
195
- /history - Show Conversation History
196
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /history ")+"Display recent messages in current session"),console.log(u.dim(" /hist ")+"Alias for /history"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Shows the last 20 messages in the current conversation.")),console.log(u.dim(" Useful for reviewing what has been discussed.")),console.log()},"detailedHelp")},{name:"delete",aliases:["rm","del"],description:"Delete a session",usage:"/delete <session-id> or /delete all",handler:i(async(e,t,n)=>{if(e.length===0){console.log(u.red(`
197
- [Usage: /delete <session-id> or /delete all]`)),await n.listSessions?.();return}e[0]==="all"?(await n.deleteAllSessions?.(),console.log(u.green(`
198
- [All sessions deleted]`)),Ap(t)):(await n.deleteSession?.(e[0]),console.log(u.green(`
199
- [Session deleted: ${e[0]}]`)),Ap(t))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
200
- /delete - Delete Saved Sessions
201
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /delete ")+"Show usage (lists sessions)"),console.log(u.dim(" /delete <id> ")+"Delete a specific session"),console.log(u.dim(" /delete all ")+"Delete ALL sessions"),console.log(u.dim(" /rm, /del ")+"Aliases for /delete"),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /delete 20260219_143052")+" # Delete specific session"),console.log(u.dim(" /delete all ")+"# Delete all sessions"),console.log(),console.log(u.bold("Workspace behavior:")),console.log(u.dim(" Deletes saved session records only.")),console.log(u.dim(" Current workspaces and checkouts remain untouched.")),console.log(),console.log(u.yellow(" Warning: /delete all cannot be undone!")),console.log()},"detailedHelp")},{name:"model",aliases:["m"],description:"Show or switch provider/model",usage:"/model [<provider>[/<model>] | /<model>]",handler:i(async(e,t,n,r)=>{let o=ga().providerModels;if(e.length===0){console.log(u.bold(`
202
- Available Providers:
203
- `));let c=dm(o);for(let l of c){let d=l.configured?u.green("[configured]"):u.red("[not configured]"),m=l.custom?u.yellow(" [custom]"):"",p=l.name===r.provider,g=p?u.cyan(" *"):"";console.log(` ${u.bold(l.name)}${g} ${d}${m}`),l.capabilityProfile.transport==="cli-bridge"&&console.log(u.yellow(` ! ${cm(l.capabilityProfile)}`));let x=Ei(l.name,o),y=p?r.model:null;for(let T of x){let v=p&&(y===T||!y&&T===l.model)?u.cyan(">"):" ";console.log(` ${v} ${T}`)}console.log()}console.log(u.dim(`Current: provider=${r.provider}${r.model?`, model=${r.model}`:""}`)),console.log(u.dim("Usage:")),console.log(u.dim(" /model <provider> Switch provider")),console.log(u.dim(" /model <provider>/<model> Switch to specific model")),console.log(u.dim(` /model /<model> Switch model within current provider
204
- `));return}let s=(e[0]??"").trim();if(!s)return;if(s.startsWith("/")){let c=s.slice(1);if(!c){console.log(u.red(`
205
- [Missing model name after /]`));return}let l=Ei(r.provider,o);if(!l.includes(c)){console.log(u.red(`
206
- [Unknown model: ${c}]`)),console.log(u.dim(`Available models for ${r.provider}: ${l.join(", ")}
207
- `));return}gr({model:c}),n.switchProvider?.(r.provider,c),console.log(u.cyan(`
208
- [Switched to ${c}] (saved)`));return}if(s.includes("/")){let c=s.indexOf("/"),l=s.slice(0,c),d=s.slice(c+1);if(!d||!l){console.log(u.red(`
209
- [Invalid format. Use: /model <provider>/<model>]`));return}if(!xi(l)){console.log(u.red(`
210
- [Unknown provider: ${l}]`)),console.log(u.dim(`Available: ${wi().join(", ")}
211
- `));return}let m=Ei(l,o);if(!m.includes(d)){console.log(u.red(`
212
- [Unknown model: ${d}]`)),console.log(u.dim(`Available models for ${l}: ${m.join(", ")}
213
- `));return}gr({provider:l,model:d}),n.switchProvider?.(l,d),console.log(u.cyan(`
214
- [Switched to ${l}/${d}] (saved)`));return}let a=s;xi(a)?(gr({provider:a,model:void 0}),n.switchProvider?.(a),console.log(u.cyan(`
215
- [Switched to ${a}] (saved)`))):(console.log(u.red(`
216
- [Unknown provider: ${a}]`)),console.log(u.dim(`Available: ${wi().join(", ")}
217
- `)))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
218
- /model - Switch LLM Provider/Model
219
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /model ")+"List all providers with models"),console.log(u.dim(" /model <provider> ")+"Switch to a provider (default model)"),console.log(u.dim(" /model <provider>/<model> ")+"Switch to a specific model"),console.log(u.dim(" /model /<model> ")+"Switch model within current provider"),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /model ")+"# See available providers & models"),console.log(u.dim(" /model anthropic ")+"# Switch to Anthropic (default model)"),console.log(u.dim(" /model openai/gpt-5.4 ")+"# Switch to OpenAI GPT-5.4"),console.log(u.dim(" /model /claude-opus-4-6 ")+"# Switch to Opus within current provider"),console.log()},"detailedHelp")},{name:"provider",description:"Inspect provider semantics and policy constraints",usage:"/provider [<provider>[/<model>]]",handler:i(async(e,t,n,r)=>{let o=(e[0]??"").trim(),s=r.provider,a=r.model;if(o)if(o.includes("/")){let d=o.indexOf("/");s=o.slice(0,d).trim(),a=o.slice(d+1).trim()||void 0}else s=o,a=void 0;if(!xi(s)){console.log(u.red(`
220
- [Unknown provider: ${s}]`)),console.log(u.dim(`Available: ${wi().join(", ")}
221
- `));return}let c=Ix(s,a);if(!c){console.log(u.red(`
222
- [Provider details unavailable: ${s}]`)),console.log();return}let l=Ex(s,a,r.reasoningMode);console.log(u.bold(`
223
- Provider Details:
224
- `)),console.log(u.dim(` Provider: ${u.cyan(c.provider)}${c.model?` / ${u.cyan(c.model)}`:""}`)),console.log(u.dim(` Source: ${kx(c.sourceKind)}`)),console.log(),console.log(u.bold("Capability Matrix:"));for(let d of Rx(c))console.log(u.dim(` - ${d}`));if(console.log(),l.length>0){console.log(u.bold("Common Scenarios:"));for(let d of l){let m=d.decision.status==="block"?u.red:d.decision.status==="warn"?u.yellow:u.green;console.log(m(` - ${d.label}: ${d.decision.status.toUpperCase()}`)),console.log(u.dim(` ${d.decision.summary}`))}console.log()}},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
225
- /provider - Inspect Provider Semantics
226
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /provider ")+"Inspect the current provider/model"),console.log(u.dim(" /provider <provider> ")+"Inspect a provider using its default model"),console.log(u.dim(" /provider <provider>/<model> ")+"Inspect a specific provider/model pair"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Shows the provider capability matrix and common 029 policy outcomes.")),console.log(u.dim(" Use this to understand why long-running, harness, or evidence-heavy flows may warn or block.")),console.log()},"detailedHelp")},{name:"thinking",aliases:["think","t"],description:"Show or change reasoning mode (compat alias)",usage:"/thinking [on|off|auto|quick|balanced|deep]",handler:i(async(e,t,n,r)=>{if(e.length===0){let s=xo(r.provider,r.model),a=r.thinking?u.green("ON"):u.dim("OFF");console.log(u.dim(`
227
- Thinking: ${a}`)),console.log(u.dim(`Reasoning mode: ${u.cyan(r.reasoningMode)}`)),console.log(u.dim(`Effective control: ${u.cyan(lm(s))}`)),console.log(u.dim(`Actual execution: ${um(r.reasoningMode,s)}`)),console.log(u.dim(`Usage: /thinking on|off|auto|quick|balanced|deep
228
- `));return}let o=e[0].toLowerCase();if(o==="on"||o==="off"||mo.includes(o)){let s=o==="on"?"auto":o==="off"?"off":o,a=hT(s,n,r);br(`Reasoning mode: ${s}`,a);return}console.log(u.red(`
229
- [Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /thinking on|off|auto|quick|balanced|deep
230
- `))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
231
- /thinking - Legacy Alias for Reasoning Mode
232
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /thinking ")+"Show current reasoning status"),console.log(u.dim(" /thinking on ")+"Map to /reasoning auto"),console.log(u.dim(" /thinking off ")+"Map to /reasoning off"),console.log(u.dim(" /thinking auto ")+"Set reasoning mode to auto"),console.log(u.dim(" /thinking quick ")+"Set reasoning mode to quick"),console.log(u.dim(" /thinking balanced ")+"Set reasoning mode to balanced"),console.log(u.dim(" /thinking deep ")+"Set reasoning mode to deep"),console.log(u.dim(" /t ")+"Alias for /thinking"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Compatibility command for the new unified reasoning modes.")),console.log(u.dim(" Use /reasoning for the primary interface.")),console.log()},"detailedHelp")},{name:"reasoning",aliases:["reason"],description:"Show or set reasoning mode",usage:"/reasoning [off|auto|quick|balanced|deep]",handler:i(async(e,t,n,r)=>{if(e.length===0){let a=xo(r.provider,r.model);console.log(u.dim(`
233
- Reasoning mode: ${u.cyan(r.reasoningMode)}`)),console.log(u.dim(`Thinking compatibility: ${r.thinking?u.green("ON"):u.dim("OFF")}`)),console.log(u.dim(`Effective control: ${u.cyan(lm(a))}`)),console.log(u.dim(`Actual execution: ${um(r.reasoningMode,a)}`)),console.log(u.dim(`Usage: /reasoning off|auto|quick|balanced|deep
234
- `));return}let o=e[0].toLowerCase();if(!mo.includes(o)){console.log(u.red(`
235
- [Invalid reasoning mode: ${e[0]}]`)),console.log(u.dim(`Usage: /reasoning off|auto|quick|balanced|deep
236
- `));return}let s=hT(o,n,r);br(`Reasoning mode: ${o}`,s)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
237
- /reasoning - Set Reasoning Mode
238
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /reasoning ")+"Show current reasoning mode"),console.log(u.dim(" /reasoning off ")+"Disable reasoning"),console.log(u.dim(" /reasoning auto ")+"Use semantic routing + adaptive depth"),console.log(u.dim(" /reasoning quick ")+"Low-depth reasoning"),console.log(u.dim(" /reasoning balanced ")+"Medium-depth reasoning"),console.log(u.dim(" /reasoning deep ")+"High-depth reasoning"),console.log(u.dim(" /reasoning:auto ")+"Inline form, equivalent to /reasoning auto"),console.log(u.dim(" /reason ")+"Alias for /reasoning"),console.log()},"detailedHelp")},{name:"agent-mode",aliases:["am"],description:"Show or set agent mode",usage:"/agent-mode [ama|sa|toggle]",handler:i(async(e,t,n,r)=>{if(e.length===0){console.log(u.dim(`
239
- Agent mode: ${u.cyan(r.agentMode.toUpperCase())}`)),console.log(u.dim(`Usage: /agent-mode [ama|sa|toggle]
240
- `));return}let o=e[0]?.toLowerCase(),s=o==="toggle"?r.agentMode==="ama"?"sa":"ama":o==="ama"||o==="sa"?o:void 0;if(!s){console.log(u.red(`
241
- [Invalid agent mode: ${e[0]}]`)),console.log(u.dim(`Usage: /agent-mode [ama|sa|toggle]
242
- `));return}let a=a_(s,n,r);br(`Agent mode: ${s.toUpperCase()}`,a)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
243
- /agent-mode - Adaptive Multi-Agent Mode Control
244
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /agent-mode ")+"Show current agent mode"),console.log(u.dim(" /agent-mode ama ")+"Enable adaptive multi-agent mode"),console.log(u.dim(" /agent-mode sa ")+"Force single-agent execution"),console.log(u.dim(" /agent-mode toggle ")+"Switch between AMA and SA"),console.log(u.dim(" /am ")+"Alias for /agent-mode"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" AMA keeps adaptive multi-agent harness selection enabled.")),console.log(u.dim(" SA keeps routing and task artifacts, but forces single-agent execution to save tokens.")),console.log()},"detailedHelp")},{name:"auto",aliases:["a"],description:"Quick switch to auto mode",handler:i(async(e,t,n,r)=>{r.permissionMode="auto",n.setPermissionMode?.("auto"),Ga("auto"),console.log(u.cyan(`
245
- [Switched to auto mode] (saved)`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
246
- /auto - Quick Switch to Auto Mode
247
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /auto ")+"Switch to auto mode"),console.log(u.dim(" /a ")+"Alias for /auto"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" Equivalent to /mode auto.")),console.log(u.dim(" Auto-mode classifier evaluates each non-Tier-1 tool call;")),console.log(u.dim(" benign actions auto-approve, risky ones escalate to user confirm.")),console.log(),console.log(u.dim(" See also: /help mode, /auto-engine, /auto-denials")),console.log()},"detailedHelp")},{name:"skills",description:"(Deprecated) Use /skill instead",usage:"/skill",handler:i(async(e,t)=>{console.log(u.dim(`
248
- [/skills is deprecated. Use /skill instead]`)),await xT(e,t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
249
- /skills - Deprecated
250
- `)),console.log(u.yellow("This command is deprecated. Use /skill instead.")),console.log(),console.log(u.dim(" /skill ")+"List all available skills"),console.log(u.dim(" /skill:<name> ")+"Invoke a skill"),console.log()},"detailedHelp")},{name:"skill",description:"Skill namespace - invoke skills with /skill:name",usage:"/skill[:name] [args]",handler:i(async(e,t,n,r)=>{await xT(e,t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
251
- /skill - Skill Namespace
252
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /skill ")+"List all available skills"),console.log(u.dim(" /skill:<name> [args] ")+"Invoke a skill by name"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" This is the pi-mono style skill invocation format.")),console.log(u.dim(" Skills can also be triggered by natural language - just ask!")),console.log(),console.log(u.bold("Examples:")),console.log(u.dim(" /skill ")+"# List all skills"),console.log(u.dim(" /skill:code-review src/ ")+"# Invoke code-review skill"),console.log(u.dim(" /skill:tdd auth ")+"# Invoke TDD skill"),console.log()},"detailedHelp")},{name:"verifier-log",description:"Toggle Sidecar Verifier log line (off by default)",usage:"/verifier-log [on|off]",argumentHint:"on | off",handler:i(async e=>{let t=e[0]?.toLowerCase(),n=process.env.KODAX_VERIFIER_LOG==="1";if(!t){let s=ga().verifierLog===!0,a=n?"on":"off",c=s===n?"":` (env=${n?"on":"off"}, config=${s?"on":"off"})`;console.log(u.dim(`
253
- Sidecar Verifier log: ${u.cyan(a)}${c}`)),console.log(u.dim(" When on, a one-line summary persists per verifier call:\n `[Sidecar Verifier] {verdict} \xB7 {provider}/{model} \xB7 {ms}ms \xB7 {trace}`")),console.log(u.dim(`Usage: /verifier-log [on|off]
254
- `));return}let r;if(t==="on"||t==="true"||t==="1")r=!0;else if(t==="off"||t==="false"||t==="0")r=!1;else{console.log(u.red(`
255
- [Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /verifier-log [on|off]
256
- `));return}r?process.env.KODAX_VERIFIER_LOG="1":delete process.env.KODAX_VERIFIER_LOG;let o=za({verifierLog:r});br(`Sidecar Verifier log: ${r?"on":"off"}`,o)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
257
- /verifier-log - Sidecar Verifier Log Toggle
258
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /verifier-log ")+"Show current state"),console.log(u.dim(" /verifier-log on ")+"Enable + persist to config"),console.log(u.dim(" /verifier-log off ")+"Disable + persist to config"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" The Sidecar Verifier is the second-pass LLM judgment that fires")),console.log(u.dim(" after a Worker terminates text-only. Off by default (silent happy")),console.log(u.dim(" path). When on, every verifier call emits a one-line summary:")),console.log(u.dim(" [Sidecar Verifier] accept \xB7 anthropic/claude-sonnet-4-6 \xB7 3214ms \xB7 verifier_ok")),console.log(),console.log(u.bold("Equivalent env var:")),console.log(u.dim(" KODAX_VERIFIER_LOG=1 ")+"Same effect, env wins over config"),console.log()},"detailedHelp")},{name:"stall-log",description:"Toggle Stall Sidecar log line (off by default)",usage:"/stall-log [on|off]",argumentHint:"on | off",handler:i(async e=>{let t=e[0]?.toLowerCase(),n=process.env.KODAX_STALL_LOG==="1";if(!t){let s=ga().stallLog===!0,a=n?"on":"off",c=s===n?"":` (env=${n?"on":"off"}, config=${s?"on":"off"})`;console.log(u.dim(`
259
- Stall Sidecar log: ${u.cyan(a)}${c}`)),console.log(u.dim(" When on, a one-line summary persists per L2 stall verdict:\n `[Stall Sidecar] isStuck={true|false} \xB7 {provider}/{model} \xB7 {ms}ms \xB7 {trace}`")),console.log(u.dim(`Usage: /stall-log [on|off]
260
- `));return}let r;if(t==="on"||t==="true"||t==="1")r=!0;else if(t==="off"||t==="false"||t==="0")r=!1;else{console.log(u.red(`
261
- [Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /stall-log [on|off]
262
- `));return}r?process.env.KODAX_STALL_LOG="1":delete process.env.KODAX_STALL_LOG;let o=za({stallLog:r});br(`Stall Sidecar log: ${r?"on":"off"}`,o)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
263
- /stall-log - Stall Sidecar Log Toggle
264
- `)),console.log(u.bold("Usage:")),console.log(u.dim(" /stall-log ")+"Show current state"),console.log(u.dim(" /stall-log on ")+"Enable + persist to config"),console.log(u.dim(" /stall-log off ")+"Disable + persist to config"),console.log(),console.log(u.bold("Description:")),console.log(u.dim(" The Stall Sidecar (FEATURE_178) is the L2 anti-loop LLM judge that")),console.log(u.dim(" fires when the L1 rule-based detector spots a repeat-tool pattern.")),console.log(u.dim(" Off by default (silent happy path). When on, every L2 verdict emits")),console.log(u.dim(" a one-line summary:")),console.log(u.dim(" [Stall Sidecar] isStuck=true \xB7 zhipu/glm-5.1 (inherit) \xB7 1842ms \xB7 sidecar_ok")),console.log(),console.log(u.bold("Equivalent env var:")),console.log(u.dim(" KODAX_STALL_LOG=1 ")+"Same effect, env wins over config"),console.log()},"detailedHelp")},yp,xp,wp],t_={General:["help","copy","exit","clear","compact","reload","extensions","status"],Permission:["mode","auto"],Session:["new","save","load","sessions","history","delete"],Settings:["model","provider","thinking","reasoning","agent-mode","plan","repointel"],Skills:["skill"]};function n_(e){let t=Uu();return e.map(n=>t.get(n)).filter(n=>n!==void 0).filter(n=>n.userInvocable!==!1)}i(n_,"getCommandsForCategory");function r_(e){return e!=="off"}i(r_,"reasoningModeToLegacyThinking");var o_=["auto","off","oss","premium-shared","premium-native"];function i_(e){return e&&o_.includes(e)?e:null}i(i_,"normalizeRepoIntelligenceMode");function gT(e){let t=e?.trim();return!t||t==="default"||t==="reset"||t==="clear"?null:t}i(gT,"normalizeRuntimeOverride");function s_(e,t){return e?e==="toggle"?!t:e==="on"||e==="true"||e==="1"?!0:e==="off"||e==="false"||e==="0"?!1:null:null}i(s_,"resolveToggleFlag");function za(e){try{return gr(e),{saved:!0}}catch(t){return{saved:!1,error:t instanceof Error?t:new Error(String(t))}}}i(za,"persistUserConfig");function br(e,t){if(t.saved){console.log(u.cyan(`
265
- [${e}] (saved)`));return}console.log(u.yellow(`
266
- [${e}]`)),console.log(u.red(`[Config save failed: ${t.error.message}]`))}i(br,"printPersistedCommandStatus");function hT(e,t,n){let r=r_(e),o=za({reasoningMode:e,thinking:r});return t.setReasoningMode?t.setReasoningMode(e):(n.reasoningMode=e,n.thinking=r),o}i(hT,"applyReasoningMode");function a_(e,t,n){let r=za({agentMode:e});return t.setAgentMode?t.setAgentMode(e):n.agentMode=e,r}i(a_,"applyAgentMode");function Wu(e,t,n,r){let o=za(t);return n.setRepoIntelligenceRuntime?n.setRepoIntelligenceRuntime(e):(e.mode!==void 0&&(r.repoIntelligenceMode=e.mode),e.endpoint!==void 0&&(r.repointelEndpoint=e.endpoint??void 0),e.bin!==void 0&&(r.repointelBin=e.bin??void 0),e.trace!==void 0&&(r.repoIntelligenceTrace=e.trace)),o}i(Wu,"applyRepoIntelligenceRuntimeConfig");function c_(e){let t=e.configuredMode===e.requestedMode?e.configuredMode:`${e.configuredMode} -> ${e.requestedMode}`,n=`${e.effectiveEngine}/${e.effectiveBridge}`,r=e.transport?`, ${e.transport}`:"",o=e.fallbackToOss?", fallback=oss":"";return`${t} => ${n} (${e.status}${r}${o})`}i(c_,"formatRepoIntelligenceSummary");function wT(e){console.log(u.bold(`
267
- Repo Intelligence:
268
- `)),console.log(u.dim(` Configured: ${u.cyan(e.configuredMode)}`)),console.log(u.dim(` Requested: ${u.cyan(e.requestedMode)}`)),console.log(u.dim(` Active: ${u.cyan(`${e.effectiveEngine}/${e.effectiveBridge}`)}`)),console.log(u.dim(` Status: ${u.cyan(e.status)}${e.transport?u.dim(` (${e.transport})`):""}`)),console.log(u.dim(` Trace: ${u.cyan(e.traceEnabled?"on":"off")}`)),console.log(u.dim(` Endpoint: ${e.endpoint}`)),console.log(u.dim(` Bin: ${e.bin}`)),e.clientBuildId&&console.log(u.dim(` Client ID: ${e.clientBuildId}`)),e.daemonBuildId&&console.log(u.dim(` Daemon ID: ${e.daemonBuildId}`)),e.daemonPid!==void 0&&console.log(u.dim(` Daemon PID: ${e.daemonPid}`)),e.daemonStartedAt&&console.log(u.dim(` Daemon Up: ${e.daemonStartedAt}`)),e.fallbackToOss&&console.log(u.yellow(" Fallback: OSS baseline is currently active")),e.error&&console.log(u.red(` Error: ${e.error}`));for(let t of e.warnings)console.log(u.yellow(` Warning: ${t}`));console.log()}i(wT,"printRepoIntelligenceInspection");function l_(e){e.warmed?console.log(u.green(`
269
- [repointel warmed successfully]`)):console.log(u.yellow(`
270
- [repointel warm did not reach a ready daemon state]`)),e.warmLatencyMs!==void 0&&console.log(u.dim(` Warm latency: ${e.warmLatencyMs} ms`)),wT(e)}i(l_,"printRepoIntelligenceWarmResult");function yT(e,t){if(t.length!==0){console.log(u.dim(`${e}:`));for(let n of t){let r=n.aliases?.length?` (${n.aliases.join(", ")})`:"";console.log(` ${u.cyan(`/${n.name}`)}${u.dim(r)} ${n.description}`)}console.log()}}i(yT,"printCommandSection");function u_(){console.log(u.bold(`
271
- Available Commands:
272
- `));let e=Uu(),t=new Set;for(let[r,o]of Object.entries(t_)){let s=n_(o);if(s.length!==0){for(let a of s)t.add(a.name.toLowerCase());yT(r,s)}}let n=new Map;for(let r of e.getAll()){if(r.userInvocable===!1||t.has(r.name.toLowerCase()))continue;let o=r.source==="extension"?"Extensions":r.source==="skill"?"Skill Commands":r.source==="prompt"?"Prompt Commands":"Other Commands",s=n.get(o)??[];s.push(r),n.set(o,s)}for(let r of p_()){if(t.has(r.name.toLowerCase()))continue;let o=n.get("Extensions")??[];o.push({name:r.name,aliases:r.aliases,description:r.description}),n.set("Extensions",o)}for(let r of["Extensions","Skill Commands","Prompt Commands","Other Commands"])yT(r,n.get(r)??[]);console.log(u.dim("Special syntax:")),console.log(` ${u.cyan("@path")} Attach image to context`),console.log(` ${u.cyan("!command")} Execute shell command`),console.log(),console.log(u.dim("Skills:")),console.log(` ${u.cyan("/skill")} List all available skills`),console.log(` ${u.cyan("/skill:<name>")} Invoke a skill (e.g., /skill:code-review)`),console.log()}i(u_,"printHelp");function d_(e){Do.size===0&&_p();let t=Do.get(e.toLowerCase());if(!t){let n=ST(e);if(!n){console.log(u.yellow(`
273
- [Unknown command: /${e}. Type /help for available commands]`));return}console.log(u.cyan(`
274
- /${n.name}`)),n.aliases?.length&&console.log(u.dim(`Aliases: ${n.aliases.join(", ")}`)),console.log(u.dim(`
275
- ${n.description}`)),console.log(u.dim(`
276
- Usage: ${g_(n)}`)),console.log();return}t.detailedHelp?t.detailedHelp():(console.log(u.cyan(`
277
- /${t.name}`)),t.aliases?.length&&console.log(u.dim(`Aliases: ${t.aliases.join(", ")}`)),console.log(u.dim(`
278
- ${t.description}`)),t.usage&&console.log(u.dim(`
279
- Usage: ${t.usage}`)),console.log())}i(d_,"printDetailedHelp");async function f_(e,t,n=[]){let r=n[0]?.toLowerCase(),o=e.contextTokenSnapshot?.currentTokens??go(e.messages),s=e.contextTokenSnapshot?.source??"estimate",a=vx(t.provider),c=$l(t.provider,t.model,t.reasoningMode);if(console.log(u.bold(`
280
- Session Status:
281
- `)),console.log(u.dim(` Provider: ${u.cyan(t.provider)}${t.model?` / ${u.cyan(t.model)}`:""}`)),console.log(u.dim(` Permission: ${u.cyan(t.permissionMode)}`)),console.log(u.dim(` Reasoning: ${u.cyan(t.reasoningMode)}`)),console.log(u.dim(` Agent Mode: ${u.cyan(t.agentMode.toUpperCase())}`)),a){let d=cm(a),m=a.transport==="cli-bridge"?u.yellow(d):u.cyan(d);console.log(u.dim(` Provider Cap: ${m}`))}if(c&&c.status!=="allow"){let d=c.status==="block"?u.red:u.yellow;console.log(u.dim(` Provider Policy: ${d(c.summary)}`))}console.log(u.dim(` Session ID: ${e.sessionId}`)),console.log(u.dim(` Messages: ${e.messages.length}`)),console.log(u.dim(` Tokens: ~${o} (${s})`));let l=await fa({mode:t.repoIntelligenceMode,trace:t.repoIntelligenceTrace});console.log(u.dim(` Repo Intel: ${u.cyan(c_(l))}`)),e.runtimeInfo?.workspaceRoot?console.log(u.dim(` Workspace: ${u.cyan(Cn(e.runtimeInfo))}`)):e.gitRoot&&console.log(u.dim(` Workspace: ${u.cyan(e.gitRoot)}`)),(r==="workspace"||r==="worktree"||r==="runtime")&&(e.runtimeInfo?.canonicalRepoRoot&&console.log(u.dim(` Canonical: ${e.runtimeInfo.canonicalRepoRoot}`)),e.runtimeInfo?.executionCwd&&console.log(u.dim(` Exec CWD: ${e.runtimeInfo.executionCwd}`)),e.runtimeInfo?.workspaceKind&&console.log(u.dim(` Kind: ${e.runtimeInfo.workspaceKind}`))),console.log(u.dim(` Created: ${e.createdAt}`)),console.log(u.dim(` Last Active: ${e.lastAccessed}`)),console.log()}i(f_,"printStatus");async function xT(e,t){let n=mr(t.gitRoot);n.size===0&&await ho(t.gitRoot),m_(n.listUserInvocable())}i(xT,"handleSkillNamespaceCommand");function m_(e){if(console.log(u.bold(`
282
- Available Skills:
283
- `)),e.length===0){console.log(u.dim(" No skills found.")),console.log(u.dim(`
284
- Skills can be placed in:`)),console.log(u.dim(" - .kodax/skills/")),console.log(u.dim(" - ~/.kodax/skills/"));return}let t=Math.max(...e.map(n=>n.name.length));for(let n of e){let r=n.name.padEnd(t),o=n.argumentHint?` ${n.argumentHint}`:"",s=n.source==="builtin"?" [builtin]":n.source==="user"?" [user]":n.source==="plugin"?" [plugin]":"",a=n.description.length>50?n.description.slice(0,50)+"...":n.description;console.log(` ${u.cyan(`/skill:${r}`)}${u.dim(o)}${u.dim(s)} ${u.dim(a)}`)}console.log(),console.log(u.dim(`Total: ${e.length} skills`)),console.log(u.dim("Usage: /skill:<name> [args] or ask naturally")),console.log()}i(m_,"printSkillsListPiMonoStyle");var Do=new os;function _p(e){Do.size>0||mT(Do,e)}i(_p,"initCommandRegistry");function Uu(e){return _p(e),Do}i(Uu,"getCommandRegistry");function p_(){return pr()?.listCommands().filter(t=>t.metadata?.userInvocable!==!1)??[]}i(p_,"getActiveExtensionCommands");function ST(e){let t=pr(),n=e.trim().toLowerCase();if(!n)return;let r=t?.listCommands().find(o=>o.name.trim().toLowerCase()===n||(o.aliases??[]).some(s=>s.trim().toLowerCase()===n));if(r)return r.metadata?.userInvocable===!1?void 0:r}i(ST,"getActiveExtensionCommand");function g_(e){return e.usage??`/${e.name}`}i(g_,"formatExtensionCommandUsage");function h_(e){return Array.isArray(e)?e.map(t=>String(t)).join(", "):e&&typeof e=="object"?JSON.stringify(e):String(e)}i(h_,"formatExtensionDiagnosticValue");function y_(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0).map(([n,r])=>`${n}=${h_(r)}`);return t.length>0?t.join(" | "):void 0}i(y_,"formatExtensionDiagnosticMetadata");function ss(e){let t=e.getDiagnostics;if(typeof t=="function")return t.call(e);let n=e.getDefaults,r=typeof n=="function"?n.call(e):void 0;return{loadedExtensions:[],capabilityProviders:e.listCapabilityProviders().map(o=>({id:o.id,kinds:[...o.kinds],source:{kind:"extension",id:`extension:${o.id}`,label:o.id,path:"(runtime)"}})),commands:e.listCommands().map(o=>({name:o.name,aliases:o.aliases,description:o.description,usage:o.usage,metadata:o.metadata,source:{kind:"extension",id:`extension-command:${o.name}`,label:o.name,path:"(runtime)"}})),tools:[],hooks:[],failures:[],defaults:{activeTools:r?.activeTools,modelSelection:r?.modelSelection??{},thinkingLevel:r?.thinkingLevel}}}i(ss,"getExtensionRuntimeDiagnostics");function x_(e,t){if(t.invocation)return{prompt:t.invocation.prompt,source:"extension",displayName:t.invocation.displayName??`/${e.name}`,disableModelInvocation:t.invocation.disableModelInvocation,allowedTools:t.invocation.allowedTools,context:t.invocation.context,model:t.invocation.model}}i(x_,"toExtensionInvocationRequest");async function w_(e,t,n){let r=pr();if(!r)return console.log(u.yellow(`
285
- [Extension runtime is not active for /${e.name}]`)),!1;let o=await e.handler(t,{sessionId:n.sessionId,gitRoot:n.gitRoot,workingDirectory:n.runtimeInfo?.executionCwd??n.gitRoot??process.cwd(),reloadExtensions:i(()=>r.reloadExtensions(),"reloadExtensions"),getDiagnostics:i(()=>ss(r),"getDiagnostics"),logger:{debug:i((...a)=>console.debug(`[kodax:extension-command:${e.name}]`,...a),"debug"),info:i((...a)=>console.info(`[kodax:extension-command:${e.name}]`,...a),"info"),warn:i((...a)=>console.warn(`[kodax:extension-command:${e.name}]`,...a),"warn"),error:i((...a)=>console.error(`[kodax:extension-command:${e.name}]`,...a),"error")}});if(!o)return!0;o.message&&console.log(o.message);let s=x_(e,o);return s?{invocation:s}:!0}i(w_,"executeExtensionCommand");function as(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=n[0]?.toLowerCase(),s=n.slice(1).filter(Boolean);if(!o)return null;if(o.startsWith("skill:")){let c=o.slice(6);return c?{command:"skill",args:s,skillInvocation:{name:c}}:{command:"skill",args:s}}let a=o.indexOf(":");if(a>0){let c=o.slice(a+1).trim();o=o.slice(0,a),s=c?[c,...s]:s}return{command:o,args:s}}i(as,"parseCommand");async function cs(e,t,n,r){if(Do.size===0&&_p(t.gitRoot),e.skillInvocation)return await S_({command:e.skillInvocation.name,args:e.args},t);let o=Do.get(e.command);if(o){if(o.userInvocable===!1)return console.log(u.yellow(`
286
- [Command /${o.name} is not user-invocable]`)),!1;try{let a=await o.handler(e.args,t,n,r);return a&&typeof a=="object"?a:!0}catch(a){return console.log(u.red(`
287
- [Command failed: ${a instanceof Error?a.message:String(a)}]`)),!1}}let s=ST(e.command);if(s)try{return await w_(s,e.args,t)}catch(a){return console.log(u.red(`
288
- [Extension command failed: ${a instanceof Error?a.message:String(a)}]`)),!1}return console.log(u.yellow(`
289
- [Unknown command: /${e.command}. Type /help for available commands]`)),!1}i(cs,"executeCommand");async function S_(e,t){let n=mr(t.gitRoot),r=e.command,o=e.args.join(" ");n.size===0&&await ho(t.gitRoot);try{let s=n.get(r);if(!s)return console.log(u.red(`
290
- [Skill not found: ${r}]`)),!1;if(!s.userInvocable)return console.log(u.yellow(`
291
- [Skill "${r}" is not user-invocable]`)),!1;console.log(u.cyan(`
292
- [Invoking skill: ${r}]`)),s.argumentHint&&console.log(u.dim(`Arguments: ${o||"(none)"}`)),console.log();let a=await n.loadFull(r),c={workingDirectory:process.cwd(),projectRoot:t.gitRoot??void 0,sessionId:t.sessionId,environment:{}},l=await nx(a,o,c);return console.log(u.green(`Skill activated: ${r}`)),console.log(u.dim("The skill context has been prepared for the AI.")),console.log(),{invocation:{prompt:l.content,source:"skill",displayName:r,path:a.skillFilePath,disableModelInvocation:l.disableModelInvocation,userInvocable:a.userInvocable,allowedTools:a.allowedTools,context:a.context,agent:a.agent,argumentHint:a.argumentHint,model:a.model,hooks:a.hooks,skillInvocation:{name:r,path:a.skillFilePath,description:a.description,arguments:o||void 0,allowedTools:a.allowedTools,context:a.context,agent:a.agent,argumentHint:a.argumentHint,model:a.model,hookEvents:a.hooks?Object.entries(a.hooks).filter(([,d])=>Array.isArray(d)&&d.length>0).map(([d])=>d):void 0,expandedContent:l.content}}}}catch(s){return console.log(u.red(`
293
- [Error invoking skill: ${s instanceof Error?s.message:String(s)}]`)),!1}}i(S_,"executeSkillCommand");import{jsx as O_}from"react/jsx-runtime";import{useState as D_,useEffect as RT,useCallback as Xr,useMemo as ET,createContext as N_,useContext as MT}from"react";import*as ju from"fs";import*as Pp from"path";function zr(e){let t=e.lastIndexOf("/");if(t===-1)return-1;for(;t>0&&!/\s/.test(e[t-1]??"");)if(t=e.lastIndexOf("/",t-1),t===-1)return-1;return t}i(zr,"findCommandSlashIndex");var No=class{static{i(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;constructor(t){this.cwdSource=t}canComplete(t,n){let r=t.slice(0,n),o=r.lastIndexOf("@");return!(o===-1||o>0&&!/\s/.test(r[o-1]??"")||r.slice(o+1).includes(" "))}async getCompletions(t,n){let r=t.slice(0,n),o=r.lastIndexOf("@");if(o===-1)return[];let s=r.slice(o+1),a=[],c=this.resolveCwd(),l=s.lastIndexOf("/"),d=l===-1?c:Pp.join(c,s.slice(0,l)),m=l===-1?s:s.slice(l+1);try{let g=(await this.readdir(d)).filter(x=>x.toLowerCase().startsWith(m.toLowerCase()));for(let x of g){let y=Pp.join(d,x),T=await this.isDirectory(y),w=l===-1?x:s.slice(0,l+1)+x;a.push({text:"@"+w+(T?"/":""),display:x+(T?"/":""),description:T?"directory":"file",type:"file"})}}catch{}return a}resolveCwd(){return typeof this.cwdSource=="function"?this.cwdSource():this.cwdSource??process.cwd()}async readdir(t){let n=Date.now(),r=this.cache.get(t);return r&&r.expiresAt>n?r.entries:(r&&this.cache.delete(t),new Promise(o=>{ju.readdir(t,(s,a)=>{s?o([]):(this.cache.set(t,{entries:a,expiresAt:Date.now()+this.cacheTimeout}),o(a))})}))}async isDirectory(t){return new Promise(n=>{ju.stat(t,(r,o)=>{n(!r&&o.isDirectory())})})}},Xa=class{static{i(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Uu().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let t=pr();for(let n of t?.listCommands()??[])n.metadata?.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]})}canComplete(t,n){let r=t.slice(0,n),o=zr(r);return o===-1?!1:!r.slice(o).includes(" ")}async getCompletions(t,n){let r=t.slice(0,n),o=zr(r);if(o===-1)return[];this.commands.clear(),this.loadCommands();let s=r.slice(o+1).toLowerCase(),a=[];for(let[c,l]of this.commands){this.fuzzyMatch(s,c)&&a.push({text:"/"+c,display:"/"+c,description:l.description,type:"command"});for(let d of l.aliases)d!==c&&this.fuzzyMatch(s,d)&&a.push({text:"/"+d,display:"/"+d,description:`Alias for /${c}: ${l.description}`,type:"command"})}return a}fuzzyMatch(t,n){if(!t)return!0;let r=t.toLowerCase(),o=n.toLowerCase(),s=0;for(let a=0;a<o.length&&s<r.length;a++)o[a]===r[s]&&s++;return s===r.length}};function TT(e){let t=new No(e),n=new Xa;return async r=>{let o=r.includes("@"),s=r.includes("/");if(!o&&!s)return[[],r];let a=[];if(s&&n.canComplete(r,r.length)){let l=await n.getCompletions(r,r.length);a.push(...l)}if(o&&t.canComplete(r,r.length)){let l=await t.getCompletions(r,r.length);a.push(...l)}return[a.map(l=>l.display),r]}}i(TT,"createCompleter");var Ya=class{static{i(this,"SkillCompleter")}gitRoot;skillsCache=null;cacheTimestamp=0;CACHE_TTL=5e3;constructor(t){this.gitRoot=t}canComplete(t,n){let r=t.slice(0,n);if(!/\/skill:[^\s]*$/.test(r))return!1;let o=r.lastIndexOf("/skill:");return!(o>0&&!/\s/.test(r[o-1]??""))}async getCompletions(t,n){let o=t.slice(0,n).match(/\/skill:([^\s]*)$/);if(!o)return[];let s=(o[1]??"").toLowerCase();return(await this.getSkills()).filter(c=>{let l=c.name.toLowerCase();return l.includes(s)||this.fuzzyIncludes(s,l)}).map(c=>({text:`/skill:${c.name}`,display:c.name,description:this.truncateDescription(c.description),type:"command"})).sort((c,l)=>{let d=c.display.toLowerCase().startsWith(s),m=l.display.toLowerCase().startsWith(s);return d&&!m?-1:!d&&m?1:c.display.length-l.display.length})}setGitRoot(t){this.gitRoot!==t&&(this.gitRoot=t,this.skillsCache=null)}async getSkills(){let t=Date.now();if(this.skillsCache&&t-this.cacheTimestamp<this.CACHE_TTL)return this.skillsCache;try{let n=mr(this.gitRoot);return n.size===0&&await ho(this.gitRoot),this.skillsCache=n.listUserInvocable(),this.cacheTimestamp=t,this.skillsCache}catch{return[]}}fuzzyIncludes(t,n){let r=0;for(let o=0;o<n.length&&r<t.length;o++)n[o]===t[r]&&r++;return r===t.length}truncateDescription(t,n=50){return t.length<=n?t:t.slice(0,n-3)+"..."}};var T_=[{name:"plan",description:"Read-only planning mode - blocks all modifications",type:"enum"},{name:"accept-edits",description:"File edits auto-approved, bash requires confirmation",type:"enum"},{name:"auto-in-project",description:"All tools auto within project directory",type:"enum"}],Gu=[{name:"on",description:"Map to reasoning auto",type:"enum"},{name:"off",description:"Disable reasoning",type:"enum"},{name:"auto",description:"Use semantic routing with adaptive depth",type:"enum"},{name:"quick",description:"Low-depth reasoning mode",type:"enum"},{name:"balanced",description:"Medium-depth reasoning mode",type:"enum"},{name:"deep",description:"High-depth reasoning mode",type:"enum"}],CT=Gu.slice(2).concat([{name:"off",description:"Disable reasoning",type:"enum"}]);function C_(e){if(e&&e.includes("/")){let t=e.indexOf("/"),n=e.slice(0,t),r=e.slice(t+1);if(xi(n))try{return Ei(n).filter(s=>!r||s.toLowerCase().includes(r.toLowerCase())).map(s=>({name:`${n}/${s}`,description:s,type:"enum"}))}catch{}return[]}return wi().map(t=>({name:t,description:`Switch to ${t} provider`,type:"enum"}))}i(C_,"getModelArgs");var bT=[{name:"on",description:"Enable plan mode for all requests",type:"enum"},{name:"off",description:"Disable plan mode",type:"enum"},{name:"once",description:"Run plan mode for a single request (followed by task)",type:"enum"},{name:"list",description:"List all saved plans",type:"enum"},{name:"resume",description:"Resume a saved plan (followed by plan ID)",type:"enum"},{name:"clear",description:"Clear completed plans",type:"enum"}],$p=[{name:"workspace",description:"Inspect current workspace/runtime truth in more detail",type:"enum"},{name:"runtime",description:"Alias for workspace runtime inspection",type:"enum"},{name:"worktree",description:"Alias for workspace runtime inspection",type:"enum"}],Lp=[{name:"all",description:"Delete ALL sessions",type:"enum"}],b_=[{name:"status",description:"Inspect the current repo-intelligence runtime state",type:"enum"},{name:"warm",description:"Warm or start the local premium runtime if available",type:"enum"},{name:"mode",description:"Switch repo-intelligence runtime mode",type:"enum"},{name:"trace",description:"Toggle repo-intelligence trace output",type:"enum"},{name:"endpoint",description:"Inspect or override the local repointel daemon endpoint",type:"enum"},{name:"bin",description:"Inspect or override the local repointel command or path",type:"enum"}],v_=[{name:"auto",description:"Resolve to premium-native when available, otherwise fall back to oss",type:"enum"},{name:"off",description:"Disable repo-intelligence injection",type:"enum"},{name:"oss",description:"Use only the public OSS repo-intelligence baseline",type:"enum"},{name:"premium-shared",description:"Use premium without the native KodaX auto lane",type:"enum"},{name:"premium-native",description:"Use premium through the native KodaX bridge",type:"enum"}],I_=[{name:"on",description:"Enable repo-intelligence trace output",type:"enum"},{name:"off",description:"Disable repo-intelligence trace output",type:"enum"},{name:"toggle",description:"Toggle repo-intelligence trace output",type:"enum"}],vT=[{name:"default",description:"Clear the override and use the default value again",type:"enum"}];function k_(e){let[t=""]=e,n=t.toLowerCase(),r=e.length===1&&e[0]===""?0:e.length;return r<=1?b_:r>2?[]:n==="mode"?v_:n==="trace"?I_:n==="endpoint"?[...vT,{name:sx,description:"Default local repointel daemon endpoint",type:"string"}]:n==="bin"?vT:[]}i(k_,"getRepointelArgs");var R_=new Map([["mode",T_],["thinking",Gu],["think",Gu],["t",Gu],["reasoning",CT],["reason",CT],["plan",bT],["p",bT],["status",$p],["info",$p],["ctx",$p],["delete",Lp],["rm",Lp],["del",Lp]]),E_=new Set(["model","m"]),M_=new Set(["repointel","ri"]);function Op(e,t,n=[]){let r=e.toLowerCase();return E_.has(r)?C_(t):M_.has(r)?k_(n):R_.get(r)??[]}i(Op,"getCommandArguments");var Ku=class{static{i(this,"ArgumentCompleter")}canComplete(t,n){let r=t.slice(0,n),o=zr(r);if(o===-1)return!1;let s=r.slice(o),a=s.split(/\s+/);if(a.length>=2&&a[0]!=="")return!0;let c=s.slice(1).toLowerCase();return Op(c).length>0}async getCompletions(t,n){let r=t.slice(0,n),o=zr(r);if(o===-1)return[];let s=r.slice(o),a=s.indexOf(" "),c=(a===-1?s.slice(1):s.slice(1,a)).toLowerCase(),l=a===-1?"":s.slice(a+1),d=l?l.split(/\s+/):[""],m=d.length-1,p=(d[m]??"").toLowerCase(),g=Op(c,p,d);if(!g||g.length===0)return[];let x=new Set(d.slice(0,-1).map(T=>T.toLowerCase()));return g.filter(T=>!x.has(T.name.toLowerCase())).filter(T=>!p||T.name.includes("/")?!0:T.name.toLowerCase().includes(p)).map(T=>({text:T.name,display:T.name,description:T.description,type:"argument"})).sort((T,w)=>{let v=T.display.toLowerCase().startsWith(p),O=w.display.toLowerCase().startsWith(p);return v&&!O?-1:!v&&O?1:T.display.length-w.display.length})}};function A_(e,t){if(!e)return{matched:!0,score:0,highlights:[]};if(e.length>t.length)return{matched:!1,score:0,highlights:[]};let n=e.toLowerCase(),r=t.toLowerCase(),o=0,s=-1,a=[];for(let l=0;l<e.length;l++){let d=n[l];if(d===void 0)continue;let m=r.indexOf(d,s+1);if(m===-1)return{matched:!1,score:0,highlights:[]};m===s+1?o+=10:m===0?o+=5:o-=1,t[m]===e[l]&&(o+=2),a.push(m),s=m}let c=__(t,a);return o+=c,{matched:!0,score:o,highlights:a}}i(A_,"fuzzyMatch");function __(e,t){let n=0;for(let r of t)if(r===0)n+=3;else if(r>0){let o=e[r-1];(o===" "||o==="-"||o==="_")&&(n+=2)}return n}i(__,"calculateWordBoundaryBonus");function P_(e,t){return e?t.toLowerCase().startsWith(e.toLowerCase()):!0}i(P_,"prefixMatch");function $_(e,t){if(P_(e,t)){let o=e?Array.from({length:e.length},(s,a)=>a):[];return{matched:!0,score:100+e.length*10,highlights:o,isPrefix:!0}}return{...A_(e,t),isPrefix:!1}}i($_,"combinedMatch");function IT(e,t,n=0){return e?t.map(r=>{let o=$_(e,r.text);return{...r,_fuzzyScore:o.matched?o.score:-1,_fuzzyHighlights:o.highlights}}).filter(r=>(r._fuzzyScore??-1)>=n).sort((r,o)=>{let s=(o._fuzzyScore??0)-(r._fuzzyScore??0);return s!==0?s:r.text.length-o.text.length}):t}i(IT,"sortCandidatesCombined");var L_={debounceDelay:100,minTriggerChars:1,maxCompletions:10,minScore:0},Dp=class{static{i(this,"AutocompleteProvider")}completers;options;state;listeners=new Set;debounceTimer=null;lastInput="";lastCursorPos=0;constructor(t={}){this.options={...L_,...t},this.completers=[new Ya(this.options.gitRoot),new Ku,new Xa,new No(this.options.cwd)],this.state={visible:!1,selectedIndex:0,completions:[],loading:!1}}getOptions(){return{...this.options}}getState(){return{...this.state}}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}updateOptions(t){let n=t.gitRoot!==void 0&&t.gitRoot!==this.options.gitRoot,r=t.cwd!==void 0&&t.cwd!==this.options.cwd;if(this.options={...this.options,...t},n&&this.completers.find(s=>s instanceof Ya)?.setGitRoot(this.options.gitRoot),r){let o=this.completers.findIndex(s=>s instanceof No);o!==-1&&(this.completers[o]=new No(this.options.cwd))}}handleInput(t,n){if(this.lastInput=t,this.lastCursorPos=n,this.debounceTimer&&clearTimeout(this.debounceTimer),!this.shouldTrigger(t,n)){this.state.visible&&this.updateState({visible:!1,completions:[],selectedIndex:0});return}this.debounceTimer=setTimeout(()=>{this.fetchCompletions(t,n)},this.options.debounceDelay)}async fetchImmediate(t,n){return this.fetchCompletionsInternal(t,n)}selectPrevious(){if(!this.state.visible||this.state.completions.length===0)return;let t=this.state.selectedIndex>0?this.state.selectedIndex-1:this.state.completions.length-1;this.updateState({selectedIndex:t})}selectNext(){if(!this.state.visible||this.state.completions.length===0)return;let t=this.state.selectedIndex<this.state.completions.length-1?this.state.selectedIndex+1:0;this.updateState({selectedIndex:t})}getSelectedCompletion(){return!this.state.visible||this.state.completions.length===0?null:this.state.completions[this.state.selectedIndex]??null}acceptCompletion(){let t=this.getSelectedCompletion();return t?(this.updateState({visible:!1,completions:[],selectedIndex:0}),t.text):null}acceptCompletionWithType(){let t=this.getSelectedCompletion();return t?(this.updateState({visible:!1,completions:[],selectedIndex:0}),{text:t.text,type:t.type}):null}cancel(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.state.visible&&this.updateState({visible:!1,completions:[],selectedIndex:0})}shouldTrigger(t,n){if(t.length<this.options.minTriggerChars)return!1;let r=t.slice(0,n),s=zr(r)!==-1,a=r.lastIndexOf("@"),c=a===0||a>0&&/\s/.test(r[a-1]??"");return s||c}fetchCompletions(t,n){this.updateState({loading:!0}),this.fetchCompletionsInternal(t,n).then(r=>{this.lastInput!==t||this.lastCursorPos!==n||(r.length>0?this.updateState({visible:!0,completions:r.slice(0,this.options.maxCompletions),selectedIndex:0,loading:!1}):this.updateState({visible:!1,completions:[],selectedIndex:0,loading:!1}))}).catch(()=>{this.updateState({loading:!1})})}async fetchCompletionsInternal(t,n){let r=this.completers.filter(l=>l.canComplete(t,n));if(r.length===0)return[];let o=[];for(let l of r)try{let d=await l.getCompletions(t,n);o.push(...d)}catch(d){console.error("[Autocomplete] Completer error:",d)}let s=this.extractPattern(t,n),a=o.map((l,d)=>({_idx:d,text:l.type==="command"&&l.display.startsWith("/")?l.display.slice(1):l.display}));return IT(s,a,this.options.minScore).map(l=>o[l._idx]).filter(l=>l!==void 0)}extractPattern(t,n){let r=t.slice(0,n),o=zr(r);if(o!==-1){let c=r.slice(o),l=c.match(/^\/skill:(\S*)$/);if(l)return l[1]??"";let d=c.match(/^\/(\S*)$/);if(d)return d[1]??"";let m=c.split(/\s+/);return(m[m.length-1]??"").toLowerCase()}let s=r.lastIndexOf("@");if(s!==-1){let c=r.slice(s+1),l=c.lastIndexOf("/");return l===-1?c:c.slice(l+1)}let a=r.match(/(\S+)$/);return a?a[1]??"":""}updateState(t){this.state={...this.state,...t};for(let n of this.listeners)try{n(this.state)}catch(r){console.error("[Autocomplete] Listener error:",r)}}};function kT(e){return new Dp(e)}i(kT,"createAutocompleteProvider");var Np=N_(null);function Bp({children:e,cwd:t,gitRoot:n}){let r=Vu({cwd:t,gitRoot:n,enabled:!0});return O_(Np.Provider,{value:r,children:e})}i(Bp,"AutocompleteContextProvider");function Bo(){return MT(Np)}i(Bo,"useAutocompleteContext");function B_(e,t){let n={command:"command",file:"file",argument:"argument",skill:"skill"},r={command:"\u26A1",file:"\u{1F4C4}",argument:"\u2022",skill:"\u2605"};return{id:`autocomplete-${t}`,text:e.text,displayText:e.display,description:e.description,type:n[e.type]??"command",icon:r[e.type]??">"}}i(B_,"completionToSuggestion");function Vu(e={}){let t=MT(Np);return t&&!e.cwd&&!e.gitRoot?t:H_(e)}i(Vu,"useAutocomplete");function H_(e){let{cwd:t,gitRoot:n,enabled:r=!0}=e,o=ET(()=>kT({cwd:t,gitRoot:n,debounceDelay:100,minTriggerChars:1,maxCompletions:8}),[]);RT(()=>{o.updateOptions({cwd:t,gitRoot:n})},[o,t,n]);let[s,a]=D_({visible:!1,selectedIndex:0,completions:[],loading:!1});RT(()=>o.subscribe(v=>{a(v)}),[o]);let c=ET(()=>s.completions.map((w,v)=>B_(w,v)),[s.completions]),l=Xr((w,v)=>{if(!r){o.cancel();return}o.handleInput(w,v)},[o,r]),d=Xr(()=>s.visible?o.acceptCompletionWithType():null,[o,s.visible]),m=Xr(()=>s.visible?o.acceptCompletionWithType():null,[o,s.visible]),p=Xr(()=>{s.visible&&o.selectPrevious()},[o,s.visible]),g=Xr(()=>{s.visible&&o.selectNext()},[o,s.visible]),x=Xr(()=>{s.visible&&o.cancel()},[o,s.visible]),y=Xr(()=>{o.cancel()},[o]),T=Xr(()=>o,[o]);return{state:s,suggestions:c,handleInput:l,handleTab:d,handleEnter:m,handleUp:p,handleDown:g,handleEscape:x,cancel:y,getProvider:T}}i(H_,"useAutocompleteImpl");import{useCallback as qa,useRef as AT}from"react";var bn=[];function Hp(e={}){let{maxSize:t=1e3,onSave:n}=e,r=AT(-1),o=AT(""),s=qa((m,p)=>{if(!m.trim())return;if(bn[bn.length-1]?.text!==m){let x={text:m,timestamp:Date.now(),...p?.pastedContents&&p.pastedContents.length>0?{pastedContents:[...p.pastedContents]}:{}};bn.push(x),bn.length>t&&bn.splice(0,bn.length-t),n?.(x)}r.current=-1,o.current=""},[t,n]),a=qa(()=>bn.length===0?null:r.current===-1?(r.current=bn.length-1,bn[r.current]??null):r.current>0?(r.current--,bn[r.current]??null):null,[]),c=qa(()=>r.current===-1?null:r.current<bn.length-1?(r.current++,bn[r.current]??null):(r.current=-1,{text:o.current,timestamp:Date.now()}),[]),l=qa(()=>{r.current=-1,o.current=""},[]),d=qa(m=>{r.current===-1&&(o.current=m)},[]);return{add:s,navigateUp:a,navigateDown:c,reset:l,saveTempInput:d}}i(Hp,"useInputHistory");function Qt(e,t,n){return Vt(e).slice(t,n).join("")}i(Qt,"sliceByCodePoints");var Qa=class{static{i(this,"TextBuffer")}_text="";_lines=[""];_cursor={row:0,col:0};_rememberedCol=0;_history=[];_historyIndex=-1;_maxHistory;constructor(t={}){this._maxHistory=t.maxHistory??100}get text(){return this._text}get lines(){return[...this._lines]}get cursor(){return{...this._cursor}}get lineCount(){return this._lines.length}get currentLine(){return this._lines[this._cursor.row]??""}get isEmpty(){return this._text.length===0}get currentLineVisualWidth(){return Xn(this.currentLine)}get visualCursor(){let t=this._lines[this._cursor.row]??"",n=Qt(t,0,this._cursor.col);return{row:this._cursor.row,col:Xn(n)}}getCharWidthAtCursor(){let t=this._lines[this._cursor.row]??"",r=Vt(t)[this._cursor.col];return r?zn(r)?2:1:0}visualColToLogicalCol(t){let n=this._lines[this._cursor.row]??"",r=Vt(n),o=0;for(let s=0;s<r.length;s++){let a=zn(r[s])?2:1;if(o+a>t)return s;o+=a}return r.length}moveToVisualCol(t){this._cursor.col=this.visualColToLogicalCol(t),this._rememberedCol=this._cursor.col}setText(t){this._saveHistory(),this._setTextInternal(t),this._clampCursor()}replaceRange(t,n,r){this._saveHistory();let o=Math.max(0,Math.min(t,this._text.length)),s=Math.max(o,Math.min(n,this._text.length)),a=this._text.slice(0,o)+r+this._text.slice(s);this._setTextInternal(a),this.moveToAbsoluteOffset(o+r.length)}insert(t,n){if(this._saveHistory(),n?.paste){this._insertText(t);return}let r=t.split(`
294
- `);for(let o=0;o<r.length;o++)o>0&&this._insertNewline(),this._insertText(r[o])}_insertText(t){let n=this._lines[this._cursor.row],r=Qt(n,0,this._cursor.col),o=Qt(n,this._cursor.col);this._lines[this._cursor.row]=r+t+o,this._cursor.col+=rn(t),this._rememberedCol=this._cursor.col,this._updateText()}newline(){this._saveHistory(),this._insertNewline()}_insertNewline(){let t=this._lines[this._cursor.row],n=Qt(t,0,this._cursor.col),r=Qt(t,this._cursor.col);this._lines[this._cursor.row]=n,this._lines.splice(this._cursor.row+1,0,r),this._cursor.row++,this._cursor.col=0,this._rememberedCol=0,this._updateText()}backspace(){if(this._cursor.col>0){this._saveHistory();let t=this._lines[this._cursor.row],n=this._cursor.col-1,r=Qt(t,0,n),o=Qt(t,this._cursor.col);this._lines[this._cursor.row]=r+o,this._cursor.col=n,this._rememberedCol=this._cursor.col,this._updateText()}else if(this._cursor.row>0){this._saveHistory();let t=this._lines[this._cursor.row],n=this._lines[this._cursor.row-1];this._cursor.col=rn(n),this._lines[this._cursor.row-1]=n+t,this._lines.splice(this._cursor.row,1),this._cursor.row--,this._rememberedCol=this._cursor.col,this._updateText()}}delete(){let t=this._lines[this._cursor.row];if(this._cursor.col<rn(t)){this._saveHistory();let n=Qt(t,0,this._cursor.col),r=Qt(t,this._cursor.col+1);this._lines[this._cursor.row]=n+r,this._updateText()}else if(this._cursor.row<this._lines.length-1){this._saveHistory();let n=this._lines[this._cursor.row+1];this._lines[this._cursor.row]=t+n,this._lines.splice(this._cursor.row+1,1),this._updateText()}}move(t){switch(t){case"up":this._moveUp();break;case"down":this._moveDown();break;case"left":this._moveLeft();break;case"right":this._moveRight();break;case"home":this._moveHome();break;case"end":this._moveEnd();break}}_moveUp(){this._cursor.row>0&&(this._cursor.row--,this._clampColumn())}_moveDown(){this._cursor.row<this._lines.length-1&&(this._cursor.row++,this._clampColumn())}_moveLeft(){this._cursor.col>0?(this._cursor.col--,this._rememberedCol=this._cursor.col):this._cursor.row>0&&(this._cursor.row--,this._cursor.col=rn(this._lines[this._cursor.row]),this._rememberedCol=this._cursor.col)}_moveRight(){let t=this._lines[this._cursor.row];this._cursor.col<rn(t)?(this._cursor.col++,this._rememberedCol=this._cursor.col):this._cursor.row<this._lines.length-1&&(this._cursor.row++,this._cursor.col=0,this._rememberedCol=0)}_moveHome(){this._cursor.col=0,this._rememberedCol=0}_moveEnd(){this._cursor.col=rn(this._lines[this._cursor.row]),this._rememberedCol=this._cursor.col}_clampColumn(){let t=this._lines[this._cursor.row],n=rn(t);this._cursor.col=Math.min(this._rememberedCol,n)}_clampCursor(){this._cursor.row=Math.max(0,Math.min(this._cursor.row,this._lines.length-1)),this._cursor.col=Math.max(0,Math.min(this._cursor.col,rn(this._lines[this._cursor.row]))),this._rememberedCol=this._cursor.col}killLineRight(){let t=this._lines[this._cursor.row];this._cursor.col<rn(t)&&(this._saveHistory(),this._lines[this._cursor.row]=Qt(t,0,this._cursor.col),this._updateText())}killLineLeft(){if(this._cursor.col>0){this._saveHistory();let t=this._lines[this._cursor.row];this._lines[this._cursor.row]=Qt(t,this._cursor.col),this._cursor.col=0,this._rememberedCol=0,this._updateText()}}deleteWordLeft(){if(this._cursor.col===0)return;this._saveHistory();let t=this._lines[this._cursor.row],n=this._cursor.col-1,r=Vt(t);for(;n>0&&/\s/.test(r[n]??"");)n--;for(;n>0&&!/\s/.test(r[n-1]??"");)n--;let o=Qt(t,0,n),s=Qt(t,this._cursor.col);this._lines[this._cursor.row]=o+s,this._cursor.col=n,this._rememberedCol=this._cursor.col,this._updateText()}_saveHistory(){this._history=this._history.slice(0,this._historyIndex+1),this._history.push(this._text),this._history.length>this._maxHistory&&this._history.shift(),this._historyIndex=this._history.length-1}undo(){return this._historyIndex>0?(this._historyIndex--,this._text=this._history[this._historyIndex]??"",this._lines=this._text.split(`
295
- `),this._lines.length===0&&(this._lines=[""]),this._clampCursor(),!0):!1}redo(){return this._historyIndex<this._history.length-1?(this._historyIndex++,this._text=this._history[this._historyIndex]??"",this._lines=this._text.split(`
296
- `),this._lines.length===0&&(this._lines=[""]),this._clampCursor(),!0):!1}_updateText(){this._text=this._lines.join(`
297
- `)}_setTextInternal(t){this._text=t,this._lines=t.split(`
298
- `),this._lines.length===0&&(this._lines=[""])}moveToAbsoluteOffset(t){let r=Math.max(0,Math.min(t,this._text.length));for(let o=0;o<this._lines.length;o++){let s=this._lines[o]??"",a=s.length;if(r<=a){this._cursor={row:o,col:rn(s.slice(0,r))},this._rememberedCol=this._cursor.col;return}r-=a,o<this._lines.length-1&&(r-=1)}this.moveToEnd()}clear(){this._saveHistory(),this._text="",this._lines=[""],this._cursor={row:0,col:0},this._rememberedCol=0}getAbsoluteOffset(){let t=0;for(let r=0;r<this._cursor.row;r++)t+=(this._lines[r]?.length??0)+1;let n=this._lines[this._cursor.row]??"";return t+=Qt(n,0,this._cursor.col).length,t}isLineContinuation(){return this._lines[this._cursor.row].endsWith("\\")}moveToEnd(){this._cursor.row=this._lines.length-1,this._cursor.col=rn(this._lines[this._cursor.row]??""),this._rememberedCol=this._cursor.col}};import{useState as F_,useCallback as vt,useRef as Fp,useEffect as W_}from"react";function Wp(e={}){let{initialValue:t="",onTextChange:n}=e,r=Fp(null),o=Fp(null),s=Fp(null),[a,c]=F_({text:t,cursor:{row:0,col:0},lines:[""],isPasting:!1,editingMode:t?"typing":"idle"});r.current===null&&(r.current=new Qa,t&&r.current.setText(t)),o.current===null&&(o.current=aT());let l=r.current,d=o.current,m=vt(M=>{c(C=>({text:l.text,cursor:l.cursor,lines:l.lines,isPasting:M?.isPasting??C.isPasting,editingMode:M?.editingMode??C.editingMode})),n?.(l.text)},[l,n]),p=vt(()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{c(M=>({...M,isPasting:!1,editingMode:M.text?"typing":"idle"})),s.current=null},120)},[]),g=vt(M=>{l.setText(M),m({isPasting:!1,editingMode:M?"typing":"idle"})},[l,m]),x=vt((M,C,Z)=>{l.replaceRange(M,C,Z),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),y=vt((M,C)=>{let Z=C?.paste??!1;if(Z&&iT(M)){let ke=M.replace(/\r\n/g,`
299
- `).replace(/\r/g,`
300
- `),{placeholder:ve}=d.registerText(ke);l.insert(ve,{paste:!0}),m({isPasting:!0,editingMode:"pasting"}),p();return}l.insert(M,{paste:!1}),m({isPasting:Z,editingMode:Z?"pasting":"typing"}),Z&&p()},[l,d,p,m]),T=vt(()=>{l.newline(),m({isPasting:!1,editingMode:"typing"})},[l,m]),w=vt(()=>{let M=l.getAbsoluteOffset(),C=Du(l.text,M);C?l.replaceRange(C.start,C.end,""):l.backspace(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),v=vt(()=>{let M=l.getAbsoluteOffset(),C=Nu(l.text,M);C?l.replaceRange(C.start,C.end,""):l.delete(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),O=vt(M=>{l.move(M),m()},[l,m]),P=vt(()=>{l.clear(),m({isPasting:!1,editingMode:"idle"})},[l,m]),D=vt(()=>{let M=l.undo();return M&&m(),M},[l,m]),L=vt(()=>{let M=l.redo();return M&&m(),M},[l,m]),X=vt(()=>{l.moveToEnd(),m()},[l,m]),I=vt(M=>{l.moveToAbsoluteOffset(M),m()},[l,m]),ie=vt(()=>{l.killLineRight(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),Te=vt(()=>{l.killLineLeft(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),K=vt(()=>{l.deleteWordLeft(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),q=vt(()=>{s.current&&(clearTimeout(s.current),s.current=null),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]);return W_(()=>()=>{s.current&&clearTimeout(s.current),r.current=null},[]),{buffer:l,text:a.text,cursor:a.cursor,lines:a.lines,isPasting:a.isPasting,editingMode:a.editingMode,pasteStore:d,resetTransientState:q,setText:g,replaceRange:x,insert:y,newline:T,backspace:w,delete:v,move:O,moveToEnd:X,moveToOffset:I,killLineRight:ie,killLineLeft:Te,deleteWordLeft:K,clear:P,undo:D,redo:L}}i(Wp,"useTextBuffer");import{jsx as Ho,jsxs as Xu}from"react/jsx-runtime";import{useState as LT}from"react";import{useCallback as ls,useEffect as Up,useRef as zu}from"react";function _T(e,t,n){let r=Math.max(0,Math.min(t,e.length)),o=e.slice(0,r);if(n.type==="command"||n.type==="skill"){let a=o.lastIndexOf("/");return{start:a===-1?0:a,end:r,replacement:n.text}}if(n.type==="argument"){let a=o.match(/\S+$/);return{start:a?r-a[0].length:0,end:r,replacement:n.text}}let s=o.lastIndexOf("@");return{start:s===-1?0:s,end:r,replacement:n.text}}i(_T,"buildAutocompleteReplacement");var j_=500;function PT(e,t,n){return n==="up"?e===0:e>=Math.max(0,t-1)}i(PT,"shouldUseHistoryNavigation");function G_(e){return e.isAutocompleteVisible?"cancel-autocomplete":e.hasText?e.timeSinceLastEscapeMs<j_?"clear-input":"arm-clear":"pass-through"}i(G_,"resolvePromptEscapeBehavior");function K_(e){return e.keyName==="newline"||e.keyName==="return"&&(e.ctrl||e.shift)||e.isPasting?"newline":e.isAutocompleteVisible?"accept-completion-and-submit":e.isLineContinuation?"line-continuation":"submit"}i(K_,"resolvePromptEnterBehavior");function V_(e){if(e.meta&&e.name==="backspace")return"delete-word-left";if(e.ctrl)switch(e.name){case"a":return"move-home";case"e":return"move-end";case"z":return"undo";case"y":return"redo";case"k":return"kill-line-right";case"u":return"kill-line-left";case"w":return"delete-word-left";default:return}}i(V_,"resolvePromptEditingCommand");function $T({onSubmit:e,onExit:t,focus:n=!0,initialValue:r="",cwd:o,gitRoot:s,autocompleteEnabled:a=!0,onInputChange:c,onHistoryRecall:l,onPopPendingInputs:d}){let m=zu(0),{add:p,navigateUp:g,navigateDown:x,reset:y,saveTempInput:T}=Hp(),{buffer:w,text:v,cursor:O,lines:P,isPasting:D,editingMode:L,pasteStore:X,resetTransientState:I,setText:ie,replaceRange:Te,clear:K,move:q,moveToOffset:M,insert:C,backspace:Z,newline:ke,delete:ve,undo:Se,redo:ce,killLineRight:De,killLineLeft:ae,deleteWordLeft:Y}=Wp({initialValue:r,onTextChange:c}),Q=zu(0);Up(()=>{if(D)return;if(v.length<=1e4){Q.current=0;return}if(v.length===Q.current)return;let V=X.peekNextId(),{truncatedText:fe,placeholderContent:F}=sT(v,V);F&&(X.registerTruncatedText(F),Q.current=fe.length,ie(fe))},[v,D,X,ie]);let Ce=Bo(),be=Vu({cwd:o,gitRoot:s,enabled:a}),{state:at,suggestions:Re,handleInput:Ue,handleTab:xe,handleEnter:kt,handleUp:qe,handleDown:ee,handleEscape:A}=Ce??be;Up(()=>{n||(m.current=0,I(),at.visible&&A())},[at.visible,n,A,I]);let _=zu(v);Up(()=>{a&&v!==_.current&&(_.current=v,Ue(v,w.getAbsoluteOffset()))},[a,w,Ue,v]);let W=ls(V=>{if(!V?.text)return;let fe=_T(v,w.getAbsoluteOffset(),V),F=v.slice(0,fe.start)+fe.replacement+v.slice(fe.end);return Te(fe.start,fe.end,fe.replacement),F},[w,Te,v]),J=ls(V=>{let fe=V??v;if(!fe.trim())return;let F=X.expand(fe),_e=new Set,Tt=/\[(Pasted text|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/g;for(let _s of fe.matchAll(Tt)){let Bn=Number.parseInt(_s[2]??"0",10);Number.isFinite(Bn)&&Bn>0&&_e.add(Bn)}let kr=[];for(let _s of _e){let Bn=X.get(_s);Bn&&kr.push(Bn)}p(fe,{pastedContents:kr}),e({displayText:fe,fullText:F,pastedContents:kr}),K()},[p,K,e,X,v]),Ne=ls(V=>{if(V){if(V.pastedContents&&V.pastedContents.length>0){for(let fe of V.pastedContents)X.adopt(fe);l?.({text:V.text,pastedContents:[...V.pastedContents]})}ie(V.text)}},[l,X,ie]),et=ls(async V=>{try{let fe=await Mx(V);if(fe.kind==="images"){let F=fe.blocks.map(_e=>`@${_e.path}`).join(" ");C(`${F} `,{paste:!1})}else fe.kind==="error"&&console.warn(`[KodaX paste] ${fe.message}`)}catch(fe){console.warn(`[KodaX paste] image handling failed: ${fe instanceof Error?fe.message:String(fe)}`)}},[C]),Ie=zu(!1),Le=ls(async()=>{if(!Ie.current){Ie.current=!0;try{let V=await Ax();if(V.kind==="images"){let fe=V.blocks.map(F=>`@${F.path}`).join(" ");C(`${fe} `,{paste:!1})}else V.kind==="error"&&console.warn(`[KodaX clipboard] ${V.message}`)}catch(V){console.warn(`[KodaX clipboard] image handling failed: ${V instanceof Error?V.message:String(V)}`)}finally{Ie.current=!1}}},[C]),Kt=ls(V=>{if(!n)return!1;if(V.name==="v"&&(V.ctrl||V.meta))return Le(),!0;if(V.name==="paste"&&V.isPasted&&_x(V.sequence).length>0)return et(V.sequence),!0;let fe=at.visible&&Re.length>0;if(V.name==="tab"&&fe){let _e=xe();return _e&&W(_e),!0}if(V.ctrl&&V.name==="c")return v.length>0?(K(),y()):t?.(),!0;if(V.name==="escape")switch(G_({isAutocompleteVisible:fe,hasText:v.length>0,timeSinceLastEscapeMs:Date.now()-m.current})){case"cancel-autocomplete":return A(),m.current=0,!0;case"clear-input":return m.current=0,K(),y(),!0;case"arm-clear":return m.current=Date.now(),!0;default:return!1}if(V.name==="up"){if(fe)return qe(),!0;if(V.ctrl)return q("up"),!0;if(v.length===0&&d){let _e=d();if(typeof _e=="string"&&_e.length>0)return ie(_e),!0}if(PT(O.row,P.length,"up")){T(v);let _e=g();Ne(_e)}else q("up");return!0}if(V.name==="down"){if(fe)return ee(),!0;if(V.ctrl)return q("down"),!0;if(PT(O.row,P.length,"down")){let _e=x();Ne(_e)}else q("down");return!0}if(V.name==="left"){let _e=w.getAbsoluteOffset(),Tt=Du(w.text,_e);return Tt?M(Tt.start):q("left"),!0}if(V.name==="right"){let _e=w.getAbsoluteOffset(),Tt=Nu(w.text,_e);return Tt?M(Tt.end):q("right"),!0}if(V.name==="home")return q("home"),!0;if(V.name==="end")return q("end"),!0;let F=V_(V);if(F)switch(F){case"move-home":return q("home"),!0;case"move-end":return q("end"),!0;case"undo":return Se(),!0;case"redo":return ce(),!0;case"kill-line-right":return De(),!0;case"kill-line-left":return ae(),!0;case"delete-word-left":return Y(),!0;default:break}if(V.name==="backspace")return Z(),!0;if(V.name==="delete")return ve(),!0;if(V.name==="return"||V.name==="newline")switch(K_({keyName:V.name,ctrl:V.ctrl,shift:V.shift,isAutocompleteVisible:fe,isLineContinuation:!!P[O.row]?.endsWith("\\"),isPasting:D})){case"accept-completion-and-submit":{let Tt=kt();if(Tt){let kr=W(Tt);J(kr)}else J();return!0}case"newline":return ke(),!0;case"line-continuation":return Z(),ke(),!0;default:return J(),!0}return V.insertable&&!V.ctrl&&!V.meta?(C(V.sequence,V.isPasted?{paste:!0}:void 0),!0):!1},[W,p,at.visible,Z,w,K,O.row,ve,n,ee,A,qe,kt,Ne,xe,et,Le,P,ae,De,q,M,x,g,ke,t,d,ce,y,T,ie,J,Re.length,v.length,Y,D,Se]);return{text:v,cursor:O,lines:P,isPasting:D,terminalFocused:n,editingMode:L,handleKey:Kt}}i($T,"usePromptInputController");var us=i(({onSubmit:e,onHistoryRecall:t,onPopPendingInputs:n,placeholder:r="Type a message...",prompt:o=">",focus:s=!0,initialValue:a="",cwd:c,gitRoot:l,autocompleteEnabled:d=!0,onInputChange:m})=>{let{exit:p}=Ur(),{cursor:g,lines:x,handleKey:y,isPasting:T,terminalFocused:w,editingMode:v}=$T({onSubmit:e,onExit:p,focus:s,initialValue:a,cwd:c,gitRoot:l,autocompleteEnabled:d,onInputChange:m,onHistoryRecall:t,onPopPendingInputs:n});return sn(Nt.High,O=>y(O),[y]),Ho(k,{flexDirection:"column",children:Ho(Jm,{lines:x,cursorRow:g.row,cursorCol:g.col,prompt:o,placeholder:r,focus:s,terminalFocused:w,isPasting:T,editingMode:v,theme:"dark"})})},"InputPrompt"),z_=i(({onSubmit:e,placeholder:t,prompt:n=">"})=>{let[r,o]=LT(""),[s,a]=LT(0);sn(Nt.High,p=>{if(p.name==="return")return r.trim()&&(e(r),o(""),a(0)),!0;if(p.name==="backspace"&&s>0){let g=[...r].slice(0,s-1).join(""),x=[...r].slice(s).join("");return o(g+x),a(s-1),!0}if(p.name==="left"&&s>0)return a(s-1),!0;if(p.name==="right"&&s<[...r].length)return a(s+1),!0;if(p.insertable&&!p.ctrl&&!p.meta){let g=[...r].slice(0,s).join(""),x=[...r].slice(s).join("");return o(g+p.sequence+x),a(s+1),!0}return!1},[r,s,e]);let c=ne("dark");if(!r)return Xu(k,{children:[Xu(b,{color:c.colors.primary,children:[n," "]}),t&&Ho(b,{dimColor:!0,children:t}),Ho(b,{backgroundColor:c.colors.primary,color:"#000000",children:" "})]});let l=[...r].slice(0,s).join(""),d=[...r][s]??" ",m=[...r].slice(s+1).join("");return Xu(k,{children:[Xu(b,{color:c.colors.primary,children:[n," "]}),Ho(b,{children:l}),Ho(b,{backgroundColor:c.colors.primary,color:"#000000",children:d}),Ho(b,{children:m})]})},"SimpleInputPrompt");import{jsx as it,jsxs as Mt}from"react/jsx-runtime";import{useState as DT,useEffect as NT}from"react";var OT=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],X_=80,Yu=new Set,Ja=null;function Y_(){let e=Array.from(Yu);for(let t of e)t()}i(Y_,"dispatchSharedSpinnerTick");function q_(e){return Yu.add(e),Ja===null&&(Ja=setInterval(Y_,X_)),()=>{Yu.delete(e),Yu.size===0&&Ja!==null&&(clearInterval(Ja),Ja=null)}}i(q_,"subscribeToSharedSpinnerClock");function BT(e=!0){let[t,n]=DT(0);return NT(()=>{if(e)return q_(()=>{n(r=>r+1)})},[e]),t}i(BT,"useSharedSpinnerTick");var vn=i(({color:e,theme:t})=>{let n=t??ne("dark"),o=BT(!0)%OT.length,s=e??n.colors.accent;return it(b,{color:s,children:OT[o]})},"Spinner");function Q_(e){return e<=0?0:Math.round(e/4)}i(Q_,"estimateOutputTokens");function J_(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;return n===0?`${r}m${o}s`:`${n}h${r}m${o}s`}i(J_,"formatElapsedDuration");var HT=i(({roundStartedAt:e,charCount:t,theme:n})=>{let r=n??ne("dark");if(BT(e!==null),e===null)return null;let o=Z_(Date.now()-e,t);return it(b,{color:r.colors.dim,children:o})},"SpinnerStatsTail");function Z_(e,t){let n=J_(e),r=Q_(t);return r>0?` (${n} \xB7 \u2193 ${r} tokens)`:` (${n})`}i(Z_,"buildSpinnerStatsText");var FT=i(({label:e,dotCount:t=3,theme:n})=>{let r=n??ne("dark"),[o,s]=DT(1);NT(()=>{let c=setInterval(()=>{s(l=>l%t+1)},300);return()=>clearInterval(c)},[t]);let a=".".repeat(o);return Mt(k,{children:[e&&it(b,{color:r.colors.text,children:e}),it(b,{color:r.colors.accent,children:a})]})},"DotsIndicator"),WT=i(({progress:e,label:t,width:n=20,theme:r})=>{let o=r??ne("dark"),s=Math.max(0,Math.min(100,e)),a=Math.round(s/100*n),c=n-a,l="\u2588".repeat(a),d="\u2591".repeat(c);return Mt(k,{flexDirection:"column",children:[t&&it(k,{marginBottom:1,children:it(b,{color:o.colors.text,children:t})}),Mt(k,{children:[it(b,{color:o.colors.primary,children:l}),it(b,{dimColor:!0,children:d}),Mt(b,{children:[" ",s,"%"]})]})]})},"ProgressIndicator"),eP=i(({message:e,showSpinner:t=!1,theme:n})=>{let r=n??ne("dark"),o=e??"Thinking";return Mt(k,{children:[t&&it(k,{marginRight:1,children:it(vn,{theme:r})}),Mt(b,{color:r.colors.accent,children:[o,"\u2026"]})]})},"ThinkingIndicator"),tP=i(({message:e,subMessage:t,progress:n,type:r="spinner",compact:o=!1,theme:s})=>{let a=s??ne("dark"),c=e??"Loading";return o?Mt(k,{children:[it(vn,{theme:a}),Mt(b,{color:a.colors.text,children:[" ",c,"\u2026"]})]}):r==="bar"&&n!==void 0?Mt(k,{flexDirection:"column",children:[it(WT,{progress:n,label:c,theme:a}),t&&it(k,{marginTop:1,children:it(b,{dimColor:!0,children:t})})]}):r==="dots"?Mt(k,{flexDirection:"column",children:[it(FT,{label:c,theme:a}),t&&it(k,{marginTop:1,children:it(b,{dimColor:!0,children:t})})]}):r==="simple"?Mt(k,{flexDirection:"column",children:[Mt(b,{color:a.colors.accent,children:[c,"\u2026"]}),t&&it(k,{marginTop:1,children:it(b,{dimColor:!0,children:t})}),n!==void 0&&it(k,{marginTop:1,children:Mt(b,{dimColor:!0,children:[n,"%"]})})]}):Mt(k,{flexDirection:"column",children:[Mt(k,{children:[it(vn,{theme:a}),Mt(b,{color:a.colors.text,children:[" ",c,"\u2026"]}),n!==void 0&&Mt(b,{dimColor:!0,children:[" (",n,"%)"]})]}),t&&it(k,{marginTop:1,children:it(b,{dimColor:!0,children:t})})]})},"LoadingIndicator");import{jsx as de,jsxs as Fe,Fragment as tg}from"react/jsx-runtime";import{useEffect as fC,useMemo as nr,memo as an}from"react";import*as ec from"node:path";function Za(e){if(qy(e)){let t=Qy(e);return t?`[memory:${t}]`:"[memory]"}if(nP(e))return"[memory]"}i(Za,"memoryBadgeFor");function nP(e){let t=ec.resolve(e),n=gn("projects");if(!t.startsWith(n+ec.sep)&&t!==n)return!1;let o=t.slice(n.length+1).split(ec.sep);return o.length>=2&&o[1]==="memory"}i(nP,"isInsideAnyMemoryDir");function Ve(e,t=120){return e.length>t?`${e.slice(0,t-3)}...`:e}i(Ve,"truncateValue");function UT(e){if(e)return e.split(/\r?\n/).map(t=>t.trim()).find(Boolean)}i(UT,"extractFirstMeaningfulLine");function KT(e){let t=e.match(/^\[([^\]]+)\]\s+(.*)$/);if(!t)return{toolLabel:e};let n=t[1]?.trim(),r=t[2]?.trim()??e,o=new RegExp(`^${n?.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:`,"i"),s=r.replace(o,"").trim();return{rolePrefix:n?`[${n}]`:void 0,toolLabel:s||r}}i(KT,"splitDisplayToolName");function qu(e){let{rolePrefix:t,toolLabel:n}=KT(e);return t?`${t} ${n}`:n}i(qu,"normalizeDisplayToolName");function Gp(e){return KT(e).toolLabel}i(Gp,"stripRolePrefix");function Qu(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(Qu,"asRecord");function VT(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(VT,"readString");function wt(e,...t){for(let n of t){let r=VT(e?.[n]);if(r)return r}}i(wt,"readFirstString");function er(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e.trim());return Number.isFinite(t)?t:void 0}}i(er,"readNumber");function zT(e){if(!Array.isArray(e))return;let t=e.map(n=>typeof n=="string"?n.trim():"").filter(Boolean);return t.length>0?t:void 0}i(zT,"readStringArray");function rP(e){if(typeof e=="string")return e.trim()||void 0;let t=Qu(e);if(t)return VT(t.preview)??void 0}i(rP,"extractPreview");function jT(e){if(e)try{return Qu(JSON.parse(e))}catch{return}}i(jT,"parsePreviewRecord");function $e(e,t){return e&&e.match(new RegExp(`"${t}"\\s*:\\s*"([^"]+)`))?.[1]?.trim()||void 0}i($e,"extractFieldFromPreview");function tr(e,t){if(!e)return;let n=e.match(new RegExp(`"${t}"\\s*:\\s*(\\d+)`));return n?.[1]?Number(n[1]):void 0}i(tr,"extractNumberFromPreview");function XT(e){if(!e)return;let t=e.match(/"paths"\s*:\s*\[([^\]]*)/);if(!t?.[1])return;let n=Array.from(t[1].matchAll(/"([^"]+)"/g)).map(r=>r[1]?.trim()??"").filter(Boolean);return n.length>0?n:void 0}i(XT,"extractPathsFromPreview");function oP(e){let t=rP(e);if(typeof e=="string")return{record:jT(t),preview:t};let n=Qu(e),r=jT(t);return n?r?{record:{...n,...r},preview:t}:{record:n,preview:t}:{record:r,preview:t}}i(oP,"resolveInputRecord");function ds(e,t,n,r=!1){let o=wt(t,"path","target_path","targetPath")??$e(n,"path")??$e(n,"target_path")??$e(n,"targetPath"),s=zT(t?.paths)??XT(n);if(r&&s?.length){if(s.length===1){let a=Za(s[0]);a&&e.push(a),e.push(Ve(s[0]))}else e.push(`${s.length} files`);return}if(o){let a=Za(o);a&&e.push(a),e.push(Ve(o));return}if(s?.length)if(s.length===1){let a=Za(s[0]);a&&e.push(a),e.push(Ve(s[0]))}else e.push(`${s.length} files`)}i(ds,"pushPathSummary");function fs(e,t,n){n!==void 0&&e.push(`${t}=${n}`)}i(fs,"pushNumericSummary");function jp(e,t,n){let r=wt(t,"baseRef","base_ref")??$e(n,"baseRef")??$e(n,"base_ref"),o=wt(t,"targetRef","target_ref")??$e(n,"targetRef")??$e(n,"target_ref");r&&o&&e.push(Ve(`${r}...${o}`,88))}i(jp,"pushRangeSummary");function iP(e,t){let{record:n,preview:r}=oP(t),o=Gp(e).toLowerCase(),s=[];if(o.includes("changed_diff_bundle")){let a=zT(n?.paths)??XT(r);a?.length?(s.push(a.length===1?Ve(a[0]):`${a.length} files`),a.length>1&&s.push(Ve(a[0]))):ds(s,n,r,!0);let c=er(n?.limit_per_path)??er(n?.limitPerPath)??tr(r,"limit_per_path")??tr(r,"limitPerPath");return c!==void 0&&s.push(`limit=${c}`),jp(s,n,r),s}if(o.includes("changed_diff"))return ds(s,n,r),fs(s,"offset",er(n?.offset)??tr(r,"offset")),fs(s,"limit",er(n?.limit)??tr(r,"limit")),jp(s,n,r),s;if(o==="read"||o.includes("read_"))return ds(s,n,r),fs(s,"offset",er(n?.offset)??tr(r,"offset")),fs(s,"limit",er(n?.limit)??tr(r,"limit")),s;if(o.includes("changed_scope"))return ds(s,n,r,!0),jp(s,n,r),s;if(o.includes("repo_overview"))return ds(s,n,r),s;if(o.includes("bash")||o.includes("shell_command")){let a=wt(n,"command")??$e(r,"command");return a&&s.push(`cmd=${Ve(a,140)}`),s}if(o==="glob"||o.includes("glob_")){let a=wt(n,"pattern")??$e(r,"pattern"),c=wt(n,"path","root","directory","cwd")??$e(r,"path")??$e(r,"root")??$e(r,"directory")??$e(r,"cwd");if(a&&s.push(`pattern=${Ve(a,96)}`),c){let l=Za(c);l&&s.push(l),s.push(Ve(c))}return s}if(o==="grep"||o.includes("grep_")){let a=wt(n,"pattern","query")??$e(r,"pattern")??$e(r,"query"),c=wt(n,"path","root","directory","cwd")??$e(r,"path")??$e(r,"root")??$e(r,"directory")??$e(r,"cwd");if(a&&s.push(`pattern=${Ve(a,96)}`),c){let l=Za(c);l&&s.push(l),s.push(Ve(c))}return s}if(o==="web_fetch"){let a=wt(n,"url")??$e(r,"url"),c=wt(n,"provider_id","providerId")??$e(r,"provider_id")??$e(r,"providerId"),l=wt(n,"capability_id","capabilityId")??$e(r,"capability_id")??$e(r,"capabilityId");return a&&s.push(Ve(a,120)),c&&s.push(`provider=${Ve(c,48)}`),l&&s.push(`cap=${Ve(l,48)}`),s}if(o==="mcp_describe"||o==="mcp_read_resource"){let a=wt(n,"id")??$e(r,"id");return a&&s.push(Ve(a,120)),s}if(o==="mcp_call"){let a=wt(n,"id")??$e(r,"id"),c=Qu(n?.args),l=c?Object.keys(c).length:void 0;return a&&s.push(Ve(a,120)),l!==void 0&&s.push(`args=${l}`),s}if(o==="mcp_search"){let a=wt(n,"query")??$e(r,"query"),c=wt(n,"server")??$e(r,"server"),l=wt(n,"kind")??$e(r,"kind"),d=er(n?.limit)??tr(r,"limit");return a&&s.push(`query=${Ve(a,96)}`),c&&s.push(`server=${Ve(c,48)}`),l&&s.push(`kind=${l}`),d!==void 0&&s.push(`limit=${d}`),s}if(o==="web_search"||o==="code_search"||o==="semantic_lookup"){let a=wt(n,"query","pattern")??$e(r,"query")??$e(r,"pattern"),c=wt(n,"path","target_path","targetPath")??$e(r,"path")??$e(r,"target_path")??$e(r,"targetPath"),l=wt(n,"provider_id","providerId")??$e(r,"provider_id")??$e(r,"providerId"),d=er(n?.limit)??tr(r,"limit");return a&&s.push(`query=${Ve(a,96)}`),c&&s.push(Ve(c,72)),l&&s.push(`provider=${Ve(l,48)}`),d!==void 0&&s.push(`limit=${d}`),s}return ds(s,n,r,!0),fs(s,"offset",er(n?.offset)??tr(r,"offset")),fs(s,"limit",er(n?.limit)??tr(r,"limit")),s}i(iP,"summarizeToolDetails");function YT(e){let t=e.match(/Showing diff lines\s+(\d+)-(\d+)\s+of\s+(\d+)/i);if(t)return`${t[1]}-${t[2]}/${t[3]}`}i(YT,"extractChangedDiffRange");function sP(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.startsWith("+")||t.startsWith("-")||t.startsWith("@@"))}i(sP,"extractDiffPreviewLine");function aP(e){let t=[],n=YT(e);if(n){let[o,s]=n.split("/");t.push(s?`Diff range: ${o} of ${s}`:`Diff range: ${n}`)}let r=sP(e);return r&&t.push(`Preview: ${Ve(r,220)}`),t}i(aP,"formatChangedDiffExplanation");function cP(e){let t=[],n=e.match(/^Changed diff bundle for\s+(\d+)\s+file\(s\)/im);if(n?.[1]){let o=Number(n[1]);Number.isFinite(o)&&o>0&&t.push(`Bundle: ${o===1?"1 file":`${o} files`}`)}let r=e.match(/^===\s+(.+?)\s+===/m);return r?.[1]&&t.push(`First file: ${Ve(r[1].trim(),220)}`),t}i(cP,"formatChangedDiffBundleExplanation");function qT(e,t){if(!t)return[];let n=Gp(e).toLowerCase(),r=[];if(n.includes("changed_diff_bundle")){let o=t.match(/^Changed diff bundle for\s+(\d+)\s+file\(s\)/im);if(o?.[1]){let a=Number(o[1]);Number.isFinite(a)&&a>0&&r.push(a===1?"1 file":`${a} files`)}let s=t.match(/^===\s+(.+?)\s+===/m);return s?.[1]&&r.push(Ve(s[1].trim())),r}if(n.includes("changed_diff")){let o=t.match(/^Changed diff for\s+(.+)$/im);o?.[1]&&r.push(Ve(o[1].trim()));let s=YT(t);return s&&r.push(s),r}if(n==="read"||n.includes("read_")){let o=t.match(/^Reading\s+(.+)$/im);return o?.[1]&&r.push(Ve(o[1].trim())),r}return[]}i(qT,"summarizeToolOutputDetails");function Kp(e,t){let n=qu(e);return t.length>0?`${n} - ${t.join(" - ")}`:n}i(Kp,"formatToolDetailSummary");function lP(e,t){if(!t)return;let n=t-e;return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}i(lP,"formatDuration");function uP(e){switch(e.status){case $.Scheduled:return"scheduled";case $.Validating:return"validating";case $.AwaitingApproval:return"awaiting approval";case $.Executing:return"running";case $.Error:return"failed";case $.Cancelled:return"cancelled";default:return}}i(uP,"formatToolStatusDetail");function GT(e){switch(e.status){case $.Scheduled:return["Queued: waiting to start"];case $.Validating:return["Validating: checking inputs and policy"];case $.AwaitingApproval:return["Waiting: approval required before execution"];case $.Executing:return e.progress!==void 0?[`Progress: ${e.progress}% complete`]:e.progressLines&&e.progressLines.length>0?e.progressLines.slice(-5):e.preview?[`Running: ${e.preview}`]:["Running: waiting for tool output"];case $.Cancelled:return["Cancelled before completion"];default:return[]}}i(GT,"formatToolProgressExplanation");function Vp(e){return e.startsWith("Error:")?"error":e.startsWith("Waiting:")?"accent":e.startsWith("Progress:")||e.startsWith("Running:")?"primary":"dim"}i(Vp,"resolveToolExplanationTone");function dP(e){let t=UT(e.error),n=typeof e.output=="string"?UT(e.output):void 0,r=[];return t&&r.push(`Error: ${Ve(t,220)}`),e.status===$.Error&&n&&(!t||n.toLowerCase()!==t.toLowerCase())&&r.push(`Last output: ${Ve(n,220)}`),r}i(dP,"formatToolFailureExplanation");function zp(e){if(typeof e.output!="string"||!e.output.trim())return GT(e);let t=Gp(e.name).toLowerCase();return e.status===$.Error?dP(e):e.status!==$.Success?GT(e):t.includes("changed_diff_bundle")?cP(e.output):t.includes("changed_diff")?aP(e.output):[]}i(zp,"formatToolResultExplanation");function Xp(e,t){return Kp(e,iP(e,t))}i(Xp,"formatToolSummary");function Ju(e){let t=typeof e.output=="string"?qT(e.name,e.output):[],n=t.length>0?Kp(e.name,t):Xp(e.name,e.input),r=uP(e),o=lP(e.startTime,e.endTime),s=e.status===$.Executing&&e.progress!==void 0?`${e.progress}%`:e.status===$.Executing&&e.preview?e.preview:void 0,a=[r,s,o].filter(Boolean);return a.length>0?`${n} (${a.join(" - ")})`:n}i(Ju,"formatToolCallInlineText");function Zu(e){let t=new Map;for(let n of e){let r=typeof n.output=="string"?qT(n.name,n.output):[],o=r.length>0?Kp(n.name,r):Xp(n.name,n.input),a=n.progressLines&&n.progressLines.length>0?`${o}|${n.id}`:`${o}|${n.error??""}`,c=t.get(a);c?(c.tool=n,c.count+=1):t.set(a,{tool:n,count:1})}return[...t.values()]}i(Zu,"collapseToolCalls");function tc(e){let t=Ju(e.tool);return e.count>1?`${t} x${e.count}`:t}i(tc,"formatCollapsedToolInlineText");function ed(e,t,n){let r=Xp(e,t);return r!==qu(e)?`[Tools] ${r}`:n>0?`[Tools] ${qu(e)} (${n} chars)`:`[Tools] ${qu(e)}`}i(ed,"formatLiveToolLabel");function Yp(e,t=e.length){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o++)e.charCodeAt(o)===10&&(n+=1);return n}i(Yp,"countNewlines");function td(e,t={}){let n=t.maxChars??1e4,r=t.headChars??2500,o=t.tailChars??2500;if(e.length<=n)return e;let s=e.slice(0,r),a=e.slice(-o),c=Yp(e),l=Yp(s),d=Yp(a),m=Math.max(0,c-l-d);return`${s}
301
- \u2026 +${m} lines \u2026
302
- ${a}`}i(td,"truncateUserMessageForDisplay");var QT=400,fP="... (thinking truncated; press Ctrl+O to inspect full reasoning)",JT=2e5,mP="... (thinking show-all truncated at 200K chars; full content available via session artifacts)",ZT=1e5;function pP(e,t){if(!e||!t)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`^\\[Tools\\]\\s+\\[${n}\\]\\s+`,"i"),"[Tools] ").replace(new RegExp(`^\\[Thinking\\]\\s+\\[${n}\\]\\s*`,"i"),"[Thinking] ").replace(new RegExp(`^\\[${n}\\]\\s+thinking\\b`,"i"),"[Thinking]").trim()}i(pP,"normalizeManagedLiveActivityLabel");function nd(e){return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}i(nd,"formatTimestamp");function eC(e){switch(e){case $.Scheduled:return"\u25CB";case $.Validating:return"\u25D0";case $.AwaitingApproval:return"\u23F8";case $.Executing:return"\u25CF";case $.Success:return"\u2713";case $.Error:return"\u2717";case $.Cancelled:return"\u2298";default:return"[tool]"}}i(eC,"getToolStatusIcon");function tC(e){switch(e){case $.Scheduled:case $.Validating:return"dim";case $.AwaitingApproval:return"accent";case $.Executing:return"primary";case $.Success:return"success";case $.Error:return"error";case $.Cancelled:return"dim";default:return"text"}}i(tC,"getToolStatusColor");function gP(e,t){let n=Math.max(1,t),r=e.split(`
303
- `),o=zt(r.length>0?r:[""],n,0,0);return o.visualLines.length>0?o.visualLines:[""]}i(gP,"wrapText");function qp(e,t,n,r=!1){if(n||r)return e.length>JT?`${e.slice(0,JT)}
304
-
305
- ${mP}`:e;let o=e.split(/\r?\n/),s=o.length>t,a=s?o.slice(0,t).join(`
306
- `):e,c=a.length>QT,l=c?a.slice(0,QT):a;return!s&&!c?e:`${l}
307
-
308
- ${fP}`}i(qp,"buildThinkingPreview");function hP(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.type==="user")return t;return 0}i(hP,"findActiveRoundStartIndex");function Oe(e,t,n,r,o){let s=gP(n,r);if(s.length===0){e.push({key:`${t}-0`,text:"",...o});return}s.forEach((a,c)=>{e.push({key:`${t}-${c}`,text:a,...o})})}i(Oe,"pushWrappedRows");function nc(e,t){e.push({key:t,text:" "})}i(nc,"pushBlankRow");function mt(e,t=0){return Math.max(20,e-t)}i(mt,"getBodyWidth");function yP(e){if(!e.input)return[];let t=JSON.stringify(e.input,null,2)?.trim();return t?t.split(/\r?\n/).slice(0,6).map((n,r)=>r===0?`input: ${n}`:n):[]}i(yP,"buildToolInputPreview");function xP(e){switch(e){case"H0_DIRECT":return"H0";case"H1_EXECUTE_EVAL":return"H1";case"H2_PLAN_EXECUTE_EVAL":return"H2";default:return e}}i(xP,"formatHarnessProfileShort");function wP(e,t,n,r,o,s=!1,a=!1){if(Oe(e,`${t}-tool-${n.id}-main`,`${eC(n.status)} ${tc({tool:n,count:r})}`,mt(o,2),{color:tC(n.status),indent:2,bold:n.status===$.Executing}),zp(n).forEach((l,d)=>{let m=Vp(l);Oe(e,`${t}-tool-${n.id}-explanation-${d}`,l,mt(o,4),{color:m,indent:4})}),s){let l=yP(n),d=a?l:l.slice(0,6);d.forEach((m,p)=>{Oe(e,`${t}-tool-${n.id}-input-${p}`,m,mt(o,4),{color:"dim",indent:4})}),!a&&l.length>d.length&&Oe(e,`${t}-tool-${n.id}-input-more`,`... (${l.length-d.length} more lines)`,mt(o,4),{color:"dim",indent:4})}if(s&&typeof n.output=="string"&&n.output.trim()){let l=n.output.trim().split(/\r?\n/),d=a?l:l.slice(0,8);d.forEach((p,g)=>{Oe(e,`${t}-tool-${n.id}-output-${g}`,p,mt(o,4),{color:"dim",indent:4})});let m=l.length;!a&&m>d.length&&Oe(e,`${t}-tool-${n.id}-output-more`,`... (${m-d.length} more lines)`,mt(o,4),{color:"dim",indent:4})}}i(wP,"buildToolRows");function SP(e,t,n,r){let o=n.status===$.Executing,s=o?"":`${eC(n.status)} `;Oe(e,`${t}-tool-${n.id}-main`,`${s}${tc({tool:n,count:1})}`,mt(r,2),{color:tC(n.status),indent:2,bold:o,spinner:o}),zp(n).forEach((c,l)=>{let d=Vp(c);Oe(e,`${t}-tool-${n.id}-explanation-${l}`,c,mt(r,4),{color:d,indent:4})})}i(SP,"buildLiveToolRows");function nC(e){let{items:t,viewportWidth:n,isLoading:r=!1,maxLines:o=1e3,isThinking:s=!1,thinkingCharCount:a=0,thinkingContent:c="",streamingResponse:l="",currentTool:d,activeToolCalls:m=[],toolInputCharCount:p=0,toolInputContent:g="",iterationHistory:x=[],currentIteration:y=1,isCompacting:T=!1,managedAgentMode:w,managedPhase:v,managedHarnessProfile:O,managedWorkerTitle:P,managedRound:D,managedMaxRounds:L,lastLiveActivityLabel:X,currentTodoActiveForm:I,showFullThinking:ie=!1,showDetailedTools:Te=!1,showAllContent:K=!1,showLiveProgressRows:q=!0}=e,M=[];for(let C of t)switch(C.type){case"user":Oe(M,`${C.id}-header`,`You [${nd(C.timestamp)}]`,n,{color:"primary",bold:!0,itemId:C.id}),Oe(M,`${C.id}-body`,td(C.text),mt(n,2),{color:"text",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"assistant":{let Z=K?C.text:C.compactText??C.text;Oe(M,`${C.id}-header`,`Assistant [${nd(C.timestamp)}]`,n,{color:"secondary",bold:!0,spinner:C.isStreaming,itemId:C.id}),Oe(M,`${C.id}-body`,Z,mt(n,2),{color:"text",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break}case"system":Oe(M,`${C.id}-header`,`System [${nd(C.timestamp)}]`,n,{color:"dim",bold:!0,itemId:C.id}),Oe(M,`${C.id}-body`,C.text,mt(n,2),{color:"dim",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"tool_group":Oe(M,`${C.id}-header`,`Tools [${nd(C.timestamp)}]`,n,{color:"accent",bold:!0,itemId:C.id}),Zu(C.tools).forEach(Z=>wP(M,C.id,Z.tool,Z.count,n,Te,K)),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"thinking":{let Z=K?qp(C.text,o,ie,K):C.compactText??qp(C.text,o,ie,K);Oe(M,`${C.id}-header`,"Thinking",n,{color:"thinking",italic:!0,itemId:C.id}),Oe(M,`${C.id}-body`,Z,mt(n,2),{color:"thinking",indent:2,italic:!0,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break}case"error":Oe(M,`${C.id}-header`,"\u2717 Error",n,{color:"error",bold:!0,itemId:C.id}),Oe(M,`${C.id}-body`,C.text,mt(n,2),{color:"error",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"info":Oe(M,`${C.id}-body`,`${C.icon??"\u2139"} ${K?C.text:C.compactText??C.text}`,n,{color:"info",itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"event":Oe(M,`${C.id}-body`,`${C.icon??">"} ${K?C.text:C.compactText??C.text}`,n,{color:"text",itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"hint":Oe(M,`${C.id}-header`,"\u{1F4A1} Hint",n,{color:"hint",bold:!0,itemId:C.id}),Oe(M,`${C.id}-body`,C.text,mt(n,2),{color:"dim",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;default:break}if(q&&x.length>0&&(x.forEach(C=>{if(Oe(M,`iteration-${C.iteration}-header`,`\u2500\u2500 Round ${C.iteration} \u2500\u2500`,n,{color:"dim",bold:!0}),C.thinkingSummary){let Z=C.thinkingLength>60?` (${C.thinkingLength} chars total)`:"";Oe(M,`iteration-${C.iteration}-thinking`,`\u{1F4AD} ${C.thinkingSummary}${Z}`,mt(n,1),{color:"thinking",indent:1,italic:!0})}if(C.response){let Z=C.response.slice(0,200);Oe(M,`iteration-${C.iteration}-response`,Z,mt(n,1),{color:"text",indent:1}),C.response.length>200&&Oe(M,`iteration-${C.iteration}-response-more`,`... (${C.response.length} chars total)`,mt(n,1),{color:"dim",indent:1})}C.toolsUsed.length>0&&Oe(M,`iteration-${C.iteration}-tools`,`* tools: ${C.toolsUsed.join(", ")}`,mt(n,1),{color:"accent",indent:1}),nc(M,`iteration-${C.iteration}-blank`)}),Oe(M,"iteration-current-header",`\u2500\u2500 Round ${y} (current) \u2500\u2500`,n,{color:"accent",bold:!0}),nc(M,"iteration-current-blank")),r&&c){let C=qp(c,o,ie,K);Oe(M,"thinking-stream-header","Thinking",n,{color:"thinking",italic:!0}),Oe(M,"thinking-stream-body",C,mt(n,2),{color:"thinking",indent:2,italic:!0}),nc(M,"thinking-stream-blank")}if(r){let C="Thinking",Z="",ke=xP(O),ve=pP(X,P),Se=P??"Scout",ce=v==="routing"?`[${w?w.toUpperCase():"AMA"} Routing] `:v==="preflight"?`[${w?w.toUpperCase():"AMA"} ${Se}] `:v==="verifying"?`[${w?w.toUpperCase():"AMA"} Verifying] `:O?`[${w?w.toUpperCase():"AMA"} ${ke??O}${P?` - ${P}`:""}] `:"",De=m.filter(be=>be.status===$.Executing).length,ae=m.filter(be=>be.status===$.Success).length,Y=m.filter(be=>be.status===$.Error).length,Q=m.filter(be=>be.status===$.Cancelled).length,Ce=m.length>0&&(De>0||!l);if(T)C="Compacting";else if(v==="verifying")Z=ce,C="checking agent output";else if(Ce){let be=[];if(De>0&&be.push(`${De} running`),ae>0&&be.push(`${ae} done`),Y>0&&be.push(`${Y} error`),Q>0&&be.push(`${Q} cancelled`),be.length===0&&be.push(`${m.length} tools`),Oe(M,"loading-tools-header",`${ce}[Tools] ${be.join(", ")}`,n,{color:"primary",bold:!0,spinner:De>0}),m.forEach(at=>{SP(M,"loading-tools",at,n)}),nc(M,"loading-tools-blank"),De>0&&!l&&!q)return M}else if(I)Z=ce||"[Plan] ",C=I;else if(d)Z=ce||"[Tool] ",C=ve?.startsWith("[Tools]")?ve:ed(d,g,p);else if(s){Z=ce||"[Thinking] ";let be=D&&L&&D>1?` round ${D}/${L}`:"";C=a>0?`${a} chars${be}`:ve?`${ve}${be}`:`processing${be}`}else ve&&(C=ve);q&&Oe(M,"loading-indicator",`${Z}${C}...`,n,{color:"accent",spinner:!0})}if(l){let C=l.lastIndexOf(`
309
- `),Z=C>=0?l.slice(0,C+1):"";Z.length>0&&(Oe(M,"streaming-header","Assistant",n,{color:"secondary",bold:!0}),Oe(M,"streaming-body",Z,mt(n,2),{color:"text",indent:2}),nc(M,"streaming-blank"))}return M}i(nC,"buildTranscriptRows");function TP(e,t,n=1e3,r=!1,o=!1){return ms(e,t,n,r,void 0,o)}i(TP,"buildStaticTranscriptSections");function ms(e,t,n=1e3,r=!1,o,s=!1){return e.map(a=>({key:a.id,rows:nC({items:[a],viewportWidth:t,maxLines:n,showAllContent:s,showDetailedTools:r||!!o?.has(a.id)})}))}i(ms,"buildHistoryItemTranscriptSections");function CP(e,t){return{key:e,rows:nC(t)}}i(CP,"buildDynamicTranscriptSection");function rd(e){let{items:t,viewportWidth:n,maxLines:r=1e3,showDetailedTools:o=!1,showAllContent:s=!1,windowed:a=!1}=e;if(a)return{staticSections:[],activeItems:t};let c=hP(t),l=t.slice(0,c),d=t.slice(c);return{staticSections:TP(l,n,r,o,s),activeItems:d}}i(rd,"buildTranscriptStaticPortion");function od(e){let{activeItems:t,viewportWidth:n,maxLines:r=1e3,showDetailedTools:o=!1,showAllContent:s=!1,expandedItemKeys:a,...c}=e,l=ms(t,n,r,o,a,s),d=CP("active-pending",{...c,items:[],managedLiveEvents:[],lastLiveActivityLabel:c.lastLiveActivityLabel,viewportWidth:n,maxLines:r,showAllContent:s,showDetailedTools:o,expandedItemKeys:a}),m=d.rows.length>0?[d]:[];return{sections:l,previewSections:m}}i(od,"buildTranscriptDynamicPortion");function id(e,t){return{staticSections:e.staticSections,sections:t.sections,rows:Fo(t.sections),previewSections:t.previewSections,previewRows:Fo(t.previewSections)}}i(id,"composeTranscriptRenderModel");function sd(e){let t=rd({items:e.items,viewportWidth:e.viewportWidth,maxLines:e.maxLines,showDetailedTools:e.showDetailedTools,showAllContent:e.showAllContent,windowed:e.windowed}),{items:n,...r}=e,o=od({...r,activeItems:t.activeItems});return id(t,o)}i(sd,"buildTranscriptRenderModel");function Fo(e){return e.flatMap(t=>t.rows)}i(Fo,"flattenTranscriptSections");function Qp(e){let t=[...e.staticSections,...e.sections];return{staticSections:[],sections:t,rows:Fo(t),previewSections:[...e.previewSections],previewRows:Fo(e.previewSections)}}i(Qp,"materializeTranscriptRenderModel");function rC(e,t={}){let{start:n,end:r,viewportTop:o,viewportHeight:s,viewportRows:a,scrollOffset:c=0,windowed:l=!1}=t;if(typeof o=="number"&&typeof s=="number"){let d=Math.max(0,o),m=Math.max(d,o+Math.max(0,s));return e.slice(d,m)}return typeof n=="number"&&typeof r=="number"?e.slice(Math.max(0,n),Math.max(0,r)):l?Zp(e,a,c):e}i(rC,"resolveVisibleTranscriptRows");var bP=200,vP=50,Jp=30;function oC(e,t,n=bP,r=vP){let o=t.current,s=o?e.findIndex(l=>l.id===o.id):-1,a=s>=0?s:o?Math.min(o.idx,Math.max(0,e.length-n)):0;e.length-a>n+r&&(a=e.length-n);let c=e[a];return c&&(o?.id!==c.id||o.idx!==a)?t.current={id:c.id,idx:a}:!c&&o&&(t.current=null),a}i(oC,"computeTranscriptCapStart");function iC(e,t){if(t<=0||e.length===0)return[];let n=0,r=0;for(let o=e.length-1;o>=0;o--)if(e[o]?.type==="user"&&(n++,n>t)){r=o+1;break}return e.slice(r)}i(iC,"sliceHistoryToRecentRounds");function Zp(e,t,n=0){if(!t||t<=0)return e;let r=Math.max(0,n),o=Math.max(0,e.length-r),s=Math.max(0,o-t);return e.slice(s,o)}i(Zp,"getVisibleTranscriptRows");function sC(e,t,n){if(!t||!n||n<=0)return 0;let r=Fo(e),o=e.find(d=>d.key===t);if(!o||o.rows.length===0)return 0;let s=o.rows[0]?.key,a=r.findIndex(d=>d.key===s);if(a===-1)return 0;let c=Math.max(0,a-Math.floor(n/3)),l=Math.min(r.length,c+n);return Math.max(0,r.length-l)}i(sC,"resolveScrollOffsetForTranscriptItem");function aC(e,t){if(t)switch(t){case"warning":return e.colors.warning;case"info":return e.colors.info;case"hint":return e.colors.hint;default:return e.colors[t]}}i(aC,"resolveTranscriptColor");var ad="__transcript_hidden_divider__";function cC(e,t){let n=e===1?"message":"messages";return{id:ad,type:"info",timestamp:t?Math.max(0,t-1):0,text:`${e} earlier ${n} hidden \u2014 press Ctrl+E to show all`,icon:"\u2191"}}i(cC,"buildTranscriptHiddenDivider");function eg(e){return e.id===ad}i(eg,"isTranscriptHiddenDivider");var lC=new Li(500);function IP(e){let t=Vt(e),n=[],r=[],o=0,s=0;for(let a of t)n.push(o),r.push(s),o+=a.length,s+=ym(a);return{graphemes:t,codeUnitOffsets:n,visualOffsets:r,length:t.length,displayWidth:s}}i(IP,"buildTranscriptTextMetrics");function rc(e){let t=lC.get(e);if(t)return t;let n=IP(e);return lC.set(e,n),n}i(rc,"getTranscriptTextMetrics");function Yr(e){return rc(e).length}i(Yr,"getTranscriptTextLength");function uC(e){return rc(e).displayWidth}i(uC,"getTranscriptTextDisplayWidth");function cd(e,t){let n=rc(e),r=Math.max(0,Math.min(n.length-1,t));return n.graphemes[r]??""}i(cd,"charAtTranscriptText");function ps(e,t,n){let r=rc(e),o=Math.max(0,Math.min(r.length,Math.floor(t))),s=typeof n=="number"?Math.max(o,Math.min(r.length,Math.floor(n))):r.length;return r.graphemes.slice(o,s).join("")}i(ps,"sliceTranscriptText");function dC(e,t){let n=rc(e),r=Math.max(0,Math.floor(t));if(r<=0||n.length===0)return 0;for(let o=0;o<n.length;o+=1){let s=n.visualOffsets[o]??0,a=o+1<n.length?n.visualOffsets[o+1]??n.displayWidth:n.displayWidth;if(r<a||r===s)return o}return n.length}i(dC,"resolveTranscriptTextIndexAtVisualColumn");function ld(e){return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}i(ld,"formatTimestamp");function kP(e,t){let n=e.split(`
310
- `),r=n.slice(0,t),o=n.length>t;return{lines:r,hasMore:o}}i(kP,"truncateLines");function RP(e){switch(e){case $.Scheduled:return"\u25CB";case $.Validating:return"\u25D0";case $.AwaitingApproval:return"\u23F8";case $.Executing:return"\u25CF";case $.Success:return"\u2713";case $.Error:return"\u2717";case $.Cancelled:return"\u2298";default:return"?"}}i(RP,"getToolStatusIcon");function EP(e,t){switch(e){case $.Scheduled:case $.Validating:return t.colors.dim;case $.AwaitingApproval:return t.colors.accent;case $.Executing:return t.colors.primary;case $.Success:return t.colors.success;case $.Error:return t.colors.error;case $.Cancelled:return t.colors.dim;default:return t.colors.text}}i(EP,"getToolStatusColor");var MP=an(({item:e,theme:t})=>{let n=nr(()=>td(e.text),[e.text]);return Fe(k,{flexDirection:"column",marginBottom:1,children:[Fe(k,{children:[de(b,{color:t.colors.primary,bold:!0,children:"You"}),Fe(b,{dimColor:!0,children:[" [",ld(e.timestamp),"]"]})]}),de(k,{marginLeft:2,children:de(b,{color:t.colors.text,children:n})})]})}),AP=an(({item:e,theme:t,maxLines:n})=>{let r=e.compactText??e.text,{lines:o,hasMore:s}=kP(r,n);return Fe(k,{flexDirection:"column",marginBottom:1,children:[Fe(k,{children:[de(b,{color:t.colors.secondary,bold:!0,children:"Assistant"}),e.isStreaming&&Fe(tg,{children:[de(b,{children:" "}),de(vn,{color:t.colors.accent})]}),Fe(b,{dimColor:!0,children:[" [",ld(e.timestamp),"]"]})]}),Fe(k,{marginLeft:2,flexDirection:"column",children:[o.map((a,c)=>de(b,{color:t.colors.text,children:a||" "},c)),s&&Fe(b,{dimColor:!0,children:["... (",r.split(`
311
- `).length-n," more lines)"]})]})]})}),_P=an(({item:e,theme:t})=>Fe(k,{flexDirection:"column",marginBottom:1,children:[Fe(k,{children:[de(b,{color:t.colors.dim,bold:!0,children:"System"}),Fe(b,{dimColor:!0,children:[" [",ld(e.timestamp),"]"]})]}),de(k,{marginLeft:2,children:de(b,{dimColor:!0,children:e.text})})]})),PP=an(({tool:e,count:t=1,theme:n})=>{let r=RP(e.status),o=EP(e.status,n);return Fe(k,{flexDirection:"column",marginLeft:2,children:[Fe(k,{children:[Fe(b,{color:o,children:[r," "]}),de(b,{color:n.colors.text,bold:!0,children:tc({tool:e,count:t})})]}),e.error&&de(k,{marginLeft:2,children:de(b,{color:n.colors.error,children:e.error})})]})}),$P=an(({item:e,theme:t})=>{let n=Zu(e.tools);return Fe(k,{flexDirection:"column",marginBottom:1,children:[Fe(k,{children:[de(b,{color:t.colors.accent,bold:!0,children:"Tools"}),Fe(b,{dimColor:!0,children:[" [",ld(e.timestamp),"]"]})]}),n.map(r=>de(PP,{tool:r.tool,count:r.count,theme:t},`${r.tool.id}-${r.count}`))]})}),LP=an(({item:e,theme:t})=>Fe(k,{flexDirection:"column",marginBottom:1,children:[de(k,{children:de(b,{color:t.colors.thinking,italic:!0,children:"Thinking"})}),de(k,{marginLeft:2,children:de(b,{color:t.colors.thinking,italic:!0,children:e.compactText??e.text})})]})),OP=an(({item:e,theme:t})=>Fe(k,{flexDirection:"column",marginBottom:1,children:[de(k,{children:Fe(b,{color:t.colors.error,bold:!0,children:["\u2717"," Error"]})}),de(k,{marginLeft:2,children:de(b,{color:t.colors.error,children:e.text})})]})),DP=an(({item:e,theme:t})=>de(k,{flexDirection:"column",marginBottom:1,children:Fe(b,{color:t.colors.text,children:[de(b,{color:t.colors.accent,bold:!0,children:e.icon??">"}),de(b,{children:" "}),e.compactText??e.text]})})),NP=an(({item:e,theme:t})=>de(k,{flexDirection:"column",marginBottom:e.tightSpacing?0:1,children:Fe(b,{color:t.colors.info,children:[Fe(b,{bold:!0,children:[e.icon??"\u2139"," "]}),e.compactText??e.text]})})),BP=an(({item:e,theme:t})=>Fe(k,{flexDirection:"column",marginBottom:1,children:[de(k,{children:Fe(b,{color:t.colors.hint,bold:!0,children:["\u{1F4A1}"," Hint"]})}),de(k,{marginLeft:2,children:de(b,{dimColor:!0,children:e.text})})]})),HP=an(({item:e,theme:t,maxLines:n=1e3})=>{let r=nr(()=>ne("dark"),[]),o=t??r;switch(e.type){case"user":return de(MP,{item:e,theme:o});case"assistant":return de(AP,{item:e,theme:o,maxLines:n});case"system":return de(_P,{item:e,theme:o});case"tool_group":return de($P,{item:e,theme:o});case"thinking":return de(LP,{item:e,theme:o});case"error":return de(OP,{item:e,theme:o});case"event":return de(DP,{item:e,theme:o});case"info":return de(NP,{item:e,theme:o});case"hint":return de(BP,{item:e,theme:o});default:return de(k,{children:de(b,{dimColor:!0,children:"Unknown item type"})})}});function FP(e,t){if(e.theme!==t.theme||(e.animateSpinners??!0)!==(t.animateSpinners??!0)||(e.selectedItem??!1)!==(t.selectedItem??!1))return!1;let n=e.row,r=t.row;if(n!==r){if(n.key!==r.key||n.text!==r.text||n.color!==r.color||n.bold!==r.bold||n.italic!==r.italic||n.indent!==r.indent||n.spinner!==r.spinner||n.itemId!==r.itemId)return!1}let o=e.selectionRange,s=t.selectionRange;return o===s?!0:!o||!s?!1:o.start===s.start&&o.end===s.end}i(FP,"areTranscriptRowPropsEqual");var mC=an(({row:e,theme:t,animateSpinners:n=!0,selectedItem:r=!1,selectionRange:o})=>{let s=aC(t,e.color),a=e.text===" "?"":e.text,c=a||" ",l=o&&a?ps(a,o.start,o.end):"",d=o&&a?ps(a,0,o.start):a,m=o&&a?ps(a,o.end):"",p=r&&!o,g=!p&&e.color==="dim",x={bold:e.bold||p,italic:e.italic,dimColor:g};return Fe(k,{marginLeft:e.indent??0,children:[e.spinner&&n&&Fe(tg,{children:[de(vn,{color:t.colors.accent,theme:t}),de(b,{children:" "})]}),de(b,{color:p?t.colors.accent:s,...x,children:o&&a?Fe(tg,{children:[d?de(b,{color:p?t.colors.accent:s,...x,children:d}):null,de(b,{backgroundColor:t.colors.accent,color:t.colors.background,bold:!0,italic:e.italic,children:l}),m?de(b,{color:p?t.colors.accent:s,...x,children:m}):null]}):c})]})},FP),WP=an(({section:e,theme:t,animateSpinners:n=!0})=>de(k,{flexDirection:"column",children:e.rows.map(r=>de(mC,{row:r,theme:t,animateSpinners:n},r.key))})),Wo=i(({items:e,isLoading:t=!1,maxLines:n=1e3,isThinking:r=!1,thinkingCharCount:o=0,thinkingContent:s="",streamingResponse:a="",currentTool:c,activeToolCalls:l,toolInputCharCount:d=0,toolInputContent:m="",iterationHistory:p=[],currentIteration:g=1,isCompacting:x=!1,agentMode:y,managedPhase:T,managedHarnessProfile:w,managedWorkerTitle:v,managedRound:O,managedMaxRounds:P,managedGlobalWorkBudget:D,managedBudgetUsage:L,managedBudgetApprovalRequired:X,lastLiveActivityLabel:I,viewportRows:ie,viewportWidth:Te,scrollOffset:K=0,animateSpinners:q=!0,windowed:M=!1,showFullThinking:C=!1,showDetailedTools:Z=!1,showAllContent:ke=!1,showLiveProgressRows:ve=!0,selectedItemId:Se,expandedItemKeys:ce,onMetricsChange:De,onVisibleRowsChange:ae,rendererWindow:Y,selectedTextRanges:Q,transcriptModel:Ce,visibleRowsOverride:be})=>{let at=nr(()=>ne("dark"),[]),{stdout:Re}=qn(),Ue=Te??Re?.columns??80,xe=nr(()=>Ce??sd({items:e,viewportWidth:Ue,isLoading:t,maxLines:n,isThinking:r,thinkingCharCount:o,thinkingContent:s,streamingResponse:a,currentTool:c,activeToolCalls:l,toolInputCharCount:d,toolInputContent:m,iterationHistory:p,currentIteration:g,isCompacting:x,managedAgentMode:y,managedPhase:T,managedHarnessProfile:w,managedWorkerTitle:v,managedRound:O,managedMaxRounds:P,managedGlobalWorkBudget:D,managedBudgetUsage:L,managedBudgetApprovalRequired:X,lastLiveActivityLabel:I,windowed:M,showFullThinking:C,showDetailedTools:Z,showAllContent:ke,showLiveProgressRows:ve,expandedItemKeys:ce}),[Ce,e,Ue,t,n,r,o,s,a,c,l,d,m,p,g,x,y,T,w,v,O,P,D,L,X,I,M,C,Z,ke,ve,ce]),kt=xe.staticSections,qe=xe.rows,ee=xe.previewRows,A=nr(()=>[...qe,...ee],[ee,qe]),W=!(A.length>0)&&e.length===0&&!t,J=nr(()=>M||Y||be?A:qe,[A,Y,qe,be,M]),Ne=nr(()=>be||rC(J,{viewportTop:Y?Math.max(0,Y.viewportTop):void 0,viewportHeight:Y?Math.max(0,Y.viewportHeight):void 0,start:void 0,end:void 0,viewportRows:ie,scrollOffset:K,windowed:M}),[Y,K,ie,be,M,J]),et=nr(()=>be||M||Y?Ne:A,[A,Y,Ne,be,M]),Ie=nr(()=>A,[A]),Le=Y?Math.max(0,Y.viewportHeight):ie;return fC(()=>{De?.({scrollHeight:A.length,viewportHeight:Y?Math.max(0,Y.viewportHeight):Le??A.length})},[A.length,Le,De,Y]),fC(()=>{ae?.({rows:et,allRows:Ie})},[Ie,ae,et]),W?de(k,{paddingY:1,children:de(b,{dimColor:!0,children:"No messages yet. Start typing to begin."})}):Fe(k,{flexDirection:"column",children:[!M&&kt.length>0&&de(Yi,{items:kt,children:i(Kt=>de(WP,{section:Kt,theme:at,animateSpinners:q},Kt.key),"children")}),et.map(Kt=>de(mC,{row:Kt,theme:at,animateSpinners:q,selectedItem:Se?Kt.key.startsWith(`${Se}-`):!1,selectionRange:Q?.get(Kt.key)},Kt.key))]})},"MessageList");var UP=i(({role:e,content:t})=>{let n=nr(()=>ne("dark"),[]),r={user:n.colors.primary,assistant:n.colors.secondary,system:n.colors.dim}[e];return Fe(k,{flexDirection:"column",marginBottom:1,children:[de(b,{color:r,bold:!0,children:e==="user"?">":e==="assistant"?"<":"#"}),de(b,{children:t})]})},"SimpleMessageDisplay");import{jsx as rg,jsxs as md}from"react/jsx-runtime";import s$,{useMemo as og}from"react";var jP="\u{1F504}",GP="\u2588",KP="\u2592",VP="\u2192",zP=" \xB7 ";function XP(e){switch(e){case"auto":return"auto";case"balanced":return"balanced";case"quick":return"quick";case"deep":return"deep";case"off":return"off";default:return e.toLowerCase()}}i(XP,"formatReasoningModeShort");function YP(e){switch(e){case"budget":case"B":return"B";case"effort":case"E":return"E";case"toggle":case"T":return"T";case"prompt":case"-":return"-";case"unknown":case"?":return"?";default:return e??""}}i(YP,"formatReasoningCapabilityShort");function qP(e){switch(e){case"off":return"dim";case"quick":return"green";case"balanced":return"yellow";case"deep":return"magenta";default:return"cyan"}}i(qP,"getReasoningColor");function pC(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}i(pC,"formatTokenCount");function QP(e){let t=Math.min(10,Math.max(0,Math.round(e/10))),n=10-t;return`${GP.repeat(t)}${KP.repeat(n)}`}i(QP,"createMiniProgressBar");function JP(e,t,n){if(t===0)return"green";let r=e/t*100,o=n*(2/3);return r>=n?"red":r>=o?"yellow":"green"}i(JP,"getContextColor");function ZP(e){switch(e.toLowerCase()){case"plan":return"blue";case"accept-edits":return"green";case"auto":case"auto-in-project":return"warning";default:return"magenta"}}i(ZP,"getPermissionModeColor");function e$(e,t){let n=Zi(e);return!(e==="auto"||e==="auto-in-project")||!t?n:`${n}${t==="llm"?"[LLM]":"[RULES]"}`}i(e$,"buildPermissionModeText");function t$(e){let t=e.toLowerCase();return t.includes("read")||t.includes("view")||t.includes("search")||t.includes("list")||t.includes("find")||t.includes("browser")||t.includes("get")?"Read":t.includes("write")||t.includes("replace")||t.includes("edit")||t.includes("modify")?"Edit":t.includes("command")||t.includes("bash")||t.includes("terminal")?"Bash":t.includes("ask")||t.includes("notify")||t.includes("user")||t.includes("question")?"Ask":t.includes("think")||t.includes("reason")?"Think":e}i(t$,"formatToolAction");function n$(e){switch(e){case"H0_DIRECT":return"H0";case"H1_EXECUTE_EVAL":return"H1";case"H2_PLAN_EXECUTE_EVAL":return"H2";default:return e}}i(n$,"formatHarnessProfileShort");function ud(e,t){return t&&t>0?`${e} (${t} chars)`:e}i(ud,"formatThinkingStatus");function dd(e,t,n){let r=t$(e);return n?`${r} (${n}...)`:t&&t>0?`${r} (${t} chars)`:r}i(dd,"formatToolStatus");function ng({activeToolCount:e,currentTool:t,isThinkingActive:n,thinkingCharCount:r,isCompacting:o,toolInputCharCount:s,toolInputContent:a,managedPhase:c,managedHarnessProfile:l,managedWorkerTitle:d,managedIdleWaiting:m,managedIdleWaitingPendingCount:p}){let g=e&&e>0?`${e} tool${e===1?"":"s"} running`:void 0;if(o)return"Compacting";if(c==="routing")return g?`Routing - ${g}`:t?`Routing - ${dd(t,s,a)}`:n?ud("Routing",r):"Routing";if(c==="preflight"){let x=d??"Scout";return g?`${x} - ${g}`:t?`${x} - ${dd(t,s,a)}`:n?ud(x,r):x}if(l){let y=`${n$(l)}${d?` - ${d}`:""}`;if(m===!0&&!g&&!t&&!n){let T=p??0,w=T>1?`waiting for ${T} children`:T===1?"waiting for 1 child":"idle - resuming";return`${y} - ${w}`}return g?`${y} - ${g}`:t?`${y} - ${dd(t,s,a)}`:n?ud(y,r):y}if(g)return g;if(t)return dd(t,s,a);if(n)return ud("Thinking",r)}i(ng,"buildBusyStatusText");function r$({agentMode:e,managedPhase:t,managedHarnessProfile:n,managedRound:r,managedMaxRounds:o,managedGlobalWorkBudget:s,managedBudgetUsage:a,currentIteration:c,maxIter:l}){let d=[];return t==="routing"||t==="preflight"||(n&&r&&o&&r>1&&d.push({label:"Round",current:r,max:o}),n&&s&&typeof a=="number"?d.push({label:"Work",current:a,max:s}):e==="sa"&&c&&l&&d.push({label:"Iter",current:c,max:l})),d}i(r$,"resolveIterationSegments");function o$(e){if(e.length!==0)return`${jP} ${e.map(t=>`${t.label} ${t.current}/${t.max}`).join(zP)}`}i(o$,"formatLabeledIterationStatus");function i$(e){let{sessionId:t,permissionMode:n,agentMode:r,provider:o,model:s,tokenUsage:a,currentTool:c,activeToolCount:l,thinking:d,isThinkingActive:m,thinkingCharCount:p,reasoningMode:g=d?"auto":"off",reasoningCapability:x,isCompacting:y,toolInputCharCount:T,toolInputContent:w,currentIteration:v,maxIter:O,contextUsage:P,showBusyStatus:D=!0,managedPhase:L,managedHarnessProfile:X,managedWorkerTitle:I,managedRound:ie,managedMaxRounds:Te,managedGlobalWorkBudget:K,managedBudgetUsage:q,managedIdleWaiting:M,managedIdleWaitingPendingCount:C}=e,Z=[{id:"agent-mode",text:`KodaX - ${r.toUpperCase()}`,color:"primary",bold:!0},{id:"permission-mode",text:e$(n,e.autoModeEngine),color:ZP(n)}],ke=XP(g),ve=YP(x);Z.push({id:"reasoning-mode",text:x?`${ke}/${ve}`:ke,color:qP(g)});let Se=r$({agentMode:r,managedPhase:L,managedHarnessProfile:X,managedRound:ie,managedMaxRounds:Te,managedGlobalWorkBudget:K,managedBudgetUsage:q,currentIteration:v,maxIter:O}),ce=o$(Se);if(ce){let ae=Math.max(...Se.map(Q=>Q.current/Q.max)),Y="green";ae>=.8?Y="red":ae>=.5&&(Y="yellow"),Z.push({id:"iteration-status",text:ce,color:Y})}Z.push({id:"session-id",text:t,color:"dim"});let De=D?ng({activeToolCount:l,currentTool:c,isThinkingActive:m,thinkingCharCount:p,isCompacting:y,toolInputCharCount:T,toolInputContent:w,managedPhase:L,managedHarnessProfile:X,managedWorkerTitle:I,managedIdleWaiting:M,managedIdleWaitingPendingCount:C}):void 0;if(De&&Z.push({id:"busy-status",text:De,color:"dim"}),Z.push({id:"provider-model",text:`${o}/${s}`,color:"secondary"}),P&&P.contextWindow!==0){let ae=Math.round(P.currentTokens/P.contextWindow*100),Y=pC(P.currentTokens),Q=pC(P.contextWindow),Ce=QP(ae);Z.push({id:"context-usage",text:`${Y}/${Q} ${Ce} ${ae}%`,color:JP(P.currentTokens,P.contextWindow,P.triggerPercent)})}return a&&Z.push({id:"token-usage",text:`${a.input}${VP}${a.output} (${a.total})`,color:"dim"}),Z}i(i$,"buildStatusBarSegments");function fd(e){let t=i$(e);return{text:t.map(n=>n.text).join(" | "),segments:t}}i(fd,"buildStatusBarViewModel");function a$(e,t){if(e.color)return t.colors[e.color]??e.color;switch(e.tone){case"primary":return t.colors.primary;case"accent":return t.colors.accent;case"success":return t.colors.success;case"warning":return t.colors.warning;case"error":return t.colors.error;default:return t.colors.dim}}i(a$,"resolveViewModelSegmentColor");var gs=i(({viewModel:e,...t})=>{let n=og(()=>ne("dark"),[]),r=og(()=>e??fd(t),[t,e]);return rg(k,{paddingX:1,children:r.segments.map((o,s)=>md(s$.Fragment,{children:[rg(b,{color:a$(o,n),bold:o.bold,children:o.text}),s<r.segments.length-1?rg(b,{dimColor:!0,children:" | "}):null]},o.id))})},"StatusBar"),c$=i(({permissionMode:e,provider:t,model:n})=>{let r=og(()=>ne("dark"),[]);return md(k,{children:[md(b,{color:r.colors.primary,bold:!0,children:["[",e,"]"]}),md(b,{dimColor:!0,children:[" ",t,"/",n]})]})},"SimpleStatusBar");import{jsx as qr,jsxs as hd}from"react/jsx-runtime";import{useState as ig,useCallback as pd,useMemo as gC}from"react";function gd(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}i(gd,"generateId");function l$(e){let t={id:e.id,timestamp:e.timestamp};switch(e.role){case"user":return{...t,type:"user",text:e.content};case"assistant":return{...t,type:"assistant",text:e.content};case"system":return{...t,type:"system",text:e.content};default:return{...t,type:"info",text:e.content}}}i(l$,"messageToHistoryItem");var u$=i(({model:e,provider:t,onSubmit:n,permissionMode:r="accept-edits",agentMode:o="ama"})=>{let{stdout:s}=qn(),a=gC(()=>ne("dark"),[]),[c,l]=ig({messages:[],isLoading:!1,sessionId:gd()}),[d,m]=ig(null),[p,g]=ig(),x=pd(async v=>{if(!v.trim())return;let O={id:gd(),role:"user",content:v,timestamp:Date.now()};l(P=>({...P,messages:[...P.messages,O],isLoading:!0}));try{await n(v)}catch(P){let D={id:gd(),role:"system",content:`Error: ${P instanceof Error?P.message:"Unknown error"}`,timestamp:Date.now()};l(L=>({...L,messages:[...L.messages,D],isLoading:!1}))}finally{l(P=>({...P,isLoading:!1}))}},[n]),y=pd((v,O)=>{let P={id:gd(),role:v,content:O,timestamp:Date.now()};l(D=>({...D,messages:[...D.messages,P]}))},[]),T=pd((v,O)=>{m({input:v,output:O,total:v+O})},[]),w=pd(v=>{g(v)},[]);return hd(k,{flexDirection:"column",children:[qr(k,{flexGrow:1,flexDirection:"column",overflow:"hidden",children:qr(Wo,{items:c.messages.map(l$),isLoading:c.isLoading})}),qr(k,{flexShrink:0,children:qr(us,{onSubmit:i(v=>x(v.fullText),"onSubmit"),prompt:">",focus:!c.isLoading})}),qr(k,{flexShrink:0,children:qr(gs,{sessionId:c.sessionId,permissionMode:r,agentMode:o,provider:t,model:e,tokenUsage:d??void 0,currentTool:p})})]})},"App"),d$=i(({model:e,provider:t,onInput:n})=>{let r=gC(()=>ne("dark"),[]);return hd(k,{flexDirection:"column",children:[hd(k,{marginBottom:1,children:[qr(b,{color:r.colors.primary,bold:!0,children:"KodaX CLI"}),hd(b,{dimColor:!0,children:[" ","- ",t,"/",e]})]}),qr(us,{onSubmit:i(o=>n(o.fullText),"onSubmit"),placeholder:"Type a message...",prompt:">"})]})},"SimpleApp");import{jsx as f$}from"react/jsx-runtime";var sg=i(({top:e,topRows:t=0,transcript:n,renderTranscriptWindow:r,footer:o,overlay:s,stickyHeader:a,jumpToLatest:c,width:l,scrollTop:d=0,scrollHeight:m=0,viewportHeight:p=0,stickyScroll:g=!0,scrollRef:x,onScrollTopChange:y,onStickyChange:T,onWindowChange:w})=>f$(Qm,{width:l,top:e,topRows:t,stickyHeader:a,jumpToLatest:c,scrollable:n,renderScrollableWindow:r,overlay:s,bottom:o,scrollTop:d,scrollHeight:m,viewportHeight:p,stickyScroll:g,scrollRef:x,onScrollTopChange:y,onStickyChange:T,onWindowChange:w}),"FullscreenTranscriptLayout");import{jsx as hC}from"react/jsx-runtime";function hs({copyMessage:e=!1,copyToolInput:t=!1,copyOnSelect:n=!1,toggleDetail:r=!1,selectionNavigation:o=!1,matchNavigation:s=!1,dismissAction:a}){let c=[];return o&&c.push("\u2190/\u2192 browse"),e&&c.push("C copy"),t&&c.push("I tool input"),n&&c.push("Mouse select copies"),r&&c.push("V details"),s&&c.push("N/Shift+N matches"),a==="clear"&&c.push("Esc clear"),a==="close-search"&&c.push("Esc close search"),c.length>0?c.join(" | "):void 0}i(hs,"buildMessageActionsText");var ag=i(({copyMessage:e=!1,copyToolInput:t=!1,copyOnSelect:n=!1,toggleDetail:r=!1,selectionNavigation:o=!1,matchNavigation:s=!1,dismissAction:a})=>{let c=ne("dark"),l=hs({copyMessage:e,copyToolInput:t,copyOnSelect:n,toggleDetail:r,selectionNavigation:o,matchNavigation:s,dismissAction:a});return l?hC(k,{paddingX:1,children:hC(b,{color:c.colors.dim,children:l})}):null},"MessageActions");import{jsx as yC}from"react/jsx-runtime";function cg({itemSummary:e,itemKind:t,position:n,detailState:r="compact"}){if(!e||!n||n.total<=0)return;let o=r==="expanded"?"expanded":"compact",s=t?`${t}: `:"";return`Selected item ${n.current}/${n.total}: ${s}${e} | ${o}`}i(cg,"buildMessageSelectorText");var m$=i(({itemSummary:e,itemKind:t,position:n,detailState:r="compact"})=>{let o=ne("dark"),s=cg({itemSummary:e,itemKind:t,position:n,detailState:r});return s?yC(k,{paddingX:1,children:yC(b,{color:o.colors.dim,children:s})}):null},"MessageSelector");import{jsx as ys,jsxs as p$}from"react/jsx-runtime";import{useMemo as xC}from"react";function yd(e,t){return Math.max(1,zt(e.length>0?e.split(`
312
- `):[""],Math.max(1,t),0,0).visualLines.length)}i(yd,"countWrappedRows");var lg=i(({browse:e,selection:t,search:n,chromeMode:r="inline",...o})=>{let s=r==="inline",a=t?.itemSummary,c=t?.position,l=t?.itemKind,d=t?.detailState??"compact",m=t?.copyCapabilities,p=m?.message??!1,g=m?.toolInput??!1,x=m?.copyOnSelect??!1,y=t?.toggleDetail??!1,T=t?.navigationCapabilities?.selection??!1,w=n?.statusText,v=n?.matches?.length??0,O=n?.surface,P=o.viewportWidth??80,D=Math.max(1,P-2),L=n?.query?.trim()?"close-search":a||p||g||y||T?"clear":void 0,X=cg({itemSummary:a,itemKind:l,position:c,detailState:d}),I=xC(()=>hs({copyMessage:p,copyToolInput:g,copyOnSelect:x,toggleDetail:y,selectionNavigation:T,matchNavigation:!!w&&v>0,dismissAction:L}),[p,g,T,y,L,v,w,x]),ie=xC(()=>{if(!s)return 0;let K=0;return e?.hintText&&(K+=yd(e.hintText,D)),X&&(K+=yd(X,D)),I&&(K+=yd(I,D)),w&&(K+=yd(w,D)),O&&(K+=1),K},[I,e?.hintText,D,s,w,O,X]),Te=typeof o.viewportRows=="number"?Math.max(1,o.viewportRows-ie):o.viewportRows;return p$(k,{flexDirection:"column",flexGrow:o.windowed?0:1,children:[s&&e?.hintText?ys(k,{paddingX:1,children:ys(b,{dimColor:!0,children:e.hintText})}):null,null,s&&(p||g||x||y||T||v>0)?ys(ag,{copyMessage:p,copyToolInput:g,copyOnSelect:x,toggleDetail:y,selectionNavigation:T,matchNavigation:!!w&&v>0,dismissAction:L}):null,s&&w?ys(k,{paddingX:1,children:ys(b,{dimColor:!0,children:w})}):null,s?O:null,ys(Wo,{...o,viewportRows:Te})]})},"TranscriptViewport");import{jsx as wC}from"react/jsx-runtime";var ug=i(e=>wC(k,{flexDirection:"column",children:wC(us,{...e})}),"PromptComposer");import{jsx as Uo,jsxs as xd}from"react/jsx-runtime";import SC from"react";var TC=" \xB7 ",wd=i(({items:e=[]})=>{let t=e.filter(r=>r.label.trim().length>0),n=ne("dark");return t.length===0?null:Uo(k,{flexGrow:1,children:t.map((r,o)=>xd(SC.Fragment,{children:[Uo(b,{color:r.accent?n.colors.accent:n.colors.dim,bold:r.accent,children:r.label}),o<t.length-1?Uo(b,{dimColor:!0,children:TC}):null]},r.id))})},"PromptFooterLeftSide"),Sd=i(({items:e=[]})=>{let t=e.filter(r=>r.label.trim().length>0),n=ne("dark");return t.length===0?null:Uo(k,{justifyContent:"flex-end",children:t.map((r,o)=>xd(SC.Fragment,{children:[Uo(b,{color:r.accent?n.colors.primary:n.colors.dim,bold:r.accent,children:r.label}),o<t.length-1?Uo(b,{dimColor:!0,children:TC}):null]},r.id))})},"PromptFooterRightSide"),Td=i(({left:e,right:t,queued:n,stashNotice:r,notifications:o,inlineNotices:s,activityBar:a,todoSurface:c,composer:l,inlineSuggestions:d,helpSurface:m,taskBar:p,statusLine:g,inlineDialogs:x})=>xd(k,{flexDirection:"column",children:[e||t?xd(k,{paddingX:1,children:[Uo(k,{flexGrow:1,children:e}),t]}):null,n,r,o,s,a,c,l,d,x,m,p,g]}),"PromptFooter");import{jsx as dg,jsxs as CC}from"react/jsx-runtime";var fg=i(({sections:e,title:t="Help"})=>{let n=ne("dark"),r=e.filter(o=>o.items.length>0);return r.length===0?null:CC(k,{flexDirection:"column",borderStyle:"round",borderColor:n.colors.accent,paddingX:1,marginTop:1,children:[dg(b,{color:n.colors.accent,bold:!0,children:t}),r.map(o=>CC(k,{flexDirection:"column",children:[dg(b,{color:n.colors.primary,bold:!0,children:o.title}),dg(b,{dimColor:!0,children:o.items.map(s=>s.label).join(" | ")})]},o.id))]})},"PromptHelpMenu");import{jsx as bC}from"react/jsx-runtime";import{createContext as vC,useContext as IC,useReducer as g$,useCallback as Bt,useMemo as h$}from"react";var y$=150;function Cd(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}i(Cd,"generateId");function mg(e){return{...e,id:Cd(),timestamp:Date.now()}}i(mg,"createHistoryItem");function pg(e){return{...e,id:Cd(),startTime:Date.now()}}i(pg,"createToolCall");function x$(e,t){switch(t.type){case"SET_STREAMING_STATE":return{...e,streamingState:t.payload};case"APPEND_TO_RESPONSE":return{...e,currentResponse:e.currentResponse+t.payload};case"CLEAR_RESPONSE":return{...e,currentResponse:""};case"ADD_HISTORY_ITEM":let n=[...e.history,t.payload];if(n.length<=y$)return{...e,history:n};let r=0,o=0;for(let a=n.length-1;a>=0;a--)if(n[a]?.type==="user"&&(r++,r>50)){o=a;break}let s=o>0?n.slice(o):n;return{...e,history:s};case"UPDATE_HISTORY_ITEM":return{...e,history:e.history.map(a=>a.id===t.payload.id?{...a,...t.payload.updates}:a)};case"CLEAR_HISTORY":return{...e,history:[]};case"ADD_TOOL_CALL":return{...e,pendingToolCalls:[...e.pendingToolCalls,t.payload]};case"UPDATE_TOOL_CALL":return{...e,pendingToolCalls:e.pendingToolCalls.map(a=>a.id===t.payload.id?{...a,...t.payload.updates}:a)};case"CLEAR_TOOL_CALLS":return{...e,pendingToolCalls:[]};case"SET_SESSION_ID":return{...e,sessionId:t.payload};case"SET_PROVIDER":return{...e,provider:t.payload};case"SET_MODEL":return{...e,model:t.payload};case"SET_TOKEN_USAGE":return{...e,tokenUsage:t.payload};case"SET_ERROR":return{...e,error:t.payload};case"SET_LOADING":return{...e,isLoading:t.payload};case"RESET_STATE":return{...ep,sessionId:e.sessionId};default:return e}}i(x$,"uiReducer");var kC=vC(null),RC=vC(null);function bd({children:e,initialState:t}){let[n,r]=g$(x$,{...ep,...t}),o=Bt(L=>{r({type:"SET_STREAMING_STATE",payload:L})},[]),s=Bt(L=>{r({type:"APPEND_TO_RESPONSE",payload:L})},[]),a=Bt(()=>{r({type:"CLEAR_RESPONSE"})},[]),c=Bt(L=>{let X=mg(L);r({type:"ADD_HISTORY_ITEM",payload:X})},[]),l=Bt((L,X)=>{r({type:"UPDATE_HISTORY_ITEM",payload:{id:L,updates:X}})},[]),d=Bt(()=>{r({type:"CLEAR_HISTORY"})},[]),m=Bt(L=>{let X=pg(L);return r({type:"ADD_TOOL_CALL",payload:X}),X.id},[]),p=Bt((L,X)=>{r({type:"UPDATE_TOOL_CALL",payload:{id:L,updates:X}})},[]),g=Bt(()=>{r({type:"CLEAR_TOOL_CALLS"})},[]),x=Bt(L=>{r({type:"SET_SESSION_ID",payload:L})},[]),y=Bt(L=>{r({type:"SET_MODE",payload:L})},[]),T=Bt(L=>{r({type:"SET_PROVIDER",payload:L})},[]),w=Bt(L=>{r({type:"SET_MODEL",payload:L})},[]),v=Bt(L=>{r({type:"SET_TOKEN_USAGE",payload:L})},[]),O=Bt(L=>{r({type:"SET_ERROR",payload:L})},[]),P=Bt(L=>{r({type:"SET_LOADING",payload:L})},[]),D=h$(()=>({setStreamingState:o,appendToResponse:s,clearResponse:a,addHistoryItem:c,updateHistoryItem:l,clearHistory:d,addToolCall:m,updateToolCall:p,clearToolCalls:g,setSessionId:x,setMode:y,setProvider:T,setModel:w,setTokenUsage:v,setError:O,setLoading:P}),[o,s,a,c,l,d,m,p,g,x,y,T,w,v,O,P]);return bC(kC.Provider,{value:n,children:bC(RC.Provider,{value:D,children:e})})}i(bd,"UIStateProvider");function oc(){let e=IC(kC);if(!e)throw new Error("useUIState must be used within a UIStateProvider");return e}i(oc,"useUIState");function ic(){let e=IC(RC);if(!e)throw new Error("useUIActions must be used within a UIStateProvider");return e}i(ic,"useUIActions");function EC(){let e=oc(),t=ic();return{state:e,actions:t}}i(EC,"useUI");function gg(){return ne()}i(gg,"useTheme");import{jsxs as Qr,jsx as vd,Fragment as w$}from"react/jsx-runtime";import{useMemo as S$}from"react";var T$=80,C$=7,b$={command:">",file:"\u{1F4C4}",history:"\u23F1",argument:"\u2022",snippet:"\u25C7",skill:"\u2605"};function v$(e,t,n){if(t<=n)return{start:0,end:t};let r=Math.floor(n/2),o=e-r,s=o+n;return o<0?(o=0,s=n):s>t&&(s=t,o=t-n),{start:o,end:s}}i(v$,"getVisibleRange");function I$({suggestion:e,isSelected:t,width:n}){let r=gg(),o=e.icon||e.type&&b$[e.type]||"",s=o?Xn(o)+1:0,a=Xn(e.displayText||e.text),c=e.description?Xn(e.description):0,l=Math.min(a,n-s-2),d=n-s-l-3,m=Math.max(0,d),p=xa(e.displayText||e.text,l),g=e.description?xa(e.description,m):"";return Qr(k,{children:[o&&Qr(b,{color:t?r.colors.accent:r.colors.dim,children:[o," "]}),vd(b,{color:t?r.colors.primary:r.colors.text,bold:t,children:p}),g&&Qr(w$,{children:[vd(b,{children:" "}),vd(b,{color:r.colors.dim,children:xa(e.description||"",m)})]}),t&&Qr(b,{color:r.colors.accent,children:[" ","\u25C0"]})]})}i(I$,"SuggestionItem");function Id({suggestions:e,selectedIndex:t,visible:n,maxVisible:r=C$,width:o=T$,showCount:s=!1}){let a=gg();if(!n||e.length===0)return null;let{start:c,end:l}=S$(()=>v$(t,e.length,r),[t,e.length,r]),d=e.slice(c,l);return Qr(k,{flexDirection:"column",marginLeft:2,children:[c>0&&Qr(b,{color:a.colors.dim,children:[" ","\u25B2 ",c," more..."]}),d.map((m,p)=>{let x=c+p===t;return vd(I$,{suggestion:m,isSelected:x,width:o},m.id)}),l<e.length&&Qr(b,{color:a.colors.dim,children:[" ","\u25BC ",e.length-l," more..."]}),s&&Qr(b,{color:a.colors.dim,children:[t+1,"/",e.length]})]})}i(Id,"SuggestionsDisplay");import{jsx as xs,jsxs as k$}from"react/jsx-runtime";var hg=i(({reserveSpace:e,width:t,hidden:n=!1,mode:r="inline"})=>{let o=Bo(),s=ne("dark");if(n)return null;if(!o)return e?xs(k,{height:8}):null;let{state:a,suggestions:c}=o;return a.visible&&c.length>0?r==="overlay"?k$(k,{flexDirection:"column",borderStyle:"round",borderColor:s.colors.accent,paddingX:1,marginTop:1,children:[xs(b,{color:s.colors.accent,bold:!0,children:"Suggestions"}),xs(Id,{suggestions:c,selectedIndex:a.selectedIndex,visible:a.visible,maxVisible:7,width:Math.max(20,t-6)})]}):xs(k,{height:8,children:xs(Id,{suggestions:c,selectedIndex:a.selectedIndex,visible:a.visible,maxVisible:7,width:Math.max(20,t-2)})}):e?xs(k,{height:8}):null},"PromptSuggestionsSurface");import{jsxs as On,jsx as In,Fragment as yg}from"react/jsx-runtime";import R$,{useEffect as E$,useState as M$}from"react";var ws=15,MC=Math.max(1,ws-2),xg=i(({confirm:e,request:t})=>e?On(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,width:"100%",children:[On(b,{color:"yellow",bold:!0,children:[te("dialog.confirm")," ",e.prompt]}),e.planContent?In(A$,{content:e.planContent}):null,e.instruction?In(b,{dimColor:!0,children:e.instruction}):null]}):t?On(k,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,marginTop:1,width:"100%",children:[t.kind==="select"?On(yg,{children:[On(b,{color:"cyan",bold:!0,children:[te("dialog.select")," ",t.title]}),(()=>{let n=t.options??[],r=t.visibleSelectOptions??5,o=t.focusedIndex??0,s=n.length,a=0;if(s>r){let d=Math.floor(r/2);a=Math.max(0,Math.min(o-d,s-r))}let c=a,l=Math.max(0,s-a-r);return On(yg,{children:[c>0?In(b,{dimColor:!0,children:te("select.more_above",{count:c})}):null,n.slice(a,a+r).map((d,m)=>{let p=a+m,g=p===o,x=t.selectedIndices?.includes(p)??!1,y=g?"\u276F ":" ",T=x?" \u2713":"",w=d.description?` - ${d.description}`:"";return In(b,{color:g?"cyan":void 0,dimColor:!g,children:`${y}${d.label}${w}${T}`},`${d.value}-${p}`)}),l>0?In(b,{dimColor:!0,children:te("select.more_below",{count:l})}):null]})})(),In(b,{dimColor:!0,children:t.multiSelect?te("select.multiselect_hint"):te("select.navigate_hint")})]}):On(yg,{children:[On(b,{color:"cyan",bold:!0,children:[te("dialog.input")," ",t.prompt]}),t.defaultValue!==void 0?In(b,{dimColor:!0,children:`${te("input.default")} ${t.defaultValue}`}):null,In(b,{dimColor:!0,children:`${te("input.value")} ${t.buffer||te("input.type_response")}`}),In(b,{dimColor:!0,children:te("select.confirm_hint")})]}),t.error?In(b,{color:"red",children:t.error}):null]}):null,"DialogSurface"),A$=i(({content:e})=>{let t=R$.useMemo(()=>e.split(`
313
- `),[e]),n=t.length,r=n>ws,[o,s]=M$(0);E$(()=>{s(d=>{let m=Math.max(0,n-ws);return d>m?m:d})},[n]),mu((d,m)=>{if(!r)return;let p=Math.max(0,n-ws);m.upArrow?s(g=>Math.max(0,g-1)):m.downArrow?s(g=>Math.min(p,g+1)):m.pageUp?s(g=>Math.max(0,g-MC)):m.pageDown&&s(g=>Math.min(p,g+MC))},{isActive:!0});let a=t.slice(o,o+ws),c=o,l=Math.max(0,n-o-ws);return On(k,{flexDirection:"column",marginTop:1,children:[r&&c>0?On(b,{dimColor:!0,children:["\u2026 ",c," more line",c===1?"":"s"," above"]}):null,a.map((d,m)=>In(b,{children:d},`plan-line-${o+m}`)),r&&l>0?On(b,{dimColor:!0,children:["\u2026 ",l," more line",l===1?"":"s"," below"]}):null,r?In(b,{dimColor:!0,children:"PgUp/PgDn/\u2191\u2193 to scroll"}):null]})},"PlanScrollPanel");import{jsxs as sc,jsx as _$}from"react/jsx-runtime";function AC(e){let t=e.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}i(AC,"normalizePendingPreview");function _C(e){if(e.length===0)return;let t=AC(e[e.length-1]??"");return e.length===1?`Queued 1 follow-up: ${t} (Esc removes it)`:`Queued ${e.length} follow-ups. Latest: ${t} (Esc removes latest)`}i(_C,"formatPendingInputsSummary");function wg(e){if(e.length===0)return[];let t=e.length;return e.map((n,r)=>({index:r+1,total:t,preview:AC(n)}))}i(wg,"formatPendingInputsLines");function PC(e){let t=wg(e);return t.length===0?void 0:[...t.map(o=>`\u23F3 [${o.index}/${o.total}] ${o.preview}`)," \u2191 pull all into editor \xB7 Esc drops latest"].join(`
314
- `)}i(PC,"formatPendingInputsBudgetText");var Sg=i(({pendingInputs:e})=>{let t=wg(e);if(t.length===0)return null;let n=ne("dark");return sc(k,{flexDirection:"column",children:[t.map(r=>sc(k,{children:[sc(b,{color:n.colors.hint,children:["\u23F3"," "]}),sc(b,{color:n.colors.dim,children:["[",r.index,"/",r.total,"] ",r.preview]})]},r.index)),_$(k,{children:sc(b,{color:n.colors.dim,children:[" ","\u2191 pull all into editor \xB7 Esc drops latest"]})})]})},"QueuedCommandsSurface");import{jsx as $C}from"react/jsx-runtime";function P$(e,t){switch(e){case"warning":return t.warning;case"accent":return t.accent;default:return t.dim}}i(P$,"resolveNotificationColor");var kd=i(({notifications:e})=>{let t=e.filter(r=>r.text.trim().length>0),n=ne("dark");return t.length===0?null:$C(k,{flexDirection:"column",paddingX:1,children:t.map(r=>$C(b,{color:P$(r.tone,n.colors),children:r.text},r.id))})},"NotificationsSurface");import{jsx as LC}from"react/jsx-runtime";var Tg=i(({notices:e})=>{let t=e.filter(r=>r.trim().length>0);if(t.length===0)return null;let n=ne("dark");return LC(k,{flexDirection:"column",paddingX:1,children:t.map((r,o)=>LC(b,{color:n.colors.dim,children:r},`${r}-${o}`))})},"StatusNoticesSurface");import{jsxs as OC,jsx as $$}from"react/jsx-runtime";var Rd=i(({text:e})=>{let t=e?.trim();if(!t)return null;let n=ne("dark");return OC(k,{paddingX:1,children:[OC(b,{color:n.colors.hint,children:["\u22EF"," "]}),$$(b,{color:n.colors.dim,children:t})]})},"StashNotice");import{jsx as jo,jsxs as L$}from"react/jsx-runtime";function DC({text:e,accent:t=!1,selected:n=!1}){let r=ne("dark");return jo(k,{marginRight:1,children:jo(b,{color:t?r.colors.accent:r.colors.primary,bold:n||t,children:`[ ${e} ]`})})}i(DC,"Pill");var Ed=i(({items:e,overflowLabel:t,ctaHint:n,showSpinner:r=!1})=>{let o=e.filter(s=>s.label.trim().length>0);return o.length===0&&!t&&!n&&!r?null:L$(k,{flexDirection:"row",paddingX:1,children:[r?jo(k,{marginRight:1,children:jo(vn,{})}):null,o.map(s=>jo(DC,{text:s.hint?`${s.label} (${s.hint})`:s.label,accent:s.accent,selected:s.selected},s.id)),t?jo(DC,{text:t}):null,n?jo(b,{dimColor:!0,children:n}):null]})},"BackgroundTaskBar");import NC,{createContext as HC,useContext as FC,useReducer as O$,useCallback as Ge,useRef as D$,useEffect as BC}from"react";function N$(e){return e.agentId===void 0&&e.priority==="user"&&e.mode==="prompt"}i(N$,"isMainThreadPrompt");function vg(){return Kn().getSnapshot().filter(N$)}i(vg,"getMainThreadPrompts");function Cg(){return vg().map(e=>e.content)}i(Cg,"getMainThreadPromptContents");var bg={state:on.Idle,currentResponse:"",error:void 0,abortController:void 0,isThinking:!1,thinkingCharCount:0,thinkingContent:"",currentTool:void 0,toolInputCharCount:0,toolInputContent:"",iterationHistory:[],currentIteration:1,maxIter:200,isCompacting:!1,pendingInputs:[],roundStartedAt:null};function Ig(){let e={...bg,pendingInputs:Cg()},t=new Set,n="",r="",o=0,s=null,a=!1,c=80,l=i(()=>{for(let y of t)y(e)},"notify"),d=i(()=>{let y=Cg();if(y.length===e.pendingInputs.length){let T=!0;for(let w=0;w<y.length;w++)if(y[w]!==e.pendingInputs[w]){T=!1;break}if(T)return}e={...e,pendingInputs:y},l()},"syncReactStateFromQueue"),m=Kn().subscribe(()=>{d()}),p=i(()=>Kn().dequeue({maxPriority:"user",mode:"prompt"}).map(T=>T.content),"drainOurSlice"),g=i(()=>{if(s&&(clearTimeout(s),s=null),n||r||o>0){let T=e.thinkingContent+r,w=r?T.length:e.thinkingCharCount+o;e={...e,currentResponse:e.currentResponse+n,thinkingContent:T,thinkingCharCount:w,...r||o>0?{isThinking:!0}:{}},n="",r="",o=0,l()}},"flushPendingUpdates"),x=i(()=>{s||(s=setTimeout(g,c))},"scheduleFlush");return{getState:i(()=>e,"getState"),setState:i(y=>{g(),e={...e,state:y},l()},"setState"),startStreaming:i(()=>{a=!1,n="",r="",o=0,s&&(clearTimeout(s),s=null),e={...e,state:on.Responding,currentResponse:"",abortController:new AbortController,error:void 0,roundStartedAt:Date.now()},l()},"startStreaming"),stopStreaming:i(()=>{g(),e={...e,state:on.Idle,abortController:void 0,roundStartedAt:null},l()},"stopStreaming"),appendResponse:i(y=>{a||(n+=y,x())},"appendResponse"),clearResponse:i(()=>{g(),e={...e,currentResponse:""},l()},"clearResponse"),setError:i(y=>{g(),e={...e,error:y,state:y?on.Idle:e.state},l()},"setError"),abort:i(y=>{a=!0,g(),e.abortController?.abort(),n="",r="",o=0,s&&(clearTimeout(s),s=null),y?.preservePendingInputs||p(),e={...e,state:on.Idle,abortController:void 0,roundStartedAt:null},l()},"abort"),reset:i(()=>{a=!0,g(),e.abortController?.abort(),n="",r="",o=0,s&&(clearTimeout(s),s=null),p(),e={...bg,pendingInputs:Cg()},a=!1,l()},"reset"),isStreaming:i(()=>e.state===on.Responding||e.state===on.WaitingForConfirmation,"isStreaming"),subscribe:i(y=>(t.add(y),()=>{t.delete(y)}),"subscribe"),startThinking:i(()=>{g(),e={...e,isThinking:!0,thinkingCharCount:0,thinkingContent:""},l()},"startThinking"),appendThinkingChars:i(y=>{a||(o+=y,x())},"appendThinkingChars"),appendThinkingContent:i(y=>{a||(r+=y,x())},"appendThinkingContent"),stopThinking:i(()=>{g(),e={...e,isThinking:!1,thinkingCharCount:0},l()},"stopThinking"),clearThinkingContent:i(()=>{g(),e={...e,isThinking:!1,thinkingCharCount:0,thinkingContent:""},l()},"clearThinkingContent"),setCurrentTool:i(y=>{g(),e={...e,currentTool:y,toolInputCharCount:0,toolInputContent:""},l()},"setCurrentTool"),appendToolInputChars:i(y=>{e={...e,toolInputCharCount:e.toolInputCharCount+y},l()},"appendToolInputChars"),appendToolInputContent:i(y=>{e.toolInputContent.length<240&&(e={...e,toolInputContent:(e.toolInputContent+y).slice(0,240)},l())},"appendToolInputContent"),clearToolInputContent:i(()=>{e={...e,toolInputContent:""},l()},"clearToolInputContent"),getSignal:i(()=>e.abortController?.signal,"getSignal"),getFullResponse:i(()=>e.currentResponse+n,"getFullResponse"),getThinkingContent:i(()=>e.thinkingContent+r,"getThinkingContent"),startNewIteration:i(y=>{g(),e.thinkingContent||e.currentResponse?e={...e,thinkingContent:"",thinkingCharCount:0,currentResponse:"",isThinking:!1,currentTool:void 0,toolInputCharCount:0,toolInputContent:"",currentIteration:y}:e={...e,currentIteration:y},l()},"startNewIteration"),clearIterationHistory:i(()=>{g(),e={...e,iterationHistory:[],currentIteration:1,maxIter:bg.maxIter,thinkingContent:"",thinkingCharCount:0,currentResponse:"",currentTool:void 0,toolInputCharCount:0,toolInputContent:""},l()},"clearIterationHistory"),setMaxIter:i(y=>{g(),e={...e,maxIter:y},l()},"setMaxIter"),startCompacting:i(()=>{g(),e={...e,isCompacting:!0},l()},"startCompacting"),stopCompacting:i(()=>{g(),e={...e,isCompacting:!1},l()},"stopCompacting"),addPendingInput:i(y=>{let T=y.trim();T&&(vg().length>=5||(g(),Kn().enqueue({priority:"user",mode:"prompt",content:T})))},"addPendingInput"),removeLastPendingInput:i(()=>{let y=vg(),T=y[y.length-1];T&&(g(),Kn().dequeue({maxPriority:"user",mode:"prompt",id:T.id}))},"removeLastPendingInput"),shiftPendingInput:i(()=>(g(),Kn().dequeue({maxPriority:"user",mode:"prompt",limit:1})[0]?.content),"shiftPendingInput"),clearPendingInputs:i(()=>{g(),p()},"clearPendingInputs"),consumePendingInputs:i(()=>(g(),p()),"consumePendingInputs"),dispose:i(()=>{m()},"dispose")}}i(Ig,"createStreamingManager");var WC=HC(null),UC=HC(null);function Md({children:e,onStateChange:t}){let n=D$(Ig()),[,r]=O$(ce=>ce+1,0);BC(()=>n.current.subscribe(De=>{r(),t?.(De)}),[t]),BC(()=>{let ce=n.current;return()=>{ce.dispose()}},[]);let o=Ge(()=>{n.current.startStreaming()},[]),s=Ge(()=>{n.current.stopStreaming()},[]),a=Ge(ce=>{n.current.appendResponse(ce)},[]),c=Ge(()=>{n.current.clearResponse()},[]),l=Ge(ce=>{n.current.setError(ce)},[]),d=Ge(ce=>{n.current.abort(ce)},[]),m=Ge(()=>{n.current.reset()},[]),p=Ge(()=>{n.current.startThinking()},[]),g=Ge(ce=>{n.current.appendThinkingChars(ce)},[]),x=Ge(ce=>{n.current.appendThinkingContent(ce)},[]),y=Ge(()=>{n.current.stopThinking()},[]),T=Ge(()=>{n.current.clearThinkingContent()},[]),w=Ge(ce=>{n.current.setCurrentTool(ce)},[]),v=Ge(ce=>{n.current.appendToolInputChars(ce)},[]),O=Ge(ce=>{n.current.appendToolInputContent(ce)},[]),P=Ge(()=>{n.current.clearToolInputContent()},[]),D=Ge(()=>n.current.getSignal(),[]),L=Ge(()=>n.current.getFullResponse(),[]),X=Ge(()=>n.current.getThinkingContent(),[]),I=Ge(ce=>{n.current.startNewIteration(ce)},[]),ie=Ge(()=>{n.current.clearIterationHistory()},[]),Te=Ge(ce=>{n.current.setMaxIter(ce)},[]),K=Ge(()=>{n.current.startCompacting()},[]),q=Ge(()=>{n.current.stopCompacting()},[]),M=Ge(ce=>{n.current.addPendingInput(ce)},[]),C=Ge(()=>{n.current.removeLastPendingInput()},[]),Z=Ge(()=>n.current.shiftPendingInput(),[]),ke=Ge(()=>{n.current.clearPendingInputs()},[]),ve=Ge(()=>n.current.consumePendingInputs(),[]),Se={startStreaming:o,stopStreaming:s,appendResponse:a,clearResponse:c,setError:l,abort:d,reset:m,startThinking:p,appendThinkingChars:g,appendThinkingContent:x,stopThinking:y,clearThinkingContent:T,setCurrentTool:w,appendToolInputChars:v,appendToolInputContent:O,clearToolInputContent:P,getSignal:D,getFullResponse:L,getThinkingContent:X,startNewIteration:I,clearIterationHistory:ie,setMaxIter:Te,startCompacting:K,stopCompacting:q,addPendingInput:M,removeLastPendingInput:C,shiftPendingInput:Z,clearPendingInputs:ke,consumePendingInputs:ve};return NC.createElement(WC.Provider,{value:n.current.getState()},NC.createElement(UC.Provider,{value:Se},e))}i(Md,"StreamingProvider");function cc(){let e=FC(WC);if(!e)throw new Error("useStreamingState must be used within a StreamingProvider");return e}i(cc,"useStreamingState");function lc(){let e=FC(UC);if(!e)throw new Error("useStreamingActions must be used within a StreamingProvider");return e}i(lc,"useStreamingActions");function jC(){let e=cc(),t=lc(),n=e.state===on.Responding||e.state===on.WaitingForConfirmation;return{state:e,actions:t,isStreaming:n}}i(jC,"useStreaming");import{useCallback as B$,useRef as H$}from"react";var F$=500;function W$(e={}){let{onKey:t,onEsc:n,onCtrlC:r,enabled:o=!0}=e,s=H$(0),{exit:a}=Ur(),c=B$(l=>{if(!o)return!1;if(l.name==="escape"){let d=Date.now(),m=d-s.current<F$;return s.current=d,m&&(l.name="escape-escape"),n?.(),t?.(l),!0}return l.ctrl&&l.name==="c"?(r?.(),t?.(l),!0):l.ctrl&&l.name==="d"?(a(),!0):(t?.(l),!1)},[o,a,r,n,t]);return sn(c,{isActive:o}),{lastEscTime:s.current}}i(W$,"useKeypress");function U$(e){return{is:i((t,n)=>!(e.name!==t||n?.ctrl!==void 0&&e.ctrl!==n.ctrl||n?.shift!==void 0&&e.shift!==n.shift||n?.meta!==void 0&&e.meta!==n.meta),"is"),isCtrl:i(t=>e.ctrl&&e.name===t,"isCtrl"),isShift:i(t=>e.shift&&e.name===t,"isShift"),isArrow:i(()=>["up","down","left","right"].includes(e.name),"isArrow"),isChar:i(()=>e.sequence?.length===1&&!e.ctrl&&!e.meta,"isChar"),getChar:i(()=>e.sequence?.length===1?e.sequence:null,"getChar")}}i(U$,"createKeyMatcher");import{useCallback as j$,useSyncExternalStore as G$}from"react";function K$(e){return e.agentId===void 0&&e.priority==="user"&&e.mode==="prompt"}i(K$,"isMainThreadPrompt");var kg=null,Ad=Object.freeze([]);function GC(){let e=Kn().getSnapshot();return e===kg||(kg=e,Ad=Object.freeze(e.filter(K$))),Ad}i(GC,"getQueueSliceSnapshot");function KC(){let e=j$(t=>Kn().subscribe(t),[]);return G$(e,GC,GC)}i(KC,"useQueuedPrompts");function V$(){return KC().map(t=>t.content)}i(V$,"useQueuedPromptContents");function z$(){kg=null,Ad=Object.freeze([])}i(z$,"_resetQueuedPromptsCacheForTests");async function uc(e){return{messages:e.existingMessages??[],uiHistory:e.existingUiHistory?.map(t=>({...t})),lineage:e.existingLineage??void 0,artifactLedger:e.existingArtifactLedger?.map(t=>({...t,metadata:t.metadata?{...t.metadata}:void 0})),sessionId:e.sessionId??dc(),title:"",gitRoot:e.gitRoot,runtimeInfo:e.runtimeInfo,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString()}}i(uc,"createInteractiveContext");function dc(){let e=new Date,t=e.toISOString().split("T")[0].replace(/-/g,""),n=e.toTimeString().split(" ")[0].replace(/:/g,"");return`${t}_${n}`}i(dc,"generateSessionId");function rr(e){e.lastAccessed=new Date().toISOString()}i(rr,"touchContext");async function fc(e){let t=await Cx({userKodaxDir:lx(),projectRoot:e.projectRoot}),n;return{getGuardrail:i(()=>n||(n=bx({rules:t.merged,claudeMd:ux(e.getAgentsFiles()),getToolProjection:i(o=>(_l(o)??fx(o))?.toClassifierInput,"getToolProjection"),resolveProvider:i(o=>{try{return po(o)}catch{return}},"resolveProvider"),defaultProvider:e.getCurrentProviderName(),defaultModel:e.getCurrentModel()??"",getDefaultProvider:e.getCurrentProviderName,getDefaultModel:i(()=>{let o=e.getCurrentModel();return o||(e.log?.("warn","[auto-mode] classifier defaultModel is empty; main session has no model set \u2014 classifier will likely fail"),"")},"getDefaultModel"),askUser:e.askUser,log:e.log,onEngineChange:e.onEngineChange,projectRoot:e.projectRoot,extraCollectors:e.extraCollectors,initialEngine:e.autoModeSettings.engine,timeoutMs:e.autoModeSettings.timeoutMs,userSettings:e.autoModeSettings.classifierModel,envVar:e.autoModeSettings.classifierModelEnv}),n),"getGuardrail"),rulesLoadResult:t}}i(fc,"bootstrapAutoMode");var Ss=class{static{i(this,"MemorySessionStorage")}sessions=new Map;async save(t,n){let r=this.sessions.get(t);this.sessions.set(t,{...structuredClone(n),scope:n.scope??r?.scope??"user",uiHistory:n.uiHistory??r?.uiHistory,extensionState:n.extensionState??r?.extensionState,artifactLedger:n.artifactLedger??r?.artifactLedger,extensionRecords:n.extensionRecords??r?.extensionRecords,lineage:hn(n.messages,n.lineage??r?.lineage)})}async load(t){return structuredClone(this.sessions.get(t)??null)}async getLineage(t){return structuredClone(this.sessions.get(t)?.lineage??null)}async setActiveEntry(t,n,r){let o=this.sessions.get(t);if(!o?.lineage)return null;let s=Ci(o.lineage,n,r);if(!s)return null;let a={...structuredClone(o),messages:Et(s),lineage:s};return this.sessions.set(t,a),structuredClone(a)}async setLabel(t,n,r){let o=this.sessions.get(t);if(!o?.lineage)return null;let s=bi(o.lineage,n,r);if(!s)return null;let a={...structuredClone(o),lineage:s};return this.sessions.set(t,a),structuredClone(a)}async fork(t,n,r){let o=this.sessions.get(t);if(!o?.lineage)return null;let s=ki(o.lineage,n);if(!s)return null;let a=r?.sessionId??await Ti(),c={messages:Et(s),title:r?.title??o.title,gitRoot:o.gitRoot,uiHistory:o.uiHistory?o.uiHistory.map(l=>({...l})):void 0,extensionState:o.extensionState?structuredClone(o.extensionState):void 0,artifactLedger:o.artifactLedger?structuredClone(o.artifactLedger):void 0,extensionRecords:o.extensionRecords?structuredClone(o.extensionRecords):void 0,lineage:s};return this.sessions.set(a,c),{sessionId:a,data:structuredClone(c)}}async rewind(t,n){let r=this.sessions.get(t);if(!r?.lineage)return null;let o=n??vi(r.lineage);if(!o)return null;let s=Ii(r.lineage,o);if(!s)return null;let a={...r,messages:Et(s),lineage:s};return this.sessions.set(t,a),structuredClone(a)}async list(t){return Array.from(this.sessions.entries()).filter(([,n])=>(n.scope??"user")==="user").map(([n,r])=>({id:n,title:r.title,msgCount:r.lineage?yo(r.lineage):r.messages.length}))}async delete(t){this.sessions.delete(t)}async deleteAll(t){this.sessions.clear()}};function X$(){return new Ss}i(X$,"createMemorySessionStorage");import*as VC from"child_process";import*as zC from"util";import _d from"chalk";var Y$=zC.promisify(VC.exec),q$={maxBuffer:1024*1024,timeout:3e4,maxOutputLength:8e3,maxErrorLength:4e3};async function Pd(e,t={}){let n={...q$,...t},r=e.trim(),o=up(r);if(o)return o.startsWith("[Blocked]")&&(console.log(_d.yellow(`
315
- ${o}`)),console.log()),o;try{console.log(_d.dim(`
316
- [Executing: ${r}]`));let{stdout:s,stderr:a}=await Y$(r,{cwd:n.cwd,maxBuffer:n.maxBuffer,timeout:n.timeout,windowsHide:!0}),c="";return s&&(c+=s),a&&(c+=(c?`
317
- `:"")+`[stderr] ${a}`),c.length>n.maxOutputLength&&(c=c.slice(0,n.maxOutputLength)+`
318
- ...[output truncated]`),console.log(_d.dim(c||"[No output]")),console.log(),`[Shell command executed: ${r}]
319
-
320
- Output:
321
- ${c||"(no output)"}`}catch(s){let c=(s instanceof Error?s:new Error(String(s))).message;return c.length>n.maxErrorLength&&(c=c.slice(0,n.maxErrorLength)+`
322
- ...[error truncated]`),console.log(_d.red(`
323
- [Shell Error: ${c}]`)),console.log(),`[Shell command failed: ${r}]
324
-
325
- Error: ${c}`}}i(Pd,"executeShellCommand");async function Rg(e,t={}){if(e.startsWith("!")){let n=e.slice(1).trim();return Pd(n,t)}return e}i(Rg,"processSpecialSyntax");function Q$(e){return e.trim().startsWith("!")}i(Q$,"isShellCommand");function J$(e){return e.startsWith("[Shell command executed:")||e.startsWith("[Shell:")}i(J$,"isShellCommandSuccess");function mc(e){return e.startsWith("[Shell command executed:")||e.startsWith("[Shell command failed:")||e.startsWith("[Shell:")||e.startsWith("[Blocked]")}i(mc,"isShellCommandHandled");function $d(e,t,n){let r=e.trim();return{type:"info",icon:"\u23F3",text:/\bretry\s+\d+\/\d+\b/i.test(r)||/\b\d+\/\d+\b/.test(r)?r:`${r} \xB7 retry ${t}/${n}`}}i($d,"createRetryHistoryItem");function Eg(e,t,n,r){e($d(t,n,r))}i(Eg,"emitRetryHistoryItem");function Ld(e){let{recoveryAction:t,attempt:n,maxAttempts:r,delayMs:o,stage:s,fallbackUsed:a}=e,c=Math.round(o/1e3);if(t==="manual_continue")return{type:"info",icon:"\u26A0",text:'Recovery exhausted. Type "continue" to retry or "stop" to cancel.'};if(t==="non_streaming_fallback"||a)return{type:"info",icon:"\u23F3",text:"Stream unstable, switching to non-streaming mode"};if(t==="sanitize_thinking_and_retry")return{type:"info",icon:"\u23F3",text:"Provider rejected replay thinking, sanitizing history and retrying"};let l;switch(s){case"before_first_delta":case"before_request_accepted":l="Provider request timed out";break;case"mid_stream_text":case"mid_stream_thinking":l="Stream interrupted after partial output";break;case"mid_stream_tool_input":l="Stream interrupted during tool input";break;case"post_tool_execution_pre_assistant_close":l="Stream interrupted after tool execution";break;default:l="Stream interrupted";break}let d=t==="stable_boundary_retry"?"recovering":"retrying";return{type:"info",icon:"\u23F3",text:c>0?`${l} \xB7 ${d} ${n}/${r} in ${c}s`:`${l} \xB7 ${d} ${n}/${r}`}}i(Ld,"createRecoveryHistoryItem");function Mg(e,t){e(Ld(t))}i(Mg,"emitRecoveryHistoryItem");import{jsx as se,jsxs as Gt,Fragment as K1}from"react/jsx-runtime";import Gv,{useState as We,useCallback as z,useRef as me,useEffect as He,useMemo as ue}from"react";import{jsx as or,Fragment as Z$,jsxs as Od}from"react/jsx-runtime";var Ag=" | ",XC=i(({searchActive:e=!1,selectionActive:t=!1,showAllActive:n=!1,searchQuery:r="",searchCurrent:o=0,searchCount:s=0,searchDetailText:a,pendingLiveUpdates:c=0,secondaryText:l,noticeText:d})=>{let m=ne("dark"),p=r.trim(),g=a?.trim(),x=l?.trim(),y=d?.trim(),T=e?p?`Search /${p}`:"Search":"Transcript",w=e?`Enter jump | n/N next/prev | Ctrl+E ${n?"collapse":"show all"} | Esc close | Ctrl+O/q back`:t?`PgUp/PgDn page | j/k scroll | / search | n/N matches | Ctrl+E ${n?"collapse":"show all"} | Esc clear focus | Ctrl+O/q back`:`PgUp/PgDn page | j/k scroll | \u2190/\u2192 select | / search | n/N matches | Ctrl+E ${n?"collapse":"show all"} | s dump | Ctrl+O/q/Esc back`,v=c>0?c===1?"1 new update":`${c} new updates`:void 0,O=e&&s>0?`${Math.max(0,o)}/${s}`:void 0,P=e&&g||x,D=!!(P||y);return Od(k,{flexDirection:"column",children:[Od(k,{paddingX:1,children:[or(b,{color:m.colors.dim,children:T}),or(b,{dimColor:!0,children:Ag}),or(b,{color:m.colors.dim,children:w}),O||v?or(k,{flexGrow:1}):null,O?Od(Z$,{children:[or(b,{dimColor:!0,children:O}),v?or(b,{dimColor:!0,children:Ag}):null]}):null,v?or(b,{color:m.colors.accent,bold:!0,children:v}):null]}),D?Od(k,{paddingX:1,children:[P?or(b,{color:m.colors.dim,children:P}):null,P&&y?or(b,{dimColor:!0,children:Ag}):null,y?or(b,{color:m.colors.accent,bold:!0,children:y}):null]}):null]})},"TranscriptModeFooter");import{jsx as eL,jsxs as tL}from"react/jsx-runtime";var YC=i(({banner:e,...t})=>tL(k,{flexDirection:"column",children:[e,eL(Wo,{...t,animateSpinners:!1,showFullThinking:!1,showDetailedTools:!1,showLiveProgressRows:!1})]}),"PromptTranscriptSurface");import{jsx as nL,jsxs as rL}from"react/jsx-runtime";var qC=i(({banner:e,windowed:t=!1,showDetailedTools:n=!1,showAllContent:r=!1,...o})=>rL(k,{flexDirection:"column",children:[e,nL(lg,{...o,chromeMode:"hidden",windowed:t,showFullThinking:!0,showDetailedTools:n,showAllContent:r,showLiveProgressRows:!0})]}),"TranscriptModeSurface");import{jsxs as oL,jsx as iL}from"react/jsx-runtime";var QC=i(({text:e,tone:t="success"})=>{let n=e?.trim();if(!n)return null;let r=ne("dark"),o=t==="warning"?r.colors.warning:r.colors.accent,s=t==="warning"?"!":"\u2713";return iL(k,{paddingX:1,backgroundColor:r.colors.inputBackground,children:oL(b,{color:o,children:[s," ",n]})})},"ClipboardToastSurface");import{jsx as Jr,Fragment as sL,jsxs as _g}from"react/jsx-runtime";var aL=" \u23BF ";function cL(e){let t=ne("dark");switch(e){case"cyan":return t.colors.primary;case"green":return t.colors.success;case"red":return t.colors.error;default:return t.colors.dim}}i(cL,"resolveSymbolColor");var lL=i(({row:e})=>{let t=cL(e.symbolColor),n=e.kind!=="item";return _g(k,{flexDirection:"row",children:[Jr(b,{color:t,bold:e.isActive,children:e.symbol}),Jr(b,{children:" "}),Jr(b,{dimColor:n,bold:e.isActive,strikethrough:e.isStrikethrough,children:e.text}),e.evaluatorBadge?_g(sL,{children:[Jr(b,{children:" "}),Jr(b,{dimColor:!0,children:e.evaluatorBadge})]}):null]})},"TodoListRow"),JC=i(({viewModel:e})=>{if(!e.shouldRender||e.rows.length===0)return null;let t=ne("dark").colors.dim;return _g(k,{flexDirection:"row",children:[Jr(b,{color:t,children:aL}),Jr(k,{flexDirection:"column",flexGrow:1,children:e.rows.map((n,r)=>Jr(lL,{row:n},`${n.kind}-${n.id??r}`))})]})},"TodoListSurface");function uL(e){switch(e){case"in_progress":return{symbol:"\u25CF",color:"cyan"};case"completed":return{symbol:"\u2713",color:"green"};case"failed":return{symbol:"\u2717",color:"red"};case"skipped":return{symbol:"\u2298",color:"gray"};case"cancelled":return{symbol:"\u2612",color:"gray"};default:return{symbol:"\u2610",color:"dim"}}}i(uL,"symbolForStatus");function dL(e){for(let t=0;t<e.length;t++)if(e[t].status==="in_progress")return t;for(let t=0;t<e.length;t++)if(e[t].status==="pending")return t;for(let t=e.length-1;t>=0;t--)if(e[t].status==="completed")return t;return 0}i(dL,"pickAnchorIndex");function fL(e){let{symbol:t,color:n}=uL(e.status),r=e.status==="failed"&&e.note?`${e.subject} (${e.note})`:e.subject,o=e.status==="cancelled",s=e.evaluator?`[${e.evaluator}]`:void 0;return{kind:"item",id:e.id,symbol:t,symbolColor:n,text:r,isActive:e.status==="in_progress",isStrikethrough:o,evaluatorBadge:s}}i(fL,"buildItemRow");function mL(e){return{kind:"summary_done",symbol:"\u2713",symbolColor:"green",text:`${e} done`,isActive:!1}}i(mL,"buildDoneSummary");function Pg(e){return{kind:"summary_pending",symbol:"\u2610",symbolColor:"dim",text:`+${e} more`,isActive:!1}}i(Pg,"buildPendingSummary");function pL(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].status==="failed"&&!t.has(n))return n;return-1}i(pL,"pickFailedToPromote");function gL(e,t){let n=e.length;if(n===0)return{visibleIdx:[],hiddenCompletedCount:0,hiddenPendingCount:0};let r=4,o=Math.max(0,t-1),s=Math.min(n,o+r);s-o<r&&o>0&&(o=Math.max(0,s-r)),s-o<r&&s<n&&(s=Math.min(n,o+r));let a=[];for(let d=o;d<s;d++)a.push(d);let c=0,l=0;for(let d=0;d<o;d++)e[d].status==="completed"&&c++;for(let d=s;d<n;d++){let m=e[d].status;(m==="pending"||m==="in_progress")&&l++}return{visibleIdx:a,hiddenCompletedCount:c,hiddenPendingCount:l}}i(gL,"decideWindow");function ZC(e,t){let n=e.length,r=e.reduce((x,y)=>y.status==="completed"?x+1:x,0),o=i((x,y)=>({shouldRender:y,rows:x,completedCount:r,totalCount:n}),"baseVm");if(n<1)return o([],!1);t.now,t.lastAllCompletedAt;let s=dL(e),a=gL(e,s),c=new Set(a.visibleIdx),l=pL(e,c),d=[...a.visibleIdx],m=a.hiddenCompletedCount,p=a.hiddenPendingCount;if(l>=0){let x=-1;for(let y=d.length-1;y>=0;y--){let T=d[y];if(T!==s&&e[T].status==="pending"){x=y;break}}if(x>=0){let y=d[x];d[x]=l,p+=1,d.sort((v,O)=>v-O);let T=d[0],w=0;for(let v=0;v<T;v++)e[v].status==="completed"&&w++;m=w}}let g=[];m>0&&g.push(mL(m));for(let x of d)g.push(fL(e[x]));if(p>0&&g.push(Pg(p)),g.length>6)for(;g.length>6;){let x=!1;for(let y=g.length-1;y>=0;y--){let T=g[y];if(T.kind==="item"&&!T.isActive){g.splice(y,1);let w=g[g.length-1];if(w&&w.kind==="summary_pending"){let v=/\+(\d+) more/.exec(w.text),O=v?Number.parseInt(v[1],10)+1:1;g[g.length-1]=Pg(O)}else g.push(Pg(1));x=!0;break}}if(!x)break}return o(g,!0)}i(ZC,"buildTodoPlanViewModel");function eb(e){let t=[];e.isHistorySearchActive?t.push({id:"search",label:"Search",accent:!0}):e.isTranscriptMode&&t.push({id:"transcript",label:"Transcript"}),e.pendingInputCount>0&&t.push({id:"queue",label:`Queue ${e.pendingInputCount}`}),e.buffering==="buffered-fallback"&&(e.isHistorySearchActive||e.isTranscriptMode)&&t.push({id:"buffered",label:"Buffered"}),e.isTranscriptMode&&e.pendingLiveUpdates>0&&t.push({id:"updates",label:e.pendingLiveUpdates===1?"1 update":`${e.pendingLiveUpdates} updates`,accent:!0});let n=[],r=[...t,...n].map(o=>o.label.trim()).filter(Boolean).join(" | ");return{leftItems:t,rightItems:n,summary:r}}i(eb,"buildFooterHeaderViewModel");function hL(e){return $l(e.provider,e.model,"off",{longRunning:!0})}i(hL,"evaluateSessionTransitionPolicy");function yL(e,t){let n=t.snapshot.model?`${t.snapshot.provider}:${t.snapshot.model}`:t.snapshot.provider,r=[`[Provider Guardrail] ${e} on ${n}: ${t.summary}`],o=t.issues[0]?.detail;return o&&r.push(` ${o}`),t.status==="block"?r.push(" Switch to a provider with durable full-history session semantics before continuing."):t.status==="warn"&&r.push(" Continuing with degraded session semantics."),r}i(yL,"formatSessionTransitionGuardMessage");function Go(e,t,n){let r=hL(e);if(!r||r.status==="allow")return!0;let[o,...s]=yL(t,r);return n(r.status,o,s),r.status!=="block"}i(Go,"enforceSessionTransitionGuard");function xL(e){switch(e.type){case"message":{let n=(typeof e.message.content=="string"?e.message.content:"[complex content]").replace(/\s+/g," ").trim();return`${e.message.role}: ${n.slice(0,48)}${n.length>48?"...":""}`}case"compaction":return`compaction: ${e.summary.slice(0,48)}${e.summary.length>48?"...":""}`;case"branch_summary":return`branch: ${e.summary.slice(0,48)}${e.summary.length>48?"...":""}`;case"archive_marker":return`archived: ${e.summary.slice(0,48)}${e.summary.length>48?"...":""}`;default:return e}}i(xL,"summarizeEntry");function tb(e,t,n,r){let o=t?n?"\\- ":"|- ":"",s=e.active?"*":" ",a=e.entry.id.slice(0,12),c=e.label?` [${e.label}]`:"";r.push(`${t}${o}${s} ${a} ${xL(e.entry)}${c}`);let l=t+(t?n?" ":"| ":"");e.children.forEach((d,m)=>{tb(d,l,m===e.children.length-1,r)})}i(tb,"formatNode");function Dd(e){let t=[];return e.forEach((n,r)=>{tb(n,"",r===e.length-1,t)}),t}i(Dd,"formatSessionTree");var wL=100,SL=/\b(curl|wget|invoke-webrequest|invoke-restmethod|iwr|irm)\b/i,rb=/\b(rm|del|erase|remove-item|rmdir|rd|git clean)\b/i,ob=/\b(npm|pnpm|yarn|pip|choco|winget)\s+(install|add|remove|uninstall|update|upgrade|ci)\b/i,ib=/\b(set-content|add-content|out-file|new-item|copy-item|move-item|rename-item|cp|mv|copy|move|ren|touch)\b/i;function Ts(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(Ts,"readString");function Ht(e,t,n){n&&e.push({label:t,value:n})}i(Ht,"pushField");function TL(e){return e.replace(/\s+/g," ").trim()}i(TL,"normalizeWhitespace");function CL(e,t){if(e.length<=t)return e;let n=Math.ceil((t-3)/2),r=Math.floor((t-3)/2);return`${e.slice(0,n)}...${e.slice(e.length-r)}`}i(CL,"truncateMiddle");function bL(e){let t=e;return t=t.replace(/\b(authorization\s*:\s*bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b((?:authorization|cookie)\s*:\s*)([^'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(bearer\s+)([^\s'"]+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|cookie|session)\b(\s*[:=]\s*)(['"]?)([^'"\s]+)(\3)/gi,(n,r,o,s)=>`${r}${o}${s}[REDACTED]${s}`),t=t.replace(/(--(?:api-key|token|secret|password|cookie)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t=t.replace(/((?:-u|--user)\s+)(\S+)/gi,(n,r)=>`${r}[REDACTED]`),t}i(bL,"maskSensitiveSegments");function nb(e){return CL(bL(TL(e)),wL)}i(nb,"summarizeCommand");function vL(e){return $n(e)?te("intent.read"):rb.test(e)?te("intent.delete"):ob.test(e)?te("intent.deps"):Ln(e)||ib.test(e)?te("intent.modify"):te("intent.execute")}i(vL,"classifyShellIntent");function IL(e){let t=[];return rb.test(e)?t.push(te("risk.destructive")):ob.test(e)?t.push(te("risk.deps")):Ln(e)||ib.test(e)?t.push(te("risk.modify")):$n(e)||t.push(te("risk.unknown")),SL.test(e)&&t.push(te("risk.network")),t}i(IL,"classifyShellRisks");function kL(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.kind=="string")}i(kL,"readSignals");function RL(e){if(e){if(e.some(t=>t.kind==="protected_path"))return te("scope.protected");if(e.some(t=>t.kind==="outside_project"||t.kind==="shell_redirect_outside"))return te("scope.outside")}}i(RL,"scopeFromSignals");function EL(e){if(e._outsideProject===!0)return te("scope.outside");if(e._alwaysConfirm===!0)return te("scope.protected")}i(EL,"scopeFromMarkers");function ML(e){if(!e)return[];let t=[],n=e.some(o=>o.kind==="dangerous_pattern"&&o.severity==="high"),r=e.some(o=>o.kind==="dangerous_pattern"&&o.severity==="medium");return n?t.push(te("risk.destructive")):r&&t.push(te("risk.modify")),e.some(o=>o.kind==="network")&&t.push(te("risk.network")),e.some(o=>o.kind==="package_install")&&t.push(te("risk.deps")),t}i(ML,"risksFromSignals");var AL={Reason:"field.reason",Intent:"field.intent",Target:"field.target",Scope:"field.scope",Risk:"field.risk",Summary:"field.summary"};function _L(e){return te(AL[e])}i(_L,"localizeFieldLabel");function Cs(e,t){return{title:e,fields:t,details:t.map(n=>`${_L(n.label)}: ${n.value}`)}}i(Cs,"buildDisplayFromFields");function Nd(e,t){if(e==="confirm"){let l=Ts(t._message);if(l)return Cs(l,[])}if(e==="exit_plan_mode"){let l=Ts(t.plan),d="Approve plan? (exits plan mode \u2192 accept-edits)";return l?{title:d,fields:[],details:l.split(`
326
- `)}:Cs(d,[])}let n=[],r=Ts(t.path),o=Ts(t.command),s=Ts(t._reason)??Ts(t.justification),a=kL(t._classifierSignals),c=RL(a)??EL(t);switch(Ht(n,"Reason",s),e){case"bash":case"shell_command":{if(o){Ht(n,"Intent",vL(o)),Ht(n,"Scope",c);let l=ML(a),d=l.length>0?l:IL(o);d.length>0&&Ht(n,"Risk",d.join("; ")),Ht(n,"Summary",nb(o))}else Ht(n,"Scope",c);return Cs(e==="bash"?te("tool.bash.title"):te("tool.shell.title"),n)}case"write":return Ht(n,"Intent",te("intent.write_file")),Ht(n,"Target",r),Ht(n,"Scope",c),Cs(te("tool.write.title"),n);case"edit":return Ht(n,"Intent",te("intent.edit_file")),Ht(n,"Target",r),Ht(n,"Scope",c),Cs(te("tool.edit.title"),n);default:return Ht(n,"Intent",te("intent.use_tool",{tool:e})),Ht(n,"Target",r),Ht(n,"Scope",c),o&&Ht(n,"Summary",nb(o)),Cs(te("tool.generic.title",{tool:e}),n)}}i(Nd,"buildToolConfirmationDisplay");function sb(e,t){let n=Nd(e,t);return n.details.length>0?`${n.title}
327
- ${n.details.join(`
328
- `)}`:n.title}i(sb,"buildToolConfirmationPrompt");var $g=[" \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D"," \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D "," \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"];import Ke from"chalk";var Bd=class e{static{i(this,"ShortcutsRegistry")}static instance=null;shortcuts=new Map;static getInstance(){return e.instance||(e.instance=new e),e.instance}static resetInstance(){e.instance=null}register(t){let n=this.shortcuts.get(t.id);this.shortcuts.set(t.id,{definition:t,effectiveBindings:n?.effectiveBindings??t.defaultBindings,handler:n?.handler})}registerAll(t){for(let n of t)this.register(n)}unregister(t){return this.shortcuts.delete(t)}setHandler(t,n){let r=this.shortcuts.get(t);r&&(r.handler=n)}findMatchingShortcut(t,n){let r=null,o=-1/0;for(let s of this.shortcuts.values()){let a=s.definition.context;a!=="global"&&a!==n||this.matchesBinding(t,s.effectiveBindings)&&s.handler&&s.definition.priority>o&&(o=s.definition.priority,r=s)}return r}matchesBinding(t,n){for(let r of n){let o=this.normalizeKeyName(t.name),s=this.normalizeKeyName(r.key);if(o===s){let a=(r.ctrl??!1)===t.ctrl,c=(r.shift??!1)===t.shift,l=(r.meta??!1)===t.meta;if(a&&c&&l)return!0}}return!1}normalizeKeyName(t){let n={return:"enter",esc:"escape",del:"delete",backspace:"backspace"," ":"space"},r=t.toLowerCase();return n[r]??r}executeShortcut(t,n){let r=this.findMatchingShortcut(t,n);return r?.handler?r.handler()===!0:!1}getAllShortcuts(){return Array.from(this.shortcuts.values())}getShortcutsByCategory(t){return this.getAllShortcuts().filter(n=>n.definition.category===t)}getShortcutsByContext(t){return this.getAllShortcuts().filter(n=>{let r=n.definition.context;return r==="global"||r===t})}formatBinding(t){let n=[];t.ctrl&&n.push("Ctrl"),t.meta&&n.push("Alt"),t.shift&&n.push("Shift");let r=t.key.length===1?t.key.toUpperCase():t.key;return n.push(r),n.join("+")}formatBindings(t){return t.map(n=>this.formatBinding(n)).join(" or ")}},ir=i(()=>Bd.getInstance(),"getShortcutsRegistry");var bs=[{id:"interrupt",name:"Interrupt",description:"Interrupt the current streaming response",defaultBindings:[{key:"c",ctrl:!0}],context:"global",priority:200,category:"global",configurable:!1},{id:"showHelp",name:"Toggle Help",description:"Show or hide shortcut help when the input is empty",defaultBindings:[{key:"?"}],context:"global",priority:150,category:"global",configurable:!0},{id:"toggleThinking",name:"Cycle Reasoning",description:"Cycle reasoning mode: off, auto, quick, balanced, deep",defaultBindings:[{key:"t",ctrl:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"toggleTranscriptMode",name:"Toggle Transcript Mode",description:"Toggle transcript mode on or off",defaultBindings:[{key:"o",ctrl:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"openTranscriptSearch",name:"Search Transcript",description:"Open transcript search",defaultBindings:[{key:"f",ctrl:!0}],context:"global",priority:150,category:"navigation",configurable:!0},{id:"togglePermissionMode",name:"Cycle Permissions",description:"Cycle permission mode: plan, accept-edits, auto-in-project",defaultBindings:[{key:"tab",shift:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"toggleAgentMode",name:"Toggle Agent Mode",description:"Switch between AMA and SA",defaultBindings:[{key:"m",meta:!0}],context:"global",priority:150,category:"mode",configurable:!0},{id:"submitInput",name:"Submit Input",description:"Submit the current input",defaultBindings:[{key:"enter"}],context:"input",priority:50,category:"global",configurable:!1},{id:"acceptCompletion",name:"Accept Completion",description:"Accept the current autocomplete suggestion",defaultBindings:[{key:"tab"}],context:"input",priority:60,category:"editing",configurable:!0},{id:"cancelInput",name:"Cancel Input",description:"Cancel or clear the current input",defaultBindings:[{key:"escape"}],context:"input",priority:70,category:"editing",configurable:!0},{id:"newline",name:"Insert Newline",description:"Insert a newline in the current input",defaultBindings:[{key:"enter",shift:!0},{key:"j",ctrl:!0}],context:"input",priority:40,category:"editing",configurable:!0},{id:"historyUp",name:"History Up",description:"Browse previous input history",defaultBindings:[{key:"up"}],context:"input",priority:30,category:"navigation",configurable:!0},{id:"historyDown",name:"History Down",description:"Browse next input history",defaultBindings:[{key:"down"}],context:"input",priority:30,category:"navigation",configurable:!0},{id:"moveLeft",name:"Move Left",description:"Move the cursor left",defaultBindings:[{key:"left"}],context:"input",priority:20,category:"navigation",configurable:!1},{id:"moveRight",name:"Move Right",description:"Move the cursor right",defaultBindings:[{key:"right"}],context:"input",priority:20,category:"navigation",configurable:!1},{id:"moveToStart",name:"Move To Start",description:"Move the cursor to the start of the line",defaultBindings:[{key:"a",ctrl:!0}],context:"input",priority:25,category:"navigation",configurable:!0},{id:"moveToEnd",name:"Move To End",description:"Move the cursor to the end of the line",defaultBindings:[{key:"e",ctrl:!0}],context:"input",priority:25,category:"navigation",configurable:!0},{id:"killLineRight",name:"Delete To End",description:"Delete from the cursor to the end of the current line",defaultBindings:[{key:"k",ctrl:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"killLineLeft",name:"Delete To Start",description:"Delete from the start of the line to the cursor",defaultBindings:[{key:"u",ctrl:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"deleteWordLeft",name:"Delete Word Left",description:"Delete the word before the cursor",defaultBindings:[{key:"w",ctrl:!0},{key:"backspace",meta:!0}],context:"input",priority:25,category:"editing",configurable:!0},{id:"moveLineUp",name:"Move Line Up",description:"Move to the previous visual line in multiline input",defaultBindings:[{key:"up",ctrl:!0}],context:"input",priority:20,category:"navigation",configurable:!0},{id:"moveLineDown",name:"Move Line Down",description:"Move to the next visual line in multiline input",defaultBindings:[{key:"down",ctrl:!0}],context:"input",priority:20,category:"navigation",configurable:!0},{id:"backspace",name:"Backspace",description:"Delete the previous character",defaultBindings:[{key:"backspace"}],context:"input",priority:10,category:"editing",configurable:!1},{id:"delete",name:"Delete",description:"Delete the next character",defaultBindings:[{key:"delete"}],context:"input",priority:10,category:"editing",configurable:!1}];import{useEffect as PL,useCallback as $L,useRef as LL}from"react";function vr(e,t,n={}){let{context:r,isActive:o=!0}=n,s=ir(),a=LL(t);a.current=t,PL(()=>(s.setHandler(e,(...d)=>a.current(...d)),()=>{s.setHandler(e,void 0)}),[s,e]);let c=$L(d=>{if(!o)return!1;let p=s.getAllShortcuts().find(T=>T.definition.id===e);if(!p)return!1;let g=r??p.definition.context,x=g==="global"?"input":g,y=s.findMatchingShortcut(d,x);return y&&y.definition.id===e?a.current()===!0:!1},[s,e,o,r]),l=OL(e,s);sn(c,{isActive:o,priority:l})}i(vr,"useShortcut");function OL(e,t){let r=t.getAllShortcuts().find(o=>o.definition.id===e);return r?r.definition.priority:0}i(OL,"getShortcutPriority");import DL,{createContext as NL,useContext as BL,useState as ab,useCallback as Lg}from"react";var cb=NL(null);function Og({children:e,initialContext:t="input"}){let[n,r]=ab(!1),[o,s]=ab(t);ir().registerAll(bs);let c=Lg(()=>{r(p=>!p)},[]),l=Lg(()=>{let g=ir().getAllShortcuts(),x={global:[],mode:[],navigation:[],editing:[]};for(let y of g){let T=y.definition.category;x[T]||(x[T]=[]),x[T].push(y)}return x},[]),d=Lg(()=>ir().getShortcutsByContext(o),[o]),m={showHelp:n,toggleHelp:c,setShowHelp:r,currentContext:o,setCurrentContext:s,getShortcutsByCategory:l,getContextShortcuts:d};return DL.createElement(cb.Provider,{value:m},e)}i(Og,"ShortcutsProvider");function Dg(){let e=BL(cb);if(!e)throw new Error("useShortcutsContext must be used within a ShortcutsProvider");return e}i(Dg,"useShortcutsContext");import HL from"chalk";function Ng({currentConfig:e,setCurrentConfig:t,isLoading:n,abort:r,stopThinking:o,clearThinkingContent:s,setCurrentTool:a,setIsLoading:c,onToggleHelp:l,setShowHelp:d,onSetThinking:m,onSetReasoningMode:p,onToggleTranscriptMode:g,onOpenTranscriptSearch:x,canOpenTranscriptSearch:y=!0,isInteractiveDialogActive:T=!1,onSetAgentMode:w,onSetPermissionMode:v,isInputEmpty:O,onSavePermissionMode:P}){return vr("interrupt",()=>n?(r(),o(),s(),a(void 0),c(!1),console.log(HL.yellow(`
329
- [Interrupted]`)),!0):!1,{isActive:n}),vr("showHelp",()=>T?!1:O?(l(),!0):!1,{isActive:O}),vr("toggleThinking",()=>{if(T)return!1;let D=mo.indexOf(e.reasoningMode),L=mo[(D+1)%mo.length],X=L!=="off";return t(I=>({...I,thinking:X,reasoningMode:L})),gr({reasoningMode:L,thinking:X}),p?.(L),m?.(X),d(!1),!0}),vr("toggleTranscriptMode",()=>T?!1:(g?.(),d(!1),!0)),vr("openTranscriptSearch",()=>T||!y?!1:(x?.(),d(!1),!0)),vr("togglePermissionMode",()=>{if(T)return!1;let D=["plan","accept-edits","auto"],L=e.permissionMode==="auto-in-project"?"auto":e.permissionMode,I=(D.indexOf(L)+1)%D.length,ie=D[I];return t(Te=>({...Te,permissionMode:ie})),v?.(ie),P?.(ie),d(!1),!0}),vr("toggleAgentMode",()=>{if(T)return!1;let D=e.agentMode==="ama"?"sa":"ama";return t(L=>({...L,agentMode:D})),gr({agentMode:D}),w?.(D),d(!1),!0}),null}i(Ng,"GlobalShortcuts");import{exec as FL}from"child_process";import{promisify as WL}from"util";var UL=WL(FL),jL={read:"read",grep:"grep",glob:"glob",write:"write",edit:"edit",bash:"bash",undo:"undo",askuserquestion:"ask-user-question",askuser:"ask-user-question"};function lb(e){let t=[],n="",r=0;for(let o of e){if(o===","&&r===0){n.trim()&&t.push(n.trim()),n="";continue}o==="("?r++:o===")"&&r>0&&r--,n+=o}return n.trim()&&t.push(n.trim()),t}i(lb,"splitTopLevelCommaList");function GL(e){if(!e?.trim())return{configured:!1,rules:[],invalidEntries:[]};let t=[];return{configured:!0,rules:lb(e).map(r=>{if(r==="*")return{tool:"*"};if(r.includes("(")&&!r.endsWith(")")){t.push(r);return}let o=r.match(/^([^(]+?)(?:\((.*)\))?$/);if(!o){t.push(r);return}let s=jL[o[1].replace(/[^a-z]/gi,"").toLowerCase()];if(!s){t.push(r);return}let a=o[2]?lb(o[2]).map(c=>c.trim()).filter(Boolean):void 0;return{tool:s,patterns:a&&a.length>0?a:void 0}}).filter(r=>r!==void 0),invalidEntries:t}}i(GL,"parseAllowedTools");function KL(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`,"i")}i(KL,"wildcardToRegExp");function ub(e,t){return KL(e).test(t)}i(ub,"matchesPattern");function db(e,t,n){if(!e.configured)return!0;if(e.rules.length===0)return!1;let r=t.toLowerCase(),o=r==="bash"?String(n.command??"").trim():"";return e.rules.some(s=>s.tool!=="*"&&s.tool!==r?!1:!s.patterns||s.patterns.length===0||r!=="bash"?!0:s.patterns.some(a=>ub(a,o)))}i(db,"isToolAllowed");function VL(e,t){return e.matcher?ub(e.matcher,t):!0}i(VL,"hookMatches");function zL(e){let t=e.source==="skill"?"skill":e.source==="extension"?"extension command":"command";return[`Note: ${e.displayName} has model invocation disabled.`,`The ${t} content is shown below for manual use:`,"",`--- ${e.displayName} ---`,e.prompt,`--- end ${e.displayName} ---`].join(`
330
- `)}i(zL,"formatManualOutput");function XL(e,t){if(!t)return;let n=t.trim();if(n){if(!["haiku","sonnet","opus"].includes(n))return n;if(e==="anthropic")switch(n){case"haiku":return"claude-3-5-haiku-latest";case"opus":return"claude-opus-4-1";default:return"claude-sonnet-4-6"}}}i(XL,"resolveModelOverride");async function YL(e,t,n,r,o,s){let a=typeof n.displayName=="string"?n.displayName:"frontmatter invocation",c={command:t.command,_reason:`Frontmatter hook ${e} for ${a}`,_frontmatterHook:!0,_hookEvent:e,_hookMatcher:t.matcher};if(!db(s,"bash",c))return{allow:!1,message:`Hook ${e} for ${a} is blocked by allowed-tools policy.`};if(o.beforeToolExecute&&!await o.beforeToolExecute("bash",c))return{allow:!1,message:`Hook ${e} for ${a} was blocked by the current permission policy.`};try{let{stdout:l,stderr:d}=await UL(t.command,{env:{...process.env,KODAX_HOOK_EVENT:e,KODAX_HOOK_PAYLOAD:JSON.stringify(n)},maxBuffer:1048576,windowsHide:!0}),m=[l.trim(),d.trim()].filter(Boolean).join(`
331
- `);m&&o.onToolResult?.({id:`frontmatter-hook:${e}`,name:"bash",content:m}),d.trim()&&await r(`[Hook ${e} stderr] ${d.trim()}`);let p=l.trim();if(!p)return{};try{let g=JSON.parse(p);return{allow:typeof g.allow=="boolean"?g.allow:typeof g.continue=="boolean"?g.continue:void 0,message:typeof g.message=="string"?g.message:void 0,additionalContext:typeof g.additionalContext=="string"?g.additionalContext:typeof g.additional_context=="string"?g.additional_context:void 0}}catch{return{message:p,additionalContext:p}}}catch(l){return await r(`[Hook ${e} failed] ${l instanceof Error?l.message:String(l)}`),{}}}i(YL,"executeHookCommand");async function vs(e,t,n,r,o,s,a){let c=e?.[t];if(!c||c.length===0)return{};let l={};for(let d of c){if(!VL(d,n))continue;let m=await YL(t,d,r,o,s,a);if(m.message&&await o(`[Hook ${t}] ${m.message}`),m.additionalContext&&(l.additionalContext=l.additionalContext?`${l.additionalContext}
332
- ${m.additionalContext}`:m.additionalContext),m.allow===!1){l.allow=!1;break}}return l}i(vs,"runHooks");async function Hd(e,t,n,r){if(t.disableModelInvocation)return{mode:"manual",manualOutput:zL(t),finalize:i(async()=>{},"finalize")};let o=e.events??{},s=GL(t.allowedTools),a=XL(e.provider,t.model),c=!1,l=i(async w=>{if(r(w),!(c||!t.hooks?.Notification?.length)){c=!0;try{await vs(t.hooks,"Notification",w,{displayName:t.displayName,source:t.source,path:t.path,message:w},async v=>{r(v)},o,s)}finally{c=!1}}},"emitWithNotifications");t.model&&!a&&await l(`[Info] Model preference '${t.model}' is not supported by provider '${e.provider}', using the current model.`),s.invalidEntries.length>0&&await l(`[Warning] ${t.displayName} has invalid allowed-tools entries: ${s.invalidEntries.join(", ")}`),s.configured&&s.rules.length===0&&await l(`[Warning] ${t.displayName} has no valid allowed-tools entries, so all tool execution will be blocked.`);let d=await vs(t.hooks,"SessionStart",t.displayName,{displayName:t.displayName,source:t.source,path:t.path},l,o,s);if(d.allow===!1)return{mode:"manual",manualOutput:`[Blocked] ${t.displayName} was stopped before execution.`,finalize:i(async()=>{},"finalize")};let m=await vs(t.hooks,"UserPromptSubmit",n,{displayName:t.displayName,source:t.source,prompt:n,path:t.path},l,o,s);if(m.allow===!1)return{mode:"manual",manualOutput:`[Blocked] ${t.displayName} was stopped by a UserPromptSubmit hook.`,finalize:i(async()=>{},"finalize")};let p=[t.agent?`Preferred agent: ${t.agent}`:void 0,d.additionalContext,m.additionalContext].filter(w=>typeof w=="string"&&w.trim().length>0),g=[p.length>0?p.join(`
333
-
334
- `):void 0,t.prompt,`User request: ${n}`].filter(w=>typeof w=="string"&&w.trim().length>0),x={...o,beforeToolExecute:i(async(w,v)=>db(s,w,v)?(await vs(t.hooks,"PreToolUse",w,{tool:w,input:v,displayName:t.displayName,source:t.source,path:t.path},l,o,s)).allow===!1?(await l(`[Blocked] PreToolUse hook blocked '${w}' for ${t.displayName}`),!1):o.beforeToolExecute?await o.beforeToolExecute(w,v):!0:(await l(`[Blocked] Tool '${w}' is not allowed by ${t.displayName}`),!1),"beforeToolExecute"),onToolResult:i(w=>{o.onToolResult?.(w),vs(t.hooks,"PostToolUse",w.name,{...w,displayName:t.displayName,source:t.source,path:t.path},l,o,s)},"onToolResult")},y=!1,T=i(async w=>{y||(y=!0,await vs(t.hooks,t.context==="fork"?"SubagentStop":"Stop",t.displayName,{displayName:t.displayName,source:t.source,path:t.path,error:w?.message},l,o,s))},"finalize");return{mode:t.context==="fork"?"fork":"inline",prompt:g.join(`
335
-
336
- `),options:{...e,modelOverride:a,context:{...e.context,rawUserInput:n,skillInvocation:t.source==="skill"?t.skillInvocation:e.context?.skillInvocation},events:x},finalize:T}}i(Hd,"prepareInvocationExecution");import{appendFileSync as qL,mkdirSync as QL,writeFileSync as JL}from"node:fs";import{join as mb}from"node:path";import fb from"node:v8";var Fg=parseInt(process.env.KODAX_MEMORY_DIAG??"0",10),Wg=Fg>=1,Ug=Si(),pb=mb(Ug,"memory-diag.log"),Bg=0,Hg=!1;function gb(){if(!Hg)try{QL(Ug,{recursive:!0}),Hg=!0}catch{Hg=!0}}i(gb,"ensureLogDir");function ZL(e){gb();try{qL(pb,e+`
337
- `)}catch{}}i(ZL,"writeLog");function pt(e){return`${(e/1024/1024).toFixed(2)}MB`}i(pt,"formatMB");function e1(){return typeof globalThis.gc=="function"?(globalThis.gc(),!0):!1}i(e1,"tryGC");function It(e){return e?e.length*2:0}i(It,"strBytes");function Ko(e,t=0){if(t>8)return 0;if(e==null)return 8;if(typeof e=="string")return e.length*2;if(typeof e=="number"||typeof e=="boolean")return 8;if(Array.isArray(e)){let n=32;for(let r of e)n+=Ko(r,t+1);return n}if(typeof e=="object"){let n=64;for(let[r,o]of Object.entries(e))n+=r.length*2,n+=Ko(o,t+1);return n}return 16}i(Ko,"estimateJsonBytes");function hb(e){if(!e||typeof e!="object")return 64;let t=e,n=64,r=new Set(["type","text","thinking","content","partial_json","input","data","signature","path","mediaType","tool_use_id","id","name","is_error"]);if(typeof t.text=="string"&&(n+=t.text.length*2),typeof t.thinking=="string"&&(n+=t.thinking.length*2),typeof t.content=="string")n+=t.content.length*2;else if(Array.isArray(t.content))for(let o of t.content)n+=hb(o);typeof t.partial_json=="string"&&(n+=t.partial_json.length*2),typeof t.data=="string"&&(n+=t.data.length*2),typeof t.signature=="string"&&(n+=t.signature.length*2),typeof t.path=="string"&&(n+=t.path.length*2),t.input!==void 0&&(n+=Ko(t.input));for(let[o,s]of Object.entries(t))r.has(o)||(n+=o.length*2+Ko(s));return n}i(hb,"estimateBlockBytes");function jg(e){if(typeof e.content=="string")return e.content.length*2+64;if(Array.isArray(e.content)){let t=64;for(let n of e.content)t+=hb(n);return t}return 200}i(jg,"estimateMessageBytes");function Fd(e){let t=128;switch(t+=It(e.id)+It(e.parentId??void 0)+It(e.timestamp),e.type){case"message":return t+jg(e.message);case"compaction":return t+=It(e.summary),t+=It(e.firstKeptEntryId),t+=It(e.reason),t+=It(e.artifactLedgerId),e.details!==void 0&&(t+=Ko(e.details)),e.memorySeed!==void 0&&(t+=Ko(e.memorySeed)),t;case"branch_summary":return t+=It(e.summary),t+=It(e.fromId),e.details!==void 0&&(t+=Ko(e.details)),t;case"label":return t+=It(e.targetId),t+=It(e.label),t;case"archive_marker":return t+=It(e.archiveBatchId),t+=It(e.summary),t+=8,t;default:return t}}i(Fd,"estimateEntryBytes");function t1(e){let t={},n=[];for(let o=0;o<e.length;o++){let s=e[o],a=jg(s);n.push({index:o,role:s.role,bytes:a});let c=t[s.role]??{count:0,bytes:0};c.count++,c.bytes+=a,t[s.role]=c}return n.sort((o,s)=>s.bytes-o.bytes),{totalBytes:n.reduce((o,s)=>o+s.bytes,0),biggest:n.slice(0,5),byRole:t}}i(t1,"buildMessageBreakdown");function Wd(){return Wg}i(Wd,"memDiagEnabled");function Ud(e,t){if(!Wg)return;e==="turn-start"&&Bg++;let n=process.memoryUsage(),r=new Date().toISOString(),o=t.biggestMessages,s=["",`\u2550\u2550\u2550 [MEMDIAG] turn=${Bg} phase=${e} @${r} \u2550\u2550\u2550`,` V8 heap: used=${pt(n.heapUsed)} total=${pt(n.heapTotal)} rss=${pt(n.rss)} ext=${pt(n.external)}`," \u2500\u2500 Data breakdown \u2500\u2500",` context.messages: ${t.messageCount} msgs, ${pt(t.messageBytes)}`,` lineage.entries: ${t.lineageEntryCount} total (msg=${t.lineageMessageEntryCount}, compact=${t.lineageCompactionCount}, branch=${t.lineageBranchSummaryCount}, label=${t.lineageLabelCount}, archive=${t.lineageArchiveMarkerCount})`,` lineage non-message: ${pt(t.lineageNonMessageBytes)} (compaction.details/memorySeed + branch_summary payloads)`,` lineage orphan messages: ${t.lineageOrphanMessageCount} msgs, ${pt(t.lineageOrphanMessageBytes)} (in lineage but not in context.messages \u2014 branches/pruned)`,` UI history: ${t.historyItemCount} items, ${pt(t.historyTextBytes)}`,` foreground turn: ${t.foregroundItemCount} items, ${pt(t.foregroundTextBytes)}`,` streaming response: ${pt(t.streamingResponseBytes)}`,` streaming thinking: ${pt(t.streamingThinkingBytes)}`,` persisted UI history: ${t.persistedUiHistoryCount} items, ${pt(t.persistedUiHistoryBytes)}`];if(o.length>0){s.push(" \u2500\u2500 Top 5 biggest messages \u2500\u2500");for(let d of o)s.push(` [${d.index}] role=${d.role} ${pt(d.bytes)}`)}let a=t.messageBytes+t.lineageNonMessageBytes+t.lineageOrphanMessageBytes+t.historyTextBytes+t.foregroundTextBytes+t.streamingResponseBytes+t.streamingThinkingBytes+t.persistedUiHistoryBytes;s.push(" \u2500\u2500 V8 heap spaces \u2500\u2500");let c=fb.getHeapSpaceStatistics();for(let d of c)d.space_used_size>1024*1024&&s.push(` ${d.space_name.padEnd(25)} used=${pt(d.space_used_size)} allocated=${pt(d.space_size)}`);if(s.push(" \u2500\u2500 Summary \u2500\u2500"),s.push(` tracked data total: ${pt(a)}`),s.push(` V8 heap used: ${pt(n.heapUsed)}`),s.push(` unaccounted (overhead): ${pt(n.heapUsed-a)}`),s.push(" (React/Ink tree, provider SDK buffers, module metadata,"),s.push(' tokenizer caches, source maps \u2014 see "Blind spots" note)'),e1()){let d=process.memoryUsage();s.push(` after forced GC: heap=${pt(d.heapUsed)} (freed ${pt(n.heapUsed-d.heapUsed)})`)}else s.push(" after forced GC: UNAVAILABLE \u2014 re-run with `node --expose-gc` to distinguish"),s.push(` "real leak" from "GC hasn't run yet".`);if(Fg>=2)try{let d=mb(Ug,`heap-turn${Bg}-${e}.heapsnapshot`);fb.writeHeapSnapshot(d),s.push(` heap snapshot: ${d}`)}catch{s.push(" heap snapshot: FAILED")}ZL(s.join(`
338
- `))}i(Ud,"memDiagSnapshot");function jd(e,t,n){let r=t1(e),o=new Set(e),s=0,a=0,c=0,l=0,d=0,m=0,p=0,g=0,x=t?.entries??[];for(let v of x)switch(v.type){case"message":g++,o.has(v.message)||(c++,a+=jg(v.message));break;case"compaction":l++,s+=Fd(v);break;case"branch_summary":d++,s+=Fd(v);break;case"label":m++,s+=Fd(v);break;case"archive_marker":p++,s+=Fd(v);break}let y=0;for(let v of n.historyItems)y+=It(v.text);let T=0;for(let v of n.foregroundItems)T+=It(v.text);let w=0;for(let v of n.persistedUiHistory)w+=It(v.text);return{messageCount:e.length,messageBytes:r.totalBytes,biggestMessages:r.biggest,lineageEntryCount:x.length,lineageMessageEntryCount:g,lineageCompactionCount:l,lineageBranchSummaryCount:d,lineageLabelCount:m,lineageArchiveMarkerCount:p,lineageNonMessageBytes:s,lineageOrphanMessageBytes:a,lineageOrphanMessageCount:c,historyItemCount:n.historyItems.length,historyTextBytes:y,foregroundItemCount:n.foregroundItems.length,foregroundTextBytes:T,streamingResponseBytes:It(n.streamingResponse),streamingThinkingBytes:It(n.streamingThinking),persistedUiHistoryCount:n.persistedUiHistory.length,persistedUiHistoryBytes:w}}i(jd,"buildMemDiagBreakdown");function yb(){if(Wg){gb();try{let e=typeof globalThis.gc=="function",t=[`[MEMDIAG] Session started at ${new Date().toISOString()}`,`[MEMDIAG] Level=${Fg} gc=${e?"available":"UNAVAILABLE (run with node --expose-gc)"}`,"[MEMDIAG] Blind spots: React/Ink trees, provider SDK buffers, WeakMap/Map caches,","[MEMDIAG] tokenizer internal state, source-map strings, native handles.",'[MEMDIAG] A large "unaccounted" number living in these buckets is expected;',"[MEMDIAG] use Level 2 (KODAX_MEMORY_DIAG=2) to dump heap snapshots for DevTools.",""].join(`
339
- `);JL(pb,t+`
340
- `)}catch{}}}i(yb,"memDiagReset");import n1 from"node:fs";import Kg from"node:path";var r1={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"},o1=/@(?:"([^"]+)"|'([^']+)'|([^\s]+))/g;function i1(e){return r1[Kg.extname(e).toLowerCase()]}i(i1,"resolveImageMediaType");var Gg="[Image unavailable]";function s1(e){return""}i(s1,"buildImageAnchor");function pc(e,t){let n=[],r=[],o=new Set,s=new Map,a=new Set,c=[],l=0;for(let m of e.matchAll(o1)){let p=m.index??l;c.push(e.slice(l,p));let g=m[1]??m[2]??m[3];if(!g){c.push(m[0]),l=p+m[0].length;continue}let x=i1(g);if(!x){c.push(m[0]),l=p+m[0].length;continue}let y=Kg.resolve(t,g);try{if(!n1.statSync(y).isFile()){a.has(y)||(r.push(`[Image input skipped] ${g} is not a file.`),a.add(y)),c.push(Gg),l=p+m[0].length;continue}}catch{a.has(y)||(r.push(`[Image input missing] ${g} was not found from ${t}.`),a.add(y)),c.push(Gg),l=p+m[0].length;continue}if(!o.has(y)){o.add(y);let T=s1(n.length+1);s.set(y,T),n.push({kind:"image",path:y,mediaType:x,source:"user-inline",description:`Attached image ${Kg.basename(y)}`})}c.push(s.get(y)??Gg),l=p+m[0].length}c.push(e.slice(l));let d=c.join("");return{promptText:d,messageContent:gx(d,n),inputArtifacts:n,warnings:r}}i(pc,"preparePromptInputArtifacts");function xb(e){let t=a1(e.stage),n=c1(e);return{type:"info",icon:"\u{1F4E1}",text:n?`[RepoIntel] ${t} \xB7 ${n}`:`[RepoIntel] ${t}`,tightSpacing:!0}}i(xb,"createRepoIntelTraceHistoryItem");function a1(e){switch(e){case"routing":return"routing";case"preturn":return"preturn";case"module":return"module";case"impact":return"impact";case"task-snapshot":return"task-snapshot";default:return String(e)}}i(a1,"stageDisplayName");function c1(e){let t=[],n=e.capability;n&&(t.push(`mode=${n.mode}`),n.status!=="ok"&&t.push(`status=${n.status}`));let r=e.trace;return r&&(r.daemonLatencyMs!==void 0&&t.push(`daemon ${r.daemonLatencyMs}ms`),r.cliLatencyMs!==void 0&&t.push(`cli ${r.cliLatencyMs}ms`),r.cacheHit!==void 0&&t.push(r.cacheHit?"cache hit":"cache miss"),r.capsuleEstimatedTokens!==void 0&&t.push(`${l1(r.capsuleEstimatedTokens)} tokens`)),t.length===0&&e.summary?u1(e.summary):t.join(" \xB7 ")}i(c1,"buildRepoIntelDetailLine");function l1(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}i(l1,"formatTokens");function u1(e){return e.replace(/^stage=[^|]+\|\s*/,"").trim()}i(u1,"stripSummaryStagePrefix");function d1(e){switch(e){case"H0_DIRECT":return"H0";case"H1_EXECUTE_EVAL":return"H1";case"H2_PLAN_EXECUTE_EVAL":return"H2";default:return e}}i(d1,"formatHarnessProfileShort");function wb(e,t){let n=e.trim();return t.trim()?n?e===t?e:t.startsWith(e)?t:e.startsWith(t)?e:t:t:e}i(wb,"mergeLiveThinkingContent");function gc(e,t){let n=t?.expanded?e.detailNote??e.note:e.note,r=d1(e.harnessProfile)??e.harnessProfile,o=`${e.agentMode.toUpperCase()} ${r}`,s=e.activeWorkerTitle??"Scout",a=`${e.agentMode.toUpperCase()} ${s}`,c=`${e.agentMode.toUpperCase()} Routing`,l=e.currentRound&&e.maxRounds&&e.currentRound>1?` - Round ${e.currentRound}/${e.maxRounds}`:"";switch(e.phase){case"routing":return`${c} - Routing ready`;case"starting":return n?`${o} - ${n}`:`${o} - Managed task starting`;case"preflight":return n?`${a} - ${n}`:`${a} - ${s} preflight starting`;case"round":return n?`${o} - ${n}`:`${o} - Managed task round update${l}`;case"worker":return n?`${o} - ${n}${l}`:`${o} - ${e.activeWorkerTitle??"Worker"} starting${l}`;case"upgrade":return n?`${o} - ${n}`:`${o} - Harness transition${l}`;case"completed":return n?`${o} - ${n}`:`${o} - Managed task completed`;default:return}}i(gc,"formatManagedTaskBreadcrumb");function Sb(e,t,n,r){let o=e?.gitRoot??t??void 0,s=e?.executionCwd??o??process.cwd();return{...e,gitRoot:o,executionCwd:s,contextTokenSnapshot:n,taskSurface:"repl",skillsPrompt:r}}i(Sb,"buildManagedRunContext");var f1=["global","mode","navigation","editing"],m1={global:["showHelp","interrupt"],mode:["toggleThinking","toggleTranscriptMode","togglePermissionMode","toggleAgentMode"],navigation:["openTranscriptSearch","historyUp","historyDown","moveToStart","moveToEnd"],editing:["acceptCompletion","cancelInput","newline","killLineRight","killLineLeft","deleteWordLeft"]},p1={global:"Global",mode:"Modes",navigation:"Navigation",editing:"Editing"},g1={id:"transcript",title:"Transcript",items:[{id:"mode",label:"Ctrl+O transcript mode"},{id:"search",label:"Ctrl+F search transcript"},{id:"browse",label:"PgUp/PgDn/j/k scroll"},{id:"match",label:"n/N next match"},{id:"latest",label:"End back to live"},{id:"exit",label:"q or Esc back to live"}]};function h1(e){let t=ir(),n=t.getAllShortcuts().find(o=>o.definition.id===e);if(n?.effectiveBindings?.length)return t.formatBindings(n.effectiveBindings);let r=bs.find(o=>o.id===e);if(r?.defaultBindings?.length)return t.formatBindings(r.defaultBindings)}i(h1,"resolveShortcutBindingLabel");function y1(e){return`${h1(e.id)??e.id} ${e.name}`}i(y1,"buildMenuItemLabel");function x1(e){return ir().getAllShortcuts().find(r=>r.definition.id===e)?.definition??bs.find(r=>r.id===e)}i(x1,"resolveShortcutDefinition");function Gd(){return[...f1.map(t=>{let n=m1[t].map(r=>x1(r)).filter(r=>!!r).map(r=>({id:r.id,label:y1(r)}));return{id:t,title:p1[t],items:n}}).filter(t=>t.items.length>0),g1]}i(Gd,"buildHelpMenuSections");var Vg=2,Tb=1,Cb=4;function Ze(e,t){let n=zt(e.length>0?e.split(`
341
- `):[""],Math.max(1,t),0,0);return Math.max(1,n.visualLines.length)}i(Ze,"wrapLineCount");function w1(e,t,n=">"){let r=n.length+1,o=Math.max(20,t-r),s=zt(e.length>0?e.split(`
342
- `):[""],o,0,0);return Math.max(1,s.visualLines.length)+2}i(w1,"calculateInputPromptRows");function bb(e){let{terminalRows:t,terminalWidth:n,windowedTranscript:r=!1,inputText:o,inputPrompt:s=">",footerHeaderText:a,activitySummary:c,pendingInputSummary:l,stashNoticeSummary:d,notificationSummary:m,statusNoticeSummary:p,workStripText:g,suggestionsReserved:x,suggestionsMode:y="inline",showHelp:T,statusBarText:w,confirmPrompt:v,confirmInstruction:O,uiRequest:P,dialogMode:D="inline",historySearch:L,maxVisibleSelectOptions:X=5,reviewHint:I,todoSurfaceRows:ie=0,activityBarVisible:Te=!1}=e,K=Math.max(0,Math.floor(ie)),q=a?Ze(a,Math.max(1,n-2)):0,M=c?Ze(c,Math.max(1,n-2)):0,C=Te?Math.max(1,M):M,Z=l?Ze(l,Math.max(1,n-2)):0,ke=d?Ze(d,Math.max(1,n-2)):0,ve=m?Ze(m,Math.max(1,n-2)):0,Se=p?Ze(p,Math.max(1,n-2)):0,ce=g?Ze(g,Math.max(1,n-2)):0,De=w1(o,n,s),ae=x?8:0,Y=T?Tb+Cb+Gd().reduce((_,W)=>_+Ze(W.title,Math.max(1,n-Vg))+Ze(W.items.map(J=>J.label).join(" | "),Math.max(1,n-Vg)),0):0,Q=Ze(w,Math.max(1,n-2)),Ce=0;if(v&&O){let _=Math.max(1,n-4);Ce=3+Ze(`[Confirm] ${v}`,_)+Ze(O,_)}let be=0,at=0;if(P){let _=Math.max(1,n-4);P.kind==="select"?(at=Math.min(X,P.options.length),be=3+Ze(`[Select] ${P.title}`,_)+P.options.slice(0,at).reduce((W,J,Ne)=>W+Ze(`${Ne+1}. ${J.label}${J.description?` - ${J.description}`:""}`,_),0)+(P.options.length>at?2:0)+Ze(`Choice: ${P.buffer||"(type a number)"}`,_)+1+(P.error?Ze(P.error,_):0)):be=3+Ze(`[Input] ${P.prompt}`,_)+(P.defaultValue!==void 0?Ze(`Default: ${P.defaultValue}`,_):0)+Ze(`Value: ${P.buffer||"(type your response)"}`,_)+1+(P.error?Ze(P.error,_):0)}let Re=0;if(L){let _=Math.max(1,n-4);Re=3+Ze(`Query: ${L.query||"(type to search)"}`,_)+(L.matchCount===0?Ze("No matches yet",_):Ze(`${Math.max(1,L.matchCount)} matches`,_)+Ze(L.selectedExcerpt||"",_))+1}let Ue=I?Ze(I,Math.max(1,n-2)):0,xe=q+C+K+Z+ke+ve+De+Y+Se+Ue+(y==="inline"?ae:0)+(D==="inline"?Ce+be+Re:0),kt=(y==="overlay"?ae:0)+(D==="overlay"?Ce+be+Re:0),qe=xe+ce+Q,ee=Math.max(1,t-qe);return{messageRows:ee,reservedBottomRows:qe,headerRows:q,activityRows:C,pendingInputRows:Z,stashNoticeRows:ke,notificationRows:ve,workStripRows:ce,inputRows:De,suggestionsRows:ae,helpRows:Y,statusNoticeRows:Se,statusRows:Q,confirmRows:Ce,uiRequestRows:be,historySearchRows:Re,footerRows:xe,overlayRows:kt,visibleSelectOptions:at,reviewHintRows:Ue,todoSurfaceRows:K,slots:[{name:"transcript",rows:ee},{name:"footer",rows:xe},{name:"overlay",rows:kt},{name:"status",rows:Q},{name:"task-bar",rows:ce}]}}i(bb,"calculateViewportBudget");function vb(e,t={}){let n=$i(e,{rendererMode:t.rendererMode??"owned"});return{hostProfile:e,surface:"prompt",buffering:n.bufferingMode,ownsViewportByDefault:n.ownsViewportByDefault,supportsMouseTracking:n.supportsMouseTracking,supportsFullscreenLayout:n.supportsFullscreenLayout,supportsOverlaySurface:n.supportsOverlaySurface,supportsSelection:n.supportsSelection,supportsCopyOnSelect:n.supportsCopyOnSelect,supportsWheelHistory:n.supportsWheelHistory,supportsViewportChrome:n.supportsViewportChrome,supportsSearchViewport:n.supportsSearchViewport,supportsStickyPrompt:n.supportsStickyPrompt,scrollAnchor:0,jumpToLatestAvailable:!1,stickyPromptVisible:!1,selectionMode:"none",selectedItemId:void 0,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0,pendingLiveUpdates:0}}i(vb,"createTranscriptDisplayState");function Ib(e){return{...e,surface:"transcript",jumpToLatestAvailable:e.pendingLiveUpdates>0}}i(Ib,"enterTranscriptMode");function kb(e){return{...e,surface:"prompt",scrollAnchor:0,jumpToLatestAvailable:!1,selectionMode:"none",selectedItemId:void 0,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0,pendingLiveUpdates:0}}i(kb,"exitTranscriptMode");function Rb(e,t){let n=Math.max(0,t);return{...e,pendingLiveUpdates:n,jumpToLatestAvailable:e.surface==="transcript"?n>0:e.scrollAnchor>0}}i(Rb,"setTranscriptPendingLiveUpdates");function Eb(e,t){let n=Math.max(0,t);return{...e,scrollAnchor:n,jumpToLatestAvailable:e.surface==="transcript"?e.pendingLiveUpdates>0:n>0}}i(Eb,"setTranscriptScrollAnchor");function Mb(e){return{...e,surface:"prompt",scrollAnchor:0,jumpToLatestAvailable:!1,selectionMode:"none",selectedItemId:void 0,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0,pendingLiveUpdates:0}}i(Mb,"jumpTranscriptToLatest");function Ab(e,t){return{...e,stickyPromptVisible:t}}i(Ab,"setTranscriptStickyPromptVisible");function Is(e,t){return{...e,selectedItemId:t,selectionMode:t?"message":"none"}}i(Is,"setTranscriptSelectedItem");function _b(e,t){return{...e,surface:"transcript",searchMode:"history",searchAnchorItemId:t?.anchorItemId??e.selectedItemId??e.searchAnchorItemId,currentMatchIndex:Math.max(0,t?.initialMatchIndex??e.currentMatchIndex),jumpToLatestAvailable:e.pendingLiveUpdates>0}}i(_b,"openTranscriptSearch");function Pb(e){return{...e,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0}}i(Pb,"closeTranscriptSearch");function $b(e,t){return{...e,currentMatchIndex:Math.max(-1,t)}}i($b,"setTranscriptSearchMatchIndex");function Lb(e){return e.supportsFullscreenLayout&&e.ownsViewportByDefault}i(Lb,"shouldWindowTranscript");function Ob(e){return e.surface==="transcript"}i(Ob,"shouldPauseLiveTranscript");function zg(e){return e.supportsSelection}i(zg,"ownsTranscriptSelectionPath");function Kd(e,t,n){if(!(!zg(e)||!n))return t.includes(n)?n:void 0}i(Kd,"resolveTranscriptSelectedItemId");function Db(e){return e.supportsSelection&&e.supportsCopyOnSelect}i(Db,"supportsPassiveTranscriptCopyOnSelect");function Nb(e){if(e.surface==="transcript")return"Transcript | PgUp/PgDn page | j/k scroll | \u2190/\u2192 select | / search | n/N matches | q/Esc/Ctrl+O back"}i(Nb,"buildTranscriptBrowseHint");var Bb="Slash commands cannot be queued mid-task. Press Esc to abort the current task, then run the command.",Hb="slash-guard";function Fb(e){return e.trimStart().startsWith("/")}i(Fb,"isSlashCommandText");var S1=`
343
-
344
- ---
345
-
346
- `;async function Wb(e){let{initialPrompt:t,runRound:n,shiftPendingPrompt:r,onRoundComplete:o,onBeforeQueuedRound:s,shouldContinue:a=i(()=>!0,"shouldContinue")}=e,c=t,l=await n(c);for(;;){if(await o?.(l),!a(l))return l;let d=[];for(;;){let m=r();if(m===void 0)break;let p=typeof m=="string"?m.trim():"";p.length>0&&d.push(p)}if(d.length===0)return l;c=d.length===1?d[0]:d.join(S1),await s?.(c),l=await n(c)}}i(Wb,"runQueuedPromptSequence");function jb(e){return e.itemsLength>0||e.currentResponse.length>0||e.thinkingContent.length>0||e.activeToolCallsLength>0}i(jb,"hasTranscriptInputActivity");function T1(e){return e.keyName==="mouse"&&e.hasMouse&&e.usesManagedMouseClicks&&e.supportsMouseTracking&&e.usesRendererMouseTracking}i(T1,"shouldHandleManagedTranscriptMouse");function Ub(e){return e.usesManagedMouseWheel&&e.supportsWheelHistory&&e.hasTranscript}i(Ub,"shouldHandleManagedTranscriptWheel");function Gb(e){if(T1({keyName:e.keyName,hasMouse:e.hasMouse,usesManagedMouseClicks:e.usesManagedMouseClicks,supportsMouseTracking:e.supportsMouseTracking,usesRendererMouseTracking:e.usesRendererMouseTracking})){if(e.mouseButton!=="left")return{kind:"none"};if(e.mouseAction==="press"||e.mouseAction==="drag"||e.mouseAction==="release")return{kind:"mouse-phase",phase:e.mouseAction}}return e.keyName==="pageup"?e.hasTranscript?{kind:"scroll-by",delta:e.reviewPageSize}:{kind:"consume"}:e.keyName==="wheelup"?Ub({usesManagedMouseWheel:e.usesManagedMouseWheel,supportsWheelHistory:e.supportsWheelHistory,hasTranscript:e.hasTranscript})?{kind:"scroll-by",delta:e.reviewWheelStep}:{kind:"none"}:e.keyName==="wheeldown"?Ub({usesManagedMouseWheel:e.usesManagedMouseWheel,supportsWheelHistory:e.supportsWheelHistory,hasTranscript:e.hasTranscript})?e.historyScrollOffset===0?{kind:"consume"}:{kind:"scroll-by",delta:-e.reviewWheelStep}:{kind:"none"}:{kind:"none"}}i(Gb,"resolveTranscriptPointerAction");function C1(e){return e.isTranscriptMode&&e.hasTextSelection}i(C1,"shouldDeferInterruptToTranscriptSelectionCopy");function Kb(e){return e.ctrl&&e.keyName==="c"?C1({isTranscriptMode:e.isTranscriptMode,hasTextSelection:e.hasTranscriptTextSelection})?{kind:"none"}:{kind:"interrupt"}:e.keyName!=="escape"?{kind:"none"}:e.isTranscriptMode||e.isAwaitingUserInteraction?{kind:"none"}:e.isInputEmpty&&e.pendingInputCount>0?{kind:"pop-pending-input"}:e.isInputEmpty?e.timeSinceLastEscapeMs<e.doubleEscapeIntervalMs?{kind:"interrupt"}:{kind:"arm-double-escape"}:{kind:"none"}}i(Kb,"resolveStreamingInterruptAction");function Vb(e){let{key:t,isTranscriptMode:n,isHistorySearchActive:r,historySearchMatchCount:o,hasTextSelection:s,hasFocusedItem:a,canCopySelectedItem:c,canCopySelectedToolInput:l,canToggleSelectedDetail:d,canCycleTranscriptSelection:m}=e;if(t.name==="pageup")return{kind:"scroll-page-up"};if(r){if(t.name==="escape")return{kind:"close-history-search"};if(t.name==="backspace")return{kind:"history-search-backspace"};if(t.name==="down")return{kind:"history-search-step",direction:"next"};if(t.name==="up")return{kind:"history-search-step",direction:"prev"};if(t.name==="enter"||t.name==="return")return{kind:"history-search-submit"};if(t.insertable&&t.sequence)return{kind:"history-search-append",text:t.sequence}}return n&&!r&&!t.ctrl&&!t.meta&&t.insertable&&t.sequence==="/"?{kind:"open-history-search"}:n&&!t.ctrl&&!t.meta&&t.name==="q"?{kind:"exit-transcript"}:n&&t.name==="escape"?s||a?{kind:"clear-selection-focus"}:{kind:"exit-transcript"}:t.name==="home"?{kind:"scroll-home"}:t.name==="pagedown"?{kind:"scroll-page-down"}:t.name==="end"?{kind:"scroll-end"}:n?t.ctrl&&!t.meta&&t.name==="e"?{kind:"toggle-show-all"}:t.name==="j"||t.name==="down"?{kind:"scroll-line-down"}:t.name==="k"||t.name==="up"?{kind:"scroll-line-up"}:!t.ctrl&&!t.meta&&t.name==="g"&&t.shift?{kind:"jump-latest"}:!t.ctrl&&!t.meta&&t.name==="g"&&!t.shift?{kind:"jump-oldest"}:t.name==="left"?m?{kind:"cycle-selection",direction:"prev"}:{kind:"none"}:t.name==="right"?m?{kind:"cycle-selection",direction:"next"}:{kind:"none"}:!t.ctrl&&!t.meta&&!t.shift&&t.name==="c"?s?{kind:"copy-selection"}:c?{kind:"copy-item"}:{kind:"none"}:!t.ctrl&&!t.meta&&!t.shift&&t.name==="i"?l?{kind:"copy-tool-input"}:{kind:"none"}:!t.ctrl&&!t.meta&&!t.shift&&t.name==="v"?d?{kind:"toggle-detail"}:{kind:"none"}:!t.ctrl&&!t.meta&&!t.shift&&t.name==="s"?{kind:"dump-to-scrollback"}:!t.ctrl&&!t.meta&&t.name==="n"?o===0?{kind:"none"}:{kind:"search-match-nav",direction:t.shift?"prev":"next"}:{kind:"none"}:{kind:"none"}}i(Vb,"resolveTranscriptKeyboardAction");function zb(e){switch(e.action.kind){case"none":return!1;case"scroll-page-up":return e.hasTranscript&&(e.disarmHistorySearchSelection(),e.scrollTranscriptBy(e.pageScrollDelta)),!0;case"close-history-search":return e.closeHistorySearchSurface(),!0;case"history-search-backspace":return e.backspaceHistorySearchQuery(),!0;case"history-search-step":return e.stepHistorySearchSelection(e.action.direction),!0;case"history-search-submit":return e.submitHistorySearchSelection(),!0;case"history-search-append":return e.appendHistorySearchQuery(e.action.text),!0;case"open-history-search":return e.openHistorySearchSurface(),!0;case"clear-selection-focus":return e.clearTranscriptSelectionFocus(),!0;case"exit-transcript":return e.exitTranscriptModeSurface(),!0;case"toggle-show-all":return e.toggleTranscriptShowAll(),!0;case"scroll-home":case"jump-oldest":return e.disarmHistorySearchSelection(),e.scrollTranscriptHome(),!0;case"scroll-page-down":return e.disarmHistorySearchSelection(),e.scrollTranscriptBy(-e.pageScrollDelta),!0;case"scroll-end":return e.isTranscriptMode?(e.exitTranscriptModeSurface(),!0):(e.scrollTranscriptToBottom(),!0);case"scroll-line-down":return e.disarmHistorySearchSelection(),e.scrollTranscriptBy(-1),!0;case"scroll-line-up":return e.disarmHistorySearchSelection(),e.scrollTranscriptBy(1),!0;case"jump-latest":return e.scrollTranscriptToBottom(),!0;case"cycle-selection":return e.cycleTranscriptSelection(e.action.direction),!0;case"copy-selection":return e.copySelectedTranscriptText(),!0;case"copy-item":return e.copySelectedTranscriptItem(),!0;case"copy-tool-input":return e.copySelectedTranscriptToolInput(),!0;case"toggle-detail":return e.toggleSelectedTranscriptDetail(),!0;case"search-match-nav":return e.navigateSearchMatch(e.action.direction),!0;case"dump-to-scrollback":return e.dumpTranscriptToScrollback(),!0;default:return!1}}i(zb,"executeTranscriptKeyboardAction");function Vo(e){let t=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,n=/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,r=/\u001b[@-_]/g;return e.replace(t,"").replace(n,"").replace(r,"")}i(Vo,"stripAnsi");function b1(e){return e.tools.map(n=>`tool: ${n.name}`).join(`
347
- `)}i(b1,"serializeToolGroup");function v1(e){switch(e.type){case"thinking":return null;case"user":return`user: ${Vo(e.text)}`;case"assistant":return`assistant: ${Vo(e.text)}`;case"system":return`system: ${Vo(e.text)}`;case"info":return`info: ${Vo(e.text)}`;case"error":return`error: ${Vo(e.text)}`;case"event":return`event: ${Vo(e.text)}`;case"hint":return`hint: ${Vo(e.text)}`;case"tool_group":return b1(e);default:return e}}i(v1,"serializeOne");function I1(e){let t=[];for(let n of e){let r=v1(n);r!==null&&r!==""&&t.push(r)}return t.join(`
348
-
349
- `)}i(I1,"serializeTranscriptForScrollback");function Xb(e){let{items:t,writeToScrollback:n,exitAltScreen:r,enterAltScreen:o}=e,s=I1(t);r(),s.length>0&&n(`${s}
350
- `),o()}i(Xb,"dumpTranscriptToNativeScrollback");function k1(e){switch(e.type){case"tool_group":return e.tools.map(t=>{let n=[t.name];return typeof t.output=="string"&&n.push(t.output),t.error&&n.push(t.error),n.join(`
351
- `)}).join(`
352
- `);case"assistant":case"user":case"system":case"thinking":case"error":case"info":case"hint":return e.text;default:return""}}i(k1,"buildSearchText");function R1(e,t){let n=e.replace(/\s+/g," ").trim();if(!n)return"";let r=n.toLowerCase(),o=t.toLowerCase(),s=r.indexOf(o);if(s===-1)return n.slice(0,120);let a=Math.max(0,s-40),c=Math.min(n.length,s+t.length+60),l=a>0?"...":"",d=c<n.length?"...":"";return`${l}${n.slice(a,c)}${d}`}i(R1,"buildExcerpt");function Yb(e){return e.map((t,n)=>({itemId:t.id,itemIndex:n,searchText:k1(t)}))}i(Yb,"createTranscriptSearchIndex");function qb(e,t){let n=t.trim().toLowerCase();return n?e.flatMap(r=>{let o=r.searchText;return o.toLowerCase().includes(n)?[{itemId:r.itemId,itemIndex:r.itemIndex,excerpt:R1(o,t.trim())}]:[]}):[]}i(qb,"searchTranscriptIndex");function Xg(e,t,n){return e<=0?0:t<0?n==="next"?0:e-1:n==="next"?(t+1)%e:t<=0?e-1:t-1}i(Xg,"stepTranscriptSearchMatch");function Qb(e,t){return e.length===0?void 0:t<0?`${e.length} transcript matches`:`${Math.min(Math.max(t,0),e.length-1)+1}/${e.length} transcript matches`}i(Qb,"buildTranscriptSearchSummary");function Jb(e,t,n){if(t.length===0||!n)return 0;let r=t.findIndex(a=>a.itemId===n);if(r>=0)return r;let o=e.find(a=>a.itemId===n)?.itemIndex;if(o===void 0)return 0;let s=t.findIndex(a=>a.itemIndex>=o);return s>=0?s:0}i(Jb,"resolveTranscriptSearchMatchIndex");function Zb(e){if(e)switch(e.type){case"assistant":return{summary:"Assistant response",kindLabel:"assistant"};case"user":return{summary:"User prompt",kindLabel:"user"};case"system":return{summary:"System note",kindLabel:"system"};case"thinking":return{summary:"Thinking trace",kindLabel:"thinking"};case"tool_group":return{summary:E1(e),kindLabel:"tool"};case"error":return{summary:"Error entry",kindLabel:"error"};case"info":return{summary:"Info note",kindLabel:"info"};case"hint":return{summary:"Hint",kindLabel:"hint"};default:return{summary:"Transcript entry",kindLabel:"entry"}}}i(Zb,"buildTranscriptSelectionSummary");function E1(e){return e.tools.length===1?`Tool call: ${e.tools[0]?.name??"tool"}`:`Tool group: ${e.tools.length} calls`}i(E1,"summarizeToolGroup");function ev(e){return e.map(t=>t.id)}i(ev,"getSelectableTranscriptItemIds");function tv(e,t,n){if(e.length===0)return;if(!t)return n==="next"?e[0]:e[e.length-1];let r=e.indexOf(t);return r===-1?n==="next"?e[0]:e[e.length-1]:n==="next"?e[Math.min(e.length-1,r+1)]:e[Math.max(0,r-1)]}i(tv,"moveTranscriptSelection");function Yg(e){if(e)switch(e.type){case"tool_group":return e.tools.map(t=>{let n=[`Tool: ${t.name}`,`Status: ${t.status}`];return t.input&&n.push(`Input: ${JSON.stringify(t.input)}`),typeof t.output=="string"&&t.output.trim()&&n.push(`Output: ${t.output}`),t.error&&n.push(`Error: ${t.error}`),n.join(`
353
- `)}).join(`
354
-
355
- `);case"assistant":case"user":case"system":case"thinking":case"error":case"info":case"hint":return e.text;default:return}}i(Yg,"buildTranscriptCopyText");function nv(e){if(!e||e.type!=="tool_group")return;let t=e.tools.map(n=>{if(!n.input)return;let r=typeof n.input=="string"?n.input:JSON.stringify(n.input,null,2);if(r?.trim())return[`Tool: ${n.name}`,r].join(`
356
- `)}).filter(n=>!!n);return t.length>0?t.join(`
357
-
358
- `):void 0}i(nv,"buildTranscriptToolInputCopyText");import{useCallback as hc,useRef as M1,useState as rv}from"react";function ov(e){let{state:t,ownsViewport:n,isAwaitingUserInteraction:r,isHistorySearchActive:o,isTranscriptMode:s,historySearchQuery:a}=e,c=Nb(t),l;if(t.supportsStickyPrompt&&t.stickyPromptVisible)if(o){let m=a.trim();l={visible:!0,label:m?`Searching transcript for "${m}"`:"Searching transcript"}}else s?l={visible:!0,label:"Transcript Mode"}:r&&(l={visible:!0,label:"Interaction active"});let d;return n&&t.supportsViewportChrome&&(s&&t.pendingLiveUpdates>0?d={visible:!0,label:t.pendingLiveUpdates===1?"1 new update":`${t.pendingLiveUpdates} new updates`,hint:"Ctrl+O",tone:"accent"}:!s&&t.jumpToLatestAvailable&&(d={visible:!0,label:"Back to live",hint:"End",tone:"accent"})),{browseHintText:c,stickyHeader:l,jumpToLatest:d}}i(ov,"buildTranscriptChromeModel");function iv(e){return Math.max(1,e-2)}i(iv,"resolveTranscriptPageSize");function sv(e){return Math.max(3,Math.floor(e/4))}i(sv,"resolveTranscriptWheelStep");function A1(e,t){return Math.max(0,e+t)}i(A1,"incrementTranscriptScrollOffset");function av(e,t,n){let r=Math.max(0,t-n);return Math.min(Math.max(0,e),r)}i(av,"clampTranscriptScrollOffset");function cv(){let e=M1(null),[t,n]=rv(0),[r,o]=rv(!0),s=hc(m=>{n(Math.max(0,m))},[]),a=hc(m=>{o(m)},[]),c=hc(m=>{if(e.current){e.current.scrollTo(m);return}n(Math.max(0,m)),o(m===0)},[]),l=hc(m=>{if(e.current){e.current.scrollBy(m);return}n(p=>A1(p,m)),o(!1)},[]),d=hc(()=>{if(e.current){e.current.scrollToBottom();return}n(0),o(!0)},[]);return{scrollRef:e,scrollOffset:t,sticky:r,setScrollOffset:n,setSticky:o,handleScrollTopChange:s,handleStickyChange:a,scrollTo:c,scrollBy:l,scrollToBottom:d}}i(cv,"useTranscriptViewportScrollController");function lv(e){let{items:t,renderModel:n,terminalWidth:r,transcriptMaxLines:o,viewportRows:s,itemId:a,visibleRows:c,expandedItemKeys:l,showDetailedTools:d=!1}=e;if(!a||c.length===0)return!1;let p=(n?.sections??ms(t,r,o,d,l)).find(y=>y.key===a);if(!p||p.rows.length===0)return!1;let g=new Set(c.map(y=>y.key)),x=Math.max(0,s??0);return x>0&&p.rows.length<=x?p.rows.every(y=>g.has(y.key)):g.has(p.rows[0]?.key??"")}i(lv,"isTranscriptItemVisible");function uv(e){let{items:t,renderModel:n,terminalWidth:r,transcriptMaxLines:o,viewportRows:s,itemId:a,expandedItemKeys:c,showDetailedTools:l=!1}=e,d=n?.sections??ms(t,r,o,l,c);return sC(d,a,s)}i(uv,"resolveTranscriptSelectionOffset");function dv(e){let{items:t,renderModel:n,selectedItemId:r,terminalWidth:o=80,transcriptMaxLines:s=1e3,viewportRows:a,scrollOffset:c=0,expandedItemKeys:l,showDetailedTools:d=!1,preferViewportAnchor:m=!1}=e;if(r&&t.some(p=>p.id===r))return r;if(m&&c>0&&a&&a>0){let p=n?.sections??ms(t,o,s,d,l),g=n?.rows??Fo(p),y=Zp(g,a,c)[0]?.key,T=y?p.find(w=>w.rows.some(v=>v.key===y)):void 0;if(T?.key)return T.key}return t[t.length-1]?.id}i(dv,"resolveTranscriptSearchAnchorItemId");function fv(e){let t=_a(e.stickyHeader),n=hu(t,e.width),r=Math.max(0,e.topChromeRows??0);return{contentWindow:e.window,topOffsetRows:n+r,stickyHeaderRows:n,topChromeRows:r}}i(fv,"resolveTranscriptOwnedWindowGeometry");function _1(e){return e.text===" "?"":e.text}i(_1,"normalizeTranscriptRowText");function qg(e){let t=new Map;return e.forEach((n,r)=>{t.set(n.key,r)}),t}i(qg,"buildTranscriptRowIndexByKey");function P1(e,t={}){let n=Math.max(0,e.indent??0),r=e.spinner&&t.animateSpinners!==!1?2:0;return 1+n+r}i(P1,"resolveTranscriptTextStartColumn");function mv(e,t={}){let n=Math.max(0,t.topOffsetRows??0),r=t.rowIndexByKey??qg(t.allRows??e),o=e.map((s,a)=>{let c=_1(s),l=P1(s,t),d=Yr(c);return{key:s.key,row:s,modelRowIndex:r.get(s.key)??a,screenRow:n+a+1,text:c,textLength:d,textStartColumn:l,textEndColumn:l+uC(c)}});return{rows:o,topRow:o[0]?.screenRow??n+1,bottomRow:o[o.length-1]?.screenRow??n,viewportHeight:Math.max(0,t.viewportHeight??e.length)}}i(mv,"buildTranscriptScreenBuffer");function $1(e,t){let n=Math.max(1,Math.floor(t));return dC(e.text,n-e.textStartColumn)}i($1,"clampTextColumn");function Qg(e,t){return{screenRow:e,point:{rowKey:e.key,modelRowIndex:e.modelRowIndex,column:$1(e,t)}}}i(Qg,"toHit");function Jg(e,t,n){let r=e.rows.find(o=>o.screenRow===t);return r?Qg(r,n):void 0}i(Jg,"hitTestTranscriptScreen");function Zg(e,t,n){if(e.rows.length!==0)return t<=e.topRow?Qg(e.rows[0],n):t>=e.bottomRow?Qg(e.rows[e.rows.length-1],n):Jg(e,t,n)}i(Zg,"clampTranscriptScreenHit");function pv(e){return e.text===" "?"":e.text}i(pv,"normalizeTranscriptRowText");function gv(e,t){return e.modelRowIndex!==t.modelRowIndex?e.modelRowIndex-t.modelRowIndex:e.column-t.column}i(gv,"comparePoints");function hv(e,t,n,r={}){if(e.length===0)return;let[o,s]=gv(t,n)<=0?[t,n]:[n,t],a=r.selectFullRowOnCollapsed===!0,c=gv(t,n)===0,l=e[o.modelRowIndex],d=e[s.modelRowIndex];if(!l||!d)return;let m=a&&c?{...o,column:0}:o,p=a&&c?{...s,column:Yr(pv(d))}:s,g=new Map,x=[],y=0;for(let T=m.modelRowIndex;T<=p.modelRowIndex;T+=1){let w=e[T];if(!w)continue;let v=pv(w),O=Yr(v),P=T===m.modelRowIndex?m.column:0,D=T===p.modelRowIndex?p.column:O,L=Math.max(0,Math.min(P,O)),X=Math.max(L,Math.min(D,O)),I=ps(v,L,X);X>L&&(g.set(w.key,{start:L,end:X}),y+=X-L),x.push(I)}if(g.size!==0)return{anchor:t,focus:n,rowRanges:g,rowCount:x.length,charCount:y,text:x.join(`
359
- `)}}i(hv,"buildTranscriptScreenSelection");function yv(e){if(!e)return;let t=`${e.charCount} char${e.charCount===1?"":"s"}`;return e.rowCount<=1?`Selected ${t}`:`Selected ${t} across ${e.rowCount} lines`}i(yv,"buildTranscriptScreenSelectionSummary");function xv(e,t){return e.rows.length===0?0:t<e.topRow?1:t>e.bottomRow?-1:0}i(xv,"resolveTranscriptDragEdgeScrollDirection");function Vd(e){return e?e.map(t=>({label:t.label,value:t.value,description:t.description})):[]}i(Vd,"toSelectOptions");function eh(e){return e.question}i(eh,"getAskUserDialogTitle");function L1(e){switch(e){case"confirm":return te("waiting.confirm");case"select":return te("waiting.select");case"input":return te("waiting.input")}}i(L1,"formatPromptWaitingText");function wv(e){return e.waitingReason==="confirm"?te("placeholder.confirm"):e.waitingReason==="select"?te("placeholder.select"):e.waitingReason==="input"?te("placeholder.input"):e.isLoading?e.canQueueFollowUps?te("placeholder.queue"):te("placeholder.busy"):te("placeholder.idle")}i(wv,"buildPromptPlaceholderText");function Sv(e){if(e.isTranscriptMode)return;if(e.waitingReason)return{kind:"waiting",text:L1(e.waitingReason),showSpinner:!1};if(!e.isLoading)return;let t=ng({activeToolCount:e.streamingState.activeToolCalls.filter(n=>n.status===$.Executing).length,currentTool:e.streamingState.currentTool,isThinkingActive:e.streamingState.isThinking,thinkingCharCount:e.streamingState.thinkingCharCount,isCompacting:e.streamingState.isCompacting,toolInputCharCount:e.streamingState.toolInputCharCount,toolInputContent:e.streamingState.toolInputContent,managedPhase:e.managedState?.phase,managedHarnessProfile:e.managedState?.harnessProfile,managedWorkerTitle:e.managedState?.workerTitle});return t?{kind:"busy",text:t,showSpinner:!0}:void 0}i(Sv,"buildPromptActivityViewModel");function Tv(e,t,n){if(e){if(e.userOverrideContextWindow!==void 0)return e.contextWindow===e.userOverrideContextWindow?e:{...e,contextWindow:e.userOverrideContextWindow};try{let o=n(t.provider)?.getEffectiveContextWindow?.(t.model);if(o!==void 0&&o!==e.contextWindow)return{...e,contextWindow:o};if(o!==void 0)return e}catch{}return e}}i(Tv,"resolveEffectiveCompactionInfo");function Cv(e){return{sessionId:e.sessionId,permissionMode:e.permissionMode,agentMode:e.agentMode,provider:e.provider,model:e.model,currentTool:e.streamingState.currentTool,activeToolCount:e.streamingState.activeToolCalls.filter(t=>t.status===$.Executing).length,thinking:e.thinking,reasoningMode:e.reasoningMode,reasoningCapability:e.reasoningCapability,isThinkingActive:e.streamingState.isThinking,thinkingCharCount:e.streamingState.thinkingCharCount,toolInputCharCount:e.isTranscriptMode?e.streamingState.toolInputCharCount:0,toolInputContent:e.isTranscriptMode?e.streamingState.toolInputContent:"",currentIteration:e.streamingState.currentIteration,maxIter:e.maxIter,contextUsage:e.contextUsage,isCompacting:e.streamingState.isCompacting,showBusyStatus:!1,managedPhase:e.isLoading?e.managedState?.phase:void 0,managedHarnessProfile:e.isLoading?e.managedState?.harnessProfile:void 0,managedWorkerTitle:e.isLoading?e.managedState?.workerTitle:void 0,managedRound:e.isLoading?e.managedState?.round:void 0,managedMaxRounds:e.isLoading?e.managedState?.maxRounds:void 0,managedGlobalWorkBudget:e.isLoading?e.managedState?.globalWorkBudget:void 0,managedBudgetUsage:e.isLoading?e.managedState?.budgetUsage:void 0,managedBudgetApprovalRequired:e.isLoading?e.managedState?.budgetApprovalRequired:void 0,managedIdleWaiting:e.isLoading?e.managedState?.idleWaiting:void 0,managedIdleWaitingPendingCount:e.isLoading?e.managedState?.idleWaitingPendingCount:void 0,autoModeEngine:e.autoModeEngine}}i(Cv,"buildSurfaceStatusBarProps");function bv(e){let t=zg(e.state),n=t?Kd(e.state,e.selectableItemIds,e.selectedItemId):void 0,r=n?e.selectableItemIds.indexOf(n):-1;return{selectionEnabled:t,selectedItemId:n,selectedItemIndex:r,position:n?{current:Math.max(1,r+1),total:e.selectableItemIds.length}:void 0,detailState:n&&e.isExpanded?"expanded":"compact",copyCapabilities:{message:t&&!!n,toolInput:t&&!!n&&e.selectedItemType==="tool_group",copyOnSelect:t&&Db(e.state)},toggleDetail:t&&!!n,navigationCapabilities:{selection:t&&!!n&&e.selectableItemIds.length>0}}}i(bv,"buildTranscriptSelectionRuntimeState");function vv(e){if(!(!e.runtime.selectionEnabled||!e.runtime.selectedItemId))return{itemSummary:e.itemSummary?.summary,itemKind:e.itemSummary?.kindLabel,position:e.runtime.position,detailState:e.runtime.detailState,copyCapabilities:e.runtime.copyCapabilities,toggleDetail:e.runtime.toggleDetail,navigationCapabilities:e.runtime.navigationCapabilities}}i(vv,"buildTranscriptSelectionViewModel");function Iv(e){return{query:e.query,matches:e.matches,currentMatchIndex:e.currentMatchIndex,anchorItemId:e.anchorItemId,statusText:e.useOverlaySurface?void 0:e.statusText}}i(Iv,"buildTranscriptSearchViewModel");function O1(e,t){return e===0?0:t<0?-1:Math.min(t,e-1)}i(O1,"clampTranscriptSearchSelectedIndex");function D1(e){return e.isHistorySearchActive?e.historySearchQuery.trim()?e.matches.length===0?"No matches yet":e.clampedSelectedIndex<0?`${e.matches.length} matches | use n/N or Enter to jump`:e.matches[e.clampedSelectedIndex]?.excerpt:"Type to search transcript":void 0}i(D1,"buildTranscriptSearchDetailText");function kv(e){let t=O1(e.matches.length,e.selectedIndex),n=Qb(e.matches,t),r=D1({isHistorySearchActive:e.isHistorySearchActive,historySearchQuery:e.historySearchQuery,matches:e.matches,clampedSelectedIndex:t});return{clampedSelectedIndex:t,statusText:n,detailText:r,searchState:Iv({query:e.historySearchQuery,matches:e.matches,currentMatchIndex:t,anchorItemId:e.anchorItemId,statusText:n,useOverlaySurface:e.useOverlaySurface})}}i(kv,"buildTranscriptSearchChrome");function N1(e=!1){return`\u2190/\u2192 enter select mode | Ctrl+E ${e?"collapse":"show all"} | Mouse drag selects text`}i(N1,"buildDefaultTranscriptSecondaryText");function Rv(e){let t=[];return e.historySearchQuery.trim().length>0&&e.isHistorySearchActive&&e.historySearchMatchCount===0&&t.push({id:"search-empty",text:"No transcript matches yet",tone:"info"}),e.pendingInputCount>=e.maxPendingInputs&&t.push({id:"queue-full",text:`Queued follow-up limit reached (${e.maxPendingInputs})`,tone:"warning"}),t}i(Rv,"buildFooterNotifications");function Ev(e){let t=[];return e.historySearchQuery.trim()&&t.push(`Search: ${e.historySearchQuery.trim()}`),e.pendingInputCount>0&&t.push(`Queued follow-ups: ${e.pendingInputCount}`),t}i(Ev,"buildBaseFooterNotices");function Mv(e){if(e.inputText.trim()&&(e.isTranscriptMode||e.isHistorySearchActive))return"Draft preserved while viewing transcript"}i(Mv,"buildStashNoticeText");function Av(e){return[...e]}i(Av,"buildPromptFooterNotices");function B1(e){let n=(e.isHistorySearchActive?[e.historySearchDetailText]:[e.selectionSummary,e.actionSummary]).filter(r=>!!(r&&r.trim().length>0));return n.length===0?N1(e.showAllActive):n.join(" | ")}i(B1,"buildTranscriptFooterSecondaryText");function H1(e){let t=[];return e&&t.push(e),t}i(H1,"buildTranscriptFooterBudgetNotices");function _v(e){let t=e.selectionState?.copyCapabilities,n=e.selectionState?.navigationCapabilities,o=yv(e.textSelection),s=e.textSelection?hs({copyMessage:!0,copyToolInput:!1,copyOnSelect:!!t?.copyOnSelect,toggleDetail:!1,selectionNavigation:!1,matchNavigation:!1,dismissAction:"clear"}):e.selectionState?.itemSummary?hs({copyMessage:!!t?.message,copyToolInput:!!t?.toolInput,copyOnSelect:!!t?.copyOnSelect,toggleDetail:!!e.selectionState?.toggleDetail,selectionNavigation:!!n?.selection,matchNavigation:!1,dismissAction:"clear"}):void 0,a=B1({isHistorySearchActive:e.isHistorySearchActive,historySearchDetailText:e.historySearchDetailText,selectionSummary:o,actionSummary:s,showAllActive:e.showAllActive,baseFooterNotices:e.baseFooterNotices});return{selectionSummary:o,actionSummary:s,secondaryText:a,budgetNotices:H1(a)}}i(_v,"buildTranscriptFooterViewModel");import{jsx as O8,jsxs as D8}from"react/jsx-runtime";function Pv(e,t){if(!(!e||!t||t<=0))switch(e){case"finding-validation":return`Validating ${t} finding${t===1?"":"s"}`;case"module-triage":return`Scanning ${t} module${t===1?"":"s"}`;case"evidence-scan":return`Parallel evidence pass (${t})`;case"hypothesis-check":return`Checking ${t} hypothesis${t===1?"":"es"}`;default:return}}i(Pv,"formatAmaWorkStripText");function $v(e){return e.replace(/^\[[^\]]+\]\s*/,"").trim()}i($v,"stripLiveActivityPrefix");function Lv(e){let t=[],n=e.showPrimary??!0;if(e.isLoading&&n){let l=e.currentTool?$v(ed(e.currentTool,e.toolInputContent??"",e.toolInputCharCount??0)):void 0,d=e.liveActivityLabel?$v(e.liveActivityLabel):void 0;e.activeWorkerTitle?t.push({id:"primary-worker",label:`${e.activeWorkerTitle} active`,accent:!0,selected:!0}):e.activePhase?t.push({id:"primary-phase",label:e.activePhase,accent:!0,selected:!0}):d?t.push({id:"primary-live-activity",label:d,accent:!0,selected:!0}):l?t.push({id:"primary-tool",label:l,accent:!0,selected:!0}):e.isThinkingActive?t.push({id:"primary-thinking",label:"Thinking",accent:!0,selected:!0}):t.push({id:"primary-generic",label:"Agent active",accent:!0,selected:!0})}e.parallelText&&t.push({id:"parallel",label:e.parallelText});let[r,o,s,...a]=t,c=[r,o,s].filter(l=>!!l);return e.isLoading?{items:c,overflowLabel:a.length>0?`+${a.length} more`:void 0,ctaHint:e.parallelText?"Ctrl+O transcript":void 0}:{items:c,overflowLabel:a.length>0?`+${a.length} more`:void 0,ctaHint:e.parallelText?"Ctrl+O transcript":void 0}}i(Lv,"buildBackgroundTaskViewModel");function Ov(e,t){if(!(!t||!e||e.agentMode!=="ama"))return Pv(e.childFanoutClass,e.childFanoutCount)}i(Ov,"buildAmaWorkStripFromStatus");function th(e){let t=Ov(e.status,e.isLoading);return{workStripText:t,backgroundTask:Lv({isLoading:e.isLoading,showPrimary:!!(e.parallelTextOverride??t),activeWorkerTitle:e.status?.activeWorkerTitle,activePhase:e.status?.phase??(e.agentMode==="ama"?"AMA active":void 0),parallelText:e.parallelTextOverride??t,currentTool:e.currentTool,toolInputCharCount:e.toolInputCharCount,toolInputContent:e.toolInputContent,liveActivityLabel:e.liveActivityLabel,isThinkingActive:e.isThinkingActive})}}i(th,"buildAmaSummaryViewModel");function nh(e){return{...e,items:[...e.items],managedLiveEvents:[...e.managedLiveEvents??[]]}}i(nh,"captureTranscriptSnapshot");function Dv(e){if(!e.isTranscriptMode||!e.snapshot)return 0;let t=Math.max(0,e.currentItemsLength-e.snapshot.items.length);return e.isLoading!==e.snapshot.isLoading&&(t+=1),e.currentResponse!==e.snapshot.currentResponse&&(t+=1),e.thinkingContent!==e.snapshot.thinkingContent&&(t+=1),e.activeToolCallsLength!==e.snapshot.activeToolCalls.length&&(t+=1),(e.currentManagedLiveEventsLength??0)!==e.snapshot.managedLiveEvents.length&&(t+=1),t}i(Dv,"countPendingTranscriptUpdates");function Nv(e){return e.snapshot?[...e.snapshot.items]:e.surface==="transcript"?[...e.transcriptItems]:[...e.promptItems]}i(Nv,"resolveTranscriptSurfaceItems");function Bv(e){let t=[];for(let n of e)switch(n.type){case"user":case"system":case"error":case"tool_group":case"event":case"info":t.push({...n});break;case"assistant":case"thinking":{let{compactText:r,...o}=n;t.push(o);break}default:break}return t}i(Bv,"buildPromptSurfaceItems");function Hv(e,t){return e.enabled?t==="transcript"?e.transcriptShell:e.promptShell:"main-screen"}i(Hv,"resolveFullscreenShellMode");function F1(e,t){return e.enabled&&Hv(e,t)==="virtual"}i(F1,"shouldUseRendererViewportShell");function Fv(e,t){let n=Hv(e,t),r=e.enabled&&n==="virtual",o=e.enabled&&n==="virtual",s=r&&(e.mouseWheel||e.mouseClicks),a=s&&e.mouseClicks,c=o&&e.mouseWheel;return{shellMode:n,usesAlternateScreenShell:r,usesRendererViewportShell:o,usesRendererMouseTracking:s,usesManagedMouseClicks:a,usesManagedMouseWheel:c,usesManagedSelection:o,usesManagedWheelHistory:c,usesNativeMainScreenScrollback:!o}}i(Fv,"resolveTranscriptInteractionPolicy");function Wv(e,t,n){return F1(e,t)?t==="transcript"||n:!1}i(Wv,"shouldOwnTranscriptViewport");var W1=500,U1=1,j1=/[\p{L}\p{N}_/.\-+~\\]/u;function G1(e){return e.text===" "?"":e.text}i(G1,"normalizeTranscriptRowText");function Uv(e,t){return e.modelRowIndex!==t.modelRowIndex?e.modelRowIndex-t.modelRowIndex:e.column-t.column}i(Uv,"comparePoints");function rh(e){return e===""||/\s/.test(e)?0:j1.test(e)?1:2}i(rh,"charClass");function jv(e){let t=e.timeoutMs??W1,n=e.distance??U1,r=e.time-e.previous.time<=t,o=Math.abs(e.row-e.previous.row)<=n&&Math.abs(e.column-e.previous.column)<=n,s=r&&o?Math.min(3,e.previous.count+1):1;return{time:e.time,row:e.row,column:e.column,count:s}}i(jv,"resolveTranscriptMultiClickState");function zd(e,t,n){let r=e[t.modelRowIndex];if(!r)return;let o=G1(r);if(n==="line")return{kind:n,start:{...t,column:0},end:{...t,column:Yr(o)}};let s=Yr(o);if(s===0)return{kind:n,start:{...t,column:0},end:{...t,column:0}};let a=Math.max(0,Math.min(s-1,t.column));t.column===s&&(a=s-1);let c=rh(cd(o,a)),l=a,d=a+1;for(;l>0&&rh(cd(o,l-1))===c;)l-=1;for(;d<s&&rh(cd(o,d))===c;)d+=1;return{kind:n,start:{...t,column:l},end:{...t,column:d}}}i(zd,"resolveTranscriptSelectionSpanAt");function oh(e,t){return Uv(t.end,e.start)<0?{anchor:e.end,focus:t.start}:Uv(t.start,e.end)>0?{anchor:e.start,focus:t.end}:{anchor:e.start,focus:e.end}}i(oh,"extendTranscriptSelectionSpan");var Kv="Do not try to modify files while planning. Finish the plan first, then call exit_plan_mode with the finalized plan \u2014 the user will review and approve or reject.";function ih(e,t){if(qt(e))return[t.getGuardrail()]}i(ih,"buildAutoModeGuardrails");function V1(e,t){return e.reasoningMode?e.reasoningMode:t.reasoningMode?t.reasoningMode:e.thinking===!0||t.thinking===!0?"auto":"off"}i(V1,"resolveInitialReasoningMode");function z1(e,t){return!(t||e.role!=="evaluator"||e.signal!=="COMPLETE")}i(z1,"shouldFilterSidecarAcceptEntry");function Vv(e,t){let n=e.managedTask;if(!n)return[];let r=t?.verifierLog??process.env.KODAX_VERIFIER_LOG==="1",o=i(p=>{if(!e.interrupted&&!n.verdict.signalReason?.includes("Orchestration cancelled"))return!1;let g=p.signalReason?.trim()??"",x=p.summary?.trim()??"",y=p.output?.trim()??"",T=g.includes("Orchestration cancelled"),w=x.includes("Orchestration cancelled"),v=!y||x==="No textual output produced.";return p.status!=="completed"&&(T||w||v)||(T||w)&&v},"isInterruptedCancellation"),s=Y1(n),a=new Map(n.roleAssignments.map((p,g)=>[p.id,g])),c=n.verdict.decidedByAssignmentId,l=Math.max(0,...n.evidence.entries.filter(p=>p.assignmentId===c).map(p=>p.round??1)),d=[...n.evidence.entries].sort((p,g)=>{let x=(p.round??1)-(g.round??1);return x!==0?x:(a.get(p.assignmentId)??0)-(a.get(g.assignmentId)??0)}).filter(p=>!o(p)).filter(p=>!z1(p,r)).filter(p=>e.interrupted||!(p.assignmentId===c&&(p.round??1)===l)).map(p=>{let g=p.output?.trim()??"",x=p.summary?.trim()??"",y=g?Po(g):"",T=x?Po(x):"",w=p.role==="scout"?T?`Scout completed: ${T}`:"Scout completed.":T;return{entry:p,text:T||y||w}}).filter(({text:p})=>!!p).map(({entry:p,text:g})=>{let x=p.role==="scout"?" Preflight":(p.round??1)>1?` Round ${p.round}`:"";return`[${p.title??p.assignmentId}${x}]
360
- ${g}`}),m=n.verdict.disposition==="complete"?te("managed.completed"):n.verdict.disposition==="needs_continuation"?te("managed.completed.continuation"):n.verdict.disposition==="blocked"?te("managed.completed.blocked"):void 0;return[...s?[s]:[],...d,...m?[`[${m}]`]:[]]}i(Vv,"buildManagedTaskTranscriptItems");function X1(e){let t=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(t.length===0)return;if(t.length===1)return t[0];let[n,r]=t,o=n.startsWith("[")?`${n} ${r}`:`${n} / ${r}`;return o.length>220?`${o.slice(0,217)}...`:o}i(X1,"buildManagedTranscriptCompactText");function Zv(e){return e===`[${te("managed.completed")}]`||e===`[${te("managed.completed.blocked")}]`||e===`[${te("managed.completed.continuation")}]`}i(Zv,"isCompletionTranscriptItem");function zv(e){let t=X1(e);return{type:"event",icon:Zv(e)?"\u2713":">",text:e,...t&&t!==e?{compactText:t}:{}}}i(zv,"toManagedTranscriptEventItem");function zo(e){switch(e.type){case"assistant":return{type:"assistant",text:e.text,...e.compactText?{compactText:e.compactText}:{}};case"thinking":return{type:"thinking",text:e.text,...e.compactText?{compactText:e.compactText}:{}};case"event":return{type:"event",text:e.text,...e.icon?{icon:e.icon}:{},...e.compactText?{compactText:e.compactText}:{}};case"info":return{type:"info",text:e.text,...e.icon?{icon:e.icon}:{},...e.compactText?{compactText:e.compactText}:{}};case"error":return{type:"error",text:e.text};case"system":return{type:"system",text:e.text};case"hint":return{type:"hint",text:e.text};case"tool_group":return{type:"tool_group",tools:e.tools};case"user":return{type:"user",text:e.text};default:return e}}i(zo,"toCreatableHistoryItem");function Y1(e){let t=e.runtime?.rawRoutingDecision,n=e.runtime?.finalRoutingDecision;return!t||!n||t.harnessProfile==="H0_DIRECT"&&n.harnessProfile==="H0_DIRECT"?void 0:["[Routing]",`AMA routing: raw=${t.harnessProfile}(${t.routingSource??"unknown"}) -> final=${n.harnessProfile}`,`Primary task: ${t.primaryTask}`,`Review target: ${n.reviewTarget??"general"}`,`Review scale: ${n.reviewScale??"unknown"}`,`Solo boundary: ${t.soloBoundaryConfidence?.toFixed(2)??"n/a"}`,`Independent QA: ${t.needsIndependentQA?"yes":"no"}`,e.runtime?.qualityAssuranceMode?`Quality assurance: ${e.runtime.qualityAssuranceMode}`:void 0,e.runtime?.budget?`Adaptive budget: rounds=${e.runtime.budget.plannedRounds} total=${e.runtime.budget.totalBudget} reserve=${e.runtime.budget.reserveBudget}`:void 0,e.runtime?.routingOverrideReason?`Override reason: ${e.runtime.routingOverrideReason}`:void 0,n.upgradeCeiling?`Upgrade ceiling: ${n.upgradeCeiling}`:void 0].filter(o=>!!o).join(`
361
- `)}i(Y1,"buildManagedTaskRoutingTranscript");function q1(e,t=240){let n=e.trim();return n?n.length>t?`${n.slice(0,t-3)}...`:n:""}i(q1,"truncateToolPreview");function Q1(e,t=800){let n=e.trim();return n?n.length>t?`${n.slice(0,t-3)}...`:n:""}i(Q1,"truncateToolOutputPreview");function lh(e,t){if(!e||!t)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`^\\[Tools\\]\\s+\\[${n}\\]\\s+`,"i"),"[Tools] ").replace(new RegExp(`^\\[Thinking\\]\\s+\\[${n}\\]\\s*`,"i"),"[Thinking] ").replace(new RegExp(`^\\[${n}\\]\\s+thinking\\b`,"i"),"[Thinking]").trim()}i(lh,"formatManagedLiveActivityLabel");function Zr(e,t){return lh(`[Tools] ${Ju(e)}`,t)??`[Tools] ${Ju(e)}`}i(Zr,"formatManagedLiveToolLabel");function sh(e,t){if(e.type!==t.type)return!1;switch(e.type){case"assistant":{let n=t;return e.text===n.text&&e.compactText===n.compactText}case"thinking":{let n=t;return e.text===n.text&&e.compactText===n.compactText}case"event":{let n=t;return e.text===n.text&&e.compactText===n.compactText&&e.icon===n.icon}case"info":{let n=t;return e.text===n.text&&e.compactText===n.compactText&&e.icon===n.icon}case"error":case"hint":case"system":case"user":{let n=t;return e.text===n.text}case"tool_group":{let n=t;return JSON.stringify(e.tools)===JSON.stringify(n.tools)}default:return!1}}i(sh,"areManagedLiveItemsEquivalent");function J1(e){return e==="Task completed"?te("managed.completed"):e==="Task needs continuation"?te("managed.completed.continuation"):e==="Task ended: blocked"?te("managed.completed.blocked"):e==="Task ended: needs_continuation"?te("managed.completed.continuation"):e.startsWith("Task ended:")?te("managed.completed.blocked"):e}i(J1,"localizeManagedCompletionSummary");function Z1(e){if(e.events&&e.events.length>0)return e.events.reduce((r,o)=>{let s=o.summary.trim(),a=(o.detail??o.summary).trim();if(!s||!a)return r;let c=`managed-live-${o.key}`,l=Date.now(),d=o.persistToHistory??e.persistToHistory??!1;if(o.presentation==="thinking")return r.push({item:{id:c,type:"thinking",timestamp:l,text:a,...s!==a?{compactText:s}:{}},persistToHistory:d}),r;if(o.presentation==="assistant")return r.push({item:{id:c,type:"assistant",timestamp:l,text:a,...s!==a?{compactText:s}:{}},persistToHistory:d}),r;let m=o.kind==="completed";if(m&&!qd)return r;let p=m?`[${J1(s)}]`:void 0,g=p??s,x=p??a;return r.push({item:{id:c,type:"event",timestamp:l,text:x,icon:o.kind==="warning"?"!":m?"\u2713":">",...g!==x?{compactText:g}:{}},persistToHistory:d}),r},[]);if(e.phase==="completed"&&!qd)return[];let t=gc(e),n=gc(e,{expanded:!0})??t;return!t||!n?[]:[{item:{id:`managed-live-fallback-${e.phase??"worker"}-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,48)}`,type:"event",timestamp:Date.now(),text:n,icon:">",...t!==n?{compactText:t}:{}},persistToHistory:e.persistToHistory??!1}]}i(Z1,"buildManagedLiveEventDrafts");function e0(e){return e.replace(/^\[[^\]]+\]\s+/,"").replace(/^[A-Za-z][A-Za-z0-9_-]*:\s*/,"").trim()}i(e0,"stripToolRolePrefix");function Xv(e){return e0(e).toLowerCase()}i(Xv,"normalizeToolNameForMatch");function uh(e){return XS(e)?"":Po(e).trim()}i(uh,"sanitizeInterruptedAssistantText");function Yv(e){return!!(e?.activeWorkerId&&!e.childFanoutClass&&(e.phase==="preflight"||e.phase==="worker"))}i(Yv,"isForegroundManagedStreamingStatus");function eO(e,t,n){let r=[],o=n?.infoItems??[],s=dh({thinking:e,toolCalls:n?.toolCalls,toolNames:n?.toolNames});for(let c of o){let l=c.trim();l&&r.push({type:"info",text:l})}r.push(...s);let a=uh(t);return a&&r.push({type:"assistant",text:`${a}
362
-
363
- [Interrupted]`}),r}i(eO,"buildInterruptedPersistenceItems");function dh({thinking:e,response:t,toolCalls:n,toolNames:r}){let o=[],s=e?.trim()??"",a=t?.trim()??"",c=n&&n.length>0?[...n]:[],l=r&&r.length>0?[...r]:[];return s&&o.push({type:"thinking",text:s}),c.length>0?o.push({type:"tool_group",tools:c}):!s&&!a&&l.length>0&&o.push({type:"info",icon:"*",text:`Tools: ${l.join(", ")}`}),a&&o.push({type:"assistant",text:a}),o}i(dh,"buildRoundHistoryItems");function t0(e){if(e.type==="tool_group")return;let t=typeof e.text=="string"?e.text.trimEnd():"";if(t)return{type:e.type,text:t,...typeof e.icon=="string"&&e.icon.length>0?{icon:e.icon}:{},...typeof e.compactText=="string"&&e.compactText.length>0?{compactText:e.compactText.trimEnd()}:{}}}i(t0,"toPersistedUiHistoryItem");var qv=150,Qv=50,qd=process.env.KODAX_TRANSCRIPT_HARNESS_MARKERS==="1";function Xo(e){if(e.length===0)return[];let t=[];for(let r=0;r<e.length;r+=1)e[r]?.type==="user"&&t.push(r);let n=[...e];if(t.length>Qv){let r=t[t.length-Qv]??0;n=e.slice(r)}if(n.length>qv){let r=n.slice(-qv),o=r.findIndex(s=>s.type==="user");n=o>0?r.slice(o):r}return[...n]}i(Xo,"trimPersistedUiHistorySnapshot");function ks(e){if(e)return Xo(e)}i(ks,"normalizePersistedUiHistory");function Jv(e){return Xo(e.map(t=>t0(t)).filter(t=>!!t))}i(Jv,"serializeUiHistorySnapshot");function tO(e){return e.map(t=>t0(t)).filter(t=>!!t)}i(tO,"serializeCreatableHistoryItems");function Xd(e,t){return t.length===0?Xo(e):Xo([...e,...tO(t)])}i(Xd,"appendPersistedUiHistorySnapshot");function Yd(e,t,n){console.log((e==="block"?Ke.red:Ke.yellow)(t)),n.forEach(r=>console.log(Ke.dim(r)))}i(Yd,"logSessionTransitionGuard");var ah=i(({config:e,sessionId:t,workingDir:n,terminalWidth:r,compactionInfo:o})=>{let s=ne("dark"),a=e.model??Vn(e.provider)??e.provider,c=xo(e.provider,e.model),l=Ll(c),d=Math.min(60,r-4),m=o?Math.round(o.contextWindow/1e3):0,p=o?Math.round(o.contextWindow*o.triggerPercent/100/1e3):0;return Gt(k,{flexDirection:"column",marginBottom:1,children:[$g.map((g,x)=>se(b,{color:s.colors.primary,children:g},x)),Gt(k,{children:[Gt(b,{bold:!0,color:s.colors.text,children:[" v",Ri]}),se(b,{dimColor:!0,children:" | "}),Gt(b,{color:s.colors.success,children:[e.provider,"/",a]}),se(b,{dimColor:!0,children:` [${l}]`}),se(b,{dimColor:!0,children:" | "}),se(b,{color:s.colors.primary,children:e.agentMode.toUpperCase()}),se(b,{dimColor:!0,children:" | "}),se(b,{color:s.colors.accent,children:e.permissionMode}),e.reasoningMode!=="off"&&se(b,{color:s.colors.warning,children:` +reason:${e.reasoningMode}`})]}),o&&Gt(k,{children:[se(b,{dimColor:!0,children:" Context: "}),Gt(b,{dimColor:!0,children:[m,"k"]}),se(b,{dimColor:!0,children:" | Compaction: "}),se(b,{color:o.enabled?s.colors.success:void 0,dimColor:!o.enabled,children:o.enabled?"on":"off"}),se(b,{dimColor:!0,children:` @ ${o.triggerPercent}% (${p}k)`})]}),Gt(b,{dimColor:!0,children:[" ","-".repeat(d)]}),Gt(k,{children:[se(b,{dimColor:!0,children:" Session: "}),se(b,{color:s.colors.accent,children:t}),se(b,{dimColor:!0,children:" | Working: "}),se(b,{dimColor:!0,children:n})]}),Gt(b,{dimColor:!0,children:[" ","-".repeat(d)]})]})},"Banner");function nO(e){let t=e.config.model??Vn(e.config.provider)??e.config.provider,n=xo(e.config.provider,e.config.model),r=Ll(n),o=Math.min(60,e.terminalWidth-4),s=e.compactionInfo?Math.round(e.compactionInfo.contextWindow/1e3):0,a=e.compactionInfo?Math.round(e.compactionInfo.contextWindow*e.compactionInfo.triggerPercent/100/1e3):0,c=` v${Ri} | ${e.config.provider}/${t} [${r}] | ${e.config.agentMode.toUpperCase()} | ${e.config.permissionMode}${e.config.reasoningMode!=="off"?` +reason:${e.config.reasoningMode}`:""}`,l=e.compactionInfo?` Context: ${s}k | Compaction: ${e.compactionInfo.enabled?"on":"off"} @ ${e.compactionInfo.triggerPercent}% (${a}k)`:void 0,d=` Session: ${e.sessionId} | Working: ${e.workingDir}`,m=` ${"-".repeat(o)}`,p=[],g=i(y=>{let T=zt(y.length>0?y.split(`
364
- `):[""],Math.max(1,e.terminalWidth),0,0);return T.visualLines.length>0?T.visualLines:[""]},"wrapBannerLine"),x=i((y,T,w)=>{g(T).forEach((v,O)=>{p.push({key:`${y}-${O}`,text:v,...w})})},"pushLineRows");return $g.forEach((y,T)=>{x(`banner-logo-${T}`,y,{color:"primary"})}),x("banner-version",c,{color:"text",bold:!0}),l&&x("banner-compaction",l,{color:"dim"}),x("banner-divider-top",m,{color:"dim"}),x("banner-session",d,{color:"dim"}),x("banner-divider-bottom",m,{color:"dim"}),p.push({key:"banner-blank",text:" "}),{key:"banner",rows:p}}i(nO,"buildBannerTranscriptSection");function ch(e,t){return t?{...e,sections:[t,...e.sections],rows:[...t.rows,...e.rows]}:e}i(ch,"prependTranscriptSection");var rO=i(({options:e,config:t,context:n,storage:r,rendererMode:o,fullscreenPolicy:s,onExit:a,compactionInfo:c,autoModeBootstrap:l,setAutoModeAskUser:d,setAutoModeEngineChange:m,setCurrentConfigRef:p,onAgentsFilesReload:g,teamModeHandle:x})=>{let{exit:y}=Ur(),{stdout:T}=qn(),{stdin:w,setRawMode:v,isRawModeSupported:O}=Ma(),P=Ji(),{history:D}=oc(),L=Gv.useRef(null),X=Gv.useRef(wx()),{addHistoryItem:I,clearHistory:ie,setSessionId:Te}=ic(),K=me(D),q=me(Jv(D));He(()=>{K.current=D,q.current=Jv(D)},[D]),He(()=>{yb()},[]),He(()=>{dT()},[]);let M=T.columns||80,C=cc(),Z=me(C);He(()=>{Z.current=C},[C]);let{startStreaming:ke,stopStreaming:ve,abort:Se,startThinking:ce,appendThinkingChars:De,appendThinkingContent:ae,stopThinking:Y,clearThinkingContent:Q,setCurrentTool:Ce,appendToolInputChars:be,appendToolInputContent:at,clearToolInputContent:Re,clearResponse:Ue,appendResponse:xe,getSignal:kt,getFullResponse:qe,getThinkingContent:ee,startNewIteration:A,clearIterationHistory:_,startCompacting:W,stopCompacting:J,setMaxIter:Ne,addPendingInput:et,removeLastPendingInput:Ie,shiftPendingInput:Le,consumePendingInputs:Kt}=lc(),[V,fe]=We(!1),[F,_e]=We(t),Tt=ue(()=>Tv(c,{provider:F.provider,model:F.model},po),[c,F.provider,F.model]),[kr,_s]=We(!0),[Bn,CD]=We(!0),[Ec,Mc]=We(0),[mf,Ps]=We(!1),[vh,Hn]=We(null),aI=ue(()=>To(),[]),$s=me(null),Ac=me(null),Ih=me(Promise.resolve()),_c=me(null),no=me({requested:!1,uiHistoryOverride:void 0}),Ls=me(null),Os=me(!1),Ds=me(null),[pf,Pc]=We(!0),[gf,$c]=We(""),[Be,Fn]=We(()=>vb(aI,{rendererMode:o})),[Ct,hf]=We(!1),[cI,lI]=We(0),{scrollRef:uI,scrollOffset:kn,sticky:yf,setScrollOffset:dI,handleScrollTopChange:fI,handleStickyChange:mI,scrollTo:Lc,scrollBy:Oc,scrollToBottom:Dc}=cv(),xf=me(null),Nc=me(null),Ns=me([]),Bc=me([]),qo=me(null),Rn=me(null),kh=me({time:0,row:-1,column:-1,count:0}),[Hc,wf]=We(void 0),[ro,Sf]=We(void 0),[Qo,Rh]=We(void 0),[en,pI]=We(()=>new Set),[Tf,Eh]=We(null),[At,Mh]=We(null),[U,Cf]=We(null),[Fc,Rr]=We([]),Jo=ue(()=>{for(let f of Fc)if(f.status==="in_progress"){if(f.activeForm&&f.activeForm.length>0)return f.activeForm;if(f.subject&&f.subject.length>0)return f.subject}},[Fc]),[bD,Bs]=We([]),[Hs,gI]=We([]),[Wc,ut]=We(void 0),[oo,Uc]=We(void 0),nt=me(null),bf=me(null),io=me([]),Zo=me([]),ln=me([]),tt=me({}),dt=me({activeToolGroupTools:[]}),Ah=me(0),jc=me({itemId:void 0,kind:"thinking",pendingText:""}),En=me(null),hI=80,yI=20,xI=me(null),Gc=ue(()=>[...D,...Hs],[D,Hs]),vf=ue(()=>{let f=oC(Gc,xI);return f===0?Gc:Gc.slice(f)},[Gc]),If=ue(()=>iC(vf,yI),[vf]),Fs=vf,_t=me(null),Wn=me(null),Un=me([]),Pt=me([]),[so,wI]=We([]),ar=me([]),un=z(f=>{ar.current=f,wI(f)},[]),_h=z(f=>{io.current=f,Bs(f)},[]),ei=z(f=>{ln.current=f,gI(f)},[]),Ph=z(f=>{let h=f([...ln.current]);ei(h)},[ei]),$h=z(f=>{f.length!==0&&ei([...ln.current,...f])},[ei]),Kc=z(f=>{let h=dt.current,S=h.activeToolGroupTools.some(R=>R.status===$.Executing);dt.current={...f?.clearOwner?{}:{workerId:h.workerId,workerTitle:h.workerTitle},...S?{activeToolGroupItemId:h.activeToolGroupItemId,activeToolGroupTools:h.activeToolGroupTools}:{activeToolGroupTools:[]}},f?.clearOwner&&(tt.current={})},[]),Ws=z(()=>{jc.current={itemId:void 0,kind:"thinking",pendingText:""},En.current&&(clearTimeout(En.current),En.current=null),Kc({clearOwner:!0}),ei([])},[Kc,ei]),Vc=z(f=>(Ah.current+=1,`managed-foreground-${f}-${Ah.current}`),[]),dn=z(f=>($h([f]),f.id),[$h]),ao=z((f,h)=>{tt.current.workerId?dn({id:`${h}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:f.type,text:f.text,...f.icon?{icon:f.icon}:{},...f.tightSpacing?{tightSpacing:!0}:{},timestamp:Date.now()}):I(f)},[I,dn]),cr=z((f,h)=>{if(!f)return;let S;return Ph(R=>R.map(E=>E.id!==f?E:(S=h(E),S))),S},[Ph]),ti=z((f,h)=>{let S=dt.current;if(S.activeKind===f){if(f==="thinking"&&S.activeThinkingItemId)return S.activeThinkingItemId;if(f==="assistant"&&S.activeAssistantItemId)return S.activeAssistantItemId;if(f==="tool_group"&&S.activeToolGroupItemId)return S.activeToolGroupItemId}let R=Date.now(),E=h?.trim()?`[${h.trim()}] `:"",N=S.activeToolGroupTools.some(G=>G.status===$.Executing);if(f==="thinking"){let G=dn({id:Vc("thinking"),type:"thinking",timestamp:R,text:E});return dt.current={...dt.current,activeKind:"thinking",activeThinkingItemId:G,currentTurnThinkingItemId:G,activeAssistantItemId:void 0,...N?{}:{activeToolGroupItemId:void 0,activeToolGroupTools:[]}},G}if(f==="assistant"){let G=dn({id:Vc("assistant"),type:"assistant",timestamp:R,text:E});return dt.current={...dt.current,activeKind:"assistant",activeThinkingItemId:void 0,activeAssistantItemId:G,...N?{}:{activeToolGroupItemId:void 0,activeToolGroupTools:[]}},G}let B=dn({id:Vc("tool_group"),type:"tool_group",timestamp:R,tools:[]});return dt.current={...dt.current,activeKind:"tool_group",activeThinkingItemId:void 0,activeAssistantItemId:void 0,activeToolGroupItemId:B,activeToolGroupTools:[]},B},[dn,Vc]),Er=z(()=>{En.current&&(clearTimeout(En.current),En.current=null);let f=jc.current;if(!f.pendingText||!f.itemId)return;let h=f.pendingText,S=f.itemId,R=f.kind;f.pendingText="",cr(S,E=>E.type!==R?E:{...E,text:`${E.text}${h}`})},[cr]),Lh=z(()=>{En.current||(En.current=setTimeout(Er,hI))},[Er]),zc=z((f,h)=>{if(!h)return;let S=dt.current.workerTitle,R=ti(f,S),E=jc.current;E.itemId===R&&E.kind===f?E.pendingText+=h:(Er(),E.itemId=R,E.kind=f,E.pendingText=h),Lh()},[ti,Er,Lh]),Oh=z(f=>{let h=f.trim();if(!h)return;let S=jc.current;S.kind==="thinking"&&S.pendingText&&(S.pendingText="",En.current&&(clearTimeout(En.current),En.current=null));let R=dt.current.workerTitle?.trim(),E=R?`[${R}] ${h}`:h,N=dt.current.currentTurnThinkingItemId;if(N){cr(N,G=>G.type==="thinking"?{...G,text:E}:G);return}let B=ti("thinking",dt.current.workerTitle);cr(B,G=>G.type==="thinking"?{...G,text:E}:G)},[ti,cr]),Mn=z(f=>{Er();let h=dt.current;if(h.activeToolGroupItemId&&h.activeToolGroupTools.some(B=>B.id===f.id)){let B=h.activeToolGroupTools.map(oe=>oe.id===f.id?f:oe),G=B.every(oe=>oe.status===$.Success||oe.status===$.Error||oe.status===$.Cancelled);dt.current={...h,...G?{activeToolGroupItemId:void 0,activeToolGroupTools:[]}:{activeToolGroupTools:B}},cr(h.activeToolGroupItemId,oe=>oe.type==="tool_group"?{...oe,tools:B}:oe);return}let S=ln.current;for(let B=S.length-1;B>=0;B-=1){let G=S[B];if(G.type!=="tool_group"||!G.tools.some(ye=>ye.id===f.id))continue;let oe=G.tools.map(ye=>ye.id===f.id?f:ye);cr(G.id,ye=>ye.type==="tool_group"?{...ye,tools:oe}:ye);return}let R=ti("tool_group",h.workerTitle),N=h.activeKind==="tool_group"&&h.activeToolGroupItemId===R?h.activeToolGroupTools.some(B=>B.id===f.id)?h.activeToolGroupTools.map(B=>B.id===f.id?f:B):[...h.activeToolGroupTools,f]:[f];dt.current={...dt.current,activeKind:"tool_group",activeToolGroupItemId:R,activeToolGroupTools:N},cr(R,B=>B.type==="tool_group"?{...B,tools:N}:B)},[ti,cr,Er]),SI=z(f=>{Er();let h=dt.current,S=h.activeToolGroupTools.some(N=>N.status===$.Executing),R=ar.current.filter(N=>N.status===$.Executing),E=new Set(R.map(N=>N.id));dt.current={workerId:f?.workerId,workerTitle:f?.workerTitle,...S?{activeToolGroupItemId:h.activeToolGroupItemId,activeToolGroupTools:h.activeToolGroupTools}:{activeToolGroupTools:[]}},tt.current={workerId:f?.workerId,workerTitle:f?.workerTitle},Un.current=[],Pt.current=Pt.current.filter(N=>E.has(N.id)),un(R),Re(),Ce(void 0),Y(),Q(),Ue(),ut(void 0)},[Er,Re,Ue,Q,Ce,un,ut,Y]),TI=z(f=>{if(f.length===0)return[];let h=[],S=[...io.current],R=[...Zo.current];for(let E of f){let N=E.item,B=S.findIndex(G=>G.id===N.id);if(B>=0){let G=S[B];sh(G,N)||(S=S.map((oe,ye)=>ye===B?{...N,timestamp:G.timestamp}:oe))}else S=[...S,N].slice(-12),h.push(N);if(E.persistToHistory){let G=R.findIndex(oe=>oe.id===N.id);if(G>=0){let oe=R[G];sh(oe,N)||(R=R.map((ye,ct)=>ct===G?{...N,timestamp:oe.timestamp}:ye))}else R=[...R,N].slice(-48)}}return Zo.current=R,(h.length>0||S.some((E,N)=>!sh(E,io.current[N]??E)||E.id!==io.current[N]?.id))&&_h(S),h},[_h]),Xc=z(f=>{if(Pt.current.findIndex(S=>S.id===f.id)===-1){Pt.current=[...Pt.current,f];return}Pt.current=Pt.current.map(S=>S.id===f.id?f:S)},[]),Mr=z(f=>{let h=ar.current.filter(S=>S.status===$.Executing);if(h.length!==0){if(f){let S=Xv(f);for(let R=h.length-1;R>=0;R-=1){let E=h[R];if(Xv(E.name)===S)return E}}return h[h.length-1]}},[]),ni=z(()=>{let f=Mr();Ce(f?e0(f.name):void 0)},[Mr,Ce]),Dh=z(f=>(Xc(f),un([...ar.current.filter(h=>h.id!==f.id),f]),ni(),f),[un,ni,Xc]),ri=z((f,h)=>{let S=ar.current.find(E=>E.id===f);if(!S)return null;let R=h(S);return Xc(R),un(ar.current.map(E=>E.id===f?R:E)),ni(),R},[un,ni,Xc]),Nh=z((f,h,S)=>{if(f){let E=ri(f,S);if(E)return E}let R=Mr(h);return R?ri(R.id,S):null},[Mr,ri]),Yc=z((f,h,S,R,E)=>{let N=f??Mr(E)?.id;return N?ri(N,B=>({...B,status:h,endTime:Date.now(),error:S,output:R})):null},[Mr,ri]),Us=z((f,h)=>{let S=Date.now(),R=new Map;for(let E of ar.current){if(E.status!==$.Executing)continue;let N=h(E);R.set(E.id,{...E,status:f,endTime:S,...N})}return R.size===0?[]:(Pt.current=Pt.current.map(E=>R.get(E.id)??E),un(ar.current.map(E=>R.get(E.id)??E)),ni(),[...R.values()])},[un,ni]),Ar=z(()=>{un([])},[un]),{showHelp:Bh,toggleHelp:CI,setShowHelp:Hh}=Dg(),bI=z(f=>{$c(f),Pc(f.trim().length===0)},[]),qc=Bo(),Fh=ue(()=>qc?qc.state.visible&&qc.suggestions.length>0:!1,[qc]),[js,Wh]=We(!1),Uh=me(Ec),Gs=z(()=>{_t.current&&(clearTimeout(_t.current),_t.current=null),Wn.current&&(clearTimeout(Wn.current),Wn.current=null)},[]);He(()=>{Fh&&!js&&Wh(!0)},[Fh,js]),He(()=>{Ec!==Uh.current&&(Uh.current=Ec,js&&Wh(!1))},[Ec,js]);let[Ye,Qc]=We(null),co=me(null),[Pe,An]=We(null),Jc=me(null),Zc=me(Pe);Zc.current=Pe;let[Ft,oi]=We(""),[el,_n]=We(0),kf=me(""),Ks=me(void 0),jh=ue(()=>{if(!Tt)return;let{contextWindow:f,triggerPercent:h}=Tt;return{currentTokens:vh??n.contextTokenSnapshot?.currentTokens??go(n.messages),contextWindow:f,triggerPercent:h}},[n.messages,n.contextTokenSnapshot,Tt,vh]),Vs=ue(()=>{if(!Ye)return;let f=!!Ye.input._alwaysConfirm,h=F.permissionMode==="accept-edits"&&!f;return f?te("confirm.instruction.protected"):h?te("confirm.instruction.always"):te("confirm.instruction.basic")},[Ye,F.permissionMode]),rt=Be.searchMode==="history",re=Be.surface==="transcript",_r=!!Ye||!!Pe||rt,gt=re?Ct?ZT:1e3:12,Pr=Fv(s,Be.surface),Gh=Pr.shellMode,Rf=Pr.usesAlternateScreenShell,ii=Pr.usesRendererViewportShell,tl=Pr.usesRendererMouseTracking,Kh=Pr.usesManagedMouseClicks,Vh=Pr.usesManagedMouseWheel,Ef=Pr.usesManagedSelection,ht=Wv(s,Be.surface,Lb(Be)),zh=Ob(Be),nl=js&&!re,Xh=z(()=>nh({items:Fs,managedLiveEvents:[],isLoading:V,isThinking:C.isThinking,thinkingCharCount:C.thinkingCharCount,thinkingContent:C.thinkingContent,currentResponse:C.currentResponse,currentTool:C.currentTool,activeToolCalls:so,toolInputCharCount:C.toolInputCharCount,toolInputContent:C.toolInputContent,lastLiveActivityLabel:Wc,workStripText:oo,iterationHistory:C.iterationHistory,currentIteration:C.currentIteration,isCompacting:C.isCompacting}),[Fs,V,C.isThinking,C.thinkingCharCount,C.thinkingContent,C.currentResponse,C.currentTool,so,C.toolInputCharCount,C.toolInputContent,Wc,oo,C.iterationHistory,C.currentIteration,C.isCompacting]);He(()=>{if(re){Eh(f=>f??Xh());return}Eh(null)},[Xh,re]);let zs=ue(()=>Dv({isTranscriptMode:re,snapshot:Tf,currentItemsLength:Fs.length,currentManagedLiveEventsLength:0,isLoading:V,currentResponse:C.currentResponse,thinkingContent:C.thinkingContent,activeToolCallsLength:so.length}),[so.length,V,re,Fs.length,C.currentResponse,C.thinkingContent,Tf]),$t=re?Tf:null,Mf=ue(()=>Bv(If),[If]),vI=ue(()=>!!(Hs.length>0||Yv(U)),[Hs.length,U]),rl=Hs.length>0,Lt=s.streamingPreview&&vI,si=Nv({surface:"transcript",snapshot:$t,promptItems:If,transcriptItems:Fs}),Xs=ue(()=>{if(!re||Ct||si.length<=Jp)return si;let f=si.slice(-Jp),h=si.length-f.length;return[cC(h,f[0]?.timestamp),...f]},[si,re,Ct]),ot=$t?.isLoading??V,Qe=s.streamingPreview?{isThinking:Lt?!1:C.isThinking,thinkingCharCount:Lt?0:C.thinkingCharCount,thinkingContent:Lt?"":C.thinkingContent,currentResponse:Lt?"":C.currentResponse,currentTool:Lt?void 0:C.currentTool,activeToolCalls:Lt?[]:so,toolInputCharCount:0,toolInputContent:"",managedLiveEvents:[],lastLiveActivityLabel:Lt?Wc:void 0,iterationHistory:[],currentIteration:C.currentIteration,isCompacting:!1}:{isThinking:!1,thinkingCharCount:0,thinkingContent:"",currentResponse:"",currentTool:void 0,activeToolCalls:[],toolInputCharCount:0,toolInputContent:"",managedLiveEvents:[],lastLiveActivityLabel:void 0,iterationHistory:[],currentIteration:C.currentIteration,isCompacting:!1},pe=s.streamingPreview?{isThinking:Lt?!1:$t?.isThinking??C.isThinking,thinkingCharCount:Lt?0:$t?.thinkingCharCount??C.thinkingCharCount,thinkingContent:Lt?"":$t?.thinkingContent??C.thinkingContent,currentResponse:Lt?"":$t?.currentResponse??C.currentResponse,currentTool:Lt?void 0:$t?.currentTool??C.currentTool,activeToolCalls:Lt?[]:$t?.activeToolCalls??so,toolInputCharCount:Lt?0:$t?.toolInputCharCount??C.toolInputCharCount,toolInputContent:Lt?"":$t?.toolInputContent??C.toolInputContent,managedLiveEvents:[],lastLiveActivityLabel:$t?.lastLiveActivityLabel??Wc,iterationHistory:Lt?[]:$t?.iterationHistory??C.iterationHistory,currentIteration:$t?.currentIteration??C.currentIteration,isCompacting:$t?.isCompacting??C.isCompacting}:{isThinking:!1,thinkingCharCount:0,thinkingContent:"",currentResponse:"",currentTool:void 0,activeToolCalls:[],toolInputCharCount:0,toolInputContent:"",managedLiveEvents:[],lastLiveActivityLabel:void 0,iterationHistory:[],currentIteration:$t?.currentIteration??C.currentIteration,isCompacting:!1},lr=re?ro:Hc,Yh=!!Hc,qh=z(()=>nh({items:Mf,managedLiveEvents:[],isLoading:V,isThinking:Qe.isThinking,thinkingCharCount:Qe.thinkingCharCount,thinkingContent:Qe.thinkingContent,currentResponse:Qe.currentResponse,currentTool:Qe.currentTool,activeToolCalls:Qe.activeToolCalls,toolInputCharCount:Qe.toolInputCharCount,toolInputContent:Qe.toolInputContent,lastLiveActivityLabel:Qe.lastLiveActivityLabel,iterationHistory:Qe.iterationHistory,currentIteration:Qe.currentIteration,isCompacting:Qe.isCompacting}),[V,Mf,Qe.activeToolCalls,Qe.currentIteration,Qe.currentResponse,Qe.currentTool,Qe.isCompacting,Qe.isThinking,Qe.iterationHistory,Qe.lastLiveActivityLabel,Qe.thinkingCharCount,Qe.thinkingContent,Qe.toolInputCharCount,Qe.toolInputContent]);He(()=>{if(!Yh){Mh(null);return}Mh(f=>f??qh())},[qh,Yh]);let Ys=At?.items??Mf,Wt=At?.isLoading??V,Ee=At?{isThinking:At.isThinking,thinkingCharCount:At.thinkingCharCount,thinkingContent:At.thinkingContent,currentResponse:At.currentResponse,currentTool:At.currentTool,activeToolCalls:At.activeToolCalls,toolInputCharCount:At.toolInputCharCount,toolInputContent:At.toolInputContent,managedLiveEvents:At.managedLiveEvents,lastLiveActivityLabel:At.lastLiveActivityLabel,iterationHistory:At.iterationHistory,currentIteration:At.currentIteration,isCompacting:At.isCompacting}:Qe,Rt=re?Xs:Ys,jn=re?ot:Wt,je=re?pe:Ee,Qh=Wt&&!C.currentResponse&&!C.thinkingContent&&so.length===0,lo=ue(()=>({config:F,sessionId:n.sessionId,workingDir:e.context?.gitRoot||process.cwd(),terminalWidth:M,compactionInfo:Tt??void 0}),[Tt,n.sessionId,F,e.context?.gitRoot,M]),ai=ue(()=>s.enabled&&Bn?nO(lo):void 0,[lo,s.enabled,Bn]),Af=ue(()=>rd({items:Ys,viewportWidth:M,maxLines:gt,showDetailedTools:!1,showAllContent:!1,windowed:!1}),[Ys,M,gt]),ol=ue(()=>{let f=od({activeItems:Af.activeItems,viewportWidth:M,isLoading:Wt,maxLines:gt,isThinking:Ee.isThinking,thinkingCharCount:Ee.thinkingCharCount,thinkingContent:Ee.thinkingContent,streamingResponse:Ee.currentResponse,currentTool:Ee.currentTool,activeToolCalls:Ee.activeToolCalls,toolInputCharCount:Ee.toolInputCharCount,toolInputContent:Ee.toolInputContent,iterationHistory:Ee.iterationHistory,currentIteration:Ee.currentIteration,isCompacting:Ee.isCompacting,managedAgentMode:F.agentMode,managedPhase:Wt?U?.phase:void 0,managedHarnessProfile:Wt?U?.harnessProfile:void 0,managedWorkerTitle:Wt?U?.activeWorkerTitle:void 0,managedRound:Wt?U?.currentRound:void 0,managedMaxRounds:Wt?U?.maxRounds:void 0,managedGlobalWorkBudget:Wt?U?.globalWorkBudget:void 0,managedBudgetUsage:Wt?U?.budgetUsage:void 0,managedBudgetApprovalRequired:Wt?U?.budgetApprovalRequired:void 0,lastLiveActivityLabel:Ee.lastLiveActivityLabel,currentTodoActiveForm:Jo,showFullThinking:!1,showDetailedTools:!1,showAllContent:!1,showLiveProgressRows:Qh});return ch(Qp(id(Af,f)),ai)},[F.agentMode,Wt,Ee.activeToolCalls,Ee.currentIteration,Ee.currentTool,Ee.isCompacting,Ee.currentResponse,Ee.isThinking,Ee.iterationHistory,Ee.lastLiveActivityLabel,Ee.thinkingCharCount,Ee.thinkingContent,Ee.toolInputCharCount,Ee.toolInputContent,U?.activeWorkerTitle,U?.budgetApprovalRequired,U?.budgetUsage,U?.currentRound,U?.globalWorkBudget,U?.harnessProfile,U?.maxRounds,U?.phase,Qh,Af,ai,M,gt,Jo]),_f=ue(()=>rd({items:Xs,viewportWidth:M,maxLines:gt,showDetailedTools:Ct,showAllContent:Ct,windowed:!1}),[Xs,M,gt,Ct]),il=ue(()=>{if(!re||ii)return;let f=od({activeItems:_f.activeItems,viewportWidth:M,isLoading:ot,maxLines:gt,isThinking:pe.isThinking,thinkingCharCount:pe.thinkingCharCount,thinkingContent:pe.thinkingContent,streamingResponse:pe.currentResponse,currentTool:pe.currentTool,activeToolCalls:pe.activeToolCalls,toolInputCharCount:pe.toolInputCharCount,toolInputContent:pe.toolInputContent,iterationHistory:pe.iterationHistory,currentIteration:pe.currentIteration,isCompacting:pe.isCompacting,managedAgentMode:F.agentMode,managedPhase:ot?U?.phase:void 0,managedHarnessProfile:ot?U?.harnessProfile:void 0,managedWorkerTitle:ot?U?.activeWorkerTitle:void 0,managedRound:ot?U?.currentRound:void 0,managedMaxRounds:ot?U?.maxRounds:void 0,managedGlobalWorkBudget:ot?U?.globalWorkBudget:void 0,managedBudgetUsage:ot?U?.budgetUsage:void 0,managedBudgetApprovalRequired:ot?U?.budgetApprovalRequired:void 0,lastLiveActivityLabel:pe.lastLiveActivityLabel,currentTodoActiveForm:Jo,showFullThinking:!0,showDetailedTools:Ct,showAllContent:Ct,showLiveProgressRows:!rl,expandedItemKeys:en});return ch(Qp(id(_f,f)),ai)},[F.agentMode,en,rl,ai,re,U?.activeWorkerTitle,U?.budgetApprovalRequired,U?.budgetUsage,U?.currentRound,U?.globalWorkBudget,U?.harnessProfile,U?.maxRounds,U?.phase,M,ot,gt,_f,pe.activeToolCalls,pe.currentIteration,pe.currentResponse,pe.currentTool,pe.isCompacting,pe.isThinking,pe.iterationHistory,pe.lastLiveActivityLabel,pe.thinkingCharCount,pe.thinkingContent,pe.toolInputCharCount,pe.toolInputContent,Ct,ii,Jo]),qs=ue(()=>{if(ht)return re?ch(sd({items:Rt,viewportWidth:M,isLoading:jn,maxLines:gt,isThinking:je.isThinking,thinkingCharCount:je.thinkingCharCount,thinkingContent:je.thinkingContent,streamingResponse:je.currentResponse,currentTool:je.currentTool,activeToolCalls:je.activeToolCalls,toolInputCharCount:je.toolInputCharCount,toolInputContent:je.toolInputContent,iterationHistory:je.iterationHistory,currentIteration:je.currentIteration,isCompacting:je.isCompacting,managedAgentMode:F.agentMode,managedPhase:jn?U?.phase:void 0,managedHarnessProfile:jn?U?.harnessProfile:void 0,managedWorkerTitle:jn?U?.activeWorkerTitle:void 0,managedRound:jn?U?.currentRound:void 0,managedMaxRounds:jn?U?.maxRounds:void 0,managedGlobalWorkBudget:jn?U?.globalWorkBudget:void 0,managedBudgetUsage:jn?U?.budgetUsage:void 0,managedBudgetApprovalRequired:jn?U?.budgetApprovalRequired:void 0,lastLiveActivityLabel:je.lastLiveActivityLabel,currentTodoActiveForm:Jo,windowed:!0,showFullThinking:re,showDetailedTools:Ct,showAllContent:Ct,showLiveProgressRows:re&&!rl,expandedItemKeys:re?en:void 0}),ai):ol},[F.agentMode,jn,Rt,rl,ai,je.activeToolCalls,je.currentIteration,je.currentResponse,je.currentTool,je.isCompacting,je.isThinking,je.iterationHistory,je.lastLiveActivityLabel,je.thinkingCharCount,je.thinkingContent,je.toolInputCharCount,je.toolInputContent,en,re,U?.activeWorkerTitle,U?.budgetApprovalRequired,U?.budgetUsage,U?.currentRound,U?.globalWorkBudget,U?.harnessProfile,U?.maxRounds,U?.phase,ol,V,re,M,gt,ht,Ct,Jo]),Gn=ue(()=>qs??il,[qs,il]),Qs=ue(()=>th({status:U,isLoading:V,agentMode:F.agentMode}),[F.agentMode,V,U]).workStripText,Js=$t?.workStripText??oo,ci=ue(()=>th({status:U,isLoading:V,agentMode:F.agentMode,parallelTextOverride:Js}),[F.agentMode,Js,V,U]),uo=ue(()=>ev(Rt).filter(f=>f!==ad),[Rt]),ze=ue(()=>Kd(Be,uo,Be.selectedItemId),[uo,Be]),tn=ue(()=>Rt.find(f=>f.id===ze),[Rt,ze]),Jh=ue(()=>({...Be,supportsSelection:Be.supportsSelection&&ht,supportsCopyOnSelect:Be.supportsCopyOnSelect&&ht}),[Be,ht]),fn=ue(()=>bv({state:Jh,selectableItemIds:uo,selectedItemId:ze,selectedItemType:tn?.type,isExpanded:ze?en.has(ze):!1}),[en,uo,tn?.type,ze,Jh]),Zh=fn.selectionEnabled,ey=fn.copyCapabilities.copyOnSelect,kD=fn.selectedItemIndex,ty=ue(()=>Zb(tn),[tn]),sl=ue(()=>Yb(Rt.filter(f=>!eg(f))),[Rt]),bt=ue(()=>qb(sl,Ft),[sl,Ft]),al=ue(()=>kv({isHistorySearchActive:rt,historySearchQuery:Ft,matches:bt,selectedIndex:el,anchorItemId:Be.searchAnchorItemId,useOverlaySurface:Be.supportsOverlaySurface&&Be.supportsSearchViewport&&ht}),[bt,Ft,el,rt,Be.searchAnchorItemId,Be.supportsOverlaySurface,Be.supportsSearchViewport,ht]),$r=al.clampedSelectedIndex,ny=al.statusText,Pf=al.detailText,ry=al.searchState,RD=fn.detailState==="expanded",cl=fn.selectionEnabled&&uo.length>0&&!lr,li=fn.copyCapabilities.message,ll=fn.copyCapabilities.toolInput,ul=fn.toggleDetail;He(()=>{if(Qs){if(Wn.current&&(clearTimeout(Wn.current),Wn.current=null),oo===Qs)return;if(oo){_t.current&&(clearTimeout(_t.current),_t.current=null),Uc(Qs);return}_t.current&&clearTimeout(_t.current),_t.current=setTimeout(()=>{Uc(Qs),_t.current=null},400);return}if(!oo){_t.current&&(clearTimeout(_t.current),_t.current=null);return}_t.current&&(clearTimeout(_t.current),_t.current=null),Wn.current&&clearTimeout(Wn.current),Wn.current=setTimeout(()=>{Uc(void 0),Wn.current=null},300)},[Gs,Qs,oo]),He(()=>()=>{Gs()},[Gs]);let Lr=ue(()=>ov({state:Be,ownsViewport:ht,isAwaitingUserInteraction:_r,isHistorySearchActive:rt,isTranscriptMode:re,historySearchQuery:Ft}),[Ft,_r,rt,re,Be,ht]);He(()=>{Fn(f=>{let h=Eb(f,kn);return h=Rb(h,zs),h=Ab(h,s.enabled&&ht?!yf||rt||_r:re||rt||_r),h=$b(h,$r),h})},[$r,s.enabled,kn,_r,rt,re,zs,ht,yf]),He(()=>{el!==$r&&_n($r)},[$r,el]),He(()=>{if(!rt){kf.current=Ft;return}if(Ft===kf.current)return;kf.current=Ft;let f=Jb(sl,bt,Be.searchAnchorItemId);_n(f)},[bt,Ft,rt,Be.searchAnchorItemId,sl]);let oy=re?pe:{isThinking:Ee.isThinking,thinkingCharCount:Ee.thinkingCharCount,currentTool:Ee.currentTool,activeToolCalls:Ee.activeToolCalls,toolInputCharCount:Ee.toolInputCharCount,toolInputContent:Ee.toolInputContent,currentIteration:Ee.currentIteration,isCompacting:Ee.isCompacting},Zs=re?ot:Wt,[$f,Lf]=We(()=>qt(F.permissionMode)?l.getGuardrail().getEngine():void 0),dl=ue(()=>Cv({sessionId:n.sessionId,permissionMode:F.permissionMode,agentMode:F.agentMode,provider:F.provider,model:F.model??Vn(F.provider)??F.provider,thinking:F.thinking,reasoningMode:F.reasoningMode,reasoningCapability:Ll(xo(F.provider,F.model)),isTranscriptMode:re,streamingState:oy,maxIter:C.maxIter,contextUsage:jh,isLoading:Zs,managedState:{phase:U?.phase,harnessProfile:U?.harnessProfile,workerTitle:U?.activeWorkerTitle,round:U?.currentRound,maxRounds:U?.maxRounds,globalWorkBudget:U?.globalWorkBudget,budgetUsage:U?.budgetUsage,budgetApprovalRequired:U?.budgetApprovalRequired,idleWaiting:U?.idleWaiting,idleWaitingPendingCount:U?.idleWaitingPendingCount},autoModeEngine:$f}),[n.sessionId,F.permissionMode,F.agentMode,F.provider,F.model,F.thinking,F.reasoningMode,re,oy,C.maxIter,jh,Zs,U?.phase,U?.harnessProfile,U?.activeWorkerTitle,U?.currentRound,U?.maxRounds,U?.globalWorkBudget,U?.budgetUsage,U?.budgetApprovalRequired,U?.idleWaiting,U?.idleWaitingPendingCount,$f]),Of=Ye?"confirm":Pe?.kind,Or=ue(()=>Sv({isTranscriptMode:re,isLoading:Zs,streamingState:Ee,managedState:Zs?{phase:U?.phase,harnessProfile:U?.harnessProfile,workerTitle:U?.activeWorkerTitle}:void 0,waitingReason:Of}),[Ee.activeToolCalls,Ee.currentTool,Ee.isCompacting,Ee.isThinking,Ee.thinkingCharCount,Ee.toolInputCharCount,Ee.toolInputContent,re,U?.activeWorkerTitle,U?.harnessProfile,U?.phase,Of,Zs]),Df=Or?.text,ur=ue(()=>ZC(Fc,{now:Date.now(),lastAllCompletedAt:null}),[Fc]),iy=me(!1);He(()=>{iy.current&&!V&&Rr(f=>f.length>0?[]:f),iy.current=V},[V]);let Nf=ue(()=>fd(dl),[dl]),sy=ue(()=>Nf,[Nf]),ay=sy.text,II=ue(()=>PC(C.pendingInputs),[C.pendingInputs]),Bf=ue(()=>eb({isHistorySearchActive:rt,isTranscriptMode:re,pendingInputCount:C.pendingInputs.length,buffering:Be.buffering,pendingLiveUpdates:zs}),[rt,re,zs,C.pendingInputs.length,Be.buffering]),cy=Bf.leftItems,ly=Bf.rightItems,uy=Bf.summary,fl=ue(()=>Ev({historySearchQuery:Ft,pendingInputCount:C.pendingInputs.length}),[Ft,C.pendingInputs.length]),ml=ue(()=>Rv({historySearchQuery:Ft,isHistorySearchActive:rt,historySearchMatchCount:bt.length,pendingInputCount:C.pendingInputs.length,maxPendingInputs:5}),[bt.length,Ft,rt,C.pendingInputs.length]),dy=ue(()=>ml.map(f=>f.text).join(" | "),[ml]),pl=ue(()=>Mv({inputText:gf,isTranscriptMode:re,isHistorySearchActive:rt}),[gf,rt,re]),fy=Be.supportsOverlaySurface&&Be.supportsSearchViewport&&ht,gl=ue(()=>vv({runtime:fn,itemSummary:ty}),[ty,fn]),Hf=ue(()=>Av(fl),[fl]),my=ue(()=>_v({textSelection:lr,selectionState:gl,isHistorySearchActive:rt,historySearchDetailText:Pf,historySearchHasMatches:!!ny&&bt.length>0,showAllActive:Ct,baseFooterNotices:fl}),[lr,fl,Pf,bt.length,ny,rt,Ct,gl]),kI=my.secondaryText,RI=my.budgetNotices,py=re?RI:Hf,gy=T.rows??24,hy=re?"":gf,yy=re?void 0:II,xy=Js,wy=re?!1:Bh,Ut=ue(()=>bb({terminalRows:gy,terminalWidth:M,windowedTranscript:ii,inputText:hy,footerHeaderText:uy,activitySummary:re?void 0:Df,activityBarVisible:re?!1:!!Df||V&&ur.shouldRender,todoSurfaceRows:re?0:V&&ur.shouldRender?ur.rows.length:0,pendingInputSummary:yy,stashNoticeSummary:pl,notificationSummary:dy,statusNoticeSummary:py.join(" | "),workStripText:xy,suggestionsReserved:nl,suggestionsMode:"inline",showHelp:wy,statusBarText:ay,confirmPrompt:Ye?.prompt,confirmInstruction:Vs,dialogMode:"inline",reviewHint:s.enabled&&ht?void 0:Lr.browseHintText,uiRequest:Pe?Pe.kind==="select"?{kind:"select",title:Pe.title,options:Pe.options.map(f=>({label:f.label,description:f.description})),buffer:Pe.buffer,error:Pe.error}:{kind:"input",prompt:Pe.prompt,defaultValue:Pe.defaultValue,buffer:Pe.buffer,error:Pe.error}:null}),[gy,M,hy,uy,Df,yy,pl,dy,py,xy,nl,fy,wy,ay,Ye,Vs,s.enabled,Lr.browseHintText,ht,Pe]),EI=ue(()=>se(hg,{reserveSpace:nl,width:M,hidden:re,mode:"inline"}),[nl,M,re,fy]),ea=ue(()=>iv(Ut.messageRows),[Ut.messageRows]),Sy=ue(()=>sv(ea),[ea]),ui=!zh&&s.transcriptSpinnerAnimation,ta=Gn?Gn.rows.length+Gn.previewRows.length:cI,hl=z(f=>{Gn||lI(f.scrollHeight)},[Gn]),na=z(f=>fv({window:f,stickyHeader:Lr.stickyHeader,width:M,topChromeRows:0}),[M,Lr.stickyHeader]),di=z((f=Ns.current,h=Bc.current,S=xf.current?na(xf.current):Nc.current)=>{if(!S||f.length===0){qo.current=null;return}Nc.current=S,qo.current=mv(f,{allRows:h,rowIndexByKey:qg(h),topOffsetRows:S.topOffsetRows,viewportHeight:S.contentWindow.viewportHeight,animateSpinners:ui})},[na,ui]),ra=z(()=>{let f=Nc.current;return f?.contentWindow.viewportHeight&&f.contentWindow.viewportHeight>0?f.contentWindow.viewportHeight:Ut.messageRows},[Ut.messageRows]),MI=z(f=>{xf.current=f;let h=na(f);Nc.current=h,di(Ns.current,Bc.current,h)},[di,na]),yl=z(f=>{Ns.current=f.rows,Bc.current=f.allRows,di(f.rows,f.allRows)},[di]),Ot=z(()=>{Rn.current=null,wf(void 0),Sf(void 0)},[]),Ff=z(()=>{Ot(),Fn(f=>Is(f,void 0))},[Ot]);He(()=>{di()},[di]),He(()=>{dI(f=>av(f,ta,Ut.messageRows))},[ta,Ut.messageRows]),He(()=>{if(!Qo)return;let f=setTimeout(()=>{Rh(void 0)},2e3);return()=>{clearTimeout(f)}},[Qo]);let dr=z((f,h="success")=>{let S=f?.trim();S&&Rh({text:S,tone:h})},[]),fi=z((f,h)=>{let S=h instanceof Error?h.message:String(h);return`${f}: ${S}`},[]),xl=z(async f=>{let h=f??lr;if(!h)return!1;let S=h.text.trimEnd();if(!S)return!1;try{return await Lo(S,{terminalWrite:P}),dr(`Copied ${h.rowCount} selected line${h.rowCount===1?"":"s"} to clipboard.`,"success"),!0}catch(R){return dr(fi("Failed to copy transcript selection",R),"warning"),!1}},[lr,fi,dr,P]),mi=z(f=>{if(!f||lv({items:Rt,renderModel:Gn,terminalWidth:M,transcriptMaxLines:gt,viewportRows:ra(),itemId:f,visibleRows:Ns.current,expandedItemKeys:en,showDetailedTools:!1}))return;let h=uv({items:Rt,renderModel:Gn,terminalWidth:M,transcriptMaxLines:gt,viewportRows:ra(),itemId:f,expandedItemKeys:en,showDetailedTools:!1});Lc(h)},[Rt,M,gt,Gn,en,ra,Lc,Ns]),Ty=z(f=>{Fn(h=>Is(h,f)),f&&mi(f)},[mi]),Wf=z(f=>{f&&mi(f)},[mi]),Cy=z(f=>{if(!cl)return;let h=tv(uo,ze,f);h&&Ty(h)},[cl,uo,ze,Ty]),by=z(()=>{!ul||!ze||(pI(f=>{let h=new Set(f);return h.has(ze)?h.delete(ze):h.add(ze),h}),mi(ze))},[mi,ul,ze]),vy=z(async()=>{if(!li||!tn)return;let f=Yg(tn);if(f)try{await Lo(f,{terminalWrite:P}),dr("Copied selected transcript entry to clipboard.","success")}catch(h){dr(fi("Failed to copy transcript entry",h),"warning")}},[fi,li,tn,dr,P]),Iy=z(async()=>{if(!ll||!tn)return;let f=nv(tn);if(f)try{await Lo(f,{terminalWrite:P}),dr("Copied selected tool args to clipboard.","success")}catch(h){dr(fi("Failed to copy tool args",h),"warning")}},[fi,ll,tn,dr,P]),oa=z(()=>Bc.current,[]),ky=z((f,h)=>{if(!s.enabled||!ht)return;let S=qo.current;return S?Jg(S,f,h):void 0},[s.enabled,ht]),pi=z((f,h,S)=>{let R=oa(),E=hv(R,f,h,{animateSpinners:ui,selectFullRowOnCollapsed:S?.selectFullRowOnCollapsed});re?Sf(E):wf(E);let N=R[Math.max(0,Math.min(h.modelRowIndex,R.length-1))];return S?.updateSelectedItem&&N?.itemId&&Fn(B=>Is(B,N.itemId)),E},[re,oa,ui]),Ry=z((f,h)=>{if(!f)return;Rn.current=null;let S={...f,focus:h?.focusPoint??f.focus};if(!(S.mode!=="char"||S.didDrag)){Ot();return}let E=pi(S.anchor,S.focus,{selectFullRowOnCollapsed:!1,updateSelectedItem:!1});if(!E){Ot();return}return h?.copySelection!==!1&&xl(E),E},[Ot,xl,pi]),Uf=z(()=>{if(!re||!Rt.length||Ye||Pe)return;Ot();let f=dv({items:Rt,selectedItemId:ze,renderModel:Gn,terminalWidth:M,transcriptMaxLines:gt,viewportRows:ra(),scrollOffset:kn,expandedItemKeys:en,showDetailedTools:!1,preferViewportAnchor:!0});Fn(h=>_b(h,{anchorItemId:f,initialMatchIndex:0})),oi(""),_n(0)},[Ye,Rt,en,kn,re,ze,Gn,M,gt,Pe,ra,Ot]),jf=z(()=>{Fn(f=>Pb(f)),oi(""),_n(0),Ot()},[Ot]),wl=z(()=>{!rt||bt.length===0||_n(-1)},[bt.length,rt]),Ey=ue(()=>{if(!Ye)return null;if(Ye.tool==="exit_plan_mode"){let f=typeof Ye.input.plan=="string"?Ye.input.plan:void 0;return{prompt:Ye.prompt.split(`
365
- `,1)[0]??Ye.prompt,instruction:Vs,planContent:f}}return{prompt:Ye.prompt,instruction:Vs}},[Vs,Ye]),My=ue(()=>Pe?Pe.kind==="select"?{kind:"select",title:Pe.title,options:Pe.options,buffer:Pe.buffer,error:Pe.error,visibleSelectOptions:Ut.visibleSelectOptions,focusedIndex:Pe.focusedIndex,selectedIndices:Pe.selectedIndices,multiSelect:Pe.multiSelect}:{kind:"input",prompt:Pe.prompt,defaultValue:Pe.defaultValue,buffer:Pe.buffer,error:Pe.error}:null,[Pe,Ut.visibleSelectOptions]),AI=ue(()=>se(xg,{confirm:Ey,request:My}),[Ey,My]),Gf=ue(()=>{if(Qo)return se(QC,{text:Qo.text,tone:Qo.tone})},[Qo]),Kf=ue(()=>{if(Gf)return se(k,{flexDirection:"column",width:"100%",children:Gf})},[Gf]),Sl=z(()=>{Fn(f=>Mb(kb(f))),hf(!1),Dc(),oi(""),_n(0),Ot()},[Ot,Dc]),Ay=z(()=>{re&&hf(f=>!f)},[re]),_I=z(()=>{if(re){Sl();return}hf(!1),Fn(f=>Ib(f)),oi(""),_n(0),Ot()},[Ot,Sl,re]);He(()=>{Zh||!Be.selectedItemId||Fn(f=>Is(f,void 0))},[Zh,Be.selectedItemId]),He(()=>{if(!re||!li||!ey){Ks.current=void 0;return}if(ro||!ze||!tn)return;if(!Ks.current){Ks.current=ze;return}if(Ks.current===ze)return;Ks.current=ze;let f=Yg(tn);f&&Lo(f,{terminalWrite:P}).catch(()=>{})},[re,tn,ze,li,ey,ro,P]),He(()=>{if(T?.isTTY!==!0)return;let f=lu(T);f?.setShellMode?.(Gh,tl),Rf||f?.setAltScreenActive?.(!1)},[Gh,T,Rf,tl]);let Xe=me({...e,thinking:F.thinking,reasoningMode:F.reasoningMode,agentMode:F.agentMode,context:{...e.context,repoIntelligenceMode:F.repoIntelligenceMode,repoIntelligenceTrace:F.repoIntelligenceTrace,toolConstructionMode:!0},session:{...e.session,id:n.sessionId},guardrails:ih(F.permissionMode,l)}),mn=me(F.permissionMode);He(()=>{mn.current=F.permissionMode},[F.permissionMode]);let _y=me(rs()),Vf=me(F);He(()=>{Vf.current=F},[F]);let zf=me(null);zf.current===null&&(zf.current=Pl({getProvider:i(()=>po(Vf.current.provider),"getProvider"),getModel:i(()=>Vf.current.model??"","getModel")}));let Py=me(Su());He(()=>{F.permissionMode==="auto-in-project"&&Py.current()},[]);let Xf=z(f=>{_e(h=>({...h,permissionMode:f})),mn.current=f,Xe.current={...Xe.current,guardrails:ih(f,l)},Lf(qt(f)?l.getGuardrail().getEngine():void 0),f==="auto-in-project"&&Py.current()},[l]),$y=me(C.pendingInputs),Je=me(!1),ia=me(0),Tl=z(()=>{if(Os.current)return;let f=bf.current?.trim(),h=K.current.length>0?K.current[K.current.length-1]:void 0,S=h&&"text"in h&&typeof h.text=="string"?h.text.trim():void 0,E=ln.current.length>0?[...ln.current.map(N=>zo(N)),...f&&f!==S?[{type:"info",text:f}]:[]]:[...ln.current.map(N=>zo(N)),...eO(ee(),qe(),{toolCalls:Pt.current,toolNames:Un.current,infoItems:f&&f!==S?[f]:[]})];E.length!==0&&(Os.current=!0,Ls.current?.(E))},[qe,ee]);He(()=>{$y.current=C.pendingInputs},[C.pendingInputs]);let Ly=z(()=>{Je.current=!0,Se(),ve(),Y(),Q(),Re(),Ue(),Ce(void 0),Ar(),ut(void 0),Ws(),io.current=[],Zo.current=[],Bs([]),fe(!1)},[Se,Ue,Q,Re,Ar,Ws,Ce,Bs,fe,ut,ve,Y]),Cl=me(0),PI=500;sn(Nt.Critical,f=>{if(!V)return!1;switch(Kb({keyName:f.name,ctrl:!!f.ctrl,isTranscriptMode:re,isAwaitingUserInteraction:_r,isInputEmpty:pf,pendingInputCount:C.pendingInputs.length,hasTranscriptTextSelection:!!ro,timeSinceLastEscapeMs:Date.now()-Cl.current,doubleEscapeIntervalMs:PI}).kind){case"interrupt":return Cl.current=0,Tl(),Ly(),!0;case"pop-pending-input":return Ie(),Cl.current=0,!0;case"arm-double-escape":return Cl.current=Date.now(),!0;default:break}return!1},[V,re,_r,pf,C.pendingInputs.length,Ie,Tl,Ly]),sn(Nt.Critical,f=>{let h=jb({itemsLength:Rt.length,currentResponse:je.currentResponse,thinkingContent:je.thinkingContent,activeToolCallsLength:je.activeToolCalls.length}),S=Gb({keyName:f.name,hasTranscript:h,historyScrollOffset:kn,reviewPageSize:ea,reviewWheelStep:Sy,hasMouse:!!f.mouse,mouseButton:f.mouse?.button,mouseAction:f.mouse?.action,usesManagedMouseClicks:Kh,supportsMouseTracking:Be.supportsMouseTracking,usesRendererMouseTracking:tl,usesManagedMouseWheel:Vh,supportsWheelHistory:Be.supportsWheelHistory});if(S.kind==="mouse-phase"){let E=f.mouse;if(!E)return!1;S.phase==="press"&&Rn.current&&Ry(Rn.current);let N=ky(E.row,E.column);if(S.phase==="press"){if(!N||!h)return lr||ze?(Ff(),!0):(Ot(),!1);let B=jv({previous:kh.current,time:Date.now(),row:E.row,column:E.column});kh.current=B;let G=B.count>=3?"line":B.count===2?"word":"char";if(wl(),Fn(oe=>Is(oe,void 0)),re?Sf(void 0):wf(void 0),G!=="char"){let oe=zd(oa(),N.point,G);if(oe)return Rn.current={anchor:oe.start,focus:oe.end,didDrag:!1,mode:G,anchorSpan:oe},pi(oe.start,oe.end,{updateSelectedItem:!1}),!0}return Rn.current={anchor:N.point,focus:N.point,didDrag:!1,mode:"char"},!0}if(!Rn.current)return!1;if(S.phase==="drag"){let B=qo.current,G=B?xv(B,E.row):0;G!==0&&Oc(G);let oe=N??(B?Zg(B,E.row,E.column):void 0);if(!oe)return!1;let ye=Rn.current;if(ye.mode!=="char"&&ye.anchorSpan){let ct=zd(oa(),oe.point,ye.mode);if(!ct)return!1;let Dt=oh(ye.anchorSpan,ct);return Rn.current={...ye,anchor:Dt.anchor,focus:Dt.focus,didDrag:!0},pi(Dt.anchor,Dt.focus,{updateSelectedItem:!1}),!0}return Rn.current={...ye,focus:oe.point,didDrag:!0},pi(ye.anchor,oe.point,{updateSelectedItem:!1}),!0}if(S.phase==="release"){let B=Rn.current,G=B.focus,ye=(N??(qo.current?Zg(qo.current,E.row,E.column):void 0))?.point??G;if(B.mode!=="char"&&B.anchorSpan){let ct=zd(oa(),ye,B.mode);if(ct){let Dt=oh(B.anchorSpan,ct);B.anchor=Dt.anchor,ye=Dt.focus}}return Ry(B,{focusPoint:ye}),!0}}if(S.kind==="scroll-by")return wl(),Oc(S.delta),!0;if(S.kind==="consume")return!0;let R=Vb({key:f,isTranscriptMode:re,isHistorySearchActive:rt,historySearchMatchCount:bt.length,hasTextSelection:!!lr,hasFocusedItem:!!ze,canCopySelectedItem:li,canCopySelectedToolInput:ll,canToggleSelectedDetail:ul,canCycleTranscriptSelection:cl});return zb({action:R,hasTranscript:h,isTranscriptMode:re,pageScrollDelta:ea,disarmHistorySearchSelection:wl,scrollTranscriptBy:Oc,closeHistorySearchSurface:jf,backspaceHistorySearchQuery:i(()=>{oi(E=>E.slice(0,-1)),_n(0)},"backspaceHistorySearchQuery"),stepHistorySearchSelection:i(E=>{_n(N=>Xg(bt.length,N,E))},"stepHistorySearchSelection"),submitHistorySearchSelection:i(()=>{let E=bt[$r];E&&(Wf(E.itemId),jf())},"submitHistorySearchSelection"),appendHistorySearchQuery:i(E=>{oi(N=>N+E),_n(0)},"appendHistorySearchQuery"),openHistorySearchSurface:Uf,clearTranscriptSelectionFocus:Ff,exitTranscriptModeSurface:Sl,toggleTranscriptShowAll:Ay,scrollTranscriptHome:i(()=>{Lc(Math.max(0,ta-Ut.messageRows))},"scrollTranscriptHome"),scrollTranscriptToBottom:i(()=>{Dc(),Ot()},"scrollTranscriptToBottom"),cycleTranscriptSelection:Cy,copySelectedTranscriptText:i(()=>{xl()},"copySelectedTranscriptText"),copySelectedTranscriptItem:i(()=>{vy()},"copySelectedTranscriptItem"),copySelectedTranscriptToolInput:i(()=>{Iy()},"copySelectedTranscriptToolInput"),toggleSelectedTranscriptDetail:by,navigateSearchMatch:i(E=>{_n(N=>{let B=Xg(bt.length,N,E),G=bt[B];return G&&Wf(G.itemId),B})},"navigateSearchMatch"),dumpTranscriptToScrollback:i(()=>{Xb({items:Rt.filter(E=>!eg(E)),exitAltScreen:i(()=>{P(gu({mouseTracking:!0}))},"exitAltScreen"),writeToScrollback:i(E=>{P(E)},"writeToScrollback"),enterAltScreen:i(()=>{P(pu({mouseTracking:!0,clearOnEnter:!1}))},"enterAltScreen")})},"dumpTranscriptToScrollback")})},[re,Rt,je.currentResponse,je.thinkingContent,je.activeToolCalls,kn,ta,ea,Sy,ze,Ff,Sl,Ay,Be,Oc,Lc,Dc,cl,$r,Ot,xl,bt,Uf,jf,wl,Cy,li,vy,ll,Iy,ul,by,Wf,lr,ky,Be.supportsMouseTracking,ro,Kh,Vh,Ef,ii,tl,pi,Ut.messageRows]),sn(f=>{if(!Ye)return!1;let h=f.sequence.trim().toLowerCase(),S=!!Ye.input._alwaysConfirm,R=F.permissionMode==="accept-edits"&&!S,E=i(N=>{let B=`${te("dialog.confirm")} ${Ye.prompt}
366
- \u2192 ${te(`confirm.result.${N}`)}`;!!tt.current.workerId?dn({id:`confirm-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"info",text:B,timestamp:Date.now()}):I({type:"info",text:B})},"recordConfirmResult");return h==="y"||h==="yes"?(E("approved"),Qc(null),co.current?.({confirmed:!0}),co.current=null,!0):R&&(h==="a"||h==="always")?(E("approved_always"),Qc(null),co.current?.({confirmed:!0,always:!0}),co.current=null,!0):h==="n"||h==="no"||f.name==="escape"?(E("denied"),Qc(null),co.current?.({confirmed:!1}),co.current=null,!0):f.insertable||f.name==="return"},{isActive:!!Ye,priority:Nt.Critical});let bl=z(f=>{An(null),Jc.current?.(f),Jc.current=null},[]),gi=z((f,h,S)=>h.length===0?Promise.resolve(void 0):new Promise(R=>{Jc.current=R,An({kind:"select",title:f,options:h,buffer:"",focusedIndex:0,selectedIndices:[],multiSelect:S})}),[]),$I=z((f,h)=>gi(f,h.map(S=>({label:S,value:S}))),[gi]),Oy=z(async f=>{let h=f.options?Vd(f.options):[];return await gi(eh(f),h,f.multiSelect)??im},[gi]);He(()=>{let f=!1;return(async()=>{let{bindAskUserForConstruction:h}=await import("./construction-bootstrap-JR63KI5N.js");f||h(Oy)})(),()=>{f=!0,(async()=>{let{bindAskUserForConstruction:h}=await import("./construction-bootstrap-JR63KI5N.js");h(null)})()}},[Oy]);let Dy=z((f,h)=>new Promise(S=>{Jc.current=S,An({kind:"input",prompt:f,defaultValue:h,buffer:""})}),[]);sn(f=>{let h=Zc.current;if(!h)return!1;if(f.name==="escape")return bl(void 0),!0;if(h.kind==="select"){let S=h.options.length;if(f.name==="up"||f.sequence==="k")return An(R=>R&&R.kind==="select"?{...R,focusedIndex:(R.focusedIndex-1+S)%S,error:void 0}:R),!0;if(f.name==="down"||f.sequence==="j")return An(R=>R&&R.kind==="select"?{...R,focusedIndex:(R.focusedIndex+1)%S,error:void 0}:R),!0;if(f.sequence===" "&&h.multiSelect)return An(R=>{if(!R||R.kind!=="select")return R;let E=R.focusedIndex,N=R.selectedIndices.includes(E)?R.selectedIndices.filter(B=>B!==E):[...R.selectedIndices,E];return{...R,selectedIndices:N,error:void 0}}),!0;if(f.name==="return"){let R=Zc.current;if(!R||R.kind!=="select")return!1;if(R.multiSelect){if(R.selectedIndices.length===0)return An(N=>N&&N.kind==="select"?{...N,error:te("select.multiselect_empty")}:N),!0;let E=R.selectedIndices.sort((N,B)=>N-B).map(N=>R.options[N]?.value).filter(Boolean).join(", ");bl(E)}else bl(R.options[R.focusedIndex]?.value);return!0}if(/^[1-9]$/.test(f.sequence)){let R=Number.parseInt(f.sequence,10)-1;if(R>=0&&R<S)return h.multiSelect?An(E=>{if(!E||E.kind!=="select")return E;let N=E.selectedIndices.includes(R)?E.selectedIndices.filter(B=>B!==R):[...E.selectedIndices,R];return{...E,focusedIndex:R,selectedIndices:N,error:void 0}}):An(E=>E&&E.kind==="select"?{...E,focusedIndex:R,error:void 0}:E),!0}return!1}if(f.name==="return"){let S=Zc.current;if(!S||S.kind!=="input")return!1;let R=S.buffer.trim();return bl(R===""?S.defaultValue??void 0:R),!0}return f.name==="backspace"||f.name==="delete"?(An(S=>S&&S.kind==="input"?{...S,buffer:S.buffer.slice(0,-1),error:void 0}:S),!0):(f.insertable||f.isPasted===!0)&&!f.ctrl&&!f.meta?(An(S=>S&&S.kind==="input"?{...S,buffer:S.buffer+f.sequence,error:void 0}:S),!0):!1},{isActive:!!Pe,priority:Nt.Critical}),He(()=>{if(n.messages.length>0&&D.length===0){if(n.uiHistory?.length){let f=Xo(n.uiHistory);f.length!==n.uiHistory.length&&(n.uiHistory=f);for(let h of f)I({type:h.type,text:h.text,...h.icon?{icon:h.icon}:{},...h.compactText?{compactText:h.compactText}:{}});return}for(let f of n.messages){let h=Fa(f);for(let S of h)I(Ha(S))}}},[n.messages,n.uiHistory,D.length,I]),He(()=>{ho(n.gitRoot)},[n.gitRoot]),He(()=>{process.env.KODAX_PREWARM_REPO_INTELLIGENCE!=="0"&&cx({executionCwd:n.gitRoot??process.cwd(),gitRoot:n.gitRoot??void 0},{mode:F.repoIntelligenceMode})},[n.gitRoot,F.repoIntelligenceMode]);let Yf=z(()=>({onThinkingDelta:i(f=>{Je.current||(C.currentTool&&(Ce(void 0),Re()),ut(lh(nt.current?.activeWorkerTitle?`[${nt.current.activeWorkerTitle}] [Thinking]`:"[Thinking]",nt.current?.activeWorkerTitle)),De(f.length),ae(f),tt.current.workerId&&zc("thinking",f))},"onThinkingDelta"),onThinkingEnd:i(f=>{if(Je.current)return;let h=ee(),S=wb(h,f);S&&S!==h&&(Q(),ce(),De(S.length),ae(S)),tt.current.workerId&&Oh(S),Y()},"onThinkingEnd"),onTextDelta:i(f=>{Je.current||(C.currentTool&&(Ce(void 0),Re()),Y(),ut(void 0),xe(f),tt.current.workerId&&zc("assistant",f))},"onTextDelta"),onToolUseStart:i(f=>{if(Je.current)return;Un.current.includes(f.name)||(Un.current=[...Un.current,f.name]);let h=nt.current?.activeWorkerTitle?`[${nt.current.activeWorkerTitle}] `:"",S={id:f.id,name:`${h}${f.name}`,status:$.Executing,startTime:Date.now(),input:f.input};Dh(S),tt.current.workerId&&Mn(S),ut(Zr(S,nt.current?.activeWorkerTitle))},"onToolUseStart"),onToolInputDelta:i((f,h,S)=>{if(Je.current)return;be(h.length),at(h);let R=Nh(S?.toolId,f,E=>{let N=E.preview??"",B=q1(`${N}${h}`);return{...E,preview:B||void 0,input:E.input?B?{...E.input,preview:B}:{...E.input}:B?{preview:B}:void 0}});R&&(tt.current.workerId&&Mn(R),ut(Zr(R,nt.current?.activeWorkerTitle)))},"onToolInputDelta"),onToolResult:i(f=>{if(Je.current)return;let h=typeof f.content=="string"?f.content:String(f.content??""),S=Q1(h);if(/^\[(?:Tool Error|Error)\]/.test(h)){let E=Yc(f.id,$.Error,S,S,f.name);E&&(tt.current.workerId&&Mn(E),ut(Zr(E,nt.current?.activeWorkerTitle)));return}if(/^\[(?:Cancelled|Blocked)\]/.test(h)){let E=Yc(f.id,$.Cancelled,void 0,S,f.name);E&&(tt.current.workerId&&Mn(E),ut(Zr(E,nt.current?.activeWorkerTitle)));return}let R=Yc(f.id,$.Success,void 0,S||void 0,f.name);R&&(tt.current.workerId&&Mn(R),ut(Zr(R,nt.current?.activeWorkerTitle)))},"onToolResult"),onToolProgress:i(f=>{if(Je.current)return;let h=f.message.length>100?f.message.slice(0,97)+"...":f.message,S=ri(f.id,R=>({...R,preview:h,progressLines:[...(R.progressLines??[]).slice(-4),h]}));S&&tt.current.workerId&&Mn(S),ut(h)},"onToolProgress"),onStreamEnd:i(()=>{if(Je.current)return;let f=Us($.Cancelled,()=>({error:"Stream ended before the tool completed.",output:void 0})),h=f[f.length-1];tt.current.workerId&&f.forEach(S=>Mn(S)),h&&ut(Zr(h,nt.current?.activeWorkerTitle)),Y(),Re(),Ce(void 0)},"onStreamEnd"),hasPendingInputs:i(()=>$y.current.length>0,"hasPendingInputs"),onMidTurnUserMessages:i(f=>{if(!Je.current)for(let h of f){let S=h.trim();S&&(tt.current.workerId?dn({id:`mid-turn-user-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"user",text:S,timestamp:Date.now()}):I({type:"user",text:S}))}},"onMidTurnUserMessages"),onError:i(f=>{let h=Mr();h?.name&&ut(Zr(h,nt.current?.activeWorkerTitle));let S=Us($.Error,()=>({error:f.message,output:void 0})),R=S[S.length-1];tt.current.workerId&&S.forEach(ct=>Mn(ct)),R&&ut(Zr(R,nt.current?.activeWorkerTitle));let E=Ky(f),N=["Transient","Permanent","Tool Call ID","User Abort"];if(E.category===ua.USER_ABORT)return;let G=[`\u274C API Error (${N[E.category]||"Unknown"}): ${f.message}`];E.shouldCleanup&&G.push(" \u{1F9F9} Cleaned incomplete tool calls"),E.category===ua.PERMANENT?(G.push(" \u{1F4A1} This error requires manual intervention. Please check:"),f.message.includes("auth")||f.message.includes("401")?(G.push(" - Your API key is valid"),G.push(" - Run /config to check provider settings")):f.message.includes("400")?(G.push(" - The request parameters are correct"),G.push(" - Try restarting the conversation")):G.push(" - The error details above")):E.category===ua.TRANSIENT?G.push(" \u23F3 Retries exhausted. Press Enter to continue the conversation"):E.category===ua.TOOL_CALL_ID&&G.push(" \u2705 Session cleaned, ready to continue");let oe=G.join(`
367
- `);!!tt.current.workerId?dn({id:`error-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"error",text:oe,timestamp:Date.now()}):I({type:"error",text:oe})},"onError"),onRetry:i((f,h,S)=>{if(Je.current)return;if(!!tt.current.workerId){let E=$d(f,h,S);dn({...E,id:`retry-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,timestamp:Date.now()})}else Eg(I,f,h,S)},"onRetry"),onProviderRecovery:i(f=>{if(Je.current)return;let h=!!tt.current.workerId,S=qe().trim();if(S&&(h?zc("assistant",S):I({type:"assistant",text:S})),Ue(),Q(),Y(),Re(),Ce(void 0),Ar(),ut(void 0),h){let R=Ld(f);dn({...R,id:`recovery-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,timestamp:Date.now()})}else Mg(I,f)},"onProviderRecovery"),onManagedTaskStatus:i(f=>{if(Je.current)return;let h=tt.current;if(Yv(f)){if(h.workerId&&h.workerId!==f.activeWorkerId)SI({workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle});else if(h.workerId!==f.activeWorkerId){let B=dt.current,G=B.activeToolGroupTools.some(oe=>oe.status===$.Executing);dt.current={workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle,...G?{activeToolGroupItemId:B.activeToolGroupItemId,activeToolGroupTools:B.activeToolGroupTools}:{activeToolGroupTools:[]}},tt.current={workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle}}}nt.current=f,Cf(f);let S=Z1(f);TI(S);let R=gc(f),N=gc(f,{expanded:!0})??R;N&&(bf.current=N)},"onManagedTaskStatus"),onProviderRateLimit:i((f,h,S)=>{Je.current||ao({type:"info",icon:"\u23F3",text:`[Rate Limit] Retrying in ${S/1e3}s (${f}/${h})...`},"ratelimit")},"onProviderRateLimit"),onRetryAfter:i(f=>{if(Je.current)return;let h=Math.round(f.waitMs/1e3),S=f.source==="exponential-backoff"?"no-header \u2192 backoff":f.source,R=f.reason==="overloaded"?"Overloaded":"Rate limited";ao({type:"info",icon:"\u23F3",text:`[${R}] (${f.provider}) \u2014 retrying in ${h}s [${S}] (${f.attempt}/${f.maxAttempts})`},"ratelimit")},"onRetryAfter"),onRepoIntelligenceTrace:i(f=>{Je.current||ao(xb(f),"repointel-trace")},"onRepoIntelligenceTrace"),onTodoUpdate:i(f=>{Je.current||Rr(f)},"onTodoUpdate"),onScoutSuspiciousCompletion:i(f=>{Je.current||qd&&ao({type:"info",icon:"\u26A0",text:`[Scout] Completion marked uncertain \u2014 signals: ${f.signals.join(", ")}. Verify the result before continuing.`},"scout-uncertain")},"onScoutSuspiciousCompletion"),onIterationStart:i((f,h)=>{if(Je.current)return;if(h&&Ne(h),nt.current?.globalWorkBudget){let ye={...nt.current,budgetUsage:Math.min(nt.current.globalWorkBudget,(nt.current.budgetUsage??0)+1)};nt.current=ye,Cf(ye)}let S=f>1?ee().trim():"",R=f>1?uh(qe()):"",E=f>1?[...Un.current]:[],N=f>1?[...Pt.current]:[],B=!!tt.current.workerId;A(f),B&&Kc({clearOwner:!1});let G=ar.current.filter(ye=>ye.status===$.Executing),oe=new Set(G.map(ye=>ye.id));if(Un.current=[],Pt.current=Pt.current.filter(ye=>oe.has(ye.id)),un(G),Re(),Ce(void 0),ut(lh(nt.current?.activeWorkerTitle?`[Thinking] [${nt.current.activeWorkerTitle}]`:void 0,nt.current?.activeWorkerTitle)),ce(),f>1&&!B){let ye=dh({thinking:S,response:R,toolCalls:N,toolNames:E});if(Ls.current)Ls.current(ye);else for(let ct of ye)I(ct)}},"onIterationStart"),beforeToolExecute:i(async(f,h)=>{let S=mn.current,R=Mo(S),E=_y.current,N=n.gitRoot;if(Sx(X.current,f,h))return`[Skipped] Previously denied operation. ${Tx(X.current)}`;if(S==="plan"&&(Sn.has(f)||f==="undo"))return`[Blocked] Tool '${f}' is not allowed in plan mode (read-only). ${Kv}`;if(S==="plan"&&f==="bash"){let B=h.command??"";if(Ln(B))return`[Blocked] Bash write operation not allowed in plan mode: ${B.slice(0,50)}... ${Kv}`}if(f==="bash"){let B=h.command??"";if($n(B))return!0}if(qt(S)&&$f==="llm")return!0;if(f==="bash"){let B=h.command??"",G=xx(B);if(G.level==="dangerous"){let oe=await fo(f,{...h,_dangerousCommand:!0});return oe.confirmed?oe.confirmed:(X.current=am(X.current,f,h,G.reason),`[Blocked] Dangerous command requires confirmation: ${G.reason}`)}}if(N){let B=!1;if(Sn.has(f)){let G=h.path;G&&Jn(G,N)&&(B=!0)}if(f==="bash"){let G=h.command;G&&fp(G,N)&&(B=!0)}if(B){let G=await fo(f,{...h,_alwaysConfirm:!0});if(mn.current==="plan"&&(Sn.has(f)||f==="undo"))return!1;if(mn.current==="plan"&&f==="bash"){let oe=h.command??"";if(Ln(oe))return!1}return G.confirmed}}if(R.has(f)){if(S==="accept-edits"&&f==="bash"&&await Gr(f,h,E,zf.current??void 0))return!0;let B=await fo(f,h);if(mn.current==="plan"&&(Sn.has(f)||f==="undo"))return!1;if(mn.current==="plan"&&f==="bash"){let G=h.command??"";if(Ln(G))return!1}if(!B.confirmed)return I({type:"info",text:te("cancelled")}),X.current=am(X.current,f,h),!1;B.always&&S==="accept-edits"&&(_u(f,h,!1),_y.current=rs())}return!0},"beforeToolExecute"),askUser:i(async f=>{let h=f.options?Vd(f.options):[],S=await gi(eh(f),h,f.multiSelect);return S===void 0?im:S},"askUser"),exitPlanMode:i(async f=>mn.current!=="plan"?"not-in-plan-mode":(await fo("exit_plan_mode",{plan:f})).confirmed?(Xf("accept-edits"),!0):!1,"exitPlanMode"),askUserMulti:i(async f=>{let h=f.questions,S={},R="__back__",E=0;for(;E<h.length;){let N=h[E],B=Vd(N.options);E>0&&B.push({label:te("select.back_prev"),value:R});let G=`[${E+1}/${h.length}] ${N.question}`,oe=await gi(G,B,N.multiSelect);if(oe===void 0)return;if(oe===R){E--;continue}S[N.question]=oe,E++}return S},"askUserMulti"),askUserInput:i(async f=>Dy(f.question,f.default),"askUserInput"),onCompactStart:i(()=>{W()},"onCompactStart"),onCompactStats:i(f=>{$s.current=f.tokensBefore,Hn(f.tokensAfter)},"onCompactStats"),onCompactedMessages:i((f,h)=>{n.messages=f,h?.artifactLedger&&h.artifactLedger.length>0&&(n.artifactLedger=da(n.artifactLedger??[],h.artifactLedger)),n.lineage=h?.anchor?rx(n.lineage,f,h.anchor,h.postCompactAttachments??[]):hn(f,n.lineage);let S=go(f);n.contextTokenSnapshot={currentTokens:S,baselineEstimatedTokens:S,source:"estimate"},rr(n),Hn(S),Ac.current?.().catch(()=>{})},"onCompactedMessages"),onCompact:i(f=>{J();let h=$s.current??f;$s.current=null;let S=Math.round(h/1e3);ao({type:"info",icon:"\u2728",text:`Context auto-compacted (was ~${S}k tokens)`},"compact")},"onCompact"),onCompactEnd:i(()=>{$s.current=null,J()},"onCompactEnd"),onIterationEnd:i(f=>{f.scope!=="worker"&&(n.contextTokenSnapshot=f.contextTokenSnapshot),Hn(f.tokenCount)},"onIterationEnd")}),[De,ae,Y,xe,Ce,be,at,Re,A,ce,F,n,W,J,I,Q,ee,qe,Kc,ut,zc,Oh,Mn,Dh,Nh,Yc,Us,Mr,Ar,un,C.currentTool]),fo=i((f,h)=>{let S=sb(f,h);return new Promise(R=>{co.current=R,Qc({tool:f,input:h,prompt:S})})},"showConfirmDialog");He(()=>(d(async(f,h,S)=>(await fo(f.name,{...f.input,_reason:`[auto-mode] ${h}`,...S&&S.length>0?{_classifierSignals:S}:{}})).confirmed?"allow":"block"),m(f=>{Lf(f)}),()=>{d(null),m(null)}),[]),He(()=>{p(F)},[F,p]);let sa=i(async(f,h,S=n.lineage?Et(n.lineage,n.lineage.activeEntryId):n.messages,R)=>{let E={...Yf(),getCostReport:L},B=mr(n.gitRoot).getSystemPromptSnippet(),G=Sb(f.context,n.gitRoot,n.contextTokenSnapshot,B);R&&R.length>0&&(G.inputArtifacts=[...R]),G.planModeBlockCheck=(oe,ye)=>mn.current!=="plan"?null:Tr(oe,ye,n.gitRoot??process.cwd());try{return await ma({...f,session:{...f.session,initialMessages:S},context:G,events:E,abortSignal:kt()},h)}finally{dx()}},"runAgentRound"),fr=z(f=>{let h=hn([...f],n.lineage);return n.lineage=h,h},[n]),aa=z(async f=>{if(n.messages.length===0)return;let h=ns(n.messages),S=Xo(f??q.current);q.current=S,n.title=h,n.uiHistory=S;let R=n.lineage??fr(n.messages);n.lineage=R;let E={messages:n.messages,title:h,gitRoot:n.gitRoot??"",uiHistory:S,lineage:R,artifactLedger:n.artifactLedger};"appendSessionDelta"in r&&typeof r.appendSessionDelta=="function"?await r.appendSessionDelta(n.sessionId,E):await r.save(n.sessionId,E),Wd()&&Ud("persist",jd(n.messages,R,{historyItems:K.current,foregroundItems:ln.current,streamingResponse:Z.current.currentResponse,streamingThinking:Z.current.thinkingContent,persistedUiHistory:q.current}))},[n,fr,r]),qf=z(()=>{if(_c.current)return _c.current;let f=(async()=>{try{for(;no.current.requested;){no.current.requested=!1;let h=no.current.uiHistoryOverride;no.current.uiHistoryOverride=void 0,await aa(h)}}finally{_c.current=null,no.current.requested&&qf()}})();return _c.current=f,Ih.current=f,f},[aa]),hi=z(f=>{if(f!==void 0){let h=Xo(f);q.current=h,no.current.uiHistoryOverride=h}return no.current.requested=!0,qf()},[qf]),LI=z(async()=>{if(Ds.current)return Ds.current;let f=(async()=>{Je.current=!0,Se(),ve(),Y(),Q(),Re(),Ue(),Ce(void 0),fe(!1),await Ih.current.catch(()=>{}),await Ac.current?.().catch(()=>{}),_s(!1),O&&w?.isRaw&&v(!1),w?.pause?.(),w?.unref?.(),y(),a()})();return Ds.current=f.finally(()=>{Ds.current=null}),Ds.current},[Se,Ue,Q,Re,y,O,a,Ce,fe,v,w,ve,Y]);He(()=>(Ac.current=hi,()=>{Ac.current=null}),[hi]);let Ny=z(f=>{if(f.length===0)return;let h=Xd(q.current,f);q.current=h,hi(h)},[hi]),ca=z(f=>{if(f.length!==0){for(let h of f)I(h);Ny(f)}},[I,Ny]),vl=z(f=>{if(f.length!==0){for(let h of f)I(h);q.current=Xd(q.current,f)}},[I]);He(()=>(Ls.current=ca,()=>{Ls.current=null}),[ca]);let By=z(async f=>{n.messages=f.messages,n.contextTokenSnapshot=f.contextTokenSnapshot,fr(f.messages);let h=f.success===!1&&!f.interrupted,S=ee().trim(),R=zS(f.messages,qe(),f.managedTask?.verdict.summary,f.lastText),E=[...ln.current],N=E.length>0,B=N&&E.some(ge=>ge.type==="assistant"&&"text"in ge&&Po(String(ge.text??"")).length>0),G=!h&&R&&!B,oe=[...Zo.current],ye=h?[]:oe.length===0?qd?Vv(f):Vv(f).filter(ge=>!Zv(ge)):[],ct=N?[]:dh({thinking:S,response:void 0,toolCalls:Pt.current,toolNames:Un.current}),Dt=[...E.map(ge=>zo(ge)),...ct,...h?[]:oe.map(ge=>zo(ge)),...ye.map(ge=>zv(ge)),...G?[{type:"assistant",text:f.interrupted?`${R}
368
-
369
- [Interrupted]`:R}]:!R&&!B&&!f.interrupted&&!h?[{type:"info",text:"[No response text was produced for this round]"}]:[]],la=Xd(q.current,Dt);Q(),Ue();for(let ge of E)I(zo(ge));for(let ge of ct)I(ge);if(!h){for(let ge of ye)I(zv(ge));for(let ge of oe)I(zo(ge))}G?I({type:"assistant",text:f.interrupted?`${R}
370
-
371
- [Interrupted]`:R}):!R&&!B&&!f.interrupted&&!h&&I({type:"info",text:"[No response text was produced for this round]"}),Un.current=[],Pt.current=[],Ar(),Re(),Ce(void 0),ut(void 0),Ws(),io.current=[],Zo.current=[],Bs([]),_(),hi(la).catch(()=>{})},[I,_,Re,Ue,Q,n,qe,ee,hi,fr,Ar,Ws,Ce,ut,C.currentIteration]),Il=z(async f=>{let h=f.trim();h&&(I({type:"user",text:h}),Mc(S=>S+1),rr(n))},[I,n]),kl=z(async(f,h)=>{let S=ia.current;Je.current=!1,Os.current=!1,Ps(!0);try{return await Wb({initialPrompt:f,runRound:h,shiftPendingPrompt:Le,onRoundComplete:i(async R=>{ia.current===S&&await By(R)},"onRoundComplete"),onBeforeQueuedRound:i(async R=>{Je.current=!1,Os.current=!1,await Il(R)},"onBeforeQueuedRound"),shouldContinue:i(R=>!Je.current&&R.success!==!1,"shouldContinue")})}finally{Ps(!1)}},[By,Le,Il]),Qf=z(async()=>{let f=Le();if(!f||!f.trim())return;let h=f.trim();await Il(h),await kl(h,async S=>sa(Xe.current,S))},[sa,kl,Le,Il]),Jf=z(f=>{let h=f[f.length-1];if(h?.role!=="assistant")return;let S=Fa(h);for(let R of S)I(Ha(R))},[I]),Hy=z(async(f,h)=>{let S=await Hd({...Xe.current,provider:F.provider,thinking:F.thinking,reasoningMode:F.reasoningMode},f,h,R=>I({type:"info",text:R}));if(S.mode==="manual"){S.manualOutput&&I({type:"info",text:S.manualOutput}),await S.finalize();return}if(!S.prompt||!S.options){await S.finalize();return}Ps(!0);try{let R=S.mode==="fork"?[]:n.lineage?Et(n.lineage,n.lineage.activeEntryId):n.messages,E=ia.current,N=await sa(S.options,S.prompt,R);if(ia.current!==E)await S.finalize();else{let B=q.current,G=[];if(S.mode==="fork"){let oe=N.messages.find(ct=>ct.role==="user");oe&&n.messages.push(oe);let ye=N.messages.slice().reverse().find(ct=>ct.role==="assistant");if(ye){n.messages.push({role:"assistant",content:ye.content}),fr(n.messages);for(let ct of Fa(ye)){let Dt=Ha(ct);I(Dt),G.push(Dt)}}}else{n.messages=N.messages,n.contextTokenSnapshot=N.contextTokenSnapshot,fr(N.messages),Jf(N.messages);let oe=N.messages[N.messages.length-1];if(oe?.role==="assistant")for(let ye of Fa(oe))G.push(Ha(ye))}await aa(Xd(B,G)),Wd()&&Ud("round-end",jd(n.messages,n.lineage,{historyItems:K.current,foregroundItems:ln.current,streamingResponse:Z.current.currentResponse,streamingThinking:Z.current.thinkingContent,persistedUiHistory:q.current})),await S.finalize()}}catch(R){let E=R instanceof Error?R:new Error(String(R));throw await S.finalize(E),Ps(!1),E}Ps(!1),await Qf()},[I,Jf,n,F.provider,F.thinking,Qf,aa,fr,sa]),OI=z(async f=>{for(let h of f.pastedContents)if(h.type==="text"&&!h.content&&h.contentHash)try{let S=await Hu(h.contentHash);S&&(h.content=S)}catch{}},[]),DI=z(async f=>{let{displayText:h,fullText:S,pastedContents:R}=f;if(!S.trim()||!kr||Ye||Pe)return;for(let ge of R){if(ge.type!=="text"||ge.content.length<1024)continue;let Ae=lT(ge.content);uT(Ae,ge.content)}if(Hh(!1),V){if(!mf)return;if(C.pendingInputs.length>=5){ao({type:"info",icon:"\u23F3",text:`Queued follow-up limit reached (${5}). Wait for the next round or press Esc to remove the latest item.`},"queue-limit");return}if(Fb(S)){ao({type:"info",icon:"\u26A0",text:Bb},Hb);return}let ge=C.currentTool;if(ge&&_l(ge)?.interruptBehavior==="cancel"){et(S),Se({preservePendingInputs:!0}),$c(""),Pc(!0),Mc(nn=>nn+1),rr(n);return}et(S),$c(""),Pc(!0),Mc(Ae=>Ae+1),rr(n);return}let E=uh(qe()),N=ln.current.map(ge=>zo(ge)),B=N.length>0;N.length>0&&vl(N),!B&&E&&vl([{type:"assistant",text:E+`
372
-
373
- [Interrupted]`}]),vl([{type:"user",text:h}]),$c(""),Pc(!0),Mc(ge=>ge+1),Wd()&&Ud("turn-start",jd(n.messages,n.lineage,{historyItems:K.current,foregroundItems:ln.current,streamingResponse:Z.current.currentResponse,streamingThinking:Z.current.thinkingContent,persistedUiHistory:q.current})),fe(!0),Je.current=!1,Os.current=!1,++ia.current,Cf(null),nt.current=null,bf.current=null,ut(void 0),Ws(),io.current=[],Zo.current=[],Bs([]),Gs(),Uc(void 0),Un.current=[],Pt.current=[],Ar(),Ue(),Re(),Ce(void 0),_(),ke(),rr(n),await new Promise(ge=>setTimeout(ge,50));let G=as(S.trim());if(G){let ge={exit:LI,saveSession:i(async()=>{if(n.messages.length>0){let H=ns(n.messages);n.title=H;let le=n.lineage??fr(n.messages);n.lineage=le,await r.save(n.sessionId,{messages:n.messages,title:H,gitRoot:n.gitRoot??"",uiHistory:q.current,lineage:le,artifactLedger:n.artifactLedger})}},"saveSession"),startNewSession:i(()=>{let H=dc(),le=new Date().toISOString();n.sessionId=H,n.title="",n.uiHistory=[],n.contextTokenSnapshot=void 0,n.lineage=void 0,n.artifactLedger=void 0,q.current=[],n.createdAt=le,n.lastAccessed=le,Xe.current.session={...Xe.current.session,id:H},Hn(null),ie(),Rr([]),Bu()?.reset(),Te(H),x?.writer.update({sessionId:H})},"startNewSession"),loadSession:i(async H=>{let le=await r.load(H);return le?Go(F,"Resuming a saved session",Yd)?(n.messages=le.messages,n.uiHistory=ks(le.uiHistory),n.lineage=le.lineage,n.artifactLedger=le.artifactLedger,n.title=le.title,n.sessionId=H,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[],Hn(null),ie(),Rr([]),Te(H),x?.writer.update({sessionId:H}),console.log(Ke.green(`[Session loaded: ${H}]`)),"loaded"):"blocked":"missing"},"loadSession"),listSessions:i(async()=>{let H=await r.list(n.gitRoot??void 0);if(H.length===0){console.log(Ke.dim(`
374
- [No saved sessions]`));return}console.log(Ke.bold(`
375
- Recent Sessions:
376
- `));for(let le of H.slice(0,10))console.log(` ${Ke.cyan(le.id)} ${Ke.dim(`(${le.msgCount} messages)`)} ${le.title.slice(0,40)}`);console.log()},"listSessions"),clearHistory:i(()=>{n.uiHistory=[],ie(),Rr([])},"clearHistory"),printHistory:i(()=>{if(n.messages.length===0){console.log(Ke.dim(`
377
- [No conversation history]`));return}console.log(Ke.bold(`
378
- Conversation History:
379
- `));let H=n.messages.slice(-20);for(let le=0;le<H.length;le++){let Me=H[le],yi=Ke.cyan(Me.role.padEnd(10)),Uy=Wa(Me.content),WI=Uy.slice(0,60).replace(/\n/g," "),UI=Uy.length>60?"...":"";console.log(` ${(le+1).toString().padStart(2)}. ${yi} ${WI}${UI}`)}console.log()},"printHistory"),switchProvider:i((H,le)=>{_e(Me=>({...Me,provider:H,model:le})),Xe.current.provider=H,Xe.current.model=le},"switchProvider"),setThinking:i(H=>{let le=H?"auto":"off";_e(Me=>({...Me,thinking:H,reasoningMode:le})),Xe.current.thinking=H,Xe.current.reasoningMode=le},"setThinking"),setReasoningMode:i(H=>{let le=H!=="off";_e(Me=>({...Me,thinking:le,reasoningMode:H})),Xe.current.thinking=le,Xe.current.reasoningMode=H},"setReasoningMode"),setAgentMode:i(H=>{_e(le=>({...le,agentMode:H})),Xe.current.agentMode=H},"setAgentMode"),setPermissionMode:i(H=>{Xf(H)},"setPermissionMode"),setRepoIntelligenceRuntime:i(H=>{_e(le=>({...le,...H.mode!==void 0?{repoIntelligenceMode:H.mode}:{},...H.endpoint!==void 0?{repointelEndpoint:H.endpoint??void 0}:{},...H.bin!==void 0?{repointelBin:H.bin??void 0}:{},...H.trace!==void 0?{repoIntelligenceTrace:H.trace}:{}})),H.mode!==void 0&&(process.env.KODAX_REPO_INTELLIGENCE_MODE=H.mode,Xe.current.context={...Xe.current.context,repoIntelligenceMode:H.mode}),H.trace!==void 0&&(H.trace?process.env.KODAX_REPO_INTELLIGENCE_TRACE="1":delete process.env.KODAX_REPO_INTELLIGENCE_TRACE,Xe.current.context={...Xe.current.context,repoIntelligenceTrace:H.trace}),H.endpoint!==void 0&&(H.endpoint?process.env.KODAX_REPOINTEL_ENDPOINT=H.endpoint:delete process.env.KODAX_REPOINTEL_ENDPOINT),H.bin!==void 0&&(H.bin?process.env.KODAX_REPOINTEL_BIN=H.bin:delete process.env.KODAX_REPOINTEL_BIN)},"setRepoIntelligenceRuntime"),deleteSession:i(async H=>{await r.delete?.(H)},"deleteSession"),deleteAllSessions:i(async()=>{await r.deleteAll?.(n.gitRoot??void 0)},"deleteAllSessions"),printSessionTree:i(async()=>{let H=await r.getLineage?.(n.sessionId);if(!H){console.log(Ke.dim(`
380
- [No session tree available for this session]`));return}let le=Dd(Ml(H));console.log(Ke.bold(`
381
- Session Tree:
382
- `)),le.forEach(Me=>console.log(` ${Me}`)),console.log()},"printSessionTree"),switchSessionBranch:i(async H=>{if(!Go(F,"Switching session branches",Yd))return"blocked";let Me=await r.setActiveEntry?.(n.sessionId,H,{summarizeCurrentBranch:!0});return Me?(n.messages=Me.messages,n.uiHistory=ks(Me.uiHistory),n.title=Me.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[],Hn(null),ie(),Rr([]),console.log(Ke.green(`
383
- [Switched to tree entry: ${H}]`)),console.log(Ke.dim(` Messages: ${Me.messages.length}`)),"switched"):"missing"},"switchSessionBranch"),labelSessionBranch:i(async(H,le)=>{if(!await r.setLabel?.(n.sessionId,H,le))return!1;let yi=le&&le.trim()?`checkpoint label set: ${le.trim()}`:"checkpoint label cleared";return console.log(Ke.green(`
384
- [${yi}]`)),!0},"labelSessionBranch"),forkSession:i(async H=>{if(!Go(F,"Forking a session branch",Yd))return"blocked";let Me=await r.fork?.(n.sessionId,H);if(!Me)return"failed";n.sessionId=Me.sessionId,n.messages=Me.data.messages,n.uiHistory=ks(Me.data.uiHistory),n.title=Me.data.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[];let yi=new Date().toISOString();return n.createdAt=yi,n.lastAccessed=yi,Xe.current.session={...Xe.current.session,id:Me.sessionId},Hn(null),ie(),Rr([]),Te(Me.sessionId),x?.writer.update({sessionId:Me.sessionId}),console.log(Ke.green(`
385
- [Forked session: ${Me.sessionId}]`)),console.log(Ke.dim(` Messages: ${Me.data.messages.length}`)),"forked"},"forkSession"),rewindSession:i(async H=>{if(!Go(F,"Rewinding session",Yd))return"blocked";let Me=await r.rewind?.(n.sessionId,H);return Me?(n.messages=Me.messages,n.uiHistory=ks(Me.uiHistory),n.title=Me.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[],Hn(null),ie(),Rr([]),console.log(Ke.green(`
386
- [Rewound session${H?` to ${H}`:" to previous turn"}]`)),console.log(Ke.dim(` Messages: ${Me.messages.length}`)),"rewound"):"failed"},"rewindSession"),getCostReport:i(()=>L.current?.()??null,"getCostReport"),getAutoModeStats:i(()=>{if(qt(mn.current))return l.getGuardrail().getStats()},"getAutoModeStats"),setAutoModeEngine:i(H=>{qt(mn.current)&&(l.getGuardrail().setEngine(H),Lf(H))},"setAutoModeEngine"),createKodaXOptions:i(()=>({...Xe.current,provider:F.provider,model:F.model,thinking:F.thinking,reasoningMode:F.reasoningMode,agentMode:F.agentMode,guardrails:ih(mn.current,l),events:Yf()}),"createKodaXOptions"),reloadAgentsFiles:i(async()=>{let H=await sm({cwd:process.cwd(),projectRoot:n.gitRoot??void 0});return g(H),H},"reloadAgentsFiles"),startCompacting:i(()=>{W()},"startCompacting"),stopCompacting:i(()=>{J()},"stopCompacting"),onCompactStats:i(H=>{$s.current=H.tokensBefore,Hn(H.tokensAfter)},"onCompactStats"),confirm:i(async H=>(await fo("confirm",{_alwaysConfirm:!0,_message:H})).confirmed,"confirm"),ui:{select:i(async(H,le)=>$I(H,le),"select"),confirm:i(async H=>(await fo("confirm",{_alwaysConfirm:!0,_message:H})).confirmed,"confirm"),input:i(async(H,le)=>Dy(H,le),"input")}},Ae=[],nn=console.log;console.log=(...H)=>{let le=H.map(Me=>typeof Me=="string"?Me:String(Me)).join(" ");Ae.push(le)};let pn;try{let H=await cs(G,n,ge,F);typeof H=="object"&&H!==null&&"invocation"in H&&(pn=H.invocation)}finally{console.log=nn}if(Ae.length>0&&I({type:"info",text:Ae.join(`
387
- `)}),pn){fe(!1),ve(),fe(!0),ke(),ce();try{await Hy(pn,S.trim())}catch(H){let le=H instanceof Error?H:new Error(String(H)),Me=le.name==="AbortError"||le.message.includes("aborted")||le.message.includes("ABORTED");console.log=nn,Me?Tl():ca([{type:"error",text:le.message}])}finally{fe(!1),ve(),Q()}return}fe(!1),ve();return}let oe=await Rg(S.trim());if(S.trim().startsWith("!")&&mc(oe)){fe(!1),ve();return}let ye=Xe.current.context?.executionCwd??process.cwd(),ct=i(ge=>{ge.length!==0&&ca(ge.map(Ae=>({type:"info",text:Ae})))},"emitArtifactWarnings");ce();let Dt=[],la=console.log;console.log=(...ge)=>{let Ae=ge.map(nn=>typeof nn=="string"?nn:String(nn)).join(" ");Dt.push(Ae)};try{await kl(oe,async ge=>{let Ae=pc(ge,Xe.current.context?.executionCwd??process.cwd());return ct(Ae.warnings),sa(Xe.current,Ae.promptText,n.messages,Ae.inputArtifacts)})}catch(ge){let Ae=ge instanceof Error?ge:new Error(String(ge));if(Ae.name==="AbortError"||Ae.message.includes("aborted")||Ae.message.includes("ABORTED"))console.log=la,Tl();else{let pn=Ae.message;Ae.message.includes("rate limit")||Ae.message.includes("Rate limit")?pn=`[Rate Limit] ${Ae.message}
388
- Suggestion: Wait a moment and try again, or switch provider with /mode`:Ae.message.includes("API key")||Ae.message.includes("not configured")?pn=`[Configuration Error] ${Ae.message}
389
- Suggestion: Set the required API key environment variable`:Ae.message.includes("network")||Ae.message.includes("ECONNREFUSED")||Ae.message.includes("ETIMEDOUT")?pn=`[Network Error] ${Ae.message}
390
- Suggestion: Check your internet connection`:(Ae.message.includes("token")||Ae.message.includes("context too long"))&&(pn=`[Context Error] ${Ae.message}
391
- Suggestion: Use /clear to start fresh`),console.log=la,tt.current.workerId?dn({id:`error-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"error",text:pn,timestamp:Date.now()}):ca([{type:"error",text:pn}])}}finally{if(console.log=la,Dt.length>0){let Ae=Dt.filter((nn,pn,H)=>H.indexOf(nn)===pn);I({type:"info",text:Ae.join(`
392
- `)})}if(!Je.current){let Ae=Us($.Cancelled,()=>({error:"Run ended before the tool result was observed.",output:void 0}));Ae.length>0&&tt.current.workerId&&Ae.forEach(nn=>Mn(nn))}fe(!1),ve(),Ue(),Q();let ge=go(n.messages);n.contextTokenSnapshot={currentTokens:ge,baselineEstimatedTokens:ge,source:"estimate"},Hn(ge)}},[kr,n,F,mf,C.pendingInputs.length,r,Ye,Pe,y,a,I,ie,ke,ve,Ue,Yf,Hy,kt,qe,ee,vl,Jf,aa,fr,kl,Qf,W,J,Ar,Us,Mn,Gs]),NI=se(Td,{left:se(wd,{items:cy}),right:se(Sd,{items:ly}),queued:se(Sg,{pendingInputs:C.pendingInputs}),stashNotice:se(Rd,{text:pl}),notifications:se(kd,{notifications:ml}),inlineNotices:Hf.length>0?se(Tg,{notices:Hf}):void 0,activityBar:Or||V&&ur.shouldRender?Gt(k,{paddingX:1,flexDirection:"row",children:[Gt(k,{flexGrow:1,children:[Or?.showSpinner?se(vn,{color:ne("dark").colors.accent}):null,Or?Gt(b,{color:Or.kind==="waiting"?ne("dark").colors.warning:ne("dark").colors.accent,children:[Or.showSpinner?" ":"",Or.text]}):null,Or?.showSpinner&&C.roundStartedAt!=null?se(HT,{roundStartedAt:C.roundStartedAt,charCount:C.currentResponse.length,theme:ne("dark")}):null]}),V&&ur.shouldRender?se(b,{dimColor:!0,children:`${ur.completedCount}/${ur.totalCount} completed`}):null]}):void 0,todoSurface:V&&ur.shouldRender?se(k,{paddingX:1,children:se(JC,{viewModel:ur})}):void 0,composer:se(ug,{onSubmit:DI,onHistoryRecall:OI,onPopPendingInputs:i(()=>{let f=Kt();if(f.length!==0)return f.join(`
393
- ---
394
- `)},"onPopPendingInputs"),prompt:">",placeholder:wv({isLoading:V,canQueueFollowUps:mf,waitingReason:Of}),focus:!Ye&&!Pe&&!rt,cwd:process.cwd(),gitRoot:e.context?.gitRoot||n.gitRoot,onInputChange:bI}),inlineSuggestions:EI,helpSurface:Bh?se(fg,{sections:Gd()}):void 0,taskBar:Js?se(Ed,{items:ci.backgroundTask.items,overflowLabel:ci.backgroundTask.overflowLabel,ctaHint:ci.backgroundTask.ctaHint,showSpinner:V}):void 0,statusLine:se(k,{children:se(gs,{...dl,viewModel:sy})}),inlineDialogs:AI}),BI=se(Td,{left:se(wd,{items:cy}),right:se(Sd,{items:ly}),stashNotice:se(Rd,{text:pl}),notifications:se(kd,{notifications:ml}),composer:se(XC,{searchActive:rt,selectionActive:!!(lr||ze),showAllActive:Ct,searchQuery:Ft,searchCurrent:bt.length>0?$r+1:0,searchCount:bt.length,searchDetailText:Pf,pendingLiveUpdates:zs,secondaryText:kI}),taskBar:Js?se(Ed,{items:ci.backgroundTask.items,overflowLabel:ci.backgroundTask.overflowLabel,ctaHint:ci.backgroundTask.ctaHint,showSpinner:ot}):void 0,statusLine:se(k,{children:se(gs,{...dl,viewModel:Nf})})}),Zf=z(f=>se(YC,{banner:f?.bannerVisible?se(ah,{...lo}):void 0,items:Ys,isLoading:Wt,viewportRows:Ut.messageRows,viewportWidth:M,scrollOffset:kn,windowed:!!f?.rendererWindow,rendererWindow:f?.rendererWindow,transcriptModel:f?.rendererWindow?qs:ol,maxLines:gt,selectedTextRanges:Ef?Hc?.rowRanges:void 0,onMetricsChange:hl,onVisibleRowsChange:yl}),[lo,Ys,Wt,hl,yl,kn,ol,M,gt,Hc?.rowRanges,Ut.messageRows,Ef]),em=z(f=>se(qC,{banner:f?.bannerVisible?se(ah,{...lo}):void 0,items:Xs,browse:{hintText:Lr.browseHintText},selection:gl,search:ry,isLoading:ot,isThinking:pe.isThinking,thinkingCharCount:pe.thinkingCharCount,thinkingContent:pe.thinkingContent,streamingResponse:pe.currentResponse,currentTool:pe.currentTool,activeToolCalls:pe.activeToolCalls,toolInputCharCount:pe.toolInputCharCount,toolInputContent:pe.toolInputContent,iterationHistory:pe.iterationHistory,currentIteration:pe.currentIteration,isCompacting:pe.isCompacting,agentMode:F.agentMode,managedPhase:ot?U?.phase:void 0,managedHarnessProfile:ot?U?.harnessProfile:void 0,managedWorkerTitle:ot?U?.activeWorkerTitle:void 0,managedRound:ot?U?.currentRound:void 0,managedMaxRounds:ot?U?.maxRounds:void 0,managedGlobalWorkBudget:ot?U?.globalWorkBudget:void 0,managedBudgetUsage:ot?U?.budgetUsage:void 0,managedBudgetApprovalRequired:ot?U?.budgetApprovalRequired:void 0,lastLiveActivityLabel:pe.lastLiveActivityLabel,viewportRows:Ut.messageRows,viewportWidth:M,scrollOffset:kn,windowed:!!f?.windowed,animateSpinners:!!f?.rendererWindow&&ui,rendererWindow:f?.rendererWindow,transcriptModel:f?.rendererWindow?qs:il,maxLines:gt,showDetailedTools:Ct,showAllContent:Ct,selectedItemId:fn.selectionEnabled?ze:void 0,selectedTextRanges:ro?.rowRanges,expandedItemKeys:fn.selectionEnabled?en:void 0,onMetricsChange:hl,onVisibleRowsChange:yl}),[lo,F.agentMode,ot,en,s.transcriptSpinnerAnimation,hl,yl,kn,zh,U?.activeWorkerTitle,U?.budgetApprovalRequired,U?.budgetUsage,U?.currentRound,U?.globalWorkBudget,U?.harnessProfile,U?.maxRounds,U?.phase,qs,il,Lr.browseHintText,ze,gl,M,ui,Xs,gt,pe.activeToolCalls,pe.currentIteration,pe.currentResponse,pe.currentTool,pe.isCompacting,pe.isThinking,pe.iterationHistory,pe.lastLiveActivityLabel,pe.thinkingCharCount,pe.thinkingContent,pe.toolInputCharCount,pe.toolInputContent,ro?.rowRanges,ry,Ct,Ut.messageRows]),HI=re?em({bannerVisible:!1,windowed:ht}):Zf({bannerVisible:!1}),Fy=re?BI:NI,FI=s.enabled&&ii,Wy=Gt(k,{flexDirection:"column",width:M,flexShrink:0,flexGrow:FI?1:0,children:[se(Ng,{currentConfig:F,setCurrentConfig:_e,isLoading:V,abort:Se,stopThinking:Y,clearThinkingContent:Q,setCurrentTool:Ce,setIsLoading:fe,onToggleHelp:CI,setShowHelp:Hh,onSetThinking:i(f=>{Xe.current.thinking=f},"onSetThinking"),onSetReasoningMode:i(f=>{Xe.current.reasoningMode=f,Xe.current.thinking=f!=="off"},"onSetReasoningMode"),onToggleTranscriptMode:_I,onOpenTranscriptSearch:Uf,canOpenTranscriptSearch:re&&!Ye&&!Pe,isInteractiveDialogActive:!!(Ye||Pe),onSetAgentMode:i(f=>{Xe.current.agentMode=f},"onSetAgentMode"),onSetPermissionMode:i(f=>{Xf(f)},"onSetPermissionMode"),isInputEmpty:pf,onSavePermissionMode:Ga}),Bn&&(s.enabled?null:se(Yi,{items:[1],children:i(()=>se(ah,{...lo},"banner"),"children")})),ii?se(sg,{width:M,stickyHeader:Lr.stickyHeader,jumpToLatest:Lr.jumpToLatest,transcript:!s.enabled||!ht?re?em({bannerVisible:!1}):Zf({bannerVisible:!1}):void 0,renderTranscriptWindow:s.enabled&&ht?f=>(()=>{let S=na(f).contentWindow;return re?em({bannerVisible:!1,windowed:!0,rendererWindow:S}):Zf({bannerVisible:!1,rendererWindow:S})})():void 0,overlay:Kf,scrollTop:kn,scrollHeight:ta,viewportHeight:Ut.messageRows,stickyScroll:!re&&!_r&&yf,scrollRef:uI,onWindowChange:MI,onScrollTopChange:fI,onStickyChange:mI,footer:Fy}):Gt(K1,{children:[Gt(k,{flexDirection:"column",flexGrow:1,children:[HI,Kf?se(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:Kf}):null]}),Fy]})]});return Rf?se(Km,{mouseTracking:Pr.usesRendererMouseTracking,children:Wy}):Wy},"InkREPLInner"),oO=i(e=>{let t=process.cwd(),n=e.options?.context?.gitRoot??void 0;return se(bd,{children:se(Md,{children:se(wu,{children:se(Og,{children:se(Bp,{cwd:t,gitRoot:n,children:se(rO,{...e})})})})})})},"InkREPL");function iO(){return process.stdin.isTTY===!0&&typeof process.stdin.setRawMode=="function"}i(iO,"isRawModeSupported");async function fh(e){if(!iO())throw new rm("Interactive mode requires a TTY with raw mode support.",['kodax -p "your task" # Run a single task',"kodax -c # Continue last session","kodax -r # Resume session"]);let t=e.storage??new Ss,n=To(),r=Co(),o=bo(n,r),{prepareRuntimeConfig:s,getGitRoot:a}=await import("./utils-HQ2QCKJA.js"),{loadCompactionConfig:c}=await import("./compaction-config-3E57ABCT.js"),{resolveProvider:l}=await import("./dist-KWHUKXEL.js"),d=s(),m=e.provider??d.provider??Rl,p=e.model??d.model,g=V1(e,d),x=e.agentMode??d.agentMode??"ama",y=g!=="off",T=Qn(d.permissionMode,"accept-edits")??"accept-edits",w=Al(),v=d.repoIntelligenceTrace===!0,O={provider:m,model:p,thinking:y,reasoningMode:g,agentMode:x,permissionMode:T,repoIntelligenceMode:w.mode,repointelEndpoint:w.endpoint,repointelBin:w.bin,repoIntelligenceTrace:v},P=e.session?.id,D=[],L,X,I,ie="",Te=await a().catch(()=>null)??void 0,K=El({meta:{cwd:process.cwd(),startedAt:Date.now()}});if(K){let ae=i(()=>{K.shutdown()},"teamModeCleanup");process.on("exit",ae),process.on("SIGTERM",ae)}try{let{bootstrapConstructionRuntime:ae}=await import("./construction-bootstrap-JR63KI5N.js"),Y=await ae(Te??process.cwd());if(Y.loaded>0||Y.failed>0||Y.tampered>0){let Q=Y.failed>0?`; ${Y.failed} failed (see warnings above)`:"",Ce=Y.tampered>0?`; ${Y.tampered} skipped due to manifest contentHash mismatch \u2014 re-stage and re-activate to re-approve`:"";console.log(Ke.dim(`[Constructed] Rehydrated ${Y.loaded} active tool(s)${Q}${Ce}.`))}if(Y.markdownLoaded>0||Y.markdownFailures.length>0){console.log(Ke.dim(`[Agents] Loaded ${Y.markdownLoaded} markdown agent(s).`));for(let Q of Y.markdownFailures)console.warn(Ke.yellow(`[Agents] Skipped ${Q.path}: ${Q.reason}`))}}catch(ae){console.warn(Ke.yellow(`[Constructed] Bootstrap failed: ${ae.message}. Self-construction disabled this session.`))}let q;try{let ae=await c(Te),Y=l(m);q={contextWindow:ae.contextWindow??Y.getContextWindow?.()??2e5,triggerPercent:ae.triggerPercent,enabled:ae.enabled,userOverrideContextWindow:ae.contextWindow}}catch{}if(e.session?.id&&!e.session.resume){let ae=await t.load(e.session.id);ae&&(D=ae.messages,L=ks(ae.uiHistory),X=ae.lineage,I=ae.artifactLedger,ie=ae.title,P=e.session.id,console.log(Ke.green(`[Session loaded: ${e.session.id}]`)))}else if(e.session?.resume||e.session?.autoResume){let ae=await t.list(Te);if(ae.length>0){let Y=ae[0];if(Y){let Q=await t.load(Y.id);Q&&(D=Q.messages,L=ks(Q.uiHistory),X=Q.lineage,I=Q.artifactLedger,ie=Q.title,P=Y.id,console.log(Ke.green(`[Continuing session: ${Y.id}]`)))}}}let M=await uc({sessionId:P,gitRoot:Te,existingMessages:D,existingUiHistory:L,existingLineage:X,existingArtifactLedger:I});M.title=ie,K?.writer.update({sessionId:M.sessionId});let Z={current:await sm({cwd:process.cwd(),projectRoot:Te??void 0})},ke={current:null},ve={current:null},Se={current:O},ce=Au(),De=await fc({askUser:i(async(ae,Y,Q)=>{let Ce=ke.current;return Ce?Ce(ae,Y,Q):"block"},"askUser"),projectRoot:Te??process.cwd(),getAgentsFiles:i(()=>Z.current,"getAgentsFiles"),getCurrentProviderName:i(()=>Se.current.provider,"getCurrentProviderName"),getCurrentModel:i(()=>Se.current.model,"getCurrentModel"),getCurrentPermissionMode:i(()=>Se.current.permissionMode,"getCurrentPermissionMode"),autoModeSettings:ce,log:i((ae,Y)=>{ae==="warn"?console.warn(Ke.yellow(Y)):console.log(Ke.dim(Y))},"log"),onEngineChange:i(ae=>{ve.current?.(ae)},"onEngineChange"),extraCollectors:[Da]});try{let ae=process.stdout,Y=process.stdin;import("./paste-5DSTHQGK.js").then(Re=>Re.prunePasteTmpDir()).catch(()=>{});let Q=!1,{waitUntilExit:Ce,cleanup:be}=fu(se(oO,{options:e,config:O,context:M,storage:t,compactionInfo:q,rendererMode:r,fullscreenPolicy:o,autoModeBootstrap:De,setAutoModeAskUser:i(Re=>{ke.current=Re},"setAutoModeAskUser"),setAutoModeEngineChange:i(Re=>{ve.current=Re},"setAutoModeEngineChange"),setCurrentConfigRef:i(Re=>{Se.current=Re},"setCurrentConfigRef"),onAgentsFilesReload:i(Re=>{Z.current=Re},"onAgentsFilesReload"),teamModeHandle:K,onExit:i(()=>{Q=!0},"onExit")}),{stdout:ae,stdin:Y,exitOnCtrlC:!1,patchConsole:!1,maxFps:30,shellMode:o.enabled?o.promptShell:"main-screen"});await Ce(),be(),K?.shutdown(),Y.isTTY===!0&&typeof Y.setRawMode=="function"&&Y.isRaw&&Y.setRawMode(!1),Y.pause?.(),Y.unref?.(),Q&&console.log(Ke.dim(`
395
- [Exiting KodaX...]`));let at=e.hardExitOnClose??process.env.VITEST!=="true";if(Q&&at){let Re=process.exitCode??0,Ue=!1,xe=i(()=>{Ue||(Ue=!0,process.exit(Re))},"requestProcessExit");setTimeout(xe,0).unref?.(),ae.write("",xe);return}}catch(ae){throw ae instanceof Error&&ae.message.includes("Raw mode")?new rm("Interactive mode failed to start.",['kodax -p "your task" # Run a single task',"kodax -c # Continue last session"]):ae}}i(fh,"runInkInteractiveMode");import cn from"chalk";var n0=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r0=["\x1B[36m","\x1B[35m","\x1B[34m"],xc=null,Rs=!1;function yc(){let e=0,t=0,n=!1,r="Thinking...",o=i(()=>{if(n)return;let c=r0[t%r0.length],l="\x1B[0m",d=n0[e%n0.length];process.stdout.write(`\r${c}${d}${l} ${r}`)},"renderFrame"),s=setInterval(()=>{e++,e%10===0&&t++,o()},80);o();let a={stop:i(()=>{n||(n=!0,clearInterval(s),process.stdout.write("\r\x1B[K"))},"stop"),isStopped:i(()=>n,"isStopped"),updateText:i(c=>{r=c},"updateText")};return xc=a,a}i(yc,"startWaitingDots");function sO(e=!0){let t=null,n=0,r=!1;return{onSessionStart:i(s=>{console.log(e?cn.cyan(`[KodaX] Provider: ${s.provider} | Session: ${s.sessionId}`):cn.cyan(`[KodaX] Provider: ${s.provider}`))},"onSessionStart"),onTextDelta:i(s=>{t&&(t.stop(),t=null),n=0,process.stdout.write(s),r=!0},"onTextDelta"),onThinkingDelta:i(s=>{n+=s.length,t||(t=yc()),t.updateText(`Thinking... (${n} chars)`)},"onThinkingDelta"),onThinkingEnd:i(s=>{if(t&&(t.stop(),t=null),s){let a=s.replace(/\n/g," "),c=a.length>100?a.slice(0,100)+"...":a;console.log(cn.dim(`[Thinking] ${c}`))}},"onThinkingEnd"),onToolUseStart:i(s=>{t||(Rs||(process.stdout.write(`
396
- `),Rs=!0),t=yc()),t.updateText(`Executing ${s.name}...`)},"onToolUseStart"),onToolInputDelta:i((s,a,c)=>{let l=a.length;t&&!t.isStopped()?t.updateText(`Receiving ${s}... (${l} chars)`):(!t||t.isStopped())&&(Rs||(process.stdout.write(`
397
- `),Rs=!0,r=!1),t=yc(),t.updateText(`Receiving ${s}... (${l} chars)`))},"onToolInputDelta"),onToolResult:i(s=>{t&&(t.stop(),t=null),console.log(cn.green(`[Result] ${s.content.slice(0,300)}${s.content.length>300?"...":""}`))},"onToolResult"),onRepoIntelligenceTrace:i(s=>{t&&(t.stop(),t=null),console.log(cn.dim(`[RepoIntel] ${s.summary}`))},"onRepoIntelligenceTrace"),onStreamEnd:i(()=>{xc&&!xc.isStopped()&&xc.stop(),xc=null,Rs=!1,r&&(console.log(),r=!1),(!t||t.isStopped())&&(t=yc(),t.updateText("Processing..."))},"onStreamEnd"),onIterationStart:i((s,a)=>{t&&!t.isStopped()&&t.stop(),Rs=!1,r=!1,console.log(cn.magenta(`
398
- [Assistant]`)),t=yc()},"onIterationStart"),onCompactStart:i(()=>{console.log(cn.dim(`
399
- [KodaX] Compacting context...`))},"onCompactStart"),onCompact:i(s=>{console.log(cn.dim(`[KodaX] Compaction finished (${s} tokens).`))},"onCompact"),onCompactEnd:i(()=>{},"onCompactEnd"),onRetry:i((s,a,c)=>{console.log(cn.yellow(`[KodaX] Retry ${a}/${c}: ${s}`))},"onRetry"),onProviderRecovery:i(s=>{let a=s.recoveryAction==="non_streaming_fallback"?"switching to non-streaming fallback":s.recoveryAction==="manual_continue"?"awaiting manual continue":`recovering ${s.attempt}/${s.maxAttempts}`;console.log(cn.yellow(`[KodaX] ${a} (${s.errorClass}, ${s.stage})`))},"onProviderRecovery"),onComplete:i(()=>{t&&(t.stop(),t=null),console.log(cn.green(`
400
- [KodaX] Done!`))},"onComplete"),onError:i(s=>{t&&(t.stop(),t=null),console.log(cn.red(`
401
- [Error] ${s.message}`))},"onError"),onScoutSuspiciousCompletion:i(s=>{console.log(cn.yellow(`
402
- [Scout] Completion marked uncertain \u2014 signals: ${s.signals.join(", ")}. Verify the result before continuing.`))},"onScoutSuspiciousCompletion"),beforeToolExecute:i(async(s,a)=>!0,"beforeToolExecute")}}i(sO,"createCliEvents");function st(e,t){e.write(`${JSON.stringify(t)}
403
- `)}i(st,"writeJsonLine");function aO(e){return{type:"error",name:e.name,message:e.message,stack:e.stack}}i(aO,"serializeError");function cO(e={}){let t=e.stdout??process.stdout,n=e.stderr??process.stderr;return{onSessionStart:i(r=>{st(t,{type:"session.start",provider:r.provider,sessionId:r.sessionId})},"onSessionStart"),onIterationStart:i((r,o)=>{st(t,{type:"iteration.start",iter:r,maxIter:o})},"onIterationStart"),onIterationEnd:i(r=>{st(t,{type:"iteration.end",iter:r.iter,maxIter:r.maxIter,tokenCount:r.tokenCount,tokenSource:r.tokenSource,usage:r.usage,contextTokenSnapshot:r.contextTokenSnapshot})},"onIterationEnd"),onTextDelta:i(r=>{st(t,{type:"text.delta",text:r})},"onTextDelta"),onThinkingDelta:i(r=>{st(t,{type:"thinking.delta",text:r})},"onThinkingDelta"),onThinkingEnd:i(r=>{st(t,{type:"thinking.end",thinking:r})},"onThinkingEnd"),onToolUseStart:i(r=>{st(t,{type:"tool.start",id:r.id,name:r.name,input:r.input})},"onToolUseStart"),onToolInputDelta:i((r,o,s)=>{st(t,{type:"tool.input.delta",toolName:r,partialJson:o,toolId:s?.toolId})},"onToolInputDelta"),onToolResult:i(r=>{st(t,{type:"tool.result",id:r.id,name:r.name,content:r.content})},"onToolResult"),onStreamEnd:i(()=>{st(t,{type:"stream.end"})},"onStreamEnd"),onCompactStart:i(()=>{st(t,{type:"compact.start"})},"onCompactStart"),onCompact:i(r=>{st(t,{type:"compact.finish",estimatedTokens:r})},"onCompact"),onCompactStats:i(r=>{st(t,{type:"compact.stats",tokensBefore:r.tokensBefore,tokensAfter:r.tokensAfter})},"onCompactStats"),onCompactEnd:i(()=>{st(t,{type:"compact.end"})},"onCompactEnd"),onRetry:i((r,o,s)=>{st(t,{type:"retry",reason:r,attempt:o,maxAttempts:s})},"onRetry"),onProviderRecovery:i(r=>{st(t,{type:"provider.recovery",stage:r.stage,reasonCode:r.errorClass,attempt:r.attempt,maxAttempts:r.maxAttempts,delayMs:r.delayMs,nextAt:Date.now()+r.delayMs,recoveryAction:r.recoveryAction,fallbackUsed:r.fallbackUsed})},"onProviderRecovery"),onProviderRateLimit:i((r,o,s)=>{st(t,{type:"provider.rate_limit",attempt:r,maxRetries:o,delayMs:s})},"onProviderRateLimit"),onRepoIntelligenceTrace:i(r=>{st(t,{type:"repo_intelligence.trace",stage:r.stage,summary:r.summary,capability:r.capability,trace:r.trace})},"onRepoIntelligenceTrace"),onToolProgress:i(r=>{st(t,{type:"tool.progress",id:r.id,message:r.message})},"onToolProgress"),onManagedTaskStatus:i(r=>{st(t,{type:"managed_task.status",agentMode:r.agentMode,harnessProfile:r.harnessProfile,phase:r.phase,activeWorkerId:r.activeWorkerId,activeWorkerTitle:r.activeWorkerTitle,childFanoutClass:r.childFanoutClass,childFanoutCount:r.childFanoutCount,currentRound:r.currentRound,maxRounds:r.maxRounds,note:r.note,detailNote:r.detailNote,globalWorkBudget:r.globalWorkBudget,budgetUsage:r.budgetUsage,budgetApprovalRequired:r.budgetApprovalRequired})},"onManagedTaskStatus"),onScoutSuspiciousCompletion:i(r=>{st(t,{type:"scout.suspicious_completion",confidence:r.confidence,signals:r.signals,sessionId:r.sessionId,lastTextPreview:r.lastTextPreview})},"onScoutSuspiciousCompletion"),onComplete:i(()=>{st(t,{type:"complete"})},"onComplete"),onError:i(r=>{st(n,aO(r))},"onError")}}i(cO,"createJsonEvents");import{jsx as lt,jsxs as Jt}from"react/jsx-runtime";import mO,{useMemo as wc}from"react";var mh=/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@.*$/,o0=/^---\s+(.+)$/;function i0(e){if(!e)return[];let t=e.split(`
404
- `),n=[],r=[],o=[],s=!1,a=null,c=null,l=0,d=0,m=i(()=>{if(r.length===0)return;let g=r.join(`
405
- `);g.length>0&&n.push({kind:"text",text:g}),r=[]},"flushText"),p=i(()=>{o.length!==0&&(n.push({kind:"diff",text:o.join(`
406
- `),addedLines:l,removedLines:d,filePath:c}),o=[],l=0,d=0,c=null)},"flushDiff");for(let g=0;g<t.length;g++){let x=t[g];if(!s){let w=o0.exec(x);if(w){let v=Math.min(g+3,t.length-1),O=!1;for(let P=g+1;P<=v;P++)if(t[P]?.startsWith("+++ ")||mh.test(t[P]??"")){O=!0;break}if(O){m(),s=!0,a=w[1]??null,c=a,o.push(x);continue}}if(mh.test(x)){m(),s=!0,o.push(x);continue}r.push(x);continue}let y=o0.exec(x);if(y){let w=Math.min(g+3,t.length-1),v=!1;for(let O=g+1;O<=w;O++)if(t[O]?.startsWith("+++ ")||mh.test(t[O]??"")){v=!0;break}if(v){p(),c=y[1]??null,o.push(x);continue}}let T=x[0];if(T==="+"||T==="-"||T===" "||T==="@"||x===""){T==="+"&&!x.startsWith("+++ ")&&l++,T==="-"&&!x.startsWith("--- ")&&d++,o.push(x);continue}p(),s=!1,a=null,r.push(x)}return p(),m(),n}i(i0,"parseUnifiedDiff");function s0(e){return e?/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/m.test(e):!1}i(s0,"containsUnifiedDiff");import{jsxs as Es,jsx as lO}from"react/jsx-runtime";import uO from"react";function dO(e){return e.startsWith("+++ ")?{text:e,kind:"file-header"}:e.startsWith("--- ")?{text:e,kind:"file-header"}:e.startsWith("@@ ")?{text:e,kind:"hunk-header"}:e.startsWith("+")?{text:e,kind:"add"}:e.startsWith("-")?{text:e,kind:"remove"}:{text:e,kind:"context"}}i(dO,"classifyLine");function fO(e,t){switch(e){case"add":return t.colors.success;case"remove":return t.colors.error;case"hunk-header":case"file-header":return t.colors.dim;default:return}}i(fO,"colorFor");var ph=uO.memo(({text:e,addedLines:t,removedLines:n,filePath:r,theme:o,maxLines:s=16,extremeThreshold:a=200})=>{let c=o??ne("dark"),l=e.split(`
407
- `),d=l.map(dO),m=`(${t>0?`+${t}`:"\xB10"} ${n>0?`-${n}`:""})`.trim();if(l.length>a)return Es(k,{flexDirection:"column",marginLeft:4,children:[r&&Es(b,{dimColor:!0,children:[r," ",m]}),Es(b,{dimColor:!0,children:["[diff too large to render inline \u2014 ",l.length," lines, ",t,"+ / ",n,"-]"]})]});let p,g=0;if(l.length>s){let x=Math.floor(s/2),y=d.slice(0,x),T=d.slice(-x);g=l.length-y.length-T.length,p=[...y,{text:"",kind:"context"},...T]}else p=d;return Es(k,{flexDirection:"column",marginLeft:4,children:[r&&Es(b,{dimColor:!0,children:[r," ",m]}),p.map((x,y)=>{if(y===Math.floor(s/2)&&g>0&&x.kind==="context"&&x.text==="")return Es(b,{dimColor:!0,children:["... ",g," lines collapsed ..."]},`collapse-${y}`);let w=fO(x.kind,c);return lO(b,{color:w,children:x.text||" "},y)})]})});ph.displayName="DiffHunk";function a0(e){switch(e){case $.Scheduled:return"\u25CB";case $.Validating:return"\u25D0";case $.AwaitingApproval:return"\u23F8";case $.Executing:return"\u25CF";case $.Success:return"\u2713";case $.Error:return"\u2717";case $.Cancelled:return"\u2298";default:return"?"}}i(a0,"getStatusIcon");function c0(e,t){switch(e){case $.Scheduled:case $.Validating:return t.colors.dim;case $.AwaitingApproval:return t.colors.accent;case $.Executing:return t.colors.primary;case $.Success:return t.colors.success??t.colors.primary;case $.Error:return t.colors.error;case $.Cancelled:return t.colors.dim;default:return t.colors.text}}i(c0,"getStatusColor");function pO(e,t){if(!t)return"";let n=t-e;return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}i(pO,"formatDuration");function gO(e){if(!e)return"";let t=JSON.stringify(e);return t.length<=50?t:t.slice(0,47)+"..."}i(gO,"formatInputSummary");var hO=i(({status:e,theme:t})=>{let n=t??wc(()=>ne("dark"),[]),r=a0(e),o=c0(e,n);return lt(b,{color:o,children:r})},"ToolStatusBadge"),l0=i(({progress:e,width:t=20,theme:n})=>{let r=n??wc(()=>ne("dark"),[]),o=Math.max(0,Math.min(100,e)),s=Math.round(o/100*t),a=t-s,c="\u2588".repeat(s),l="\u2591".repeat(a);return Jt(k,{children:[lt(b,{color:r.colors.primary,children:c}),lt(b,{dimColor:!0,children:l}),Jt(b,{children:[" ",o,"%"]})]})},"ToolProgressBar"),u0=i(({tool:e,collapsed:t=!1,theme:n})=>{let r=n??wc(()=>ne("dark"),[]),o=a0(e.status),s=c0(e.status,r),a=gO(e.input),c=pO(e.startTime,e.endTime);return t?Jt(k,{children:[Jt(b,{color:s,children:[o," "]}),lt(b,{color:r.colors.text,children:e.name})]}):Jt(k,{flexDirection:"column",marginLeft:2,children:[Jt(k,{children:[Jt(b,{color:s,children:[o," "]}),lt(b,{color:r.colors.text,bold:!0,children:e.name}),a&&Jt(b,{dimColor:!0,children:[" ",a]})]}),e.progress!==void 0&&e.status===$.Executing&&lt(k,{marginLeft:2,children:lt(l0,{progress:e.progress,theme:r})}),e.progressLines&&e.progressLines.length>0&&e.status===$.Executing&&lt(k,{flexDirection:"column",marginLeft:2,children:e.progressLines.slice(-5).map((l,d)=>lt(b,{dimColor:!0,children:l},d))}),e.error&&lt(k,{marginLeft:2,children:lt(b,{color:r.colors.error,children:e.error})}),e.status===$.Success&&typeof e.output=="string"&&e.output.length>0&&lt(d0,{output:e.output,theme:r}),c&&e.status!==$.Executing&&lt(k,{marginLeft:2,children:Jt(b,{dimColor:!0,children:["Completed in ",c]})})]})},"ToolCallDisplay"),d0=mO.memo(({output:e,theme:t})=>{if(!s0(e))return lt(k,{marginLeft:2,children:lt(b,{dimColor:!0,children:e})});let n=i0(e);return lt(k,{flexDirection:"column",marginLeft:2,children:n.map((r,o)=>r.kind==="text"?lt(b,{dimColor:!0,children:r.text},o):lt(ph,{text:r.text,addedLines:r.addedLines,removedLines:r.removedLines,filePath:r.filePath,theme:t},o))})});d0.displayName="ToolOutputBlock";var yO=i(({tools:e,collapsed:t=!1,title:n,theme:r})=>{let o=r??wc(()=>ne("dark"),[]);if(e.length===0)return null;let s=wc(()=>{let c={[$.Scheduled]:0,[$.Validating]:0,[$.AwaitingApproval]:0,[$.Executing]:0,[$.Success]:0,[$.Error]:0,[$.Cancelled]:0};for(let l of e)c[l.status]++;return c},[e]),a=n??"Tools";if(t){let c=s[$.Success],l=s[$.Error],d=s[$.Executing]+s[$.Scheduled]+s[$.Validating];return lt(k,{flexDirection:"column",marginBottom:1,children:Jt(k,{children:[lt(b,{color:o.colors.accent,bold:!0,children:a}),Jt(b,{dimColor:!0,children:[" ","(",e.length," tools",c>0&&`, ${c} succeeded`,l>0&&`, ${l} failed`,d>0&&`, ${d} running`,")"]})]})})}return Jt(k,{flexDirection:"column",marginBottom:1,children:[Jt(k,{children:[lt(b,{color:o.colors.accent,bold:!0,children:a}),Jt(b,{dimColor:!0,children:[" ","(",e.length," ",e.length===1?"tool":"tools",")"]})]}),e.map(c=>lt(u0,{tool:c,theme:o},c.id))]})},"ToolGroup");import{jsxs as f0,jsx as xO}from"react/jsx-runtime";var wO=i(({pendingInputs:e})=>{let t=_C(e);if(!t)return null;let n=ne("dark");return f0(k,{children:[f0(b,{color:n.colors.hint,children:["\u23F3"," "]}),xO(b,{color:n.colors.dim,children:t})]})},"PendingInputsIndicator");import*as m0 from"child_process";var Sc;function SO(){if(process.platform!=="win32")return null;if(Sc!==void 0)return Sc;try{Sc=m0.execFileSync(process.env.ComSpec??"cmd.exe",["/d","/s","/c","chcp"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).match(/(\d{3,5})/)?.[1]??null}catch{Sc=null}return Sc}i(SO,"detectWindowsCodePage");function Qd(){let e=process.env;return!!(e.COLORTERM==="truecolor"||e.COLORTERM==="24bit"||e.TERM_PROGRAM==="iTerm.app"||e.WT_SESSION||e.TERM==="xterm-kitty"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="gnome-terminal")}i(Qd,"supportsTrueColor");function p0(){if(Qd())return!0;let e=process.env.TERM||"";return e.includes("256color")||e==="xterm-256color"||e==="screen-256color"||e==="tmux-256color"}i(p0,"supports256Colors");function Ir(){let e=process.env,t=e.LC_ALL||"",n=e.LC_CTYPE||"",r=e.LANG||"";if(t==="C"||t==="POSIX"||n==="C"||n==="POSIX"||r==="C"||r==="POSIX")return!1;let o=`${t}|${n}|${r}`.toLowerCase();return o.includes("utf-8")||o.includes("utf8")?!0:process.platform==="win32"?e.WT_SESSION||e.TERM_PROGRAM==="vscode"?!0:SO()==="65001":!0}i(Ir,"supportsUnicode");function g0(){let e=process.env;return!!(e.TERM_PROGRAM==="iTerm.app"||e.WT_SESSION||e.TERM==="xterm-kitty"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="Apple_Terminal"||e.TERM_PROGRAM==="gnome-terminal"||e.COLORTERM)}i(g0,"supportsEmoji");function h0(){if(process.stdout?.columns)return process.stdout.columns;let t=process.env.COLUMNS;if(t){let n=Number.parseInt(t,10);if(!Number.isNaN(n)&&n>0)return n}return 80}i(h0,"getTerminalWidth");function y0(){let e=process.env;return!!(e.NO_COLOR||e.TERM==="dumb"||e.CI)}i(y0,"isScreenReader");function TO(){return process.stdout?.isTTY??!1}i(TO,"isTTY");function CO(){return{trueColor:Qd(),colors256:p0(),unicode:Ir(),emoji:g0(),tty:TO(),columns:h0(),screenReader:y0()}}i(CO,"detectTerminalCapabilities");var Tc=class{static{i(this,"ConsoleCapturer")}captured=[];originalLog=null;start(){this.captured=[],this.originalLog=console.log,console.log=(...t)=>{let n=t.map(r=>typeof r=="string"?r:String(r)).join(" ");this.captured.push(n)}}stop(){return this.originalLog!==null&&(console.log=this.originalLog,this.originalLog=null),this.captured}getCaptured(){return[...this.captured]}clear(){this.captured=[]}};async function bO(e){let t=new Tc;t.start();try{let n=await e(),r=t.stop();return{result:n,captured:r}}finally{t.stop()}}i(bO,"withCapture");function vO(e){let t=new Tc;t.start();try{let n=e(),r=t.stop();return{result:n,captured:r}}finally{t.stop()}}i(vO,"withCaptureSync");import*as I0 from"readline";import*as k0 from"child_process";import*as kc from"path";import*as Ic from"fs";import*as R0 from"os";import j from"chalk";import Dn from"chalk";var IO=[{key:"y",label:"Yes",description:"Confirm the action",value:"yes"},{key:"n",label:"No",description:"Cancel the action",value:"no"}],kO=[{key:"y",label:"Yes",description:"Allow this once",value:"yes"},{key:"n",label:"No",description:"Cancel",value:"no"},{key:"a",label:"Always",description:"Always allow this kind of action",value:"always"}];function RO(e,t=!0){return e.map(n=>{let r=Dn.dim(`[${n.key}]`);return t?`${r} ${Dn.cyan(n.label)} ${Dn.dim(`- ${n.description}`)}`:`${r} ${n.label}`}).join(" ")}i(RO,"formatOptions");function Ms(){return process.stdout.columns??80}i(Ms,"getTerminalWidth");function EO(){return Ir()}i(EO,"supportsUnicode");function MO(){let e=EO();return{success:e?"\u2713":"[OK]",error:e?"\u2717":"[X]",warning:e?"\u26A0":"[!]",info:e?"\u2139":"[i]",arrow:e?"\u2192":"->",bullet:e?"\u2022":"*",check:e?"\u2713":"[v]",cross:e?"\u2717":"[x]"}}i(MO,"getSymbols");async function AO(e,t){let{message:n,default:r,options:o,showDescription:s=!0}=t,a=o??IO,c=RO(a,s);console.log(),console.log(Dn.cyan(`? ${n}`));let l=Ms();if(c.length>l-4)for(let d of a){let m=Dn.dim(` [${d.key}]`);console.log(`${m} ${Dn.cyan(d.label)}`),s&&console.log(Dn.dim(` ${d.description}`))}else console.log(Dn.dim(` ${c}`));return new Promise(d=>{let m=r?` (${r})`:"";e.question(Dn.dim(` Choose${m}: `),p=>{let g=p.trim().toLowerCase()||r||"",x=a.find(y=>y.key===g||y.value===g||y.label.toLowerCase()===g);d(x?x.value:g===""?"no":g)})})}i(AO,"confirmEnhanced");async function Cc(e,t,n,r){let{isOutsideProject:o=!1,isProtectedPath:s=!1,permissionMode:a="accept-edits"}=r??{},c=MO(),l,d,m={...n,...o?{_outsideProject:!0}:{},...s?{_alwaysConfirm:!0}:{}},p=Nd(t,m),g=p.details.map(y=>` ${Dn.dim(y)}`);o||s?(l=`${Dn.yellow(c.warning)} Safety Warning`,g.length>0&&(l+=`
408
- ${g.join(`
409
- `)}`),d=[{key:"y",label:"Yes",description:"Allow this once",value:"yes"},{key:"n",label:"No",description:"Cancel",value:"no"}]):(l=p.title,g.length>0&&(l+=`
410
- ${g.join(`
411
- `)}`),d=a==="accept-edits"?kO:[{key:"y",label:"Yes",description:"Confirm the action",value:"yes"},{key:"n",label:"No",description:"Cancel",value:"no"}]);let x=await AO(e,{message:l,default:"n",options:d});return x==="always"?{confirmed:!0,always:!0}:{confirmed:x==="yes"}}i(Cc,"confirmToolExecution");import Zt from"chalk";var Jd=/\x1b\[[0-9;]*m/g,sr={SAVE_CURSOR:"\x1B[s",RESTORE_CURSOR:"\x1B[u",MOVE_TO_BOTTOM:"\x1B[999;1H",CLEAR_LINE:"\x1B[2K",RESET:"\x1B[0m",REVERSE:"\x1B[7m"};function _O(e,t){if(t<=0)return"";let n="",r=0,o=0;for(;o<e.length&&r<t;){Jd.lastIndex=o;let s=Jd.exec(e);if(s&&s.index===o){n+=s[0],o+=s[0].length;continue}n+=e[o],r+=1,o+=1}return n}i(_O,"truncateAnsi");function x0(e){return Jd.lastIndex=0,e.replace(Jd,"")}i(x0,"stripAnsi");function PO(e,t=Ms()){let n=[],r=e.sessionId.slice(0,6);n.push(Zt.dim(`#${r}`));let o=e.permissionMode==="plan"?Zt.blue:e.permissionMode==="accept-edits"?Zt.cyan:e.permissionMode==="auto-in-project"?Zt.magenta:Zt.green,s=Zi(e.permissionMode),c=(e.permissionMode==="auto"||e.permissionMode==="auto-in-project")&&e.autoModeEngine?e.autoModeEngine==="llm"?Zt.green("[LLM]"):Zt.yellow("[RULES]"):"";if(n.push(o(s)+c),e.reasoningMode&&n.push(Zt.yellow(`reason:${e.reasoningMode}`)),n.push(Zt.cyan(e.provider)),e.tokenUsage){let m=e.tokenUsage.total,p=m>=1e3?`${(m/1e3).toFixed(1)}k`:String(m);n.push(Zt.dim(`${p}t`))}if(e.currentTool&&n.push(Zt.magenta(`tool:${e.currentTool}`)),e.projectInfo){let{completedFeatures:m,totalFeatures:p}=e.projectInfo,g=p>0?Math.round(m/p*100):0;n.push(Zt.dim(`${m}/${p} [${g}%]`))}e.messageCount!==void 0&&n.push(Zt.dim(`${e.messageCount} msgs`));let l=n.join(Zt.dim(" | ")),d=t-1;return x0(l).length>d&&(l=`${_O(l,Math.max(0,d-3))}...`),l}i(PO,"buildStatusBarContent");var Zd=class{static{i(this,"StatusBar")}state;visible=!1;constructor(t){this.state=t}update(t){this.state={...this.state,...t},this.visible&&this.render()}show(){this.visible||(this.visible=!0,this.render())}hide(){this.visible&&(this.visible=!1,this.clear())}toggle(){if(this.visible){this.hide();return}this.show()}getLinesUsed(){return 1}render(){let t=Ms(),n=PO(this.state,t),r=n+" ".repeat(Math.max(0,t-x0(n).length));process.stdout.write(sr.SAVE_CURSOR+sr.MOVE_TO_BOTTOM+sr.CLEAR_LINE+sr.REVERSE+r+sr.RESET+sr.RESTORE_CURSOR)}clear(){process.stdout.write(sr.SAVE_CURSOR+sr.MOVE_TO_BOTTOM+sr.CLEAR_LINE+sr.RESTORE_CURSOR)}};function w0(e,t,n,r,o="off"){return{sessionId:e,permissionMode:t,reasoningMode:o,provider:n,model:r}}i(w0,"createStatusBarState");function S0(){if(!process.stdout.isTTY||_i())return!1;let e=process.env.TERM??"",t=process.env.TERM_PROGRAM??"",n=["xterm","xterm-256color","screen","screen-256color","tmux","tmux-256color","vt100","vt220"],r=["iTerm.app","Terminal.app","Apple_Terminal","vscode","Hyper","Alacritty","kitty","Windows Terminal"];return n.some(o=>e.startsWith(o))||r.includes(t)||process.env.WT_SESSION!==void 0}i(S0,"supportsStatusBar");import b4 from"chalk";function T0(){return{prompt:"\u276F",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",arrow:"\u2192",bullet:"\u2022",check:"\u2713",cross:"\u2717",spinner:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]}}i(T0,"getUnicodeSymbols");function gh(){return{prompt:">",success:"[OK]",error:"[X]",warning:"[!]",info:"[i]",arrow:"->",bullet:"*",check:"[v]",cross:"[x]",spinner:["|","/","-","\\","|","/","-","\\"]}}i(gh,"getAsciiSymbols");var C0={name:"dark",description:"Dark theme with vibrant colors",colors:{primary:"#00D7FF",secondary:"#9D9D9D",accent:"#FF6B6B",text:"#FFFFFF",dim:"#6B6B6B",success:"#4CAF50",warning:"#FF9800",error:"#F44336",info:"#2196F3"},symbols:Ir()?T0():gh(),spinner:{frames:Ir()?["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]:["|","/","-","\\","|","/","-","\\"],interval:80}},$O={name:"light",description:"Light theme for bright terminals",colors:{primary:"#0066CC",secondary:"#666666",accent:"#CC0000",text:"#000000",dim:"#999999",success:"#228B22",warning:"#CC7A00",error:"#CC0000",info:"#0066CC"},symbols:Ir()?T0():gh(),spinner:{frames:Ir()?["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]:["|","/","-","\\","|","/","-","\\"],interval:80}},LO={name:"minimal",description:"Minimal theme without colors (for CI or limited terminals)",colors:{primary:"",secondary:"",accent:"",text:"",dim:"",success:"",warning:"",error:"",info:""},symbols:gh(),spinner:{frames:[".","o","O","0","O","o"],interval:120}},OO={dark:C0,light:$O,minimal:LO},b0=C0;function vc(){return b0}i(vc,"getCurrentTheme");function bc(e){let t=OO[e];return t?(b0=t,!0):!1}i(bc,"setTheme");function DO(){if(!process.stdout.isTTY){bc("minimal");return}let e=process.env;if(e.WT_SESSION!==void 0||e.TERM_PROGRAM==="vscode"){bc("dark");return}bc("dark")}i(DO,"autoSelectTheme");DO();var ef=class{static{i(this,"ReadlineUIContext")}rl;constructor(t){this.rl=t}async select(t,n){if(n.length!==0)return console.log(`
412
- ${t}`),console.log("\u2500".repeat(t.length)),n.forEach((r,o)=>{console.log(` ${o+1}. ${r}`)}),console.log(" 0. Cancel"),console.log(""),new Promise(r=>{this.rl.question("Enter choice (0 to cancel): ",o=>{let s=o.trim();if(s==="0"||s===""){r(void 0);return}let a=parseInt(s,10)-1;if(isNaN(a)||a<0||a>=n.length){console.log("Invalid choice. Please try again."),r(void 0);return}r(n[a])})})}async confirm(t){return new Promise(n=>{this.rl.question(`${t} (y/N): `,r=>{let o=r.trim().toLowerCase();n(o==="y"||o==="yes")})})}async input(t,n){let r=n?`${t} [${n}]: `:`${t}: `;return new Promise(o=>{this.rl.question(r,s=>{let a=s.trim();if(a===""&&n!==void 0){o(n);return}o(a||void 0)})})}};var yh=class{static{i(this,"MemorySessionStorage")}sessions=new Map;async save(t,n){let r=this.sessions.get(t),o=hn(n.messages,n.lineage??r?.data.lineage);this.sessions.set(t,{createdAt:r?.createdAt??new Date().toISOString(),data:{...structuredClone(n),scope:n.scope??r?.data.scope??"user",uiHistory:n.uiHistory??r?.data.uiHistory,extensionState:n.extensionState??r?.data.extensionState,extensionRecords:n.extensionRecords??r?.data.extensionRecords,lineage:o}})}async load(t){return structuredClone(this.sessions.get(t)?.data??null)}async getLineage(t){return structuredClone(this.sessions.get(t)?.data.lineage??null)}async setActiveEntry(t,n,r){let o=this.sessions.get(t);if(!o?.data.lineage)return null;let s=Ci(o.data.lineage,n,r);if(!s)return null;let a={...structuredClone(o.data),messages:Et(s),lineage:s};return this.sessions.set(t,{...o,data:a}),structuredClone(a)}async setLabel(t,n,r){let o=this.sessions.get(t);if(!o?.data.lineage)return null;let s=bi(o.data.lineage,n,r);if(!s)return null;let a={...structuredClone(o.data),lineage:s};return this.sessions.set(t,{...o,data:a}),structuredClone(a)}async fork(t,n,r){let o=this.sessions.get(t);if(!o?.data.lineage)return null;let s=ki(o.data.lineage,n);if(!s)return null;let a=r?.sessionId??await Ti(),c={messages:Et(s),title:r?.title??o.data.title,gitRoot:o.data.gitRoot,runtimeInfo:o.data.runtimeInfo?structuredClone(o.data.runtimeInfo):void 0,scope:o.data.scope??"user",extensionState:o.data.extensionState?structuredClone(o.data.extensionState):void 0,extensionRecords:o.data.extensionRecords?structuredClone(o.data.extensionRecords):void 0,lineage:s};return this.sessions.set(a,{createdAt:new Date().toISOString(),data:c}),{sessionId:a,data:structuredClone(c)}}async rewind(t,n){let r=this.sessions.get(t);if(!r?.data.lineage)return null;let o=n??vi(r.data.lineage);if(!o)return null;let s=Ii(r.data.lineage,o);if(!s)return null;let a={...r.data,messages:Et(s),lineage:s};return this.sessions.set(t,{...r,data:a}),structuredClone(a)}async list(t){return Array.from(this.sessions.entries()).filter(([,n])=>(n.data.scope??"user")==="user").map(([n,r])=>({id:n,title:r.data.title,msgCount:r.data.lineage?yo(r.data.lineage):r.data.messages.length,...r.data.runtimeInfo?{runtimeInfo:structuredClone(r.data.runtimeInfo)}:{}}))}async delete(t){this.sessions.delete(t)}async deleteAll(t){this.sessions.clear()}};function hh(e,t,n){e.runtimeInfo=n,e.gitRoot=n?.workspaceRoot??e.gitRoot,t.context={...t.context,gitRoot:e.gitRoot,executionCwd:n?.executionCwd??process.cwd()}}i(hh,"applyRuntimeContext");function NO(e){e?.workspaceRoot&&(console.log(j.dim(` Workspace: ${Cn(e)}`)),console.log(j.dim(` Use /status workspace for runtime details.
413
- `)))}i(NO,"printWorkspaceEntryNotice");function BO(e,t){return e.reasoningMode?e.reasoningMode:t.reasoningMode?t.reasoningMode:(e.thinking===!0||t.thinking===!0,"auto")}i(BO,"resolveInitialReasoningMode");var xh={current:null};async function HO(e){let t=await is({cwd:process.cwd()}),n=t.workspaceRoot??await wo()??void 0,r=e.storage??new yh,o=El({meta:{cwd:process.cwd(),startedAt:Date.now()}}),s=fm(),a=e.provider??s.provider??Rl,c=e.model??s.model,l=BO(e,s),d=e.agentMode??s.agentMode??"ama",m=l!=="off",p=Qn(s.permissionMode,"accept-edits")??"accept-edits",g=Su();p==="auto-in-project"&&g();let x=Al(),y=s.theme;y&&bc(y);let T=vc(),w={provider:a,model:c,thinking:m,reasoningMode:l,agentMode:d,permissionMode:p,repoIntelligenceMode:x.mode,repointelEndpoint:x.endpoint,repointelBin:x.bin,repoIntelligenceTrace:x.trace},v=p,O=rs(),P=0,D="",L=!1,X=500,I=await uc({sessionId:e.session?.id,gitRoot:n,runtimeInfo:t});o?.writer.update({sessionId:I.sessionId});let ie=i(A=>Go(w,A,(_,W,J)=>{console.log((_==="block"?j.red:j.yellow)(`
414
- ${W}`));for(let Ne of J)console.log(j.dim(Ne));console.log()}),"guardSessionTransition"),Te=await Ol(n??void 0),{resolveProvider:K}=await import("./dist-KWHUKXEL.js"),q=K(w.provider),M=Te.contextWindow??q.getEffectiveContextWindow?.(w.model)??q.getContextWindow?.()??2e5,{loadAgentsFiles:C}=await import("./dist-KWHUKXEL.js"),Z=i(async()=>C({cwd:process.cwd(),projectRoot:I.gitRoot??void 0}),"reloadAgentsFiles"),ke=await Z();jO(w,w.permissionMode,{contextWindow:M,triggerPercent:Te.triggerPercent,enabled:Te.enabled},ke),NO(t);let ve=TT(()=>I.gitRoot??process.cwd()),Se=I0.createInterface({input:process.stdin,output:process.stdout,terminal:process.stdout.isTTY??!0,historySize:100,completer:i((A,_)=>{ve(A).then(W=>{_(null,W)}).catch(()=>{_(null,[[],A])})},"completer")}),ce=Au(),De=await fc({askUser:i(async(A,_,W)=>(await Cc(Se,A.name,{...A.input,...W&&W.length>0?{_classifierSignals:W}:{}},{permissionMode:v,reason:`[auto-mode] ${_}`})).confirmed?"allow":"block","askUser"),projectRoot:n??process.cwd(),getAgentsFiles:i(()=>ke,"getAgentsFiles"),getCurrentProviderName:i(()=>w.provider,"getCurrentProviderName"),getCurrentModel:i(()=>w.model,"getCurrentModel"),getCurrentPermissionMode:i(()=>v,"getCurrentPermissionMode"),autoModeSettings:ce,log:i((A,_)=>{A==="warn"?console.warn(j.yellow(_)):console.log(j.dim(_))},"log"),onEngineChange:i(A=>{qt(v)&&Q?.update({autoModeEngine:A})},"onEngineChange"),extraCollectors:[Da]}),ae=Pl({getProvider:i(()=>K(w.provider),"getProvider"),getModel:i(()=>w.model??"","getModel")}),Y=w.model??Vn(w.provider)??w.provider,Q=null;S0()&&(Q=new Zd(w0(I.sessionId,w.permissionMode,w.provider,Y,w.reasoningMode)),qt(v)&&Q.update({autoModeEngine:De.getGuardrail().getEngine()}));let Ce=`
415
- Keyboard Shortcuts:
416
- Tab Auto-complete (@paths, /commands)
417
- Esc+Esc Edit last message
418
- Ctrl+T Cycle reasoning mode
419
- Ctrl+E Open external editor
420
- Ctrl+R Search command history (built-in)
421
- Ctrl+C Cancel current input
422
- Ctrl+D Exit REPL`,be=i(()=>{console.log(j.dim(Ce))},"_printKeyboardShortcuts");process.stdin.isTTY&&process.stdin.on("keypress",(A,_)=>{if(_&&_.name==="escape"){let W=Date.now();W-P<X&&D&&(L=!0,console.log(j.dim(`
423
- [Opening editor with last message...]`)),Se.pause()),P=W}});let Re=mr(n).getSystemPromptSnippet(),Ue=!0,xe={...e,reasoningMode:l,thinking:m,context:{...e.context,gitRoot:n,executionCwd:t.executionCwd,repoIntelligenceMode:x.mode,repoIntelligenceTrace:x.trace,skillsPrompt:Re},session:{...e.session,id:I.sessionId}};xh.current=null;let kt={exit:i(()=>{Ue=!1,o?.shutdown(),Se.close()},"exit"),saveSession:i(async()=>{if(I.messages.length>0){let A=tf(I.messages);I.title=A,await r.save(I.sessionId,{messages:I.messages,title:A,gitRoot:I.gitRoot??"",runtimeInfo:I.runtimeInfo,artifactLedger:I.artifactLedger})}},"saveSession"),startNewSession:i(()=>{I.sessionId=dc(),I.title="",I.contextTokenSnapshot=void 0,I.artifactLedger=void 0,I.createdAt=new Date().toISOString(),I.lastAccessed=I.createdAt,hh(I,xe,t),xe.session={...xe.session,id:I.sessionId},Q?.update({sessionId:I.sessionId,messageCount:0}),o?.writer.update({sessionId:I.sessionId})},"startNewSession"),loadSession:i(async A=>{let _=await r.load(A);if(_){if(!ie("Resuming a saved session"))return"blocked";let W=await is({cwd:process.cwd()}),J=Va(_),Ne=J??W;return J?.workspaceRoot&&!pT(J)?(console.log(j.yellow(`
424
- [Saved workspace unavailable]`)),console.log(j.dim(` Session workspace: ${Cn(J)}`)),console.log(j.dim(` Falling back to current workspace: ${Cn(W)}`)),Ne=W):J?.workspaceRoot&&W.workspaceRoot&&J.workspaceRoot!==W.workspaceRoot&&(console.log(j.cyan(`
425
- [Loading sibling workspace session]`)),console.log(j.dim(` Current workspace: ${Cn(W)}`)),console.log(j.dim(` Session workspace: ${Cn(J)}`))),I.messages=_.messages,I.title=_.title,I.sessionId=A,I.contextTokenSnapshot=void 0,I.artifactLedger=_.artifactLedger,I.lastAccessed=new Date().toISOString(),hh(I,xe,Ne),xe.session={...xe.session,id:A},Q?.update({sessionId:A,messageCount:_.messages.length}),o?.writer.update({sessionId:A}),console.log(j.green(`
426
- [Loaded session: ${A}]`)),console.log(j.dim(` Messages: ${_.messages.length}`)),I.runtimeInfo?.workspaceRoot&&console.log(j.dim(` Workspace: ${Cn(I.runtimeInfo)}`)),"loaded"}return"missing"},"loadSession"),listSessions:i(async()=>{let A=await r.list(I.gitRoot??void 0);if(A.length===0){console.log(j.dim(`
427
- [No saved sessions]`));return}console.log(j.bold(`
428
- Recent Sessions:
429
- `)),I.runtimeInfo?.workspaceRoot&&(console.log(j.dim(` Current workspace: ${Cn(I.runtimeInfo)}`)),console.log());for(let _ of A.slice(0,10))if(console.log(` ${j.cyan(_.id)} ${j.dim(`(${_.msgCount} messages)`)} ${_.title.slice(0,40)}`),_.runtimeInfo?.workspaceRoot){let J=I.runtimeInfo?.workspaceRoot===_.runtimeInfo.workspaceRoot?" (current workspace)":"";console.log(j.dim(` workspace: ${Cn(_.runtimeInfo)}${J}`))}console.log()},"listSessions"),clearHistory:i(()=>{I.messages=[],I.contextTokenSnapshot=void 0},"clearHistory"),printHistory:i(()=>{if(I.messages.length===0){console.log(j.dim(`
430
- [No conversation history]`));return}console.log(j.bold(`
431
- Conversation History:
432
- `));let A=I.messages.slice(-20);for(let _=0;_<A.length;_++){let W=A[_],J=j.cyan(W.role.padEnd(10)),Ne=typeof W.content=="string"?W.content:"[Complex content]",et=Ne.slice(0,60).replace(/\n/g," "),Ie=Ne.length>60?"...":"";console.log(` ${(_+1).toString().padStart(2)}. ${J} ${et}${Ie}`)}console.log()},"printHistory"),switchProvider:i((A,_)=>{w.provider=A,w.model=_,xe.provider=A,xe.model=_;let W=_??Vn(A);if(!W)try{W=Gy(A)?.getModel()??A}catch{W=A}Q?.update({provider:A,model:W})},"switchProvider"),setThinking:i(A=>{w.thinking=A,xe.thinking=A,w.reasoningMode=A?"auto":"off",xe.reasoningMode=w.reasoningMode,Q?.update({reasoningMode:w.reasoningMode})},"setThinking"),setReasoningMode:i(A=>{let _=A!=="off";w.reasoningMode=A,w.thinking=_,xe.reasoningMode=A,xe.thinking=_,Q?.update({reasoningMode:A})},"setReasoningMode"),setPermissionMode:i(A=>{w.permissionMode=A,v=A;let _=qt(A)?De.getGuardrail().getEngine():void 0;Q?.update({permissionMode:A,autoModeEngine:_}),A==="auto-in-project"&&g()},"setPermissionMode"),setRepoIntelligenceRuntime:i(A=>{A.mode!==void 0&&(w.repoIntelligenceMode=A.mode,process.env.KODAX_REPO_INTELLIGENCE_MODE=A.mode,xe.context={...xe.context,repoIntelligenceMode:A.mode}),A.trace!==void 0&&(w.repoIntelligenceTrace=A.trace,A.trace?process.env.KODAX_REPO_INTELLIGENCE_TRACE="1":delete process.env.KODAX_REPO_INTELLIGENCE_TRACE,xe.context={...xe.context,repoIntelligenceTrace:A.trace}),A.endpoint!==void 0&&(w.repointelEndpoint=A.endpoint??void 0,A.endpoint?process.env.KODAX_REPOINTEL_ENDPOINT=A.endpoint:delete process.env.KODAX_REPOINTEL_ENDPOINT),A.bin!==void 0&&(w.repointelBin=A.bin??void 0,A.bin?process.env.KODAX_REPOINTEL_BIN=A.bin:delete process.env.KODAX_REPOINTEL_BIN)},"setRepoIntelligenceRuntime"),deleteSession:i(async A=>{await r.delete?.(A)},"deleteSession"),deleteAllSessions:i(async()=>{await r.deleteAll?.(I.gitRoot??void 0)},"deleteAllSessions"),printSessionTree:i(async()=>{let A=await r.getLineage?.(I.sessionId);if(!A){console.log(j.dim(`
433
- [No session tree available for this session]`));return}let _=Dd(Ml(A));console.log(j.bold(`
434
- Session Tree:
435
- `));for(let W of _)console.log(` ${W}`);console.log()},"printSessionTree"),switchSessionBranch:i(async A=>{if(!ie("Switching session branches"))return"blocked";let _=await r.setActiveEntry?.(I.sessionId,A,{summarizeCurrentBranch:!0});return _?(I.messages=_.messages,I.title=_.title,I.contextTokenSnapshot=void 0,Q?.update({messageCount:I.messages.length}),console.log(j.green(`
436
- [Switched to tree entry: ${A}]`)),console.log(j.dim(` Messages: ${_.messages.length}`)),"switched"):"missing"},"switchSessionBranch"),labelSessionBranch:i(async(A,_)=>{if(!await r.setLabel?.(I.sessionId,A,_))return!1;let J=_&&_.trim()?`checkpoint label set: ${_.trim()}`:"checkpoint label cleared";return console.log(j.green(`
437
- [${J}]`)),!0},"labelSessionBranch"),forkSession:i(async A=>{if(!ie("Forking a session branch"))return"blocked";let _=await r.fork?.(I.sessionId,A);return _?(I.sessionId=_.sessionId,I.messages=_.data.messages,I.title=_.data.title,I.contextTokenSnapshot=void 0,I.createdAt=new Date().toISOString(),I.lastAccessed=I.createdAt,hh(I,xe,Va(_.data)??I.runtimeInfo),xe.session={...xe.session,id:_.sessionId},Q?.update({sessionId:_.sessionId,messageCount:I.messages.length}),console.log(j.green(`
438
- [Forked session: ${_.sessionId}]`)),console.log(j.dim(` Messages: ${_.data.messages.length}`)),"forked"):"failed"},"forkSession"),rewindSession:i(async A=>{if(!ie("Rewinding session"))return"blocked";let _=await r.rewind?.(I.sessionId,A);return _?(I.messages=_.messages,I.title=_.title,I.contextTokenSnapshot=void 0,I.lastAccessed=new Date().toISOString(),Q?.update({messageCount:I.messages.length}),console.log(j.green(`
439
- [Rewound session${A?` to ${A}`:" to previous turn"}]`)),console.log(j.dim(` Messages: ${_.messages.length}`)),"rewound"):"failed"},"rewindSession"),getCostReport:i(()=>xh.current?.()??null,"getCostReport"),getAutoModeStats:i(()=>{if(qt(v))return De.getGuardrail().getStats()},"getAutoModeStats"),setAutoModeEngine:i(A=>{qt(v)&&(De.getGuardrail().setEngine(A),Q?.update({permissionMode:v}))},"setAutoModeEngine"),createKodaXOptions:i(()=>{let A=i((W,J)=>v!=="plan"?null:Tr(W,J,n??process.cwd()),"planModeBlockCheck"),_=qt(v)?[De.getGuardrail()]:void 0;return{...xe,provider:w.provider,model:w.model,thinking:w.thinking,reasoningMode:w.reasoningMode,guardrails:_,context:{...xe.context,planModeBlockCheck:A},events:{...xe.events,exitPlanMode:i(async W=>v!=="plan"?"not-in-plan-mode":(await Cc(Se,"exit_plan_mode",{plan:W},{isProtectedPath:!1,permissionMode:v})).confirmed?(w.permissionMode="accept-edits",v="accept-edits",Q?.update({permissionMode:"accept-edits"}),!0):!1,"exitPlanMode"),beforeToolExecute:i(async(W,J)=>{let Ne=v,et=Mo(Ne);if(Ne==="plan"){let Ie=Tr(W,J,n??process.cwd());if(Ie)return console.log(j.yellow(Ie)),`${Ie} Do not modify files while planning. Finish the plan first, then call exit_plan_mode with the finalized plan \u2014 the user will review and approve or reject.`}if(W==="bash"){let Ie=J.command??"";if($n(Ie))return!0}if(n&&Sn.has(W)){let Ie=J.path;if(Ie&&Jn(Ie,n))return(await Cc(Se,W,J,{isProtectedPath:!0,permissionMode:Ne})).confirmed?!0:(console.log(j.dim("[Cancelled] Operation on protected path requires confirmation")),!1)}if(et.has(W)){if(Ne==="accept-edits"&&W==="bash"&&await Gr(W,J,O,ae))return!0;let Ie=await Cc(Se,W,J,{isOutsideProject:J._outsideProject===!0,reason:J._reason,permissionMode:Ne});if(!Ie.confirmed)return console.log(j.dim("[Cancelled] Operation cancelled by user")),!1;Ie.always&&Ne==="accept-edits"&&(_u(W,J,!1),O=rs())}return!0},"beforeToolExecute")}}},"createKodaXOptions"),reloadAgentsFiles:i(async()=>(ke=await Z(),ke),"reloadAgentsFiles"),readline:Se,ui:new ef(Se)};Se.on("SIGINT",async()=>{console.log(j.dim(`
440
-
441
- [Press /exit to quit]`)),Se.prompt()});let qe=i(()=>{Q?.hide(),o?.shutdown(),Se.close()},"cleanup");process.on("exit",qe),process.on("SIGTERM",qe);let ee=i(async(A,_)=>{if(!A||typeof A!="object"||!A.invocation)return;let W=await Hd({...xe,provider:w.provider,thinking:w.thinking,reasoningMode:w.reasoningMode},A.invocation,_,J=>console.log(j.dim(`
442
- ${J}`)));if(W.mode==="manual"){W.manualOutput&&console.log(j.yellow(`
443
- ${W.manualOutput}
444
- `)),await W.finalize();return}if(!W.prompt||!W.options){await W.finalize();return}try{let J=W.mode==="fork"?[]:I.messages,Ne=await v0(W.options,I,W.prompt,J);if(W.mode==="fork"){let et=Ua(Ne.messages);et.trim()&&(console.log(`
445
- ${et}
446
- `),I.messages.push({role:"assistant",content:et}))}else I.messages=Ne.messages,I.contextTokenSnapshot=Ne.contextTokenSnapshot;if(Q?.update({messageCount:I.messages.length}),I.messages.length>0){let et=tf(I.messages);I.title=et,await r.save(I.sessionId,{messages:I.messages,title:et,gitRoot:I.gitRoot??"",runtimeInfo:I.runtimeInfo})}await W.finalize()}catch(J){throw await W.finalize(J instanceof Error?J:new Error(String(J))),J}},"handleCommandResult");for(;Ue;){if(L&&D){L=!1,Se.resume();let Ie=await E0(D);if(Ie&&Ie.trim()&&Ie!==D){console.log(j.dim(`
447
- [Edited message ready to send]`));let Le=Ie.trim();rr(I);let Kt=as(Le);if(Kt){let F=await cs(Kt,I,kt,w);await ee(F,Le);continue}let V=await wh(Le);if(Le.startsWith("!")&&mc(V))continue;let fe=pc(V,xe.context?.executionCwd??process.cwd());for(let F of fe.warnings)console.log(j.yellow(`
448
- ${F}`));I.messages.push({role:"user",content:fe.messageContent}),D=Le,Q?.update({messageCount:I.messages.length});try{let F=await ma({...xe,provider:w.provider,thinking:w.thinking,reasoningMode:w.reasoningMode,session:{...xe.session,initialMessages:I.lineage?Et(I.lineage,I.lineage.activeEntryId):I.messages},context:{...xe.context,taskSurface:"repl",planModeBlockCheck:i((_e,Tt)=>v!=="plan"?null:Tr(_e,Tt,n??process.cwd()),"planModeBlockCheck"),...fe.inputArtifacts.length>0?{inputArtifacts:fe.inputArtifacts}:{}}},V);if(I.messages=F.messages,I.contextTokenSnapshot=F.contextTokenSnapshot,I.artifactLedger=da(I.artifactLedger??[],F.artifactLedger??om(F.messages)),I.messages.length>0){let _e=tf(I.messages);I.title=_e,await r.save(I.sessionId,{messages:I.messages,title:_e,gitRoot:I.gitRoot??"",runtimeInfo:I.runtimeInfo,artifactLedger:I.artifactLedger})}}catch(F){let _e=F instanceof Error?F:new Error(String(F));I.messages.pop(),console.log(j.red(`
449
- [Error] ${_e.message}`))}continue}else Ie===D&&console.log(j.dim(`
450
- [No changes made, continuing...]`))}let A=FO(w.permissionMode,w),_=await WO(Se,A);if(!Ue)break;let W=_.trim();if(!W)continue;rr(I);let J=as(W);if(J){let Ie=await cs(J,I,kt,w);await ee(Ie,W);continue}let Ne=await wh(W);if(W.startsWith("!")&&mc(Ne))continue;let et=pc(Ne,xe.context?.executionCwd??process.cwd());for(let Ie of et.warnings)console.log(j.yellow(`
451
- ${Ie}`));I.messages.push({role:"user",content:et.messageContent}),D=W,Q?.update({messageCount:I.messages.length});try{let Ie=await v0(xe,I,Ne,I.messages,et.inputArtifacts);if(I.messages=Ie.messages,I.contextTokenSnapshot=Ie.contextTokenSnapshot,I.artifactLedger=da(I.artifactLedger??[],Ie.artifactLedger??om(Ie.messages)),Q?.update({messageCount:I.messages.length}),I.messages.length>0){let Le=tf(I.messages);I.title=Le,await r.save(I.sessionId,{messages:I.messages,title:Le,gitRoot:I.gitRoot??"",runtimeInfo:I.runtimeInfo,artifactLedger:I.artifactLedger})}}catch(Ie){let Le=Ie instanceof Error?Ie:new Error(String(Ie));I.messages.pop(),Le.message.includes("rate limit")||Le.message.includes("Rate limit")?(console.log(j.yellow(`
452
- [Rate Limit] ${Le.message}`)),console.log(j.dim(`Suggestion: Wait a moment and try again, or switch provider with /mode
453
- `))):Le.message.includes("API key")||Le.message.includes("not configured")?(console.log(j.red(`
454
- [Configuration Error] ${Le.message}`)),console.log(j.dim(`Suggestion: Set the required API key environment variable
455
- `))):Le.message.includes("network")||Le.message.includes("ECONNREFUSED")||Le.message.includes("ETIMEDOUT")?(console.log(j.red(`
456
- [Network Error] ${Le.message}`)),console.log(j.dim(`Suggestion: Check your internet connection and try again
457
- `))):Le.message.includes("token")||Le.message.includes("context too long")?(console.log(j.yellow(`
458
- [Context Error] ${Le.message}`)),console.log(j.dim(`Suggestion: Use /clear to start a fresh conversation
459
- `))):(console.log(j.red(`
460
- [Error] ${Le.message}`)),console.log(j.dim(`Your message was not sent. Please try again.
461
- `)))}}}i(HO,"runInteractiveMode");function FO(e,t){let n=vc(),r=e==="plan"?j.hex(n.colors.warning):j.hex(n.colors.success),o=t.model??Vn(t.provider)??t.provider,s=Ms();if(s<60){let c=e==="plan"?"?":n.symbols.prompt;return r(`${c} `)}else if(s<100){let c=t.reasoningMode!=="off"?t.reasoningMode[0]?.toUpperCase()??"R":"",l=c?j.hex(n.colors.dim)(`[${c}]`):"";return r(`kodax:${e}${l}> `)}let a=t.reasoningMode!=="off"?j.hex(n.colors.info)(`[reason:${t.reasoningMode}]`):"";return r(`kodax:${e} (${t.provider}:${o})${a}> `)}i(FO,"getPrompt");async function WO(e,t){let n=vc(),r=[],o=await new Promise(a=>{e.question(t,a)});if(o===""||o.toLowerCase()==="/e")return await E0(r.join(`
462
- `));for(r.push(o);UO(r.join(`
463
- `));){let a=j.hex(n.colors.dim)("... "),c=await new Promise(l=>{e.question(a,l)});r.push(c)}return r.join(`
464
- `).replace(/\\\n/g,`
465
- `)}i(WO,"askInput");async function E0(e){let t=kc.join(R0.tmpdir(),"kodax"),n=kc.join(t,`input-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`);try{await Ic.promises.mkdir(t,{recursive:!0}),await Ic.promises.writeFile(n,e,"utf-8");let r=process.env.EDITOR??process.env.VISUAL??(process.platform==="win32"?"notepad.exe":"nano");if(r.includes("/")||r.includes("\\")||r.includes("&&")||r.includes("|")){let a=kc.basename(r);console.log(j.yellow(`
466
- [Security] Editor path sanitized: ${a}`)),r=a}console.log(j.dim(`
467
- [Opening editor: ${r}]`));let o=process.platform==="win32"&&(r.toLowerCase()==="notepad"||r.toLowerCase()==="notepad.exe");return console.log(o?j.dim(`Note: Please close Notepad manually after editing to continue.
468
- `):j.dim(`Save and close the editor to continue...
469
- `)),k0.spawnSync(r,[n],{stdio:"inherit",timeout:3e5,shell:!1}),(await Ic.promises.readFile(n,"utf-8")).trim()}catch(r){let o=r instanceof Error?r:new Error(String(r));return console.log(j.red(`
470
- [Editor Error] ${o.message}`)),e}finally{try{await Ic.promises.unlink(n)}catch{}}}i(E0,"openExternalEditor");function UO(e){if(e.endsWith("\\")&&!e.endsWith("\\\\"))return!0;let t={"(":0,"[":0,"{":0},n={")":"(","]":"[","}":"{"},r=null;for(let o=0;o<e.length;o++){let s=e[o];if((s==='"'||s==="'"||s==="`")&&e[o-1]!=="\\"){r===s?r=null:r===null&&(r=s);continue}if(!r){if(s in t)t[s]++;else if(s in n){let a=n[s];a&&t[a]--}}}return!!(Object.values(t).some(o=>o>0)||r)}i(UO,"needsContinuation");async function wh(e){let t=e.match(/@[\w./-]+/g);if(t)for(let n of t){let r=n.slice(1)}if(e.startsWith("!")){let n=e.slice(1).trim();return Pd(n,{cwd:process.cwd()})}return e}i(wh,"processSpecialSyntax");async function v0(e,t,n,r=t.messages,o){let s={...e.events??{},getCostReport:xh};return ma({...e,events:s,session:{...e.session,initialMessages:r},context:{...e.context,contextTokenSnapshot:t.contextTokenSnapshot,taskSurface:"repl",...o&&o.length>0?{inputArtifacts:[...o]}:{}}},n)}i(v0,"runAgentRound");function tf(e){return ns(e)}i(tf,"extractTitle");function jO(e,t,n,r){let o=vc(),s=e.model??Vn(e.provider)??e.provider;if(console.log(j.hex(o.colors.primary)(`
471
- `+`
472
- \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
473
- \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D
474
- \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D
475
- \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557
476
- \u2588\u2588\u2551 \u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u255D \u2588\u2588\u2557
477
- \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D`)),console.log(j.hex(o.colors.text)(`
478
- v${Ri} | AI Coding Agent | ${e.provider}:${s}`)),console.log(j.hex(o.colors.dim)(`
479
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`)),console.log(j.hex(o.colors.dim)(" Mode: ")+j.hex(o.colors.primary)(t)+j.hex(o.colors.dim)(" | Reasoning: ")+(e.reasoningMode==="off"?j.hex(o.colors.dim)("off"):j.hex(o.colors.success)(e.reasoningMode))),n){let c=Math.round(n.contextWindow/1e3),l=Math.round(n.contextWindow*n.triggerPercent/100/1e3),d=n.enabled?j.hex(o.colors.success)("on"):j.hex(o.colors.dim)("off");console.log(j.hex(o.colors.dim)(` Context: ${c}k | Compaction: `)+d+j.hex(o.colors.dim)(` @ ${n.triggerPercent}% (${l}k)`))}if(console.log(j.hex(o.colors.dim)(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
480
- `)),r){let c=r.length;console.log(j.hex(o.colors.dim)(" Project Rules: ")+j.hex(o.colors.success)(`${c} rule file(s) loaded`)),console.log(j.hex(o.colors.dim)(` Use /reload to refresh rules
481
- `))}console.log(j.hex(o.colors.dim)(" Quick tips:")),console.log(j.hex(o.colors.primary)(" /help ")+j.hex(o.colors.dim)("Show all commands")),console.log(j.hex(o.colors.primary)(" /mode ")+j.hex(o.colors.dim)("Switch permission mode")),console.log(j.hex(o.colors.primary)(" /clear ")+j.hex(o.colors.dim)("Clear conversation")),console.log(j.hex(o.colors.primary)(" @path ")+j.hex(o.colors.dim)("Attach image to context")),console.log(j.hex(o.colors.primary)(" !cmd ")+j.hex(o.colors.dim)("Run read-only shell command")),console.log(j.hex(o.colors.dim)(`
482
- Keyboard: Tab (complete) | Esc+Esc (edit last) | Ctrl+T (reasoning) | Ctrl+E (editor) | Ctrl+R (history)
483
- `))}i(jO,"printStartupBanner");import nf from"node:fs";import GO from"node:path";function KO(){let e=of();return sf(e).map(n=>rf(n))}i(KO,"listCustomProviders");function VO(e){if(typeof e!="string"||e.length===0)return;let t=sf(of()).find(n=>n.name===e);return t?rf(t):void 0}i(VO,"getCustomProviderConfig");function zO(e){jy(e);let t=rf(e),n=of(),r=sf(n),o=r.findIndex(a=>a.name===t.name),s=o>=0?r.map((a,c)=>c===o?t:a):[...r,t];return A0({...n,customProviders:s}),nm(s),rf(t)}i(zO,"upsertCustomProvider");function XO(e){if(typeof e!="string"||e.length===0)return!1;let t=of(),n=sf(t),r=n.filter(o=>o.name!==e);return r.length===n.length?!1:(A0({...t,customProviders:r}),nm(r),!0)}i(XO,"removeCustomProvider");function M0(){return gn("config.json")}i(M0,"configFilePath");function of(){let e=M0();if(!nf.existsSync(e))return{};try{let t=JSON.parse(nf.readFileSync(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}i(of,"readWholeConfig");function A0(e){let t=M0();nf.mkdirSync(GO.dirname(t),{recursive:!0}),nf.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}i(A0,"writeWholeConfig");function sf(e){let t=e.customProviders;return Array.isArray(t)?t:[]}i(sf,"extractCustomProviders");function rf(e){return structuredClone(e)}i(rf,"cloneCustomProvider");import af from"node:fs";import YO from"node:path";function qO(){let e=cf();return eD(lf(e))}i(qO,"listMcpServers");function QO(e){if(typeof e!="string"||e.length===0)return;let n=lf(cf())[e];return n?Sh(n):void 0}i(QO,"getMcpServerConfig");function JO(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("upsertMcpServer: name must be a non-empty string");_0(e,t);let n=Sh(t),r=cf(),s={...lf(r),[e]:n};return $0({...r,mcpServers:s}),Sh(n)}i(JO,"upsertMcpServer");function ZO(e){if(typeof e!="string"||e.length===0)return!1;let t=cf(),n=lf(t);if(!(e in n))return!1;let r={};for(let o of Object.keys(n))o!==e&&(r[o]=n[o]);return $0({...t,mcpServers:r}),!0}i(ZO,"removeMcpServer");function _0(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("MCP server name must be a non-empty string");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError(`MCP server "${e}": config must be a plain object`);let n=t.type??"stdio";if(!["stdio","sse","streamable-http"].includes(n))throw new TypeError(`MCP server "${e}": unknown transport type "${n}" (expected stdio | sse | streamable-http)`);if(n==="stdio"){if(typeof t.command!="string"||t.command.length===0)throw new TypeError(`MCP server "${e}": stdio transport requires a non-empty "command"`)}else if(typeof t.url!="string"||t.url.length===0)throw new TypeError(`MCP server "${e}": "${n}" transport requires a non-empty "url"`);if(t.connect!==void 0&&!["lazy","prewarm","disabled"].includes(t.connect))throw new TypeError(`MCP server "${e}": unknown connect mode "${t.connect}" (expected lazy | prewarm | disabled)`)}i(_0,"validateMcpServerConfig");function P0(){return gn("config.json")}i(P0,"configFilePath");function cf(){let e=P0();if(!af.existsSync(e))return{};try{let t=JSON.parse(af.readFileSync(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}i(cf,"readWholeConfig");function $0(e){let t=P0();af.mkdirSync(YO.dirname(t),{recursive:!0}),af.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}i($0,"writeWholeConfig");function lf(e){let t=e.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?{}:t}i(lf,"extractMcpServers");function Sh(e){return structuredClone(e)}i(Sh,"cloneMcpServerConfig");function eD(e){return structuredClone(e)}i(eD,"cloneMcpServers");import Nn from"fs/promises";import uf from"fs";import df from"path";import N0 from"chalk";var tD=new Set(["user","assistant","system"]);function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(St,"isRecord");function Yo(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(Yo);if(!St(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(Yo)}i(Yo,"isKodaXJsonValue");function L0(e){return St(e)&&typeof e.id=="string"&&typeof e.extensionId=="string"&&typeof e.type=="string"&&typeof e.ts=="number"&&(e.data===void 0||Yo(e.data))&&(e.dedupeKey===void 0||typeof e.dedupeKey=="string")}i(L0,"isKodaXExtensionSessionRecord");function O0(e){return St(e)?Object.values(e).every(t=>St(t)?Object.values(t).every(Yo):!1):!1}i(O0,"isKodaXExtensionSessionState");function nD(e){if(!St(e)||typeof e.type!="string")return!1;switch(e.type){case"text":return typeof e.text=="string";case"tool_use":return typeof e.id=="string"&&typeof e.name=="string"&&St(e.input);case"tool_result":return typeof e.tool_use_id=="string"&&typeof e.content=="string"&&(e.is_error===void 0||typeof e.is_error=="boolean");case"image":return typeof e.path=="string"&&(e.mediaType===void 0||typeof e.mediaType=="string");case"thinking":return typeof e.thinking=="string"&&(e.signature===void 0||typeof e.signature=="string");case"redacted_thinking":return typeof e.data=="string";default:return!1}}i(nD,"isKodaXContentBlock");function Th(e){return!St(e)||typeof e.role!="string"||!tD.has(e.role)?!1:typeof e.content=="string"||Array.isArray(e.content)&&e.content.every(nD)}i(Th,"isKodaXMessage");function D0(e){return St(e)?(e.lastError===void 0||typeof e.lastError=="string")&&(e.lastErrorTime===void 0||typeof e.lastErrorTime=="number")&&(e.consecutiveErrors===void 0||typeof e.consecutiveErrors=="number"):!1}i(D0,"isSessionErrorMetadata");function rD(e){return St(e)&&typeof e.type=="string"&&(e.type==="user"||e.type==="assistant"||e.type==="system"||e.type==="thinking"||e.type==="error"||e.type==="info"||e.type==="hint")&&typeof e.text=="string"}i(rD,"isKodaXSessionUiHistoryItem");function Ch(e){return Array.isArray(e)&&e.every(rD)}i(Ch,"isKodaXSessionUiHistory");function oD(e){return!St(e)||e._type!=="meta_update"?!1:(e.title===void 0||typeof e.title=="string")&&(e.activeEntryId===void 0||typeof e.activeEntryId=="string"||e.activeEntryId===null)&&(e.activeMessageCount===void 0||typeof e.activeMessageCount=="number")&&(e.uiHistory===void 0||Ch(e.uiHistory))&&(e.scope===void 0||typeof e.scope=="string")}i(oD,"isPersistedMetaUpdateLine");function B0(e,t){t!==0&&process.stderr.write(`[KodaX] Skipped ${t} malformed session record(s) from ${df.basename(e)}.
484
- `)}i(B0,"warnMalformedSessionData");function eo(e){process.stderr.write(`${e}
485
- `)}i(eo,"writeStorageNotice");function H0(e){return{_type:"extension_record",...e}}i(H0,"toExtensionRecordLine");function F0(e){return{_type:"lineage_entry",entry:e}}i(F0,"toLineageEntryLine");function W0(e){return{_type:"artifact_ledger_entry",entry:e}}i(W0,"toArtifactLedgerLine");function iD(e){return St(e)&&e._type==="extension_record"&&L0(e)}i(iD,"isPersistedExtensionRecordLine");function sD(e){return St(e)&&typeof e.id=="string"&&(e.parentId===null||typeof e.parentId=="string")&&typeof e.timestamp=="string"&&typeof e.type=="string"}i(sD,"hasEntryBase");function aD(e){if(!sD(e))return!1;let t=e;switch(t.type){case"message":return Th(t.message);case"compaction":return typeof t.summary=="string"&&(t.firstKeptEntryId===void 0||typeof t.firstKeptEntryId=="string")&&(t.tokensBefore===void 0||typeof t.tokensBefore=="number");case"branch_summary":return typeof t.summary=="string"&&(t.fromId===void 0||typeof t.fromId=="string")&&(t.details===void 0||Yo(t.details));case"label":return typeof t.targetId=="string"&&(t.label===void 0||typeof t.label=="string");case"archive_marker":return typeof t.archiveBatchId=="string"&&typeof t.archivedEntryCount=="number"&&typeof t.summary=="string";default:return!1}}i(aD,"isKodaXSessionEntry");function cD(e){return St(e)&&e._type==="lineage_entry"&&aD(e.entry)}i(cD,"isPersistedLineageEntryLine");function lD(e){return St(e)&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.target=="string"&&typeof e.timestamp=="string"&&(e.sourceTool===void 0||typeof e.sourceTool=="string")&&(e.action===void 0||typeof e.action=="string")&&(e.displayTarget===void 0||typeof e.displayTarget=="string")&&(e.summary===void 0||typeof e.summary=="string")&&(e.sessionEntryId===void 0||typeof e.sessionEntryId=="string")&&(e.metadata===void 0||Yo(e.metadata))}i(lD,"isKodaXSessionArtifactLedgerEntry");function uD(e){return St(e)&&e._type==="artifact_ledger_entry"&&lD(e.entry)}i(uD,"isPersistedArtifactLedgerLine");function j0(e){return St(e)&&(e.canonicalRepoRoot===void 0||typeof e.canonicalRepoRoot=="string")&&(e.workspaceRoot===void 0||typeof e.workspaceRoot=="string")&&(e.executionCwd===void 0||typeof e.executionCwd=="string")&&(e.branch===void 0||typeof e.branch=="string")&&(e.workspaceKind===void 0||e.workspaceKind==="detected"||e.workspaceKind==="managed")}i(j0,"isKodaXSessionRuntimeInfo");function U0(e,t){return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase()===t.toLowerCase():e===t}i(U0,"pathsEqual");function dD(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n&&n.type!=="label")return n.id}return null}i(dD,"getLastNavigableEntryId");function fD(e){if(e.lineageEntries.length>0)return{version:2,activeEntryId:e.meta?.activeEntryId??dD(e.lineageEntries),entries:e.lineageEntries};if(e.legacyMessages.length!==0)return hn(e.legacyMessages)}i(fD,"buildLineage");function mD(e){let t=fD(e);return{createdAt:e.meta?.createdAt,data:{messages:t?Et(t):[...e.legacyMessages],title:e.meta?.title??"",gitRoot:e.meta?.gitRoot??"",runtimeInfo:j0(e.meta?.runtimeInfo)?{...e.meta.runtimeInfo}:void 0,scope:e.meta?.scope??"user",uiHistory:Ch(e.meta?.uiHistory)?e.meta.uiHistory.map(n=>({...n})):void 0,errorMetadata:D0(e.meta?.errorMetadata)?{...e.meta.errorMetadata}:void 0,extensionState:O0(e.meta?.extensionState)?e.meta?.extensionState:void 0,extensionRecords:e.extensionRecords.map(n=>({...n})),lineage:t,artifactLedger:e.artifactLedger.map(n=>({...n,metadata:n.metadata?structuredClone(n.metadata):void 0}))}}}i(mD,"buildSessionData");function pD(e,t,n,r){return{_type:"meta",title:t.title,id:e,gitRoot:t.gitRoot,runtimeInfo:t.runtimeInfo?{...t.runtimeInfo}:void 0,createdAt:r??new Date().toISOString(),scope:t.scope??"user",uiHistory:t.uiHistory,errorMetadata:t.errorMetadata,extensionState:t.extensionState,extensionRecordCount:t.extensionRecords?.length??0,artifactLedgerCount:t.artifactLedger?.length??0,lineageVersion:n?.version,activeEntryId:n?.activeEntryId,lineageEntryCount:n?.entries.length??0,activeMessageCount:n?yo(n):t.messages.length}}i(pD,"createSessionMeta");async function gD(e){if(!uf.existsSync(e))return null;let n=(await Nn.readFile(e,"utf-8")).trim();if(!n)return null;let r={legacyMessages:[],lineageEntries:[],artifactLedger:[],extensionRecords:[],malformedCount:0},o=n.split(`
486
- `);for(let s=0;s<o.length;s+=1)try{let a=JSON.parse(o[s]);if(s===0&&St(a)&&a._type==="meta"){r.meta=a;continue}if(oD(a)){r.meta&&(a.title!==void 0&&(r.meta.title=a.title),a.activeEntryId!==void 0&&(r.meta.activeEntryId=a.activeEntryId),a.activeMessageCount!==void 0&&(r.meta.activeMessageCount=a.activeMessageCount),a.uiHistory!==void 0&&(r.meta.uiHistory=a.uiHistory),a.scope!==void 0&&(r.meta.scope=a.scope));continue}if(cD(a)){r.lineageEntries.push(a.entry);continue}if(uD(a)){r.artifactLedger.push(a.entry);continue}if(iD(a)){r.extensionRecords.push({id:a.id,extensionId:a.extensionId,type:a.type,ts:a.ts,data:a.data,dedupeKey:a.dedupeKey});continue}if(Th(a)){r.legacyMessages.push(a);continue}r.malformedCount+=1}catch{r.malformedCount+=1}return r}i(gD,"readPersistedSessionFile");var to=class{static{i(this,"FileSessionStorage")}sessionsDir;constructor(t){this.sessionsDir=t?.sessionsDir??pa}writeQueues=new Map;serializedWrite(t,n){let o=(this.writeQueues.get(t)??Promise.resolve()).then(n,()=>n());return this.writeQueues.set(t,o),o}appendState=new Map;syncAppendState(t,n,r){let o=this.appendState.get(t);this.appendState.set(t,{lineageCount:n.lineage?.entries.length??o?.lineageCount??0,artifactCount:n.artifactLedger?.length??o?.artifactCount??0,extensionCount:n.extensionRecords?.length??o?.extensionCount??0,metaUpdateCount:r??o?.metaUpdateCount??0})}getSessionFilePath(t){return df.join(this.sessionsDir,`${t}.jsonl`)}getArchiveFilePath(t){return df.join(this.sessionsDir,`${t}.archive.jsonl`)}async readSession(t){let n=this.getSessionFilePath(t),r=await gD(n);return r?(B0(n,r.malformedCount),mD(r)):null}async writeSessionInternal(t,n,r){await Nn.mkdir(this.sessionsDir,{recursive:!0});let o=this.getSessionFilePath(t),s=`${o}.${process.pid}.${Date.now()}.tmp`,a=n.lineage??hn(n.messages),c=pD(t,n,a,r);try{let l=await Nn.open(s,"w");try{await l.write(JSON.stringify(c)+`
487
- `);for(let d of a.entries)await l.write(JSON.stringify(F0(d))+`
488
- `);for(let d of n.artifactLedger??[])await l.write(JSON.stringify(W0(d))+`
489
- `);for(let d of n.extensionRecords??[])await l.write(JSON.stringify(H0(d))+`
490
- `)}finally{await l.close()}await Nn.rename(s,o)}finally{uf.existsSync(s)&&await Nn.unlink(s).catch(()=>{})}}async mergeAndWriteInternal(t,n){let r=await this.readSession(t),o={...n,scope:n.scope??r?.data.scope??"user",uiHistory:n.uiHistory??r?.data.uiHistory,extensionState:n.extensionState??r?.data.extensionState,artifactLedger:n.artifactLedger??r?.data.artifactLedger,extensionRecords:n.extensionRecords??r?.data.extensionRecords,runtimeInfo:n.runtimeInfo??r?.data.runtimeInfo,errorMetadata:n.errorMetadata??r?.data.errorMetadata,lineage:n.lineage??hn(n.messages,r?.data.lineage)};await this.writeSessionInternal(t,o,r?.createdAt),this.syncAppendState(t,o)}async appendSessionDelta(t,n){let r=this.getSessionFilePath(t);if(!uf.existsSync(r)||!n.lineage){await this.save(t,n);return}await this.serializedWrite(t,async()=>{let s=this.appendState.get(t);if(!s){await this.mergeAndWriteInternal(t,n);return}if(n.lineage.entries.length<s.lineageCount||(n.artifactLedger?.length??0)<s.artifactCount){await this.mergeAndWriteInternal(t,n);return}let a=n.lineage.entries.slice(s.lineageCount),c=(n.artifactLedger??[]).slice(s.artifactCount),l=(n.extensionRecords??[]).slice(s.extensionCount),d=[];for(let p of a)d.push(JSON.stringify(F0(p)));for(let p of c)d.push(JSON.stringify(W0(p)));for(let p of l)d.push(JSON.stringify(H0(p)));let m={_type:"meta_update",title:n.title,activeEntryId:n.lineage.activeEntryId,activeMessageCount:yo(n.lineage),...n.uiHistory!==void 0?{uiHistory:n.uiHistory}:{},...n.scope!==void 0?{scope:n.scope}:{}};d.push(JSON.stringify(m)),d.length>0&&await Nn.appendFile(r,`
491
- `+d.join(`
492
- `),"utf-8"),this.syncAppendState(t,n,s.metaUpdateCount+1)});let o=this.appendState.get(t);o&&this.shouldRunMaintenance(o)&&this.runMaintenance(t).catch(s=>{process.stderr.write(`[KodaX] Archive maintenance failed: ${String(s)}
493
- `)})}shouldRunMaintenance(t){return t.metaUpdateCount>=50||t.lineageCount>500}async runMaintenance(t){await this.serializedWrite(t,async()=>{let n=await this.readSession(t);if(!n?.data.lineage)return;let{slimmedLineage:r,archivedEntries:o,archiveBatchId:s}=ox(n.data.lineage);if(o.length===0){await this.writeSessionInternal(t,n.data,n.createdAt),this.syncAppendState(t,n.data,0);return}let a=this.getArchiveFilePath(t),c=await Nn.open(a,"a");try{await c.write(JSON.stringify({_type:"archive_batch",archiveBatchId:s,sessionId:t,archivedAt:new Date().toISOString(),entryCount:o.length})+`
494
- `);for(let d of o)await c.write(JSON.stringify({_type:"archived_entry",archiveBatchId:s,entry:d})+`
495
- `)}finally{await c.close()}let l={...n.data,lineage:r};await this.writeSessionInternal(t,l,n.createdAt),this.syncAppendState(t,l,0)})}async save(t,n){await this.serializedWrite(t,async()=>{await this.mergeAndWriteInternal(t,n)})}async load(t){let n=await this.readSession(t);if(!n)return null;this.syncAppendState(t,n.data);let{data:r,createdAt:o}=n,s=this.getSessionFilePath(t),a=await wo(),c=await is(),l=Va(r);if((c.canonicalRepoRoot&&l?.canonicalRepoRoot&&!Fu(c,l)||a&&r.gitRoot&&a!==r.gitRoot&&!Fu(c,{canonicalRepoRoot:r.gitRoot}))&&(eo(N0.yellow(`
496
- [Warning] Session project mismatch:`)),c.workspaceRoot&&eo(` Current workspace: ${c.workspaceRoot}`),l?.workspaceRoot&&eo(` Session workspace: ${l.workspaceRoot}`),c.canonicalRepoRoot&&eo(` Current repo: ${c.canonicalRepoRoot}`),l?.canonicalRepoRoot?eo(` Session repo: ${l.canonicalRepoRoot}`):r.gitRoot&&eo(` Session repo: ${r.gitRoot}`),eo(` Continuing anyway...
497
- `)),r.errorMetadata?.consecutiveErrors&&r.errorMetadata.consecutiveErrors>0){let m=zy(r.messages);if(m!==r.messages){eo(N0.cyan("[Session Recovery] Cleaned incomplete tool calls from previous session"));let p={...r,messages:m,errorMetadata:{...r.errorMetadata,consecutiveErrors:0},lineage:hn(m,r.lineage)};return await this.serializedWrite(t,async()=>{await this.writeSessionInternal(t,p,o),this.syncAppendState(t,p)}),p}}return B0(s,0),r}async getLineage(t){return(await this.readSession(t))?.data.lineage??null}async setActiveEntry(t,n,r){let o=null;return await this.serializedWrite(t,async()=>{let s=await this.readSession(t);if(!s?.data.lineage)return;let a=Ci(s.data.lineage,n,r);if(!a)return;let c={...s.data,messages:Et(a),lineage:a};await this.writeSessionInternal(t,c,s.createdAt),this.syncAppendState(t,c),o=c}),o}async rewind(t,n){let r=null;return await this.serializedWrite(t,async()=>{let o=await this.readSession(t);if(!o?.data.lineage)return;let s=n??vi(o.data.lineage);if(!s)return;let a=Ii(o.data.lineage,s);if(!a)return;let c={...o.data,messages:Et(a),lineage:a};await this.writeSessionInternal(t,c,o.createdAt),this.syncAppendState(t,c),r=c}),r}async setLabel(t,n,r){let o=null;return await this.serializedWrite(t,async()=>{let s=await this.readSession(t);if(!s?.data.lineage)return;let a=bi(s.data.lineage,n,r);if(!a)return;let c={...s.data,lineage:a};await this.writeSessionInternal(t,c,s.createdAt),this.syncAppendState(t,c),o=c}),o}async fork(t,n,r){let o=null;return await this.serializedWrite(t,async()=>{let s=await this.readSession(t);if(!s?.data.lineage)return;let a=ki(s.data.lineage,n);if(!a)return;let c=r?.sessionId??await Ti(),l={messages:Et(a),title:r?.title??s.data.title,gitRoot:s.data.gitRoot,uiHistory:s.data.uiHistory?s.data.uiHistory.map(d=>({...d})):void 0,extensionState:s.data.extensionState?structuredClone(s.data.extensionState):void 0,artifactLedger:s.data.artifactLedger?structuredClone(s.data.artifactLedger):void 0,extensionRecords:s.data.extensionRecords?structuredClone(s.data.extensionRecords):void 0,lineage:a};await this.writeSessionInternal(c,l),o={sessionId:c,data:l}}),o}async list(t){await Nn.mkdir(this.sessionsDir,{recursive:!0});let n=t??await wo(),r=await is({cwd:n??process.cwd()}),o=(await Nn.readdir(this.sessionsDir)).filter(a=>a.endsWith(".jsonl")),s=[];for(let a of o)try{let c=(await Nn.readFile(df.join(this.sessionsDir,a),"utf-8")).trim(),l=c.split(`
498
- `)[0];if(!l)continue;let d=JSON.parse(l);if(St(d)&&d._type==="meta"){let m=typeof d.gitRoot=="string"?d.gitRoot:"",p=j0(d.runtimeInfo)?d.runtimeInfo:void 0,g=d.scope==="managed-task-worker"?"managed-task-worker":"user";if(n){let w=Fu(r,p),v=p?.workspaceRoot?U0(p.workspaceRoot,r.workspaceRoot??""):U0(m,n);if(!w&&!v)continue}if(g!=="user")continue;let x=c.split(`
499
- `).length,y=typeof d.extensionRecordCount=="number"&&d.extensionRecordCount>0?d.extensionRecordCount:0,T=typeof d.activeMessageCount=="number"&&d.activeMessageCount>=0?d.activeMessageCount:Math.max(0,x-1-y);s.push({id:a.replace(".jsonl",""),title:typeof d.title=="string"?d.title:"",msgCount:T,createdAt:typeof d.createdAt=="string"?d.createdAt:void 0,runtimeInfo:p?{...p}:void 0})}else{let m=c.split(`
500
- `).length;s.push({id:a.replace(".jsonl",""),title:"",msgCount:m})}}catch{continue}return s.sort((a,c)=>{let l=a.createdAt?Date.parse(a.createdAt):Number.NaN,d=c.createdAt?Date.parse(c.createdAt):Number.NaN;return Number.isFinite(l)&&Number.isFinite(d)&&l!==d?d-l:Number.isFinite(d)&&!Number.isFinite(l)?1:Number.isFinite(l)&&!Number.isFinite(d)?-1:c.id.localeCompare(a.id)}).slice(0,10).map(({id:a,title:c,msgCount:l,runtimeInfo:d})=>d?{id:a,title:c,msgCount:l,runtimeInfo:d}:{id:a,title:c,msgCount:l})}async delete(t){let n=this.getSessionFilePath(t);uf.existsSync(n)&&await Nn.unlink(n)}async deleteAll(t){let n=t??await wo(),r=await this.list(n??void 0);for(let o of r)await this.delete(o.id)}};import Rc from"node:fs";import bh from"node:fs/promises";import G0 from"node:path";function As(e){return e!==void 0?new to({sessionsDir:e}):new to}i(As,"getStorage");function K0(e){return e??pa}i(K0,"resolveSessionsDir");async function V0(e){return z0(e,void 0)}i(V0,"listSessions");async function z0(e,t){try{let n=K0(t),r=e?.projectRoot,o=As(t);await bh.mkdir(n,{recursive:!0});let s=e?.scope??"user",a=e?.includeArchived??!1,c=e?.limit??50,l=e?.before?Date.parse(e.before):void 0;if(s==="user"&&!r&&l===void 0&&!a)return(await o.list(r)).slice(0,c).map(hD);let d=(await bh.readdir(n)).filter(p=>p.endsWith(".jsonl")&&(a||!p.startsWith("archived-"))),m=[];for(let p of d)try{let g=(await bh.readFile(G0.join(n,p),"utf-8")).trim(),x=g.split(`
501
- `)[0];if(!x)continue;let y=JSON.parse(x);if(y===null||typeof y!="object"||y._type!=="meta")continue;let T=y,w=T.scope==="managed-task-worker"?"managed-task-worker":"user";if(s==="user"&&w!=="user"||s==="managed-task-worker"&&w!=="managed-task-worker")continue;let v=typeof T.createdAt=="string"?T.createdAt:void 0;if(l!==void 0&&v!==void 0){let I=Date.parse(v);if(!Number.isNaN(I)&&I>=l)continue}let O=g.split(`
502
- `).length,P=typeof T.extensionRecordCount=="number"&&T.extensionRecordCount>0?T.extensionRecordCount:0,D=typeof T.activeMessageCount=="number"&&T.activeMessageCount>=0?T.activeMessageCount:Math.max(0,O-1-P),L=T.runtimeInfo!==null&&typeof T.runtimeInfo=="object"?X0(T.runtimeInfo):void 0,X=typeof T.gitRoot=="string"?T.gitRoot:void 0;m.push({id:p.replace(".jsonl",""),title:typeof T.title=="string"?T.title:"",msgCount:D,createdAt:v,runtimeInfo:L??(X?{gitRoot:X}:void 0),_createdAtMs:v?Date.parse(v):void 0})}catch{continue}return m.sort((p,g)=>{let x=p._createdAtMs,y=g._createdAtMs;return Number.isFinite(x)&&Number.isFinite(y)&&x!==y?y-x:Number.isFinite(y)&&!Number.isFinite(x)?1:Number.isFinite(x)&&!Number.isFinite(y)?-1:g.id.localeCompare(p.id)}),m.slice(0,c).map(({id:p,title:g,msgCount:x,createdAt:y,runtimeInfo:T})=>({id:p,title:g,msgCount:x,...y!==void 0?{createdAt:y}:{},...T!==void 0?{runtimeInfo:T}:{}}))}catch{return[]}}i(z0,"listSessionsImpl");function X0(e){if(!(!e.workspaceRoot&&!e.canonicalRepoRoot))return{...e.workspaceRoot?{workspaceRoot:e.workspaceRoot}:{},...e.canonicalRepoRoot?{gitRoot:e.canonicalRepoRoot}:{}}}i(X0,"extractRuntimeInfoSummary");function hD(e){let t=e.runtimeInfo?X0(e.runtimeInfo):void 0;return{id:e.id,title:e.title,msgCount:e.msgCount,...t!==void 0?{runtimeInfo:t}:{}}}i(hD,"toSessionSummary");async function Y0(e){return q0(e,void 0)}i(Y0,"loadSession");async function q0(e,t){try{return await As(t).load(e)}catch{return null}}i(q0,"loadSessionImpl");async function Q0(e,t){return J0(e,t,void 0)}i(Q0,"forkSession");async function J0(e,t,n){try{return await As(n).fork(e,t?.selector,{sessionId:t?.sessionId,title:t?.title})}catch{return null}}i(J0,"forkSessionImpl");async function Z0(e,t){return eI(e,t,void 0)}i(Z0,"rewindSession");async function eI(e,t,n){try{return await As(n).rewind(e,t?.selector)}catch{return null}}i(eI,"rewindSessionImpl");async function tI(e,t){return nI(e,t,void 0)}i(tI,"setActiveEntry");async function nI(e,t,n){try{return await As(n).setActiveEntry(e,t)}catch{return null}}i(nI,"setActiveEntryImpl");async function ff(){try{return Vy({excludePid:process.pid}).map(t=>({pid:t.pid,startedAt:t.state.meta.startedAt,cwd:t.state.meta.cwd,sessionId:t.state.sessionId}))}catch{return[]}}i(ff,"listRunningSessions");async function rI(e){return oI(e,void 0)}i(rI,"deleteSession");async function oI(e,t){try{let r=(await ff()).find(o=>o.sessionId===e);return r?{error:{code:"session_running",runningProcess:{pid:r.pid,startedAt:r.startedAt}}}:(await As(t).delete(e),{ok:!0})}catch{return{ok:!0}}}i(oI,"deleteSessionImpl");function iI(e){return sI(e,void 0)}i(iI,"watchSessions");function sI(e,t){let n=K0(t);return process.platform==="win32"?SD(e,n):xD(e,n)}i(sI,"watchSessionsImpl");function yD(e){return e.endsWith(".jsonl")?e.slice(0,-6):null}i(yD,"sessionIdFromFilename");function xD(e,t){let n=null,r=!1,o=new Map;function s(c,l){let d=o.get(l);d!==void 0&&clearTimeout(d);let m=setTimeout(()=>{o.delete(l),r||e({kind:c,sessionId:l})},100);o.set(l,m)}i(s,"emitDebounced");function a(){if(!r)try{if(!Rc.existsSync(t)){setTimeout(a,1e3);return}n=Rc.watch(t,(c,l)=>{if(!l)return;let d=yD(l);if(!d)return;let m=c==="rename"?wD(t,l):"change";s(m,d)}),n.on("error",()=>{n?.close(),n=null,r||setTimeout(a,1e3)})}catch{}}return i(a,"startWatch"),a(),{close(){r=!0,n?.close(),n=null;for(let c of o.values())clearTimeout(c);o.clear()}}}i(xD,"watchSessionsPosix");function wD(e,t){try{return Rc.statSync(G0.join(e,t)),"add"}catch{return"remove"}}i(wD,"detectRenameKind");function SD(e,t){let n=!1,r=new Set;function o(){try{return Rc.existsSync(t)?new Set(Rc.readdirSync(t).filter(a=>a.endsWith(".jsonl")).map(a=>a.slice(0,-6))):new Set}catch{return new Set}}i(o,"buildSnapshot"),r=o();let s=setInterval(()=>{if(n)return;let a=o();for(let c of a)r.has(c)||e({kind:"add",sessionId:c});for(let c of r)a.has(c)||e({kind:"remove",sessionId:c});r=a},1e3);return{close(){n=!0,clearInterval(s)}}}i(SD,"watchSessionsWindows");function TD(e){let t=e?.sessionsDir,n=t!==void 0?new to({sessionsDir:t}):new to;return t===void 0?{listSessions:V0,loadSession:Y0,forkSession:Q0,rewindSession:Z0,setActiveEntry:tI,deleteSession:rI,listRunningSessions:ff,watchSessions:iI,storage:n}:{listSessions:i(r=>z0(r,t),"listSessions"),loadSession:i(r=>q0(r,t),"loadSession"),forkSession:i((r,o)=>J0(r,o,t),"forkSession"),rewindSession:i((r,o)=>eI(r,o,t),"rewindSession"),setActiveEntry:i((r,o)=>nI(r,o,t),"setActiveEntry"),deleteSession:i(r=>oI(r,t),"deleteSession"),listRunningSessions:ff,watchSessions:i(r=>sI(r,t),"watchSessions"),storage:n}}i(TD,"createSessionManager");export{Mi as a,Ai as b,ha as c,_i as d,ya as e,mm as f,So as g,To as h,Pi as i,Co as j,Nl as k,bo as l,$i as m,Bl as n,Hl as o,Li as p,rn as q,zn as r,Xn as s,YI as t,Vt as u,xa as v,hm as w,ym as x,zt as y,xm as z,wm as A,Dx as B,Nx as C,ne as D,ND as E,Jm as F,aM as G,xu as H,Pa as I,mS as J,fM as K,mM as L,on as M,$ as N,OW as O,Nt as P,ep as Q,np as R,wu as S,rp as T,hS as U,$a as V,Zi as W,Mo as X,op as Y,Qn as Z,$n as _,Ln as $,Gr as aa,Iu as ba,Jn as ca,Ru as da,_o as ea,gp as fa,Tr as ga,Wa as ha,ns as ia,dA as ja,Ip as ka,as as la,cs as ma,Bp as na,Bo as oa,Vu as pa,Hp as qa,Qa as ra,Wp as sa,us as ta,z_ as ua,vn as va,FT as wa,WT as xa,eP as ya,tP as za,HP as Aa,Wo as Ba,UP as Ca,gs as Da,c$ as Ea,u$ as Fa,d$ as Ga,sg as Ha,ag as Ia,m$ as Ja,lg as Ka,ug as La,wd as Ma,Sd as Na,Td as Oa,fg as Pa,Cd as Qa,mg as Ra,pg as Sa,bd as Ta,oc as Ua,ic as Va,EC as Wa,Id as Xa,hg as Ya,xg as Za,Sg as _a,kd as $a,Tg as ab,Rd as bb,Ed as cb,Ig as db,Md as eb,cc as fb,lc as gb,jC as hb,W$ as ib,U$ as jb,KC as kb,V$ as lb,z$ as mb,uc as nb,rr as ob,fc as pb,Ss as qb,X$ as rb,Pd as sb,Q$ as tb,J$ as ub,$d as vb,Eg as wb,Ld as xb,Mg as yb,fh as zb,sO as Ab,cO as Bb,hO as Cb,l0 as Db,u0 as Eb,yO as Fb,wO as Gb,Qd as Hb,p0 as Ib,Ir as Jb,g0 as Kb,h0 as Lb,y0 as Mb,CO as Nb,Tc as Ob,bO as Pb,vO as Qb,HO as Rb,wh as Sb,KO as Tb,VO as Ub,zO as Vb,XO as Wb,qO as Xb,QO as Yb,JO as Zb,ZO as _b,_0 as $b,to as ac,V0 as bc,Y0 as cc,Q0 as dc,Z0 as ec,tI as fc,ff as gc,rI as hc,iI as ic,TD as jc};