@kodax-ai/kodax 0.7.42 → 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.
- package/CHANGELOG.md +65 -6
- package/README.md +87 -56
- package/README_CN.md +46 -25
- package/dist/chunks/chunk-35BDEEC5.js +2 -0
- package/dist/chunks/chunk-4YPL2UVZ.js +848 -0
- package/dist/chunks/chunk-DI2G3YWL.js +31 -0
- package/dist/chunks/chunk-HHQ7YTGM.js +425 -0
- package/dist/chunks/chunk-QHILHQBB.js +519 -0
- package/dist/chunks/{chunk-IYJ5EPRV.js → chunk-RUDYNAK7.js} +1 -1
- package/dist/chunks/compaction-config-NAPRF7XR.js +2 -0
- package/dist/chunks/{construction-bootstrap-J2WOCYEK.js → construction-bootstrap-PHTGBRNU.js} +4 -4
- package/dist/chunks/dist-CCYBJJZY.js +2 -0
- package/dist/chunks/dist-RHIHZAYX.js +2 -0
- package/dist/chunks/utils-TV3UYCHQ.js +2 -0
- package/dist/index.d.ts +11 -11
- package/dist/index.js +2 -2
- package/dist/kodax_cli.js +1159 -1102
- package/dist/provider-capabilities.json +167 -0
- package/dist/sdk-agent.d.ts +905 -48
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +995 -755
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-llm.d.ts +5 -3
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.d.ts +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-repl.d.ts +10 -9
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-session.d.ts +23 -11
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/types-chunks/{cost-tracker.d-B6vMoLLF.d.ts → base.d-FUJahC0i.d.ts} +2 -110
- package/dist/types-chunks/{bash-prefix-extractor.d-CkhaqKkg.d.ts → bash-prefix-extractor.d-DdoSeghD.d.ts} +442 -131
- package/dist/types-chunks/cost-tracker.d-wRtyEW9d.d.ts +110 -0
- package/dist/types-chunks/file-tracker.d-DOfaoCbJ.d.ts +633 -0
- package/dist/types-chunks/manager.d-87belpiS.d.ts +370 -0
- package/dist/types-chunks/{resolver.d-DX9au4NJ.d.ts → resolver.d-B7ZnVuuf.d.ts} +157 -10
- package/dist/types-chunks/{session-storage.d-Cci897iM.d.ts → storage.d-DFD9ln5c.d.ts} +49 -2
- package/dist/types-chunks/{history-cleanup.d-DznrzEiU.d.ts → types.d-DM8zEJgF.d.ts} +1084 -282
- package/dist/types-chunks/{types.d-mM8vqvhT.d.ts → types.d-HBbWT-iA.d.ts} +41 -3
- package/dist/types-chunks/{storage.d-Bc5DoAwp.d.ts → utils.d-C5fzCE9W.d.ts} +25 -47
- package/package.json +7 -6
- package/dist/chunks/chunk-3RKBXWZS.js +0 -2
- package/dist/chunks/chunk-7JLYVWAF.js +0 -1033
- package/dist/chunks/chunk-CD3R5YBH.js +0 -16
- package/dist/chunks/chunk-DKXUY5F2.js +0 -209
- package/dist/chunks/chunk-HMYEQJGT.js +0 -31
- package/dist/chunks/chunk-KUX5LRPP.js +0 -2
- package/dist/chunks/chunk-OWSKU55I.js +0 -13
- package/dist/chunks/chunk-ZZ4KRK2B.js +0 -465
- package/dist/chunks/compaction-config-FIFFP4FT.js +0 -2
- package/dist/chunks/dist-2ZHWDXMQ.js +0 -2
- package/dist/chunks/dist-W4CJWLIH.js +0 -2
- package/dist/chunks/utils-A5MWDTWZ.js +0 -2
- package/dist/types-chunks/instance-discovery.d-BsKnIwpg.d.ts +0 -990
- package/dist/types-chunks/transport.d-DuyjG30t.d.ts +0 -180
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{A as Ox,B as Dx,C as Nx,a as te,c as ha,j as Mi,k as Xn,l as Ai,m as wr,n as Px,o as Lx,p as Nl,q as fm,r as Bl,s as mm,t as pm,u as gm,w as ya,x as hm,y as xo,z as Sr}from"./chunk-35BDEEC5.js";import{a as Hl}from"./chunk-RUDYNAK7.js";import{n as Bx,o as Hx,p as Fx}from"./chunk-EVIDQWMF.js";import{$ as mx,$b as bx,Ba as hx,Db as Ol,Ga as yx,Gb as Sx,Ia as xx,Ib as Tx,Ja as wx,Kb as Cx,Ma as um,P as dx,Q as Ll,S as pa,T as fx,Vd as $x,Yc as kx,Yd as Dl,Zc as ga,c as sm,d as fa,e as Yy,g as cm,id as Rx,jd as Ex,ld as dm,md as Mx,nd as Ax,qa as px,ra as lm,sa as gx,uc as vx,vc as Ix,yb as yo,zd as _x}from"./chunk-4YPL2UVZ.js";import{Q as _l,aa as zy,ca as im,da as Xy,j as pr,qa as gr,ra as wi,sa as Si}from"./chunk-DI2G3YWL.js";import{$b as Ci,Bb as ox,Bc as am,Cb as rx,Cc as ma,Db as ix,Mc as ux,Qb as ho,Ra as qy,Rb as yr,Wa as $l,Wb as sx,Ya as Qy,ab as Jy,bb as Zy,cb as ex,db as tx,fb as nx,hc as xn,jc as Mt,k as hr,lc as bi,mc as vi,nc as ax,pc as Ii,qc as ki,rc as Ri,sc as Pl,tc as xr,uc as cx,va as Ti,wa as hn,wc as Ei,xc as lx,za as yn}from"./chunk-HHQ7YTGM.js";import{a as i,b as rm,c as ek}from"./chunk-V4WSBIXB.js";var _S=rm((uU,AS)=>{"use strict";AS.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 BS=rm((fU,NS)=>{"use strict";var DS="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",$S=new RegExp("^"+DS+"$"),PS="|&;()<> \\t",_M='"((\\\\"|[^"])*?)"',$M="'((\\\\'|[^'])*?)'",PM=/^#$/,LS="'",OS='"',lp="$",_r="",LM=4294967296;for(up=0;up<4;up++)_r+=(LM*Math.random()).toString(16);var up,OM=new RegExp("^"+_r);function DM(e,t){for(var n=t.lastIndex,o=[],r;r=t.exec(e);)o.push(r),t.lastIndex===r.index&&(t.lastIndex+=1);return t.lastIndex=n,o}i(DM,"matchAll");function NM(e,t,n){var o=typeof e=="function"?e(n):e[n];return typeof o>"u"&&n!=""?o="":typeof o>"u"&&(o="$"),typeof o=="object"?t+_r+JSON.stringify(o)+_r:t+o}i(NM,"getVar");function BM(e,t,n){n||(n={});var o=n.escape||"\\",r="(\\"+o+`['"`+PS+`]|[^\\s'"`+PS+"])+",s=new RegExp(["("+DS+")","("+r+"|"+_M+"|"+$M+")+"].join("|"),"g"),a=DM(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($S.test(d))return{op:d};var m=!1,p=!1,g="",x=!1,y;function T(){y+=1;var O,$,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));$=d.slice(y,O),y=O}else if(/[*@#?$!_-]/.test(D))$=D,y+=1;else{var L=d.slice(y);O=L.match(/[^\w\d_]/),O?($=L.slice(0,O.index),y+=O.index-1):($=L,y=d.length)}return NM(t,"",$)}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==LS?g+=w:w===o?(y+=1,w=d.charAt(y),w===OS||w===o||w===lp?g+=w:g+=o+w):w===lp?g+=T():g+=w;else if(w===OS||w===LS)m=w;else{if($S.test(w))return{op:d};if(PM.test(w)){c=!0;var I={comment:e.slice(l.index+y+1)};return g.length?[g,I]:[I]}else w===o?p=!0:w===lp?g+=T():g+=w}}return x?{op:"glob",pattern:g}:g}).reduce(function(l,d){return typeof d>"u"?l:l.concat(d)},[])}i(BM,"parseInternal");NS.exports=i(function(t,n,o){var r=BM(t,n,o);return typeof n!="function"?r:r.reduce(function(s,a){if(typeof a=="object")return s.concat(a);var c=a.split(RegExp("("+_r+".*?"+_r+")","g"));return c.length===1?s.concat(c[0]):s.concat(c.filter(Boolean).map(function(l){return OM.test(l)?JSON.parse(l.split(_r)[1]):l}))},[])},"parse")});var HS=rm(dp=>{"use strict";dp.quote=_S();dp.parse=BS()});import{spawnSync as tk}from"node:child_process";function Fl(e){return e==="1"||e?.toLowerCase()==="true"}i(Fl,"isTruthyEnv");function Wx(e){return e==="0"||e?.toLowerCase()==="false"}i(Wx,"isFalseyEnv");function _i(e=process.env){return e.TERM_PROGRAM?.toLowerCase()==="vscode"||!!e.VSCODE_GIT_IPC_HANDLE||!!e.VSCODE_INJECTION}i(_i,"isVsCodeTerminalHostEnv");function $i(e={}){let t=e.env??process.env;return(e.platform??process.platform)==="win32"||!!t.WT_SESSION}i($i,"hasCursorUpViewportYankRisk");function nk(e){return!!(e.SSH_CONNECTION||e.SSH_CLIENT||e.SSH_TTY)}i(nk,"isSshSession");function xa(e={}){let t=e.env??process.env;return Fl(t.KODAX_FULLSCREEN)?!1:(e.platform??process.platform)==="win32"&&nk(t)}i(xa,"isRemoteConptyHost");function Pi(e={}){let t=e.env??process.env;return $i(e)||_i(t)}i(Pi,"hasMainScreenRenderScrollRisk");function ok(e){if(!e.TMUX||e.TERM_PROGRAM!=="iTerm.app")return!1;let t=e.TERM??"";return!t.startsWith("screen")&&!t.startsWith("tmux")}i(ok,"isTmuxControlModeEnvHeuristic");var wo;function wa(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(ok(t))return!0;if(!(t===process.env&&n===process.platform))return!1;if(wo!==void 0||(wo=!1,!t.TMUX)||t.TERM_PROGRAM&&t.TERM_PROGRAM!=="iTerm.app")return wo;try{let r=tk("tmux",["display-message","-p","#{client_control_mode}"],{encoding:"utf8",timeout:2e3});r.status===0&&(wo=r.stdout.trim()==="1")}catch{wo=!1}return wo}i(wa,"isTmuxControlMode");function ym(){wo=void 0}i(ym,"resetTmuxControlModeProbeForTesting");function Tr(e={}){let t=e.env??process.env,n=e.isTTY??process.stdout.isTTY===!0,o=e.rawModeSupported??(process.stdin.isTTY===!0&&typeof process.stdin.setRawMode=="function");return!n||!o||t.TERM==="dumb"||t.CI==="true"?"unsupported_control_host":wa(e)?"tmux_control_mode":_i(t)?"xtermjs_host":xa(e)?"remote_conpty_host":$i(e)?"degraded_vt":"native_vt"}i(Tr,"detectTerminalRenderHost");var Cr=Tr;function Li(e={}){let t=e.env??process.env;if(Fl(t.KODAX_FORCE_INK))return"legacy";let n=t.KODAX_TUI_RENDERER?.trim().toLowerCase();return n==="legacy"||n==="owned"||n==="auto"?n:"auto"}i(Li,"resolveConfiguredTuiRendererMode");function br(e={}){let t=Li(e);if(t==="legacy"||t==="owned")return t;let n=Tr(e);return n==="unsupported_control_host"||n==="tmux_control_mode"?"legacy":"owned"}i(br,"resolveEffectiveTuiRendererMode");function Wl(e={}){let t=e.env??process.env;if(Fl(t.KODAX_FORCE_CLASSIC_REPL))return"classic";let n=Li({env:t});if(n==="legacy"||n==="owned")return"ink";let o=Tr(e);return o==="unsupported_control_host"||o==="tmux_control_mode"?"classic":"ink"}i(Wl,"resolveInteractiveSurfacePreference");var Ux={enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!0};function vr(e,t="owned",n={}){let o=n.env??process.env;return Wx(o.KODAX_FULLSCREEN)?Ux:rk(e,t)}i(vr,"resolveFullscreenPolicy");function rk(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 Ux;default:return{enabled:!1,promptShell:"main-screen",transcriptShell:"main-screen",mouseWheel:!1,mouseClicks:!1,streamingPreview:!1,transcriptSpinnerAnimation:!1}}}i(rk,"buildFullscreenPolicy");function Oi(e,t={}){let n=t.rendererMode??"owned",o=vr(e,n,{env:t.env}),r=e!=="unsupported_control_host"&&e!=="tmux_control_mode";return{profile:e,ownsViewportByDefault:o.enabled&&o.promptShell==="virtual",supportsMouseTracking:o.mouseWheel||o.mouseClicks,bufferingMode:o.streamingPreview?"live":"buffered-fallback",supportsFullscreenLayout:o.enabled,supportsOverlaySurface:o.enabled,supportsSelection:r,supportsCopyOnSelect:!1,supportsWheelHistory:o.mouseWheel,supportsViewportChrome:o.enabled,supportsSearchViewport:o.enabled,supportsStickyPrompt:o.enabled}}i(Oi,"getTerminalHostCapabilities");function Ul(e={}){return br(e)==="owned"}i(Ul,"isOwnedRendererPreferred");function jl(e={}){let t=e.env??process.env;return Fl(t.KODAX_FORCE_CLASSIC_REPL)&&!Wx(t.KODAX_FORCE_CLASSIC_REPL)}i(jl,"isClassicReplForced");var Di=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 o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}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}},xm=1,wm=2,ik=1e3,jx;function Gl(){if(!(typeof Intl>"u"||typeof Intl.Segmenter!="function"))return jx??=new Intl.Segmenter("en",{granularity:"grapheme"}),jx}i(Gl,"getGraphemeSegmenter");function rn(e){if(!e)return 0;let t=Gl();if(t){let n=0;for(let o of t.segment(e))n++;return n}return[...e].length}i(rn,"getCodePointLength");function Yn(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(Yn,"isWideChar");function qn(e){if(!e)return 0;let t=0,n=Gl();if(n)for(let o of n.segment(e))t+=Yn(o.segment)?wm:xm;else for(let o of e)t+=Yn(o)?wm:xm;return t}i(qn,"getVisualWidth");function sk(e,t){if(!e||t<0)return"";let n=Gl();if(n){let r=0;for(let s of n.segment(e)){if(r===t)return s.segment;r++}return""}let o=[...e];return t>=o.length?"":o[t]}i(sk,"getCharAtCodePoint");function zt(e){if(!e)return[];let t=Gl();if(t){let n=[];for(let o of t.segment(e))n.push(o.segment);return n}return[...e]}i(zt,"splitByCodePoints");function ak(e,t,n){return zt(e).slice(t,n).join("")}i(ak,"sliceByCodePoints");function Gx(e,t){let n=Math.max(0,t),o=zt(e),r=0,s=0;for(;r<o.length;){let a=Yn(o[r])?wm:xm;if(s+a>n)break;s+=a,r++}return{before:o.slice(0,r).join(""),current:o[r]??"",after:o.slice(r+1).join("")}}i(Gx,"splitAtVisualColumn");function Sa(e,t,n=!1){if(!e||t<=0)return"";let o="\u2026",s=n?t-1:t,a="",c=0,l=zt(e);for(let d of l){let m=Yn(d)?2:1;if(c+m>s)break;a+=d,c+=m}return n&&a.length<e.length&&(a+=o),a}i(Sa,"truncateByVisualWidth");var Sm=new Di(ik);function Tm(e){let t=Sm.get(e);if(t!==void 0)return t;let n=qn(e);return Sm.set(e,n),n}i(Tm,"getVisualWidthCached");function Xt(e,t,n,o){let r=[],s=[],a=[];for(let c=0;c<e.length;c++){let l=e[c]||"";if(s[c]=[],l.length===0){r.push("");let p=r.length-1;s[c].push([p,0]),a.push([c,0]);continue}let d=0,m=zt(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],I=Yn(w)?2:1;if(g+I>t){y>=0&&T-d>0?(p=m.slice(d,y).join(""),g=m.slice(d,y).reduce((O,$)=>O+(Yn($)?2:1),0),x=y):p.length===0&&I>t&&(p=w,g=I,x=T+1);break}p+=w,g+=I,x=T+1,w===" "&&(y=T+1)}if(p.length>0||r.length===0){let T=d,w=r.length;r.push(p),s[c].push([w,T]),a.push([c,T])}d=x}}return{visualLines:r,logicalToVisualMap:s,visualToLogicalMap:a}}i(Xt,"calculateVisualLayout");function Cm(e,t){let{logicalToVisualMap:n,visualLines:o}=e;if(o.length===0)return[0,0];let[r,s]=t,a=n[r];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=o[l]??"",p=Math.max(0,s-d),g=qn(ak(m,0,p));return[l,g]}i(Cm,"calculateVisualCursorFromLayout");var bm={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"]}},Kx={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 Vx={dark:bm,minimal:Kx};function ne(e="dark"){return Vx[e]??bm}i(ne,"getTheme");function tN(){return Object.keys(Vx)}i(tN,"getThemeNames");import{jsx as qt,jsxs as Sn,Fragment as gM}from"react/jsx-runtime";import{useMemo as Tu}from"react";import{jsx as gS}from"react/jsx-runtime";import{createContext as KE,useContext as Mr,useEffect as qi,useMemo as pS,useState as VE,useCallback as hS,useRef as pu}from"react";import{Stream as TE}from"node:stream";import{openSync as CE,writeSync as nS}from"node:fs";import{performance as bE}from"node:perf_hooks";import{tmpdir as vE}from"node:os";import{join as IE}from"node:path";import vm,{forwardRef as uk,useContext as dk}from"react";import{createContext as ck}from"react";var Ni=ck({isScreenReaderEnabled:!1});import{createContext as lk}from"react";var Kl=lk(void 0);var zx=uk(({children:e,backgroundColor:t,"aria-label":n,"aria-hidden":o,"aria-role":r,"aria-state":s,...a},c)=>{let{isScreenReaderEnabled:l}=dk(Ni),d=n?vm.createElement("ink-text",null,n):void 0;if(l&&o)return null;let m=vm.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:r,state:s}},l&&d?d:e);return t?vm.createElement(Kl.Provider,{value:t},m):m});zx.displayName="Box";var wn=zx;import gk,{useContext as Xx}from"react";import Bi from"chalk";import Bo from"chalk";var fk=/^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/,mk=/^ansi256\(\s?(\d+)\s?\)$/;function pk(e){return e in Bo}i(pk,"isNamedColor");function Ln(e,t,n){if(!t)return e;if(pk(t)){let o=Bo;if(n==="foreground")return o[t]?.(e)??e;let r=`bg${t[0].toUpperCase()+t.slice(1)}`;return o[r]?.(e)??e}if(t.startsWith("#"))return n==="foreground"?Bo.hex(t)(e):Bo.bgHex(t)(e);if(t.startsWith("ansi256")){let o=mk.exec(t);if(!o)return e;let r=Number(o[1]);return n==="foreground"?Bo.ansi256(r)(e):Bo.bgAnsi256(r)(e)}if(t.startsWith("rgb")){let o=fk.exec(t);if(!o)return e;let r=Number(o[1]),s=Number(o[2]),a=Number(o[3]);return n==="foreground"?Bo.rgb(r,s,a)(e):Bo.bgRgb(r,s,a)(e)}return e}i(Ln,"colorize");function Yt({color:e,backgroundColor:t,dimColor:n=!1,bold:o=!1,italic:r=!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}=Xx(Ni),x=Xx(Kl),y=g&&m?m:d;if(y==null)return null;let T=i(w=>{let I=w;n&&(I=Bi.dim(I)),e&&(I=Ln(I,e,"foreground"));let O=t??x;return O&&(I=Ln(I,O,"background")),o&&(I=Bi.bold(I)),r&&(I=Bi.italic(I)),s&&(I=Bi.underline(I)),a&&(I=Bi.strikethrough(I)),c&&(I=Bi.inverse(I)),I},"transform");return g&&p?null:gk.createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:l},internal_transform:T},g&&m?m:d)}i(Yt,"Text");import hk,{useLayoutEffect as yk,useMemo as Yx,useState as xk}from"react";function Im({items:e,children:t,style:n}){let[o,r]=xk(0),s=Yx(()=>e.slice(o),[e,o]);yk(()=>{r(e.length)},[e.length]);let a=s.map((l,d)=>t(l,o+d)),c=Yx(()=>({position:"absolute",flexDirection:"column",...n}),[n]);return hk.createElement("ink-box",{internal_static:!0,style:c},a)}i(Im,"Static");import Yi from"node:process";import Zw from"react";import{throttle as nE}from"es-toolkit/compat";import bo from"ansi-escapes";import Wo from"is-in-ci";import oE from"auto-bind";import{onExit as rE}from"signal-exit";import iE from"patch-console";import{LegacyRoot as sE,ConcurrentRoot as aE}from"react-reconciler/constants.js";import cE from"yoga-layout";import lE from"wrap-ansi";import uE from"terminal-size";import wk from"node:process";var Vl=i(()=>wk.env.DEV==="true","isDev");import Vk from"react-reconciler";import{DefaultEventPriority as zk,NoEventPriority as dw}from"react-reconciler/constants.js";import*as Ho from"scheduler";import aw from"yoga-layout";import{createContext as Xk}from"react";import Lk from"yoga-layout";import Sk from"widest-line";var qx=new Map,Tk=i(e=>{if(e.length===0)return{width:0,height:0};let t=qx.get(e);if(t)return t;let n=Sk(e),o=e.split(`
|
|
3
|
+
`).length,r={width:n,height:o};return qx.set(e,r),r},"measureText"),km=Tk;import Ck from"wrap-ansi";import bk from"cli-truncate";var Qx={},vk=i((e,t,n)=>{let o=e+String(t)+String(n),r=Qx[o];if(r)return r;let s=e;if(n==="wrap"&&(s=Ck(e,t,{trim:!1,hard:!0})),n.startsWith("truncate")){let a="end";n==="truncate-middle"&&(a="middle"),n==="truncate-start"&&(a="start"),s=bk(e,t,{position:a})}return Qx[o]=s,s},"wrapText"),zl=vk;var Ik=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=63},"isCsiParameterCharacter"),kk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isCsiIntermediateCharacter"),Rk=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=64&&t<=126},"isCsiFinalCharacter"),ew=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=32&&t<=47},"isEscapeIntermediateCharacter"),Ek=i(e=>{let t=e.codePointAt(0);return t!==void 0&&t>=48&&t<=126},"isEscapeFinalCharacter"),tw=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(!Ik(c))break;n++}let o=e.slice(t,n),r=n;for(;n<e.length;){let c=e[n];if(!kk(c))break;n++}let s=e.slice(r,n),a=e[n];if(!(a===void 0||!Rk(a)))return{endIndex:n+1,parameterString:o,intermediateString:s,finalCharacter:a}},"readCsiSequence"),Zx=i((e,t,n)=>{for(let o=t;o<e.length;o++){let r=e[o];if(n&&r==="\x07"||r==="\x9C")return o+1;if(r==="\x1B"){let s=e[o+1];if(s==="\x1B"){o++;continue}if(s==="\\")return o+2}}},"findControlStringTerminatorIndex"),Mk=i((e,t)=>{let n=t;for(;n<e.length;){let s=e[n];if(!ew(s))break;n++}let o=e.slice(t,n),r=e[n];if(!(r===void 0||!Ek(r)))return{endIndex:n+1,intermediateString:o,finalCharacter:r}},"readEscapeSequence"),Ak=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"),_k=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"),Rm=i(e=>{if(e.includes("\x1B"))return!0;for(let t of e)if(tw(t))return!0;return!1},"hasAnsiControlCharacters"),Hi=i((e,t,n,o)=>(o>n&&e.push({type:"text",value:t.slice(n,o)}),e.push({type:"invalid",value:t.slice(o)}),e),"malformedFromIndex"),nw=i(e=>{if(!Rm(e))return[{type:"text",value:e}];let t=[],n=0;for(let o=0;o<e.length;){let r=e[o];if(r===void 0)break;if(r==="\x1B"){let a=e[o+1];if(a===void 0)return Hi(t,e,n,o);if(a==="["){let d=Jx(e,o+2);if(d===void 0)return Hi(t,e,n,o);o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"csi",value:e.slice(o,d.endIndex),parameterString:d.parameterString,intermediateString:d.intermediateString,finalCharacter:d.finalCharacter}),o=d.endIndex,n=o;continue}let c=Ak(a);if(c!==void 0){let d=Zx(e,o+2,c.allowBellTerminator);if(d===void 0)return Hi(t,e,n,o);o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:c.type,value:e.slice(o,d)}),o=d,n=o;continue}let l=Mk(e,o+1);if(l===void 0){if(ew(a))return Hi(t,e,n,o);o>n&&t.push({type:"text",value:e.slice(n,o)}),o++,n=o;continue}o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"esc",value:e.slice(o,l.endIndex),intermediateString:l.intermediateString,finalCharacter:l.finalCharacter}),o=l.endIndex,n=o;continue}if(r==="\x9B"){let a=Jx(e,o+1);if(a===void 0)return Hi(t,e,n,o);o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"csi",value:e.slice(o,a.endIndex),parameterString:a.parameterString,intermediateString:a.intermediateString,finalCharacter:a.finalCharacter}),o=a.endIndex,n=o;continue}let s=_k(r);if(s!==void 0){let a=Zx(e,o+1,s.allowBellTerminator);if(a===void 0)return Hi(t,e,n,o);o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:s.type,value:e.slice(o,a)}),o=a,n=o;continue}if(r==="\x9C"){o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"st",value:r}),o++,n=o;continue}if(tw(r)){o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"c1",value:r}),o++,n=o;continue}o++}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t},"tokenizeAnsi");var $k=/^[\d:;]*$/,Pk=i(e=>{if(!Rm(e))return e;let t="";for(let n of nw(e)){if(n.type==="text"||n.type==="osc"){t+=n.value;continue}n.type==="csi"&&n.finalCharacter==="m"&&n.intermediateString===""&&$k.test(n.parameterString)&&(t+=n.value)}return t},"sanitizeAnsi"),ow=Pk;var rw=i(e=>{let t="";for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(o===void 0)continue;let r="";o.nodeName==="#text"?r=o.nodeValue:((o.nodeName==="ink-text"||o.nodeName==="ink-virtual-text")&&(r=rw(o)),r.length>0&&typeof o.internal_transform=="function"&&(r=o.internal_transform(r,n))),t+=r}return ow(t)},"squashTextNodes"),Ta=rw;var Xl=i(e=>{let t={nodeName:e,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:e==="ink-virtual-text"?void 0:Lk.Node.create(),internal_accessibility:{}};return e==="ink-text"&&t.yogaNode?.setMeasureFunc(Ok.bind(null,t)),t},"createNode"),Yl=i((e,t)=>{t.parentNode&&Ca(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")&&ql(e)},"appendChildNode"),Em=i((e,t,n)=>{t.parentNode&&Ca(t.parentNode,t),t.parentNode=e;let o=e.childNodes.indexOf(n);o>=0?(e.childNodes.splice(o,0,t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,o)):(e.childNodes.push(t),t.yogaNode&&e.yogaNode?.insertChild(t.yogaNode,e.yogaNode.getChildCount())),(e.nodeName==="ink-text"||e.nodeName==="ink-virtual-text")&&ql(e)},"insertBeforeNode"),Ca=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")&&ql(e)},"removeChildNode"),Mm=i((e,t,n)=>{if(t==="internal_accessibility"){e.internal_accessibility=n;return}e.attributes[t]=n},"setAttribute"),Am=i((e,t)=>{e.style=t},"setStyle"),iw=i(e=>{let t={nodeName:"#text",nodeValue:e,yogaNode:void 0,parentNode:void 0,style:{}};return ba(t,e),t},"createTextNode"),Ok=i(function(e,t){let n=e.nodeName==="#text"?e.nodeValue:Ta(e),o=km(n);if(o.width<=t||o.width>=1&&t>0&&t<1)return o;let r=e.style?.textWrap??"wrap",s=zl(n,t,r);return km(s)},"measureTextNode"),sw=i(e=>{if(e?.parentNode)return e.yogaNode??sw(e.parentNode)},"findClosestYogaNode"),ql=i(e=>{sw(e)?.markDirty()},"markNodeAsDirty"),ba=i((e,t)=>{typeof t!="string"&&(t=String(t)),e.nodeValue=t,ql(e)},"setTextNodeValue");import he from"yoga-layout";var Nk=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"),Bk=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"),Hk=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"),Fk=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"),Wk=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"),Uk=i((e,t)=>{"display"in t&&e.setDisplay(t.display==="flex"?he.DISPLAY_FLEX:he.DISPLAY_NONE)},"applyDisplayStyles"),jk=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"),Gk=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"),Kk=i((e,t={})=>{Nk(e,t),Bk(e,t),Hk(e,t),Fk(e,t),Wk(e,t),Uk(e,t),jk(e,t),Gk(e,t)},"styles"),_m=Kk;if(Vl())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 cw=i((e,t)=>{if(e===t)return;if(!e)return t;let n={},o=!1;for(let r of Object.keys(e))(!t||!Object.hasOwn(t,r))&&(n[r]=void 0,o=!0);if(t)for(let r of Object.keys(t))t[r]!==e[r]&&(n[r]=t[r],o=!0);return o?n:void 0},"diff"),lw=i(e=>{e?.unsetMeasureFunc(),e?.freeRecursive()},"cleanupYogaNode"),Ql=dw,$m,uw={name:void 0,version:void 0},So=Vk({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,o=t==="ink-text"||t==="ink-virtual-text";return n===o?e:{isInsideText:o}},shouldSetTextContent:i(()=>!1,"shouldSetTextContent"),createInstance(e,t,n,o){if(o.isInsideText&&e==="ink-box")throw new Error("<Box> can\u2019t be nested inside <Text> component");let r=e==="ink-text"&&o.isInsideText?"ink-virtual-text":e,s=Xl(r);for(let[a,c]of Object.entries(t))if(a!=="children"){if(a==="style"){Am(s,c),s.yogaNode&&_m(s.yogaNode,c);continue}if(a==="internal_transform"){s.internal_transform=c;continue}if(a==="internal_static"){$m=n,s.internal_static=!0,n.isStaticDirty=!0,n.staticNode=s;continue}Mm(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 iw(e)},resetTextContent(){},hideTextInstance(e){ba(e,"")},unhideTextInstance(e,t){ba(e,t)},getPublicInstance:i(e=>e,"getPublicInstance"),hideInstance(e){e.yogaNode?.setDisplay(aw.DISPLAY_NONE)},unhideInstance(e){e.yogaNode?.setDisplay(aw.DISPLAY_FLEX)},appendInitialChild:Yl,appendChild:Yl,insertBefore:Em,finalizeInitialChildren(){return!1},isPrimaryRenderer:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,scheduleCallback:Ho.unstable_scheduleCallback,cancelCallback:Ho.unstable_cancelCallback,shouldYield:Ho.unstable_shouldYield,now:Ho.unstable_now,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},getInstanceFromNode:i(()=>null,"getInstanceFromNode"),prepareScopeUpdate(){},getInstanceFromScope:i(()=>null,"getInstanceFromScope"),appendChildToContainer:Yl,insertInContainerBefore:Em,removeChildFromContainer(e,t){Ca(e,t),lw(t.yogaNode)},commitUpdate(e,t,n,o){$m&&e.internal_static&&($m.isStaticDirty=!0);let r=cw(n,o),s=cw(n.style,o.style);if(!(!r&&!s)){if(r)for(let[a,c]of Object.entries(r)){if(a==="style"){Am(e,c);continue}if(a==="internal_transform"){e.internal_transform=c;continue}if(a==="internal_static"){e.internal_static=!0;continue}Mm(e,a,c)}s&&e.yogaNode&&_m(e.yogaNode,s)}},commitTextUpdate(e,t,n){ba(e,n)},removeChild(e,t){Ca(e,t),lw(t.yogaNode)},setCurrentUpdatePriority(e){Ql=e},getCurrentUpdatePriority:i(()=>Ql,"getCurrentUpdatePriority"),resolveUpdatePriority(){return Ql!==dw?Ql:zk},maySuspendCommit(){return!0},NotPendingTransition:void 0,HostTransitionContext:Xk(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null},rendererPackageName:uw.name,rendererVersion:uw.version});import Zk from"widest-line";import eR from"indent-string";import Fi from"yoga-layout";import Jl from"yoga-layout";var Yk=i(e=>e.getComputedWidth()-e.getComputedPadding(Jl.EDGE_LEFT)-e.getComputedPadding(Jl.EDGE_RIGHT)-e.getComputedBorder(Jl.EDGE_LEFT)-e.getComputedBorder(Jl.EDGE_RIGHT),"getMaxWidth"),fw=Yk;import qk from"cli-boxes";import Zl from"chalk";var Qk=i((e,t,n,o)=>{if(n.style.borderStyle){let r=n.yogaNode.getComputedWidth(),s=n.yogaNode.getComputedHeight(),a=typeof n.style.borderStyle=="string"?qk[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,I=n.style.borderLeft!==!1,O=n.style.borderRight!==!1,$=r-(I?1:0)-(O?1:0),D=T?Ln((I?a.topLeft:"")+a.top.repeat($)+(O?a.topRight:""),c,"foreground"):void 0;T&&p&&(D=Zl.dim(D));let L=s;T&&(L-=1),w&&(L-=1);let X=(Ln(a.left,d,"foreground")+`
|
|
12
|
+
`).repeat(L);x&&(X=Zl.dim(X));let v=(Ln(a.right,m,"foreground")+`
|
|
13
|
+
`).repeat(L);y&&(v=Zl.dim(v));let ie=w?Ln((I?a.bottomLeft:"")+a.bottom.repeat($)+(O?a.bottomRight:""),l,"foreground"):void 0;w&&g&&(ie=Zl.dim(ie));let Te=T?1:0;D&&o.write(e,t,D,{transformers:[]}),I&&o.write(e,t+Te,X,{transformers:[]}),O&&o.write(e+r-1,t+Te,v,{transformers:[]}),ie&&o.write(e,t+s-1,ie,{transformers:[]})}},"renderBorder"),mw=Qk;var Jk=i((e,t,n,o)=>{if(!n.style.backgroundColor)return;let r=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=r-a-c,p=s-l-d;if(!(m>0&&p>0))return;let g=Ln(" ".repeat(m),n.style.backgroundColor,"background");for(let x=0;x<p;x++)o.write(e+a,t+l+x,g,{transformers:[]})},"renderBackground"),pw=Jk;var tR=i((e,t)=>{let n=e.childNodes[0]?.yogaNode;if(n){let o=n.getComputedLeft(),r=n.getComputedTop();t=`
|
|
14
|
+
`.repeat(r)+eR(t,o)}return t},"applyPaddingToText"),eu=i((e,t={})=>{if(t.skipStaticElements&&e.internal_static||e.yogaNode?.getDisplay()===Fi.DISPLAY_NONE)return"";let n="";if(e.nodeName==="ink-text")n=Ta(e);else if(e.nodeName==="ink-box"||e.nodeName==="ink-root"){let o=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=>eu(s,{parentRole:e.internal_accessibility?.role,skipStaticElements:t.skipStaticElements})).filter(Boolean).join(o)}if(e.internal_accessibility){let{role:o,state:r}=e.internal_accessibility;if(r){let a=Object.keys(r).filter(c=>r[c]).join(", ");a&&(n=`(${a}) ${n}`)}o&&o!==t.parentRole&&(n=`${o}: ${n}`)}return n},"renderNodeToScreenReaderOutput"),gw=i((e,t,n)=>{let{offsetX:o=0,offsetY:r=0,transformers:s=[],skipStaticElements:a}=n;if(a&&e.internal_static)return;let{yogaNode:c}=e;if(c){if(c.getDisplay()===Fi.DISPLAY_NONE)return;let l=o+c.getComputedLeft(),d=r+c.getComputedTop(),m=s;if(typeof e.internal_transform=="function"&&(m=[e.internal_transform,...s]),e.nodeName==="ink-text"){let g=Ta(e);if(g.length>0){let x=Zk(g),y=fw(c);if(x>y){let T=e.style.textWrap??"wrap";g=zl(g,y,T)}g=tR(e,g),t.write(l,d,g,{transformers:m})}return}let p=!1;if(e.nodeName==="ink-box"){pw(l,d,e,t),mw(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(Fi.EDGE_LEFT):void 0,T=g?l+c.getComputedWidth()-c.getComputedBorder(Fi.EDGE_RIGHT):void 0,w=x?d+c.getComputedBorder(Fi.EDGE_TOP):void 0,I=x?d+c.getComputedHeight()-c.getComputedBorder(Fi.EDGE_BOTTOM):void 0;t.clip({x1:y,x2:T,y1:w,y2:I}),p=!0}}if(e.nodeName==="ink-root"||e.nodeName==="ink-box"){for(let g of e.childNodes)gw(g,t,{offsetX:l,offsetY:d,transformers:m,skipStaticElements:a});p&&t.unclip()}}},"renderNodeToOutput"),Pm=gw;import nR from"slice-ansi";import oR from"string-width";import{styledCharsFromTokens as rR,styledCharsToString as iR,tokenize as sR}from"@alcalzone/ansi-tokenize";var Lm=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=rR(sR(t)),this.styledChars.set(t,n)),n}getStringWidth(t){let n=this.widths.get(t);return n===void 0&&(n=oR(t),this.widths.set(t,n)),n}getWidestLine(t){let n=this.blockWidths.get(t);if(n===void 0){let o=0;for(let r of t.split(`
|
|
16
|
+
`))o=Math.max(o,this.getStringWidth(r));n=o,this.blockWidths.set(t,n)}return n}},Wi=class{static{i(this,"Output")}width;height;operations=[];caches=new Lm;constructor(t){let{width:n,height:o}=t;this.width=n,this.height=o}write(t,n,o,r){let{transformers:s}=r;o&&this.operations.push({type:"write",x:t,y:n,text:o,transformers:s})}clip(t){this.operations.push({type:"clip",clip:t})}unclip(){this.operations.push({type:"unclip"})}getGrid(){let t=[];for(let o=0;o<this.height;o++){let r=[];for(let s=0;s<this.width;s++)r.push({type:"char",value:" ",fullWidth:!1,styles:[]});t.push(r)}let n=[];for(let o of this.operations)if(o.type==="clip"&&n.push(o.clip),o.type==="unclip"&&n.pop(),o.type==="write"){let{text:r,transformers:s}=o,{x:a,y:c}=o,l=r.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(r);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 nR(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 I=Math.max(1,this.caches.getStringWidth(w.value));if(I>1)for(let O=1;O<I;O++)x[T+O]={type:"char",value:"",fullWidth:!1,styles:w.styles};T+=I}m++}}return t}get(){let t=this.getGrid();return{output:t.map(o=>{let r=o.filter(s=>s!==void 0);return iR(r).trimEnd()}).join(`
|
|
18
|
+
`),height:t.length}}};var To={Single:0,Wide:1,SpacerTail:2},Ir={char:" ",width:To.Single,style:"",hyperlink:void 0};function hw(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(Ir);return{width:e,height:t,cells:n}}i(hw,"createScreen");function Ui(e,t,n){if(!(t<0||n<0||t>=e.width||n>=e.height))return e.cells[n*e.width+t]}i(Ui,"cellAt");function yw(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(Ir),o=!1;return{width:e,height:t,setCellAt(r,s,a){if(o)throw new Error("ScreenBuilder.setCellAt called after build()");if(r<0||s<0||r>=e||s>=t)throw new RangeError(`ScreenBuilder.setCellAt out of bounds: (${r}, ${s}) on ${e}x${t}`);n[s*e+r]=a},build(){if(o)throw new Error("ScreenBuilder.build called twice");return o=!0,{width:e,height:t,cells:n}}}}i(yw,"createScreenBuilder");function*tu(e,t){let n=Math.max(e.width,t.width),o=Math.max(e.height,t.height);for(let r=0;r<o;r++)for(let s=0;s<n;s++){let a=Ui(e,s,r),c=Ui(t,s,r);aR(a,c)||(yield{x:s,y:r,prev:a,next:c})}}i(tu,"diffEach");function aR(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(aR,"cellsEqual");var Om="\x1B]8;";function cR(e){return e.endsWith("\x07")?e.slice(0,-1):e}i(cR,"stripOsc8Terminator");function lR(e){if(!e.startsWith(Om))return;let t=e.slice(Om.length),n=t.indexOf(";");if(n<0)return;let o=t.slice(n+1),r=cR(o);return r.length>0?r:void 0}i(lR,"parseOsc8Url");function uR(e){if(e.value==="")return{char:"",width:To.SpacerTail,style:"",hyperlink:void 0};let t="",n;for(let o of e.styles)if(o.code.startsWith(Om)){let r=lR(o.code);r!==void 0&&(n=r)}else t+=o.code;return{char:e.value,width:e.fullWidth?To.Wide:To.Single,style:t,hyperlink:n}}i(uR,"styledCharToCell");function xw(e){let t=e.getGrid(),n=e.width,o=e.height,r=yw(n,o),s=Math.min(t.length,o);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=uR(m);p.char===Ir.char&&p.width===Ir.width&&p.style===Ir.style&&p.hyperlink===Ir.hyperlink||r.setCellAt(d,a,p)}}return r.build()}i(xw,"outputToScreen");var dR=i((e,t,n)=>{if(e.yogaNode){if(t){let p=eu(e,{skipStaticElements:!0}),g=p===""?0:p.split(`
|
|
19
|
+
`).length,x="";return e.staticNode&&(x=eu(e.staticNode,{skipStaticElements:!1})),{output:p,outputHeight:g,staticOutput:x?`${x}
|
|
20
|
+
`:"",frame:void 0}}let o=new Wi({width:e.yogaNode.getComputedWidth(),height:e.yogaNode.getComputedHeight()});Pm(e,o,{skipStaticElements:!0});let r;e.staticNode?.yogaNode&&(r=new Wi({width:e.staticNode.yogaNode.getComputedWidth(),height:e.staticNode.yogaNode.getComputedHeight()}),Pm(e.staticNode,r,{skipStaticElements:!1}));let{output:s,height:a}=o.get(),c=xw(o),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:r?`${r.get().output}
|
|
21
|
+
`:"",frame:m}}return{output:"",outputHeight:0,staticOutput:"",frame:void 0}},"renderer"),ww=dR;function Qn(...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(Qn,"csi");function Sw(e=1){return e===0?"":Qn(e,"A")}i(Sw,"cursorUp");function fR(e=1){return e===0?"":Qn(e,"B")}i(fR,"cursorDown");function mR(e=1){return e===0?"":Qn(e,"C")}i(mR,"cursorForward");function pR(e=1){return e===0?"":Qn(e,"D")}i(pR,"cursorBack");function Tw(e){return Qn(e,"G")}i(Tw,"cursorTo");var gR=Qn("G"),Cw=Qn("H");function bw(e,t){let n="";return e<0?n+=pR(-e):e>0&&(n+=mR(e)),t<0?n+=Sw(-t):t>0&&(n+=fR(t)),n}i(bw,"cursorMove");var hR=Qn(2,"K");function vw(e){if(e<=0)return"";let t="";for(let n=0;n<e;n++)t+=hR,n<e-1&&(t+=Sw(1));return t+=gR,t}i(vw,"eraseLines");var UB=Qn("r"),nu=Qn(0,"m");function Iw(e){return`\x1B]${e.join(";")}\x07`}i(Iw,"osc");function yR(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(yR,"osc8Id");function va(e,t){if(!e)return Ia;let n={id:yR(e),...t??{}},o=Object.entries(n).map(([r,s])=>`${r}=${s}`).join(":");return Iw(["8",o,e])}i(va,"link");var Ia=Iw(["8","",""]);function Dm(e){let{screen:t}=e;if(t.width===0||t.height===0)return[];let n=[],o="",r;for(let s=0;s<t.height;s++){let a="";for(let c=0;c<t.width;c++){let l=Ui(t,c,s);!l||l.width===To.SpacerTail||(l.hyperlink!==r&&(r!==void 0&&(a+=Ia),l.hyperlink!==void 0&&(a+=va(l.hyperlink)),r=l.hyperlink),l.style!==o&&(o!==""&&(a+=nu),l.style!==""&&(a+=l.style),o=l.style),a+=l.char)}r!==void 0&&(a+=Ia,r=void 0),o!==""&&(a+=nu,o=""),n.push(a.trimEnd())}return[{type:"stdout",content:n.join(`
|
|
22
|
+
`)}]}i(Dm,"renderFullFrame");var xR=Object.freeze([]),wR=Object.freeze([]);function ji(e,t){if(e===t)return{patches:xR,current:e};let n=[];return e!==""&&n.push({type:"stdout",content:nu}),t!==""&&n.push({type:"stdout",content:t}),{patches:n,current:t}}i(ji,"transitionStyle");function ou(e,t){let n=ji(e,t),o="";for(let r of n.patches)r.type==="stdout"&&(o+=r.content);return{str:o,current:n.current}}i(ou,"transitionStyleStr");function kr(e,t){if(e===t)return{patches:wR,current:e};let n=[];return e!==void 0&&n.push({type:"stdout",content:Ia}),t!==void 0&&n.push({type:"stdout",content:va(t)}),{patches:n,current:t}}i(kr,"transitionHyperlink");function kw(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(kw,"needsWidthCompensation");var Gi=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,o]=t(this.cursor);for(let r of n)this._diffMut.push(r);this._cursorMut.x+=o.dx,this._cursorMut.y+=o.dy}},Fo={type:"carriageReturn"},ka={type:"stdout",content:`
|
|
23
|
+
`};function ru(e,t,n){let o=t.width===To.Wide?2:1,r=e.viewportWidth,s=!1;return e.txn(a=>{let c=a.x;if(o===2&&c<r){let m=t.char.length>2?r:r+1;if(c+2>=m)return[[],{dx:0,dy:0}]}let l=[];n.length>0&&l.push({type:"stdout",content:n});let d=o===2&&kw(t.char);return d&&c+1<r&&(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+o+1}),s=!0,c>=r?[l,{dx:o-c,dy:1}]:[l,{dx:o,dy:0}]}),s}i(ru,"writeCellWithStyleStr");function Ra(e,t,n){e.txn(o=>{let r=t-o.x,s=n-o.y;return o.x>=e.viewportWidth?[[Fo,{type:"cursorMove",x:t,y:s}],{dx:r,dy:s}]:s!==0?[[Fo,{type:"cursorMove",x:t,y:s}],{dx:r,dy:s}]:[[{type:"cursorMove",x:r,y:s}],{dx:r,dy:s}]})}i(Ra,"moveCursorTo");function iu(e,t,n,o){let r="",s;for(let a=n;a<o;a++){if(e.cursor.y<a){let d=a-e.cursor.y;e.txn(m=>{let p=new Array(1+d);p[0]=Fo;for(let g=0;g<d;g++)p[1+g]=ka;return[p,{dx:-m.x,dy:d}]})}for(let d=0;d<t.screen.width;d++){let m=Ui(t.screen,d,a);if(!m||m.width===To.SpacerTail||m.char===" "&&m.style===""&&m.hyperlink===void 0)continue;Ra(e,d,a);let p=kr(s,m.hyperlink);for(let x of p.patches)e.txn(()=>[[x],{dx:0,dy:0}]);s=p.current;let g=ou(r,m.style);ru(e,m,g.str)&&(r=g.current)}let c=ji(r,"");for(let d of c.patches)e.txn(()=>[[d],{dx:0,dy:0}]);r=c.current;let l=kr(s,void 0);for(let d of l.patches)e.txn(()=>[[d],{dx:0,dy:0}]);s=l.current,e.txn(d=>[[Fo,ka],{dx:-d.x,dy:1}])}if(r!==""||s!==void 0){let a=ji(r,"");for(let l of a.patches)e.txn(()=>[[l],{dx:0,dy:0}]);let c=kr(s,void 0);for(let l of c.patches)e.txn(()=>[[l],{dx:0,dy:0}])}}i(iu,"renderFrameSlice");function Nm(e,t){let n="";for(let o=0;o<e.width;o++){let r=Ui(e,o,t);n+=r?.char??" "}return n.trimEnd()}i(Nm,"readLine");function su(e,t){let n=new Gi({x:0,y:0},e.viewport.width);iu(n,e,0,e.screen.height);let o=[{type:"clearTerminal",reason:t}];for(let r of n.diff)o.push(r);return o}i(su,"fullResetSequence_CAUSES_FLICKER");function Bm(e,t){let n=e.cursor.y>=e.screen.height,o=t.screen.height>e.screen.height,r=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:o?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:o,shrinking:r,prevHadScrollback:s,nextFitsViewport:a}}i(Bm,"computeViewportState");function Rw(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 o=Bm(e,t);if(o.prevHadScrollback&&o.nextFitsViewport&&o.shrinking)return{reset:!0,reason:"offscreen"};if(e.screen.height>=e.viewport.height&&e.screen.height>0&&o.cursorAtBottom&&!o.growing){let s=e.screen.height-e.viewport.height+1;for(let a of tu(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 o.shrinking&&e.screen.height-t.screen.height>e.viewport.height?{reset:!0,reason:"offscreen"}:{reset:!1}}i(Rw,"shouldFullReset");function Ew(e,t,n){return!!(t&&t.width===2||e&&e.width===2&&!t||t&&n&&!e)}i(Ew,"shouldSkipDiff");var au=class{static{i(this,"LogUpdate")}options;constructor(t){this.options=t}render(t,n){if(!this.options.isTTY)return Dm(n);let o=Rw(t,n,Nm);return o.reset?su(n,o.reason):bR(t,n)}reset(){}};function Hm(e,t){for(let n of t)e.txn(()=>[[n],{dx:0,dy:0}])}i(Hm,"emitPatches");function Mw(e,t,n){if(t!==""){let o=ji(t,"");Hm(e,o.patches)}if(n!==void 0){let o=kr(n,void 0);Hm(e,o.patches)}return{style:"",hyperlink:void 0}}i(Mw,"resetStyleAndHyperlink");function SR(e,t,n){let o=t.screen.height-n.screen.height;e.txn(r=>[[{type:"clear",count:o},{type:"cursorMove",x:0,y:-1}],{dx:-r.x,dy:-o}])}i(SR,"applyShrink");function TR(e,t,n,o){let r="",s,a=!1;for(let c of tu(t.screen,n.screen)){let{x:l,y:d,prev:m,next:p}=c;if(o.growing&&d>=t.screen.height)continue;let g=!!(p&&p.char===" "&&p.style===""&&p.hyperlink===void 0);if(!Ew(m,p,g)){if(d<o.viewportY){a=!0;break}if(Ra(e,l,d),p){let x=kr(s,p.hyperlink);Hm(e,x.patches),s=x.current;let y=ou(r,p.style);ru(e,p,y.str)&&(r=y.current)}else if(m){let x=Mw(e,r,s);r=x.style,s=x.hyperlink,e.txn(()=>[[{type:"stdout",content:" "}],{dx:1,dy:0}])}}}return{currentStyle:r,currentHyperlink:s,needsFullReset:a}}i(TR,"diffPass");function CR(e,t){t.cursor.y>=t.screen.height?e.txn(n=>{let o=t.cursor.y-n.y;if(o>0){let s=new Array(1+o);s[0]=Fo;for(let a=0;a<o;a++)s[1+a]=ka;return[s,{dx:-n.x,dy:o}]}let r=t.cursor.y-n.y;return r!==0||n.x!==t.cursor.x?[[Fo,{type:"cursorMove",x:t.cursor.x,y:r}],{dx:t.cursor.x-n.x,dy:r}]:[[],{dx:0,dy:0}]}):Ra(e,t.cursor.x,t.cursor.y)}i(CR,"restoreCursor");function bR(e,t){let n=Bm(e,t),o=new Gi(e.cursor,t.viewport.width);n.shrinking&&SR(o,e,t);let r=TR(o,e,t,n);return r.needsFullReset?su(t,"offscreen"):(Mw(o,r.currentStyle,r.currentHyperlink),n.growing&&iu(o,t,e.screen.height,t.screen.height),CR(o,t),o.diff)}i(bR,"renderIncremental");var vR="\x1B[?25l",IR="\x1B[?25h",kR=`\x1B[2J${Cw}`;function RR(e){switch(e.type){case"stdout":return e.content;case"carriageReturn":return"\r";case"cursorHide":return vR;case"cursorShow":return IR;case"cursorMove":return bw(e.x,e.y);case"cursorTo":return Tw(e.col);case"clear":return vw(e.count);case"clearTerminal":return kR;case"hyperlink":return va(e.uri)}}i(RR,"patchToBytes");function cu(e,t){let n="";for(let o of t)n+=RR(o);n.length>0&&e.write(n)}i(cu,"applyDiff");function Aw(e,t){if(t===void 0)return!1;let n=e.cellLogUpdate.render(e.prevFrame,t);return cu(e.stdout,n),e.prevFrame=t,!0}i(Aw,"applyCellFrame");function Ea(e,t){return{screen:hw(0,0),viewport:{width:t,height:e},cursor:{x:0,y:0,visible:!0}}}i(Ea,"emptyFrame");import ER from"is-in-ci";var Ki="\x1B[?2026h",Rr="\x1B[?2026l";function Vi(e){return"isTTY"in e&&e.isTTY===!0&&!ER}i(Vi,"shouldSynchronize");var MR=new WeakMap,_w=MR;import{EventEmitter as YR}from"node:events";import qR from"node:process";import Er,{useState as Um,useRef as zi,useCallback as pt,useMemo as Xi,useEffect as Yw}from"react";import QR from"cli-cursor";var AR=i(e=>e>=48&&e<=63,"isCsiParameterByte"),_R=i(e=>e>=32&&e<=47,"isCsiIntermediateByte"),Pw=i(e=>e>=64&&e<=126,"isCsiFinalByte");function $R(e,t,n){let o=t+n+1,r=o;for(;r<e.length;r+=1){let s=e.codePointAt(r);if(s===void 0)return"pending";if(!(AR(s)||_R(s))&&!(s===91&&r===o))return Pw(s)?{sequence:e.slice(t,r+1),nextIndex:r+1}:void 0}return"pending"}i($R,"parseCsiSequence");function PR(e,t,n){let o=t+n+2;if(o>e.length)return"pending";let r=e.codePointAt(o-1);if(!(r===void 0||!Pw(r)))return{sequence:e.slice(t,o),nextIndex:o}}i(PR,"parseSs3Sequence");function $w(e,t,n){let o=e[t+n];if(o===void 0)return"pending";if(o==="[")return $R(e,t,n);if(o==="O")return PR(e,t,n)}i($w,"parseControlSequence");function LR(e,t){let n=e.codePointAt(t+1),o=n!==void 0&&n>65535?2:1,r=t+1+o;return{sequence:e.slice(t,r),nextIndex:r}}i(LR,"parseEscapedCodePoint");function OR(e){let t=[],n=0,o=i(r=>({events:t,pending:e.slice(r)}),"pendingFrom");for(;n<e.length;){let r=e.indexOf("\x1B",n);if(r===-1)return t.push(e.slice(n)),{events:t,pending:""};if(r>n&&t.push(e.slice(n,r)),r===e.length-1)return o(r);let s=$w(e,r,1);if(s==="pending")return o(r);if(s){t.push(s.sequence),n=s.nextIndex;continue}if(e[r+1]==="\x1B"){if(r+2>=e.length)return o(r);let l=$w(e,r,2);if(l==="pending")return o(r);if(l){t.push(l.sequence),n=l.nextIndex;continue}t.push(e.slice(r,r+2)),n=r+2;continue}let c=LR(e,r);t.push(c.sequence),n=c.nextIndex}return{events:t,pending:""}}i(OR,"parseKeypresses");function lu(){let e="";return{push(t){let n=OR(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(lu,"createInputParser");import{createContext as DR}from"react";var Lw=DR({exit(){}});Lw.displayName="InternalAppContext";var Ow=Lw;import{EventEmitter as NR}from"node:events";import{createContext as BR}from"react";var HR={isTTY:!1,isRaw:!1,on(){},off(){},pause(){},resume(){},setRawMode(){}},Dw=BR({stdin:HR,internal_eventEmitter:new NR,setRawMode(){},isRawModeSupported:!1,internal_exitOnCtrlC:!0});Dw.displayName="InternalStdinContext";var Nw=Dw;import{createContext as FR}from"react";var WR={isTTY:!1,columns:80,rows:24,write(){return!0},on(){},off(){}},Bw=FR({stdout:WR,write(){}});Bw.displayName="InternalStdoutContext";var Hw=Bw;import{createContext as UR}from"react";var jR={isTTY:!1,write(){return!0},on(){},off(){}},Fw=UR({stderr:jR,write(){}});Fw.displayName="InternalStderrContext";var Ww=Fw;import{createContext as GR}from"react";var Uw=GR({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});Uw.displayName="InternalFocusContext";var jw=Uw;import{createContext as KR}from"react";var Gw=KR({setCursorPosition(){}});Gw.displayName="InternalCursorContext";var Kw=Gw;import zR,{PureComponent as XR}from"react";import*as uu from"node:fs";import{cwd as Xw}from"node:process";import wt from"react";import Vw from"stack-utils";import VR from"code-excerpt";var Fm=i(e=>e?.replace(`file://${Xw()}/`,""),"cleanupPath"),zw=new Vw({cwd:Xw(),internals:Vw.nodeInternals()});function Wm({error:e}){let t=e.stack?e.stack.split(`
|
|
24
|
+
`).slice(1):void 0,n=t?zw.parseLine(t[0]):void 0,o=Fm(n?.file),r,s=0;if(o&&n?.line&&uu.existsSync(o)){let a=uu.readFileSync(o,"utf8");if(r=VR(a,n.line),r)for(let{line:c}of r)s=Math.max(s,String(c).length)}return wt.createElement(wn,{flexDirection:"column",padding:1},wt.createElement(wn,null,wt.createElement(Yt,{backgroundColor:"red",color:"white"}," ","ERROR"," "),wt.createElement(Yt,null," ",e.message)),n&&o&&wt.createElement(wn,{marginTop:1},wt.createElement(Yt,{dimColor:!0},o,":",n.line,":",n.column)),n&&r&&wt.createElement(wn,{marginTop:1,flexDirection:"column"},r.map(({line:a,value:c})=>wt.createElement(wn,{key:a},wt.createElement(wn,{width:s+1},wt.createElement(Yt,{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," "),":")),wt.createElement(Yt,{key:a,backgroundColor:a===n.line?"red":void 0,color:a===n.line?"white":void 0}," "+c)))),e.stack&&wt.createElement(wn,{marginTop:1,flexDirection:"column"},e.stack.split(`
|
|
25
|
+
`).slice(1).map(a=>{let c=zw.parseLine(a);return c?wt.createElement(wn,{key:a},wt.createElement(Yt,{dimColor:!0},"- "),wt.createElement(Yt,{dimColor:!0,bold:!0},c.function),wt.createElement(Yt,{dimColor:!0,color:"gray","aria-label":`at ${Fm(c.file)??""} line ${c.line} column ${c.column}`}," ","(",Fm(c.file)??"",":",c.line,":",c.column,")")):wt.createElement(wn,{key:a},wt.createElement(Yt,{dimColor:!0},"- "),wt.createElement(Yt,{dimColor:!0,bold:!0},a,"\\t"," "))})))}i(Wm,"ErrorOverview");var Ma=class extends XR{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?zR.createElement(Wm,{error:this.state.error}):this.props.children}};var JR=" ",ZR="\x1B[Z",eE="\x1B";function qw({children:e,stdin:t,stdout:n,stderr:o,writeToStdout:r,writeToStderr:s,exitOnCtrlC:a,onExit:c,setCursorPosition:l}){let[d,m]=Um(!0),[p,g]=Um(void 0),[,x]=Um([]),y=zi(0),T=zi(0),w=zi(new YR);w.current.setMaxListeners(1/0);let I=zi(void 0),O=zi(lu()),$=zi(void 0),D=pt(()=>{$.current&&(clearImmediate($.current),$.current=void 0)},[]),L=t.isTTY,X=pt(()=>{I.current&&(t.removeListener("readable",I.current),I.current=void 0)},[t]),v=pt(()=>{t.setRawMode(!1),X(),t.unref(),T.current=0,O.current.reset(),D()},[t,X,D]),ie=pt(ee=>{L&&T.current>0&&v(),c(ee)},[L,v,c]),Te=pt(ee=>{if(ee===""&&a){ie();return}ee===eE&&g(A=>A&&void 0)},[a,ie]),G=pt(ee=>{Te(ee),w.current.emit("input",ee)},[Te]),q=pt(()=>{D(),$.current=setImmediate(()=>{$.current=void 0;let ee=O.current.flushPendingEscape();ee&&G(ee)})},[D,G]),M=pt(()=>{D();let ee;for(;(ee=t.read())!==null;){let A=O.current.push(ee);for(let _ of A)G(_)}O.current.hasPendingEscape()&&q()},[t,G,D,q]),C=pt(ee=>{if(!L)throw t===qR.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),I.current=M,t.addListener("readable",M)),T.current++;return}T.current!==0&&--T.current===0&&v()},[L,t,M,v]),Z=pt((ee,A)=>{let _=ee.findIndex(F=>F.id===A);for(let F=_+1;F<ee.length;F++){let J=ee[F];if(J?.isActive)return J.id}},[]),Re=pt((ee,A)=>{let _=ee.findIndex(F=>F.id===A);for(let F=_-1;F>=0;F--){let J=ee[F];if(J?.isActive)return J.id}},[]),Ie=pt(()=>{x(ee=>(g(A=>{let _=ee.find(J=>J.isActive)?.id;return Z(ee,A)??_}),ee))},[Z]),Se=pt(()=>{x(ee=>(g(A=>{let _=ee.findLast(J=>J.isActive)?.id;return Re(ee,A)??_}),ee))},[Re]);Yw(()=>{let ee=i(_=>{!d||y.current===0||(_===JR&&Ie(),_===ZR&&Se())},"handleTabNavigation");w.current.on("input",ee);let A=w.current;return()=>{A.off("input",ee)}},[d,Ie,Se]);let ce=pt(()=>{m(!0)},[]),Ne=pt(()=>{m(!1)},[]),ae=pt(ee=>{x(A=>(A.some(F=>F?.id===ee)&&g(ee),A))},[]),Y=pt((ee,{autoFocus:A})=>{x(_=>(y.current=_.length+1,[..._,{id:ee,isActive:!0}])),A&&g(_=>_??ee)},[]),Q=pt(ee=>{g(A=>A===ee?void 0:A),x(A=>{let _=A.filter(F=>F.id!==ee);return y.current=_.length,_})},[]),be=pt(ee=>{x(A=>A.map(_=>_.id!==ee?_:{id:ee,isActive:!0}))},[]),ve=pt(ee=>{g(A=>A===ee?void 0:A),x(A=>A.map(_=>_.id!==ee?_:{id:ee,isActive:!1}))},[]);Yw(()=>()=>{QR.show(n),L&&T.current>0&&v()},[n,L,v]);let lt=Xi(()=>({exit:ie}),[ie]),Ee=Xi(()=>({stdin:t,setRawMode:C,isRawModeSupported:L,internal_exitOnCtrlC:a,internal_eventEmitter:w.current}),[t,C,L,a]),je=Xi(()=>({stdout:n,write:r}),[n,r]),xe=Xi(()=>({stderr:o,write:s}),[o,s]),Rt=Xi(()=>({setCursorPosition:l}),[l]),Qe=Xi(()=>({activeId:p,add:Y,remove:Q,activate:be,deactivate:ve,enableFocus:ce,disableFocus:Ne,focusNext:Ie,focusPrevious:Se,focus:ae}),[p,Y,Q,be,ve,ce,Ne,Ie,Se,ae]);return Er.createElement(Ow.Provider,{value:lt},Er.createElement(Nw.Provider,{value:Ee},Er.createElement(Hw.Provider,{value:je},Er.createElement(Ww.Provider,{value:xe},Er.createElement(jw.Provider,{value:Qe},Er.createElement(Kw.Provider,{value:Rt},Er.createElement(Ma,{onError:ie},e)))))))}i(qw,"App");qw.displayName="InternalApp";var Qw=qw;var tE={disambiguateEscapeCodes:1,reportEventTypes:2,reportAlternateKeys:4,reportAllKeysAsEscapeCodes:8,reportAssociatedText:16};function Jw(e){let t=0;for(let n of e)t|=tE[n];return t}i(Jw,"resolveFlags");var Co={shift:1,alt:2,ctrl:4,super:8,hyper:16,meta:32,capsLock:64,numLock:128};var du=i(()=>{},"noop"),dE=27,fE=91,mE=63,pE=117,gE=48,hE=57,yE=i(e=>e>=gE&&e<=hE,"isDigitByte"),eS=i((e,t)=>{if(e[t]!==dE||e[t+1]!==fE||e[t+2]!==mE)return;let n=t+3,o=n;for(;n<e.length&&yE(e[n]);)n++;if(n!==o){if(n===e.length)return{state:"partial"};if(e[n]===pE)return{state:"complete",endIndex:n}}},"matchKittyQueryResponse"),xE=i(e=>{for(let t=0;t<e.length;t++)if(eS(e,t)?.state==="complete")return!0;return!1},"hasCompleteKittyQueryResponse"),wE=i(e=>{let t=[],n=0;for(;n<e.length;){let o=eS(e,n);if(o?.state==="complete"){n=o.endIndex+1;continue}if(o?.state==="partial")break;t.push(e[n]),n++}return t},"stripKittyQueryResponsesAndTrailingPartial"),jm=i(e=>e instanceof Error||Object.prototype.toString.call(e)==="[object Error]","isErrorInput"),SE=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){oE(this),this.options=t,this.rootNode=Xl("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=t.isScreenReaderEnabled??Yi.env.INK_SCREEN_READER==="true";let n=t.debug||this.isScreenReaderEnabled,o=t.maxFps??30,r=o>0?Math.max(1,Math.ceil(1e3/o)):0;if(n)this.rootNode.onRender=this.onRender,this.throttledOnRender=void 0;else{let a=nE(this.onRender,r,{leading:!0,trailing:!0});this.rootNode.onRender=()=>{this.hasPendingThrottledRender=!0,a()},this.throttledOnRender=a}this.rootNode.onImmediateRender=this.onRender,this.cellLogUpdate=new au({isTTY:!!t.stdout.isTTY}),this.prevFrame=Ea(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?aE:sE;this.container=So.createContainer(this.rootNode,s,null,!1,null,"id",()=>{},()=>{},()=>{},()=>{}),this.unsubscribeExit=rE(this.unmount,{alwaysLast:!1}),Vl()&&So.injectIntoDevTools(),t.patchConsole&&this.patchConsole(),Wo||(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:uE()?.columns??80,"getTerminalWidth");resized=i(()=>{let t=this.getTerminalWidth();if(t<this.lastTerminalWidth){let n=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";n.length>0&&this.options.stdout.write(n),this.lastOutput="",this.lastOutputToRender="",this.cellLogUpdate.reset(),this.prevFrame=Ea(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(jm(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(),o=this.options.stdout.rows??24;if(n<=0||o<=0){this.cursorPosition=void 0;return}let r=Math.max(0,Math.min(t.x|0,n-1)),s=Math.max(0,Math.min(t.y|0,o-1));this.cursorPosition={x:r,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 o=this.shellMode,r=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.shellMode=t,this.mouseTrackingActive=a;let c=this.usesVirtualShellOwnership();(o!==t&&(s||c)||r!==a&&c)&&this.resetOutputTracking()}setAltScreenActive(t,n){let o=this.altScreenActive,r=this.mouseTrackingActive,s=this.usesVirtualShellOwnership(),a=n??!1;this.altScreenActive=t,this.mouseTrackingActive=a,this.shellTransitionPhase=void 0;let c=this.usesVirtualShellOwnership();(o!==t||r!==a&&(s||c))&&this.resetOutputTracking()}clearTextSelection(){}restoreLastOutput=i(()=>{if(this.prevFrame.screen.height===0)return;let t=Ea(this.options.stdout.rows??24,this.getTerminalWidth()),n=this.cellLogUpdate.render(t,this.prevFrame);cu(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,cE.DIRECTION_LTR)},"calculateLayout");onRender=i(()=>{if(this.hasPendingThrottledRender=!1,this.isUnmounted)return;!this.cursorHidden&&!Wo&&!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:o,outputHeight:r,staticOutput:s,frame:a}=ww(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+o);return}if(Wo){c&&this.options.stdout.write(s),this.lastOutput=o,this.lastOutputToRender=o+`
|
|
29
|
+
`,this.lastOutputHeight=r;return}if(this.isScreenReaderEnabled){let p=Vi(this.options.stdout);if(p&&this.options.stdout.write(Ki),c){let y=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(y+s),this.lastOutputHeight=0}if(o===this.lastOutput&&!c){p&&this.options.stdout.write(Rr);return}let g=this.getTerminalWidth(),x=lE(o,g,{trim:!1,hard:!0});if(c)this.options.stdout.write(x);else{let y=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(y+x)}this.lastOutput=o,this.lastOutputToRender=x,this.lastOutputHeight=x===""?0:x.split(`
|
|
30
|
+
`).length,p&&this.options.stdout.write(Rr);return}c&&(this.fullStaticOutput+=s);let l=this.altScreenActive,m=this.options.stdout.isTTY&&r>=this.options.stdout.rows&&l?o:o+`
|
|
31
|
+
`;if(this.lastOutputHeight>=this.options.stdout.rows&&l){let p=Vi(this.options.stdout);p&&this.options.stdout.write(Ki);let g=this.fullStaticOutput+m;if(this.altScreenActive){let x=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(x+g)}else this.options.stdout.write(bo.clearTerminal+this.fullStaticOutput+o);this.lastOutput=o,this.lastOutputToRender=this.altScreenActive?g:m,this.lastOutputHeight=r,this.invalidateCellFrame(),p&&this.options.stdout.write(Rr);return}if(c){let p=Vi(this.options.stdout);p&&this.options.stdout.write(Ki);let g=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(g+s),this.invalidateCellFrame(),this.applyCellFrame(a),p&&this.options.stdout.write(Rr)}else this.applyCellFrame(a);this.lastOutput=o,this.lastOutputToRender=m,this.lastOutputHeight=r},"onRender");applyCellFrame=i(t=>{let n={cellLogUpdate:this.cellLogUpdate,prevFrame:this.prevFrame,stdout:this.options.stdout},o=Aw(n,t);return this.prevFrame=n.prevFrame,o},"applyCellFrame");invalidateCellFrame=i(()=>{this.cellLogUpdate.reset(),this.prevFrame=Ea(this.options.stdout.rows??24,this.getTerminalWidth())},"invalidateCellFrame");render(t){let n=Zw.createElement(Ni.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},Zw.createElement(Qw,{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?So.updateContainer(n,this.container,null,du):(So.updateContainerSync(n,this.container,null,du),So.flushSyncWork())}writeToStdout(t){if(this.isUnmounted)return;if(this.options.debug){this.options.stdout.write(t+this.fullStaticOutput+this.lastOutput);return}if(Wo){this.options.stdout.write(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.options.stdout.write(t),this.invalidateCellFrame();return}let n=Vi(this.options.stdout);n&&this.options.stdout.write(Ki);let o=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(o+t),this.restoreLastOutput(),n&&this.options.stdout.write(Rr)}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(Wo){this.options.stderr.write(t);return}if(!this.shouldRestoreManagedShellAfterExternalWrite()){this.options.stderr.write(t),this.invalidateCellFrame();return}let n=Vi(this.options.stdout);n&&this.options.stdout.write(Ki);let o=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";o.length>0&&this.options.stdout.write(o),this.options.stderr.write(t),this.restoreLastOutput(),n&&this.options.stdout.write(Rr)}unmount(t){if(this.isUnmounted||this.isUnmounting)return;this.isUnmounting=!0,this.beforeExitHandler&&(Yi.off("beforeExit",this.beforeExitHandler),this.beforeExitHandler=void 0);let n=this.options.stdout,o=!n.destroyed&&!n.writableEnded&&(n.writable??!0);if(i(d=>{typeof d.flush=="function"&&(o?d.flush():typeof d.cancel=="function"&&d.cancel())},"settleThrottle")(this.throttledOnRender??{}),o&&(!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(),o){if(this.kittyProtocolEnabled)try{this.options.stdout.write("\x1B[<u")}catch{}Wo&&this.options.stdout.write(this.lastOutput+`
|
|
32
|
+
`)}this.kittyProtocolEnabled=!1,this.shellTransitionPhase=void 0,this.options.concurrent?So.updateContainer(null,this.container,null,du):(So.updateContainerSync(null,this.container,null,du),So.flushSyncWork()),_w.delete(this.options.stdout);let{exitResult:s}=this,a=i(()=>{jm(t)?this.rejectExitPromise(t):this.resolveExitPromise(s)},"resolveOrReject"),c=t!==void 0&&!jm(t),l=n._writableState!==void 0||n.writableLength!==void 0;c?a():o&&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()},Yi.once("beforeExit",this.beforeExitHandler)),this.exitPromise}clear(){if(!Wo&&!this.options.debug){let t=this.lastOutputHeight>0?bo.eraseLines(this.lastOutputHeight):"";t.length>0&&this.options.stdout.write(t),this.invalidateCellFrame()}}patchConsole(){this.options.debug||(this.restoreConsole=iE((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 o=t.flags??["disambiguateEscapeCodes"];if(n==="enabled"){this.enableKittyProtocol(o);return}let r=Yi.env.TERM??"",s=Yi.env.TERM_PROGRAM??"",a="KITTY_WINDOW_ID"in Yi.env||r==="xterm-kitty"||s==="WezTerm"||s==="ghostty";!Wo&&a&&this.confirmKittySupport(o)}confirmKittySupport(t){let{stdin:n,stdout:o}=this.options,r=[],s=i(()=>{this.cancelKittyDetection=void 0,clearTimeout(c),n.removeListener("data",a);let l=wE(r);r=[],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)r.push(m);xE(r)&&(s(),this.isUnmounted||this.enableKittyProtocol(t))},"onData");n.on("data",a);let c=setTimeout(s,200);this.cancelKittyDetection=s,o.write("\x1B[?u")}enableKittyProtocol(t){this.options.stdout.write(`\x1B[>${Jw(t)}u`),this.kittyProtocolEnabled=!0}},tS=SE;var Aa=class{static{i(this,"KodaXRenderer")}engineInstance;isConcurrent;constructor(t){this.engineInstance=new tS(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 Uo=null;function oS(){if(Uo===-1)return null;if(Uo!==null)return Uo;let e=process.env.KODAX_RENDER_TRACE;if(!e||e==="0"||e==="false")return Uo=-1,null;let t=e==="1"||e==="true"?IE(vE(),`kodax-render-trace-${process.pid}.log`):e;try{return Uo=CE(t,"a"),nS(Uo,`=== KODAX render trace pid=${process.pid} ${new Date().toISOString()} platform=${process.platform} node=${process.version} ===
|
|
33
|
+
`),Uo}catch{return Uo=-1,null}}i(oS,"resolveTraceFd");function kE(e){let t=oS();if(t!==null)try{nS(t,e)}catch{}}i(kE,"traceLine");var fu=new WeakMap,RE={isTTY:!1,columns:80,rows:24,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")},EE={isTTY:!1,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")},ME={isTTY:!1,isRaw:!1,on:i(()=>{},"on"),off:i(()=>{},"off"),pause:i(()=>{},"pause"),resume:i(()=>{},"resume"),setRawMode:i(()=>{},"setRawMode")};function AE(e={}){return e instanceof TE?{stdout:e}:e}i(AE,"getOptions");function _E(e,t,n){let o=fu.get(e);return o?o.isConcurrent!==n&&console.warn(`Warning: render() was called with concurrent: ${n}, but the existing renderer for this stdout uses concurrent: ${o.isConcurrent}. The concurrent option only takes effect on the first render. Call unmount() first if you need to change the rendering mode.`):(o=t(),fu.set(e,o)),o}i(_E,"getInstance");function mu(e){return fu.get(e)}i(mu,"getRendererInstance");function Gm(e,t){let n={stdout:RE,stdin:ME,stderr:EE,debug:!1,exitOnCtrlC:!0,patchConsole:!1,maxFps:30,concurrent:!1,...AE(t)};if(oS()!==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=bE.now(),y=d===0?0:x-d,T=s,w=T.columns??0,I=T.rows??0;return kE(`frame=${m} renderTime=${g.renderTime.toFixed(2)}ms interval=${y.toFixed(2)}ms writes=${c} bytes=${l} viewport=${w}x${I}
|
|
34
|
+
`),c=0,l=0,d=x,m+=1,p?.(g)}}let r=_E(n.stdout,()=>new Aa(n),n.concurrent??!1);return r.render(e),{rerender:r.render,unmount(){r.unmount()},waitUntilExit:r.waitUntilExit,cleanup:i(()=>{fu.delete(n.stdout)},"cleanup"),clear:r.clear}}i(Gm,"render");var rS=wn,iS=Yt,sS=Im;import{Buffer as PE}from"node:buffer";var LE=/^(?:\x1b)([a-zA-Z0-9])$/,OE=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,cS={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"},lS=[...Object.values(cS),"backspace"],DE=i(e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),"isShiftKey"),NE=i(e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),"isCtrlKey"),uS=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,BE=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,HE={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},FE={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"},aS={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"},dS=i(e=>e>=0&&e<=1114111&&!(e>=55296&&e<=57343),"isValidCodepoint"),Km=i(e=>dS(e)?String.fromCodePoint(e):"?","safeFromCodePoint");function fS(e){return e===3?"release":e===2?"repeat":"press"}i(fS,"resolveEventType");function mS(e){return{ctrl:!!(e&Co.ctrl),shift:!!(e&Co.shift),meta:!!(e&Co.meta),option:!!(e&Co.alt),super:!!(e&Co.super),hyper:!!(e&Co.hyper),capsLock:!!(e&Co.capsLock),numLock:!!(e&Co.numLock)}}i(mS,"parseKittyModifiers");function WE(e){let t=uS.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),o=t[2]?Math.max(0,Number.parseInt(t[2],10)-1):0,r=t[3]?Number.parseInt(t[3],10):1,s=t[4];if(!dS(n))return null;let a;s&&(a=s.split(":").map(d=>Km(Number.parseInt(d,10))).join(""));let c,l;return n===32?(c="space",l=!0):n===13?(c="return",l=!0):aS[n]?(c=aS[n],l=!1):n>=1&&n<=26?(c=String.fromCodePoint(n+96),l=!1):(c=Km(n).toLowerCase(),l=!0),l&&!a&&(a=Km(n)),{name:c,...mS(o),eventType:fS(r),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:l,text:a}}i(WE,"parseKittyKeypress");function UE(e){let t=BE.exec(e);if(!t)return null;let n=Number.parseInt(t[1],10),o=Math.max(0,Number.parseInt(t[2],10)-1),r=Number.parseInt(t[3],10),s=t[4],a=s==="~"?FE[n]:HE[s];return a?{name:a,...mS(o),eventType:fS(r),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1}:null}i(UE,"parseKittySpecialKey");var Vm="\x1B[200~",jE="\x1B[201~";function GE(e){if(!e.startsWith(Vm))return null;let t=e.indexOf(jE,Vm.length);return t===-1?null:e.slice(Vm.length,t)}i(GE,"extractBracketedPaste");function zm(e=""){let t=e,n;if(PE.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=GE(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 o=WE(t);if(o)return o;let r=UE(t);if(r)return r;if(uS.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=LE.exec(t))s.meta=!0,s.shift=/^[A-Z]$/.test(n[1]??"");else if(n=OE.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=cS[c]??"",s.shift=DE(c)||s.shift,s.ctrl=NE(c)||s.ctrl}return s}i(zm,"parseKeypress");var zE=50;function gu(e){return{columns:e?.columns??80,rows:e?.rows??24}}i(gu,"resolveTerminalSize");var jo=KE(null),Xm={isTTY:!1,columns:80,rows:24,write:i(()=>!0,"write"),on:i(()=>{},"on"),off:i(()=>{},"off")};var yS={isTTY:!1,isRaw:!1,on:i(()=>{},"on"),off:i(()=>{},"off"),pause:i(()=>{},"pause"),resume:i(()=>{},"resume"),setRawMode:i(()=>{},"setRawMode")};function XE(e){for(let t of e)if(t.rawMode)return!0;return!1}i(XE,"hasRawModeSubscribers");function YE({stdin:e,setRawMode:t,isRawModeSupported:n}){let o=new Set,r,s=!1,a=i(m=>{for(let p of o)p.listener(m)},"handleData"),c=i(()=>{if(s){try{t(!1)}catch{}s=!1}},"disableRawModeIfOwned"),l=i(()=>{r?.off?.("data",a),r=void 0,c()},"detachInput"),d=i(()=>{if(r&&r!==e&&l(),!e||o.size===0){l();return}if(r!==e&&(e.on?.("data",a),r=e),!(n&&XE(o))){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 o.add(g),d(),()=>{o.delete(g),d()}},dispose(){o.clear(),l()}}}i(YE,"createTerminalInputController");var qE=i(({children:e,runtime:t})=>{let[n,o]=VE(()=>t.terminalSize);qi(()=>{if(o(gu(t.stdout)),typeof t.stdout?.on!="function"||typeof t.stdout?.off!="function")return;let c=i(()=>{o(gu(t.stdout))},"handleResize");return t.stdout.on("resize",c),()=>{t.stdout.off?.("resize",c)}},[t.stdout]);let r=hS(c=>typeof t.stdout?.write!="function"?!1:(t.stdout.write(c),!0),[t.stdout]),s=pS(()=>YE({stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported}),[t.stdin,t.isRawModeSupported,t.setRawMode]);qi(()=>()=>{s.dispose()},[s]);let a=pS(()=>({stdout:t.stdout,stdin:t.stdin,setRawMode:t.setRawMode,isRawModeSupported:t.isRawModeSupported,exit:t.exit,terminalSize:n,isTTY:t.stdout?.isTTY===!0,writeRaw:r,subscribeInput:s.subscribe}),[s.subscribe,t.exit,t.isRawModeSupported,t.setRawMode,t.stdin,t.stdout,s.subscribe,n,r]);return gS(jo.Provider,{value:a,children:e})},"TuiRuntimeProvider");function QE(e){let t=e?.stdout??Xm,n=e?.stdin??yS,o=i(s=>{typeof n?.setRawMode=="function"&&n.setRawMode(s)},"setRawMode"),r;return{stdout:t,stdin:n,setRawMode:o,isRawModeSupported:typeof n?.setRawMode=="function",exit:i(()=>{r?.()},"exit"),terminalSize:gu(t),isTTY:t?.isTTY===!0,writeRaw:i(s=>typeof t?.write!="function"?!1:(t.write(s),!0),"writeRaw"),subscribeInput:i(()=>()=>{},"subscribeInput"),attachExit(s){r=s}}}i(QE,"createRuntimeValue");function hu(e,t){let n=QE(t),o=Gm(gS(qE,{runtime:n,children:e}),t);return n.attachExit(o.unmount),o}i(hu,"render");var k=rS,b=iS,Qi=sS;function JE(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&&lS.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(JE,"createCompatKeypress");function yu(e,t={}){let{isActive:n=!0}=t,o=pu(e),r=pu(null),s=pu(null);qi(()=>{o.current=e},[e]),qi(()=>{if(!n){r.current=null,s.current&&(clearTimeout(s.current),s.current=null);return}return r.current=lu(),()=>{r.current?.reset(),r.current=null,s.current&&(clearTimeout(s.current),s.current=null)}},[n]);let a=hS(c=>{let{input:l,key:d}=JE(zm(c));l==="c"&&d.ctrl||o.current(l,d)},[]);$a(c=>{if(!n)return;s.current&&(clearTimeout(s.current),s.current=null);let l=r.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=r.current?.flushPendingEscape();p&&a(p)},zE))},{isActive:n,rawMode:!0})}i(yu,"useInput");function Jn(){return{stdout:Mr(jo)?.stdout??Xm}}i(Jn,"useStdout");function _a(){let e=Mr(jo),t=e?.stdin??yS,n=e?.setRawMode??(o=>{typeof t?.setRawMode=="function"&&t.setRawMode(o)});return{stdin:t,setRawMode:n,isRawModeSupported:e?.isRawModeSupported??typeof t?.setRawMode=="function"}}i(_a,"useStdin");function Go(){return{exit:Mr(jo)?.exit??(()=>{})}}i(Go,"useApp");function Ji(){return Mr(jo)?.stdout??Xm}i(Ji,"useTerminalOutput");function Zi(){let e=Ji();return Mr(jo)?.terminalSize??gu(e)}i(Zi,"useTerminalSize");function es(){let e=Ji();return Mr(jo)?.writeRaw??(n=>typeof e?.write!="function"?!1:(e.write(n),!0))}i(es,"useTerminalWrite");function $a(e,t={}){let{isActive:n=!0,rawMode:o=!0}=t,r=Mr(jo),{stdin:s,setRawMode:a,isRawModeSupported:c}=_a(),l=pu(e);qi(()=>{l.current=e},[e]),qi(()=>{if(!n||!s)return;if(r)return r.subscribeInput(g=>{l.current(g)},{rawMode:o});let d=s,m=d.isRaw;o&&c&&m===!1&&a(!0);let p=i(g=>{l.current(g)},"handleData");return d.on?.("data",p),()=>{if(d.off?.("data",p),o&&c&&m===!1)try{a(!1)}catch{}}},[r,s,n,o,c,a])}i($a,"useTerminalInput");import{jsx as rM}from"react/jsx-runtime";import{useInsertionEffect as iM,useMemo as sM}from"react";var ZE="\x1B[?1049h",eM="\x1B[?1049l";var tM="\x1B[2J",nM="\x1B[?1000h\x1B[?1002h\x1B[?1006h",oM="\x1B[?1006l\x1B[?1002l\x1B[?1000l";function xu(e={}){let t=e.mouseTracking!==!1,n=e.clearOnEnter===!0;return ZE+(n?tM:"")+"\x1B[H"+(t?nM:"")}i(xu,"buildAlternateScreenEnterSequence");function wu(e={}){return(e.mouseTracking!==!1?oM:"")+eM}i(wu,"buildAlternateScreenExitSequence");var Ym=i(({children:e,mouseTracking:t=!0,enabled:n=!0,clearOnEnter:o=!1})=>{let r=Ji(),{rows:s}=Zi(),a=es(),c=sM(()=>n&&r.isTTY===!0,[n,r]);return iM(()=>{if(!c)return;let l=mu(r);if(l?.setShellMode?.("virtual",t),l?.beginShellTransition?.("enter-alt-screen"),!!a(xu({mouseTracking:t,clearOnEnter:o})))return l?.setAltScreenActive?.(!0,t),()=>{l?.beginShellTransition?.("exit-alt-screen"),l?.clearTextSelection?.(),l?.setAltScreenActive?.(!1),a(wu({mouseTracking:t}))}},[o,c,t,r,a]),rM(k,{flexDirection:"column",height:s,width:"100%",flexGrow:1,flexShrink:0,children:e})},"AlternateScreen");import{jsx as Ko,jsxs as TS}from"react/jsx-runtime";import{jsx as aM}from"react/jsx-runtime";import cM,{useEffect as qm,useImperativeHandle as lM,useMemo as uM,useRef as Qm,useCallback as Jm,useState as dM}from"react";function xS(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:Zm(t,t.scrollTop)}}i(xS,"normalizeScrollSnapshot");function wS(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(wS,"areSnapshotsEqual");function fM(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(fM,"areWindowsEqual");function Zm(e,t){let n=Math.max(0,e.scrollHeight-e.viewportHeight),o=e.clampMin??0,r=e.clampMax??n;return Math.max(o,Math.min(Math.floor(t),Math.min(n,r)))}i(Zm,"clampScrollTop");function SS(e){let t=Math.max(0,e.viewportHeight),n=Zm(e,e.scrollTop),o=Math.max(0,e.scrollHeight-n),r=Math.max(0,o-t);return{start:r,end:o,scrollTop:n,scrollHeight:e.scrollHeight,viewportHeight:t,viewportTop:r,pendingDelta:e.pendingDelta,sticky:e.sticky}}i(SS,"resolveScrollWindow");function mM(e){let t=Zm(e,e.scrollTop);return Math.max(0,e.scrollHeight-e.viewportHeight-t)}i(mM,"resolveNativeScrollTop");var ep=i(({children:e,width:t,flexGrow:n=0,flexShrink:o=1,paddingTop:r=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=Qm(null),T=Qm(new Set),w=Qm(xS({scrollTop:s,scrollHeight:a,viewportHeight:c,pendingDelta:0,sticky:l})),[I,O]=dM(()=>SS(w.current)),$=Jm(()=>{for(let G of T.current)G()},[]),D=Jm((G,q=!0)=>{let M=w.current,C=xS(G),Z=SS(C);return w.current=C,O(Re=>fM(Re,Z)?Re:Z),q&&!wS(M,C)&&$(),{previous:M,snapshot:C,window:Z,changed:!wS(M,C)}},[$]);qm(()=>{let G=w.current,q={scrollTop:s,scrollHeight:a,viewportHeight:c,pendingDelta:0,clampMin:G.clampMin,clampMax:G.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=Jm(()=>{let G=y.current;if(!G)return;let q=typeof G.scrollHeight=="number"?Math.max(0,Math.floor(G.scrollHeight)):void 0,M=typeof G.scrollViewportHeight=="number"?Math.max(0,Math.floor(G.scrollViewportHeight)):void 0,C=typeof G.scrollViewportTop=="number"?Math.max(0,Math.floor(G.scrollViewportTop)):void 0;if(q===void 0||M===void 0||C===void 0)return;let Z=Math.max(0,q-M-C),Re=D({...w.current,scrollTop:Z,scrollHeight:q,viewportHeight:M});Re.changed&&Re.window.scrollTop!==Re.previous.scrollTop&&m?.(Re.window.scrollTop)},[D,m]);qm(()=>{L()},[L]);let X=uM(()=>({scrollTo(G){let q=D({...w.current,scrollTop:G,pendingDelta:0,sticky:!1});q.previous.sticky!==!1&&p?.(!1),m?.(q.window.scrollTop)},scrollBy(G){let q=D({...w.current,scrollTop:w.current.scrollTop+G,pendingDelta:w.current.pendingDelta+Math.floor(G),sticky:!1});q.previous.sticky!==!1&&p?.(!1),m?.(q.window.scrollTop)},scrollToElement(G,q=0){let M=D({...w.current,scrollTop:G-q,pendingDelta:0,sticky:!1});M.previous.sticky!==!1&&p?.(!1),m?.(M.window.scrollTop)},scrollToBottom(){let G=D({...w.current,scrollTop:0,pendingDelta:0,sticky:!0});m?.(G.window.scrollTop),G.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??I.viewportHeight},getViewportTop(){return y.current?.scrollViewportTop??I.viewportTop},isSticky(){return w.current.sticky},subscribe(G){return T.current.add(G),()=>{T.current.delete(G)}},setClampBounds(G,q){let M=D({...w.current,clampMin:G,clampMax:q});M.window.scrollTop!==M.previous.scrollTop&&m?.(M.window.scrollTop)}}),[D,m,p]);lM(d,()=>X,[X]),qm(()=>{g?.(I)},[g,I]);let v=x?x(I):e,ie=Math.max(0,c+r),Te=mM(w.current);return cM.createElement("ink-box",{ref:y,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:n,flexShrink:o,width:t,height:ie,paddingTop:r,overflowX:"visible",overflowY:"scroll"},scrollTop:Te,scrollHeight:w.current.scrollHeight,scrollViewportHeight:w.current.viewportHeight,scrollViewportTop:I.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}:{}},aM(k,{flexDirection:"column",flexGrow:1,flexShrink:0,width:"100%",children:v}))},"ScrollBox");var pM=80;function Pa(e){if(!(!e?.visible||!e.label))return e.hint?`${e.label}: ${e.hint}`:e.label}i(Pa,"resolveFullscreenChromeSlotText");function Su(e,t){if(!e)return 0;let n=Math.max(1,(typeof t=="number"?t:pM)-2);return Math.max(1,Xt(e.split(`
|
|
36
|
+
`),n,0,0).visualLines.length)}i(Su,"measureFullscreenChromeSlotRows");var tp=i(({top:e,topRows:t=0,scrollable:n,renderScrollableWindow:o,bottom:r,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 I=i((Te,G)=>G?Ko(k,{paddingX:1,children:Ko(b,{dimColor:Te?.tone!=="accent",children:G})}):null,"renderChromeSlot"),O=Pa(a),$=Pa(c),D=Su(O,l),L=I(a,O),X=s?null:I(c,$),v=Math.max(0,e?t:0),ie=Math.max(0,p-D-v);return TS(k,{flexDirection:"column",width:l,flexGrow:1,flexShrink:0,children:[e?Ko(k,{flexDirection:"column",flexShrink:0,children:e}):null,TS(k,{flexDirection:"column",flexGrow:1,overflowY:"hidden",children:[Ko(ep,{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:o,children:n}),L?Ko(k,{position:"absolute",top:0,left:0,right:0,flexDirection:"column",children:L}):null,X?Ko(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:X}):null,s?Ko(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:s}):null]}),Ko(k,{flexDirection:"column",flexShrink:0,children:r})]})},"FullscreenLayout");import hM from"string-width";function yM(){return Zi().columns}i(yM,"useTerminalWidth");var np=i(({lines:e,cursorRow:t,cursorCol:n,prompt:o=">",placeholder:r="Type your message...",focus:s=!0,terminalFocused:a=!0,isPasting:c=!1,editingMode:l="idle",theme:d="dark",width:m})=>{let p=Tu(()=>ne(d),[d]),g=yM(),x=m??g,y=hM(o)+1,T=Tu(()=>{let L=Math.max(20,x-y);return Xt(e,L,t,n)},[e,x,t,n,y]),w=Tu(()=>{if(!T)return null;let[L,X]=Cm(T,[t,n]);return{row:L,col:X}},[T,t,n]),I=s&&a,O=c&&e.some(L=>L.length>0),$=T,D=w;return Sn(k,{flexDirection:"column",borderStyle:"round",borderColor:p.colors.dim,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,width:m??"100%",children:[O?qt(k,{children:qt(b,{dimColor:!0,children:l==="pasting"?"Pasting input...":"Editing input..."})}):null,$.visualLines.length===0||$.visualLines.length===1&&$.visualLines[0]===""?Sn(k,{children:[Sn(b,{color:p.colors.primary,children:[o," "]}),I?Sn(gM,{children:[qt(b,{backgroundColor:p.colors.primary,color:"#000000",children:" "}),qt(b,{dimColor:!0,children:r})]}):qt(b,{dimColor:!0,children:r})]}):$.visualLines.map((L,X)=>{let v=X===D.row,ie=X===0?o:" ".repeat(y-1);if(v&&I){let{before:Te,current:G,after:q}=Gx(L,D.col),M=G||" ";return Sn(k,{children:[Sn(b,{color:p.colors.primary,children:[ie," "]}),qt(b,{color:p.colors.text,children:Te}),qt(b,{backgroundColor:p.colors.primary,color:"#000000",children:M}),qt(b,{color:p.colors.text,children:q})]},X)}return Sn(k,{children:[Sn(b,{color:p.colors.dim,children:[ie," "]}),qt(b,{color:p.colors.text,children:L})]},X)})]})},"TextInput"),xM=i(({value:e,cursorCol:t,prompt:n=">",placeholder:o,focus:r=!0,theme:s="dark"})=>{let a=Tu(()=>ne(s),[s]);if(!e)return Sn(k,{children:[Sn(b,{color:a.colors.primary,children:[n," "]}),o&&qt(b,{dimColor:!0,children:o}),r&&qt(b,{backgroundColor:a.colors.primary,color:"#000000",children:" "})]});let c=zt(e),l=c.slice(0,t).join(""),d=c[t]??" ",m=c.slice(t+1).join("");return Sn(k,{children:[Sn(b,{color:a.colors.primary,children:[n," "]}),qt(b,{color:a.colors.text,children:l}),qt(b,{backgroundColor:a.colors.primary,color:"#000000",children:d}),qt(b,{color:a.colors.text,children:m})]})},"SingleLineTextInput");var op={"[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"}},wM=/^\x1b\[([0-9]+);?([0-9]+)?([~A-Za-z])?/,SM=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/;function TM(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"unknown"}}i(TM,"parseMouseButton");function CM(e){return{shift:(e&1)!==0,alt:(e&2)!==0,ctrl:(e&4)!==0,meta:(e&8)!==0}}i(CM,"parseModifier");function Cu(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 o=e.match(SM);if(o){let[,r,s,a,c]=o,l=Number(r),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:TM(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 r=e.slice(1);if(r.length===1)return n.meta=!0,r>="a"&&r<="z"?(n.name=r,n.insertable=!0):r>="A"&&r<="Z"?(n.name=r.toLowerCase(),n.shift=!0,n.insertable=!0):r.charCodeAt(0)>=32&&(n.name=r,n.insertable=!0),n;let s=e.match(wM);if(s){let[,l,d,m]=s,p=m||"~",x=op[r];if(x)return Object.assign(n,x),n;let y="["+l+p+"]",T=op[y];if(T&&T.name){if(n.name=T.name,d){let w=parseInt(d,10)-1,I=CM(w);Object.assign(n,I)}return n}}let c=op[r];if(c)return Object.assign(n,c),n;if(e.startsWith("\x1B\x1B")){n.meta=!0;let l="\x1B"+e.slice(2),d=Cu(l);return n.name=d.name,n}}return n}i(Cu,"parseKeypress");var La=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 o=typeof t=="string"?t:t.toString("utf8");this.buffer+=o,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=Cu(s,this.inBracketedPaste);this.emit(a)}break}let{sequence:n,remaining:o}=t;this.buffer=o;let r=Cu(n,this.inBracketedPaste);if(r.name==="paste_start"){this.inBracketedPaste=!0,this.pasteAccumulator="";continue}if(r.name==="paste_end"){this.inBracketedPaste=!1,this.flushPasteAccumulator();continue}this.emit(r)}}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 o=2;for(;o<this.buffer.length;){let a=this.buffer[o];if(!a)break;if(a>="0"&&a<="9"||a===";"){o++;continue}if(a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="~"){o++;break}break}let r=this.buffer[o-1];return r&&(r>="A"&&r<="Z"||r>="a"&&r<="z"||r==="~")?{sequence:this.buffer.slice(0,o),remaining:this.buffer.slice(o)}:this.flushing?{sequence:this.buffer.slice(0,o),remaining:this.buffer.slice(o)}: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 CS(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(CS,"isFunctionKey");function bM(e){return e.ctrl||e.meta||CS(e)?!1:e.sequence.length===1&&e.sequence.charCodeAt(0)>=32}i(bM,"isPrintable");function vM(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(vM,"getKeyDisplayName");var sn;(function(e){e.Idle="idle",e.Responding="responding",e.WaitingForConfirmation="waiting_for_confirmation"})(sn||(sn={}));var P;(function(e){e.Scheduled="scheduled",e.Validating="validating",e.AwaitingApproval="awaiting_approval",e.Executing="executing",e.Success="success",e.Error="error",e.Cancelled="cancelled"})(P||(P={}));var ZW={[P.Scheduled]:"\u25CB",[P.Validating]:"\u25CC",[P.AwaitingApproval]:"?",[P.Executing]:"\u25CB",[P.Success]:"\u2713",[P.Error]:"\u2717",[P.Cancelled]:"-"},Bt;(function(e){e[e.Low=-100]="Low",e[e.Normal=0]="Normal",e[e.High=100]="High",e[e.Critical=200]="Critical"})(Bt||(Bt={}));var rp={streamingState:sn.Idle,currentResponse:"",history:[],pendingToolCalls:[],sessionId:"",provider:"",model:"",isLoading:!1};import IM,{createContext as kM,useContext as RM,useEffect as bS,useCallback as EM,useRef as ip}from"react";var MM=50;function sp(){let e=new Map,t=null,n=i(()=>(t===null&&(t=[...e.keys()].sort((o,r)=>r-o)),t),"getSortedPriorities");return{register(o,r){return e.has(o)||e.set(o,[]),e.get(o).push(r),t=null,()=>{let s=e.get(o);if(!s)return;let a=s.indexOf(r);a>=0&&s.splice(a,1),s.length===0&&e.delete(o),t=null}},dispatch(o){let r=n();for(let s of r){let a=e.get(s);if(a)for(let c=a.length-1;c>=0;c-=1){let l=a[c];if(l&&l(o)===!0)return!0}}return!1},size(){let o=0;for(let r of e.values())o+=r.length;return o}}}i(sp,"createKeypressManager");var vS=kM(null);function bu({children:e,enabled:t=!0}){let{stdout:n}=Jn(),o=ip(sp()),r=ip(null),s=ip(null),a=EM(c=>{t&&o.current.dispatch(c)},[t]);return bS(()=>{if(!t)return;n?.write?.("\x1B[?2004h");let c=new La;r.current=c;let l=c.onKeypress(a);return()=>{s.current&&(clearTimeout(s.current),s.current=null),l(),r.current=null;try{n?.write?.("\x1B[?2004l")}catch{}}},[a,t,n]),$a(c=>{t&&(s.current&&clearTimeout(s.current),r.current?.feed(c),c.length!==0&&(s.current=setTimeout(()=>{r.current?.feed("",!0)},MM)))},{isActive:t,rawMode:!0}),IM.createElement(vS.Provider,{value:o.current},e)}i(bu,"KeypressProvider");function ap(){let e=RM(vS);if(!e)throw new Error("useKeypressManager must be used within a KeypressProvider");return e}i(ap,"useKeypressManager");function an(e,t,n=[]){let o=ap(),r=typeof e=="function",s,a,c;if(r){s=e;let l=t??{};c=l.isActive??!0;let d=l.priority;a=typeof d=="boolean"?d?Bt.High:Bt.Normal:d??Bt.Normal}else a=typeof e=="boolean"?e?Bt.High:Bt.Normal:e,s=t,c=!0;bS(()=>c?o.register(a,s):void 0,[o,a,c,...r?[]:n])}i(an,"useKeypress");function Tn(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(Tn,"createKeyMatcher");var IS={isEnter:Tn({name:"return"}),isEscape:Tn({name:"escape"}),isCtrlC:Tn({name:"c",ctrl:!0}),isCtrlD:Tn({name:"d",ctrl:!0}),isUp:Tn({name:"up"}),isDown:Tn({name:"down"}),isLeft:Tn({name:"left"}),isRight:Tn({name:"right"}),isBackspace:Tn({name:"backspace"}),isDelete:Tn({name:"delete"}),isTab:Tn({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 Oa=["plan","accept-edits","auto","auto-in-project"];function Qt(e){return e==="auto"||e==="auto-in-project"}i(Qt,"isAutoMode");function ts(e){switch(e){case"plan":return"Plan";case"accept-edits":return"Edits";case"auto":case"auto-in-project":return"Auto"}}i(ts,"permissionModeDisplayName");var AM='[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 vu(e=console.warn){let t=!1;return()=>{t||(t=!0,e(AM))}}i(vu,"createAutoInProjectDeprecationEmitter");var kS=Tx(),Cn=new Set(kS.filter(e=>e.sideEffect==="mutates-fs"&&e.requiredParams.includes("path")).map(e=>e.name)),RS=new Set(kS.filter(e=>e.sideEffect!=="readonly").map(e=>e.name)),ES=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"]),MS=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 Ar(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(Ar,"computeConfirmTools");function cp(e){return e!==void 0&&Oa.includes(e)}i(cp,"isPermissionMode");function Zn(e,t){return cp(e)?e:t}i(Zn,"normalizePermissionMode");import Iu from"fs";import St from"path";import Na from"os";var US=ek(HS(),1);var FS=new Set(["/dev/null","nul","NUL"]);function fp(e){return FS.has(e)||FS.has(e.toLowerCase())}i(fp,"isNullDevice");function Da(e){let t=e.trim();if(!t)return{statements:[],unparseable:!1};if(t.includes("`"))return{statements:[],unparseable:!0};let n;try{n=(0,US.parse)(t)}catch{return{statements:[],unparseable:!0}}let o=[],r=[],s=[],a=[],c=null,l=!1,d=i(()=>{(s.length>0||a.length>0)&&(r.push({argv:s,redirections:a}),s=[],a=[])},"flushStage"),m=i(p=>{d(),r.length>0&&(o.push({precedingOp:c,stages:r}),r=[]),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(WS(`&${y.op}`,T)),p+=2;continue}l=!0;continue}if(FM(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(WS(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:o,unparseable:l}}i(Da,"parseBashCommand");var HM=new Set([">",">>","<","<<","<<<","&>","&>>"]),jS=/^([0-9]+|&)(>>?|<<?)$/;function FM(e){return HM.has(e)||jS.test(e)}i(FM,"isRedirectionOp");function WS(e,t){let n=null,o=e,r=jS.exec(e);return r&&(n=r[1],o=r[2]),{op:e,fd:n,append:o===">>"||e==="&>>",input:o==="<"||o==="<<"||e==="<<<",target:t}}i(WS,"parseRedirection");var WM=St.join(".agent","plan_mode_doc.md"),ku=new Map,Ru=null;function UM(e){if(!e||!e.trim())return!1;let t=e.trim().replace(/\s+/g," ").toLowerCase();for(let n of MS)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 r=t.split(/\s+/);if(r.includes("-f")||r.includes("--file"))return!1}if(["node","npm","yarn","pnpm","tsc","python","pip","go","cargo","rustc","ruby","perl"].includes(n)){let r=t.split(/\s+/).slice(1);if(r.length>0&&!r.every(s=>/^(-v|--version|-h|--help)$/.test(s)))return!1}return!0}return!1}i(UM,"isSingleBashReadCommand");var jM=/^[a-zA-Z0-9]+$/;function GM(e){let t=e.trim();if(!t.endsWith("--help")||t.includes('"')||t.includes("'"))return!1;let n=!1;for(let o of t.split(/\s+/))if(o.startsWith("-"))if(o==="--help")n=!0;else return!1;else if(!jM.test(o))return!1;return n}i(GM,"isHelpCommand");function On(e){if(!e||!e.trim())return!1;if(GM(e))return!0;let t=e.trim().replace(/\\\r?\n/g," "),n=Da(t);if(n.unparseable||n.statements.length===0)return!1;let o=n.statements.length>1||(n.statements[0]?.stages.length??0)>1;for(let r of n.statements){if(r.precedingOp!==null&&r.precedingOp!=="&&")return!1;for(let s of r.stages){for(let c of s.redirections)if(c.input||!fp(c.target))return!1;let a=s.argv.join(" ");if(a&&!(o&&s.argv[0]?.toLowerCase()==="cd"&&s.argv.length>=2)&&!UM(a))return!1}}return!0}i(On,"isBashReadCommand");function pp(e){let t=e.trim();return t?On(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(pp,"getDirectShellBypassBlockReason");var KS=new Set(["remove-item","set-content","add-content","out-file","new-item","copy-item","move-item","rename-item","ni"]);function Dn(e){if(!e||!e.trim())return!1;let t=Da(e);if(t.unparseable)return!1;for(let n of t.statements)for(let o of n.stages){let r=o.argv.map(s=>s.toLowerCase());if(r.length>0){let s=r[0],a=r.length>=2?`${r[0]} ${r[1]}`:null;for(let c of ES)if(c===s||a!==null&&c===a)return!0}for(let s of r)if(KS.has(s))return!0;for(let s of o.redirections)if(!s.input&&!fp(s.target))return!0}return!1}i(Dn,"isBashWriteCommand");function gp(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(gp,"parseAllowedToolPattern");function KM(e,t){if(t==="*")return!1;if(t.endsWith(":*")){let n=t.slice(0,-2);return e.startsWith(n)}return e===t}i(KM,"matchesBashPatternLegacy");function VM(e,t){if(t==="*")return!1;if(t.endsWith(":*")){let n=t.slice(0,-2);return e===n}return e===t}i(VM,"matchesBashPatternByExtractedPrefix");async function Vo(e,t,n,o,r){if(e.toLowerCase()!=="bash")return!1;let s=t.command??"",a=[];for(let c of n){let l=gp(c);if(l.tool==="bash"){if(l.pattern===null)return!0;a.push({pattern:l.pattern})}}if(a.length===0)return!1;if(o){let c;try{c=await o.extract(s,r)}catch{return!1}if(c.kind!=="prefix")return!1;for(let{pattern:l}of a)if(l&&VM(c.value,l))return!0;return!1}for(let{pattern:c}of a)if(c&&KM(s,c))return!0;return!1}i(Vo,"isToolCallAllowed");function Mu(e,t,n){if(e.toLowerCase()!=="bash")return"";let o=t.command??"",r=o.split(" ");return r.length>1?`Bash(${r.slice(0,2).join(" ")}:*)`:`Bash(${o})`}i(Mu,"generateSavePattern");function eo(e,t){try{let n=St.resolve(e),o=St.resolve(t),r=Ti(),s=St.join(o,".kodax");return ns(n,s)||ns(n,r)?!0:!(ns(n,o)||XS().some(c=>ns(n,c)))}catch{return!1}}i(eo,"isAlwaysConfirmPath");function GS(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"&&zM.test(e)):!!(e.startsWith(".")&&/[/\\]/.test(e))}i(GS,"looksLikePath");var zM=/^\/[A-Za-z][A-Za-z0-9]*(?::[A-Za-z0-9]+)?$/;function XM(e){let t=[],n=/["']([^"']+)["']/g,o;for(;(o=n.exec(e))!==null;)t.push(o[1]);let r=/(?:^|\s)(\.\.?\/[^\s]+|\.\.?\\[^\s]+|[a-zA-Z]:\\[^\s]+|~\/[^\s]+|\.[^\s]*[/\\][^\s]*)/g;for(;(o=r.exec(e))!==null;)t.push(o[1]);return t}i(XM,"legacyRegexPathScan");function Au(e){let t=new Set,n=Da(e);if(!n.unparseable)for(let o of n.statements)for(let r of o.stages){for(let s of r.argv)GS(s)&&t.add(s);for(let s of r.redirections)GS(s.target)&&t.add(s.target)}for(let o of XM(e))t.add(o);return Array.from(t)}i(Au,"extractPathsFromCommand");function hp(e,t){let n=Au(e);for(let o of n)if(eo(o,t))return!0;return!1}i(hp,"isCommandOnProtectedPath");function Eu(e){let t=St.normalize(e);return process.platform==="win32"?t.toLowerCase():t}i(Eu,"normalizePathForComparison");function YM(e,t){return Eu(e)===Eu(t)}i(YM,"pathsEqual");function ns(e,t){let n=Eu(e),o=Eu(t);return n===o||n.startsWith(o+St.sep)}i(ns,"isPathInsideDirectory");function _u(e,t){try{let n=St.resolve(t),o=St.resolve(n,zS(VS(e)));return ns(o,n)}catch{return!1}}i(_u,"isPathInsideProject");function qM(e){let t=e.match(/[A-Za-z]:[\\/][^\s;|&<>(){}'"]+|\/[^\s;|&<>(){}'"]+/g);return t?t.filter(n=>!/^(?:\/dev\/|\/proc\/)/i.test(n)):[]}i(qM,"collectAbsolutePathCandidates");function yp(e){let t=St.resolve(e),n=ku.get(t);if(n)return n;if(Iu.existsSync(t)){let c=Iu.realpathSync.native(t);return ku.set(t,c),c}let o=[],r=t;for(;!Iu.existsSync(r);){let c=St.dirname(r);if(c===r)return ku.set(t,t),t;o.unshift(St.basename(r)),r=c}let s=Iu.realpathSync.native(r),a=St.join(s,...o);return ku.set(t,a),a}i(yp,"resolveExistingPathPrefix");function VS(e){return e==="~"?Na.homedir():e.startsWith(`~${St.sep}`)||e.startsWith("~/")||e.startsWith("~\\")?St.join(Na.homedir(),e.slice(2)):e}i(VS,"expandHomeDirectory");function zS(e){let t=Na.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[o,r]of n)if(o.test(e))return e.replace(o,r);return e}i(zS,"expandSystemTempAlias");function QM(e,t){let n=St.resolve(t??process.cwd()),o=zS(VS(e)),r=St.isAbsolute(o)?St.resolve(o):St.resolve(n,o);return yp(r)}i(QM,"resolvePermissionPath");function XS(){if(Ru)return Ru;let e=new Set,t=[Na.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(yp(n))}catch{}return Ru=Array.from(e),Ru}i(XS,"getSystemTempDirectories");function xp(e){let t=yp(e??process.cwd());return{projectPlanDoc:St.join(t,WM),systemTempDirs:XS()}}i(xp,"getPlanModeAllowedWritablePaths");function mp(e,t){let n=QM(e,t),{projectPlanDoc:o,systemTempDirs:r}=xp(t);return YM(n,o)?!0:r.some(s=>ns(n,s))}i(mp,"isPlanModeAllowedPath");function JM(e){let{projectPlanDoc:t,systemTempDirs:n}=xp(e),o=n[0]??Na.tmpdir();return`${t} or the system temp directory (${o})`}i(JM,"formatPlanModeAllowedLocations");var ZM=new Set(["-a","--append","-i","--ignore-interrupts"]);function eA(e){let t=[];for(let n=1;n<e.argv.length;n+=1){let o=e.argv[n];ZM.has(o)||o.startsWith("-")||t.push(o)}return t}i(eA,"collectTeeTargets");function tA(e){let t=[],n=1,o=!1;for(;n<e.argv.length;){let r=e.argv[n],s=r.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}}!r.startsWith("-")&&!o&&(t.push(r),o=!0),n+=1}return t}i(tA,"collectPowerShellWriteTargets");function $r(e){let t=new Set,n=i(r=>{let s=r?.trim();s&&t.add(s)},"pushTarget");for(let r of Au(e))n(r);let o=Da(e);if(o.unparseable)return Array.from(t);for(let r of o.statements)for(let s of r.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 eA(s))n(c);else if(KS.has(a))for(let c of tA(s))n(c)}}return Array.from(t)}i($r,"collectBashWriteTargets");function wp(e,t){if(!Dn(e))return{dangerous:!1};let n=new Set([...$r(e),...qM(e)]);for(let o of n)if(!_u(o,t))return{dangerous:!0,reason:`Command may modify file outside project: ${o}`};return{dangerous:!1}}i(wp,"getBashOutsideProjectWriteRisk");function vo(e,t,n){let o=JM(n);if(Cx(e))return null;if(Cn.has(e)){let r=typeof t.path=="string"?t.path:"";return r?mp(r,n)?null:`[Blocked] Plan mode only allows file modifications in ${o}. Requested path: ${r}`:`[Blocked] Tool '${e}' is not allowed in plan mode unless it targets ${o}.`}if(e==="bash"){let r=t.command??"";if(!Dn(r))return null;let s=$r(r);if(s.length===0)return`[Blocked] Plan mode only allows bash write operations when every target is either ${o}. Could not determine a safe target from: ${r.slice(0,80)}${r.length>80?"...":""}`;let a=s.find(c=>!mp(c,n));return a?`[Blocked] Plan mode only allows bash write operations in ${o}. 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 ${o}.`}i(vo,"getPlanModeBlockReason");import zo from"node:path";import nA from"node:os";function os(e,t){try{let n=zo.resolve(e),o=zo.resolve(t);return n===o?!0:n.startsWith(o+zo.sep)}catch{return!1}}i(os,"isPathUnder");function oA(){try{return Ti()}catch{return}}i(oA,"safeGetAgentConfigHome");function YS(e,t){let n=oA();if(n&&os(e,n))return"user-kodax";let o=zo.join(zo.resolve(t),".kodax");if(os(e,o))return"project-kodax"}i(YS,"resolveProtectedZone");function rA(){let e=new Set;try{e.add(nA.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(rA,"getSystemTempDirs");var iA=new Set(["bash"]),Ba={toolNames:iA,collect(e,t){let n=typeof e.input.command=="string"?e.input.command:"";if(!n||!t)return[];let o=[],r=new Set,s=new Set,a=rA(),c=zo.resolve(t);for(let l of Au(n)){let d;try{d=zo.resolve(t,l)}catch{continue}let m=YS(d,t);if(m){r.has(d)||(r.add(d),o.push({kind:"protected_path",path:l,zone:m}));continue}if(eo(l,t)){let p=a.some(x=>os(d,x)),g=os(d,c);!p&&!g&&!s.has(d)&&(s.add(d),o.push({kind:"outside_project",path:l}))}}for(let l of $r(n)){let d;try{d=zo.resolve(t,l)}catch{continue}YS(d,t)||os(d,c)||a.some(g=>os(d,g))||o.push({kind:"shell_redirect_outside",target:l})}return o}};function Wa(e){return e.type==="tool_summary"?{type:"event",text:e.text,icon:"tool"}:e}i(Wa,"seedToHistoryItem");var sA="[Thinking]",aA="[/Thinking]",cA="Untitled Session",qS=50,lA=60,JS="...",ZS=["[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:"],eT=[/(?:^|\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:/],uA=/(^|\r?\n)\[Thinking\]\r?\n([\s\S]*?)\r?\n\[\/Thinking\](?=\r?\n|$)/g;function dA(e){let t=-1;for(let n of ZS){let o=e.indexOf(n);o>=0&&(t===-1||o<t)&&(t=o)}for(let n of eT){let o=n.exec(e);o&&o.index>=0&&(t===-1||o.index<t)&&(t=o.index)}return t}i(dA,"findControlPlaneCutIndex");function fA(e){return ZS.some(t=>e.includes(t))||eT.some(t=>t.test(e))}i(fA,"hasControlPlaneSignal");function tT(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(tT,"collectTextBlocks");function mA(e){return typeof e=="string"?e:Array.isArray(e)?tT(e).join(`
|
|
42
|
+
`):""}i(mA,"extractAssistantTextOnly");function Fa(e,t,n){n.trim().length!==0&&e.push({type:t,text:n})}i(Fa,"pushSeed");function QS(e){return e.replace(/^\n+/,"").replace(/\n+$/,"")}i(QS,"stripLegacyTagBoundaryNewlines");function pA(e){let t=e.name,n=e.input;if(!n)return`\u26A1 ${t}`;let o=t==="bash"?Ha(String(n.command??"")):t==="read"||t==="write"||t==="edit"?Ha(String(n.file_path??n.path??"")):t==="grep"||t==="glob"?Ha(String(n.pattern??"")):t==="web_search"||t==="web_fetch"?Ha(String(n.query??n.url??"")):void 0;return o?`\u26A1 ${t}(${o})`:`\u26A1 ${t}`}i(pA,"formatToolUseSummary");function Ha(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}...`:n}i(Ha,"truncateToolHint");function gA(e){if(!e.includes(sA)||!e.includes(aA))return e.trim().length>0?[{type:"assistant",text:e}]:[];let t=[],n=0;for(let o of e.matchAll(uA)){let r=o.index??-1,s=o[1]??"",a=o[2]??"";if(r<0)continue;let c=r+s.length;Fa(t,"assistant",QS(e.slice(n,c))),Fa(t,"thinking",a),n=r+o[0].length}return Fa(t,"assistant",QS(e.slice(n))),t.length===0?e.trim().length>0?[{type:"assistant",text:e}]:[]:t}i(gA,"parseLegacyAssistantContent");function hA(e){if(typeof e=="string")return gA(e);if(!Array.isArray(e))return[];let t=[],n=[],o=i(()=>{n.length!==0&&(Fa(t,"assistant",n.join(`
|
|
43
|
+
`)),n.length=0)},"flushAssistantBuffer");for(let r of e)if(!(!r||typeof r!="object"||!("type"in r)))switch(r.type){case"text":"text"in r&&n.push(String(r.text));break;case"thinking":o(),"thinking"in r&&Fa(t,"thinking",String(r.thinking));break;case"tool_use":if(o(),"name"in r){let s=pA(r);s&&t.push({type:"tool_summary",text:s})}break;case"tool_result":case"redacted_thinking":break;default:break}return o(),t}i(hA,"extractAssistantHistorySeeds");var yA=["You are the Scout role","You are the Generator role","You are the Planner role","You are the Evaluator role"],xA=/\r?\n?\`\`\`kodax[\w-]*[\s\S]*?\`\`\`\s*/g;function wA(e){return yA.some(t=>e.includes(t))}i(wA,"isManagedWorkerPrompt");function SA(e){return e.replace(xA,"").trim()}i(SA,"stripManagedProtocolBlocks");function Ua(e){switch(e.role){case"assistant":return hA(e.content).map(n=>({...n,text:SA(n.text)})).filter(n=>n.text.length>0);case"user":{if(e._synthetic)return[];let t=ja(e.content);return t.trim().length===0||wA(t)?[]:[{type:"user",text:t}]}case"system":return[];default:return[]}}i(Ua,"extractHistorySeedsFromMessage");function ja(e){return typeof e=="string"?e:Array.isArray(e)?tT(e).join(`
|
|
44
|
+
`):""}i(ja,"extractTextContent");function TA(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>qS?`${t.slice(0,qS)}${JS}`:t:cA}i(TA,"formatSessionTitle");function Ga(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!=="assistant")continue;let o=mA(n.content);if(o)return o}return""}i(Ga,"extractLastAssistantText");function nT(e,t,n,o){let r=[Ga(e),t.trim(),n?.trim()??"",o?.trim()??""];for(let s of r){let a=Pr(s);if(a)return a}return""}i(nT,"resolveCompletedAssistantText");function Pr(e){let t=e.trim();if(!t)return"";let n=dA(t);return n===0?"":(n>0?t.slice(0,n):t).trim()}i(Pr,"sanitizeUserFacingAssistantText");function oT(e){let t=e.trim();return t.length>0&&Pr(t).length===0&&fA(t)}i(oT,"isControlPlaneOnlyAssistantText");function rs(e){let t=e.find(o=>o.role==="user"),n=t?ja(t.content):"";return TA(n)}i(rs,"extractTitle");function CA(e,t=lA){let n=e.replace(/\n/g," "),o=n.length>t?JS:"";return n.slice(0,t)+o}i(CA,"formatMessagePreview");import u from"chalk";import $u from"fs";import iT from"path";var Pu=hn("config.json");function sT(){return iT.join(process.cwd(),".kodax","config.local.json")}i(sT,"getProjectConfigFile");function Lu(e=process.env){let n=Ka(Pu).autoMode??{},o=e.KODAX_AUTO_MODE_ENGINE?.trim(),r=o==="llm"||o==="rules"?o:void 0,s=n.engine==="llm"||n.engine==="rules"?n.engine:void 0,a=r??s??"llm",c=rT(n.classifierModel),l=rT(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(Lu,"loadAutoModeSettings");function rT(e){if(typeof e!="string")return;let t=e.trim();return t.length===0?void 0:t}i(rT,"nonEmptyString");function Ka(e){try{if($u.existsSync(e))return JSON.parse($u.readFileSync(e,"utf-8"))}catch{}return{}}i(Ka,"readJsonFile");function aT(e,t){$u.mkdirSync(iT.dirname(e),{recursive:!0}),$u.writeFileSync(e,JSON.stringify(t,null,2))}i(aT,"writeJsonFile");function Va(e){let t=Ka(Pu);aT(Pu,{...t,permissionMode:e})}i(Va,"savePermissionModeUser");function is(){let e=Ka(Pu),t=Ka(sT()),n=e.alwaysAllowTools??[],o=t.alwaysAllowTools??[];return[...new Set([...n,...o])]}i(is,"loadAlwaysAllowTools");function Ou(e,t,n=!1){let o=Mu(e,t,n);if(!o)return;let r=sT(),s=Ka(r),a=s.alwaysAllowTools??[];a.includes(o)||aT(r,{...s,alwaysAllowTools:[...a,o]})}i(Ou,"saveAlwaysAllowToolPattern");var ss=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 r=this.aliases.get(n);throw new Error(`Command "${t.name}" conflicts with existing alias for "${r}"`)}let o=new Set;for(let r of t.aliases??[]){let s=r.toLowerCase();if(s!==n){if(o.has(s))throw new Error(`Alias "${r}" is duplicated within command "${t.name}"`);if(this.commands.has(s))throw new Error(`Alias "${r}" conflicts with existing command "${s}"`);if(this.aliases.has(s)){let a=this.aliases.get(s);throw new Error(`Alias "${r}" is already registered for "${a}"`)}o.add(s)}}if(this.commands.set(n,{...t,source:t.source??"builtin"}),t.aliases)for(let r of t.aliases){let s=r.toLowerCase();s!==n&&this.aliases.set(s,n)}}unregister(t){let n=t.toLowerCase(),o=this.aliases.get(n)??n;if(!this.commands.has(o))return!1;let r=this.commands.get(o);if(r?.aliases)for(let s of r.aliases)this.aliases.delete(s.toLowerCase());return this.commands.delete(o),!0}get(t){let n=t.toLowerCase(),o=this.aliases.get(n)??n;return this.commands.get(o)}has(t){let n=t.toLowerCase(),o=this.aliases.get(n)??n;return this.commands.has(o)}getAll(t){let n=new Map;for(let[o,r]of this.commands)t&&r.source!==t||n.has(o)||n.set(o,{name:r.name,aliases:r.aliases,description:r.description,source:r.source??"builtin",usage:r.usage,priority:r.priority,location:r.location,path:r.path,userInvocable:r.userInvocable,disableModelInvocation:r.disableModelInvocation,allowedTools:r.allowedTools,context:r.context,agent:r.agent,argumentHint:r.argumentHint,model:r.model});return Array.from(n.values()).sort((o,r)=>o.name.localeCompare(r.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}},bA=new ss;import bn from"chalk";import{Buffer as dT}from"node:buffer";import{spawn as vA}from"node:child_process";import cT from"node:process";var Lr="\x1B",IA="\x07",Sp=`${Lr}\\`;function lT(e,t){return e.SSH_CONNECTION?!1:t==="win32"||t==="darwin"||t==="linux"}i(lT,"shouldPreferNativeClipboard");function kA(e,t){let n=dT.from(e,"utf8").toString("base64"),o=t.TERM==="xterm-kitty"?Sp:IA,r=`${Lr}]52;c;${n}${o}`;return t.TMUX?`${Lr}Ptmux;${r.replaceAll(Lr,`${Lr}${Lr}`)}${Sp}`:t.STY?`${Lr}P${r}${Sp}`:r}i(kA,"buildOscSequence");async function Du(e,t,n){return new Promise((o,r)=>{let s=vA(e,t,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),a="";s.on("error",r),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("close",c=>{if(c===0){o(!0);return}r(new Error(a.trim()||`${e} exited with code ${c??"unknown"}`))}),s.stdin?.write(n),s.stdin?.end()})}i(Du,"execClipboardCommand");function RA(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=dT.from(e,"utf8");return[["powershell",["-NoProfile","-NonInteractive","-Command",t],n],["pwsh",["-NoProfile","-NonInteractive","-Command",t],n],["cmd",["/c","chcp 65001 >nul & clip"],n]]}i(RA,"buildWindowsClipboardCandidates");async function uT(e,t,n){if(t.SSH_CONNECTION)return!1;switch(n){case"win32":{let o=RA(e);for(let[r,s,a]of o)try{if(await Du(r,s,a))return!0}catch{}return!1}case"darwin":return Du("pbcopy",[],e);case"linux":{let o=[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]];for(let[r,s]of o)try{if(await Du(r,s,e))return!0}catch{}return!1}default:return!1}}i(uT,"tryNativeClipboard");async function EA(e,t){if(!t.TMUX)return!1;let n=t.LC_TERMINAL==="iTerm2"?["load-buffer","-"]:["load-buffer","-w","-"];try{return await Du("tmux",n,e)}catch{return!1}}i(EA,"tryTmuxClipboard");async function Or(e,t={}){let n=t.env??cT.env,o=t.platform??cT.platform,r=e.trimEnd(),s=kA(r,n);if(!r)throw new Error("Nothing to copy.");if(lT(n,o))try{if(await uT(r,n,o))return{path:"native"}}catch{}if(await EA(r,n))return{path:"tmux-buffer"};if(t.terminalWrite?.(s))return{path:"osc52"};if(!lT(n,o))try{if(await uT(r,n,o))return{path:"native"}}catch{}throw new Error("Unable to access any clipboard path.")}i(Or,"copyTextToClipboard");var Tp={name:"copy",description:"Copy last assistant message to clipboard",usage:"/copy",handler:i(async(e,t)=>{let n=Ga(t.messages);if(!n){console.log(bn.yellow(`
|
|
45
|
+
No assistant message found to copy.`)),console.log(bn.dim("The assistant needs to respond first before you can copy its message."));return}try{await Or(n);let o=n.length>50?n.slice(0,50)+"...":n;console.log(bn.green(`
|
|
46
|
+
Copied to clipboard!`)),console.log(bn.dim(`Preview: ${o}`))}catch(o){let r=o instanceof Error?o.message:String(o);console.log(bn.red(`
|
|
47
|
+
Failed to copy to clipboard: ${r}`)),console.log(bn.dim("You may need to check clipboard permissions or manually copy the message."))}},"handler"),detailedHelp:i(()=>{console.log(bn.bold(`
|
|
48
|
+
/copy - Copy Last Assistant Message
|
|
49
|
+
`)),console.log("Usage:"),console.log(bn.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(bn.dim(" User: Explain how async/await works")),console.log(bn.dim(" AI: [responds with explanation]")),console.log(bn.cyan(" /copy")+bn.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 to from"node:fs";import*as Nu from"node:path";import we from"chalk";function MA(e){return e.runtimeInfo?.workspaceRoot??e.runtimeInfo?.executionCwd??process.cwd()}i(MA,"resolveCwd");function mT(e){let t;try{t=to.readdirSync(e,{withFileTypes:!0})}catch(o){return o.code!=="ENOENT"&&console.error(`[memory] failed to read memory directory ${e}:`,o),[]}let n=[];for(let o of t){if(!o.isFile()||!o.name.endsWith(".md")||o.name==="MEMORY.md")continue;let r=Nu.join(e,o.name),s="",a=0;try{s=to.readFileSync(r,"utf-8"),a=to.statSync(r).mtimeMs}catch(p){console.error(`[memory] failed to read ${r}:`,p);continue}let l=nx(s).frontmatter,d=l.name!==void 0||l.description!==void 0||l.type!==void 0,m=Nu.basename(o.name,".md");n.push({filename:o.name,absPath:r,mtimeMs:a,title:l.name?.trim()||m,description:l.description?.trim()||m,type:l.type,parseOk:d})}return n}i(mT,"readTopicFiles");function AA(e){return e.map(t=>`- [${t.title}](${t.filename}) \u2014 ${t.description}`)}i(AA,"buildIndexLines");async function _A(e,t){console.log(we.cyan(`
|
|
53
|
+
[memory] per-project memory directory`)),console.log(we.dim(` ${e}`));let n=mT(e),o=n.filter(a=>!a.parseOk);console.log(we.dim(` ${n.length} topic file${n.length===1?"":"s"}`+(o.length>0?`, ${o.length} without parsable frontmatter`:"")));let r=!1,s="";try{s=to.readFileSync(t,"utf-8"),r=!0}catch{r=!1}if(!r){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(_A,"listMemory");async function $A(e,t){let n=!1;try{n=to.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 o=mT(e);if(o.length===0){console.log(we.yellow(`
|
|
59
|
+
[memory] no topic files found \u2014 nothing to rebuild.`)),console.log(we.dim(` ${e}
|
|
60
|
+
`));return}let r=[...o].sort((l,d)=>d.mtimeMs-l.mtimeMs),a=AA(r).join(`
|
|
61
|
+
`)+`
|
|
62
|
+
`;to.writeFileSync(t,a,"utf-8"),console.log(we.green(`
|
|
63
|
+
[memory] rebuilt MEMORY.md with ${r.length} entries (newest first).`)),console.log(we.dim(` ${t}`));let c=r.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($A,"rebuildMemory");function PA(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(PA,"openMemory");function fT(){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(fT,"printHelp");function LA(){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(LA,"printDetailedHelp");var Cp={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=MA(t),o=Jy(n),r=Zy(n),s=(e[0]??"list").toLowerCase();if(s==="help"||s==="--help"||s==="-h"){fT();return}if(s==="list"){await _A(o,r);return}if(s==="rebuild"){await $A(o,r);return}if(s==="open"){PA(o,r);return}console.log(we.yellow(`
|
|
77
|
+
[memory] unknown subcommand: ${s}`)),fT()},"handler"),detailedHelp:LA};import Pe from"chalk";function pT(){console.log(`
|
|
78
|
+
${Pe.bold("/goal")} \u2014 persistent session goal
|
|
79
|
+
|
|
80
|
+
${Pe.bold("Subcommands:")}
|
|
81
|
+
${Pe.cyan("/goal <objective> [--tokens N]")} Create a new persistent goal.
|
|
82
|
+
${Pe.cyan("/goal status")} Show current goal (default).
|
|
83
|
+
${Pe.cyan("/goal pause")} Pause an active goal.
|
|
84
|
+
${Pe.cyan("/goal resume")} Resume a paused goal.
|
|
85
|
+
${Pe.cyan("/goal clear")} Clear the current goal.
|
|
86
|
+
${Pe.cyan("/goal help")} Show this help.
|
|
87
|
+
|
|
88
|
+
${Pe.bold("Notes:")}
|
|
89
|
+
- The agent auto-continues toward an active goal on every Worker turn end.
|
|
90
|
+
- Token budget is optional; set it only when you want a hard ceiling.
|
|
91
|
+
- update_goal({complete}) is verifier-gated; the agent cannot
|
|
92
|
+
self-declare done without runtime confirmation.
|
|
93
|
+
`.trim())}i(pT,"printHelp");function OA(e){let t=null,n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s==="--tokens"){let a=e[r+1];if(!a)return{error:"--tokens requires a value (e.g. `--tokens 50000`)"};let c=Number(a);if(!um(c))return{error:"--tokens value must be a positive integer"};t=c,r++;continue}if(s.startsWith("--tokens=")){let a=s.slice(9),c=Number(a);if(!um(c))return{error:"--tokens value must be a positive integer"};t=c;continue}if(s.startsWith("--"))return{error:`unknown flag: ${s}`};n.push(s)}let o=n.join(" ").trim();return o?{objective:o,tokenBudget:t}:{error:"objective is required"}}i(OA,"parseCreateArgs");function DA(e){if(!e)return Pe.dim("No goal set. Use `/goal <objective>` to create one.");let t=[`${Pe.bold("Goal:")} ${e.objective}`,`${Pe.bold("Status:")} ${e.status}`,`${Pe.bold("Tokens used:")} ${e.tokensUsed}`];if(e.tokenBudget!==null){let n=Math.max(0,e.tokenBudget-e.tokensUsed);t.push(`${Pe.bold("Token budget:")} ${e.tokenBudget} (remaining ${n})`)}else t.push(`${Pe.bold("Token budget:")} ${Pe.dim("none")}`);return t.push(`${Pe.bold("Elapsed:")} ${e.timeUsedSeconds}s`),e.status==="blocked"&&e.lastBlockerKind&&t.push(`${Pe.bold("Blocker:")} ${e.lastBlockerKind}`),t.join(`
|
|
94
|
+
`)}i(DA,"renderStatus");async function za(e,t,n,o){if(!e.lineage)throw new Error("session lineage unavailable \u2014 open or start a new session before using /goal");e.lineage=lx(e.lineage,n,o),await t.saveSession()}i(za,"persist");async function NA(e,t,n){if(!t.lineage){console.log(Pe.red("[/goal] no active session lineage"));return}let o=Ei(t.lineage);if(o&&o.status!=="complete"){console.log(Pe.yellow(`[/goal] a goal is already active (status: ${o.status}). Clear it first with \`/goal clear\` before creating a new one.`));return}let r=OA(e);if("error"in r){console.log(Pe.red(`[/goal] ${r.error}`));return}try{o&&o.status==="complete"&&await za(t,n,null,"cleared");let s=yx(r.objective,r.tokenBudget);await za(t,n,s,"created"),console.log(Pe.green(`[/goal] created: "${s.objective}"`)),s.tokenBudget!==null&&console.log(Pe.dim(` budget: ${s.tokenBudget} tokens`))}catch(s){let a=s instanceof Error?s.message:String(s);console.log(Pe.red(`[/goal] ${a}`))}}i(NA,"doCreate");async function BA(e){if(!e.lineage){console.log(Pe.red("[/goal] no active session lineage"));return}let t=Ei(e.lineage);console.log(DA(t))}i(BA,"doStatus");async function HA(e,t){if(!e.lineage){console.log(Pe.red("[/goal] no active session lineage"));return}let n=Ei(e.lineage);if(!n){console.log(Pe.yellow("[/goal] no goal to pause"));return}if(n.status!=="active"){console.log(Pe.yellow(`[/goal] cannot pause from status '${n.status}' (only 'active' is pausable)`));return}let o=xx(n);await za(e,t,o,"paused"),console.log(Pe.green("[/goal] paused"))}i(HA,"doPause");async function FA(e,t){if(!e.lineage){console.log(Pe.red("[/goal] no active session lineage"));return}let n=Ei(e.lineage);if(!n){console.log(Pe.yellow("[/goal] no goal to resume"));return}if(n.status!=="paused"){console.log(Pe.yellow(`[/goal] cannot resume from status '${n.status}' (only 'paused' is resumable)`));return}let o=wx(n);await za(e,t,o,"resumed"),console.log(Pe.green("[/goal] resumed"))}i(FA,"doResume");async function WA(e,t){if(!e.lineage){console.log(Pe.red("[/goal] no active session lineage"));return}if(!Ei(e.lineage)){console.log(Pe.yellow("[/goal] no goal to clear"));return}await za(e,t,null,"cleared"),console.log(Pe.green("[/goal] cleared"))}i(WA,"doClear");var gT={name:"goal",description:"Manage a persistent session goal (FEATURE_192)",usage:"/goal [<objective> [--tokens N] | status | pause | resume | clear | help]",argumentHint:"<objective> | status | pause | resume | clear | help",handler:i(async(e,t,n)=>{let o=(e[0]??"status").toLowerCase();if(o==="help"||o==="--help"||o==="-h"){pT();return}if(o==="status"){await BA(t);return}if(o==="pause"){await HA(t,n);return}if(o==="resume"){await FA(t,n);return}if(o==="clear"){await WA(t,n);return}await NA(e,t,n)},"handler"),detailedHelp:pT};import Gt from"chalk";var bp={name:"new",description:"Start a new conversation session",usage:"/new",handler:i(async(e,t,n)=>{if(t.messages.length===0){console.log(Gt.yellow(`
|
|
95
|
+
Current session is already empty.`)),console.log(Gt.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(Gt.dim(`
|
|
96
|
+
Cancelled. Current session preserved.`));return}try{await n.saveSession(),console.log(Gt.dim(`
|
|
97
|
+
[Previous session saved]`))}catch{console.log(Gt.yellow(`
|
|
98
|
+
[Warning: Failed to save previous session]`))}n.startNewSession?.(),t.messages=[],n.clearHistory(),console.log(Gt.green(`
|
|
99
|
+
\u2713 Started new session`)),console.log(Gt.dim("Conversation history cleared. Ready for a fresh start!"))},"handler"),detailedHelp:i(()=>{console.log(Gt.bold(`
|
|
100
|
+
/new - Start New Session
|
|
101
|
+
`)),console.log("Usage:"),console.log(Gt.cyan(" /new")+` - Clear current session and start fresh
|
|
102
|
+
`),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.
|
|
103
|
+
`),console.log("Examples:"),console.log(Gt.dim(" User: Help me refactor the authentication module")),console.log(Gt.dim(" AI: [provides refactoring help]")),console.log(Gt.cyan(" /new")),console.log(Gt.dim(" \u2713 Started new session")),console.log(Gt.dim(" User: Now I need help with database optimization")),console.log(Gt.dim(` AI: [provides database help]
|
|
104
|
+
`)),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 Hu(e){let t=e.match(/\r\n|\r|\n/g);return t?t.length:0}i(Hu,"getPastedTextRefNumLines");function UA(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}i(UA,"formatPastedTextRef");function jA(e,t){return`[...Truncated text #${e} +${t} lines...]`}i(jA,"formatTruncatedTextRef");var GA=/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/g;function KA(e){let t=[],n=new RegExp(GA.source,"g");for(let o of e.matchAll(n)){let r=Number.parseInt(o[2]??"0",10);!Number.isFinite(r)||r<=0||t.push({id:r,kind:o[1],match:o[0],index:o.index??0})}return t}i(KA,"parseReferences");function VA(e,t){let n=KA(e);if(n.length===0)return e;let o=i(s=>t instanceof Map?t.get(s):t[s],"getContent"),r=e;for(let s=n.length-1;s>=0;s--){let a=n[s];if(a.kind==="Image")continue;let c=o(a.id);!c||c.type!=="text"||(r=r.slice(0,a.index)+c.content+r.slice(a.index+a.match.length))}return r}i(VA,"expandPastedTextRefs");var zA=/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]$/,XA=/^\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/;function YA(e,t){if(t>=e.length)return!0;let n=e[t];return!n||/\s/.test(n)}i(YA,"isAtWordBoundaryAfter");function qA(e,t){if(t===0)return!0;let n=e[t-1];return!n||/\s/.test(n)}i(qA,"isAtWordBoundaryBefore");function Fu(e,t){if(t<=0||!YA(e,t))return null;let o=e.slice(0,t).match(zA);if(!o)return null;let r=t-o[0].length,s=Number.parseInt(o[2]??"0",10);return!Number.isFinite(s)||s<=0?null:{start:r,end:t,id:s,kind:o[1]}}i(Fu,"findPlaceholderBeforeCursor");function Wu(e,t){if(t>=e.length||!qA(e,t))return null;let o=e.slice(t).match(XA);if(!o)return null;let r=Number.parseInt(o[2]??"0",10);return!Number.isFinite(r)||r<=0?null:{start:t,end:t+o[0].length,id:r,kind:o[1]}}i(Wu,"findPlaceholderAfterCursor");function hT(e){return e.length>800||Hu(e)>2}i(hT,"shouldReplacePasteWithPlaceholder");function yT(e,t){if(e.length<=1e4)return{truncatedText:e,placeholderContent:""};let n=Math.floor(1e3/2),o=Math.floor(1e3/2),r=e.slice(0,n),s=e.slice(-o),a=e.slice(n,-o),c=Hu(a),l=jA(t,c);return{truncatedText:r+l+s,placeholderContent:a}}i(yT,"maybeTruncateLongInput");var vp=class{static{i(this,"PasteStore")}contents=new Map;nextId=1;registerText(t){let n=this.nextId++,o=Hu(t);return this.contents.set(n,{id:n,type:"text",content:t}),{id:n,placeholder:UA(n,o),numLines:o}}registerTruncatedText(t){let n=this.nextId++,o=Hu(t);return this.contents.set(n,{id:n,type:"text",content:t}),{id:n,numLines:o}}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 VA(t,this.contents)}snapshot(){return new Map(this.contents)}restore(t){this.contents.clear();for(let[n,o]of t)this.contents.set(n,o);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())}},Bu=null;function xT(){return Bu===null&&(Bu=new vp),Bu}i(xT,"getOrCreateModulePasteStore");function Uu(){return Bu??void 0}i(Uu,"getActivePasteStore");import{createHash as QA}from"node:crypto";import{mkdir as JA,readdir as ZA,readFile as e_,stat as t_,unlink as n_,writeFile as o_}from"node:fs/promises";import*as Ip from"node:path";var r_="paste-cache",i_=720*60*60*1e3;function kp(){return hn(r_)}i(kp,"getPasteCacheDir");function wT(e){return Ip.join(kp(),`${e}.txt`)}i(wT,"getPastePath");function ST(e){return QA("sha256").update(e).digest("hex").slice(0,16)}i(ST,"hashPastedText");async function TT(e,t){try{let n=kp();return await JA(n,{recursive:!0}),await o_(wT(e),t,{encoding:"utf8",mode:384}),!0}catch{return!1}}i(TT,"storePastedText");async function ju(e){try{return await e_(wT(e),{encoding:"utf8"})}catch{return null}}i(ju,"retrievePastedText");async function CT(e=i_){let t=kp(),n=Date.now()-e,o=0,r=0,s;try{s=await ZA(t)}catch{return{scanned:o,removed:r}}for(let a of s){if(!a.endsWith(".txt"))continue;o+=1;let c=Ip.join(t,a);try{(await t_(c)).mtimeMs<n&&(await n_(c),r+=1)}catch{}}return{scanned:o,removed:r}}i(CT,"cleanupOldPastes");import*as $p from"path";import*as bT from"os";function s_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(s_,"escapeRegExp");function a_(e,t){if(!e)return;let n=e.trim();if(!n.startsWith("/"))return;let o=new RegExp(`^/${s_(t)}(?:\\s+)?`,"i"),r=n.replace(o,"").trim();return r.length>0?r:void 0}i(a_,"deriveArgumentHintFromUsage");function Rp(e,t="builtin"){return{...e,source:e.source??t,userInvocable:e.userInvocable??!0,disableModelInvocation:e.disableModelInvocation??!1,argumentHint:e.argumentHint??a_(e.usage,e.name)}}i(Rp,"toCommandDefinition");function Ep(e){for(let t of Mp)try{let n=Rp(t,"builtin");e.register(n)}catch(n){console.error(`Failed to register command "${t.name}":`,n)}}i(Ep,"registerBuiltinCommands");import*as Io from"fs";import*as Dr from"path";function c_(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(c_,"normalizeAliases");function l_(e){if(e==="critical"||e==="high"||e==="medium"||e==="low")return e}i(l_,"normalizePriority");function u_(e){return{disableModelInvocation:e["disable-model-invocation"]===!0,userInvocable:e["user-invocable"]!==!1,allowedTools:rx(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:ix(e.hooks),frontmatter:e}}i(u_,"buildExecutionMetadata");function d_(e,t){try{let n=Io.readFileSync(e,"utf-8"),[o,r]=ox(n),s=o??{},a=Dr.basename(e,".md"),c=typeof s.name=="string"&&s.name.trim()?s.name.trim():a;if(!c||r.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:c_(s.aliases),priority:l_(s.priority),content:r.trim(),location:t,path:e,frontmatter:s,execution:u_(s)}}catch(n){console.error(`Error parsing command file ${e}:`,n);return}}i(d_,"parseCommandFile");function Ap(e){let t=[],n=new Set;for(let o=0;o<e.length;o++){let r=e[o],s=typeof r=="string"?r:r.path,a=typeof r=="string"?o===0?"user":"project":r.location;if(!Io.existsSync(s))continue;let c=Dr.resolve(s);try{c=Io.realpathSync.native?.(s)??Io.realpathSync(s)}catch{c=Dr.resolve(s)}if(!n.has(c)){n.add(c);try{let l=Io.readdirSync(s);for(let d of l){if(!d.endsWith(".md"))continue;let m=Dr.join(s,d),p=d_(m,a);p&&t.push(p)}}catch(l){console.error(`Error scanning directory ${s}:`,l)}}}return t}i(Ap,"discoverCommands");function _p(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(o){console.error(`Error registering command ${n.name}:`,o)}}i(_p,"registerDiscoveredCommands");function vT(e,t){Ep(e);try{let n=bT.homedir(),o=t??process.cwd(),r=Ap([{path:$p.join(o,".kodax","commands"),location:"project"},{path:hn("commands"),location:"user"},{path:$p.join(n,".agents","commands"),location:"user"}]);_p(r,e)}catch(n){console.error("Failed to discover commands:",n)}}i(vT,"registerAllCommands");import{execFile as f_}from"child_process";import m_ from"fs";import Pp from"path";import{promisify as p_}from"util";var g_=p_(f_);function Xo(e){if(!(!e||!e.trim()))return Pp.resolve(e).replace(/\\/g,"/")}i(Xo,"normalizePath");async function Xa(e,t){try{let{stdout:n}=await g_("git",t,{cwd:e,windowsHide:!0,maxBuffer:1048576}),o=n.trim();return o||void 0}catch{return}}i(Xa,"gitStdout");function h_(e){let t=Xo(e);if(t)return Pp.posix.basename(t)===".git"?Pp.posix.dirname(t):t}i(h_,"deriveCanonicalRepoRoot");async function as(e={}){let t=Xo(e.cwd??process.cwd())??process.cwd().replace(/\\/g,"/"),n=Xo(await Xa(t,["rev-parse","--show-toplevel"])),o=await Xa(n??t,["rev-parse","--path-format=absolute","--git-common-dir"])??await Xa(n??t,["rev-parse","--git-common-dir"]),r=await Xa(n??t,["branch","--show-current"])??await Xa(n??t,["rev-parse","--abbrev-ref","HEAD"]);return{canonicalRepoRoot:h_(o)??n,workspaceRoot:n,executionCwd:t,branch:r&&r!=="HEAD"?r:void 0,workspaceKind:e.workspaceKind??"detected"}}i(as,"inspectWorkspaceRuntime");function Gu(e,t){return!e?.canonicalRepoRoot||!t?.canonicalRepoRoot?!1:Xo(e.canonicalRepoRoot)===Xo(t.canonicalRepoRoot)}i(Gu,"isSameCanonicalRepo");function IT(e){return!!(e?.workspaceRoot&&m_.existsSync(e.workspaceRoot))}i(IT,"workspaceExists");function Ya(e){let t=Xo(e.runtimeInfo?.workspaceRoot??e.gitRoot),n=Xo(e.runtimeInfo?.executionCwd??t),o=Xo(e.runtimeInfo?.canonicalRepoRoot??t);if(!(!t&&!n&&!o))return{canonicalRepoRoot:o,workspaceRoot:t,executionCwd:n,branch:e.runtimeInfo?.branch,workspaceKind:e.runtimeInfo?.workspaceKind??"detected"}}i(Ya,"resolveSessionRuntimeInfo");function vn(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(vn,"formatWorkspaceTruth");function y_(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(y_,"summarizeAgentsFiles");function x_(e,t,n){if(!Number.isFinite(t)||t<=0||n<=0)return{...e,enabled:!0};let o=t/n*100,r=Math.max(1,Math.ceil(o)-1);return{...e,enabled:!0,triggerPercent:Math.min(e.triggerPercent,r)}}i(x_,"createManualCompactionConfig");function Lp(e){e.runtimeInfo?.workspaceRoot?console.log(u.dim(` Workspace unchanged: ${vn(e.runtimeInfo)}`)):console.log(u.dim(" Workspace unchanged."))}i(Lp,"printWorkspaceUnchangedNote");var Mp=[{name:"help",aliases:["h","?"],description:"Show all available commands",usage:"/help [command]",handler:i(async e=>{e.length>0?M_(e[0]):E_()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
105
|
+
/help - Show Command Help
|
|
106
|
+
`)),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(`
|
|
107
|
+
Session saved. Goodbye!`)),await n.exit()},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
108
|
+
/exit - Exit Interactive Mode
|
|
109
|
+
`)),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(`
|
|
110
|
+
[Conversation cleared]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
111
|
+
/clear - Clear Conversation History
|
|
112
|
+
`)),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 o=n.getCostReport?.();if(!o){console.log(u.dim(`
|
|
113
|
+
[No cost data available yet]`));return}console.log(u.cyan(`
|
|
114
|
+
`+o))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
115
|
+
/cost - Session Cost Report
|
|
116
|
+
`)),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(`
|
|
117
|
+
/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=Uu();if(!n){console.log(u.yellow(`
|
|
118
|
+
[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 o=n.export();if(o.length===0){console.log(u.dim(`
|
|
119
|
+
[No pasted content in this session yet]`));return}console.log(u.bold(`
|
|
120
|
+
Pasted content in this session:
|
|
121
|
+
`));for(let r of o){let s=r.content?.length??0,a=r.contentHash?` (hash ${r.contentHash.slice(0,8)})`:"";console.log(` ${u.cyan(`#${r.id}`)} ${r.type} ${s} chars${a}`)}console.log();return}if(t==="show"){let o=e[1],r=o?Number.parseInt(o,10):NaN;if(!Number.isFinite(r)||r<=0){console.log(u.yellow(`
|
|
122
|
+
Usage: /paste show <id>`));return}let s=n.get(r);if(!s){console.log(u.dim(`
|
|
123
|
+
[No paste registered with id #${r}]`));return}let a=s.content??"";if(!a&&s.contentHash){let c=await ju(s.contentHash);c&&(a=c)}if(!a){console.log(u.yellow(`
|
|
124
|
+
[Paste #${r} has no stored content (hash ${s.contentHash??"n/a"})]`));return}console.log(u.bold(`
|
|
125
|
+
Pasted text #${r} (${a.length} chars):
|
|
126
|
+
`)),console.log(a),console.log();return}console.log(u.yellow(`
|
|
127
|
+
[Unknown /paste subcommand: ${t}]`)),console.log(u.dim(" Try /paste show <id> or /paste list"))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
128
|
+
/paste - Inspect stored paste contents
|
|
129
|
+
`)),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,o)=>{try{let r=await Hl(t.gitRoot),s=o.provider,a=gr(s);if(!a){console.log(u.red(`
|
|
130
|
+
[Provider not found: ${s}]`));return}let c=e.length>0?e.join(" "):void 0,l=r.contextWindow??a.getEffectiveContextWindow?.(o.model)??a.getContextWindow?.()??2e5,d=t.contextTokenSnapshot?.currentTokens??hr(t.messages),m=x_(r,d,l);console.log(u.dim(`
|
|
131
|
+
[Compacting conversation...]`)),n.startCompacting?.();try{let p=await ux(t.messages,m,a,l,c,void 0,d,vx,Ix);if(!p.compacted){console.log(u.green(`
|
|
132
|
+
[No compaction needed]`)),console.log(u.dim(`Current token usage: ${p.tokensBefore.toLocaleString()}
|
|
133
|
+
`));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(`
|
|
134
|
+
[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(r){let s=r instanceof Error?r.message:String(r);console.log(u.red(`
|
|
135
|
+
[Compaction failed: ${s}]
|
|
136
|
+
`))}},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
137
|
+
/compact - Manual Context Compaction
|
|
138
|
+
`)),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,o)=>{console.log(u.cyan(`
|
|
139
|
+
Reloading project rule files and runtime extensions...
|
|
140
|
+
`));try{let r=await n.reloadAgentsFiles?.()??[],s=y_(r),a=yo(),c=a?cs(a).loadedExtensions.length:0,l=a?cs(a).failures.length:0,d=0,m=0;if(a){await a.reloadExtensions({continueOnError:!0});let p=cs(a);d=c||p.loadedExtensions.length,m=Math.max(0,p.failures.length-l)}if(r.length===0&&d===0){console.log(u.yellow(`No project rule files or active extensions found.
|
|
141
|
+
`)),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:
|
|
142
|
+
`)),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(r){console.log(u.red(`Failed to reload rules.
|
|
143
|
+
`)),console.log(u.dim(` Error: ${r instanceof Error?r.message:String(r)}`)),console.log()}},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
144
|
+
/reload - Reload Project Rules
|
|
145
|
+
`)),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=yo();if(!e){console.log(u.yellow(`
|
|
146
|
+
[No active extension runtime]
|
|
147
|
+
`));return}let t=cs(e),n=t.tools.filter(o=>o.source.kind==="extension");if(console.log(u.bold(`
|
|
148
|
+
Extension Runtime:
|
|
149
|
+
`)),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 o of t.loadedExtensions)console.log(u.dim(` - ${o.label} [${o.loadSource}] (${o.path})`));console.log()}if(t.commands.length>0){console.log(u.bold("Extension Commands:"));for(let o of t.commands){let r=o.aliases?.length?` [${o.aliases.join(", ")}]`:"";console.log(u.dim(` - /${o.name}${r} ${o.description}`))}console.log()}if(t.capabilityProviders.length>0){console.log(u.bold("Capability Providers:"));for(let o of t.capabilityProviders){let r=O_(o.metadata);console.log(u.dim(` - ${o.id} [${o.kinds.join(", ")}]${r?` ${r}`:""}`))}console.log()}if(n.length>0){console.log(u.bold("Extension Tools:"));for(let o of n){let r=o.shadowedSources.length>0?` overrides: ${o.shadowedSources.map(s=>s.label??s.id??s.kind).join(", ")}`:"";console.log(u.dim(` - ${o.name}${r}`))}console.log()}if(t.hooks.length>0){console.log(u.bold("Hook Participation:"));for(let o of t.hooks)console.log(u.dim(` - ${o.hook} [#${o.order}] ${o.source.label}`));console.log()}if(t.failures.length>0){console.log(u.bold("Recent Failures:"));for(let o of t.failures.slice(-10))console.log(u.dim(` - [${o.stage}] ${o.source.label}: ${o.target} -> ${o.message}`));console.log()}},"handler")},{name:"status",aliases:["info","ctx"],description:"Show current session status",handler:i(async(e,t,n,o)=>{await A_(t,o,e)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
150
|
+
/status - Show Session Status
|
|
151
|
+
`)),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=yo();if(!t){console.log(u.yellow(`
|
|
152
|
+
[No extension runtime active \u2014 MCP is not available]`));return}let o=cs(t).capabilityProviders.find(c=>c.id==="mcp");if((e[0]?.toLowerCase()??"status")==="refresh"){console.log(u.dim(`
|
|
153
|
+
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(`
|
|
154
|
+
MCP Status
|
|
155
|
+
`)),!o){console.log(u.yellow(" No MCP provider registered.")),console.log(u.dim(` Add mcpServers to ~/.kodax/config.json to enable MCP.
|
|
156
|
+
`));return}let a=o.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(`
|
|
157
|
+
/mcp - MCP Server Management
|
|
158
|
+
`)),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,o)=>{let r=e[0]?.toLowerCase()??"status";if(r==="status"){let s=await pa({mode:o.repoIntelligenceMode,trace:o.repoIntelligenceTrace,probePremium:!0});AT(s);return}if(r==="warm"){let s=await fx({mode:o.repoIntelligenceMode,trace:o.repoIntelligenceTrace});R_(s);return}if(r==="mode"){if(e.length===1){console.log(u.dim(`
|
|
159
|
+
Current repo-intelligence mode: ${u.cyan(o.repoIntelligenceMode??"auto")}`)),console.log(u.dim(`Usage: /repointel mode [auto|off|oss|premium-shared|premium-native]
|
|
160
|
+
`));return}let s=b_(e[1]);if(!s){console.log(u.red(`
|
|
161
|
+
[Invalid repo-intelligence mode: ${e[1]}]`)),console.log(u.dim(`Usage: /repointel mode [auto|off|oss|premium-shared|premium-native]
|
|
162
|
+
`));return}let a=Ku({mode:s},{repoIntelligenceMode:s},n,o);ko(`Repo intelligence mode: ${s}`,a);return}if(r==="trace"){let s=e[1]?.toLowerCase();if(!s){console.log(u.dim(`
|
|
163
|
+
Current repo-intelligence trace: ${u.cyan(o.repoIntelligenceTrace?"on":"off")}`)),console.log(u.dim(`Usage: /repointel trace [on|off|toggle]
|
|
164
|
+
`));return}let a=v_(s,o.repoIntelligenceTrace??!1);if(a===null){console.log(u.red(`
|
|
165
|
+
[Invalid trace value: ${e[1]}]`)),console.log(u.dim(`Usage: /repointel trace [on|off|toggle]
|
|
166
|
+
`));return}let c=Ku({trace:a},{repoIntelligenceTrace:a},n,o);ko(`Repo intelligence trace: ${a?"on":"off"}`,c);return}if(r==="endpoint"){if(e.length===1){let c=await pa({mode:o.repoIntelligenceMode,trace:o.repoIntelligenceTrace});console.log(u.dim(`
|
|
167
|
+
Current repointel endpoint: ${u.cyan(c.endpoint)}`)),console.log(u.dim(`Usage: /repointel endpoint [http://host:port|default]
|
|
168
|
+
`));return}let s=kT(e[1]),a=Ku({endpoint:s},{repointelEndpoint:s??void 0},n,o);ko(`Repointel endpoint: ${s??"default"}`,a);return}if(r==="bin"){if(e.length===1){let c=await pa({mode:o.repoIntelligenceMode,trace:o.repoIntelligenceTrace});console.log(u.dim(`
|
|
169
|
+
Current repointel bin: ${u.cyan(c.bin)}`)),console.log(u.dim(`Usage: /repointel bin [<path-or-command>|default]
|
|
170
|
+
`));return}let s=kT(e.slice(1).join(" ")),a=Ku({bin:s},{repointelBin:s??void 0},n,o);ko(`Repointel bin: ${s??"default"}`,a);return}console.log(u.red(`
|
|
171
|
+
[Unknown /repointel subcommand: ${e[0]}]`)),console.log(u.dim(`Usage: /repointel [status|mode|trace|warm|endpoint|bin]
|
|
172
|
+
`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
173
|
+
/repointel - Repo-Intelligence Runtime Control
|
|
174
|
+
`)),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,o)=>{if(e.length===0){let s=Zn(o.permissionMode,"accept-edits")??"accept-edits";console.log(u.dim(`
|
|
175
|
+
Current mode: ${u.cyan(s)}`)),console.log(u.dim("Usage: /mode [plan|accept-edits|auto]"));return}let r=e[0];Oa.includes(r)?(o.permissionMode=r,n.setPermissionMode?.(r),Va(r),console.log(u.cyan(`
|
|
176
|
+
[Switched to ${r} mode] (saved)`))):console.log(u.red(`
|
|
177
|
+
[Unknown mode: ${e[0]}. Use: plan | accept-edits | auto]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
178
|
+
/mode - Switch Permission Mode
|
|
179
|
+
`)),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 o=n.getAutoModeStats?.();if(!o){console.log(u.yellow(`
|
|
180
|
+
[auto-engine] not in auto mode \u2014 switch via /mode auto first`));return}if(e.length===0){console.log(u.dim(`
|
|
181
|
+
Classifier engine: ${u.cyan(o.engine)}`)),console.log(u.dim(` consecutive denials: ${o.denials.consecutive}`)),console.log(u.dim(` cumulative denials: ${o.denials.cumulative}`)),console.log(u.dim(` breaker errors: ${o.breaker.timestamps.filter(s=>s>=Date.now()-600*1e3).length}`)),console.log(u.dim("Usage: /auto-engine [llm|rules]"));return}let r=e[0];if(r!=="llm"&&r!=="rules"){console.log(u.red(`
|
|
182
|
+
[auto-engine] unknown engine "${e[0]}" \u2014 use llm or rules`));return}n.setAutoModeEngine?.(r),console.log(u.cyan(`
|
|
183
|
+
[auto-engine] switched to ${r}`)),console.log(r==="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(`
|
|
184
|
+
/auto-engine - Auto-Mode Classifier Engine Toggle
|
|
185
|
+
`)),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 o=n.getAutoModeStats?.();if(!o){console.log(u.yellow(`
|
|
186
|
+
[auto-denials] not in auto mode \u2014 switch via /mode auto first`));return}console.log(u.cyan(`
|
|
187
|
+
[auto-mode classifier stats]`)),console.log(u.dim(` engine: ${u.cyan(o.engine)}`)),console.log(u.dim(" Denial tracker:")),console.log(u.dim(` consecutive blocks: ${o.denials.consecutive} / 3`)),console.log(u.dim(` cumulative blocks: ${o.denials.cumulative} / 20`)),console.log(u.dim(" Circuit breaker:")),console.log(u.dim(` errors in window: ${o.breaker.timestamps.filter(r=>r>=Date.now()-600*1e3).length} / 5 (10 min)`)),console.log(),o.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(`
|
|
188
|
+
/auto-denials - Auto-Mode Classifier Diagnostic Dump
|
|
189
|
+
`)),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(`
|
|
190
|
+
[Session saved]`)),Lp(t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
191
|
+
/save - Save Current Session
|
|
192
|
+
`)),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(`
|
|
193
|
+
[Usage: /load <session-id>]`)),await n.listSessions();return}await n.loadSession(e[0])==="missing"&&console.log(u.red(`
|
|
194
|
+
[Session not found: ${e[0]}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
195
|
+
/load - Load a Saved Session
|
|
196
|
+
`)),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 o=e[0]?.trim().toLowerCase();if(o==="label"){if(e.length<3){console.log(u.red(`
|
|
197
|
+
[Usage: /tree label <entry-id|label> <name>]`));return}await n.labelSessionBranch?.(e[1],e.slice(2).join(" "))||console.log(u.red(`
|
|
198
|
+
[Tree entry not found: ${e[1]}]`));return}if(o==="unlabel"){if(e.length<2){console.log(u.red(`
|
|
199
|
+
[Usage: /tree unlabel <entry-id|label>]`));return}await n.labelSessionBranch?.(e[1],void 0)||console.log(u.red(`
|
|
200
|
+
[Tree entry not found: ${e[1]}]`));return}await n.switchSessionBranch?.(e[0])==="missing"&&console.log(u.red(`
|
|
201
|
+
[Tree entry not found: ${e[0]}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
202
|
+
/tree - Inspect Session Lineage
|
|
203
|
+
`)),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(`
|
|
204
|
+
[Unable to fork session${e[0]?` from ${e[0]}`:""}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
205
|
+
/fork - Export a Branch to a New Session
|
|
206
|
+
`)),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(`
|
|
207
|
+
[Unable to rewind${e[0]?` to ${e[0]}`:" \u2014 no previous turn found"}]`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
208
|
+
/rewind - Rewind Session to a Previous Point
|
|
209
|
+
`)),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(`
|
|
210
|
+
/sessions - List Saved Sessions
|
|
211
|
+
`)),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(`
|
|
212
|
+
/history - Show Conversation History
|
|
213
|
+
`)),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(`
|
|
214
|
+
[Usage: /delete <session-id> or /delete all]`)),await n.listSessions?.();return}e[0]==="all"?(await n.deleteAllSessions?.(),console.log(u.green(`
|
|
215
|
+
[All sessions deleted]`)),Lp(t)):(await n.deleteSession?.(e[0]),console.log(u.green(`
|
|
216
|
+
[Session deleted: ${e[0]}]`)),Lp(t))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
217
|
+
/delete - Delete Saved Sessions
|
|
218
|
+
`)),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,o)=>{let r=ya().providerModels;if(e.length===0){console.log(u.bold(`
|
|
219
|
+
Available Providers:
|
|
220
|
+
`));let c=gm(r);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===o.provider,g=p?u.cyan(" *"):"";console.log(` ${u.bold(l.name)}${g} ${d}${m}`),l.capabilityProfile.transport==="cli-bridge"&&console.log(u.yellow(` ! ${fm(l.capabilityProfile)}`));let x=Ai(l.name,r),y=p?o.model:null;for(let T of x){let I=p&&(y===T||!y&&T===l.model)?u.cyan(">"):" ";console.log(` ${I} ${T}`)}console.log()}console.log(u.dim(`Current: provider=${o.provider}${o.model?`, model=${o.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
|
|
221
|
+
`));return}let s=(e[0]??"").trim();if(!s)return;if(s.startsWith("/")){let c=s.slice(1);if(!c){console.log(u.red(`
|
|
222
|
+
[Missing model name after /]`));return}let l=Ai(o.provider,r);if(!l.includes(c)){console.log(u.red(`
|
|
223
|
+
[Unknown model: ${c}]`)),console.log(u.dim(`Available models for ${o.provider}: ${l.join(", ")}
|
|
224
|
+
`));return}xo({model:c}),n.switchProvider?.(o.provider,c),console.log(u.cyan(`
|
|
225
|
+
[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(`
|
|
226
|
+
[Invalid format. Use: /model <provider>/<model>]`));return}if(!wi(l)){console.log(u.red(`
|
|
227
|
+
[Unknown provider: ${l}]`)),console.log(u.dim(`Available: ${Si().join(", ")}
|
|
228
|
+
`));return}let m=Ai(l,r);if(!m.includes(d)){console.log(u.red(`
|
|
229
|
+
[Unknown model: ${d}]`)),console.log(u.dim(`Available models for ${l}: ${m.join(", ")}
|
|
230
|
+
`));return}xo({provider:l,model:d}),n.switchProvider?.(l,d),console.log(u.cyan(`
|
|
231
|
+
[Switched to ${l}/${d}] (saved)`));return}let a=s;wi(a)?(xo({provider:a,model:void 0}),n.switchProvider?.(a),console.log(u.cyan(`
|
|
232
|
+
[Switched to ${a}] (saved)`))):(console.log(u.red(`
|
|
233
|
+
[Unknown provider: ${a}]`)),console.log(u.dim(`Available: ${Si().join(", ")}
|
|
234
|
+
`)))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
235
|
+
/model - Switch LLM Provider/Model
|
|
236
|
+
`)),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,o)=>{let r=(e[0]??"").trim(),s=o.provider,a=o.model;if(r)if(r.includes("/")){let d=r.indexOf("/");s=r.slice(0,d).trim(),a=r.slice(d+1).trim()||void 0}else s=r,a=void 0;if(!wi(s)){console.log(u.red(`
|
|
237
|
+
[Unknown provider: ${s}]`)),console.log(u.dim(`Available: ${Si().join(", ")}
|
|
238
|
+
`));return}let c=Lx(s,a);if(!c){console.log(u.red(`
|
|
239
|
+
[Provider details unavailable: ${s}]`)),console.log();return}let l=Nx(s,a,o.reasoningMode);console.log(u.bold(`
|
|
240
|
+
Provider Details:
|
|
241
|
+
`)),console.log(u.dim(` Provider: ${u.cyan(c.provider)}${c.model?` / ${u.cyan(c.model)}`:""}`)),console.log(u.dim(` Source: ${Ox(c.sourceKind)}`)),console.log(),console.log(u.bold("Capability Matrix:"));for(let d of Dx(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(`
|
|
242
|
+
/provider - Inspect Provider Semantics
|
|
243
|
+
`)),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,o)=>{if(e.length===0){let s=wr(o.provider,o.model),a=o.thinking?u.green("ON"):u.dim("OFF");console.log(u.dim(`
|
|
244
|
+
Thinking: ${a}`)),console.log(u.dim(`Reasoning mode: ${u.cyan(o.reasoningMode)}`)),console.log(u.dim(`Effective control: ${u.cyan(mm(s))}`)),console.log(u.dim(`Actual execution: ${pm(o.reasoningMode,s)}`)),console.log(u.dim(`Usage: /thinking on|off|auto|quick|balanced|deep
|
|
245
|
+
`));return}let r=e[0].toLowerCase();if(r==="on"||r==="off"||pr.includes(r)){let s=r==="on"?"auto":r==="off"?"off":r,a=RT(s,n,o);ko(`Reasoning mode: ${s}`,a);return}console.log(u.red(`
|
|
246
|
+
[Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /thinking on|off|auto|quick|balanced|deep
|
|
247
|
+
`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
248
|
+
/thinking - Legacy Alias for Reasoning Mode
|
|
249
|
+
`)),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,o)=>{if(e.length===0){let a=wr(o.provider,o.model);console.log(u.dim(`
|
|
250
|
+
Reasoning mode: ${u.cyan(o.reasoningMode)}`)),console.log(u.dim(`Thinking compatibility: ${o.thinking?u.green("ON"):u.dim("OFF")}`)),console.log(u.dim(`Effective control: ${u.cyan(mm(a))}`)),console.log(u.dim(`Actual execution: ${pm(o.reasoningMode,a)}`)),console.log(u.dim(`Usage: /reasoning off|auto|quick|balanced|deep
|
|
251
|
+
`));return}let r=e[0].toLowerCase();if(!pr.includes(r)){console.log(u.red(`
|
|
252
|
+
[Invalid reasoning mode: ${e[0]}]`)),console.log(u.dim(`Usage: /reasoning off|auto|quick|balanced|deep
|
|
253
|
+
`));return}let s=RT(r,n,o);ko(`Reasoning mode: ${r}`,s)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
254
|
+
/reasoning - Set Reasoning Mode
|
|
255
|
+
`)),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,o)=>{if(e.length===0){console.log(u.dim(`
|
|
256
|
+
Agent mode: ${u.cyan(o.agentMode.toUpperCase())}`)),console.log(u.dim(`Usage: /agent-mode [ama|sa|toggle]
|
|
257
|
+
`));return}let r=e[0]?.toLowerCase(),s=r==="toggle"?o.agentMode==="ama"?"sa":"ama":r==="ama"||r==="sa"?r:void 0;if(!s){console.log(u.red(`
|
|
258
|
+
[Invalid agent mode: ${e[0]}]`)),console.log(u.dim(`Usage: /agent-mode [ama|sa|toggle]
|
|
259
|
+
`));return}let a=I_(s,n,o);ko(`Agent mode: ${s.toUpperCase()}`,a)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
260
|
+
/agent-mode - Adaptive Multi-Agent Mode Control
|
|
261
|
+
`)),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,o)=>{o.permissionMode="auto",n.setPermissionMode?.("auto"),Va("auto"),console.log(u.cyan(`
|
|
262
|
+
[Switched to auto mode] (saved)`))},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
263
|
+
/auto - Quick Switch to Auto Mode
|
|
264
|
+
`)),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(`
|
|
265
|
+
[/skills is deprecated. Use /skill instead]`)),await MT(e,t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
266
|
+
/skills - Deprecated
|
|
267
|
+
`)),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,o)=>{await MT(e,t)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
268
|
+
/skill - Skill Namespace
|
|
269
|
+
`)),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=ya().verifierLog===!0,a=n?"on":"off",c=s===n?"":` (env=${n?"on":"off"}, config=${s?"on":"off"})`;console.log(u.dim(`
|
|
270
|
+
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]
|
|
271
|
+
`));return}let o;if(t==="on"||t==="true"||t==="1")o=!0;else if(t==="off"||t==="false"||t==="0")o=!1;else{console.log(u.red(`
|
|
272
|
+
[Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /verifier-log [on|off]
|
|
273
|
+
`));return}o?process.env.KODAX_VERIFIER_LOG="1":delete process.env.KODAX_VERIFIER_LOG;let r=qa({verifierLog:o});ko(`Sidecar Verifier log: ${o?"on":"off"}`,r)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
274
|
+
/verifier-log - Sidecar Verifier Log Toggle
|
|
275
|
+
`)),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=ya().stallLog===!0,a=n?"on":"off",c=s===n?"":` (env=${n?"on":"off"}, config=${s?"on":"off"})`;console.log(u.dim(`
|
|
276
|
+
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]
|
|
277
|
+
`));return}let o;if(t==="on"||t==="true"||t==="1")o=!0;else if(t==="off"||t==="false"||t==="0")o=!1;else{console.log(u.red(`
|
|
278
|
+
[Invalid value: ${e[0]}]`)),console.log(u.dim(`Usage: /stall-log [on|off]
|
|
279
|
+
`));return}o?process.env.KODAX_STALL_LOG="1":delete process.env.KODAX_STALL_LOG;let r=qa({stallLog:o});ko(`Stall Sidecar log: ${o?"on":"off"}`,r)},"handler"),detailedHelp:i(()=>{console.log(u.cyan(`
|
|
280
|
+
/stall-log - Stall Sidecar Log Toggle
|
|
281
|
+
`)),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")},Tp,Cp,gT,bp],w_={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 S_(e){let t=Vu();return e.map(n=>t.get(n)).filter(n=>n!==void 0).filter(n=>n.userInvocable!==!1)}i(S_,"getCommandsForCategory");function T_(e){return e!=="off"}i(T_,"reasoningModeToLegacyThinking");var C_=["auto","off","oss","premium-shared","premium-native"];function b_(e){return e&&C_.includes(e)?e:null}i(b_,"normalizeRepoIntelligenceMode");function kT(e){let t=e?.trim();return!t||t==="default"||t==="reset"||t==="clear"?null:t}i(kT,"normalizeRuntimeOverride");function v_(e,t){return e?e==="toggle"?!t:e==="on"||e==="true"||e==="1"?!0:e==="off"||e==="false"||e==="0"?!1:null:null}i(v_,"resolveToggleFlag");function qa(e){try{return xo(e),{saved:!0}}catch(t){return{saved:!1,error:t instanceof Error?t:new Error(String(t))}}}i(qa,"persistUserConfig");function ko(e,t){if(t.saved){console.log(u.cyan(`
|
|
282
|
+
[${e}] (saved)`));return}console.log(u.yellow(`
|
|
283
|
+
[${e}]`)),console.log(u.red(`[Config save failed: ${t.error.message}]`))}i(ko,"printPersistedCommandStatus");function RT(e,t,n){let o=T_(e),r=qa({reasoningMode:e,thinking:o});return t.setReasoningMode?t.setReasoningMode(e):(n.reasoningMode=e,n.thinking=o),r}i(RT,"applyReasoningMode");function I_(e,t,n){let o=qa({agentMode:e});return t.setAgentMode?t.setAgentMode(e):n.agentMode=e,o}i(I_,"applyAgentMode");function Ku(e,t,n,o){let r=qa(t);return n.setRepoIntelligenceRuntime?n.setRepoIntelligenceRuntime(e):(e.mode!==void 0&&(o.repoIntelligenceMode=e.mode),e.endpoint!==void 0&&(o.repointelEndpoint=e.endpoint??void 0),e.bin!==void 0&&(o.repointelBin=e.bin??void 0),e.trace!==void 0&&(o.repoIntelligenceTrace=e.trace)),r}i(Ku,"applyRepoIntelligenceRuntimeConfig");function k_(e){let t=e.configuredMode===e.requestedMode?e.configuredMode:`${e.configuredMode} -> ${e.requestedMode}`,n=`${e.effectiveEngine}/${e.effectiveBridge}`,o=e.transport?`, ${e.transport}`:"",r=e.fallbackToOss?", fallback=oss":"";return`${t} => ${n} (${e.status}${o}${r})`}i(k_,"formatRepoIntelligenceSummary");function AT(e){console.log(u.bold(`
|
|
284
|
+
Repo Intelligence:
|
|
285
|
+
`)),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(AT,"printRepoIntelligenceInspection");function R_(e){e.warmed?console.log(u.green(`
|
|
286
|
+
[repointel warmed successfully]`)):console.log(u.yellow(`
|
|
287
|
+
[repointel warm did not reach a ready daemon state]`)),e.warmLatencyMs!==void 0&&console.log(u.dim(` Warm latency: ${e.warmLatencyMs} ms`)),AT(e)}i(R_,"printRepoIntelligenceWarmResult");function ET(e,t){if(t.length!==0){console.log(u.dim(`${e}:`));for(let n of t){let o=n.aliases?.length?` (${n.aliases.join(", ")})`:"";console.log(` ${u.cyan(`/${n.name}`)}${u.dim(o)} ${n.description}`)}console.log()}}i(ET,"printCommandSection");function E_(){console.log(u.bold(`
|
|
288
|
+
Available Commands:
|
|
289
|
+
`));let e=Vu(),t=new Set;for(let[o,r]of Object.entries(w_)){let s=S_(r);if(s.length!==0){for(let a of s)t.add(a.name.toLowerCase());ET(o,s)}}let n=new Map;for(let o of e.getAll()){if(o.userInvocable===!1||t.has(o.name.toLowerCase()))continue;let r=o.source==="extension"?"Extensions":o.source==="skill"?"Skill Commands":o.source==="prompt"?"Prompt Commands":"Other Commands",s=n.get(r)??[];s.push(o),n.set(r,s)}for(let o of $_()){if(t.has(o.name.toLowerCase()))continue;let r=n.get("Extensions")??[];r.push({name:o.name,aliases:o.aliases,description:o.description}),n.set("Extensions",r)}for(let o of["Extensions","Skill Commands","Prompt Commands","Other Commands"])ET(o,n.get(o)??[]);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(E_,"printHelp");function M_(e){Nr.size===0&&Op();let t=Nr.get(e.toLowerCase());if(!t){let n=_T(e);if(!n){console.log(u.yellow(`
|
|
290
|
+
[Unknown command: /${e}. Type /help for available commands]`));return}console.log(u.cyan(`
|
|
291
|
+
/${n.name}`)),n.aliases?.length&&console.log(u.dim(`Aliases: ${n.aliases.join(", ")}`)),console.log(u.dim(`
|
|
292
|
+
${n.description}`)),console.log(u.dim(`
|
|
293
|
+
Usage: ${P_(n)}`)),console.log();return}t.detailedHelp?t.detailedHelp():(console.log(u.cyan(`
|
|
294
|
+
/${t.name}`)),t.aliases?.length&&console.log(u.dim(`Aliases: ${t.aliases.join(", ")}`)),console.log(u.dim(`
|
|
295
|
+
${t.description}`)),t.usage&&console.log(u.dim(`
|
|
296
|
+
Usage: ${t.usage}`)),console.log())}i(M_,"printDetailedHelp");async function A_(e,t,n=[]){let o=n[0]?.toLowerCase(),r=e.contextTokenSnapshot?.currentTokens??hr(e.messages),s=e.contextTokenSnapshot?.source??"estimate",a=Px(t.provider),c=Nl(t.provider,t.model,t.reasoningMode);if(console.log(u.bold(`
|
|
297
|
+
Session Status:
|
|
298
|
+
`)),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=fm(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: ~${r} (${s})`));let l=await pa({mode:t.repoIntelligenceMode,trace:t.repoIntelligenceTrace});console.log(u.dim(` Repo Intel: ${u.cyan(k_(l))}`)),e.runtimeInfo?.workspaceRoot?console.log(u.dim(` Workspace: ${u.cyan(vn(e.runtimeInfo))}`)):e.gitRoot&&console.log(u.dim(` Workspace: ${u.cyan(e.gitRoot)}`)),(o==="workspace"||o==="worktree"||o==="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(A_,"printStatus");async function MT(e,t){let n=ho(t.gitRoot);n.size===0&&await yr(t.gitRoot),__(n.listUserInvocable())}i(MT,"handleSkillNamespaceCommand");function __(e){if(console.log(u.bold(`
|
|
299
|
+
Available Skills:
|
|
300
|
+
`)),e.length===0){console.log(u.dim(" No skills found.")),console.log(u.dim(`
|
|
301
|
+
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 o=n.name.padEnd(t),r=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:${o}`)}${u.dim(r)}${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(__,"printSkillsListPiMonoStyle");var Nr=new ss;function Op(e){Nr.size>0||vT(Nr,e)}i(Op,"initCommandRegistry");function Vu(e){return Op(e),Nr}i(Vu,"getCommandRegistry");function $_(){return yo()?.listCommands().filter(t=>t.metadata?.userInvocable!==!1)??[]}i($_,"getActiveExtensionCommands");function _T(e){let t=yo(),n=e.trim().toLowerCase();if(!n)return;let o=t?.listCommands().find(r=>r.name.trim().toLowerCase()===n||(r.aliases??[]).some(s=>s.trim().toLowerCase()===n));if(o)return o.metadata?.userInvocable===!1?void 0:o}i(_T,"getActiveExtensionCommand");function P_(e){return e.usage??`/${e.name}`}i(P_,"formatExtensionCommandUsage");function L_(e){return Array.isArray(e)?e.map(t=>String(t)).join(", "):e&&typeof e=="object"?JSON.stringify(e):String(e)}i(L_,"formatExtensionDiagnosticValue");function O_(e){if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0).map(([n,o])=>`${n}=${L_(o)}`);return t.length>0?t.join(" | "):void 0}i(O_,"formatExtensionDiagnosticMetadata");function cs(e){let t=e.getDiagnostics;if(typeof t=="function")return t.call(e);let n=e.getDefaults,o=typeof n=="function"?n.call(e):void 0;return{loadedExtensions:[],capabilityProviders:e.listCapabilityProviders().map(r=>({id:r.id,kinds:[...r.kinds],source:{kind:"extension",id:`extension:${r.id}`,label:r.id,path:"(runtime)"}})),commands:e.listCommands().map(r=>({name:r.name,aliases:r.aliases,description:r.description,usage:r.usage,metadata:r.metadata,source:{kind:"extension",id:`extension-command:${r.name}`,label:r.name,path:"(runtime)"}})),tools:[],hooks:[],failures:[],defaults:{activeTools:o?.activeTools,modelSelection:o?.modelSelection??{},thinkingLevel:o?.thinkingLevel}}}i(cs,"getExtensionRuntimeDiagnostics");function D_(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(D_,"toExtensionInvocationRequest");async function N_(e,t,n){let o=yo();if(!o)return console.log(u.yellow(`
|
|
302
|
+
[Extension runtime is not active for /${e.name}]`)),!1;let r=await e.handler(t,{sessionId:n.sessionId,gitRoot:n.gitRoot,workingDirectory:n.runtimeInfo?.executionCwd??n.gitRoot??process.cwd(),reloadExtensions:i(()=>o.reloadExtensions(),"reloadExtensions"),getDiagnostics:i(()=>cs(o),"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(!r)return!0;r.message&&console.log(r.message);let s=D_(e,r);return s?{invocation:s}:!0}i(N_,"executeExtensionCommand");function ls(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),r=n[0]?.toLowerCase(),s=n.slice(1).filter(Boolean);if(!r)return null;if(r.startsWith("skill:")){let c=r.slice(6);return c?{command:"skill",args:s,skillInvocation:{name:c}}:{command:"skill",args:s}}let a=r.indexOf(":");if(a>0){let c=r.slice(a+1).trim();r=r.slice(0,a),s=c?[c,...s]:s}return{command:r,args:s}}i(ls,"parseCommand");async function us(e,t,n,o){if(Nr.size===0&&Op(t.gitRoot),e.skillInvocation)return await B_({command:e.skillInvocation.name,args:e.args},t);let r=Nr.get(e.command);if(r){if(r.userInvocable===!1)return console.log(u.yellow(`
|
|
303
|
+
[Command /${r.name} is not user-invocable]`)),!1;try{let a=await r.handler(e.args,t,n,o);return a&&typeof a=="object"?a:!0}catch(a){return console.log(u.red(`
|
|
304
|
+
[Command failed: ${a instanceof Error?a.message:String(a)}]`)),!1}}let s=_T(e.command);if(s)try{return await N_(s,e.args,t)}catch(a){return console.log(u.red(`
|
|
305
|
+
[Extension command failed: ${a instanceof Error?a.message:String(a)}]`)),!1}return console.log(u.yellow(`
|
|
306
|
+
[Unknown command: /${e.command}. Type /help for available commands]`)),!1}i(us,"executeCommand");async function B_(e,t){let n=ho(t.gitRoot),o=e.command,r=e.args.join(" ");n.size===0&&await yr(t.gitRoot);try{let s=n.get(o);if(!s)return console.log(u.red(`
|
|
307
|
+
[Skill not found: ${o}]`)),!1;if(!s.userInvocable)return console.log(u.yellow(`
|
|
308
|
+
[Skill "${o}" is not user-invocable]`)),!1;console.log(u.cyan(`
|
|
309
|
+
[Invoking skill: ${o}]`)),s.argumentHint&&console.log(u.dim(`Arguments: ${r||"(none)"}`)),console.log();let a=await n.loadFull(o),c={workingDirectory:process.cwd(),projectRoot:t.gitRoot??void 0,sessionId:t.sessionId,environment:{}},l=await sx(a,r,c);return console.log(u.green(`Skill activated: ${o}`)),console.log(u.dim("The skill context has been prepared for the AI.")),console.log(),{invocation:{prompt:l.content,source:"skill",displayName:o,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:o,path:a.skillFilePath,description:a.description,arguments:r||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(`
|
|
310
|
+
[Error invoking skill: ${s instanceof Error?s.message:String(s)}]`)),!1}}i(B_,"executeSkillCommand");import{jsx as Z_}from"react/jsx-runtime";import{useState as e$,useEffect as BT,useCallback as qo,useMemo as HT,createContext as t$,useContext as FT}from"react";import*as zu from"fs";import*as Dp from"path";function Yo(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(Yo,"findCommandSlashIndex");var Br=class{static{i(this,"FileCompleter")}cwdSource;cache=new Map;cacheTimeout=5e3;constructor(t){this.cwdSource=t}canComplete(t,n){let o=t.slice(0,n),r=o.lastIndexOf("@");return!(r===-1||r>0&&!/\s/.test(o[r-1]??"")||o.slice(r+1).includes(" "))}async getCompletions(t,n){let o=t.slice(0,n),r=o.lastIndexOf("@");if(r===-1)return[];let s=o.slice(r+1),a=[],c=this.resolveCwd(),l=s.lastIndexOf("/"),d=l===-1?c:Dp.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=Dp.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(),o=this.cache.get(t);return o&&o.expiresAt>n?o.entries:(o&&this.cache.delete(t),new Promise(r=>{zu.readdir(t,(s,a)=>{s?r([]):(this.cache.set(t,{entries:a,expiresAt:Date.now()+this.cacheTimeout}),r(a))})}))}async isDirectory(t){return new Promise(n=>{zu.stat(t,(o,r)=>{n(!o&&r.isDirectory())})})}},Qa=class{static{i(this,"CommandCompleter")}commands;constructor(){this.commands=new Map,this.loadCommands()}loadCommands(){for(let n of Vu().getAll())n.userInvocable!==!1&&this.commands.set(n.name,{description:n.description,aliases:n.aliases??[]});let t=yo();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 o=t.slice(0,n),r=Yo(o);return r===-1?!1:!o.slice(r).includes(" ")}async getCompletions(t,n){let o=t.slice(0,n),r=Yo(o);if(r===-1)return[];this.commands.clear(),this.loadCommands();let s=o.slice(r+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 o=t.toLowerCase(),r=n.toLowerCase(),s=0;for(let a=0;a<r.length&&s<o.length;a++)r[a]===o[s]&&s++;return s===o.length}};function $T(e){let t=new Br(e),n=new Qa;return async o=>{let r=o.includes("@"),s=o.includes("/");if(!r&&!s)return[[],o];let a=[];if(s&&n.canComplete(o,o.length)){let l=await n.getCompletions(o,o.length);a.push(...l)}if(r&&t.canComplete(o,o.length)){let l=await t.getCompletions(o,o.length);a.push(...l)}return[a.map(l=>l.display),o]}}i($T,"createCompleter");var Ja=class{static{i(this,"SkillCompleter")}gitRoot;skillsCache=null;cacheTimestamp=0;CACHE_TTL=5e3;constructor(t){this.gitRoot=t}canComplete(t,n){let o=t.slice(0,n);if(!/\/skill:[^\s]*$/.test(o))return!1;let r=o.lastIndexOf("/skill:");return!(r>0&&!/\s/.test(o[r-1]??""))}async getCompletions(t,n){let r=t.slice(0,n).match(/\/skill:([^\s]*)$/);if(!r)return[];let s=(r[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=ho(this.gitRoot);return n.size===0&&await yr(this.gitRoot),this.skillsCache=n.listUserInvocable(),this.cacheTimestamp=t,this.skillsCache}catch{return[]}}fuzzyIncludes(t,n){let o=0;for(let r=0;r<n.length&&o<t.length;r++)n[r]===t[o]&&o++;return o===t.length}truncateDescription(t,n=50){return t.length<=n?t:t.slice(0,n-3)+"..."}};var H_=[{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"}],Xu=[{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"}],PT=Xu.slice(2).concat([{name:"off",description:"Disable reasoning",type:"enum"}]);function F_(e){if(e&&e.includes("/")){let t=e.indexOf("/"),n=e.slice(0,t),o=e.slice(t+1);if(wi(n))try{return Ai(n).filter(s=>!o||s.toLowerCase().includes(o.toLowerCase())).map(s=>({name:`${n}/${s}`,description:s,type:"enum"}))}catch{}return[]}return Si().map(t=>({name:t,description:`Switch to ${t} provider`,type:"enum"}))}i(F_,"getModelArgs");var LT=[{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"}],Np=[{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"}],Bp=[{name:"all",description:"Delete ALL sessions",type:"enum"}],W_=[{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"}],U_=[{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"}],j_=[{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"}],OT=[{name:"default",description:"Clear the override and use the default value again",type:"enum"}];function G_(e){let[t=""]=e,n=t.toLowerCase(),o=e.length===1&&e[0]===""?0:e.length;return o<=1?W_:o>2?[]:n==="mode"?U_:n==="trace"?j_:n==="endpoint"?[...OT,{name:dx,description:"Default local repointel daemon endpoint",type:"string"}]:n==="bin"?OT:[]}i(G_,"getRepointelArgs");var K_=new Map([["mode",H_],["thinking",Xu],["think",Xu],["t",Xu],["reasoning",PT],["reason",PT],["plan",LT],["p",LT],["status",Np],["info",Np],["ctx",Np],["delete",Bp],["rm",Bp],["del",Bp]]),V_=new Set(["model","m"]),z_=new Set(["repointel","ri"]);function Hp(e,t,n=[]){let o=e.toLowerCase();return V_.has(o)?F_(t):z_.has(o)?G_(n):K_.get(o)??[]}i(Hp,"getCommandArguments");var Yu=class{static{i(this,"ArgumentCompleter")}canComplete(t,n){let o=t.slice(0,n),r=Yo(o);if(r===-1)return!1;let s=o.slice(r),a=s.split(/\s+/);if(a.length>=2&&a[0]!=="")return!0;let c=s.slice(1).toLowerCase();return Hp(c).length>0}async getCompletions(t,n){let o=t.slice(0,n),r=Yo(o);if(r===-1)return[];let s=o.slice(r),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=Hp(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 I=T.display.toLowerCase().startsWith(p),O=w.display.toLowerCase().startsWith(p);return I&&!O?-1:!I&&O?1:T.display.length-w.display.length})}};function X_(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(),o=t.toLowerCase(),r=0,s=-1,a=[];for(let l=0;l<e.length;l++){let d=n[l];if(d===void 0)continue;let m=o.indexOf(d,s+1);if(m===-1)return{matched:!1,score:0,highlights:[]};m===s+1?r+=10:m===0?r+=5:r-=1,t[m]===e[l]&&(r+=2),a.push(m),s=m}let c=Y_(t,a);return r+=c,{matched:!0,score:r,highlights:a}}i(X_,"fuzzyMatch");function Y_(e,t){let n=0;for(let o of t)if(o===0)n+=3;else if(o>0){let r=e[o-1];(r===" "||r==="-"||r==="_")&&(n+=2)}return n}i(Y_,"calculateWordBoundaryBonus");function q_(e,t){return e?t.toLowerCase().startsWith(e.toLowerCase()):!0}i(q_,"prefixMatch");function Q_(e,t){if(q_(e,t)){let r=e?Array.from({length:e.length},(s,a)=>a):[];return{matched:!0,score:100+e.length*10,highlights:r,isPrefix:!0}}return{...X_(e,t),isPrefix:!1}}i(Q_,"combinedMatch");function DT(e,t,n=0){return e?t.map(o=>{let r=Q_(e,o.text);return{...o,_fuzzyScore:r.matched?r.score:-1,_fuzzyHighlights:r.highlights}}).filter(o=>(o._fuzzyScore??-1)>=n).sort((o,r)=>{let s=(r._fuzzyScore??0)-(o._fuzzyScore??0);return s!==0?s:o.text.length-r.text.length}):t}i(DT,"sortCandidatesCombined");var J_={debounceDelay:100,minTriggerChars:1,maxCompletions:10,minScore:0},Fp=class{static{i(this,"AutocompleteProvider")}completers;options;state;listeners=new Set;debounceTimer=null;lastInput="";lastCursorPos=0;constructor(t={}){this.options={...J_,...t},this.completers=[new Ja(this.options.gitRoot),new Yu,new Qa,new Br(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,o=t.cwd!==void 0&&t.cwd!==this.options.cwd;if(this.options={...this.options,...t},n&&this.completers.find(s=>s instanceof Ja)?.setGitRoot(this.options.gitRoot),o){let r=this.completers.findIndex(s=>s instanceof Br);r!==-1&&(this.completers[r]=new Br(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 o=t.slice(0,n),s=Yo(o)!==-1,a=o.lastIndexOf("@"),c=a===0||a>0&&/\s/.test(o[a-1]??"");return s||c}fetchCompletions(t,n){this.updateState({loading:!0}),this.fetchCompletionsInternal(t,n).then(o=>{this.lastInput!==t||this.lastCursorPos!==n||(o.length>0?this.updateState({visible:!0,completions:o.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 o=this.completers.filter(l=>l.canComplete(t,n));if(o.length===0)return[];let r=[];for(let l of o)try{let d=await l.getCompletions(t,n);r.push(...d)}catch(d){console.error("[Autocomplete] Completer error:",d)}let s=this.extractPattern(t,n),a=r.map((l,d)=>({_idx:d,text:l.type==="command"&&l.display.startsWith("/")?l.display.slice(1):l.display}));return DT(s,a,this.options.minScore).map(l=>r[l._idx]).filter(l=>l!==void 0)}extractPattern(t,n){let o=t.slice(0,n),r=Yo(o);if(r!==-1){let c=o.slice(r),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=o.lastIndexOf("@");if(s!==-1){let c=o.slice(s+1),l=c.lastIndexOf("/");return l===-1?c:c.slice(l+1)}let a=o.match(/(\S+)$/);return a?a[1]??"":""}updateState(t){this.state={...this.state,...t};for(let n of this.listeners)try{n(this.state)}catch(o){console.error("[Autocomplete] Listener error:",o)}}};function NT(e){return new Fp(e)}i(NT,"createAutocompleteProvider");var Wp=t$(null);function Up({children:e,cwd:t,gitRoot:n}){let o=qu({cwd:t,gitRoot:n,enabled:!0});return Z_(Wp.Provider,{value:o,children:e})}i(Up,"AutocompleteContextProvider");function Hr(){return FT(Wp)}i(Hr,"useAutocompleteContext");function n$(e,t){let n={command:"command",file:"file",argument:"argument",skill:"skill"},o={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:o[e.type]??">"}}i(n$,"completionToSuggestion");function qu(e={}){let t=FT(Wp);return t&&!e.cwd&&!e.gitRoot?t:o$(e)}i(qu,"useAutocomplete");function o$(e){let{cwd:t,gitRoot:n,enabled:o=!0}=e,r=HT(()=>NT({cwd:t,gitRoot:n,debounceDelay:100,minTriggerChars:1,maxCompletions:8}),[]);BT(()=>{r.updateOptions({cwd:t,gitRoot:n})},[r,t,n]);let[s,a]=e$({visible:!1,selectedIndex:0,completions:[],loading:!1});BT(()=>r.subscribe(I=>{a(I)}),[r]);let c=HT(()=>s.completions.map((w,I)=>n$(w,I)),[s.completions]),l=qo((w,I)=>{if(!o){r.cancel();return}r.handleInput(w,I)},[r,o]),d=qo(()=>s.visible?r.acceptCompletionWithType():null,[r,s.visible]),m=qo(()=>s.visible?r.acceptCompletionWithType():null,[r,s.visible]),p=qo(()=>{s.visible&&r.selectPrevious()},[r,s.visible]),g=qo(()=>{s.visible&&r.selectNext()},[r,s.visible]),x=qo(()=>{s.visible&&r.cancel()},[r,s.visible]),y=qo(()=>{r.cancel()},[r]),T=qo(()=>r,[r]);return{state:s,suggestions:c,handleInput:l,handleTab:d,handleEnter:m,handleUp:p,handleDown:g,handleEscape:x,cancel:y,getProvider:T}}i(o$,"useAutocompleteImpl");import{useCallback as Za,useRef as WT}from"react";var In=[];function jp(e={}){let{maxSize:t=1e3,onSave:n}=e,o=WT(-1),r=WT(""),s=Za((m,p)=>{if(!m.trim())return;if(In[In.length-1]?.text!==m){let x={text:m,timestamp:Date.now(),...p?.pastedContents&&p.pastedContents.length>0?{pastedContents:[...p.pastedContents]}:{}};In.push(x),In.length>t&&In.splice(0,In.length-t),n?.(x)}o.current=-1,r.current=""},[t,n]),a=Za(()=>In.length===0?null:o.current===-1?(o.current=In.length-1,In[o.current]??null):o.current>0?(o.current--,In[o.current]??null):null,[]),c=Za(()=>o.current===-1?null:o.current<In.length-1?(o.current++,In[o.current]??null):(o.current=-1,{text:r.current,timestamp:Date.now()}),[]),l=Za(()=>{o.current=-1,r.current=""},[]),d=Za(m=>{o.current===-1&&(r.current=m)},[]);return{add:s,navigateUp:a,navigateDown:c,reset:l,saveTempInput:d}}i(jp,"useInputHistory");function Jt(e,t,n){return zt(e).slice(t,n).join("")}i(Jt,"sliceByCodePoints");var ec=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 qn(this.currentLine)}get visualCursor(){let t=this._lines[this._cursor.row]??"",n=Jt(t,0,this._cursor.col);return{row:this._cursor.row,col:qn(n)}}getCharWidthAtCursor(){let t=this._lines[this._cursor.row]??"",o=zt(t)[this._cursor.col];return o?Yn(o)?2:1:0}visualColToLogicalCol(t){let n=this._lines[this._cursor.row]??"",o=zt(n),r=0;for(let s=0;s<o.length;s++){let a=Yn(o[s])?2:1;if(r+a>t)return s;r+=a}return o.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,o){this._saveHistory();let r=Math.max(0,Math.min(t,this._text.length)),s=Math.max(r,Math.min(n,this._text.length)),a=this._text.slice(0,r)+o+this._text.slice(s);this._setTextInternal(a),this.moveToAbsoluteOffset(r+o.length)}insert(t,n){if(this._saveHistory(),n?.paste){this._insertText(t);return}let o=t.split(`
|
|
311
|
+
`);for(let r=0;r<o.length;r++)r>0&&this._insertNewline(),this._insertText(o[r])}_insertText(t){let n=this._lines[this._cursor.row],o=Jt(n,0,this._cursor.col),r=Jt(n,this._cursor.col);this._lines[this._cursor.row]=o+t+r,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=Jt(t,0,this._cursor.col),o=Jt(t,this._cursor.col);this._lines[this._cursor.row]=n,this._lines.splice(this._cursor.row+1,0,o),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,o=Jt(t,0,n),r=Jt(t,this._cursor.col);this._lines[this._cursor.row]=o+r,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=Jt(t,0,this._cursor.col),o=Jt(t,this._cursor.col+1);this._lines[this._cursor.row]=n+o,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]=Jt(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]=Jt(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,o=zt(t);for(;n>0&&/\s/.test(o[n]??"");)n--;for(;n>0&&!/\s/.test(o[n-1]??"");)n--;let r=Jt(t,0,n),s=Jt(t,this._cursor.col);this._lines[this._cursor.row]=r+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(`
|
|
312
|
+
`),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(`
|
|
313
|
+
`),this._lines.length===0&&(this._lines=[""]),this._clampCursor(),!0):!1}_updateText(){this._text=this._lines.join(`
|
|
314
|
+
`)}_setTextInternal(t){this._text=t,this._lines=t.split(`
|
|
315
|
+
`),this._lines.length===0&&(this._lines=[""])}moveToAbsoluteOffset(t){let o=Math.max(0,Math.min(t,this._text.length));for(let r=0;r<this._lines.length;r++){let s=this._lines[r]??"",a=s.length;if(o<=a){this._cursor={row:r,col:rn(s.slice(0,o))},this._rememberedCol=this._cursor.col;return}o-=a,r<this._lines.length-1&&(o-=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 o=0;o<this._cursor.row;o++)t+=(this._lines[o]?.length??0)+1;let n=this._lines[this._cursor.row]??"";return t+=Jt(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 r$,useCallback as It,useRef as Gp,useEffect as i$}from"react";function Kp(e={}){let{initialValue:t="",onTextChange:n}=e,o=Gp(null),r=Gp(null),s=Gp(null),[a,c]=r$({text:t,cursor:{row:0,col:0},lines:[""],isPasting:!1,editingMode:t?"typing":"idle"});o.current===null&&(o.current=new ec,t&&o.current.setText(t)),r.current===null&&(r.current=xT());let l=o.current,d=r.current,m=It(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=It(()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{c(M=>({...M,isPasting:!1,editingMode:M.text?"typing":"idle"})),s.current=null},120)},[]),g=It(M=>{l.setText(M),m({isPasting:!1,editingMode:M?"typing":"idle"})},[l,m]),x=It((M,C,Z)=>{l.replaceRange(M,C,Z),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),y=It((M,C)=>{let Z=C?.paste??!1;if(Z&&hT(M)){let Re=M.replace(/\r\n/g,`
|
|
316
|
+
`).replace(/\r/g,`
|
|
317
|
+
`),{placeholder:Ie}=d.registerText(Re);l.insert(Ie,{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=It(()=>{l.newline(),m({isPasting:!1,editingMode:"typing"})},[l,m]),w=It(()=>{let M=l.getAbsoluteOffset(),C=Fu(l.text,M);C?l.replaceRange(C.start,C.end,""):l.backspace(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),I=It(()=>{let M=l.getAbsoluteOffset(),C=Wu(l.text,M);C?l.replaceRange(C.start,C.end,""):l.delete(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),O=It(M=>{l.move(M),m()},[l,m]),$=It(()=>{l.clear(),m({isPasting:!1,editingMode:"idle"})},[l,m]),D=It(()=>{let M=l.undo();return M&&m(),M},[l,m]),L=It(()=>{let M=l.redo();return M&&m(),M},[l,m]),X=It(()=>{l.moveToEnd(),m()},[l,m]),v=It(M=>{l.moveToAbsoluteOffset(M),m()},[l,m]),ie=It(()=>{l.killLineRight(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),Te=It(()=>{l.killLineLeft(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),G=It(()=>{l.deleteWordLeft(),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]),q=It(()=>{s.current&&(clearTimeout(s.current),s.current=null),m({isPasting:!1,editingMode:l.text?"typing":"idle"})},[l,m]);return i$(()=>()=>{s.current&&clearTimeout(s.current),o.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:I,move:O,moveToEnd:X,moveToOffset:v,killLineRight:ie,killLineLeft:Te,deleteWordLeft:G,clear:$,undo:D,redo:L}}i(Kp,"useTextBuffer");import{jsx as Fr,jsxs as Ju}from"react/jsx-runtime";import{useState as KT}from"react";import{useCallback as ds,useEffect as Vp,useRef as Qu}from"react";function UT(e,t,n){let o=Math.max(0,Math.min(t,e.length)),r=e.slice(0,o);if(n.type==="command"||n.type==="skill"){let a=r.lastIndexOf("/");return{start:a===-1?0:a,end:o,replacement:n.text}}if(n.type==="argument"){let a=r.match(/\S+$/);return{start:a?o-a[0].length:0,end:o,replacement:n.text}}let s=r.lastIndexOf("@");return{start:s===-1?0:s,end:o,replacement:n.text}}i(UT,"buildAutocompleteReplacement");var a$=500;function jT(e,t,n){return n==="up"?e===0:e>=Math.max(0,t-1)}i(jT,"shouldUseHistoryNavigation");function c$(e){return e.isAutocompleteVisible?"cancel-autocomplete":e.hasText?e.timeSinceLastEscapeMs<a$?"clear-input":"arm-clear":"pass-through"}i(c$,"resolvePromptEscapeBehavior");function l$(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(l$,"resolvePromptEnterBehavior");function u$(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(u$,"resolvePromptEditingCommand");function GT({onSubmit:e,onExit:t,focus:n=!0,initialValue:o="",cwd:r,gitRoot:s,autocompleteEnabled:a=!0,onInputChange:c,onHistoryRecall:l,onPopPendingInputs:d}){let m=Qu(0),{add:p,navigateUp:g,navigateDown:x,reset:y,saveTempInput:T}=jp(),{buffer:w,text:I,cursor:O,lines:$,isPasting:D,editingMode:L,pasteStore:X,resetTransientState:v,setText:ie,replaceRange:Te,clear:G,move:q,moveToOffset:M,insert:C,backspace:Z,newline:Re,delete:Ie,undo:Se,redo:ce,killLineRight:Ne,killLineLeft:ae,deleteWordLeft:Y}=Kp({initialValue:o,onTextChange:c}),Q=Qu(0);Vp(()=>{if(D)return;if(I.length<=1e4){Q.current=0;return}if(I.length===Q.current)return;let K=X.peekNextId(),{truncatedText:fe,placeholderContent:V}=yT(I,K);V&&(X.registerTruncatedText(V),Q.current=fe.length,ie(fe))},[I,D,X,ie]);let be=Hr(),ve=qu({cwd:r,gitRoot:s,enabled:a}),{state:lt,suggestions:Ee,handleInput:je,handleTab:xe,handleEnter:Rt,handleUp:Qe,handleDown:ee,handleEscape:A}=be??ve;Vp(()=>{n||(m.current=0,v(),lt.visible&&A())},[lt.visible,n,A,v]);let _=Qu(I);Vp(()=>{a&&I!==_.current&&(_.current=I,je(I,w.getAbsoluteOffset()))},[a,w,je,I]);let F=ds(K=>{if(!K?.text)return;let fe=UT(I,w.getAbsoluteOffset(),K),V=I.slice(0,fe.start)+fe.replacement+I.slice(fe.end);return Te(fe.start,fe.end,fe.replacement),V},[w,Te,I]),J=ds(K=>{let fe=K??I;if(!fe.trim())return;let V=X.expand(fe),Ce=new Set,ot=/\[(Pasted text|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.*)\]/g;for(let Ps of fe.matchAll(ot)){let Wn=Number.parseInt(Ps[2]??"0",10);Number.isFinite(Wn)&&Wn>0&&Ce.add(Wn)}let Fn=[];for(let Ps of Ce){let Wn=X.get(Ps);Wn&&Fn.push(Wn)}p(fe,{pastedContents:Fn}),e({displayText:fe,fullText:V,pastedContents:Fn}),G()},[p,G,e,X,I]),Be=ds(K=>{if(K){if(K.pastedContents&&K.pastedContents.length>0){for(let fe of K.pastedContents)X.adopt(fe);l?.({text:K.text,pastedContents:[...K.pastedContents]})}ie(K.text)}},[l,X,ie]),tt=ds(async K=>{try{let fe=await Bx(K);if(fe.kind==="images"){let V=fe.blocks.map(Ce=>`@${Ce.path}`).join(" ");C(`${V} `,{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]),ke=Qu(!1),Oe=ds(async()=>{if(!ke.current){ke.current=!0;try{let K=await Hx();if(K.kind==="images"){let fe=K.blocks.map(V=>`@${V.path}`).join(" ");C(`${fe} `,{paste:!1})}else K.kind==="error"&&console.warn(`[KodaX clipboard] ${K.message}`)}catch(K){console.warn(`[KodaX clipboard] image handling failed: ${K instanceof Error?K.message:String(K)}`)}finally{ke.current=!1}}},[C]),Vt=ds(K=>{if(!n)return!1;if(K.name==="v"&&(K.ctrl||K.meta))return Oe(),!0;if(K.name==="paste"&&K.isPasted&&Fx(K.sequence).length>0)return tt(K.sequence),!0;let fe=lt.visible&&Ee.length>0;if(K.name==="tab"&&fe){let Ce=xe();return Ce&&F(Ce),!0}if(K.ctrl&&K.name==="c")return I.length>0?(G(),y()):t?.(),!0;if(K.name==="escape")switch(c$({isAutocompleteVisible:fe,hasText:I.length>0,timeSinceLastEscapeMs:Date.now()-m.current})){case"cancel-autocomplete":return A(),m.current=0,!0;case"clear-input":return m.current=0,G(),y(),!0;case"arm-clear":return m.current=Date.now(),!0;default:return!1}if(K.name==="up"){if(fe)return Qe(),!0;if(K.ctrl)return q("up"),!0;if(I.length===0&&d){let Ce=d();if(typeof Ce=="string"&&Ce.length>0)return ie(Ce),!0}if(jT(O.row,$.length,"up")){T(I);let Ce=g();Be(Ce)}else q("up");return!0}if(K.name==="down"){if(fe)return ee(),!0;if(K.ctrl)return q("down"),!0;if(jT(O.row,$.length,"down")){let Ce=x();Be(Ce)}else q("down");return!0}if(K.name==="left"){let Ce=w.getAbsoluteOffset(),ot=Fu(w.text,Ce);return ot?M(ot.start):q("left"),!0}if(K.name==="right"){let Ce=w.getAbsoluteOffset(),ot=Wu(w.text,Ce);return ot?M(ot.end):q("right"),!0}if(K.name==="home")return q("home"),!0;if(K.name==="end")return q("end"),!0;let V=u$(K);if(V)switch(V){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 Ne(),!0;case"kill-line-left":return ae(),!0;case"delete-word-left":return Y(),!0;default:break}if(K.name==="backspace")return Z(),!0;if(K.name==="delete")return Ie(),!0;if(K.name==="return"||K.name==="newline")switch(l$({keyName:K.name,ctrl:K.ctrl,shift:K.shift,isAutocompleteVisible:fe,isLineContinuation:!!$[O.row]?.endsWith("\\"),isPasting:D})){case"accept-completion-and-submit":{let ot=Rt();if(ot){let Fn=F(ot);J(Fn)}else J();return!0}case"newline":return Re(),!0;case"line-continuation":return Z(),Re(),!0;default:return J(),!0}return K.insertable&&!K.ctrl&&!K.meta?(C(K.sequence,K.isPasted?{paste:!0}:void 0),!0):!1},[F,p,lt.visible,Z,w,G,O.row,Ie,n,ee,A,Qe,Rt,Be,xe,tt,Oe,$,ae,Ne,q,M,x,g,Re,t,d,ce,y,T,ie,J,Ee.length,I.length,Y,D,Se]);return{text:I,cursor:O,lines:$,isPasting:D,terminalFocused:n,editingMode:L,handleKey:Vt}}i(GT,"usePromptInputController");var fs=i(({onSubmit:e,onHistoryRecall:t,onPopPendingInputs:n,placeholder:o="Type a message...",prompt:r=">",focus:s=!0,initialValue:a="",cwd:c,gitRoot:l,autocompleteEnabled:d=!0,onInputChange:m})=>{let{exit:p}=Go(),{cursor:g,lines:x,handleKey:y,isPasting:T,terminalFocused:w,editingMode:I}=GT({onSubmit:e,onExit:p,focus:s,initialValue:a,cwd:c,gitRoot:l,autocompleteEnabled:d,onInputChange:m,onHistoryRecall:t,onPopPendingInputs:n});return an(Bt.High,O=>y(O),[y]),Fr(k,{flexDirection:"column",children:Fr(np,{lines:x,cursorRow:g.row,cursorCol:g.col,prompt:r,placeholder:o,focus:s,terminalFocused:w,isPasting:T,editingMode:I,theme:"dark"})})},"InputPrompt"),d$=i(({onSubmit:e,placeholder:t,prompt:n=">"})=>{let[o,r]=KT(""),[s,a]=KT(0);an(Bt.High,p=>{if(p.name==="return")return o.trim()&&(e(o),r(""),a(0)),!0;if(p.name==="backspace"&&s>0){let g=[...o].slice(0,s-1).join(""),x=[...o].slice(s).join("");return r(g+x),a(s-1),!0}if(p.name==="left"&&s>0)return a(s-1),!0;if(p.name==="right"&&s<[...o].length)return a(s+1),!0;if(p.insertable&&!p.ctrl&&!p.meta){let g=[...o].slice(0,s).join(""),x=[...o].slice(s).join("");return r(g+p.sequence+x),a(s+1),!0}return!1},[o,s,e]);let c=ne("dark");if(!o)return Ju(k,{children:[Ju(b,{color:c.colors.primary,children:[n," "]}),t&&Fr(b,{dimColor:!0,children:t}),Fr(b,{backgroundColor:c.colors.primary,color:"#000000",children:" "})]});let l=[...o].slice(0,s).join(""),d=[...o][s]??" ",m=[...o].slice(s+1).join("");return Ju(k,{children:[Ju(b,{color:c.colors.primary,children:[n," "]}),Fr(b,{children:l}),Fr(b,{backgroundColor:c.colors.primary,color:"#000000",children:d}),Fr(b,{children:m})]})},"SimpleInputPrompt");import{jsx as at,jsxs as At}from"react/jsx-runtime";import{useState as zT,useEffect as XT}from"react";var VT=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f$=80,Zu=new Set,tc=null;function m$(){let e=Array.from(Zu);for(let t of e)t()}i(m$,"dispatchSharedSpinnerTick");function p$(e){return Zu.add(e),tc===null&&(tc=setInterval(m$,f$)),()=>{Zu.delete(e),Zu.size===0&&tc!==null&&(clearInterval(tc),tc=null)}}i(p$,"subscribeToSharedSpinnerClock");function YT(e=!0){let[t,n]=zT(0);return XT(()=>{if(e)return p$(()=>{n(o=>o+1)})},[e]),t}i(YT,"useSharedSpinnerTick");var kn=i(({color:e,theme:t})=>{let n=t??ne("dark"),r=YT(!0)%VT.length,s=e??n.colors.accent;return at(b,{color:s,children:VT[r]})},"Spinner");function g$(e){return e<=0?0:Math.round(e/4)}i(g$,"estimateOutputTokens");function h$(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/3600),o=Math.floor(t%3600/60),r=t%60;return n===0?`${o}m${r}s`:`${n}h${o}m${r}s`}i(h$,"formatElapsedDuration");var qT=i(({roundStartedAt:e,charCount:t,theme:n})=>{let o=n??ne("dark");if(YT(e!==null),e===null)return null;let r=y$(Date.now()-e,t);return at(b,{color:o.colors.dim,children:r})},"SpinnerStatsTail");function y$(e,t){let n=h$(e),o=g$(t);return o>0?` (${n} \xB7 \u2193 ${o} tokens)`:` (${n})`}i(y$,"buildSpinnerStatsText");var QT=i(({label:e,dotCount:t=3,theme:n})=>{let o=n??ne("dark"),[r,s]=zT(1);XT(()=>{let c=setInterval(()=>{s(l=>l%t+1)},300);return()=>clearInterval(c)},[t]);let a=".".repeat(r);return At(k,{children:[e&&at(b,{color:o.colors.text,children:e}),at(b,{color:o.colors.accent,children:a})]})},"DotsIndicator"),JT=i(({progress:e,label:t,width:n=20,theme:o})=>{let r=o??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 At(k,{flexDirection:"column",children:[t&&at(k,{marginBottom:1,children:at(b,{color:r.colors.text,children:t})}),At(k,{children:[at(b,{color:r.colors.primary,children:l}),at(b,{dimColor:!0,children:d}),At(b,{children:[" ",s,"%"]})]})]})},"ProgressIndicator"),x$=i(({message:e,showSpinner:t=!1,theme:n})=>{let o=n??ne("dark"),r=e??"Thinking";return At(k,{children:[t&&at(k,{marginRight:1,children:at(kn,{theme:o})}),At(b,{color:o.colors.accent,children:[r,"\u2026"]})]})},"ThinkingIndicator"),w$=i(({message:e,subMessage:t,progress:n,type:o="spinner",compact:r=!1,theme:s})=>{let a=s??ne("dark"),c=e??"Loading";return r?At(k,{children:[at(kn,{theme:a}),At(b,{color:a.colors.text,children:[" ",c,"\u2026"]})]}):o==="bar"&&n!==void 0?At(k,{flexDirection:"column",children:[at(JT,{progress:n,label:c,theme:a}),t&&at(k,{marginTop:1,children:at(b,{dimColor:!0,children:t})})]}):o==="dots"?At(k,{flexDirection:"column",children:[at(QT,{label:c,theme:a}),t&&at(k,{marginTop:1,children:at(b,{dimColor:!0,children:t})})]}):o==="simple"?At(k,{flexDirection:"column",children:[At(b,{color:a.colors.accent,children:[c,"\u2026"]}),t&&at(k,{marginTop:1,children:at(b,{dimColor:!0,children:t})}),n!==void 0&&at(k,{marginTop:1,children:At(b,{dimColor:!0,children:[n,"%"]})})]}):At(k,{flexDirection:"column",children:[At(k,{children:[at(kn,{theme:a}),At(b,{color:a.colors.text,children:[" ",c,"\u2026"]}),n!==void 0&&At(b,{dimColor:!0,children:[" (",n,"%)"]})]}),t&&at(k,{marginTop:1,children:at(b,{dimColor:!0,children:t})})]})},"LoadingIndicator");import{jsx as de,jsxs as We,Fragment as ig}from"react/jsx-runtime";import{useEffect as bC,useMemo as ro,memo as cn}from"react";import*as oc from"node:path";function nc(e){if(ex(e)){let t=tx(e);return t?`[memory:${t}]`:"[memory]"}if(S$(e))return"[memory]"}i(nc,"memoryBadgeFor");function S$(e){let t=oc.resolve(e),n=hn("projects");if(!t.startsWith(n+oc.sep)&&t!==n)return!1;let r=t.slice(n.length+1).split(oc.sep);return r.length>=2&&r[1]==="memory"}i(S$,"isInsideAnyMemoryDir");function ze(e,t=120){return e.length>t?`${e.slice(0,t-3)}...`:e}i(ze,"truncateValue");function ZT(e){if(e)return e.split(/\r?\n/).map(t=>t.trim()).find(Boolean)}i(ZT,"extractFirstMeaningfulLine");function nC(e){let t=e.match(/^\[([^\]]+)\]\s+(.*)$/);if(!t)return{toolLabel:e};let n=t[1]?.trim(),o=t[2]?.trim()??e,r=new RegExp(`^${n?.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}:`,"i"),s=o.replace(r,"").trim();return{rolePrefix:n?`[${n}]`:void 0,toolLabel:s||o}}i(nC,"splitDisplayToolName");function ed(e){let{rolePrefix:t,toolLabel:n}=nC(e);return t?`${t} ${n}`:n}i(ed,"normalizeDisplayToolName");function Xp(e){return nC(e).toolLabel}i(Xp,"stripRolePrefix");function td(e){if(!(!e||Array.isArray(e)||typeof e!="object"))return e}i(td,"asRecord");function oC(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(oC,"readString");function Tt(e,...t){for(let n of t){let o=oC(e?.[n]);if(o)return o}}i(Tt,"readFirstString");function no(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(no,"readNumber");function rC(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(rC,"readStringArray");function T$(e){if(typeof e=="string")return e.trim()||void 0;let t=td(e);if(t)return oC(t.preview)??void 0}i(T$,"extractPreview");function eC(e){if(e)try{return td(JSON.parse(e))}catch{return}}i(eC,"parsePreviewRecord");function Le(e,t){return e&&e.match(new RegExp(`"${t}"\\s*:\\s*"([^"]+)`))?.[1]?.trim()||void 0}i(Le,"extractFieldFromPreview");function oo(e,t){if(!e)return;let n=e.match(new RegExp(`"${t}"\\s*:\\s*(\\d+)`));return n?.[1]?Number(n[1]):void 0}i(oo,"extractNumberFromPreview");function iC(e){if(!e)return;let t=e.match(/"paths"\s*:\s*\[([^\]]*)/);if(!t?.[1])return;let n=Array.from(t[1].matchAll(/"([^"]+)"/g)).map(o=>o[1]?.trim()??"").filter(Boolean);return n.length>0?n:void 0}i(iC,"extractPathsFromPreview");function C$(e){let t=T$(e);if(typeof e=="string")return{record:eC(t),preview:t};let n=td(e),o=eC(t);return n?o?{record:{...n,...o},preview:t}:{record:n,preview:t}:{record:o,preview:t}}i(C$,"resolveInputRecord");function ms(e,t,n,o=!1){let r=Tt(t,"path","target_path","targetPath")??Le(n,"path")??Le(n,"target_path")??Le(n,"targetPath"),s=rC(t?.paths)??iC(n);if(o&&s?.length){if(s.length===1){let a=nc(s[0]);a&&e.push(a),e.push(ze(s[0]))}else e.push(`${s.length} files`);return}if(r){let a=nc(r);a&&e.push(a),e.push(ze(r));return}if(s?.length)if(s.length===1){let a=nc(s[0]);a&&e.push(a),e.push(ze(s[0]))}else e.push(`${s.length} files`)}i(ms,"pushPathSummary");function ps(e,t,n){n!==void 0&&e.push(`${t}=${n}`)}i(ps,"pushNumericSummary");function zp(e,t,n){let o=Tt(t,"baseRef","base_ref")??Le(n,"baseRef")??Le(n,"base_ref"),r=Tt(t,"targetRef","target_ref")??Le(n,"targetRef")??Le(n,"target_ref");o&&r&&e.push(ze(`${o}...${r}`,88))}i(zp,"pushRangeSummary");function b$(e,t){let{record:n,preview:o}=C$(t),r=Xp(e).toLowerCase(),s=[];if(r.includes("changed_diff_bundle")){let a=rC(n?.paths)??iC(o);a?.length?(s.push(a.length===1?ze(a[0]):`${a.length} files`),a.length>1&&s.push(ze(a[0]))):ms(s,n,o,!0);let c=no(n?.limit_per_path)??no(n?.limitPerPath)??oo(o,"limit_per_path")??oo(o,"limitPerPath");return c!==void 0&&s.push(`limit=${c}`),zp(s,n,o),s}if(r.includes("changed_diff"))return ms(s,n,o),ps(s,"offset",no(n?.offset)??oo(o,"offset")),ps(s,"limit",no(n?.limit)??oo(o,"limit")),zp(s,n,o),s;if(r==="read"||r.includes("read_"))return ms(s,n,o),ps(s,"offset",no(n?.offset)??oo(o,"offset")),ps(s,"limit",no(n?.limit)??oo(o,"limit")),s;if(r.includes("changed_scope"))return ms(s,n,o,!0),zp(s,n,o),s;if(r.includes("repo_overview"))return ms(s,n,o),s;if(r.includes("bash")||r.includes("shell_command")){let a=Tt(n,"command")??Le(o,"command");return a&&s.push(`cmd=${ze(a,140)}`),s}if(r==="glob"||r.includes("glob_")){let a=Tt(n,"pattern")??Le(o,"pattern"),c=Tt(n,"path","root","directory","cwd")??Le(o,"path")??Le(o,"root")??Le(o,"directory")??Le(o,"cwd");if(a&&s.push(`pattern=${ze(a,96)}`),c){let l=nc(c);l&&s.push(l),s.push(ze(c))}return s}if(r==="grep"||r.includes("grep_")){let a=Tt(n,"pattern","query")??Le(o,"pattern")??Le(o,"query"),c=Tt(n,"path","root","directory","cwd")??Le(o,"path")??Le(o,"root")??Le(o,"directory")??Le(o,"cwd");if(a&&s.push(`pattern=${ze(a,96)}`),c){let l=nc(c);l&&s.push(l),s.push(ze(c))}return s}if(r==="web_fetch"){let a=Tt(n,"url")??Le(o,"url"),c=Tt(n,"provider_id","providerId")??Le(o,"provider_id")??Le(o,"providerId"),l=Tt(n,"capability_id","capabilityId")??Le(o,"capability_id")??Le(o,"capabilityId");return a&&s.push(ze(a,120)),c&&s.push(`provider=${ze(c,48)}`),l&&s.push(`cap=${ze(l,48)}`),s}if(r==="mcp_describe"||r==="mcp_read_resource"){let a=Tt(n,"id")??Le(o,"id");return a&&s.push(ze(a,120)),s}if(r==="mcp_call"){let a=Tt(n,"id")??Le(o,"id"),c=td(n?.args),l=c?Object.keys(c).length:void 0;return a&&s.push(ze(a,120)),l!==void 0&&s.push(`args=${l}`),s}if(r==="mcp_search"){let a=Tt(n,"query")??Le(o,"query"),c=Tt(n,"server")??Le(o,"server"),l=Tt(n,"kind")??Le(o,"kind"),d=no(n?.limit)??oo(o,"limit");return a&&s.push(`query=${ze(a,96)}`),c&&s.push(`server=${ze(c,48)}`),l&&s.push(`kind=${l}`),d!==void 0&&s.push(`limit=${d}`),s}if(r==="web_search"||r==="code_search"||r==="semantic_lookup"){let a=Tt(n,"query","pattern")??Le(o,"query")??Le(o,"pattern"),c=Tt(n,"path","target_path","targetPath")??Le(o,"path")??Le(o,"target_path")??Le(o,"targetPath"),l=Tt(n,"provider_id","providerId")??Le(o,"provider_id")??Le(o,"providerId"),d=no(n?.limit)??oo(o,"limit");return a&&s.push(`query=${ze(a,96)}`),c&&s.push(ze(c,72)),l&&s.push(`provider=${ze(l,48)}`),d!==void 0&&s.push(`limit=${d}`),s}return ms(s,n,o,!0),ps(s,"offset",no(n?.offset)??oo(o,"offset")),ps(s,"limit",no(n?.limit)??oo(o,"limit")),s}i(b$,"summarizeToolDetails");function sC(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(sC,"extractChangedDiffRange");function v$(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.startsWith("+")||t.startsWith("-")||t.startsWith("@@"))}i(v$,"extractDiffPreviewLine");function I$(e){let t=[],n=sC(e);if(n){let[r,s]=n.split("/");t.push(s?`Diff range: ${r} of ${s}`:`Diff range: ${n}`)}let o=v$(e);return o&&t.push(`Preview: ${ze(o,220)}`),t}i(I$,"formatChangedDiffExplanation");function k$(e){let t=[],n=e.match(/^Changed diff bundle for\s+(\d+)\s+file\(s\)/im);if(n?.[1]){let r=Number(n[1]);Number.isFinite(r)&&r>0&&t.push(`Bundle: ${r===1?"1 file":`${r} files`}`)}let o=e.match(/^===\s+(.+?)\s+===/m);return o?.[1]&&t.push(`First file: ${ze(o[1].trim(),220)}`),t}i(k$,"formatChangedDiffBundleExplanation");function aC(e,t){if(!t)return[];let n=Xp(e).toLowerCase(),o=[];if(n.includes("changed_diff_bundle")){let r=t.match(/^Changed diff bundle for\s+(\d+)\s+file\(s\)/im);if(r?.[1]){let a=Number(r[1]);Number.isFinite(a)&&a>0&&o.push(a===1?"1 file":`${a} files`)}let s=t.match(/^===\s+(.+?)\s+===/m);return s?.[1]&&o.push(ze(s[1].trim())),o}if(n.includes("changed_diff")){let r=t.match(/^Changed diff for\s+(.+)$/im);r?.[1]&&o.push(ze(r[1].trim()));let s=sC(t);return s&&o.push(s),o}if(n==="read"||n.includes("read_")){let r=t.match(/^Reading\s+(.+)$/im);return r?.[1]&&o.push(ze(r[1].trim())),o}return[]}i(aC,"summarizeToolOutputDetails");function Yp(e,t){let n=ed(e);return t.length>0?`${n} - ${t.join(" - ")}`:n}i(Yp,"formatToolDetailSummary");function R$(e,t){if(!t)return;let n=t-e;return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}i(R$,"formatDuration");function E$(e){switch(e.status){case P.Scheduled:return"scheduled";case P.Validating:return"validating";case P.AwaitingApproval:return"awaiting approval";case P.Executing:return"running";case P.Error:return"failed";case P.Cancelled:return"cancelled";default:return}}i(E$,"formatToolStatusDetail");function tC(e){switch(e.status){case P.Scheduled:return["Queued: waiting to start"];case P.Validating:return["Validating: checking inputs and policy"];case P.AwaitingApproval:return["Waiting: approval required before execution"];case P.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 P.Cancelled:return["Cancelled before completion"];default:return[]}}i(tC,"formatToolProgressExplanation");function qp(e){return e.startsWith("Error:")?"error":e.startsWith("Waiting:")?"accent":e.startsWith("Progress:")||e.startsWith("Running:")?"primary":"dim"}i(qp,"resolveToolExplanationTone");function M$(e){let t=ZT(e.error),n=typeof e.output=="string"?ZT(e.output):void 0,o=[];return t&&o.push(`Error: ${ze(t,220)}`),e.status===P.Error&&n&&(!t||n.toLowerCase()!==t.toLowerCase())&&o.push(`Last output: ${ze(n,220)}`),o}i(M$,"formatToolFailureExplanation");function Qp(e){if(typeof e.output!="string"||!e.output.trim())return tC(e);let t=Xp(e.name).toLowerCase();return e.status===P.Error?M$(e):e.status!==P.Success?tC(e):t.includes("changed_diff_bundle")?k$(e.output):t.includes("changed_diff")?I$(e.output):[]}i(Qp,"formatToolResultExplanation");function Jp(e,t){return Yp(e,b$(e,t))}i(Jp,"formatToolSummary");function nd(e){let t=typeof e.output=="string"?aC(e.name,e.output):[],n=t.length>0?Yp(e.name,t):Jp(e.name,e.input),o=E$(e),r=R$(e.startTime,e.endTime),s=e.status===P.Executing&&e.progress!==void 0?`${e.progress}%`:e.status===P.Executing&&e.preview?e.preview:void 0,a=[o,s,r].filter(Boolean);return a.length>0?`${n} (${a.join(" - ")})`:n}i(nd,"formatToolCallInlineText");function od(e){let t=new Map;for(let n of e){let o=typeof n.output=="string"?aC(n.name,n.output):[],r=o.length>0?Yp(n.name,o):Jp(n.name,n.input),a=n.progressLines&&n.progressLines.length>0?`${r}|${n.id}`:`${r}|${n.error??""}`,c=t.get(a);c?(c.tool=n,c.count+=1):t.set(a,{tool:n,count:1})}return[...t.values()]}i(od,"collapseToolCalls");function rc(e){let t=nd(e.tool);return e.count>1?`${t} x${e.count}`:t}i(rc,"formatCollapsedToolInlineText");function rd(e,t,n){let o=Jp(e,t);return o!==ed(e)?`[Tools] ${o}`:n>0?`[Tools] ${ed(e)} (${n} chars)`:`[Tools] ${ed(e)}`}i(rd,"formatLiveToolLabel");function Zp(e,t=e.length){let n=0,o=Math.min(t,e.length);for(let r=0;r<o;r++)e.charCodeAt(r)===10&&(n+=1);return n}i(Zp,"countNewlines");function id(e,t={}){let n=t.maxChars??1e4,o=t.headChars??2500,r=t.tailChars??2500;if(e.length<=n)return e;let s=e.slice(0,o),a=e.slice(-r),c=Zp(e),l=Zp(s),d=Zp(a),m=Math.max(0,c-l-d);return`${s}
|
|
318
|
+
\u2026 +${m} lines \u2026
|
|
319
|
+
${a}`}i(id,"truncateUserMessageForDisplay");var cC=400,A$="... (thinking truncated; press Ctrl+O to inspect full reasoning)",lC=2e5,_$="... (thinking show-all truncated at 200K chars; full content available via session artifacts)",uC=1e5;function $$(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($$,"normalizeManagedLiveActivityLabel");function sd(e){return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}i(sd,"formatTimestamp");function dC(e){switch(e){case P.Scheduled:return"\u25CB";case P.Validating:return"\u25D0";case P.AwaitingApproval:return"\u23F8";case P.Executing:return"\u25CF";case P.Success:return"\u2713";case P.Error:return"\u2717";case P.Cancelled:return"\u2298";default:return"[tool]"}}i(dC,"getToolStatusIcon");function fC(e){switch(e){case P.Scheduled:case P.Validating:return"dim";case P.AwaitingApproval:return"accent";case P.Executing:return"primary";case P.Success:return"success";case P.Error:return"error";case P.Cancelled:return"dim";default:return"text"}}i(fC,"getToolStatusColor");function P$(e,t){let n=Math.max(1,t),o=e.split(`
|
|
320
|
+
`),r=Xt(o.length>0?o:[""],n,0,0);return r.visualLines.length>0?r.visualLines:[""]}i(P$,"wrapText");function eg(e,t,n,o=!1){if(n||o)return e.length>lC?`${e.slice(0,lC)}
|
|
321
|
+
|
|
322
|
+
${_$}`:e;let r=e.split(/\r?\n/),s=r.length>t,a=s?r.slice(0,t).join(`
|
|
323
|
+
`):e,c=a.length>cC,l=c?a.slice(0,cC):a;return!s&&!c?e:`${l}
|
|
324
|
+
|
|
325
|
+
${A$}`}i(eg,"buildThinkingPreview");function L$(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.type==="user")return t;return 0}i(L$,"findActiveRoundStartIndex");function De(e,t,n,o,r){let s=P$(n,o);if(s.length===0){e.push({key:`${t}-0`,text:"",...r});return}s.forEach((a,c)=>{e.push({key:`${t}-${c}`,text:a,...r})})}i(De,"pushWrappedRows");function ic(e,t){e.push({key:t,text:" "})}i(ic,"pushBlankRow");function gt(e,t=0){return Math.max(20,e-t)}i(gt,"getBodyWidth");function O$(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,o)=>o===0?`input: ${n}`:n):[]}i(O$,"buildToolInputPreview");function D$(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(D$,"formatHarnessProfileShort");function N$(e,t,n,o,r,s=!1,a=!1){if(De(e,`${t}-tool-${n.id}-main`,`${dC(n.status)} ${rc({tool:n,count:o})}`,gt(r,2),{color:fC(n.status),indent:2,bold:n.status===P.Executing}),Qp(n).forEach((l,d)=>{let m=qp(l);De(e,`${t}-tool-${n.id}-explanation-${d}`,l,gt(r,4),{color:m,indent:4})}),s){let l=O$(n),d=a?l:l.slice(0,6);d.forEach((m,p)=>{De(e,`${t}-tool-${n.id}-input-${p}`,m,gt(r,4),{color:"dim",indent:4})}),!a&&l.length>d.length&&De(e,`${t}-tool-${n.id}-input-more`,`... (${l.length-d.length} more lines)`,gt(r,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)=>{De(e,`${t}-tool-${n.id}-output-${g}`,p,gt(r,4),{color:"dim",indent:4})});let m=l.length;!a&&m>d.length&&De(e,`${t}-tool-${n.id}-output-more`,`... (${m-d.length} more lines)`,gt(r,4),{color:"dim",indent:4})}}i(N$,"buildToolRows");function B$(e,t,n,o){let r=n.status===P.Executing,s=r?"":`${dC(n.status)} `;De(e,`${t}-tool-${n.id}-main`,`${s}${rc({tool:n,count:1})}`,gt(o,2),{color:fC(n.status),indent:2,bold:r,spinner:r}),Qp(n).forEach((c,l)=>{let d=qp(c);De(e,`${t}-tool-${n.id}-explanation-${l}`,c,gt(o,4),{color:d,indent:4})})}i(B$,"buildLiveToolRows");function mC(e){let{items:t,viewportWidth:n,isLoading:o=!1,maxLines:r=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:I,managedHarnessProfile:O,managedWorkerTitle:$,managedRound:D,managedMaxRounds:L,lastLiveActivityLabel:X,currentTodoActiveForm:v,showFullThinking:ie=!1,showDetailedTools:Te=!1,showAllContent:G=!1,showLiveProgressRows:q=!0}=e,M=[];for(let C of t)switch(C.type){case"user":De(M,`${C.id}-header`,`You [${sd(C.timestamp)}]`,n,{color:"primary",bold:!0,itemId:C.id}),De(M,`${C.id}-body`,id(C.text),gt(n,2),{color:"text",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"assistant":{let Z=G?C.text:C.compactText??C.text;De(M,`${C.id}-header`,`Assistant [${sd(C.timestamp)}]`,n,{color:"secondary",bold:!0,spinner:C.isStreaming,itemId:C.id}),De(M,`${C.id}-body`,Z,gt(n,2),{color:"text",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break}case"system":De(M,`${C.id}-header`,`System [${sd(C.timestamp)}]`,n,{color:"dim",bold:!0,itemId:C.id}),De(M,`${C.id}-body`,C.text,gt(n,2),{color:"dim",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"tool_group":De(M,`${C.id}-header`,`Tools [${sd(C.timestamp)}]`,n,{color:"accent",bold:!0,itemId:C.id}),od(C.tools).forEach(Z=>N$(M,C.id,Z.tool,Z.count,n,Te,G)),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"thinking":{let Z=G?eg(C.text,r,ie,G):C.compactText??eg(C.text,r,ie,G);De(M,`${C.id}-header`,"Thinking",n,{color:"thinking",italic:!0,itemId:C.id}),De(M,`${C.id}-body`,Z,gt(n,2),{color:"thinking",indent:2,italic:!0,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break}case"error":De(M,`${C.id}-header`,"\u2717 Error",n,{color:"error",bold:!0,itemId:C.id}),De(M,`${C.id}-body`,C.text,gt(n,2),{color:"error",indent:2,itemId:C.id}),M.push({key:`${C.id}-blank`,text:" ",itemId:C.id});break;case"info":De(M,`${C.id}-body`,`${C.icon??"\u2139"} ${G?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":De(M,`${C.id}-body`,`${C.icon??">"} ${G?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":De(M,`${C.id}-header`,"\u{1F4A1} Hint",n,{color:"hint",bold:!0,itemId:C.id}),De(M,`${C.id}-body`,C.text,gt(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(De(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)`:"";De(M,`iteration-${C.iteration}-thinking`,`\u{1F4AD} ${C.thinkingSummary}${Z}`,gt(n,1),{color:"thinking",indent:1,italic:!0})}if(C.response){let Z=C.response.slice(0,200);De(M,`iteration-${C.iteration}-response`,Z,gt(n,1),{color:"text",indent:1}),C.response.length>200&&De(M,`iteration-${C.iteration}-response-more`,`... (${C.response.length} chars total)`,gt(n,1),{color:"dim",indent:1})}C.toolsUsed.length>0&&De(M,`iteration-${C.iteration}-tools`,`* tools: ${C.toolsUsed.join(", ")}`,gt(n,1),{color:"accent",indent:1}),ic(M,`iteration-${C.iteration}-blank`)}),De(M,"iteration-current-header",`\u2500\u2500 Round ${y} (current) \u2500\u2500`,n,{color:"accent",bold:!0}),ic(M,"iteration-current-blank")),o&&c){let C=eg(c,r,ie,G);De(M,"thinking-stream-header","Thinking",n,{color:"thinking",italic:!0}),De(M,"thinking-stream-body",C,gt(n,2),{color:"thinking",indent:2,italic:!0}),ic(M,"thinking-stream-blank")}if(o){let C="Thinking",Z="",Re=D$(O),Ie=$$(X,$),Se=$??"Scout",ce=I==="routing"?`[${w?w.toUpperCase():"AMA"} Routing] `:I==="preflight"?`[${w?w.toUpperCase():"AMA"} ${Se}] `:I==="verifying"?`[${w?w.toUpperCase():"AMA"} Verifying] `:O?`[${w?w.toUpperCase():"AMA"} ${Re??O}${$?` - ${$}`:""}] `:"",Ne=m.filter(ve=>ve.status===P.Executing).length,ae=m.filter(ve=>ve.status===P.Success).length,Y=m.filter(ve=>ve.status===P.Error).length,Q=m.filter(ve=>ve.status===P.Cancelled).length,be=m.length>0&&(Ne>0||!l);if(T)C="Compacting";else if(I==="verifying")Z=ce,C="checking agent output";else if(be){let ve=[];if(Ne>0&&ve.push(`${Ne} running`),ae>0&&ve.push(`${ae} done`),Y>0&&ve.push(`${Y} error`),Q>0&&ve.push(`${Q} cancelled`),ve.length===0&&ve.push(`${m.length} tools`),De(M,"loading-tools-header",`${ce}[Tools] ${ve.join(", ")}`,n,{color:"primary",bold:!0,spinner:Ne>0}),m.forEach(lt=>{B$(M,"loading-tools",lt,n)}),ic(M,"loading-tools-blank"),Ne>0&&!l&&!q)return M}else if(v)Z=ce||"[Plan] ",C=v;else if(d)Z=ce||"[Tool] ",C=Ie?.startsWith("[Tools]")?Ie:rd(d,g,p);else if(s){Z=ce||"[Thinking] ";let ve=D&&L&&D>1?` round ${D}/${L}`:"";C=a>0?`${a} chars${ve}`:Ie?`${Ie}${ve}`:`processing${ve}`}else Ie&&(C=Ie);q&&De(M,"loading-indicator",`${Z}${C}...`,n,{color:"accent",spinner:!0})}if(l){let C=l.lastIndexOf(`
|
|
326
|
+
`),Z=C>=0?l.slice(0,C+1):"";Z.length>0&&(De(M,"streaming-header","Assistant",n,{color:"secondary",bold:!0}),De(M,"streaming-body",Z,gt(n,2),{color:"text",indent:2}),ic(M,"streaming-blank"))}return M}i(mC,"buildTranscriptRows");function H$(e,t,n=1e3,o=!1,r=!1){return gs(e,t,n,o,void 0,r)}i(H$,"buildStaticTranscriptSections");function gs(e,t,n=1e3,o=!1,r,s=!1){return e.map(a=>({key:a.id,rows:mC({items:[a],viewportWidth:t,maxLines:n,showAllContent:s,showDetailedTools:o||!!r?.has(a.id)})}))}i(gs,"buildHistoryItemTranscriptSections");function F$(e,t){return{key:e,rows:mC(t)}}i(F$,"buildDynamicTranscriptSection");function ad(e){let{items:t,viewportWidth:n,maxLines:o=1e3,showDetailedTools:r=!1,showAllContent:s=!1,windowed:a=!1}=e;if(a)return{staticSections:[],activeItems:t};let c=L$(t),l=t.slice(0,c),d=t.slice(c);return{staticSections:H$(l,n,o,r,s),activeItems:d}}i(ad,"buildTranscriptStaticPortion");function cd(e){let{activeItems:t,viewportWidth:n,maxLines:o=1e3,showDetailedTools:r=!1,showAllContent:s=!1,expandedItemKeys:a,...c}=e,l=gs(t,n,o,r,a,s),d=F$("active-pending",{...c,items:[],managedLiveEvents:[],lastLiveActivityLabel:c.lastLiveActivityLabel,viewportWidth:n,maxLines:o,showAllContent:s,showDetailedTools:r,expandedItemKeys:a}),m=d.rows.length>0?[d]:[];return{sections:l,previewSections:m}}i(cd,"buildTranscriptDynamicPortion");function ld(e,t){return{staticSections:e.staticSections,sections:t.sections,rows:Wr(t.sections),previewSections:t.previewSections,previewRows:Wr(t.previewSections)}}i(ld,"composeTranscriptRenderModel");function ud(e){let t=ad({items:e.items,viewportWidth:e.viewportWidth,maxLines:e.maxLines,showDetailedTools:e.showDetailedTools,showAllContent:e.showAllContent,windowed:e.windowed}),{items:n,...o}=e,r=cd({...o,activeItems:t.activeItems});return ld(t,r)}i(ud,"buildTranscriptRenderModel");function Wr(e){return e.flatMap(t=>t.rows)}i(Wr,"flattenTranscriptSections");function tg(e){let t=[...e.staticSections,...e.sections];return{staticSections:[],sections:t,rows:Wr(t),previewSections:[...e.previewSections],previewRows:Wr(e.previewSections)}}i(tg,"materializeTranscriptRenderModel");function pC(e,t={}){let{start:n,end:o,viewportTop:r,viewportHeight:s,viewportRows:a,scrollOffset:c=0,windowed:l=!1}=t;if(typeof r=="number"&&typeof s=="number"){let d=Math.max(0,r),m=Math.max(d,r+Math.max(0,s));return e.slice(d,m)}return typeof n=="number"&&typeof o=="number"?e.slice(Math.max(0,n),Math.max(0,o)):l?og(e,a,c):e}i(pC,"resolveVisibleTranscriptRows");var W$=200,U$=50,ng=30;function gC(e,t,n=W$,o=U$){let r=t.current,s=r?e.findIndex(l=>l.id===r.id):-1,a=s>=0?s:r?Math.min(r.idx,Math.max(0,e.length-n)):0;e.length-a>n+o&&(a=e.length-n);let c=e[a];return c&&(r?.id!==c.id||r.idx!==a)?t.current={id:c.id,idx:a}:!c&&r&&(t.current=null),a}i(gC,"computeTranscriptCapStart");function hC(e,t){if(t<=0||e.length===0)return[];let n=0,o=0;for(let r=e.length-1;r>=0;r--)if(e[r]?.type==="user"&&(n++,n>t)){o=r+1;break}return e.slice(o)}i(hC,"sliceHistoryToRecentRounds");function og(e,t,n=0){if(!t||t<=0)return e;let o=Math.max(0,n),r=Math.max(0,e.length-o),s=Math.max(0,r-t);return e.slice(s,r)}i(og,"getVisibleTranscriptRows");function yC(e,t,n){if(!t||!n||n<=0)return 0;let o=Wr(e),r=e.find(d=>d.key===t);if(!r||r.rows.length===0)return 0;let s=r.rows[0]?.key,a=o.findIndex(d=>d.key===s);if(a===-1)return 0;let c=Math.max(0,a-Math.floor(n/3)),l=Math.min(o.length,c+n);return Math.max(0,o.length-l)}i(yC,"resolveScrollOffsetForTranscriptItem");function xC(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(xC,"resolveTranscriptColor");var dd="__transcript_hidden_divider__";function wC(e,t){let n=e===1?"message":"messages";return{id:dd,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(wC,"buildTranscriptHiddenDivider");function rg(e){return e.id===dd}i(rg,"isTranscriptHiddenDivider");var SC=new Di(500);function j$(e){let t=zt(e),n=[],o=[],r=0,s=0;for(let a of t)n.push(r),o.push(s),r+=a.length,s+=Tm(a);return{graphemes:t,codeUnitOffsets:n,visualOffsets:o,length:t.length,displayWidth:s}}i(j$,"buildTranscriptTextMetrics");function sc(e){let t=SC.get(e);if(t)return t;let n=j$(e);return SC.set(e,n),n}i(sc,"getTranscriptTextMetrics");function Qo(e){return sc(e).length}i(Qo,"getTranscriptTextLength");function TC(e){return sc(e).displayWidth}i(TC,"getTranscriptTextDisplayWidth");function fd(e,t){let n=sc(e),o=Math.max(0,Math.min(n.length-1,t));return n.graphemes[o]??""}i(fd,"charAtTranscriptText");function hs(e,t,n){let o=sc(e),r=Math.max(0,Math.min(o.length,Math.floor(t))),s=typeof n=="number"?Math.max(r,Math.min(o.length,Math.floor(n))):o.length;return o.graphemes.slice(r,s).join("")}i(hs,"sliceTranscriptText");function CC(e,t){let n=sc(e),o=Math.max(0,Math.floor(t));if(o<=0||n.length===0)return 0;for(let r=0;r<n.length;r+=1){let s=n.visualOffsets[r]??0,a=r+1<n.length?n.visualOffsets[r+1]??n.displayWidth:n.displayWidth;if(o<a||o===s)return r}return n.length}i(CC,"resolveTranscriptTextIndexAtVisualColumn");function md(e){return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}i(md,"formatTimestamp");function G$(e,t){let n=e.split(`
|
|
327
|
+
`),o=n.slice(0,t),r=n.length>t;return{lines:o,hasMore:r}}i(G$,"truncateLines");function K$(e){switch(e){case P.Scheduled:return"\u25CB";case P.Validating:return"\u25D0";case P.AwaitingApproval:return"\u23F8";case P.Executing:return"\u25CF";case P.Success:return"\u2713";case P.Error:return"\u2717";case P.Cancelled:return"\u2298";default:return"?"}}i(K$,"getToolStatusIcon");function V$(e,t){switch(e){case P.Scheduled:case P.Validating:return t.colors.dim;case P.AwaitingApproval:return t.colors.accent;case P.Executing:return t.colors.primary;case P.Success:return t.colors.success;case P.Error:return t.colors.error;case P.Cancelled:return t.colors.dim;default:return t.colors.text}}i(V$,"getToolStatusColor");var z$=cn(({item:e,theme:t})=>{let n=ro(()=>id(e.text),[e.text]);return We(k,{flexDirection:"column",marginBottom:1,children:[We(k,{children:[de(b,{color:t.colors.primary,bold:!0,children:"You"}),We(b,{dimColor:!0,children:[" [",md(e.timestamp),"]"]})]}),de(k,{marginLeft:2,children:de(b,{color:t.colors.text,children:n})})]})}),X$=cn(({item:e,theme:t,maxLines:n})=>{let o=e.compactText??e.text,{lines:r,hasMore:s}=G$(o,n);return We(k,{flexDirection:"column",marginBottom:1,children:[We(k,{children:[de(b,{color:t.colors.secondary,bold:!0,children:"Assistant"}),e.isStreaming&&We(ig,{children:[de(b,{children:" "}),de(kn,{color:t.colors.accent})]}),We(b,{dimColor:!0,children:[" [",md(e.timestamp),"]"]})]}),We(k,{marginLeft:2,flexDirection:"column",children:[r.map((a,c)=>de(b,{color:t.colors.text,children:a||" "},c)),s&&We(b,{dimColor:!0,children:["... (",o.split(`
|
|
328
|
+
`).length-n," more lines)"]})]})]})}),Y$=cn(({item:e,theme:t})=>We(k,{flexDirection:"column",marginBottom:1,children:[We(k,{children:[de(b,{color:t.colors.dim,bold:!0,children:"System"}),We(b,{dimColor:!0,children:[" [",md(e.timestamp),"]"]})]}),de(k,{marginLeft:2,children:de(b,{dimColor:!0,children:e.text})})]})),q$=cn(({tool:e,count:t=1,theme:n})=>{let o=K$(e.status),r=V$(e.status,n);return We(k,{flexDirection:"column",marginLeft:2,children:[We(k,{children:[We(b,{color:r,children:[o," "]}),de(b,{color:n.colors.text,bold:!0,children:rc({tool:e,count:t})})]}),e.error&&de(k,{marginLeft:2,children:de(b,{color:n.colors.error,children:e.error})})]})}),Q$=cn(({item:e,theme:t})=>{let n=od(e.tools);return We(k,{flexDirection:"column",marginBottom:1,children:[We(k,{children:[de(b,{color:t.colors.accent,bold:!0,children:"Tools"}),We(b,{dimColor:!0,children:[" [",md(e.timestamp),"]"]})]}),n.map(o=>de(q$,{tool:o.tool,count:o.count,theme:t},`${o.tool.id}-${o.count}`))]})}),J$=cn(({item:e,theme:t})=>We(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})})]})),Z$=cn(({item:e,theme:t})=>We(k,{flexDirection:"column",marginBottom:1,children:[de(k,{children:We(b,{color:t.colors.error,bold:!0,children:["\u2717"," Error"]})}),de(k,{marginLeft:2,children:de(b,{color:t.colors.error,children:e.text})})]})),eP=cn(({item:e,theme:t})=>de(k,{flexDirection:"column",marginBottom:1,children:We(b,{color:t.colors.text,children:[de(b,{color:t.colors.accent,bold:!0,children:e.icon??">"}),de(b,{children:" "}),e.compactText??e.text]})})),tP=cn(({item:e,theme:t})=>de(k,{flexDirection:"column",marginBottom:e.tightSpacing?0:1,children:We(b,{color:t.colors.info,children:[We(b,{bold:!0,children:[e.icon??"\u2139"," "]}),e.compactText??e.text]})})),nP=cn(({item:e,theme:t})=>We(k,{flexDirection:"column",marginBottom:1,children:[de(k,{children:We(b,{color:t.colors.hint,bold:!0,children:["\u{1F4A1}"," Hint"]})}),de(k,{marginLeft:2,children:de(b,{dimColor:!0,children:e.text})})]})),oP=cn(({item:e,theme:t,maxLines:n=1e3})=>{let o=ro(()=>ne("dark"),[]),r=t??o;switch(e.type){case"user":return de(z$,{item:e,theme:r});case"assistant":return de(X$,{item:e,theme:r,maxLines:n});case"system":return de(Y$,{item:e,theme:r});case"tool_group":return de(Q$,{item:e,theme:r});case"thinking":return de(J$,{item:e,theme:r});case"error":return de(Z$,{item:e,theme:r});case"event":return de(eP,{item:e,theme:r});case"info":return de(tP,{item:e,theme:r});case"hint":return de(nP,{item:e,theme:r});default:return de(k,{children:de(b,{dimColor:!0,children:"Unknown item type"})})}});function rP(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,o=t.row;if(n!==o){if(n.key!==o.key||n.text!==o.text||n.color!==o.color||n.bold!==o.bold||n.italic!==o.italic||n.indent!==o.indent||n.spinner!==o.spinner||n.itemId!==o.itemId)return!1}let r=e.selectionRange,s=t.selectionRange;return r===s?!0:!r||!s?!1:r.start===s.start&&r.end===s.end}i(rP,"areTranscriptRowPropsEqual");var vC=cn(({row:e,theme:t,animateSpinners:n=!0,selectedItem:o=!1,selectionRange:r})=>{let s=xC(t,e.color),a=e.text===" "?"":e.text,c=a||" ",l=r&&a?hs(a,r.start,r.end):"",d=r&&a?hs(a,0,r.start):a,m=r&&a?hs(a,r.end):"",p=o&&!r,g=!p&&e.color==="dim",x={bold:e.bold||p,italic:e.italic,dimColor:g};return We(k,{marginLeft:e.indent??0,children:[e.spinner&&n&&We(ig,{children:[de(kn,{color:t.colors.accent,theme:t}),de(b,{children:" "})]}),de(b,{color:p?t.colors.accent:s,...x,children:r&&a?We(ig,{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})]})},rP),iP=cn(({section:e,theme:t,animateSpinners:n=!0})=>de(k,{flexDirection:"column",children:e.rows.map(o=>de(vC,{row:o,theme:t,animateSpinners:n},o.key))})),Ur=i(({items:e,isLoading:t=!1,maxLines:n=1e3,isThinking:o=!1,thinkingCharCount:r=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:I,managedRound:O,managedMaxRounds:$,managedGlobalWorkBudget:D,managedBudgetUsage:L,managedBudgetApprovalRequired:X,lastLiveActivityLabel:v,viewportRows:ie,viewportWidth:Te,scrollOffset:G=0,animateSpinners:q=!0,windowed:M=!1,showFullThinking:C=!1,showDetailedTools:Z=!1,showAllContent:Re=!1,showLiveProgressRows:Ie=!0,selectedItemId:Se,expandedItemKeys:ce,onMetricsChange:Ne,onVisibleRowsChange:ae,rendererWindow:Y,selectedTextRanges:Q,transcriptModel:be,visibleRowsOverride:ve})=>{let lt=ro(()=>ne("dark"),[]),{stdout:Ee}=Jn(),je=Te??Ee?.columns??80,xe=ro(()=>be??ud({items:e,viewportWidth:je,isLoading:t,maxLines:n,isThinking:o,thinkingCharCount:r,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:I,managedRound:O,managedMaxRounds:$,managedGlobalWorkBudget:D,managedBudgetUsage:L,managedBudgetApprovalRequired:X,lastLiveActivityLabel:v,windowed:M,showFullThinking:C,showDetailedTools:Z,showAllContent:Re,showLiveProgressRows:Ie,expandedItemKeys:ce}),[be,e,je,t,n,o,r,s,a,c,l,d,m,p,g,x,y,T,w,I,O,$,D,L,X,v,M,C,Z,Re,Ie,ce]),Rt=xe.staticSections,Qe=xe.rows,ee=xe.previewRows,A=ro(()=>[...Qe,...ee],[ee,Qe]),F=!(A.length>0)&&e.length===0&&!t,J=ro(()=>M||Y||ve?A:Qe,[A,Y,Qe,ve,M]),Be=ro(()=>ve||pC(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:G,windowed:M}),[Y,G,ie,ve,M,J]),tt=ro(()=>ve||M||Y?Be:A,[A,Y,Be,ve,M]),ke=ro(()=>A,[A]),Oe=Y?Math.max(0,Y.viewportHeight):ie;return bC(()=>{Ne?.({scrollHeight:A.length,viewportHeight:Y?Math.max(0,Y.viewportHeight):Oe??A.length})},[A.length,Oe,Ne,Y]),bC(()=>{ae?.({rows:tt,allRows:ke})},[ke,ae,tt]),F?de(k,{paddingY:1,children:de(b,{dimColor:!0,children:"No messages yet. Start typing to begin."})}):We(k,{flexDirection:"column",children:[!M&&Rt.length>0&&de(Qi,{items:Rt,children:i(Vt=>de(iP,{section:Vt,theme:lt,animateSpinners:q},Vt.key),"children")}),tt.map(Vt=>de(vC,{row:Vt,theme:lt,animateSpinners:q,selectedItem:Se?Vt.key.startsWith(`${Se}-`):!1,selectionRange:Q?.get(Vt.key)},Vt.key))]})},"MessageList");var sP=i(({role:e,content:t})=>{let n=ro(()=>ne("dark"),[]),o={user:n.colors.primary,assistant:n.colors.secondary,system:n.colors.dim}[e];return We(k,{flexDirection:"column",marginBottom:1,children:[de(b,{color:o,bold:!0,children:e==="user"?">":e==="assistant"?"<":"#"}),de(b,{children:t})]})},"SimpleMessageDisplay");import{jsx as ag,jsxs as yd}from"react/jsx-runtime";import vP,{useMemo as cg}from"react";var aP="\u{1F504}",cP="\u2588",lP="\u2592",uP="\u2192",dP=" \xB7 ";function fP(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(fP,"formatReasoningModeShort");function mP(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(mP,"formatReasoningCapabilityShort");function pP(e){switch(e){case"off":return"dim";case"quick":return"green";case"balanced":return"yellow";case"deep":return"magenta";default:return"cyan"}}i(pP,"getReasoningColor");function IC(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}i(IC,"formatTokenCount");function gP(e){let t=Math.min(10,Math.max(0,Math.round(e/10))),n=10-t;return`${cP.repeat(t)}${lP.repeat(n)}`}i(gP,"createMiniProgressBar");function hP(e,t,n){if(t===0)return"green";let o=e/t*100,r=n*(2/3);return o>=n?"red":o>=r?"yellow":"green"}i(hP,"getContextColor");function yP(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(yP,"getPermissionModeColor");function xP(e,t){let n=ts(e);return!(e==="auto"||e==="auto-in-project")||!t?n:`${n}${t==="llm"?"[LLM]":"[RULES]"}`}i(xP,"buildPermissionModeText");function wP(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(wP,"formatToolAction");function SP(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(SP,"formatHarnessProfileShort");function pd(e,t){return t&&t>0?`${e} (${t} chars)`:e}i(pd,"formatThinkingStatus");function gd(e,t,n){let o=wP(e);return n?`${o} (${n}...)`:t&&t>0?`${o} (${t} chars)`:o}i(gd,"formatToolStatus");function sg({activeToolCount:e,currentTool:t,isThinkingActive:n,thinkingCharCount:o,isCompacting:r,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(r)return"Compacting";if(c==="routing")return g?`Routing - ${g}`:t?`Routing - ${gd(t,s,a)}`:n?pd("Routing",o):"Routing";if(c==="preflight"){let x=d??"Scout";return g?`${x} - ${g}`:t?`${x} - ${gd(t,s,a)}`:n?pd(x,o):x}if(l){let y=`${SP(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} - ${gd(t,s,a)}`:n?pd(y,o):y}if(g)return g;if(t)return gd(t,s,a);if(n)return pd("Thinking",o)}i(sg,"buildBusyStatusText");function TP({agentMode:e,managedPhase:t,managedHarnessProfile:n,managedRound:o,managedMaxRounds:r,managedGlobalWorkBudget:s,managedBudgetUsage:a,currentIteration:c,maxIter:l}){let d=[];return t==="routing"||t==="preflight"||(n&&o&&r&&o>1&&d.push({label:"Round",current:o,max:r}),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(TP,"resolveIterationSegments");function CP(e){if(e.length!==0)return`${aP} ${e.map(t=>`${t.label} ${t.current}/${t.max}`).join(dP)}`}i(CP,"formatLabeledIterationStatus");function bP(e){let{sessionId:t,permissionMode:n,agentMode:o,provider:r,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:I,maxIter:O,contextUsage:$,showBusyStatus:D=!0,managedPhase:L,managedHarnessProfile:X,managedWorkerTitle:v,managedRound:ie,managedMaxRounds:Te,managedGlobalWorkBudget:G,managedBudgetUsage:q,managedIdleWaiting:M,managedIdleWaitingPendingCount:C}=e,Z=[{id:"agent-mode",text:`KodaX - ${o.toUpperCase()}`,color:"primary",bold:!0},{id:"permission-mode",text:xP(n,e.autoModeEngine),color:yP(n)}],Re=fP(g),Ie=mP(x);Z.push({id:"reasoning-mode",text:x?`${Re}/${Ie}`:Re,color:pP(g)});let Se=TP({agentMode:o,managedPhase:L,managedHarnessProfile:X,managedRound:ie,managedMaxRounds:Te,managedGlobalWorkBudget:G,managedBudgetUsage:q,currentIteration:I,maxIter:O}),ce=CP(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 Ne=D?sg({activeToolCount:l,currentTool:c,isThinkingActive:m,thinkingCharCount:p,isCompacting:y,toolInputCharCount:T,toolInputContent:w,managedPhase:L,managedHarnessProfile:X,managedWorkerTitle:v,managedIdleWaiting:M,managedIdleWaitingPendingCount:C}):void 0;if(Ne&&Z.push({id:"busy-status",text:Ne,color:"dim"}),Z.push({id:"provider-model",text:`${r}/${s}`,color:"secondary"}),$&&$.contextWindow!==0){let ae=Math.round($.currentTokens/$.contextWindow*100),Y=IC($.currentTokens),Q=IC($.contextWindow),be=gP(ae);Z.push({id:"context-usage",text:`${Y}/${Q} ${be} ${ae}%`,color:hP($.currentTokens,$.contextWindow,$.triggerPercent)})}return a&&Z.push({id:"token-usage",text:`${a.input}${uP}${a.output} (${a.total})`,color:"dim"}),Z}i(bP,"buildStatusBarSegments");function hd(e){let t=bP(e);return{text:t.map(n=>n.text).join(" | "),segments:t}}i(hd,"buildStatusBarViewModel");function IP(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(IP,"resolveViewModelSegmentColor");var ys=i(({viewModel:e,...t})=>{let n=cg(()=>ne("dark"),[]),o=cg(()=>e??hd(t),[t,e]);return ag(k,{paddingX:1,children:o.segments.map((r,s)=>yd(vP.Fragment,{children:[ag(b,{color:IP(r,n),bold:r.bold,children:r.text}),s<o.segments.length-1?ag(b,{dimColor:!0,children:" | "}):null]},r.id))})},"StatusBar"),kP=i(({permissionMode:e,provider:t,model:n})=>{let o=cg(()=>ne("dark"),[]);return yd(k,{children:[yd(b,{color:o.colors.primary,bold:!0,children:["[",e,"]"]}),yd(b,{dimColor:!0,children:[" ",t,"/",n]})]})},"SimpleStatusBar");import{jsx as Jo,jsxs as Sd}from"react/jsx-runtime";import{useState as lg,useCallback as xd,useMemo as kC}from"react";function wd(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}i(wd,"generateId");function RP(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(RP,"messageToHistoryItem");var EP=i(({model:e,provider:t,onSubmit:n,permissionMode:o="accept-edits",agentMode:r="ama"})=>{let{stdout:s}=Jn(),a=kC(()=>ne("dark"),[]),[c,l]=lg({messages:[],isLoading:!1,sessionId:wd()}),[d,m]=lg(null),[p,g]=lg(),x=xd(async I=>{if(!I.trim())return;let O={id:wd(),role:"user",content:I,timestamp:Date.now()};l($=>({...$,messages:[...$.messages,O],isLoading:!0}));try{await n(I)}catch($){let D={id:wd(),role:"system",content:`Error: ${$ instanceof Error?$.message:"Unknown error"}`,timestamp:Date.now()};l(L=>({...L,messages:[...L.messages,D],isLoading:!1}))}finally{l($=>({...$,isLoading:!1}))}},[n]),y=xd((I,O)=>{let $={id:wd(),role:I,content:O,timestamp:Date.now()};l(D=>({...D,messages:[...D.messages,$]}))},[]),T=xd((I,O)=>{m({input:I,output:O,total:I+O})},[]),w=xd(I=>{g(I)},[]);return Sd(k,{flexDirection:"column",children:[Jo(k,{flexGrow:1,flexDirection:"column",overflow:"hidden",children:Jo(Ur,{items:c.messages.map(RP),isLoading:c.isLoading})}),Jo(k,{flexShrink:0,children:Jo(fs,{onSubmit:i(I=>x(I.fullText),"onSubmit"),prompt:">",focus:!c.isLoading})}),Jo(k,{flexShrink:0,children:Jo(ys,{sessionId:c.sessionId,permissionMode:o,agentMode:r,provider:t,model:e,tokenUsage:d??void 0,currentTool:p})})]})},"App"),MP=i(({model:e,provider:t,onInput:n})=>{let o=kC(()=>ne("dark"),[]);return Sd(k,{flexDirection:"column",children:[Sd(k,{marginBottom:1,children:[Jo(b,{color:o.colors.primary,bold:!0,children:"KodaX CLI"}),Sd(b,{dimColor:!0,children:[" ","- ",t,"/",e]})]}),Jo(fs,{onSubmit:i(r=>n(r.fullText),"onSubmit"),placeholder:"Type a message...",prompt:">"})]})},"SimpleApp");import{jsx as AP}from"react/jsx-runtime";var ug=i(({top:e,topRows:t=0,transcript:n,renderTranscriptWindow:o,footer:r,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})=>AP(tp,{width:l,top:e,topRows:t,stickyHeader:a,jumpToLatest:c,scrollable:n,renderScrollableWindow:o,overlay:s,bottom:r,scrollTop:d,scrollHeight:m,viewportHeight:p,stickyScroll:g,scrollRef:x,onScrollTopChange:y,onStickyChange:T,onWindowChange:w}),"FullscreenTranscriptLayout");import{jsx as RC}from"react/jsx-runtime";function xs({copyMessage:e=!1,copyToolInput:t=!1,copyOnSelect:n=!1,toggleDetail:o=!1,selectionNavigation:r=!1,matchNavigation:s=!1,dismissAction:a}){let c=[];return r&&c.push("\u2190/\u2192 browse"),e&&c.push("C copy"),t&&c.push("I tool input"),n&&c.push("Mouse select copies"),o&&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(xs,"buildMessageActionsText");var dg=i(({copyMessage:e=!1,copyToolInput:t=!1,copyOnSelect:n=!1,toggleDetail:o=!1,selectionNavigation:r=!1,matchNavigation:s=!1,dismissAction:a})=>{let c=ne("dark"),l=xs({copyMessage:e,copyToolInput:t,copyOnSelect:n,toggleDetail:o,selectionNavigation:r,matchNavigation:s,dismissAction:a});return l?RC(k,{paddingX:1,children:RC(b,{color:c.colors.dim,children:l})}):null},"MessageActions");import{jsx as EC}from"react/jsx-runtime";function fg({itemSummary:e,itemKind:t,position:n,detailState:o="compact"}){if(!e||!n||n.total<=0)return;let r=o==="expanded"?"expanded":"compact",s=t?`${t}: `:"";return`Selected item ${n.current}/${n.total}: ${s}${e} | ${r}`}i(fg,"buildMessageSelectorText");var _P=i(({itemSummary:e,itemKind:t,position:n,detailState:o="compact"})=>{let r=ne("dark"),s=fg({itemSummary:e,itemKind:t,position:n,detailState:o});return s?EC(k,{paddingX:1,children:EC(b,{color:r.colors.dim,children:s})}):null},"MessageSelector");import{jsx as ws,jsxs as $P}from"react/jsx-runtime";import{useMemo as MC}from"react";function Td(e,t){return Math.max(1,Xt(e.length>0?e.split(`
|
|
329
|
+
`):[""],Math.max(1,t),0,0).visualLines.length)}i(Td,"countWrappedRows");var mg=i(({browse:e,selection:t,search:n,chromeMode:o="inline",...r})=>{let s=o==="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,I=n?.matches?.length??0,O=n?.surface,$=r.viewportWidth??80,D=Math.max(1,$-2),L=n?.query?.trim()?"close-search":a||p||g||y||T?"clear":void 0,X=fg({itemSummary:a,itemKind:l,position:c,detailState:d}),v=MC(()=>xs({copyMessage:p,copyToolInput:g,copyOnSelect:x,toggleDetail:y,selectionNavigation:T,matchNavigation:!!w&&I>0,dismissAction:L}),[p,g,T,y,L,I,w,x]),ie=MC(()=>{if(!s)return 0;let G=0;return e?.hintText&&(G+=Td(e.hintText,D)),X&&(G+=Td(X,D)),v&&(G+=Td(v,D)),w&&(G+=Td(w,D)),O&&(G+=1),G},[v,e?.hintText,D,s,w,O,X]),Te=typeof r.viewportRows=="number"?Math.max(1,r.viewportRows-ie):r.viewportRows;return $P(k,{flexDirection:"column",flexGrow:r.windowed?0:1,children:[s&&e?.hintText?ws(k,{paddingX:1,children:ws(b,{dimColor:!0,children:e.hintText})}):null,null,s&&(p||g||x||y||T||I>0)?ws(dg,{copyMessage:p,copyToolInput:g,copyOnSelect:x,toggleDetail:y,selectionNavigation:T,matchNavigation:!!w&&I>0,dismissAction:L}):null,s&&w?ws(k,{paddingX:1,children:ws(b,{dimColor:!0,children:w})}):null,s?O:null,ws(Ur,{...r,viewportRows:Te})]})},"TranscriptViewport");import{jsx as AC}from"react/jsx-runtime";var pg=i(e=>AC(k,{flexDirection:"column",children:AC(fs,{...e})}),"PromptComposer");import{jsx as jr,jsxs as Cd}from"react/jsx-runtime";import _C from"react";var $C=" \xB7 ",bd=i(({items:e=[]})=>{let t=e.filter(o=>o.label.trim().length>0),n=ne("dark");return t.length===0?null:jr(k,{flexGrow:1,children:t.map((o,r)=>Cd(_C.Fragment,{children:[jr(b,{color:o.accent?n.colors.accent:n.colors.dim,bold:o.accent,children:o.label}),r<t.length-1?jr(b,{dimColor:!0,children:$C}):null]},o.id))})},"PromptFooterLeftSide"),vd=i(({items:e=[]})=>{let t=e.filter(o=>o.label.trim().length>0),n=ne("dark");return t.length===0?null:jr(k,{justifyContent:"flex-end",children:t.map((o,r)=>Cd(_C.Fragment,{children:[jr(b,{color:o.accent?n.colors.primary:n.colors.dim,bold:o.accent,children:o.label}),r<t.length-1?jr(b,{dimColor:!0,children:$C}):null]},o.id))})},"PromptFooterRightSide"),Id=i(({left:e,right:t,queued:n,stashNotice:o,notifications:r,inlineNotices:s,activityBar:a,todoSurface:c,composer:l,inlineSuggestions:d,helpSurface:m,taskBar:p,statusLine:g,inlineDialogs:x})=>Cd(k,{flexDirection:"column",children:[e||t?Cd(k,{paddingX:1,children:[jr(k,{flexGrow:1,children:e}),t]}):null,n,o,r,s,a,c,l,d,x,m,p,g]}),"PromptFooter");import{jsx as gg,jsxs as PC}from"react/jsx-runtime";var hg=i(({sections:e,title:t="Help"})=>{let n=ne("dark"),o=e.filter(r=>r.items.length>0);return o.length===0?null:PC(k,{flexDirection:"column",borderStyle:"round",borderColor:n.colors.accent,paddingX:1,marginTop:1,children:[gg(b,{color:n.colors.accent,bold:!0,children:t}),o.map(r=>PC(k,{flexDirection:"column",children:[gg(b,{color:n.colors.primary,bold:!0,children:r.title}),gg(b,{dimColor:!0,children:r.items.map(s=>s.label).join(" | ")})]},r.id))]})},"PromptHelpMenu");import{jsx as LC}from"react/jsx-runtime";import{createContext as OC,useContext as DC,useReducer as PP,useCallback as Ht,useMemo as LP}from"react";var OP=150;function kd(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}i(kd,"generateId");function yg(e){return{...e,id:kd(),timestamp:Date.now()}}i(yg,"createHistoryItem");function xg(e){return{...e,id:kd(),startTime:Date.now()}}i(xg,"createToolCall");function DP(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<=OP)return{...e,history:n};let o=0,r=0;for(let a=n.length-1;a>=0;a--)if(n[a]?.type==="user"&&(o++,o>50)){r=a;break}let s=r>0?n.slice(r):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{...rp,sessionId:e.sessionId};default:return e}}i(DP,"uiReducer");var NC=OC(null),BC=OC(null);function Rd({children:e,initialState:t}){let[n,o]=PP(DP,{...rp,...t}),r=Ht(L=>{o({type:"SET_STREAMING_STATE",payload:L})},[]),s=Ht(L=>{o({type:"APPEND_TO_RESPONSE",payload:L})},[]),a=Ht(()=>{o({type:"CLEAR_RESPONSE"})},[]),c=Ht(L=>{let X=yg(L);o({type:"ADD_HISTORY_ITEM",payload:X})},[]),l=Ht((L,X)=>{o({type:"UPDATE_HISTORY_ITEM",payload:{id:L,updates:X}})},[]),d=Ht(()=>{o({type:"CLEAR_HISTORY"})},[]),m=Ht(L=>{let X=xg(L);return o({type:"ADD_TOOL_CALL",payload:X}),X.id},[]),p=Ht((L,X)=>{o({type:"UPDATE_TOOL_CALL",payload:{id:L,updates:X}})},[]),g=Ht(()=>{o({type:"CLEAR_TOOL_CALLS"})},[]),x=Ht(L=>{o({type:"SET_SESSION_ID",payload:L})},[]),y=Ht(L=>{o({type:"SET_MODE",payload:L})},[]),T=Ht(L=>{o({type:"SET_PROVIDER",payload:L})},[]),w=Ht(L=>{o({type:"SET_MODEL",payload:L})},[]),I=Ht(L=>{o({type:"SET_TOKEN_USAGE",payload:L})},[]),O=Ht(L=>{o({type:"SET_ERROR",payload:L})},[]),$=Ht(L=>{o({type:"SET_LOADING",payload:L})},[]),D=LP(()=>({setStreamingState:r,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:I,setError:O,setLoading:$}),[r,s,a,c,l,d,m,p,g,x,y,T,w,I,O,$]);return LC(NC.Provider,{value:n,children:LC(BC.Provider,{value:D,children:e})})}i(Rd,"UIStateProvider");function ac(){let e=DC(NC);if(!e)throw new Error("useUIState must be used within a UIStateProvider");return e}i(ac,"useUIState");function cc(){let e=DC(BC);if(!e)throw new Error("useUIActions must be used within a UIStateProvider");return e}i(cc,"useUIActions");function HC(){let e=ac(),t=cc();return{state:e,actions:t}}i(HC,"useUI");function wg(){return ne()}i(wg,"useTheme");import{jsxs as Zo,jsx as Ed,Fragment as NP}from"react/jsx-runtime";import{useMemo as BP}from"react";var HP=80,FP=7,WP={command:">",file:"\u{1F4C4}",history:"\u23F1",argument:"\u2022",snippet:"\u25C7",skill:"\u2605"};function UP(e,t,n){if(t<=n)return{start:0,end:t};let o=Math.floor(n/2),r=e-o,s=r+n;return r<0?(r=0,s=n):s>t&&(s=t,r=t-n),{start:r,end:s}}i(UP,"getVisibleRange");function jP({suggestion:e,isSelected:t,width:n}){let o=wg(),r=e.icon||e.type&&WP[e.type]||"",s=r?qn(r)+1:0,a=qn(e.displayText||e.text),c=e.description?qn(e.description):0,l=Math.min(a,n-s-2),d=n-s-l-3,m=Math.max(0,d),p=Sa(e.displayText||e.text,l),g=e.description?Sa(e.description,m):"";return Zo(k,{children:[r&&Zo(b,{color:t?o.colors.accent:o.colors.dim,children:[r," "]}),Ed(b,{color:t?o.colors.primary:o.colors.text,bold:t,children:p}),g&&Zo(NP,{children:[Ed(b,{children:" "}),Ed(b,{color:o.colors.dim,children:Sa(e.description||"",m)})]}),t&&Zo(b,{color:o.colors.accent,children:[" ","\u25C0"]})]})}i(jP,"SuggestionItem");function Md({suggestions:e,selectedIndex:t,visible:n,maxVisible:o=FP,width:r=HP,showCount:s=!1}){let a=wg();if(!n||e.length===0)return null;let{start:c,end:l}=BP(()=>UP(t,e.length,o),[t,e.length,o]),d=e.slice(c,l);return Zo(k,{flexDirection:"column",marginLeft:2,children:[c>0&&Zo(b,{color:a.colors.dim,children:[" ","\u25B2 ",c," more..."]}),d.map((m,p)=>{let x=c+p===t;return Ed(jP,{suggestion:m,isSelected:x,width:r},m.id)}),l<e.length&&Zo(b,{color:a.colors.dim,children:[" ","\u25BC ",e.length-l," more..."]}),s&&Zo(b,{color:a.colors.dim,children:[t+1,"/",e.length]})]})}i(Md,"SuggestionsDisplay");import{jsx as Ss,jsxs as GP}from"react/jsx-runtime";var Sg=i(({reserveSpace:e,width:t,hidden:n=!1,mode:o="inline"})=>{let r=Hr(),s=ne("dark");if(n)return null;if(!r)return e?Ss(k,{height:8}):null;let{state:a,suggestions:c}=r;return a.visible&&c.length>0?o==="overlay"?GP(k,{flexDirection:"column",borderStyle:"round",borderColor:s.colors.accent,paddingX:1,marginTop:1,children:[Ss(b,{color:s.colors.accent,bold:!0,children:"Suggestions"}),Ss(Md,{suggestions:c,selectedIndex:a.selectedIndex,visible:a.visible,maxVisible:7,width:Math.max(20,t-6)})]}):Ss(k,{height:8,children:Ss(Md,{suggestions:c,selectedIndex:a.selectedIndex,visible:a.visible,maxVisible:7,width:Math.max(20,t-2)})}):e?Ss(k,{height:8}):null},"PromptSuggestionsSurface");import{jsxs as Nn,jsx as Rn,Fragment as Tg}from"react/jsx-runtime";import KP,{useEffect as VP,useState as zP}from"react";var Ts=15,FC=Math.max(1,Ts-2),Cg=i(({confirm:e,request:t})=>e?Nn(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,marginTop:1,width:"100%",children:[Nn(b,{color:"yellow",bold:!0,children:[te("dialog.confirm")," ",e.prompt]}),e.planContent?Rn(XP,{content:e.planContent}):null,e.instruction?Rn(b,{dimColor:!0,children:e.instruction}):null]}):t?Nn(k,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,marginTop:1,width:"100%",children:[t.kind==="select"?Nn(Tg,{children:[Nn(b,{color:"cyan",bold:!0,children:[te("dialog.select")," ",t.title]}),(()=>{let n=t.options??[],o=t.visibleSelectOptions??5,r=t.focusedIndex??0,s=n.length,a=0;if(s>o){let d=Math.floor(o/2);a=Math.max(0,Math.min(r-d,s-o))}let c=a,l=Math.max(0,s-a-o);return Nn(Tg,{children:[c>0?Rn(b,{dimColor:!0,children:te("select.more_above",{count:c})}):null,n.slice(a,a+o).map((d,m)=>{let p=a+m,g=p===r,x=t.selectedIndices?.includes(p)??!1,y=g?"\u276F ":" ",T=x?" \u2713":"",w=d.description?` - ${d.description}`:"";return Rn(b,{color:g?"cyan":void 0,dimColor:!g,children:`${y}${d.label}${w}${T}`},`${d.value}-${p}`)}),l>0?Rn(b,{dimColor:!0,children:te("select.more_below",{count:l})}):null]})})(),Rn(b,{dimColor:!0,children:t.multiSelect?te("select.multiselect_hint"):te("select.navigate_hint")})]}):Nn(Tg,{children:[Nn(b,{color:"cyan",bold:!0,children:[te("dialog.input")," ",t.prompt]}),t.defaultValue!==void 0?Rn(b,{dimColor:!0,children:`${te("input.default")} ${t.defaultValue}`}):null,Rn(b,{dimColor:!0,children:`${te("input.value")} ${t.buffer||te("input.type_response")}`}),Rn(b,{dimColor:!0,children:te("select.confirm_hint")})]}),t.error?Rn(b,{color:"red",children:t.error}):null]}):null,"DialogSurface"),XP=i(({content:e})=>{let t=KP.useMemo(()=>e.split(`
|
|
330
|
+
`),[e]),n=t.length,o=n>Ts,[r,s]=zP(0);VP(()=>{s(d=>{let m=Math.max(0,n-Ts);return d>m?m:d})},[n]),yu((d,m)=>{if(!o)return;let p=Math.max(0,n-Ts);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-FC)):m.pageDown&&s(g=>Math.min(p,g+FC))},{isActive:!0});let a=t.slice(r,r+Ts),c=r,l=Math.max(0,n-r-Ts);return Nn(k,{flexDirection:"column",marginTop:1,children:[o&&c>0?Nn(b,{dimColor:!0,children:["\u2026 ",c," more line",c===1?"":"s"," above"]}):null,a.map((d,m)=>Rn(b,{children:d},`plan-line-${r+m}`)),o&&l>0?Nn(b,{dimColor:!0,children:["\u2026 ",l," more line",l===1?"":"s"," below"]}):null,o?Rn(b,{dimColor:!0,children:"PgUp/PgDn/\u2191\u2193 to scroll"}):null]})},"PlanScrollPanel");import{jsxs as lc,jsx as YP}from"react/jsx-runtime";function WC(e){let t=e.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}i(WC,"normalizePendingPreview");function UC(e){if(e.length===0)return;let t=WC(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(UC,"formatPendingInputsSummary");function bg(e){if(e.length===0)return[];let t=e.length;return e.map((n,o)=>({index:o+1,total:t,preview:WC(n)}))}i(bg,"formatPendingInputsLines");function jC(e){let t=bg(e);return t.length===0?void 0:[...t.map(r=>`\u23F3 [${r.index}/${r.total}] ${r.preview}`)," \u2191 pull all into editor \xB7 Esc drops latest"].join(`
|
|
331
|
+
`)}i(jC,"formatPendingInputsBudgetText");var vg=i(({pendingInputs:e})=>{let t=bg(e);if(t.length===0)return null;let n=ne("dark");return lc(k,{flexDirection:"column",children:[t.map(o=>lc(k,{children:[lc(b,{color:n.colors.hint,children:["\u23F3"," "]}),lc(b,{color:n.colors.dim,children:["[",o.index,"/",o.total,"] ",o.preview]})]},o.index)),YP(k,{children:lc(b,{color:n.colors.dim,children:[" ","\u2191 pull all into editor \xB7 Esc drops latest"]})})]})},"QueuedCommandsSurface");import{jsx as GC}from"react/jsx-runtime";function qP(e,t){switch(e){case"warning":return t.warning;case"accent":return t.accent;default:return t.dim}}i(qP,"resolveNotificationColor");var Ad=i(({notifications:e})=>{let t=e.filter(o=>o.text.trim().length>0),n=ne("dark");return t.length===0?null:GC(k,{flexDirection:"column",paddingX:1,children:t.map(o=>GC(b,{color:qP(o.tone,n.colors),children:o.text},o.id))})},"NotificationsSurface");import{jsx as KC}from"react/jsx-runtime";var Ig=i(({notices:e})=>{let t=e.filter(o=>o.trim().length>0);if(t.length===0)return null;let n=ne("dark");return KC(k,{flexDirection:"column",paddingX:1,children:t.map((o,r)=>KC(b,{color:n.colors.dim,children:o},`${o}-${r}`))})},"StatusNoticesSurface");import{jsxs as VC,jsx as QP}from"react/jsx-runtime";var _d=i(({text:e})=>{let t=e?.trim();if(!t)return null;let n=ne("dark");return VC(k,{paddingX:1,children:[VC(b,{color:n.colors.hint,children:["\u22EF"," "]}),QP(b,{color:n.colors.dim,children:t})]})},"StashNotice");import{jsx as Gr,jsxs as JP}from"react/jsx-runtime";function zC({text:e,accent:t=!1,selected:n=!1}){let o=ne("dark");return Gr(k,{marginRight:1,children:Gr(b,{color:t?o.colors.accent:o.colors.primary,bold:n||t,children:`[ ${e} ]`})})}i(zC,"Pill");var $d=i(({items:e,overflowLabel:t,ctaHint:n,showSpinner:o=!1})=>{let r=e.filter(s=>s.label.trim().length>0);return r.length===0&&!t&&!n&&!o?null:JP(k,{flexDirection:"row",paddingX:1,children:[o?Gr(k,{marginRight:1,children:Gr(kn,{})}):null,r.map(s=>Gr(zC,{text:s.hint?`${s.label} (${s.hint})`:s.label,accent:s.accent,selected:s.selected},s.id)),t?Gr(zC,{text:t}):null,n?Gr(b,{dimColor:!0,children:n}):null]})},"BackgroundTaskBar");import XC,{createContext as qC,useContext as QC,useReducer as ZP,useCallback as Ke,useRef as eL,useEffect as YC}from"react";function tL(e){return e.agentId===void 0&&e.priority==="user"&&e.mode==="prompt"}i(tL,"isMainThreadPrompt");function Eg(){return yn().getSnapshot().filter(tL)}i(Eg,"getMainThreadPrompts");function kg(){return Eg().map(e=>e.content)}i(kg,"getMainThreadPromptContents");var Rg={state:sn.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 Mg(){let e={...Rg,pendingInputs:kg()},t=new Set,n="",o="",r=0,s=null,a=!1,c=80,l=i(()=>{for(let y of t)y(e)},"notify"),d=i(()=>{let y=kg();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=yn().subscribe(()=>{d()}),p=i(()=>yn().dequeue({maxPriority:"user",mode:"prompt"}).map(T=>T.content),"drainOurSlice"),g=i(()=>{if(s&&(clearTimeout(s),s=null),n||o||r>0){let T=e.thinkingContent+o,w=o?T.length:e.thinkingCharCount+r;e={...e,currentResponse:e.currentResponse+n,thinkingContent:T,thinkingCharCount:w,...o||r>0?{isThinking:!0}:{}},n="",o="",r=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="",o="",r=0,s&&(clearTimeout(s),s=null),e={...e,state:sn.Responding,currentResponse:"",abortController:new AbortController,error:void 0,roundStartedAt:Date.now()},l()},"startStreaming"),stopStreaming:i(()=>{g(),e={...e,state:sn.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?sn.Idle:e.state},l()},"setError"),abort:i(y=>{a=!0,g(),e.abortController?.abort(),n="",o="",r=0,s&&(clearTimeout(s),s=null),y?.preservePendingInputs||p(),e={...e,state:sn.Idle,abortController:void 0,roundStartedAt:null},l()},"abort"),reset:i(()=>{a=!0,g(),e.abortController?.abort(),n="",o="",r=0,s&&(clearTimeout(s),s=null),p(),e={...Rg,pendingInputs:kg()},a=!1,l()},"reset"),isStreaming:i(()=>e.state===sn.Responding||e.state===sn.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||(r+=y,x())},"appendThinkingChars"),appendThinkingContent:i(y=>{a||(o+=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+o,"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:Rg.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&&(Eg().length>=5||(g(),yn().enqueue({priority:"user",mode:"prompt",content:T})))},"addPendingInput"),removeLastPendingInput:i(()=>{let y=Eg(),T=y[y.length-1];T&&(g(),yn().dequeue({maxPriority:"user",mode:"prompt",id:T.id}))},"removeLastPendingInput"),shiftPendingInput:i(()=>(g(),yn().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(Mg,"createStreamingManager");var JC=qC(null),ZC=qC(null);function Pd({children:e,onStateChange:t}){let n=eL(Mg()),[,o]=ZP(ce=>ce+1,0);YC(()=>n.current.subscribe(Ne=>{o(),t?.(Ne)}),[t]),YC(()=>{let ce=n.current;return()=>{ce.dispose()}},[]);let r=Ke(()=>{n.current.startStreaming()},[]),s=Ke(()=>{n.current.stopStreaming()},[]),a=Ke(ce=>{n.current.appendResponse(ce)},[]),c=Ke(()=>{n.current.clearResponse()},[]),l=Ke(ce=>{n.current.setError(ce)},[]),d=Ke(ce=>{n.current.abort(ce)},[]),m=Ke(()=>{n.current.reset()},[]),p=Ke(()=>{n.current.startThinking()},[]),g=Ke(ce=>{n.current.appendThinkingChars(ce)},[]),x=Ke(ce=>{n.current.appendThinkingContent(ce)},[]),y=Ke(()=>{n.current.stopThinking()},[]),T=Ke(()=>{n.current.clearThinkingContent()},[]),w=Ke(ce=>{n.current.setCurrentTool(ce)},[]),I=Ke(ce=>{n.current.appendToolInputChars(ce)},[]),O=Ke(ce=>{n.current.appendToolInputContent(ce)},[]),$=Ke(()=>{n.current.clearToolInputContent()},[]),D=Ke(()=>n.current.getSignal(),[]),L=Ke(()=>n.current.getFullResponse(),[]),X=Ke(()=>n.current.getThinkingContent(),[]),v=Ke(ce=>{n.current.startNewIteration(ce)},[]),ie=Ke(()=>{n.current.clearIterationHistory()},[]),Te=Ke(ce=>{n.current.setMaxIter(ce)},[]),G=Ke(()=>{n.current.startCompacting()},[]),q=Ke(()=>{n.current.stopCompacting()},[]),M=Ke(ce=>{n.current.addPendingInput(ce)},[]),C=Ke(()=>{n.current.removeLastPendingInput()},[]),Z=Ke(()=>n.current.shiftPendingInput(),[]),Re=Ke(()=>{n.current.clearPendingInputs()},[]),Ie=Ke(()=>n.current.consumePendingInputs(),[]),Se={startStreaming:r,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:I,appendToolInputContent:O,clearToolInputContent:$,getSignal:D,getFullResponse:L,getThinkingContent:X,startNewIteration:v,clearIterationHistory:ie,setMaxIter:Te,startCompacting:G,stopCompacting:q,addPendingInput:M,removeLastPendingInput:C,shiftPendingInput:Z,clearPendingInputs:Re,consumePendingInputs:Ie};return XC.createElement(JC.Provider,{value:n.current.getState()},XC.createElement(ZC.Provider,{value:Se},e))}i(Pd,"StreamingProvider");function dc(){let e=QC(JC);if(!e)throw new Error("useStreamingState must be used within a StreamingProvider");return e}i(dc,"useStreamingState");function fc(){let e=QC(ZC);if(!e)throw new Error("useStreamingActions must be used within a StreamingProvider");return e}i(fc,"useStreamingActions");function eb(){let e=dc(),t=fc(),n=e.state===sn.Responding||e.state===sn.WaitingForConfirmation;return{state:e,actions:t,isStreaming:n}}i(eb,"useStreaming");import{useCallback as nL,useRef as oL}from"react";var rL=500;function iL(e={}){let{onKey:t,onEsc:n,onCtrlC:o,enabled:r=!0}=e,s=oL(0),{exit:a}=Go(),c=nL(l=>{if(!r)return!1;if(l.name==="escape"){let d=Date.now(),m=d-s.current<rL;return s.current=d,m&&(l.name="escape-escape"),n?.(),t?.(l),!0}return l.ctrl&&l.name==="c"?(o?.(),t?.(l),!0):l.ctrl&&l.name==="d"?(a(),!0):(t?.(l),!1)},[r,a,o,n,t]);return an(c,{isActive:r}),{lastEscTime:s.current}}i(iL,"useKeypress");function sL(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(sL,"createKeyMatcher");import{useCallback as aL,useSyncExternalStore as cL}from"react";function lL(e){return e.agentId===void 0&&e.priority==="user"&&e.mode==="prompt"}i(lL,"isMainThreadPrompt");var Ag=null,Ld=Object.freeze([]);function tb(){let e=yn().getSnapshot();return e===Ag||(Ag=e,Ld=Object.freeze(e.filter(lL))),Ld}i(tb,"getQueueSliceSnapshot");function nb(){let e=aL(t=>yn().subscribe(t),[]);return cL(e,tb,tb)}i(nb,"useQueuedPrompts");function uL(){return nb().map(t=>t.content)}i(uL,"useQueuedPromptContents");function dL(){Ag=null,Ld=Object.freeze([])}i(dL,"_resetQueuedPromptsCacheForTests");async function mc(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??pc(),title:"",gitRoot:e.gitRoot,runtimeInfo:e.runtimeInfo,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString()}}i(mc,"createInteractiveContext");function pc(){let e=new Date,t=e.toISOString().split("T")[0].replace(/-/g,""),n=e.toTimeString().split(" ")[0].replace(/:/g,"");return`${t}_${n}`}i(pc,"generateSessionId");function io(e){e.lastAccessed=new Date().toISOString()}i(io,"touchContext");async function gc(e){let t=await _x({userKodaxDir:px(),projectRoot:e.projectRoot}),n;return{getGuardrail:i(()=>n||(n=$x({rules:t.merged,claudeMd:gx(e.getAgentsFiles()),getToolProjection:i(r=>(Ol(r)??Sx(r))?.toClassifierInput,"getToolProjection"),resolveProvider:i(r=>{try{return gr(r)}catch{return}},"resolveProvider"),defaultProvider:e.getCurrentProviderName(),defaultModel:e.getCurrentModel()??"",getDefaultProvider:e.getCurrentProviderName,getDefaultModel:i(()=>{let r=e.getCurrentModel();return r||(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(gc,"bootstrapAutoMode");var Cs=class{static{i(this,"MemorySessionStorage")}sessions=new Map;async save(t,n){let o=this.sessions.get(t);this.sessions.set(t,{...structuredClone(n),scope:n.scope??o?.scope??"user",uiHistory:n.uiHistory??o?.uiHistory,extensionState:n.extensionState??o?.extensionState,artifactLedger:n.artifactLedger??o?.artifactLedger,extensionRecords:n.extensionRecords??o?.extensionRecords,lineage:xn(n.messages,n.lineage??o?.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,o){let r=this.sessions.get(t);if(!r?.lineage)return null;let s=bi(r.lineage,n,o);if(!s)return null;let a={...structuredClone(r),messages:Mt(s),lineage:s};return this.sessions.set(t,a),structuredClone(a)}async setLabel(t,n,o){let r=this.sessions.get(t);if(!r?.lineage)return null;let s=vi(r.lineage,n,o);if(!s)return null;let a={...structuredClone(r),lineage:s};return this.sessions.set(t,a),structuredClone(a)}async fork(t,n,o){let r=this.sessions.get(t);if(!r?.lineage)return null;let s=Ri(r.lineage,n);if(!s)return null;let a=o?.sessionId??await Ci(),c={messages:Mt(s),title:o?.title??r.title,gitRoot:r.gitRoot,uiHistory:r.uiHistory?r.uiHistory.map(l=>({...l})):void 0,extensionState:r.extensionState?structuredClone(r.extensionState):void 0,artifactLedger:r.artifactLedger?structuredClone(r.artifactLedger):void 0,extensionRecords:r.extensionRecords?structuredClone(r.extensionRecords):void 0,lineage:s};return this.sessions.set(a,c),{sessionId:a,data:structuredClone(c)}}async rewind(t,n){let o=this.sessions.get(t);if(!o?.lineage)return null;let r=n??Ii(o.lineage);if(!r)return null;let s=ki(o.lineage,r);if(!s)return null;let a={...o,messages:Mt(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,o])=>({id:n,title:o.title,msgCount:o.lineage?xr(o.lineage):o.messages.length}))}async delete(t){this.sessions.delete(t)}async deleteAll(t){this.sessions.clear()}};function fL(){return new Cs}i(fL,"createMemorySessionStorage");import*as ob from"child_process";import*as rb from"util";import Od from"chalk";var mL=rb.promisify(ob.exec),pL={maxBuffer:1024*1024,timeout:3e4,maxOutputLength:8e3,maxErrorLength:4e3};async function Dd(e,t={}){let n={...pL,...t},o=e.trim(),r=pp(o);if(r)return r.startsWith("[Blocked]")&&(console.log(Od.yellow(`
|
|
332
|
+
${r}`)),console.log()),r;try{console.log(Od.dim(`
|
|
333
|
+
[Executing: ${o}]`));let{stdout:s,stderr:a}=await mL(o,{cwd:n.cwd,maxBuffer:n.maxBuffer,timeout:n.timeout,windowsHide:!0}),c="";return s&&(c+=s),a&&(c+=(c?`
|
|
334
|
+
`:"")+`[stderr] ${a}`),c.length>n.maxOutputLength&&(c=c.slice(0,n.maxOutputLength)+`
|
|
335
|
+
...[output truncated]`),console.log(Od.dim(c||"[No output]")),console.log(),`[Shell command executed: ${o}]
|
|
336
|
+
|
|
337
|
+
Output:
|
|
338
|
+
${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)+`
|
|
339
|
+
...[error truncated]`),console.log(Od.red(`
|
|
340
|
+
[Shell Error: ${c}]`)),console.log(),`[Shell command failed: ${o}]
|
|
341
|
+
|
|
342
|
+
Error: ${c}`}}i(Dd,"executeShellCommand");async function _g(e,t={}){if(e.startsWith("!")){let n=e.slice(1).trim();return Dd(n,t)}return e}i(_g,"processSpecialSyntax");function gL(e){return e.trim().startsWith("!")}i(gL,"isShellCommand");function hL(e){return e.startsWith("[Shell command executed:")||e.startsWith("[Shell:")}i(hL,"isShellCommandSuccess");function hc(e){return e.startsWith("[Shell command executed:")||e.startsWith("[Shell command failed:")||e.startsWith("[Shell:")||e.startsWith("[Blocked]")}i(hc,"isShellCommandHandled");function Nd(e,t,n){let o=e.trim();return{type:"info",icon:"\u23F3",text:/\bretry\s+\d+\/\d+\b/i.test(o)||/\b\d+\/\d+\b/.test(o)?o:`${o} \xB7 retry ${t}/${n}`}}i(Nd,"createRetryHistoryItem");function $g(e,t,n,o){e(Nd(t,n,o))}i($g,"emitRetryHistoryItem");function Bd(e){let{recoveryAction:t,attempt:n,maxAttempts:o,delayMs:r,stage:s,fallbackUsed:a}=e,c=Math.round(r/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}/${o} in ${c}s`:`${l} \xB7 ${d} ${n}/${o}`}}i(Bd,"createRecoveryHistoryItem");function Pg(e,t){e(Bd(t))}i(Pg,"emitRecoveryHistoryItem");import{jsx as se,jsxs as Kt,Fragment as lO}from"react/jsx-runtime";import t0,{useState as Ue,useCallback as z,useRef as me,useEffect as Fe,useMemo as ue}from"react";import{jsx as so,Fragment as yL,jsxs as Hd}from"react/jsx-runtime";var Lg=" | ",ib=i(({searchActive:e=!1,selectionActive:t=!1,showAllActive:n=!1,searchQuery:o="",searchCurrent:r=0,searchCount:s=0,searchDetailText:a,pendingLiveUpdates:c=0,secondaryText:l,noticeText:d})=>{let m=ne("dark"),p=o.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`,I=c>0?c===1?"1 new update":`${c} new updates`:void 0,O=e&&s>0?`${Math.max(0,r)}/${s}`:void 0,$=e&&g||x,D=!!($||y);return Hd(k,{flexDirection:"column",children:[Hd(k,{paddingX:1,children:[so(b,{color:m.colors.dim,children:T}),so(b,{dimColor:!0,children:Lg}),so(b,{color:m.colors.dim,children:w}),O||I?so(k,{flexGrow:1}):null,O?Hd(yL,{children:[so(b,{dimColor:!0,children:O}),I?so(b,{dimColor:!0,children:Lg}):null]}):null,I?so(b,{color:m.colors.accent,bold:!0,children:I}):null]}),D?Hd(k,{paddingX:1,children:[$?so(b,{color:m.colors.dim,children:$}):null,$&&y?so(b,{dimColor:!0,children:Lg}):null,y?so(b,{color:m.colors.accent,bold:!0,children:y}):null]}):null]})},"TranscriptModeFooter");import{jsx as xL,jsxs as wL}from"react/jsx-runtime";var sb=i(({banner:e,...t})=>wL(k,{flexDirection:"column",children:[e,xL(Ur,{...t,animateSpinners:!1,showFullThinking:!1,showDetailedTools:!1,showLiveProgressRows:!1})]}),"PromptTranscriptSurface");import{jsx as SL,jsxs as TL}from"react/jsx-runtime";var ab=i(({banner:e,windowed:t=!1,showDetailedTools:n=!1,showAllContent:o=!1,...r})=>TL(k,{flexDirection:"column",children:[e,SL(mg,{...r,chromeMode:"hidden",windowed:t,showFullThinking:!0,showDetailedTools:n,showAllContent:o,showLiveProgressRows:!0})]}),"TranscriptModeSurface");import{jsxs as CL,jsx as bL}from"react/jsx-runtime";var cb=i(({text:e,tone:t="success"})=>{let n=e?.trim();if(!n)return null;let o=ne("dark"),r=t==="warning"?o.colors.warning:o.colors.accent,s=t==="warning"?"!":"\u2713";return bL(k,{paddingX:1,backgroundColor:o.colors.inputBackground,children:CL(b,{color:r,children:[s," ",n]})})},"ClipboardToastSurface");import{jsx as er,Fragment as vL,jsxs as Og}from"react/jsx-runtime";var IL=" \u23BF ";function kL(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(kL,"resolveSymbolColor");var RL=i(({row:e})=>{let t=kL(e.symbolColor),n=e.kind!=="item";return Og(k,{flexDirection:"row",children:[er(b,{color:t,bold:e.isActive,children:e.symbol}),er(b,{children:" "}),er(b,{dimColor:n,bold:e.isActive,strikethrough:e.isStrikethrough,children:e.text}),e.evaluatorBadge?Og(vL,{children:[er(b,{children:" "}),er(b,{dimColor:!0,children:e.evaluatorBadge})]}):null]})},"TodoListRow"),lb=i(({viewModel:e})=>{if(!e.shouldRender||e.rows.length===0)return null;let t=ne("dark").colors.dim;return Og(k,{flexDirection:"row",children:[er(b,{color:t,children:IL}),er(k,{flexDirection:"column",flexGrow:1,children:e.rows.map((n,o)=>er(RL,{row:n},`${n.kind}-${n.id??o}`))})]})},"TodoListSurface");function EL(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(EL,"symbolForStatus");function ML(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(ML,"pickAnchorIndex");function AL(e){let{symbol:t,color:n}=EL(e.status),o=e.status==="failed"&&e.note?`${e.subject} (${e.note})`:e.subject,r=e.status==="cancelled",s=e.evaluator?`[${e.evaluator}]`:void 0;return{kind:"item",id:e.id,symbol:t,symbolColor:n,text:o,isActive:e.status==="in_progress",isStrikethrough:r,evaluatorBadge:s}}i(AL,"buildItemRow");function _L(e){return{kind:"summary_done",symbol:"\u2713",symbolColor:"green",text:`${e} done`,isActive:!1}}i(_L,"buildDoneSummary");function Dg(e){return{kind:"summary_pending",symbol:"\u2610",symbolColor:"dim",text:`+${e} more`,isActive:!1}}i(Dg,"buildPendingSummary");function $L(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].status==="failed"&&!t.has(n))return n;return-1}i($L,"pickFailedToPromote");function PL(e,t){let n=e.length;if(n===0)return{visibleIdx:[],hiddenCompletedCount:0,hiddenPendingCount:0};let o=4,r=Math.max(0,t-1),s=Math.min(n,r+o);s-r<o&&r>0&&(r=Math.max(0,s-o)),s-r<o&&s<n&&(s=Math.min(n,r+o));let a=[];for(let d=r;d<s;d++)a.push(d);let c=0,l=0;for(let d=0;d<r;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(PL,"decideWindow");function ub(e,t){let n=e.length,o=e.reduce((x,y)=>y.status==="completed"?x+1:x,0),r=i((x,y)=>({shouldRender:y,rows:x,completedCount:o,totalCount:n}),"baseVm");if(n<1)return r([],!1);t.now,t.lastAllCompletedAt;let s=ML(e),a=PL(e,s),c=new Set(a.visibleIdx),l=$L(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((I,O)=>I-O);let T=d[0],w=0;for(let I=0;I<T;I++)e[I].status==="completed"&&w++;m=w}}let g=[];m>0&&g.push(_L(m));for(let x of d)g.push(AL(e[x]));if(p>0&&g.push(Dg(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 I=/\+(\d+) more/.exec(w.text),O=I?Number.parseInt(I[1],10)+1:1;g[g.length-1]=Dg(O)}else g.push(Dg(1));x=!0;break}}if(!x)break}return r(g,!0)}i(ub,"buildTodoPlanViewModel");function db(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=[],o=[...t,...n].map(r=>r.label.trim()).filter(Boolean).join(" | ");return{leftItems:t,rightItems:n,summary:o}}i(db,"buildFooterHeaderViewModel");function LL(e){return Nl(e.provider,e.model,"off",{longRunning:!0})}i(LL,"evaluateSessionTransitionPolicy");function OL(e,t){let n=t.snapshot.model?`${t.snapshot.provider}:${t.snapshot.model}`:t.snapshot.provider,o=[`[Provider Guardrail] ${e} on ${n}: ${t.summary}`],r=t.issues[0]?.detail;return r&&o.push(` ${r}`),t.status==="block"?o.push(" Switch to a provider with durable full-history session semantics before continuing."):t.status==="warn"&&o.push(" Continuing with degraded session semantics."),o}i(OL,"formatSessionTransitionGuardMessage");function Kr(e,t,n){let o=LL(e);if(!o||o.status==="allow")return!0;let[r,...s]=OL(t,o);return n(o.status,r,s),o.status!=="block"}i(Kr,"enforceSessionTransitionGuard");function DL(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(DL,"summarizeEntry");function fb(e,t,n,o){let r=t?n?"\\- ":"|- ":"",s=e.active?"*":" ",a=e.entry.id.slice(0,12),c=e.label?` [${e.label}]`:"";o.push(`${t}${r}${s} ${a} ${DL(e.entry)}${c}`);let l=t+(t?n?" ":"| ":"");e.children.forEach((d,m)=>{fb(d,l,m===e.children.length-1,o)})}i(fb,"formatNode");function Fd(e){let t=[];return e.forEach((n,o)=>{fb(n,"",o===e.length-1,t)}),t}i(Fd,"formatSessionTree");var NL=100,BL=/\b(curl|wget|invoke-webrequest|invoke-restmethod|iwr|irm)\b/i,pb=/\b(rm|del|erase|remove-item|rmdir|rd|git clean)\b/i,gb=/\b(npm|pnpm|yarn|pip|choco|winget)\s+(install|add|remove|uninstall|update|upgrade|ci)\b/i,hb=/\b(set-content|add-content|out-file|new-item|copy-item|move-item|rename-item|cp|mv|copy|move|ren|touch)\b/i;function bs(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}i(bs,"readString");function Ft(e,t,n){n&&e.push({label:t,value:n})}i(Ft,"pushField");function HL(e){return e.replace(/\s+/g," ").trim()}i(HL,"normalizeWhitespace");function FL(e,t){if(e.length<=t)return e;let n=Math.ceil((t-3)/2),o=Math.floor((t-3)/2);return`${e.slice(0,n)}...${e.slice(e.length-o)}`}i(FL,"truncateMiddle");function WL(e){let t=e;return t=t.replace(/\b(authorization\s*:\s*bearer\s+)([^\s'"]+)/gi,(n,o)=>`${o}[REDACTED]`),t=t.replace(/\b((?:authorization|cookie)\s*:\s*)([^'"]+)/gi,(n,o)=>`${o}[REDACTED]`),t=t.replace(/\b(bearer\s+)([^\s'"]+)/gi,(n,o)=>`${o}[REDACTED]`),t=t.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|cookie|session)\b(\s*[:=]\s*)(['"]?)([^'"\s]+)(\3)/gi,(n,o,r,s)=>`${o}${r}${s}[REDACTED]${s}`),t=t.replace(/(--(?:api-key|token|secret|password|cookie)\s+)(\S+)/gi,(n,o)=>`${o}[REDACTED]`),t=t.replace(/((?:-u|--user)\s+)(\S+)/gi,(n,o)=>`${o}[REDACTED]`),t}i(WL,"maskSensitiveSegments");function mb(e){return FL(WL(HL(e)),NL)}i(mb,"summarizeCommand");function UL(e){return On(e)?te("intent.read"):pb.test(e)?te("intent.delete"):gb.test(e)?te("intent.deps"):Dn(e)||hb.test(e)?te("intent.modify"):te("intent.execute")}i(UL,"classifyShellIntent");function jL(e){let t=[];return pb.test(e)?t.push(te("risk.destructive")):gb.test(e)?t.push(te("risk.deps")):Dn(e)||hb.test(e)?t.push(te("risk.modify")):On(e)||t.push(te("risk.unknown")),BL.test(e)&&t.push(te("risk.network")),t}i(jL,"classifyShellRisks");function GL(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.kind=="string")}i(GL,"readSignals");function KL(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(KL,"scopeFromSignals");function VL(e){if(e._outsideProject===!0)return te("scope.outside");if(e._alwaysConfirm===!0)return te("scope.protected")}i(VL,"scopeFromMarkers");function zL(e){if(!e)return[];let t=[],n=e.some(r=>r.kind==="dangerous_pattern"&&r.severity==="high"),o=e.some(r=>r.kind==="dangerous_pattern"&&r.severity==="medium");return n?t.push(te("risk.destructive")):o&&t.push(te("risk.modify")),e.some(r=>r.kind==="network")&&t.push(te("risk.network")),e.some(r=>r.kind==="package_install")&&t.push(te("risk.deps")),t}i(zL,"risksFromSignals");var XL={Reason:"field.reason",Intent:"field.intent",Target:"field.target",Scope:"field.scope",Risk:"field.risk",Summary:"field.summary"};function YL(e){return te(XL[e])}i(YL,"localizeFieldLabel");function vs(e,t){return{title:e,fields:t,details:t.map(n=>`${YL(n.label)}: ${n.value}`)}}i(vs,"buildDisplayFromFields");function Wd(e,t){if(e==="confirm"){let l=bs(t._message);if(l)return vs(l,[])}if(e==="exit_plan_mode"){let l=bs(t.plan),d="Approve plan? (exits plan mode \u2192 accept-edits)";return l?{title:d,fields:[],details:l.split(`
|
|
343
|
+
`)}:vs(d,[])}let n=[],o=bs(t.path),r=bs(t.command),s=bs(t._reason)??bs(t.justification),a=GL(t._classifierSignals),c=KL(a)??VL(t);switch(Ft(n,"Reason",s),e){case"bash":case"shell_command":{if(r){Ft(n,"Intent",UL(r)),Ft(n,"Scope",c);let l=zL(a),d=l.length>0?l:jL(r);d.length>0&&Ft(n,"Risk",d.join("; ")),Ft(n,"Summary",mb(r))}else Ft(n,"Scope",c);return vs(e==="bash"?te("tool.bash.title"):te("tool.shell.title"),n)}case"write":return Ft(n,"Intent",te("intent.write_file")),Ft(n,"Target",o),Ft(n,"Scope",c),vs(te("tool.write.title"),n);case"edit":return Ft(n,"Intent",te("intent.edit_file")),Ft(n,"Target",o),Ft(n,"Scope",c),vs(te("tool.edit.title"),n);default:return Ft(n,"Intent",te("intent.use_tool",{tool:e})),Ft(n,"Target",o),Ft(n,"Scope",c),r&&Ft(n,"Summary",mb(r)),vs(te("tool.generic.title",{tool:e}),n)}}i(Wd,"buildToolConfirmationDisplay");function yb(e,t){let n=Wd(e,t);return n.details.length>0?`${n.title}
|
|
344
|
+
${n.details.join(`
|
|
345
|
+
`)}`:n.title}i(yb,"buildToolConfirmationPrompt");var Ng=[" \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 Ve from"chalk";var Ud=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 o=this.shortcuts.get(t);o&&(o.handler=n)}findMatchingShortcut(t,n){let o=null,r=-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>r&&(r=s.definition.priority,o=s)}return o}matchesBinding(t,n){for(let o of n){let r=this.normalizeKeyName(t.name),s=this.normalizeKeyName(o.key);if(r===s){let a=(o.ctrl??!1)===t.ctrl,c=(o.shift??!1)===t.shift,l=(o.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"},o=t.toLowerCase();return n[o]??o}executeShortcut(t,n){let o=this.findMatchingShortcut(t,n);return o?.handler?o.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 o=n.definition.context;return o==="global"||o===t})}formatBinding(t){let n=[];t.ctrl&&n.push("Ctrl"),t.meta&&n.push("Alt"),t.shift&&n.push("Shift");let o=t.key.length===1?t.key.toUpperCase():t.key;return n.push(o),n.join("+")}formatBindings(t){return t.map(n=>this.formatBinding(n)).join(" or ")}},ao=i(()=>Ud.getInstance(),"getShortcutsRegistry");var Is=[{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 qL,useCallback as QL,useRef as JL}from"react";function Ro(e,t,n={}){let{context:o,isActive:r=!0}=n,s=ao(),a=JL(t);a.current=t,qL(()=>(s.setHandler(e,(...d)=>a.current(...d)),()=>{s.setHandler(e,void 0)}),[s,e]);let c=QL(d=>{if(!r)return!1;let p=s.getAllShortcuts().find(T=>T.definition.id===e);if(!p)return!1;let g=o??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,r,o]),l=ZL(e,s);an(c,{isActive:r,priority:l})}i(Ro,"useShortcut");function ZL(e,t){let o=t.getAllShortcuts().find(r=>r.definition.id===e);return o?o.definition.priority:0}i(ZL,"getShortcutPriority");import e1,{createContext as t1,useContext as n1,useState as xb,useCallback as Bg}from"react";var wb=t1(null);function Hg({children:e,initialContext:t="input"}){let[n,o]=xb(!1),[r,s]=xb(t);ao().registerAll(Is);let c=Bg(()=>{o(p=>!p)},[]),l=Bg(()=>{let g=ao().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=Bg(()=>ao().getShortcutsByContext(r),[r]),m={showHelp:n,toggleHelp:c,setShowHelp:o,currentContext:r,setCurrentContext:s,getShortcutsByCategory:l,getContextShortcuts:d};return e1.createElement(wb.Provider,{value:m},e)}i(Hg,"ShortcutsProvider");function Fg(){let e=n1(wb);if(!e)throw new Error("useShortcutsContext must be used within a ShortcutsProvider");return e}i(Fg,"useShortcutsContext");import o1 from"chalk";function Wg({currentConfig:e,setCurrentConfig:t,isLoading:n,abort:o,stopThinking:r,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:I,isInputEmpty:O,onSavePermissionMode:$}){return Ro("interrupt",()=>n?(o(),r(),s(),a(void 0),c(!1),console.log(o1.yellow(`
|
|
346
|
+
[Interrupted]`)),!0):!1,{isActive:n}),Ro("showHelp",()=>T?!1:O?(l(),!0):!1,{isActive:O}),Ro("toggleThinking",()=>{if(T)return!1;let D=pr.indexOf(e.reasoningMode),L=pr[(D+1)%pr.length],X=L!=="off";return t(v=>({...v,thinking:X,reasoningMode:L})),xo({reasoningMode:L,thinking:X}),p?.(L),m?.(X),d(!1),!0}),Ro("toggleTranscriptMode",()=>T?!1:(g?.(),d(!1),!0)),Ro("openTranscriptSearch",()=>T||!y?!1:(x?.(),d(!1),!0)),Ro("togglePermissionMode",()=>{if(T)return!1;let D=["plan","accept-edits","auto"],L=e.permissionMode==="auto-in-project"?"auto":e.permissionMode,v=(D.indexOf(L)+1)%D.length,ie=D[v];return t(Te=>({...Te,permissionMode:ie})),I?.(ie),$?.(ie),d(!1),!0}),Ro("toggleAgentMode",()=>{if(T)return!1;let D=e.agentMode==="ama"?"sa":"ama";return t(L=>({...L,agentMode:D})),xo({agentMode:D}),w?.(D),d(!1),!0}),null}i(Wg,"GlobalShortcuts");import{exec as r1}from"child_process";import{promisify as i1}from"util";var s1=i1(r1),a1={read:"read",grep:"grep",glob:"glob",write:"write",edit:"edit",bash:"bash",undo:"undo",askuserquestion:"ask-user-question",askuser:"ask-user-question"};function Sb(e){let t=[],n="",o=0;for(let r of e){if(r===","&&o===0){n.trim()&&t.push(n.trim()),n="";continue}r==="("?o++:r===")"&&o>0&&o--,n+=r}return n.trim()&&t.push(n.trim()),t}i(Sb,"splitTopLevelCommaList");function c1(e){if(!e?.trim())return{configured:!1,rules:[],invalidEntries:[]};let t=[];return{configured:!0,rules:Sb(e).map(o=>{if(o==="*")return{tool:"*"};if(o.includes("(")&&!o.endsWith(")")){t.push(o);return}let r=o.match(/^([^(]+?)(?:\((.*)\))?$/);if(!r){t.push(o);return}let s=a1[r[1].replace(/[^a-z]/gi,"").toLowerCase()];if(!s){t.push(o);return}let a=r[2]?Sb(r[2]).map(c=>c.trim()).filter(Boolean):void 0;return{tool:s,patterns:a&&a.length>0?a:void 0}}).filter(o=>o!==void 0),invalidEntries:t}}i(c1,"parseAllowedTools");function l1(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`,"i")}i(l1,"wildcardToRegExp");function Tb(e,t){return l1(e).test(t)}i(Tb,"matchesPattern");function Cb(e,t,n){if(!e.configured)return!0;if(e.rules.length===0)return!1;let o=t.toLowerCase(),r=o==="bash"?String(n.command??"").trim():"";return e.rules.some(s=>s.tool!=="*"&&s.tool!==o?!1:!s.patterns||s.patterns.length===0||o!=="bash"?!0:s.patterns.some(a=>Tb(a,r)))}i(Cb,"isToolAllowed");function u1(e,t){return e.matcher?Tb(e.matcher,t):!0}i(u1,"hookMatches");function d1(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(`
|
|
347
|
+
`)}i(d1,"formatManualOutput");function f1(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(f1,"resolveModelOverride");async function m1(e,t,n,o,r,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(!Cb(s,"bash",c))return{allow:!1,message:`Hook ${e} for ${a} is blocked by allowed-tools policy.`};if(r.beforeToolExecute&&!await r.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 s1(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(`
|
|
348
|
+
`);m&&r.onToolResult?.({id:`frontmatter-hook:${e}`,name:"bash",content:m}),d.trim()&&await o(`[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 o(`[Hook ${e} failed] ${l instanceof Error?l.message:String(l)}`),{}}}i(m1,"executeHookCommand");async function ks(e,t,n,o,r,s,a){let c=e?.[t];if(!c||c.length===0)return{};let l={};for(let d of c){if(!u1(d,n))continue;let m=await m1(t,d,o,r,s,a);if(m.message&&await r(`[Hook ${t}] ${m.message}`),m.additionalContext&&(l.additionalContext=l.additionalContext?`${l.additionalContext}
|
|
349
|
+
${m.additionalContext}`:m.additionalContext),m.allow===!1){l.allow=!1;break}}return l}i(ks,"runHooks");async function jd(e,t,n,o){if(t.disableModelInvocation)return{mode:"manual",manualOutput:d1(t),finalize:i(async()=>{},"finalize")};let r=e.events??{},s=c1(t.allowedTools),a=f1(e.provider,t.model),c=!1,l=i(async w=>{if(o(w),!(c||!t.hooks?.Notification?.length)){c=!0;try{await ks(t.hooks,"Notification",w,{displayName:t.displayName,source:t.source,path:t.path,message:w},async I=>{o(I)},r,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 ks(t.hooks,"SessionStart",t.displayName,{displayName:t.displayName,source:t.source,path:t.path},l,r,s);if(d.allow===!1)return{mode:"manual",manualOutput:`[Blocked] ${t.displayName} was stopped before execution.`,finalize:i(async()=>{},"finalize")};let m=await ks(t.hooks,"UserPromptSubmit",n,{displayName:t.displayName,source:t.source,prompt:n,path:t.path},l,r,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(`
|
|
350
|
+
|
|
351
|
+
`):void 0,t.prompt,`User request: ${n}`].filter(w=>typeof w=="string"&&w.trim().length>0),x={...r,beforeToolExecute:i(async(w,I)=>Cb(s,w,I)?(await ks(t.hooks,"PreToolUse",w,{tool:w,input:I,displayName:t.displayName,source:t.source,path:t.path},l,r,s)).allow===!1?(await l(`[Blocked] PreToolUse hook blocked '${w}' for ${t.displayName}`),!1):r.beforeToolExecute?await r.beforeToolExecute(w,I):!0:(await l(`[Blocked] Tool '${w}' is not allowed by ${t.displayName}`),!1),"beforeToolExecute"),onToolResult:i(w=>{r.onToolResult?.(w),ks(t.hooks,"PostToolUse",w.name,{...w,displayName:t.displayName,source:t.source,path:t.path},l,r,s)},"onToolResult")},y=!1,T=i(async w=>{y||(y=!0,await ks(t.hooks,t.context==="fork"?"SubagentStop":"Stop",t.displayName,{displayName:t.displayName,source:t.source,path:t.path,error:w?.message},l,r,s))},"finalize");return{mode:t.context==="fork"?"fork":"inline",prompt:g.join(`
|
|
352
|
+
|
|
353
|
+
`),options:{...e,modelOverride:a,context:{...e.context,rawUserInput:n,skillInvocation:t.source==="skill"?t.skillInvocation:e.context?.skillInvocation},events:x},finalize:T}}i(jd,"prepareInvocationExecution");import{appendFileSync as p1,mkdirSync as g1,writeFileSync as h1}from"node:fs";import{join as vb}from"node:path";import bb from"node:v8";var Gg=parseInt(process.env.KODAX_MEMORY_DIAG??"0",10),Kg=Gg>=1,Vg=Ti(),Ib=vb(Vg,"memory-diag.log"),Ug=0,jg=!1;function kb(){if(!jg)try{g1(Vg,{recursive:!0}),jg=!0}catch{jg=!0}}i(kb,"ensureLogDir");function y1(e){kb();try{p1(Ib,e+`
|
|
354
|
+
`)}catch{}}i(y1,"writeLog");function ht(e){return`${(e/1024/1024).toFixed(2)}MB`}i(ht,"formatMB");function x1(){return typeof globalThis.gc=="function"?(globalThis.gc(),!0):!1}i(x1,"tryGC");function kt(e){return e?e.length*2:0}i(kt,"strBytes");function Vr(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 o of e)n+=Vr(o,t+1);return n}if(typeof e=="object"){let n=64;for(let[o,r]of Object.entries(e))n+=o.length*2,n+=Vr(r,t+1);return n}return 16}i(Vr,"estimateJsonBytes");function Rb(e){if(!e||typeof e!="object")return 64;let t=e,n=64,o=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 r of t.content)n+=Rb(r);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+=Vr(t.input));for(let[r,s]of Object.entries(t))o.has(r)||(n+=r.length*2+Vr(s));return n}i(Rb,"estimateBlockBytes");function zg(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+=Rb(n);return t}return 200}i(zg,"estimateMessageBytes");function Gd(e){let t=128;switch(t+=kt(e.id)+kt(e.parentId??void 0)+kt(e.timestamp),e.type){case"message":return t+zg(e.message);case"compaction":return t+=kt(e.summary),t+=kt(e.firstKeptEntryId),t+=kt(e.reason),t+=kt(e.artifactLedgerId),e.details!==void 0&&(t+=Vr(e.details)),e.memorySeed!==void 0&&(t+=Vr(e.memorySeed)),t;case"branch_summary":return t+=kt(e.summary),t+=kt(e.fromId),e.details!==void 0&&(t+=Vr(e.details)),t;case"label":return t+=kt(e.targetId),t+=kt(e.label),t;case"archive_marker":return t+=kt(e.archiveBatchId),t+=kt(e.summary),t+=8,t;default:return t}}i(Gd,"estimateEntryBytes");function w1(e){let t={},n=[];for(let r=0;r<e.length;r++){let s=e[r],a=zg(s);n.push({index:r,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((r,s)=>s.bytes-r.bytes),{totalBytes:n.reduce((r,s)=>r+s.bytes,0),biggest:n.slice(0,5),byRole:t}}i(w1,"buildMessageBreakdown");function Kd(){return Kg}i(Kd,"memDiagEnabled");function Vd(e,t){if(!Kg)return;e==="turn-start"&&Ug++;let n=process.memoryUsage(),o=new Date().toISOString(),r=t.biggestMessages,s=["",`\u2550\u2550\u2550 [MEMDIAG] turn=${Ug} phase=${e} @${o} \u2550\u2550\u2550`,` V8 heap: used=${ht(n.heapUsed)} total=${ht(n.heapTotal)} rss=${ht(n.rss)} ext=${ht(n.external)}`," \u2500\u2500 Data breakdown \u2500\u2500",` context.messages: ${t.messageCount} msgs, ${ht(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: ${ht(t.lineageNonMessageBytes)} (compaction.details/memorySeed + branch_summary payloads)`,` lineage orphan messages: ${t.lineageOrphanMessageCount} msgs, ${ht(t.lineageOrphanMessageBytes)} (in lineage but not in context.messages \u2014 branches/pruned)`,` UI history: ${t.historyItemCount} items, ${ht(t.historyTextBytes)}`,` foreground turn: ${t.foregroundItemCount} items, ${ht(t.foregroundTextBytes)}`,` streaming response: ${ht(t.streamingResponseBytes)}`,` streaming thinking: ${ht(t.streamingThinkingBytes)}`,` persisted UI history: ${t.persistedUiHistoryCount} items, ${ht(t.persistedUiHistoryBytes)}`];if(r.length>0){s.push(" \u2500\u2500 Top 5 biggest messages \u2500\u2500");for(let d of r)s.push(` [${d.index}] role=${d.role} ${ht(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=bb.getHeapSpaceStatistics();for(let d of c)d.space_used_size>1024*1024&&s.push(` ${d.space_name.padEnd(25)} used=${ht(d.space_used_size)} allocated=${ht(d.space_size)}`);if(s.push(" \u2500\u2500 Summary \u2500\u2500"),s.push(` tracked data total: ${ht(a)}`),s.push(` V8 heap used: ${ht(n.heapUsed)}`),s.push(` unaccounted (overhead): ${ht(n.heapUsed-a)}`),s.push(" (React/Ink tree, provider SDK buffers, module metadata,"),s.push(' tokenizer caches, source maps \u2014 see "Blind spots" note)'),x1()){let d=process.memoryUsage();s.push(` after forced GC: heap=${ht(d.heapUsed)} (freed ${ht(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(Gg>=2)try{let d=vb(Vg,`heap-turn${Ug}-${e}.heapsnapshot`);bb.writeHeapSnapshot(d),s.push(` heap snapshot: ${d}`)}catch{s.push(" heap snapshot: FAILED")}y1(s.join(`
|
|
355
|
+
`))}i(Vd,"memDiagSnapshot");function zd(e,t,n){let o=w1(e),r=new Set(e),s=0,a=0,c=0,l=0,d=0,m=0,p=0,g=0,x=t?.entries??[];for(let I of x)switch(I.type){case"message":g++,r.has(I.message)||(c++,a+=zg(I.message));break;case"compaction":l++,s+=Gd(I);break;case"branch_summary":d++,s+=Gd(I);break;case"label":m++,s+=Gd(I);break;case"archive_marker":p++,s+=Gd(I);break}let y=0;for(let I of n.historyItems)y+=kt(I.text);let T=0;for(let I of n.foregroundItems)T+=kt(I.text);let w=0;for(let I of n.persistedUiHistory)w+=kt(I.text);return{messageCount:e.length,messageBytes:o.totalBytes,biggestMessages:o.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:kt(n.streamingResponse),streamingThinkingBytes:kt(n.streamingThinking),persistedUiHistoryCount:n.persistedUiHistory.length,persistedUiHistoryBytes:w}}i(zd,"buildMemDiagBreakdown");function Eb(){if(Kg){kb();try{let e=typeof globalThis.gc=="function",t=[`[MEMDIAG] Session started at ${new Date().toISOString()}`,`[MEMDIAG] Level=${Gg} 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(`
|
|
356
|
+
`);h1(Ib,t+`
|
|
357
|
+
`)}catch{}}}i(Eb,"memDiagReset");import S1 from"node:fs";import Yg from"node:path";var T1={".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"},C1=/@(?:"([^"]+)"|'([^']+)'|([^\s]+))/g;function b1(e){return T1[Yg.extname(e).toLowerCase()]}i(b1,"resolveImageMediaType");var Xg="[Image unavailable]";function v1(e){return""}i(v1,"buildImageAnchor");function yc(e,t){let n=[],o=[],r=new Set,s=new Map,a=new Set,c=[],l=0;for(let m of e.matchAll(C1)){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=b1(g);if(!x){c.push(m[0]),l=p+m[0].length;continue}let y=Yg.resolve(t,g);try{if(!S1.statSync(y).isFile()){a.has(y)||(o.push(`[Image input skipped] ${g} is not a file.`),a.add(y)),c.push(Xg),l=p+m[0].length;continue}}catch{a.has(y)||(o.push(`[Image input missing] ${g} was not found from ${t}.`),a.add(y)),c.push(Xg),l=p+m[0].length;continue}if(!r.has(y)){r.add(y);let T=v1(n.length+1);s.set(y,T),n.push({kind:"image",path:y,mediaType:x,source:"user-inline",description:`Attached image ${Yg.basename(y)}`})}c.push(s.get(y)??Xg),l=p+m[0].length}c.push(e.slice(l));let d=c.join("");return{promptText:d,messageContent:bx(d,n),inputArtifacts:n,warnings:o}}i(yc,"preparePromptInputArtifacts");function Mb(e){let t=I1(e.stage),n=k1(e);return{type:"info",icon:"\u{1F4E1}",text:n?`[RepoIntel] ${t} \xB7 ${n}`:`[RepoIntel] ${t}`,tightSpacing:!0}}i(Mb,"createRepoIntelTraceHistoryItem");function I1(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(I1,"stageDisplayName");function k1(e){let t=[],n=e.capability;n&&(t.push(`mode=${n.mode}`),n.status!=="ok"&&t.push(`status=${n.status}`));let o=e.trace;return o&&(o.daemonLatencyMs!==void 0&&t.push(`daemon ${o.daemonLatencyMs}ms`),o.cliLatencyMs!==void 0&&t.push(`cli ${o.cliLatencyMs}ms`),o.cacheHit!==void 0&&t.push(o.cacheHit?"cache hit":"cache miss"),o.capsuleEstimatedTokens!==void 0&&t.push(`${R1(o.capsuleEstimatedTokens)} tokens`)),t.length===0&&e.summary?E1(e.summary):t.join(" \xB7 ")}i(k1,"buildRepoIntelDetailLine");function R1(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}i(R1,"formatTokens");function E1(e){return e.replace(/^stage=[^|]+\|\s*/,"").trim()}i(E1,"stripSummaryStagePrefix");function M1(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(M1,"formatHarnessProfileShort");function Ab(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(Ab,"mergeLiveThinkingContent");function xc(e,t){let n=t?.expanded?e.detailNote??e.note:e.note,o=M1(e.harnessProfile)??e.harnessProfile,r=`${e.agentMode.toUpperCase()} ${o}`,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?`${r} - ${n}`:`${r} - Managed task starting`;case"preflight":return n?`${a} - ${n}`:`${a} - ${s} preflight starting`;case"round":return n?`${r} - ${n}`:`${r} - Managed task round update${l}`;case"worker":return n?`${r} - ${n}${l}`:`${r} - ${e.activeWorkerTitle??"Worker"} starting${l}`;case"upgrade":return n?`${r} - ${n}`:`${r} - Harness transition${l}`;case"completed":return n?`${r} - ${n}`:`${r} - Managed task completed`;default:return}}i(xc,"formatManagedTaskBreadcrumb");function _b(e,t,n,o){let r=e?.gitRoot??t??void 0,s=e?.executionCwd??r??process.cwd();return{...e,gitRoot:r,executionCwd:s,contextTokenSnapshot:n,taskSurface:"repl",skillsPrompt:o}}i(_b,"buildManagedRunContext");var A1=["global","mode","navigation","editing"],_1={global:["showHelp","interrupt"],mode:["toggleThinking","toggleTranscriptMode","togglePermissionMode","toggleAgentMode"],navigation:["openTranscriptSearch","historyUp","historyDown","moveToStart","moveToEnd"],editing:["acceptCompletion","cancelInput","newline","killLineRight","killLineLeft","deleteWordLeft"]},$1={global:"Global",mode:"Modes",navigation:"Navigation",editing:"Editing"},P1={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 L1(e){let t=ao(),n=t.getAllShortcuts().find(r=>r.definition.id===e);if(n?.effectiveBindings?.length)return t.formatBindings(n.effectiveBindings);let o=Is.find(r=>r.id===e);if(o?.defaultBindings?.length)return t.formatBindings(o.defaultBindings)}i(L1,"resolveShortcutBindingLabel");function O1(e){return`${L1(e.id)??e.id} ${e.name}`}i(O1,"buildMenuItemLabel");function D1(e){return ao().getAllShortcuts().find(o=>o.definition.id===e)?.definition??Is.find(o=>o.id===e)}i(D1,"resolveShortcutDefinition");function Xd(){return[...A1.map(t=>{let n=_1[t].map(o=>D1(o)).filter(o=>!!o).map(o=>({id:o.id,label:O1(o)}));return{id:t,title:$1[t],items:n}}).filter(t=>t.items.length>0),P1]}i(Xd,"buildHelpMenuSections");var qg=2,$b=1,Pb=4;function et(e,t){let n=Xt(e.length>0?e.split(`
|
|
358
|
+
`):[""],Math.max(1,t),0,0);return Math.max(1,n.visualLines.length)}i(et,"wrapLineCount");function N1(e,t,n=">"){let o=n.length+1,r=Math.max(20,t-o),s=Xt(e.length>0?e.split(`
|
|
359
|
+
`):[""],r,0,0);return Math.max(1,s.visualLines.length)+2}i(N1,"calculateInputPromptRows");function Lb(e){let{terminalRows:t,terminalWidth:n,windowedTranscript:o=!1,inputText:r,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:I,confirmInstruction:O,uiRequest:$,dialogMode:D="inline",historySearch:L,maxVisibleSelectOptions:X=5,reviewHint:v,todoSurfaceRows:ie=0,activityBarVisible:Te=!1}=e,G=Math.max(0,Math.floor(ie)),q=a?et(a,Math.max(1,n-2)):0,M=c?et(c,Math.max(1,n-2)):0,C=Te?Math.max(1,M):M,Z=l?et(l,Math.max(1,n-2)):0,Re=d?et(d,Math.max(1,n-2)):0,Ie=m?et(m,Math.max(1,n-2)):0,Se=p?et(p,Math.max(1,n-2)):0,ce=g?et(g,Math.max(1,n-2)):0,Ne=N1(r,n,s),ae=x?8:0,Y=T?$b+Pb+Xd().reduce((_,F)=>_+et(F.title,Math.max(1,n-qg))+et(F.items.map(J=>J.label).join(" | "),Math.max(1,n-qg)),0):0,Q=et(w,Math.max(1,n-2)),be=0;if(I&&O){let _=Math.max(1,n-4);be=3+et(`[Confirm] ${I}`,_)+et(O,_)}let ve=0,lt=0;if($){let _=Math.max(1,n-4);$.kind==="select"?(lt=Math.min(X,$.options.length),ve=3+et(`[Select] ${$.title}`,_)+$.options.slice(0,lt).reduce((F,J,Be)=>F+et(`${Be+1}. ${J.label}${J.description?` - ${J.description}`:""}`,_),0)+($.options.length>lt?2:0)+et(`Choice: ${$.buffer||"(type a number)"}`,_)+1+($.error?et($.error,_):0)):ve=3+et(`[Input] ${$.prompt}`,_)+($.defaultValue!==void 0?et(`Default: ${$.defaultValue}`,_):0)+et(`Value: ${$.buffer||"(type your response)"}`,_)+1+($.error?et($.error,_):0)}let Ee=0;if(L){let _=Math.max(1,n-4);Ee=3+et(`Query: ${L.query||"(type to search)"}`,_)+(L.matchCount===0?et("No matches yet",_):et(`${Math.max(1,L.matchCount)} matches`,_)+et(L.selectedExcerpt||"",_))+1}let je=v?et(v,Math.max(1,n-2)):0,xe=q+C+G+Z+Re+Ie+Ne+Y+Se+je+(y==="inline"?ae:0)+(D==="inline"?be+ve+Ee:0),Rt=(y==="overlay"?ae:0)+(D==="overlay"?be+ve+Ee:0),Qe=xe+ce+Q,ee=Math.max(1,t-Qe);return{messageRows:ee,reservedBottomRows:Qe,headerRows:q,activityRows:C,pendingInputRows:Z,stashNoticeRows:Re,notificationRows:Ie,workStripRows:ce,inputRows:Ne,suggestionsRows:ae,helpRows:Y,statusNoticeRows:Se,statusRows:Q,confirmRows:be,uiRequestRows:ve,historySearchRows:Ee,footerRows:xe,overlayRows:Rt,visibleSelectOptions:lt,reviewHintRows:je,todoSurfaceRows:G,slots:[{name:"transcript",rows:ee},{name:"footer",rows:xe},{name:"overlay",rows:Rt},{name:"status",rows:Q},{name:"task-bar",rows:ce}]}}i(Lb,"calculateViewportBudget");function Ob(e,t={}){let n=Oi(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(Ob,"createTranscriptDisplayState");function Db(e){return{...e,surface:"transcript",jumpToLatestAvailable:e.pendingLiveUpdates>0}}i(Db,"enterTranscriptMode");function Nb(e){return{...e,surface:"prompt",scrollAnchor:0,jumpToLatestAvailable:!1,selectionMode:"none",selectedItemId:void 0,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0,pendingLiveUpdates:0}}i(Nb,"exitTranscriptMode");function Bb(e,t){let n=Math.max(0,t);return{...e,pendingLiveUpdates:n,jumpToLatestAvailable:e.surface==="transcript"?n>0:e.scrollAnchor>0}}i(Bb,"setTranscriptPendingLiveUpdates");function Hb(e,t){let n=Math.max(0,t);return{...e,scrollAnchor:n,jumpToLatestAvailable:e.surface==="transcript"?e.pendingLiveUpdates>0:n>0}}i(Hb,"setTranscriptScrollAnchor");function Fb(e){return{...e,surface:"prompt",scrollAnchor:0,jumpToLatestAvailable:!1,selectionMode:"none",selectedItemId:void 0,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0,pendingLiveUpdates:0}}i(Fb,"jumpTranscriptToLatest");function Wb(e,t){return{...e,stickyPromptVisible:t}}i(Wb,"setTranscriptStickyPromptVisible");function Rs(e,t){return{...e,selectedItemId:t,selectionMode:t?"message":"none"}}i(Rs,"setTranscriptSelectedItem");function Ub(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(Ub,"openTranscriptSearch");function jb(e){return{...e,searchMode:"closed",searchAnchorItemId:void 0,currentMatchIndex:0}}i(jb,"closeTranscriptSearch");function Gb(e,t){return{...e,currentMatchIndex:Math.max(-1,t)}}i(Gb,"setTranscriptSearchMatchIndex");function Kb(e){return e.supportsFullscreenLayout&&e.ownsViewportByDefault}i(Kb,"shouldWindowTranscript");function Vb(e){return e.surface==="transcript"}i(Vb,"shouldPauseLiveTranscript");function Qg(e){return e.supportsSelection}i(Qg,"ownsTranscriptSelectionPath");function Yd(e,t,n){if(!(!Qg(e)||!n))return t.includes(n)?n:void 0}i(Yd,"resolveTranscriptSelectedItemId");function zb(e){return e.supportsSelection&&e.supportsCopyOnSelect}i(zb,"supportsPassiveTranscriptCopyOnSelect");function Xb(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(Xb,"buildTranscriptBrowseHint");var Yb="Slash commands cannot be queued mid-task. Press Esc to abort the current task, then run the command.",qb="slash-guard";function Qb(e){return e.trimStart().startsWith("/")}i(Qb,"isSlashCommandText");var B1=`
|
|
360
|
+
|
|
361
|
+
---
|
|
362
|
+
|
|
363
|
+
`;async function Jb(e){let{initialPrompt:t,runRound:n,shiftPendingPrompt:o,onRoundComplete:r,onBeforeQueuedRound:s,shouldContinue:a=i(()=>!0,"shouldContinue")}=e,c=t,l=await n(c);for(;;){if(await r?.(l),!a(l))return l;let d=[];for(;;){let m=o();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(B1),await s?.(c),l=await n(c)}}i(Jb,"runQueuedPromptSequence");function ev(e){return e.itemsLength>0||e.currentResponse.length>0||e.thinkingContent.length>0||e.activeToolCallsLength>0}i(ev,"hasTranscriptInputActivity");function H1(e){return e.keyName==="mouse"&&e.hasMouse&&e.usesManagedMouseClicks&&e.supportsMouseTracking&&e.usesRendererMouseTracking}i(H1,"shouldHandleManagedTranscriptMouse");function Zb(e){return e.usesManagedMouseWheel&&e.supportsWheelHistory&&e.hasTranscript}i(Zb,"shouldHandleManagedTranscriptWheel");function tv(e){if(H1({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"?Zb({usesManagedMouseWheel:e.usesManagedMouseWheel,supportsWheelHistory:e.supportsWheelHistory,hasTranscript:e.hasTranscript})?{kind:"scroll-by",delta:e.reviewWheelStep}:{kind:"none"}:e.keyName==="wheeldown"?Zb({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(tv,"resolveTranscriptPointerAction");function F1(e){return e.isTranscriptMode&&e.hasTextSelection}i(F1,"shouldDeferInterruptToTranscriptSelectionCopy");function nv(e){return e.ctrl&&e.keyName==="c"?F1({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(nv,"resolveStreamingInterruptAction");function ov(e){let{key:t,isTranscriptMode:n,isHistorySearchActive:o,historySearchMatchCount:r,hasTextSelection:s,hasFocusedItem:a,canCopySelectedItem:c,canCopySelectedToolInput:l,canToggleSelectedDetail:d,canCycleTranscriptSelection:m}=e;if(t.name==="pageup")return{kind:"scroll-page-up"};if(o){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&&!o&&!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"?r===0?{kind:"none"}:{kind:"search-match-nav",direction:t.shift?"prev":"next"}:{kind:"none"}:{kind:"none"}}i(ov,"resolveTranscriptKeyboardAction");function rv(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(rv,"executeTranscriptKeyboardAction");function zr(e){let t=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,n=/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,o=/\u001b[@-_]/g;return e.replace(t,"").replace(n,"").replace(o,"")}i(zr,"stripAnsi");function W1(e){return e.tools.map(n=>`tool: ${n.name}`).join(`
|
|
364
|
+
`)}i(W1,"serializeToolGroup");function U1(e){switch(e.type){case"thinking":return null;case"user":return`user: ${zr(e.text)}`;case"assistant":return`assistant: ${zr(e.text)}`;case"system":return`system: ${zr(e.text)}`;case"info":return`info: ${zr(e.text)}`;case"error":return`error: ${zr(e.text)}`;case"event":return`event: ${zr(e.text)}`;case"hint":return`hint: ${zr(e.text)}`;case"tool_group":return W1(e);default:return e}}i(U1,"serializeOne");function j1(e){let t=[];for(let n of e){let o=U1(n);o!==null&&o!==""&&t.push(o)}return t.join(`
|
|
365
|
+
|
|
366
|
+
`)}i(j1,"serializeTranscriptForScrollback");function iv(e){let{items:t,writeToScrollback:n,exitAltScreen:o,enterAltScreen:r}=e,s=j1(t);o(),s.length>0&&n(`${s}
|
|
367
|
+
`),r()}i(iv,"dumpTranscriptToNativeScrollback");function G1(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(`
|
|
368
|
+
`)}).join(`
|
|
369
|
+
`);case"assistant":case"user":case"system":case"thinking":case"error":case"info":case"hint":return e.text;default:return""}}i(G1,"buildSearchText");function K1(e,t){let n=e.replace(/\s+/g," ").trim();if(!n)return"";let o=n.toLowerCase(),r=t.toLowerCase(),s=o.indexOf(r);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(K1,"buildExcerpt");function sv(e){return e.map((t,n)=>({itemId:t.id,itemIndex:n,searchText:G1(t)}))}i(sv,"createTranscriptSearchIndex");function av(e,t){let n=t.trim().toLowerCase();return n?e.flatMap(o=>{let r=o.searchText;return r.toLowerCase().includes(n)?[{itemId:o.itemId,itemIndex:o.itemIndex,excerpt:K1(r,t.trim())}]:[]}):[]}i(av,"searchTranscriptIndex");function Jg(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(Jg,"stepTranscriptSearchMatch");function cv(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(cv,"buildTranscriptSearchSummary");function lv(e,t,n){if(t.length===0||!n)return 0;let o=t.findIndex(a=>a.itemId===n);if(o>=0)return o;let r=e.find(a=>a.itemId===n)?.itemIndex;if(r===void 0)return 0;let s=t.findIndex(a=>a.itemIndex>=r);return s>=0?s:0}i(lv,"resolveTranscriptSearchMatchIndex");function uv(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:V1(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(uv,"buildTranscriptSelectionSummary");function V1(e){return e.tools.length===1?`Tool call: ${e.tools[0]?.name??"tool"}`:`Tool group: ${e.tools.length} calls`}i(V1,"summarizeToolGroup");function dv(e){return e.map(t=>t.id)}i(dv,"getSelectableTranscriptItemIds");function fv(e,t,n){if(e.length===0)return;if(!t)return n==="next"?e[0]:e[e.length-1];let o=e.indexOf(t);return o===-1?n==="next"?e[0]:e[e.length-1]:n==="next"?e[Math.min(e.length-1,o+1)]:e[Math.max(0,o-1)]}i(fv,"moveTranscriptSelection");function Zg(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(`
|
|
370
|
+
`)}).join(`
|
|
371
|
+
|
|
372
|
+
`);case"assistant":case"user":case"system":case"thinking":case"error":case"info":case"hint":return e.text;default:return}}i(Zg,"buildTranscriptCopyText");function mv(e){if(!e||e.type!=="tool_group")return;let t=e.tools.map(n=>{if(!n.input)return;let o=typeof n.input=="string"?n.input:JSON.stringify(n.input,null,2);if(o?.trim())return[`Tool: ${n.name}`,o].join(`
|
|
373
|
+
`)}).filter(n=>!!n);return t.length>0?t.join(`
|
|
374
|
+
|
|
375
|
+
`):void 0}i(mv,"buildTranscriptToolInputCopyText");import{useCallback as wc,useRef as z1,useState as pv}from"react";function gv(e){let{state:t,ownsViewport:n,isAwaitingUserInteraction:o,isHistorySearchActive:r,isTranscriptMode:s,historySearchQuery:a}=e,c=Xb(t),l;if(t.supportsStickyPrompt&&t.stickyPromptVisible)if(r){let m=a.trim();l={visible:!0,label:m?`Searching transcript for "${m}"`:"Searching transcript"}}else s?l={visible:!0,label:"Transcript Mode"}:o&&(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(gv,"buildTranscriptChromeModel");function hv(e){return Math.max(1,e-2)}i(hv,"resolveTranscriptPageSize");function yv(e){return Math.max(3,Math.floor(e/4))}i(yv,"resolveTranscriptWheelStep");function X1(e,t){return Math.max(0,e+t)}i(X1,"incrementTranscriptScrollOffset");function xv(e,t,n){let o=Math.max(0,t-n);return Math.min(Math.max(0,e),o)}i(xv,"clampTranscriptScrollOffset");function wv(){let e=z1(null),[t,n]=pv(0),[o,r]=pv(!0),s=wc(m=>{n(Math.max(0,m))},[]),a=wc(m=>{r(m)},[]),c=wc(m=>{if(e.current){e.current.scrollTo(m);return}n(Math.max(0,m)),r(m===0)},[]),l=wc(m=>{if(e.current){e.current.scrollBy(m);return}n(p=>X1(p,m)),r(!1)},[]),d=wc(()=>{if(e.current){e.current.scrollToBottom();return}n(0),r(!0)},[]);return{scrollRef:e,scrollOffset:t,sticky:o,setScrollOffset:n,setSticky:r,handleScrollTopChange:s,handleStickyChange:a,scrollTo:c,scrollBy:l,scrollToBottom:d}}i(wv,"useTranscriptViewportScrollController");function Sv(e){let{items:t,renderModel:n,terminalWidth:o,transcriptMaxLines:r,viewportRows:s,itemId:a,visibleRows:c,expandedItemKeys:l,showDetailedTools:d=!1}=e;if(!a||c.length===0)return!1;let p=(n?.sections??gs(t,o,r,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(Sv,"isTranscriptItemVisible");function Tv(e){let{items:t,renderModel:n,terminalWidth:o,transcriptMaxLines:r,viewportRows:s,itemId:a,expandedItemKeys:c,showDetailedTools:l=!1}=e,d=n?.sections??gs(t,o,r,l,c);return yC(d,a,s)}i(Tv,"resolveTranscriptSelectionOffset");function Cv(e){let{items:t,renderModel:n,selectedItemId:o,terminalWidth:r=80,transcriptMaxLines:s=1e3,viewportRows:a,scrollOffset:c=0,expandedItemKeys:l,showDetailedTools:d=!1,preferViewportAnchor:m=!1}=e;if(o&&t.some(p=>p.id===o))return o;if(m&&c>0&&a&&a>0){let p=n?.sections??gs(t,r,s,d,l),g=n?.rows??Wr(p),y=og(g,a,c)[0]?.key,T=y?p.find(w=>w.rows.some(I=>I.key===y)):void 0;if(T?.key)return T.key}return t[t.length-1]?.id}i(Cv,"resolveTranscriptSearchAnchorItemId");function bv(e){let t=Pa(e.stickyHeader),n=Su(t,e.width),o=Math.max(0,e.topChromeRows??0);return{contentWindow:e.window,topOffsetRows:n+o,stickyHeaderRows:n,topChromeRows:o}}i(bv,"resolveTranscriptOwnedWindowGeometry");function Y1(e){return e.text===" "?"":e.text}i(Y1,"normalizeTranscriptRowText");function eh(e){let t=new Map;return e.forEach((n,o)=>{t.set(n.key,o)}),t}i(eh,"buildTranscriptRowIndexByKey");function q1(e,t={}){let n=Math.max(0,e.indent??0),o=e.spinner&&t.animateSpinners!==!1?2:0;return 1+n+o}i(q1,"resolveTranscriptTextStartColumn");function vv(e,t={}){let n=Math.max(0,t.topOffsetRows??0),o=t.rowIndexByKey??eh(t.allRows??e),r=e.map((s,a)=>{let c=Y1(s),l=q1(s,t),d=Qo(c);return{key:s.key,row:s,modelRowIndex:o.get(s.key)??a,screenRow:n+a+1,text:c,textLength:d,textStartColumn:l,textEndColumn:l+TC(c)}});return{rows:r,topRow:r[0]?.screenRow??n+1,bottomRow:r[r.length-1]?.screenRow??n,viewportHeight:Math.max(0,t.viewportHeight??e.length)}}i(vv,"buildTranscriptScreenBuffer");function Q1(e,t){let n=Math.max(1,Math.floor(t));return CC(e.text,n-e.textStartColumn)}i(Q1,"clampTextColumn");function th(e,t){return{screenRow:e,point:{rowKey:e.key,modelRowIndex:e.modelRowIndex,column:Q1(e,t)}}}i(th,"toHit");function nh(e,t,n){let o=e.rows.find(r=>r.screenRow===t);return o?th(o,n):void 0}i(nh,"hitTestTranscriptScreen");function oh(e,t,n){if(e.rows.length!==0)return t<=e.topRow?th(e.rows[0],n):t>=e.bottomRow?th(e.rows[e.rows.length-1],n):nh(e,t,n)}i(oh,"clampTranscriptScreenHit");function Iv(e){return e.text===" "?"":e.text}i(Iv,"normalizeTranscriptRowText");function kv(e,t){return e.modelRowIndex!==t.modelRowIndex?e.modelRowIndex-t.modelRowIndex:e.column-t.column}i(kv,"comparePoints");function Rv(e,t,n,o={}){if(e.length===0)return;let[r,s]=kv(t,n)<=0?[t,n]:[n,t],a=o.selectFullRowOnCollapsed===!0,c=kv(t,n)===0,l=e[r.modelRowIndex],d=e[s.modelRowIndex];if(!l||!d)return;let m=a&&c?{...r,column:0}:r,p=a&&c?{...s,column:Qo(Iv(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 I=Iv(w),O=Qo(I),$=T===m.modelRowIndex?m.column:0,D=T===p.modelRowIndex?p.column:O,L=Math.max(0,Math.min($,O)),X=Math.max(L,Math.min(D,O)),v=hs(I,L,X);X>L&&(g.set(w.key,{start:L,end:X}),y+=X-L),x.push(v)}if(g.size!==0)return{anchor:t,focus:n,rowRanges:g,rowCount:x.length,charCount:y,text:x.join(`
|
|
376
|
+
`)}}i(Rv,"buildTranscriptScreenSelection");function Ev(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(Ev,"buildTranscriptScreenSelectionSummary");function Mv(e,t){return e.rows.length===0?0:t<e.topRow?1:t>e.bottomRow?-1:0}i(Mv,"resolveTranscriptDragEdgeScrollDirection");function qd(e){return e?e.map(t=>({label:t.label,value:t.value,description:t.description})):[]}i(qd,"toSelectOptions");function rh(e){return e.question}i(rh,"getAskUserDialogTitle");function J1(e){switch(e){case"confirm":return te("waiting.confirm");case"select":return te("waiting.select");case"input":return te("waiting.input")}}i(J1,"formatPromptWaitingText");function Av(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(Av,"buildPromptPlaceholderText");function _v(e){if(e.isTranscriptMode)return;if(e.waitingReason)return{kind:"waiting",text:J1(e.waitingReason),showSpinner:!1};if(!e.isLoading)return;let t=sg({activeToolCount:e.streamingState.activeToolCalls.filter(n=>n.status===P.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(_v,"buildPromptActivityViewModel");function $v(e,t,n){if(e){if(e.userOverrideContextWindow!==void 0)return e.contextWindow===e.userOverrideContextWindow?e:{...e,contextWindow:e.userOverrideContextWindow};try{let r=n(t.provider)?.getEffectiveContextWindow?.(t.model);if(r!==void 0&&r!==e.contextWindow)return{...e,contextWindow:r};if(r!==void 0)return e}catch{}return e}}i($v,"resolveEffectiveCompactionInfo");function Pv(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===P.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(Pv,"buildSurfaceStatusBarProps");function Lv(e){let t=Qg(e.state),n=t?Yd(e.state,e.selectableItemIds,e.selectedItemId):void 0,o=n?e.selectableItemIds.indexOf(n):-1;return{selectionEnabled:t,selectedItemId:n,selectedItemIndex:o,position:n?{current:Math.max(1,o+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&&zb(e.state)},toggleDetail:t&&!!n,navigationCapabilities:{selection:t&&!!n&&e.selectableItemIds.length>0}}}i(Lv,"buildTranscriptSelectionRuntimeState");function Ov(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(Ov,"buildTranscriptSelectionViewModel");function Dv(e){return{query:e.query,matches:e.matches,currentMatchIndex:e.currentMatchIndex,anchorItemId:e.anchorItemId,statusText:e.useOverlaySurface?void 0:e.statusText}}i(Dv,"buildTranscriptSearchViewModel");function Z1(e,t){return e===0?0:t<0?-1:Math.min(t,e-1)}i(Z1,"clampTranscriptSearchSelectedIndex");function eO(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(eO,"buildTranscriptSearchDetailText");function Nv(e){let t=Z1(e.matches.length,e.selectedIndex),n=cv(e.matches,t),o=eO({isHistorySearchActive:e.isHistorySearchActive,historySearchQuery:e.historySearchQuery,matches:e.matches,clampedSelectedIndex:t});return{clampedSelectedIndex:t,statusText:n,detailText:o,searchState:Dv({query:e.historySearchQuery,matches:e.matches,currentMatchIndex:t,anchorItemId:e.anchorItemId,statusText:n,useOverlaySurface:e.useOverlaySurface})}}i(Nv,"buildTranscriptSearchChrome");function tO(e=!1){return`\u2190/\u2192 enter select mode | Ctrl+E ${e?"collapse":"show all"} | Mouse drag selects text`}i(tO,"buildDefaultTranscriptSecondaryText");function Bv(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(Bv,"buildFooterNotifications");function Hv(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(Hv,"buildBaseFooterNotices");function Fv(e){if(e.inputText.trim()&&(e.isTranscriptMode||e.isHistorySearchActive))return"Draft preserved while viewing transcript"}i(Fv,"buildStashNoticeText");function Wv(e){return[...e]}i(Wv,"buildPromptFooterNotices");function nO(e){let n=(e.isHistorySearchActive?[e.historySearchDetailText]:[e.selectionSummary,e.actionSummary]).filter(o=>!!(o&&o.trim().length>0));return n.length===0?tO(e.showAllActive):n.join(" | ")}i(nO,"buildTranscriptFooterSecondaryText");function oO(e){let t=[];return e&&t.push(e),t}i(oO,"buildTranscriptFooterBudgetNotices");function Uv(e){let t=e.selectionState?.copyCapabilities,n=e.selectionState?.navigationCapabilities,r=Ev(e.textSelection),s=e.textSelection?xs({copyMessage:!0,copyToolInput:!1,copyOnSelect:!!t?.copyOnSelect,toggleDetail:!1,selectionNavigation:!1,matchNavigation:!1,dismissAction:"clear"}):e.selectionState?.itemSummary?xs({copyMessage:!!t?.message,copyToolInput:!!t?.toolInput,copyOnSelect:!!t?.copyOnSelect,toggleDetail:!!e.selectionState?.toggleDetail,selectionNavigation:!!n?.selection,matchNavigation:!1,dismissAction:"clear"}):void 0,a=nO({isHistorySearchActive:e.isHistorySearchActive,historySearchDetailText:e.historySearchDetailText,selectionSummary:r,actionSummary:s,showAllActive:e.showAllActive,baseFooterNotices:e.baseFooterNotices});return{selectionSummary:r,actionSummary:s,secondaryText:a,budgetNotices:oO(a)}}i(Uv,"buildTranscriptFooterViewModel");import{jsx as iY,jsxs as sY}from"react/jsx-runtime";function jv(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(jv,"formatAmaWorkStripText");function Gv(e){return e.replace(/^\[[^\]]+\]\s*/,"").trim()}i(Gv,"stripLiveActivityPrefix");function Kv(e){let t=[],n=e.showPrimary??!0;if(e.isLoading&&n){let l=e.currentTool?Gv(rd(e.currentTool,e.toolInputContent??"",e.toolInputCharCount??0)):void 0,d=e.liveActivityLabel?Gv(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[o,r,s,...a]=t,c=[o,r,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(Kv,"buildBackgroundTaskViewModel");function Vv(e,t){if(!(!t||!e||e.agentMode!=="ama"))return jv(e.childFanoutClass,e.childFanoutCount)}i(Vv,"buildAmaWorkStripFromStatus");function ih(e){let t=Vv(e.status,e.isLoading);return{workStripText:t,backgroundTask:Kv({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(ih,"buildAmaSummaryViewModel");function sh(e){return{...e,items:[...e.items],managedLiveEvents:[...e.managedLiveEvents??[]]}}i(sh,"captureTranscriptSnapshot");function zv(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(zv,"countPendingTranscriptUpdates");function Xv(e){return e.snapshot?[...e.snapshot.items]:e.surface==="transcript"?[...e.transcriptItems]:[...e.promptItems]}i(Xv,"resolveTranscriptSurfaceItems");function Yv(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:o,...r}=n;t.push(r);break}default:break}return t}i(Yv,"buildPromptSurfaceItems");function qv(e,t){return e.enabled?t==="transcript"?e.transcriptShell:e.promptShell:"main-screen"}i(qv,"resolveFullscreenShellMode");function rO(e,t){return e.enabled&&qv(e,t)==="virtual"}i(rO,"shouldUseRendererViewportShell");function Qv(e,t){let n=qv(e,t),o=e.enabled&&n==="virtual",r=e.enabled&&n==="virtual",s=o&&(e.mouseWheel||e.mouseClicks),a=s&&e.mouseClicks,c=r&&e.mouseWheel;return{shellMode:n,usesAlternateScreenShell:o,usesRendererViewportShell:r,usesRendererMouseTracking:s,usesManagedMouseClicks:a,usesManagedMouseWheel:c,usesManagedSelection:r,usesManagedWheelHistory:c,usesNativeMainScreenScrollback:!r}}i(Qv,"resolveTranscriptInteractionPolicy");function Jv(e,t,n){return rO(e,t)?t==="transcript"||n:!1}i(Jv,"shouldOwnTranscriptViewport");var iO=500,sO=1,aO=/[\p{L}\p{N}_/.\-+~\\]/u;function cO(e){return e.text===" "?"":e.text}i(cO,"normalizeTranscriptRowText");function Zv(e,t){return e.modelRowIndex!==t.modelRowIndex?e.modelRowIndex-t.modelRowIndex:e.column-t.column}i(Zv,"comparePoints");function ah(e){return e===""||/\s/.test(e)?0:aO.test(e)?1:2}i(ah,"charClass");function e0(e){let t=e.timeoutMs??iO,n=e.distance??sO,o=e.time-e.previous.time<=t,r=Math.abs(e.row-e.previous.row)<=n&&Math.abs(e.column-e.previous.column)<=n,s=o&&r?Math.min(3,e.previous.count+1):1;return{time:e.time,row:e.row,column:e.column,count:s}}i(e0,"resolveTranscriptMultiClickState");function Qd(e,t,n){let o=e[t.modelRowIndex];if(!o)return;let r=cO(o);if(n==="line")return{kind:n,start:{...t,column:0},end:{...t,column:Qo(r)}};let s=Qo(r);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=ah(fd(r,a)),l=a,d=a+1;for(;l>0&&ah(fd(r,l-1))===c;)l-=1;for(;d<s&&ah(fd(r,d))===c;)d+=1;return{kind:n,start:{...t,column:l},end:{...t,column:d}}}i(Qd,"resolveTranscriptSelectionSpanAt");function ch(e,t){return Zv(t.end,e.start)<0?{anchor:e.end,focus:t.start}:Zv(t.start,e.end)>0?{anchor:e.start,focus:t.end}:{anchor:e.start,focus:e.end}}i(ch,"extendTranscriptSelectionSpan");var n0="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 lh(e,t){if(Qt(e))return[t.getGuardrail()]}i(lh,"buildAutoModeGuardrails");function uO(e,t){return e.reasoningMode?e.reasoningMode:t.reasoningMode?t.reasoningMode:e.thinking===!0||t.thinking===!0?"auto":"off"}i(uO,"resolveInitialReasoningMode");function dO(e,t){return!(t||e.role!=="evaluator"||e.signal!=="COMPLETE")}i(dO,"shouldFilterSidecarAcceptEntry");function o0(e,t){let n=e.managedTask;if(!n)return[];let o=t?.verifierLog??process.env.KODAX_VERIFIER_LOG==="1",r=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"),I=!y||x==="No textual output produced.";return p.status!=="completed"&&(T||w||I)||(T||w)&&I},"isInterruptedCancellation"),s=mO(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=>!r(p)).filter(p=>!dO(p,o)).filter(p=>e.interrupted||!(p.assignmentId===c&&(p.round??1)===l)).map(p=>{let g=p.output?.trim()??"",x=p.summary?.trim()??"",y=g?Pr(g):"",T=x?Pr(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}]
|
|
377
|
+
${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(o0,"buildManagedTaskTranscriptItems");function fO(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,o]=t,r=n.startsWith("[")?`${n} ${o}`:`${n} / ${o}`;return r.length>220?`${r.slice(0,217)}...`:r}i(fO,"buildManagedTranscriptCompactText");function u0(e){return e===`[${te("managed.completed")}]`||e===`[${te("managed.completed.blocked")}]`||e===`[${te("managed.completed.continuation")}]`}i(u0,"isCompletionTranscriptItem");function r0(e){let t=fO(e);return{type:"event",icon:u0(e)?"\u2713":">",text:e,...t&&t!==e?{compactText:t}:{}}}i(r0,"toManagedTranscriptEventItem");function Xr(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(Xr,"toCreatableHistoryItem");function mO(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(r=>!!r).join(`
|
|
378
|
+
`)}i(mO,"buildManagedTaskRoutingTranscript");function pO(e,t=240){let n=e.trim();return n?n.length>t?`${n.slice(0,t-3)}...`:n:""}i(pO,"truncateToolPreview");function gO(e,t=800){let n=e.trim();return n?n.length>t?`${n.slice(0,t-3)}...`:n:""}i(gO,"truncateToolOutputPreview");function mh(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(mh,"formatManagedLiveActivityLabel");function tr(e,t){return mh(`[Tools] ${nd(e)}`,t)??`[Tools] ${nd(e)}`}i(tr,"formatManagedLiveToolLabel");function uh(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(uh,"areManagedLiveItemsEquivalent");function hO(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(hO,"localizeManagedCompletionSummary");function yO(e){if(e.events&&e.events.length>0)return e.events.reduce((o,r)=>{let s=r.summary.trim(),a=(r.detail??r.summary).trim();if(!s||!a)return o;let c=`managed-live-${r.key}`,l=Date.now(),d=r.persistToHistory??e.persistToHistory??!1;if(r.presentation==="thinking")return o.push({item:{id:c,type:"thinking",timestamp:l,text:a,...s!==a?{compactText:s}:{}},persistToHistory:d}),o;if(r.presentation==="assistant")return o.push({item:{id:c,type:"assistant",timestamp:l,text:a,...s!==a?{compactText:s}:{}},persistToHistory:d}),o;let m=r.kind==="completed";if(m&&!ef)return o;let p=m?`[${hO(s)}]`:void 0,g=p??s,x=p??a;return o.push({item:{id:c,type:"event",timestamp:l,text:x,icon:r.kind==="warning"?"!":m?"\u2713":">",...g!==x?{compactText:g}:{}},persistToHistory:d}),o},[]);if(e.phase==="completed"&&!ef)return[];let t=xc(e),n=xc(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(yO,"buildManagedLiveEventDrafts");function d0(e){return e.replace(/^\[[^\]]+\]\s+/,"").replace(/^[A-Za-z][A-Za-z0-9_-]*:\s*/,"").trim()}i(d0,"stripToolRolePrefix");function i0(e){return d0(e).toLowerCase()}i(i0,"normalizeToolNameForMatch");function ph(e){return oT(e)?"":Pr(e).trim()}i(ph,"sanitizeInterruptedAssistantText");function s0(e){return!!(e?.activeWorkerId&&!e.childFanoutClass&&(e.phase==="preflight"||e.phase==="worker"))}i(s0,"isForegroundManagedStreamingStatus");function xO(e,t,n){let o=[],r=n?.infoItems??[],s=gh({thinking:e,toolCalls:n?.toolCalls,toolNames:n?.toolNames});for(let c of r){let l=c.trim();l&&o.push({type:"info",text:l})}o.push(...s);let a=ph(t);return a&&o.push({type:"assistant",text:`${a}
|
|
379
|
+
|
|
380
|
+
[Interrupted]`}),o}i(xO,"buildInterruptedPersistenceItems");function gh({thinking:e,response:t,toolCalls:n,toolNames:o}){let r=[],s=e?.trim()??"",a=t?.trim()??"",c=n&&n.length>0?[...n]:[],l=o&&o.length>0?[...o]:[];return s&&r.push({type:"thinking",text:s}),c.length>0?r.push({type:"tool_group",tools:c}):!s&&!a&&l.length>0&&r.push({type:"info",icon:"*",text:`Tools: ${l.join(", ")}`}),a&&r.push({type:"assistant",text:a}),r}i(gh,"buildRoundHistoryItems");function f0(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(f0,"toPersistedUiHistoryItem");var a0=150,c0=50,ef=process.env.KODAX_TRANSCRIPT_HARNESS_MARKERS==="1";function Yr(e){if(e.length===0)return[];let t=[];for(let o=0;o<e.length;o+=1)e[o]?.type==="user"&&t.push(o);let n=[...e];if(t.length>c0){let o=t[t.length-c0]??0;n=e.slice(o)}if(n.length>a0){let o=n.slice(-a0),r=o.findIndex(s=>s.type==="user");n=r>0?o.slice(r):o}return[...n]}i(Yr,"trimPersistedUiHistorySnapshot");function Es(e){if(e)return Yr(e)}i(Es,"normalizePersistedUiHistory");function l0(e){return Yr(e.map(t=>f0(t)).filter(t=>!!t))}i(l0,"serializeUiHistorySnapshot");function wO(e){return e.map(t=>f0(t)).filter(t=>!!t)}i(wO,"serializeCreatableHistoryItems");function Jd(e,t){return t.length===0?Yr(e):Yr([...e,...wO(t)])}i(Jd,"appendPersistedUiHistorySnapshot");function Zd(e,t,n){console.log((e==="block"?Ve.red:Ve.yellow)(t)),n.forEach(o=>console.log(Ve.dim(o)))}i(Zd,"logSessionTransitionGuard");var dh=i(({config:e,sessionId:t,workingDir:n,terminalWidth:o,compactionInfo:r})=>{let s=ne("dark"),a=e.model??Xn(e.provider)??e.provider,c=wr(e.provider,e.model),l=Bl(c),d=Math.min(60,o-4),m=r?Math.round(r.contextWindow/1e3):0,p=r?Math.round(r.contextWindow*r.triggerPercent/100/1e3):0;return Kt(k,{flexDirection:"column",marginBottom:1,children:[Ng.map((g,x)=>se(b,{color:s.colors.primary,children:g},x)),Kt(k,{children:[Kt(b,{bold:!0,color:s.colors.text,children:[" v",Mi]}),se(b,{dimColor:!0,children:" | "}),Kt(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}`})]}),r&&Kt(k,{children:[se(b,{dimColor:!0,children:" Context: "}),Kt(b,{dimColor:!0,children:[m,"k"]}),se(b,{dimColor:!0,children:" | Compaction: "}),se(b,{color:r.enabled?s.colors.success:void 0,dimColor:!r.enabled,children:r.enabled?"on":"off"}),se(b,{dimColor:!0,children:` @ ${r.triggerPercent}% (${p}k)`})]}),Kt(b,{dimColor:!0,children:[" ","-".repeat(d)]}),Kt(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})]}),Kt(b,{dimColor:!0,children:[" ","-".repeat(d)]})]})},"Banner");function SO(e){let t=e.config.model??Xn(e.config.provider)??e.config.provider,n=wr(e.config.provider,e.config.model),o=Bl(n),r=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${Mi} | ${e.config.provider}/${t} [${o}] | ${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(r)}`,p=[],g=i(y=>{let T=Xt(y.length>0?y.split(`
|
|
381
|
+
`):[""],Math.max(1,e.terminalWidth),0,0);return T.visualLines.length>0?T.visualLines:[""]},"wrapBannerLine"),x=i((y,T,w)=>{g(T).forEach((I,O)=>{p.push({key:`${y}-${O}`,text:I,...w})})},"pushLineRows");return Ng.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(SO,"buildBannerTranscriptSection");function fh(e,t){return t?{...e,sections:[t,...e.sections],rows:[...t.rows,...e.rows]}:e}i(fh,"prependTranscriptSection");var TO=i(({options:e,config:t,context:n,storage:o,rendererMode:r,fullscreenPolicy:s,onExit:a,compactionInfo:c,autoModeBootstrap:l,setAutoModeAskUser:d,setAutoModeEngineChange:m,setCurrentConfigRef:p,onAgentsFilesReload:g,teamModeHandle:x})=>{let{exit:y}=Go(),{stdout:T}=Jn(),{stdin:w,setRawMode:I,isRawModeSupported:O}=_a(),$=es(),{history:D}=ac(),L=t0.useRef(null),X=t0.useRef(Ex()),{addHistoryItem:v,clearHistory:ie,setSessionId:Te}=cc(),G=me(D),q=me(l0(D));Fe(()=>{G.current=D,q.current=l0(D)},[D]),Fe(()=>{Eb()},[]),Fe(()=>{CT()},[]);let M=T.columns||80,C=dc(),Z=me(C);Fe(()=>{Z.current=C},[C]);let{startStreaming:Re,stopStreaming:Ie,abort:Se,startThinking:ce,appendThinkingChars:Ne,appendThinkingContent:ae,stopThinking:Y,clearThinkingContent:Q,setCurrentTool:be,appendToolInputChars:ve,appendToolInputContent:lt,clearToolInputContent:Ee,clearResponse:je,appendResponse:xe,getSignal:Rt,getFullResponse:Qe,getThinkingContent:ee,startNewIteration:A,clearIterationHistory:_,startCompacting:F,stopCompacting:J,setMaxIter:Be,addPendingInput:tt,removeLastPendingInput:ke,shiftPendingInput:Oe,consumePendingInputs:Vt}=fc(),[K,fe]=Ue(!1),[V,Ce]=Ue(t),ot=ue(()=>$v(c,{provider:V.provider,model:V.model},gr),[c,V.provider,V.model]),[Fn,Ps]=Ue(!0),[Wn,FD]=Ue(!0),[$c,Pc]=Ue(0),[hf,Ls]=Ue(!1),[Eh,Un]=Ue(null),xI=ue(()=>Cr(),[]),Os=me(null),Lc=me(null),Mh=me(Promise.resolve()),Oc=me(null),rr=me({requested:!1,uiHistoryOverride:void 0}),Ds=me(null),Ns=me(!1),Bs=me(null),[yf,Dc]=Ue(!0),[xf,Nc]=Ue(""),[He,jn]=Ue(()=>Ob(xI,{rendererMode:r})),[bt,wf]=Ue(!1),[wI,SI]=Ue(0),{scrollRef:TI,scrollOffset:En,sticky:Sf,setScrollOffset:CI,handleScrollTopChange:bI,handleStickyChange:vI,scrollTo:Bc,scrollBy:Hc,scrollToBottom:Fc}=wv(),Tf=me(null),Wc=me(null),Hs=me([]),Uc=me([]),Qr=me(null),Mn=me(null),Ah=me({time:0,row:-1,column:-1,count:0}),[jc,Cf]=Ue(void 0),[ir,bf]=Ue(void 0),[Jr,_h]=Ue(void 0),[tn,II]=Ue(()=>new Set),[vf,$h]=Ue(null),[_t,Ph]=Ue(null),[W,If]=Ue(null),[Gc,Mo]=Ue([]),Zr=ue(()=>{for(let f of Gc)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}},[Gc]),[WD,Fs]=Ue([]),[Ws,kI]=Ue([]),[Kc,ft]=Ue(void 0),[sr,Vc]=Ue(void 0),rt=me(null),kf=me(null),ar=me([]),ei=me([]),un=me([]),nt=me({}),mt=me({activeToolGroupTools:[]}),Lh=me(0),zc=me({itemId:void 0,kind:"thinking",pendingText:""}),An=me(null),RI=80,EI=20,MI=me(null),Xc=ue(()=>[...D,...Ws],[D,Ws]),Rf=ue(()=>{let f=gC(Xc,MI);return f===0?Xc:Xc.slice(f)},[Xc]),Ef=ue(()=>hC(Rf,EI),[Rf]),Us=Rf,$t=me(null),Gn=me(null),Kn=me([]),Pt=me([]),[cr,AI]=Ue([]),lo=me([]),dn=z(f=>{lo.current=f,AI(f)},[]),Oh=z(f=>{ar.current=f,Fs(f)},[]),ti=z(f=>{un.current=f,kI(f)},[]),Dh=z(f=>{let h=f([...un.current]);ti(h)},[ti]),Nh=z(f=>{f.length!==0&&ti([...un.current,...f])},[ti]),Yc=z(f=>{let h=mt.current,S=h.activeToolGroupTools.some(R=>R.status===P.Executing);mt.current={...f?.clearOwner?{}:{workerId:h.workerId,workerTitle:h.workerTitle},...S?{activeToolGroupItemId:h.activeToolGroupItemId,activeToolGroupTools:h.activeToolGroupTools}:{activeToolGroupTools:[]}},f?.clearOwner&&(nt.current={})},[]),js=z(()=>{zc.current={itemId:void 0,kind:"thinking",pendingText:""},An.current&&(clearTimeout(An.current),An.current=null),Yc({clearOwner:!0}),ti([])},[Yc,ti]),qc=z(f=>(Lh.current+=1,`managed-foreground-${f}-${Lh.current}`),[]),fn=z(f=>(Nh([f]),f.id),[Nh]),lr=z((f,h)=>{nt.current.workerId?fn({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()}):v(f)},[v,fn]),uo=z((f,h)=>{if(!f)return;let S;return Dh(R=>R.map(E=>E.id!==f?E:(S=h(E),S))),S},[Dh]),ni=z((f,h)=>{let S=mt.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(j=>j.status===P.Executing);if(f==="thinking"){let j=fn({id:qc("thinking"),type:"thinking",timestamp:R,text:E});return mt.current={...mt.current,activeKind:"thinking",activeThinkingItemId:j,currentTurnThinkingItemId:j,activeAssistantItemId:void 0,...N?{}:{activeToolGroupItemId:void 0,activeToolGroupTools:[]}},j}if(f==="assistant"){let j=fn({id:qc("assistant"),type:"assistant",timestamp:R,text:E});return mt.current={...mt.current,activeKind:"assistant",activeThinkingItemId:void 0,activeAssistantItemId:j,...N?{}:{activeToolGroupItemId:void 0,activeToolGroupTools:[]}},j}let B=fn({id:qc("tool_group"),type:"tool_group",timestamp:R,tools:[]});return mt.current={...mt.current,activeKind:"tool_group",activeThinkingItemId:void 0,activeAssistantItemId:void 0,activeToolGroupItemId:B,activeToolGroupTools:[]},B},[fn,qc]),Ao=z(()=>{An.current&&(clearTimeout(An.current),An.current=null);let f=zc.current;if(!f.pendingText||!f.itemId)return;let h=f.pendingText,S=f.itemId,R=f.kind;f.pendingText="",uo(S,E=>E.type!==R?E:{...E,text:`${E.text}${h}`})},[uo]),Bh=z(()=>{An.current||(An.current=setTimeout(Ao,RI))},[Ao]),Qc=z((f,h)=>{if(!h)return;let S=mt.current.workerTitle,R=ni(f,S),E=zc.current;E.itemId===R&&E.kind===f?E.pendingText+=h:(Ao(),E.itemId=R,E.kind=f,E.pendingText=h),Bh()},[ni,Ao,Bh]),Hh=z(f=>{let h=f.trim();if(!h)return;let S=zc.current;S.kind==="thinking"&&S.pendingText&&(S.pendingText="",An.current&&(clearTimeout(An.current),An.current=null));let R=mt.current.workerTitle?.trim(),E=R?`[${R}] ${h}`:h,N=mt.current.currentTurnThinkingItemId;if(N){uo(N,j=>j.type==="thinking"?{...j,text:E}:j);return}let B=ni("thinking",mt.current.workerTitle);uo(B,j=>j.type==="thinking"?{...j,text:E}:j)},[ni,uo]),_n=z(f=>{Ao();let h=mt.current;if(h.activeToolGroupItemId&&h.activeToolGroupTools.some(B=>B.id===f.id)){let B=h.activeToolGroupTools.map(re=>re.id===f.id?f:re),j=B.every(re=>re.status===P.Success||re.status===P.Error||re.status===P.Cancelled);mt.current={...h,...j?{activeToolGroupItemId:void 0,activeToolGroupTools:[]}:{activeToolGroupTools:B}},uo(h.activeToolGroupItemId,re=>re.type==="tool_group"?{...re,tools:B}:re);return}let S=un.current;for(let B=S.length-1;B>=0;B-=1){let j=S[B];if(j.type!=="tool_group"||!j.tools.some(ye=>ye.id===f.id))continue;let re=j.tools.map(ye=>ye.id===f.id?f:ye);uo(j.id,ye=>ye.type==="tool_group"?{...ye,tools:re}:ye);return}let R=ni("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];mt.current={...mt.current,activeKind:"tool_group",activeToolGroupItemId:R,activeToolGroupTools:N},uo(R,B=>B.type==="tool_group"?{...B,tools:N}:B)},[ni,uo,Ao]),_I=z(f=>{Ao();let h=mt.current,S=h.activeToolGroupTools.some(N=>N.status===P.Executing),R=lo.current.filter(N=>N.status===P.Executing),E=new Set(R.map(N=>N.id));mt.current={workerId:f?.workerId,workerTitle:f?.workerTitle,...S?{activeToolGroupItemId:h.activeToolGroupItemId,activeToolGroupTools:h.activeToolGroupTools}:{activeToolGroupTools:[]}},nt.current={workerId:f?.workerId,workerTitle:f?.workerTitle},Kn.current=[],Pt.current=Pt.current.filter(N=>E.has(N.id)),dn(R),Ee(),be(void 0),Y(),Q(),je(),ft(void 0)},[Ao,Ee,je,Q,be,dn,ft,Y]),$I=z(f=>{if(f.length===0)return[];let h=[],S=[...ar.current],R=[...ei.current];for(let E of f){let N=E.item,B=S.findIndex(j=>j.id===N.id);if(B>=0){let j=S[B];uh(j,N)||(S=S.map((re,ye)=>ye===B?{...N,timestamp:j.timestamp}:re))}else S=[...S,N].slice(-12),h.push(N);if(E.persistToHistory){let j=R.findIndex(re=>re.id===N.id);if(j>=0){let re=R[j];uh(re,N)||(R=R.map((ye,ut)=>ut===j?{...N,timestamp:re.timestamp}:ye))}else R=[...R,N].slice(-48)}}return ei.current=R,(h.length>0||S.some((E,N)=>!uh(E,ar.current[N]??E)||E.id!==ar.current[N]?.id))&&Oh(S),h},[Oh]),Jc=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)},[]),_o=z(f=>{let h=lo.current.filter(S=>S.status===P.Executing);if(h.length!==0){if(f){let S=i0(f);for(let R=h.length-1;R>=0;R-=1){let E=h[R];if(i0(E.name)===S)return E}}return h[h.length-1]}},[]),oi=z(()=>{let f=_o();be(f?d0(f.name):void 0)},[_o,be]),Fh=z(f=>(Jc(f),dn([...lo.current.filter(h=>h.id!==f.id),f]),oi(),f),[dn,oi,Jc]),ri=z((f,h)=>{let S=lo.current.find(E=>E.id===f);if(!S)return null;let R=h(S);return Jc(R),dn(lo.current.map(E=>E.id===f?R:E)),oi(),R},[dn,oi,Jc]),Wh=z((f,h,S)=>{if(f){let E=ri(f,S);if(E)return E}let R=_o(h);return R?ri(R.id,S):null},[_o,ri]),Zc=z((f,h,S,R,E)=>{let N=f??_o(E)?.id;return N?ri(N,B=>({...B,status:h,endTime:Date.now(),error:S,output:R})):null},[_o,ri]),Gs=z((f,h)=>{let S=Date.now(),R=new Map;for(let E of lo.current){if(E.status!==P.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),dn(lo.current.map(E=>R.get(E.id)??E)),oi(),[...R.values()])},[dn,oi]),$o=z(()=>{dn([])},[dn]),{showHelp:Uh,toggleHelp:PI,setShowHelp:jh}=Fg(),LI=z(f=>{Nc(f),Dc(f.trim().length===0)},[]),el=Hr(),Gh=ue(()=>el?el.state.visible&&el.suggestions.length>0:!1,[el]),[Ks,Kh]=Ue(!1),Vh=me($c),Vs=z(()=>{$t.current&&(clearTimeout($t.current),$t.current=null),Gn.current&&(clearTimeout(Gn.current),Gn.current=null)},[]);Fe(()=>{Gh&&!Ks&&Kh(!0)},[Gh,Ks]),Fe(()=>{$c!==Vh.current&&(Vh.current=$c,Ks&&Kh(!1))},[$c,Ks]);let[qe,tl]=Ue(null),ur=me(null),[$e,$n]=Ue(null),nl=me(null),ol=me($e);ol.current=$e;let[Wt,ii]=Ue(""),[rl,Pn]=Ue(0),Mf=me(""),zs=me(void 0),zh=ue(()=>{if(!ot)return;let{contextWindow:f,triggerPercent:h}=ot;return{currentTokens:Eh??n.contextTokenSnapshot?.currentTokens??hr(n.messages),contextWindow:f,triggerPercent:h}},[n.messages,n.contextTokenSnapshot,ot,Eh]),Xs=ue(()=>{if(!qe)return;let f=!!qe.input._alwaysConfirm,h=V.permissionMode==="accept-edits"&&!f;return f?te("confirm.instruction.protected"):h?te("confirm.instruction.always"):te("confirm.instruction.basic")},[qe,V.permissionMode]),it=He.searchMode==="history",oe=He.surface==="transcript",Po=!!qe||!!$e||it,yt=oe?bt?uC:1e3:12,Lo=Qv(s,He.surface),Xh=Lo.shellMode,Af=Lo.usesAlternateScreenShell,si=Lo.usesRendererViewportShell,il=Lo.usesRendererMouseTracking,Yh=Lo.usesManagedMouseClicks,qh=Lo.usesManagedMouseWheel,_f=Lo.usesManagedSelection,xt=Jv(s,He.surface,Kb(He)),Qh=Vb(He),sl=Ks&&!oe,Jh=z(()=>sh({items:Us,managedLiveEvents:[],isLoading:K,isThinking:C.isThinking,thinkingCharCount:C.thinkingCharCount,thinkingContent:C.thinkingContent,currentResponse:C.currentResponse,currentTool:C.currentTool,activeToolCalls:cr,toolInputCharCount:C.toolInputCharCount,toolInputContent:C.toolInputContent,lastLiveActivityLabel:Kc,workStripText:sr,iterationHistory:C.iterationHistory,currentIteration:C.currentIteration,isCompacting:C.isCompacting}),[Us,K,C.isThinking,C.thinkingCharCount,C.thinkingContent,C.currentResponse,C.currentTool,cr,C.toolInputCharCount,C.toolInputContent,Kc,sr,C.iterationHistory,C.currentIteration,C.isCompacting]);Fe(()=>{if(oe){$h(f=>f??Jh());return}$h(null)},[Jh,oe]);let Ys=ue(()=>zv({isTranscriptMode:oe,snapshot:vf,currentItemsLength:Us.length,currentManagedLiveEventsLength:0,isLoading:K,currentResponse:C.currentResponse,thinkingContent:C.thinkingContent,activeToolCallsLength:cr.length}),[cr.length,K,oe,Us.length,C.currentResponse,C.thinkingContent,vf]),Lt=oe?vf:null,$f=ue(()=>Yv(Ef),[Ef]),OI=ue(()=>!!(Ws.length>0||s0(W)),[Ws.length,W]),al=Ws.length>0,Ot=s.streamingPreview&&OI,ai=Xv({surface:"transcript",snapshot:Lt,promptItems:Ef,transcriptItems:Us}),qs=ue(()=>{if(!oe||bt||ai.length<=ng)return ai;let f=ai.slice(-ng),h=ai.length-f.length;return[wC(h,f[0]?.timestamp),...f]},[ai,oe,bt]),st=Lt?.isLoading??K,Je=s.streamingPreview?{isThinking:Ot?!1:C.isThinking,thinkingCharCount:Ot?0:C.thinkingCharCount,thinkingContent:Ot?"":C.thinkingContent,currentResponse:Ot?"":C.currentResponse,currentTool:Ot?void 0:C.currentTool,activeToolCalls:Ot?[]:cr,toolInputCharCount:0,toolInputContent:"",managedLiveEvents:[],lastLiveActivityLabel:Ot?Kc: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:Ot?!1:Lt?.isThinking??C.isThinking,thinkingCharCount:Ot?0:Lt?.thinkingCharCount??C.thinkingCharCount,thinkingContent:Ot?"":Lt?.thinkingContent??C.thinkingContent,currentResponse:Ot?"":Lt?.currentResponse??C.currentResponse,currentTool:Ot?void 0:Lt?.currentTool??C.currentTool,activeToolCalls:Ot?[]:Lt?.activeToolCalls??cr,toolInputCharCount:Ot?0:Lt?.toolInputCharCount??C.toolInputCharCount,toolInputContent:Ot?"":Lt?.toolInputContent??C.toolInputContent,managedLiveEvents:[],lastLiveActivityLabel:Lt?.lastLiveActivityLabel??Kc,iterationHistory:Ot?[]:Lt?.iterationHistory??C.iterationHistory,currentIteration:Lt?.currentIteration??C.currentIteration,isCompacting:Lt?.isCompacting??C.isCompacting}:{isThinking:!1,thinkingCharCount:0,thinkingContent:"",currentResponse:"",currentTool:void 0,activeToolCalls:[],toolInputCharCount:0,toolInputContent:"",managedLiveEvents:[],lastLiveActivityLabel:void 0,iterationHistory:[],currentIteration:Lt?.currentIteration??C.currentIteration,isCompacting:!1},fo=oe?ir:jc,Zh=!!jc,ey=z(()=>sh({items:$f,managedLiveEvents:[],isLoading:K,isThinking:Je.isThinking,thinkingCharCount:Je.thinkingCharCount,thinkingContent:Je.thinkingContent,currentResponse:Je.currentResponse,currentTool:Je.currentTool,activeToolCalls:Je.activeToolCalls,toolInputCharCount:Je.toolInputCharCount,toolInputContent:Je.toolInputContent,lastLiveActivityLabel:Je.lastLiveActivityLabel,iterationHistory:Je.iterationHistory,currentIteration:Je.currentIteration,isCompacting:Je.isCompacting}),[K,$f,Je.activeToolCalls,Je.currentIteration,Je.currentResponse,Je.currentTool,Je.isCompacting,Je.isThinking,Je.iterationHistory,Je.lastLiveActivityLabel,Je.thinkingCharCount,Je.thinkingContent,Je.toolInputCharCount,Je.toolInputContent]);Fe(()=>{if(!Zh){Ph(null);return}Ph(f=>f??ey())},[ey,Zh]);let Qs=_t?.items??$f,Ut=_t?.isLoading??K,Me=_t?{isThinking:_t.isThinking,thinkingCharCount:_t.thinkingCharCount,thinkingContent:_t.thinkingContent,currentResponse:_t.currentResponse,currentTool:_t.currentTool,activeToolCalls:_t.activeToolCalls,toolInputCharCount:_t.toolInputCharCount,toolInputContent:_t.toolInputContent,managedLiveEvents:_t.managedLiveEvents,lastLiveActivityLabel:_t.lastLiveActivityLabel,iterationHistory:_t.iterationHistory,currentIteration:_t.currentIteration,isCompacting:_t.isCompacting}:Je,Et=oe?qs:Qs,Vn=oe?st:Ut,Ge=oe?pe:Me,ty=Ut&&!C.currentResponse&&!C.thinkingContent&&cr.length===0,dr=ue(()=>({config:V,sessionId:n.sessionId,workingDir:e.context?.gitRoot||process.cwd(),terminalWidth:M,compactionInfo:ot??void 0}),[ot,n.sessionId,V,e.context?.gitRoot,M]),ci=ue(()=>s.enabled&&Wn?SO(dr):void 0,[dr,s.enabled,Wn]),Pf=ue(()=>ad({items:Qs,viewportWidth:M,maxLines:yt,showDetailedTools:!1,showAllContent:!1,windowed:!1}),[Qs,M,yt]),cl=ue(()=>{let f=cd({activeItems:Pf.activeItems,viewportWidth:M,isLoading:Ut,maxLines:yt,isThinking:Me.isThinking,thinkingCharCount:Me.thinkingCharCount,thinkingContent:Me.thinkingContent,streamingResponse:Me.currentResponse,currentTool:Me.currentTool,activeToolCalls:Me.activeToolCalls,toolInputCharCount:Me.toolInputCharCount,toolInputContent:Me.toolInputContent,iterationHistory:Me.iterationHistory,currentIteration:Me.currentIteration,isCompacting:Me.isCompacting,managedAgentMode:V.agentMode,managedPhase:Ut?W?.phase:void 0,managedHarnessProfile:Ut?W?.harnessProfile:void 0,managedWorkerTitle:Ut?W?.activeWorkerTitle:void 0,managedRound:Ut?W?.currentRound:void 0,managedMaxRounds:Ut?W?.maxRounds:void 0,managedGlobalWorkBudget:Ut?W?.globalWorkBudget:void 0,managedBudgetUsage:Ut?W?.budgetUsage:void 0,managedBudgetApprovalRequired:Ut?W?.budgetApprovalRequired:void 0,lastLiveActivityLabel:Me.lastLiveActivityLabel,currentTodoActiveForm:Zr,showFullThinking:!1,showDetailedTools:!1,showAllContent:!1,showLiveProgressRows:ty});return fh(tg(ld(Pf,f)),ci)},[V.agentMode,Ut,Me.activeToolCalls,Me.currentIteration,Me.currentTool,Me.isCompacting,Me.currentResponse,Me.isThinking,Me.iterationHistory,Me.lastLiveActivityLabel,Me.thinkingCharCount,Me.thinkingContent,Me.toolInputCharCount,Me.toolInputContent,W?.activeWorkerTitle,W?.budgetApprovalRequired,W?.budgetUsage,W?.currentRound,W?.globalWorkBudget,W?.harnessProfile,W?.maxRounds,W?.phase,ty,Pf,ci,M,yt,Zr]),Lf=ue(()=>ad({items:qs,viewportWidth:M,maxLines:yt,showDetailedTools:bt,showAllContent:bt,windowed:!1}),[qs,M,yt,bt]),ll=ue(()=>{if(!oe||si)return;let f=cd({activeItems:Lf.activeItems,viewportWidth:M,isLoading:st,maxLines:yt,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:V.agentMode,managedPhase:st?W?.phase:void 0,managedHarnessProfile:st?W?.harnessProfile:void 0,managedWorkerTitle:st?W?.activeWorkerTitle:void 0,managedRound:st?W?.currentRound:void 0,managedMaxRounds:st?W?.maxRounds:void 0,managedGlobalWorkBudget:st?W?.globalWorkBudget:void 0,managedBudgetUsage:st?W?.budgetUsage:void 0,managedBudgetApprovalRequired:st?W?.budgetApprovalRequired:void 0,lastLiveActivityLabel:pe.lastLiveActivityLabel,currentTodoActiveForm:Zr,showFullThinking:!0,showDetailedTools:bt,showAllContent:bt,showLiveProgressRows:!al,expandedItemKeys:tn});return fh(tg(ld(Lf,f)),ci)},[V.agentMode,tn,al,ci,oe,W?.activeWorkerTitle,W?.budgetApprovalRequired,W?.budgetUsage,W?.currentRound,W?.globalWorkBudget,W?.harnessProfile,W?.maxRounds,W?.phase,M,st,yt,Lf,pe.activeToolCalls,pe.currentIteration,pe.currentResponse,pe.currentTool,pe.isCompacting,pe.isThinking,pe.iterationHistory,pe.lastLiveActivityLabel,pe.thinkingCharCount,pe.thinkingContent,pe.toolInputCharCount,pe.toolInputContent,bt,si,Zr]),Js=ue(()=>{if(xt)return oe?fh(ud({items:Et,viewportWidth:M,isLoading:Vn,maxLines:yt,isThinking:Ge.isThinking,thinkingCharCount:Ge.thinkingCharCount,thinkingContent:Ge.thinkingContent,streamingResponse:Ge.currentResponse,currentTool:Ge.currentTool,activeToolCalls:Ge.activeToolCalls,toolInputCharCount:Ge.toolInputCharCount,toolInputContent:Ge.toolInputContent,iterationHistory:Ge.iterationHistory,currentIteration:Ge.currentIteration,isCompacting:Ge.isCompacting,managedAgentMode:V.agentMode,managedPhase:Vn?W?.phase:void 0,managedHarnessProfile:Vn?W?.harnessProfile:void 0,managedWorkerTitle:Vn?W?.activeWorkerTitle:void 0,managedRound:Vn?W?.currentRound:void 0,managedMaxRounds:Vn?W?.maxRounds:void 0,managedGlobalWorkBudget:Vn?W?.globalWorkBudget:void 0,managedBudgetUsage:Vn?W?.budgetUsage:void 0,managedBudgetApprovalRequired:Vn?W?.budgetApprovalRequired:void 0,lastLiveActivityLabel:Ge.lastLiveActivityLabel,currentTodoActiveForm:Zr,windowed:!0,showFullThinking:oe,showDetailedTools:bt,showAllContent:bt,showLiveProgressRows:oe&&!al,expandedItemKeys:oe?tn:void 0}),ci):cl},[V.agentMode,Vn,Et,al,ci,Ge.activeToolCalls,Ge.currentIteration,Ge.currentResponse,Ge.currentTool,Ge.isCompacting,Ge.isThinking,Ge.iterationHistory,Ge.lastLiveActivityLabel,Ge.thinkingCharCount,Ge.thinkingContent,Ge.toolInputCharCount,Ge.toolInputContent,tn,oe,W?.activeWorkerTitle,W?.budgetApprovalRequired,W?.budgetUsage,W?.currentRound,W?.globalWorkBudget,W?.harnessProfile,W?.maxRounds,W?.phase,cl,K,oe,M,yt,xt,bt,Zr]),zn=ue(()=>Js??ll,[Js,ll]),Zs=ue(()=>ih({status:W,isLoading:K,agentMode:V.agentMode}),[V.agentMode,K,W]).workStripText,ea=Lt?.workStripText??sr,li=ue(()=>ih({status:W,isLoading:K,agentMode:V.agentMode,parallelTextOverride:ea}),[V.agentMode,ea,K,W]),fr=ue(()=>dv(Et).filter(f=>f!==dd),[Et]),Xe=ue(()=>Yd(He,fr,He.selectedItemId),[fr,He]),nn=ue(()=>Et.find(f=>f.id===Xe),[Et,Xe]),ny=ue(()=>({...He,supportsSelection:He.supportsSelection&&xt,supportsCopyOnSelect:He.supportsCopyOnSelect&&xt}),[He,xt]),mn=ue(()=>Lv({state:ny,selectableItemIds:fr,selectedItemId:Xe,selectedItemType:nn?.type,isExpanded:Xe?tn.has(Xe):!1}),[tn,fr,nn?.type,Xe,ny]),oy=mn.selectionEnabled,ry=mn.copyCapabilities.copyOnSelect,GD=mn.selectedItemIndex,iy=ue(()=>uv(nn),[nn]),ul=ue(()=>sv(Et.filter(f=>!rg(f))),[Et]),vt=ue(()=>av(ul,Wt),[ul,Wt]),dl=ue(()=>Nv({isHistorySearchActive:it,historySearchQuery:Wt,matches:vt,selectedIndex:rl,anchorItemId:He.searchAnchorItemId,useOverlaySurface:He.supportsOverlaySurface&&He.supportsSearchViewport&&xt}),[vt,Wt,rl,it,He.searchAnchorItemId,He.supportsOverlaySurface,He.supportsSearchViewport,xt]),Oo=dl.clampedSelectedIndex,sy=dl.statusText,Of=dl.detailText,ay=dl.searchState,KD=mn.detailState==="expanded",fl=mn.selectionEnabled&&fr.length>0&&!fo,ui=mn.copyCapabilities.message,ml=mn.copyCapabilities.toolInput,pl=mn.toggleDetail;Fe(()=>{if(Zs){if(Gn.current&&(clearTimeout(Gn.current),Gn.current=null),sr===Zs)return;if(sr){$t.current&&(clearTimeout($t.current),$t.current=null),Vc(Zs);return}$t.current&&clearTimeout($t.current),$t.current=setTimeout(()=>{Vc(Zs),$t.current=null},400);return}if(!sr){$t.current&&(clearTimeout($t.current),$t.current=null);return}$t.current&&(clearTimeout($t.current),$t.current=null),Gn.current&&clearTimeout(Gn.current),Gn.current=setTimeout(()=>{Vc(void 0),Gn.current=null},300)},[Vs,Zs,sr]),Fe(()=>()=>{Vs()},[Vs]);let Do=ue(()=>gv({state:He,ownsViewport:xt,isAwaitingUserInteraction:Po,isHistorySearchActive:it,isTranscriptMode:oe,historySearchQuery:Wt}),[Wt,Po,it,oe,He,xt]);Fe(()=>{jn(f=>{let h=Hb(f,En);return h=Bb(h,Ys),h=Wb(h,s.enabled&&xt?!Sf||it||Po:oe||it||Po),h=Gb(h,Oo),h})},[Oo,s.enabled,En,Po,it,oe,Ys,xt,Sf]),Fe(()=>{rl!==Oo&&Pn(Oo)},[Oo,rl]),Fe(()=>{if(!it){Mf.current=Wt;return}if(Wt===Mf.current)return;Mf.current=Wt;let f=lv(ul,vt,He.searchAnchorItemId);Pn(f)},[vt,Wt,it,He.searchAnchorItemId,ul]);let cy=oe?pe:{isThinking:Me.isThinking,thinkingCharCount:Me.thinkingCharCount,currentTool:Me.currentTool,activeToolCalls:Me.activeToolCalls,toolInputCharCount:Me.toolInputCharCount,toolInputContent:Me.toolInputContent,currentIteration:Me.currentIteration,isCompacting:Me.isCompacting},ta=oe?st:Ut,[Df,Nf]=Ue(()=>Qt(V.permissionMode)?l.getGuardrail().getEngine():void 0),gl=ue(()=>Pv({sessionId:n.sessionId,permissionMode:V.permissionMode,agentMode:V.agentMode,provider:V.provider,model:V.model??Xn(V.provider)??V.provider,thinking:V.thinking,reasoningMode:V.reasoningMode,reasoningCapability:Bl(wr(V.provider,V.model)),isTranscriptMode:oe,streamingState:cy,maxIter:C.maxIter,contextUsage:zh,isLoading:ta,managedState:{phase:W?.phase,harnessProfile:W?.harnessProfile,workerTitle:W?.activeWorkerTitle,round:W?.currentRound,maxRounds:W?.maxRounds,globalWorkBudget:W?.globalWorkBudget,budgetUsage:W?.budgetUsage,budgetApprovalRequired:W?.budgetApprovalRequired,idleWaiting:W?.idleWaiting,idleWaitingPendingCount:W?.idleWaitingPendingCount},autoModeEngine:Df}),[n.sessionId,V.permissionMode,V.agentMode,V.provider,V.model,V.thinking,V.reasoningMode,oe,cy,C.maxIter,zh,ta,W?.phase,W?.harnessProfile,W?.activeWorkerTitle,W?.currentRound,W?.maxRounds,W?.globalWorkBudget,W?.budgetUsage,W?.budgetApprovalRequired,W?.idleWaiting,W?.idleWaitingPendingCount,Df]),Bf=qe?"confirm":$e?.kind,No=ue(()=>_v({isTranscriptMode:oe,isLoading:ta,streamingState:Me,managedState:ta?{phase:W?.phase,harnessProfile:W?.harnessProfile,workerTitle:W?.activeWorkerTitle}:void 0,waitingReason:Bf}),[Me.activeToolCalls,Me.currentTool,Me.isCompacting,Me.isThinking,Me.thinkingCharCount,Me.toolInputCharCount,Me.toolInputContent,oe,W?.activeWorkerTitle,W?.harnessProfile,W?.phase,Bf,ta]),Hf=No?.text,mo=ue(()=>ub(Gc,{now:Date.now(),lastAllCompletedAt:null}),[Gc]),ly=me(!1);Fe(()=>{ly.current&&!K&&Mo(f=>f.length>0?[]:f),ly.current=K},[K]);let Ff=ue(()=>hd(gl),[gl]),uy=ue(()=>Ff,[Ff]),dy=uy.text,DI=ue(()=>jC(C.pendingInputs),[C.pendingInputs]),Wf=ue(()=>db({isHistorySearchActive:it,isTranscriptMode:oe,pendingInputCount:C.pendingInputs.length,buffering:He.buffering,pendingLiveUpdates:Ys}),[it,oe,Ys,C.pendingInputs.length,He.buffering]),fy=Wf.leftItems,my=Wf.rightItems,py=Wf.summary,hl=ue(()=>Hv({historySearchQuery:Wt,pendingInputCount:C.pendingInputs.length}),[Wt,C.pendingInputs.length]),yl=ue(()=>Bv({historySearchQuery:Wt,isHistorySearchActive:it,historySearchMatchCount:vt.length,pendingInputCount:C.pendingInputs.length,maxPendingInputs:5}),[vt.length,Wt,it,C.pendingInputs.length]),gy=ue(()=>yl.map(f=>f.text).join(" | "),[yl]),xl=ue(()=>Fv({inputText:xf,isTranscriptMode:oe,isHistorySearchActive:it}),[xf,it,oe]),hy=He.supportsOverlaySurface&&He.supportsSearchViewport&&xt,wl=ue(()=>Ov({runtime:mn,itemSummary:iy}),[iy,mn]),Uf=ue(()=>Wv(hl),[hl]),yy=ue(()=>Uv({textSelection:fo,selectionState:wl,isHistorySearchActive:it,historySearchDetailText:Of,historySearchHasMatches:!!sy&&vt.length>0,showAllActive:bt,baseFooterNotices:hl}),[fo,hl,Of,vt.length,sy,it,bt,wl]),NI=yy.secondaryText,BI=yy.budgetNotices,xy=oe?BI:Uf,wy=T.rows??24,Sy=oe?"":xf,Ty=oe?void 0:DI,Cy=ea,by=oe?!1:Uh,jt=ue(()=>Lb({terminalRows:wy,terminalWidth:M,windowedTranscript:si,inputText:Sy,footerHeaderText:py,activitySummary:oe?void 0:Hf,activityBarVisible:oe?!1:!!Hf||K&&mo.shouldRender,todoSurfaceRows:oe?0:K&&mo.shouldRender?mo.rows.length:0,pendingInputSummary:Ty,stashNoticeSummary:xl,notificationSummary:gy,statusNoticeSummary:xy.join(" | "),workStripText:Cy,suggestionsReserved:sl,suggestionsMode:"inline",showHelp:by,statusBarText:dy,confirmPrompt:qe?.prompt,confirmInstruction:Xs,dialogMode:"inline",reviewHint:s.enabled&&xt?void 0:Do.browseHintText,uiRequest:$e?$e.kind==="select"?{kind:"select",title:$e.title,options:$e.options.map(f=>({label:f.label,description:f.description})),buffer:$e.buffer,error:$e.error}:{kind:"input",prompt:$e.prompt,defaultValue:$e.defaultValue,buffer:$e.buffer,error:$e.error}:null}),[wy,M,Sy,py,Hf,Ty,xl,gy,xy,Cy,sl,hy,by,dy,qe,Xs,s.enabled,Do.browseHintText,xt,$e]),HI=ue(()=>se(Sg,{reserveSpace:sl,width:M,hidden:oe,mode:"inline"}),[sl,M,oe,hy]),na=ue(()=>hv(jt.messageRows),[jt.messageRows]),vy=ue(()=>yv(na),[na]),di=!Qh&&s.transcriptSpinnerAnimation,oa=zn?zn.rows.length+zn.previewRows.length:wI,Sl=z(f=>{zn||SI(f.scrollHeight)},[zn]),ra=z(f=>bv({window:f,stickyHeader:Do.stickyHeader,width:M,topChromeRows:0}),[M,Do.stickyHeader]),fi=z((f=Hs.current,h=Uc.current,S=Tf.current?ra(Tf.current):Wc.current)=>{if(!S||f.length===0){Qr.current=null;return}Wc.current=S,Qr.current=vv(f,{allRows:h,rowIndexByKey:eh(h),topOffsetRows:S.topOffsetRows,viewportHeight:S.contentWindow.viewportHeight,animateSpinners:di})},[ra,di]),ia=z(()=>{let f=Wc.current;return f?.contentWindow.viewportHeight&&f.contentWindow.viewportHeight>0?f.contentWindow.viewportHeight:jt.messageRows},[jt.messageRows]),FI=z(f=>{Tf.current=f;let h=ra(f);Wc.current=h,fi(Hs.current,Uc.current,h)},[fi,ra]),Tl=z(f=>{Hs.current=f.rows,Uc.current=f.allRows,fi(f.rows,f.allRows)},[fi]),Dt=z(()=>{Mn.current=null,Cf(void 0),bf(void 0)},[]),jf=z(()=>{Dt(),jn(f=>Rs(f,void 0))},[Dt]);Fe(()=>{fi()},[fi]),Fe(()=>{CI(f=>xv(f,oa,jt.messageRows))},[oa,jt.messageRows]),Fe(()=>{if(!Jr)return;let f=setTimeout(()=>{_h(void 0)},2e3);return()=>{clearTimeout(f)}},[Jr]);let po=z((f,h="success")=>{let S=f?.trim();S&&_h({text:S,tone:h})},[]),mi=z((f,h)=>{let S=h instanceof Error?h.message:String(h);return`${f}: ${S}`},[]),Cl=z(async f=>{let h=f??fo;if(!h)return!1;let S=h.text.trimEnd();if(!S)return!1;try{return await Or(S,{terminalWrite:$}),po(`Copied ${h.rowCount} selected line${h.rowCount===1?"":"s"} to clipboard.`,"success"),!0}catch(R){return po(mi("Failed to copy transcript selection",R),"warning"),!1}},[fo,mi,po,$]),pi=z(f=>{if(!f||Sv({items:Et,renderModel:zn,terminalWidth:M,transcriptMaxLines:yt,viewportRows:ia(),itemId:f,visibleRows:Hs.current,expandedItemKeys:tn,showDetailedTools:!1}))return;let h=Tv({items:Et,renderModel:zn,terminalWidth:M,transcriptMaxLines:yt,viewportRows:ia(),itemId:f,expandedItemKeys:tn,showDetailedTools:!1});Bc(h)},[Et,M,yt,zn,tn,ia,Bc,Hs]),Iy=z(f=>{jn(h=>Rs(h,f)),f&&pi(f)},[pi]),Gf=z(f=>{f&&pi(f)},[pi]),ky=z(f=>{if(!fl)return;let h=fv(fr,Xe,f);h&&Iy(h)},[fl,fr,Xe,Iy]),Ry=z(()=>{!pl||!Xe||(II(f=>{let h=new Set(f);return h.has(Xe)?h.delete(Xe):h.add(Xe),h}),pi(Xe))},[pi,pl,Xe]),Ey=z(async()=>{if(!ui||!nn)return;let f=Zg(nn);if(f)try{await Or(f,{terminalWrite:$}),po("Copied selected transcript entry to clipboard.","success")}catch(h){po(mi("Failed to copy transcript entry",h),"warning")}},[mi,ui,nn,po,$]),My=z(async()=>{if(!ml||!nn)return;let f=mv(nn);if(f)try{await Or(f,{terminalWrite:$}),po("Copied selected tool args to clipboard.","success")}catch(h){po(mi("Failed to copy tool args",h),"warning")}},[mi,ml,nn,po,$]),sa=z(()=>Uc.current,[]),Ay=z((f,h)=>{if(!s.enabled||!xt)return;let S=Qr.current;return S?nh(S,f,h):void 0},[s.enabled,xt]),gi=z((f,h,S)=>{let R=sa(),E=Rv(R,f,h,{animateSpinners:di,selectFullRowOnCollapsed:S?.selectFullRowOnCollapsed});oe?bf(E):Cf(E);let N=R[Math.max(0,Math.min(h.modelRowIndex,R.length-1))];return S?.updateSelectedItem&&N?.itemId&&jn(B=>Rs(B,N.itemId)),E},[oe,sa,di]),_y=z((f,h)=>{if(!f)return;Mn.current=null;let S={...f,focus:h?.focusPoint??f.focus};if(!(S.mode!=="char"||S.didDrag)){Dt();return}let E=gi(S.anchor,S.focus,{selectFullRowOnCollapsed:!1,updateSelectedItem:!1});if(!E){Dt();return}return h?.copySelection!==!1&&Cl(E),E},[Dt,Cl,gi]),Kf=z(()=>{if(!oe||!Et.length||qe||$e)return;Dt();let f=Cv({items:Et,selectedItemId:Xe,renderModel:zn,terminalWidth:M,transcriptMaxLines:yt,viewportRows:ia(),scrollOffset:En,expandedItemKeys:tn,showDetailedTools:!1,preferViewportAnchor:!0});jn(h=>Ub(h,{anchorItemId:f,initialMatchIndex:0})),ii(""),Pn(0)},[qe,Et,tn,En,oe,Xe,zn,M,yt,$e,ia,Dt]),Vf=z(()=>{jn(f=>jb(f)),ii(""),Pn(0),Dt()},[Dt]),bl=z(()=>{!it||vt.length===0||Pn(-1)},[vt.length,it]),$y=ue(()=>{if(!qe)return null;if(qe.tool==="exit_plan_mode"){let f=typeof qe.input.plan=="string"?qe.input.plan:void 0;return{prompt:qe.prompt.split(`
|
|
382
|
+
`,1)[0]??qe.prompt,instruction:Xs,planContent:f}}return{prompt:qe.prompt,instruction:Xs}},[Xs,qe]),Py=ue(()=>$e?$e.kind==="select"?{kind:"select",title:$e.title,options:$e.options,buffer:$e.buffer,error:$e.error,visibleSelectOptions:jt.visibleSelectOptions,focusedIndex:$e.focusedIndex,selectedIndices:$e.selectedIndices,multiSelect:$e.multiSelect}:{kind:"input",prompt:$e.prompt,defaultValue:$e.defaultValue,buffer:$e.buffer,error:$e.error}:null,[$e,jt.visibleSelectOptions]),WI=ue(()=>se(Cg,{confirm:$y,request:Py}),[$y,Py]),zf=ue(()=>{if(Jr)return se(cb,{text:Jr.text,tone:Jr.tone})},[Jr]),Xf=ue(()=>{if(zf)return se(k,{flexDirection:"column",width:"100%",children:zf})},[zf]),vl=z(()=>{jn(f=>Fb(Nb(f))),wf(!1),Fc(),ii(""),Pn(0),Dt()},[Dt,Fc]),Ly=z(()=>{oe&&wf(f=>!f)},[oe]),UI=z(()=>{if(oe){vl();return}wf(!1),jn(f=>Db(f)),ii(""),Pn(0),Dt()},[Dt,vl,oe]);Fe(()=>{oy||!He.selectedItemId||jn(f=>Rs(f,void 0))},[oy,He.selectedItemId]),Fe(()=>{if(!oe||!ui||!ry){zs.current=void 0;return}if(ir||!Xe||!nn)return;if(!zs.current){zs.current=Xe;return}if(zs.current===Xe)return;zs.current=Xe;let f=Zg(nn);f&&Or(f,{terminalWrite:$}).catch(()=>{})},[oe,nn,Xe,ui,ry,ir,$]),Fe(()=>{if(T?.isTTY!==!0)return;let f=mu(T);f?.setShellMode?.(Xh,il),Af||f?.setAltScreenActive?.(!1)},[Xh,T,Af,il]);let Ye=me({...e,thinking:V.thinking,reasoningMode:V.reasoningMode,agentMode:V.agentMode,context:{...e.context,repoIntelligenceMode:V.repoIntelligenceMode,repoIntelligenceTrace:V.repoIntelligenceTrace,toolConstructionMode:!0},session:{...e.session,id:n.sessionId},guardrails:lh(V.permissionMode,l)}),pn=me(V.permissionMode);Fe(()=>{pn.current=V.permissionMode},[V.permissionMode]);let Oy=me(is()),Yf=me(V);Fe(()=>{Yf.current=V},[V]);let qf=me(null);qf.current===null&&(qf.current=Dl({getProvider:i(()=>gr(Yf.current.provider),"getProvider"),getModel:i(()=>Yf.current.model??"","getModel")}));let Dy=me(vu());Fe(()=>{V.permissionMode==="auto-in-project"&&Dy.current()},[]);let Qf=z(f=>{Ce(h=>({...h,permissionMode:f})),pn.current=f,Ye.current={...Ye.current,guardrails:lh(f,l)},Nf(Qt(f)?l.getGuardrail().getEngine():void 0),f==="auto-in-project"&&Dy.current()},[l]),Ny=me(C.pendingInputs),Ze=me(!1),aa=me(0),Il=z(()=>{if(Ns.current)return;let f=kf.current?.trim(),h=G.current.length>0?G.current[G.current.length-1]:void 0,S=h&&"text"in h&&typeof h.text=="string"?h.text.trim():void 0,E=un.current.length>0?[...un.current.map(N=>Xr(N)),...f&&f!==S?[{type:"info",text:f}]:[]]:[...un.current.map(N=>Xr(N)),...xO(ee(),Qe(),{toolCalls:Pt.current,toolNames:Kn.current,infoItems:f&&f!==S?[f]:[]})];E.length!==0&&(Ns.current=!0,Ds.current?.(E))},[Qe,ee]);Fe(()=>{Ny.current=C.pendingInputs},[C.pendingInputs]);let By=z(()=>{Ze.current=!0,Se(),Ie(),Y(),Q(),Ee(),je(),be(void 0),$o(),ft(void 0),js(),ar.current=[],ei.current=[],Fs([]),fe(!1)},[Se,je,Q,Ee,$o,js,be,Fs,fe,ft,Ie,Y]),kl=me(0),jI=500;an(Bt.Critical,f=>{if(!K)return!1;switch(nv({keyName:f.name,ctrl:!!f.ctrl,isTranscriptMode:oe,isAwaitingUserInteraction:Po,isInputEmpty:yf,pendingInputCount:C.pendingInputs.length,hasTranscriptTextSelection:!!ir,timeSinceLastEscapeMs:Date.now()-kl.current,doubleEscapeIntervalMs:jI}).kind){case"interrupt":return kl.current=0,Il(),By(),!0;case"pop-pending-input":return ke(),kl.current=0,!0;case"arm-double-escape":return kl.current=Date.now(),!0;default:break}return!1},[K,oe,Po,yf,C.pendingInputs.length,ke,Il,By]),an(Bt.Critical,f=>{let h=ev({itemsLength:Et.length,currentResponse:Ge.currentResponse,thinkingContent:Ge.thinkingContent,activeToolCallsLength:Ge.activeToolCalls.length}),S=tv({keyName:f.name,hasTranscript:h,historyScrollOffset:En,reviewPageSize:na,reviewWheelStep:vy,hasMouse:!!f.mouse,mouseButton:f.mouse?.button,mouseAction:f.mouse?.action,usesManagedMouseClicks:Yh,supportsMouseTracking:He.supportsMouseTracking,usesRendererMouseTracking:il,usesManagedMouseWheel:qh,supportsWheelHistory:He.supportsWheelHistory});if(S.kind==="mouse-phase"){let E=f.mouse;if(!E)return!1;S.phase==="press"&&Mn.current&&_y(Mn.current);let N=Ay(E.row,E.column);if(S.phase==="press"){if(!N||!h)return fo||Xe?(jf(),!0):(Dt(),!1);let B=e0({previous:Ah.current,time:Date.now(),row:E.row,column:E.column});Ah.current=B;let j=B.count>=3?"line":B.count===2?"word":"char";if(bl(),jn(re=>Rs(re,void 0)),oe?bf(void 0):Cf(void 0),j!=="char"){let re=Qd(sa(),N.point,j);if(re)return Mn.current={anchor:re.start,focus:re.end,didDrag:!1,mode:j,anchorSpan:re},gi(re.start,re.end,{updateSelectedItem:!1}),!0}return Mn.current={anchor:N.point,focus:N.point,didDrag:!1,mode:"char"},!0}if(!Mn.current)return!1;if(S.phase==="drag"){let B=Qr.current,j=B?Mv(B,E.row):0;j!==0&&Hc(j);let re=N??(B?oh(B,E.row,E.column):void 0);if(!re)return!1;let ye=Mn.current;if(ye.mode!=="char"&&ye.anchorSpan){let ut=Qd(sa(),re.point,ye.mode);if(!ut)return!1;let Nt=ch(ye.anchorSpan,ut);return Mn.current={...ye,anchor:Nt.anchor,focus:Nt.focus,didDrag:!0},gi(Nt.anchor,Nt.focus,{updateSelectedItem:!1}),!0}return Mn.current={...ye,focus:re.point,didDrag:!0},gi(ye.anchor,re.point,{updateSelectedItem:!1}),!0}if(S.phase==="release"){let B=Mn.current,j=B.focus,ye=(N??(Qr.current?oh(Qr.current,E.row,E.column):void 0))?.point??j;if(B.mode!=="char"&&B.anchorSpan){let ut=Qd(sa(),ye,B.mode);if(ut){let Nt=ch(B.anchorSpan,ut);B.anchor=Nt.anchor,ye=Nt.focus}}return _y(B,{focusPoint:ye}),!0}}if(S.kind==="scroll-by")return bl(),Hc(S.delta),!0;if(S.kind==="consume")return!0;let R=ov({key:f,isTranscriptMode:oe,isHistorySearchActive:it,historySearchMatchCount:vt.length,hasTextSelection:!!fo,hasFocusedItem:!!Xe,canCopySelectedItem:ui,canCopySelectedToolInput:ml,canToggleSelectedDetail:pl,canCycleTranscriptSelection:fl});return rv({action:R,hasTranscript:h,isTranscriptMode:oe,pageScrollDelta:na,disarmHistorySearchSelection:bl,scrollTranscriptBy:Hc,closeHistorySearchSurface:Vf,backspaceHistorySearchQuery:i(()=>{ii(E=>E.slice(0,-1)),Pn(0)},"backspaceHistorySearchQuery"),stepHistorySearchSelection:i(E=>{Pn(N=>Jg(vt.length,N,E))},"stepHistorySearchSelection"),submitHistorySearchSelection:i(()=>{let E=vt[Oo];E&&(Gf(E.itemId),Vf())},"submitHistorySearchSelection"),appendHistorySearchQuery:i(E=>{ii(N=>N+E),Pn(0)},"appendHistorySearchQuery"),openHistorySearchSurface:Kf,clearTranscriptSelectionFocus:jf,exitTranscriptModeSurface:vl,toggleTranscriptShowAll:Ly,scrollTranscriptHome:i(()=>{Bc(Math.max(0,oa-jt.messageRows))},"scrollTranscriptHome"),scrollTranscriptToBottom:i(()=>{Fc(),Dt()},"scrollTranscriptToBottom"),cycleTranscriptSelection:ky,copySelectedTranscriptText:i(()=>{Cl()},"copySelectedTranscriptText"),copySelectedTranscriptItem:i(()=>{Ey()},"copySelectedTranscriptItem"),copySelectedTranscriptToolInput:i(()=>{My()},"copySelectedTranscriptToolInput"),toggleSelectedTranscriptDetail:Ry,navigateSearchMatch:i(E=>{Pn(N=>{let B=Jg(vt.length,N,E),j=vt[B];return j&&Gf(j.itemId),B})},"navigateSearchMatch"),dumpTranscriptToScrollback:i(()=>{iv({items:Et.filter(E=>!rg(E)),exitAltScreen:i(()=>{$(wu({mouseTracking:!0}))},"exitAltScreen"),writeToScrollback:i(E=>{$(E)},"writeToScrollback"),enterAltScreen:i(()=>{$(xu({mouseTracking:!0,clearOnEnter:!1}))},"enterAltScreen")})},"dumpTranscriptToScrollback")})},[oe,Et,Ge.currentResponse,Ge.thinkingContent,Ge.activeToolCalls,En,oa,na,vy,Xe,jf,vl,Ly,He,Hc,Bc,Fc,fl,Oo,Dt,Cl,vt,Kf,Vf,bl,ky,ui,Ey,ml,My,pl,Ry,Gf,fo,Ay,He.supportsMouseTracking,ir,Yh,qh,_f,si,il,gi,jt.messageRows]),an(f=>{if(!qe)return!1;let h=f.sequence.trim().toLowerCase(),S=!!qe.input._alwaysConfirm,R=V.permissionMode==="accept-edits"&&!S,E=i(N=>{let B=`${te("dialog.confirm")} ${qe.prompt}
|
|
383
|
+
\u2192 ${te(`confirm.result.${N}`)}`;!!nt.current.workerId?fn({id:`confirm-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"info",text:B,timestamp:Date.now()}):v({type:"info",text:B})},"recordConfirmResult");return h==="y"||h==="yes"?(E("approved"),tl(null),ur.current?.({confirmed:!0}),ur.current=null,!0):R&&(h==="a"||h==="always")?(E("approved_always"),tl(null),ur.current?.({confirmed:!0,always:!0}),ur.current=null,!0):h==="n"||h==="no"||f.name==="escape"?(E("denied"),tl(null),ur.current?.({confirmed:!1}),ur.current=null,!0):f.insertable||f.name==="return"},{isActive:!!qe,priority:Bt.Critical});let Rl=z(f=>{$n(null),nl.current?.(f),nl.current=null},[]),hi=z((f,h,S)=>h.length===0?Promise.resolve(void 0):new Promise(R=>{nl.current=R,$n({kind:"select",title:f,options:h,buffer:"",focusedIndex:0,selectedIndices:[],multiSelect:S})}),[]),GI=z((f,h)=>hi(f,h.map(S=>({label:S,value:S}))),[hi]),Hy=z(async f=>{let h=f.options?qd(f.options):[];return await hi(rh(f),h,f.multiSelect)??cm},[hi]);Fe(()=>{let f=!1;return(async()=>{let{bindAskUserForConstruction:h}=await import("./construction-bootstrap-PHTGBRNU.js");f||h(Hy)})(),()=>{f=!0,(async()=>{let{bindAskUserForConstruction:h}=await import("./construction-bootstrap-PHTGBRNU.js");h(null)})()}},[Hy]);let Fy=z((f,h)=>new Promise(S=>{nl.current=S,$n({kind:"input",prompt:f,defaultValue:h,buffer:""})}),[]);an(f=>{let h=ol.current;if(!h)return!1;if(f.name==="escape")return Rl(void 0),!0;if(h.kind==="select"){let S=h.options.length;if(f.name==="up"||f.sequence==="k")return $n(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 $n(R=>R&&R.kind==="select"?{...R,focusedIndex:(R.focusedIndex+1)%S,error:void 0}:R),!0;if(f.sequence===" "&&h.multiSelect)return $n(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=ol.current;if(!R||R.kind!=="select")return!1;if(R.multiSelect){if(R.selectedIndices.length===0)return $n(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(", ");Rl(E)}else Rl(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?$n(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}}):$n(E=>E&&E.kind==="select"?{...E,focusedIndex:R,error:void 0}:E),!0}return!1}if(f.name==="return"){let S=ol.current;if(!S||S.kind!=="input")return!1;let R=S.buffer.trim();return Rl(R===""?S.defaultValue??void 0:R),!0}return f.name==="backspace"||f.name==="delete"?($n(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?($n(S=>S&&S.kind==="input"?{...S,buffer:S.buffer+f.sequence,error:void 0}:S),!0):!1},{isActive:!!$e,priority:Bt.Critical}),Fe(()=>{if(n.messages.length>0&&D.length===0){if(n.uiHistory?.length){let f=Yr(n.uiHistory);f.length!==n.uiHistory.length&&(n.uiHistory=f);for(let h of f)v({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=Ua(f);for(let S of h)v(Wa(S))}}},[n.messages,n.uiHistory,D.length,v]),Fe(()=>{yr(n.gitRoot)},[n.gitRoot]),Fe(()=>{process.env.KODAX_PREWARM_REPO_INTELLIGENCE!=="0"&&mx({executionCwd:n.gitRoot??process.cwd(),gitRoot:n.gitRoot??void 0},{mode:V.repoIntelligenceMode})},[n.gitRoot,V.repoIntelligenceMode]);let Jf=z(()=>({onThinkingDelta:i(f=>{Ze.current||(C.currentTool&&(be(void 0),Ee()),ft(mh(rt.current?.activeWorkerTitle?`[${rt.current.activeWorkerTitle}] [Thinking]`:"[Thinking]",rt.current?.activeWorkerTitle)),Ne(f.length),ae(f),nt.current.workerId&&Qc("thinking",f))},"onThinkingDelta"),onThinkingEnd:i(f=>{if(Ze.current)return;let h=ee(),S=Ab(h,f);S&&S!==h&&(Q(),ce(),Ne(S.length),ae(S)),nt.current.workerId&&Hh(S),Y()},"onThinkingEnd"),onTextDelta:i(f=>{Ze.current||(C.currentTool&&(be(void 0),Ee()),Y(),ft(void 0),xe(f),nt.current.workerId&&Qc("assistant",f))},"onTextDelta"),onToolUseStart:i(f=>{if(Ze.current)return;Kn.current.includes(f.name)||(Kn.current=[...Kn.current,f.name]);let h=rt.current?.activeWorkerTitle?`[${rt.current.activeWorkerTitle}] `:"",S={id:f.id,name:`${h}${f.name}`,status:P.Executing,startTime:Date.now(),input:f.input};Fh(S),nt.current.workerId&&_n(S),ft(tr(S,rt.current?.activeWorkerTitle))},"onToolUseStart"),onToolInputDelta:i((f,h,S)=>{if(Ze.current)return;ve(h.length),lt(h);let R=Wh(S?.toolId,f,E=>{let N=E.preview??"",B=pO(`${N}${h}`);return{...E,preview:B||void 0,input:E.input?B?{...E.input,preview:B}:{...E.input}:B?{preview:B}:void 0}});R&&(nt.current.workerId&&_n(R),ft(tr(R,rt.current?.activeWorkerTitle)))},"onToolInputDelta"),onToolResult:i(f=>{if(Ze.current)return;let h=typeof f.content=="string"?f.content:String(f.content??""),S=gO(h);if(/^\[(?:Tool Error|Error)\]/.test(h)){let E=Zc(f.id,P.Error,S,S,f.name);E&&(nt.current.workerId&&_n(E),ft(tr(E,rt.current?.activeWorkerTitle)));return}if(/^\[(?:Cancelled|Blocked)\]/.test(h)){let E=Zc(f.id,P.Cancelled,void 0,S,f.name);E&&(nt.current.workerId&&_n(E),ft(tr(E,rt.current?.activeWorkerTitle)));return}let R=Zc(f.id,P.Success,void 0,S||void 0,f.name);R&&(nt.current.workerId&&_n(R),ft(tr(R,rt.current?.activeWorkerTitle)))},"onToolResult"),onToolProgress:i(f=>{if(Ze.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&&nt.current.workerId&&_n(S),ft(h)},"onToolProgress"),onStreamEnd:i(()=>{if(Ze.current)return;let f=Gs(P.Cancelled,()=>({error:"Stream ended before the tool completed.",output:void 0})),h=f[f.length-1];nt.current.workerId&&f.forEach(S=>_n(S)),h&&ft(tr(h,rt.current?.activeWorkerTitle)),Y(),Ee(),be(void 0)},"onStreamEnd"),hasPendingInputs:i(()=>Ny.current.length>0,"hasPendingInputs"),onMidTurnUserMessages:i(f=>{if(!Ze.current)for(let h of f){let S=h.trim();S&&(nt.current.workerId?fn({id:`mid-turn-user-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"user",text:S,timestamp:Date.now()}):v({type:"user",text:S}))}},"onMidTurnUserMessages"),onError:i(f=>{let h=_o();h?.name&&ft(tr(h,rt.current?.activeWorkerTitle));let S=Gs(P.Error,()=>({error:f.message,output:void 0})),R=S[S.length-1];nt.current.workerId&&S.forEach(ut=>_n(ut)),R&&ft(tr(R,rt.current?.activeWorkerTitle));let E=Yy(f),N=["Transient","Permanent","Tool Call ID","User Abort"];if(E.category===fa.USER_ABORT)return;let j=[`\u274C API Error (${N[E.category]||"Unknown"}): ${f.message}`];E.shouldCleanup&&j.push(" \u{1F9F9} Cleaned incomplete tool calls"),E.category===fa.PERMANENT?(j.push(" \u{1F4A1} This error requires manual intervention. Please check:"),f.message.includes("auth")||f.message.includes("401")?(j.push(" - Your API key is valid"),j.push(" - Run /config to check provider settings")):f.message.includes("400")?(j.push(" - The request parameters are correct"),j.push(" - Try restarting the conversation")):j.push(" - The error details above")):E.category===fa.TRANSIENT?j.push(" \u23F3 Retries exhausted. Press Enter to continue the conversation"):E.category===fa.TOOL_CALL_ID&&j.push(" \u2705 Session cleaned, ready to continue");let re=j.join(`
|
|
384
|
+
`);!!nt.current.workerId?fn({id:`error-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"error",text:re,timestamp:Date.now()}):v({type:"error",text:re})},"onError"),onRetry:i((f,h,S)=>{if(Ze.current)return;if(!!nt.current.workerId){let E=Nd(f,h,S);fn({...E,id:`retry-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,timestamp:Date.now()})}else $g(v,f,h,S)},"onRetry"),onProviderRecovery:i(f=>{if(Ze.current)return;let h=!!nt.current.workerId,S=Qe().trim();if(S&&(h?Qc("assistant",S):v({type:"assistant",text:S})),je(),Q(),Y(),Ee(),be(void 0),$o(),ft(void 0),h){let R=Bd(f);fn({...R,id:`recovery-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,timestamp:Date.now()})}else Pg(v,f)},"onProviderRecovery"),onManagedTaskStatus:i(f=>{if(Ze.current)return;let h=nt.current;if(s0(f)){if(h.workerId&&h.workerId!==f.activeWorkerId)_I({workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle});else if(h.workerId!==f.activeWorkerId){let B=mt.current,j=B.activeToolGroupTools.some(re=>re.status===P.Executing);mt.current={workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle,...j?{activeToolGroupItemId:B.activeToolGroupItemId,activeToolGroupTools:B.activeToolGroupTools}:{activeToolGroupTools:[]}},nt.current={workerId:f.activeWorkerId,workerTitle:f.activeWorkerTitle}}}rt.current=f,If(f);let S=yO(f);$I(S);let R=xc(f),N=xc(f,{expanded:!0})??R;N&&(kf.current=N)},"onManagedTaskStatus"),onProviderRateLimit:i((f,h,S)=>{Ze.current||lr({type:"info",icon:"\u23F3",text:`[Rate Limit] Retrying in ${S/1e3}s (${f}/${h})...`},"ratelimit")},"onProviderRateLimit"),onRetryAfter:i(f=>{if(Ze.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";lr({type:"info",icon:"\u23F3",text:`[${R}] (${f.provider}) \u2014 retrying in ${h}s [${S}] (${f.attempt}/${f.maxAttempts})`},"ratelimit")},"onRetryAfter"),onRepoIntelligenceTrace:i(f=>{Ze.current||lr(Mb(f),"repointel-trace")},"onRepoIntelligenceTrace"),onTodoUpdate:i(f=>{Ze.current||Mo(f)},"onTodoUpdate"),onScoutSuspiciousCompletion:i(f=>{Ze.current||ef&&lr({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(Ze.current)return;if(h&&Be(h),rt.current?.globalWorkBudget){let ye={...rt.current,budgetUsage:Math.min(rt.current.globalWorkBudget,(rt.current.budgetUsage??0)+1)};rt.current=ye,If(ye)}let S=f>1?ee().trim():"",R=f>1?ph(Qe()):"",E=f>1?[...Kn.current]:[],N=f>1?[...Pt.current]:[],B=!!nt.current.workerId;A(f),B&&Yc({clearOwner:!1});let j=lo.current.filter(ye=>ye.status===P.Executing),re=new Set(j.map(ye=>ye.id));if(Kn.current=[],Pt.current=Pt.current.filter(ye=>re.has(ye.id)),dn(j),Ee(),be(void 0),ft(mh(rt.current?.activeWorkerTitle?`[Thinking] [${rt.current.activeWorkerTitle}]`:void 0,rt.current?.activeWorkerTitle)),ce(),f>1&&!B){let ye=gh({thinking:S,response:R,toolCalls:N,toolNames:E});if(Ds.current)Ds.current(ye);else for(let ut of ye)v(ut)}},"onIterationStart"),beforeToolExecute:i(async(f,h)=>{let S=pn.current,R=Ar(S),E=Oy.current,N=n.gitRoot;if(Mx(X.current,f,h))return`[Skipped] Previously denied operation. ${Ax(X.current)}`;if(S==="plan"&&(Cn.has(f)||f==="undo"))return`[Blocked] Tool '${f}' is not allowed in plan mode (read-only). ${n0}`;if(S==="plan"&&f==="bash"){let B=h.command??"";if(Dn(B))return`[Blocked] Bash write operation not allowed in plan mode: ${B.slice(0,50)}... ${n0}`}if(f==="bash"){let B=h.command??"";if(On(B))return!0}if(Qt(S)&&Df==="llm")return!0;if(f==="bash"){let B=h.command??"",j=Rx(B);if(j.level==="dangerous"){let re=await mr(f,{...h,_dangerousCommand:!0});return re.confirmed?re.confirmed:(X.current=dm(X.current,f,h,j.reason),`[Blocked] Dangerous command requires confirmation: ${j.reason}`)}}if(N){let B=!1;if(Cn.has(f)){let j=h.path;j&&eo(j,N)&&(B=!0)}if(f==="bash"){let j=h.command;j&&hp(j,N)&&(B=!0)}if(B){let j=await mr(f,{...h,_alwaysConfirm:!0});if(pn.current==="plan"&&(Cn.has(f)||f==="undo"))return!1;if(pn.current==="plan"&&f==="bash"){let re=h.command??"";if(Dn(re))return!1}return j.confirmed}}if(R.has(f)){if(S==="accept-edits"&&f==="bash"&&await Vo(f,h,E,qf.current??void 0))return!0;let B=await mr(f,h);if(pn.current==="plan"&&(Cn.has(f)||f==="undo"))return!1;if(pn.current==="plan"&&f==="bash"){let j=h.command??"";if(Dn(j))return!1}if(!B.confirmed)return v({type:"info",text:te("cancelled")}),X.current=dm(X.current,f,h),!1;B.always&&S==="accept-edits"&&(Ou(f,h,!1),Oy.current=is())}return!0},"beforeToolExecute"),askUser:i(async f=>{let h=f.options?qd(f.options):[],S=await hi(rh(f),h,f.multiSelect);return S===void 0?cm:S},"askUser"),exitPlanMode:i(async f=>pn.current!=="plan"?"not-in-plan-mode":(await mr("exit_plan_mode",{plan:f})).confirmed?(Qf("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=qd(N.options);E>0&&B.push({label:te("select.back_prev"),value:R});let j=`[${E+1}/${h.length}] ${N.question}`,re=await hi(j,B,N.multiSelect);if(re===void 0)return;if(re===R){E--;continue}S[N.question]=re,E++}return S},"askUserMulti"),askUserInput:i(async f=>Fy(f.question,f.default),"askUserInput"),onCompactStart:i(()=>{F()},"onCompactStart"),onCompactStats:i(f=>{Os.current=f.tokensBefore,Un(f.tokensAfter)},"onCompactStats"),onCompactedMessages:i((f,h)=>{n.messages=f,h?.artifactLedger&&h.artifactLedger.length>0&&(n.artifactLedger=ma(n.artifactLedger??[],h.artifactLedger)),n.lineage=h?.anchor?ax(n.lineage,f,h.anchor,h.postCompactAttachments??[]):xn(f,n.lineage);let S=hr(f);n.contextTokenSnapshot={currentTokens:S,baselineEstimatedTokens:S,source:"estimate"},io(n),Un(S),Lc.current?.().catch(()=>{})},"onCompactedMessages"),onCompact:i(f=>{J();let h=Os.current??f;Os.current=null;let S=Math.round(h/1e3);lr({type:"info",icon:"\u2728",text:`Context auto-compacted (was ~${S}k tokens)`},"compact")},"onCompact"),onCompactEnd:i(()=>{Os.current=null,J()},"onCompactEnd"),onIterationEnd:i(f=>{f.scope!=="worker"&&(n.contextTokenSnapshot=f.contextTokenSnapshot),Un(f.tokenCount)},"onIterationEnd")}),[Ne,ae,Y,xe,be,ve,lt,Ee,A,ce,V,n,F,J,v,Q,ee,Qe,Yc,ft,Qc,Hh,_n,Fh,Wh,Zc,Gs,_o,$o,dn,C.currentTool]),mr=i((f,h)=>{let S=yb(f,h);return new Promise(R=>{ur.current=R,tl({tool:f,input:h,prompt:S})})},"showConfirmDialog");Fe(()=>(d(async(f,h,S)=>(await mr(f.name,{...f.input,_reason:`[auto-mode] ${h}`,...S&&S.length>0?{_classifierSignals:S}:{}})).confirmed?"allow":"block"),m(f=>{Nf(f)}),()=>{d(null),m(null)}),[]),Fe(()=>{p(V)},[V,p]);let ca=i(async(f,h,S=n.lineage?Mt(n.lineage,n.lineage.activeEntryId):n.messages,R)=>{let E={...Jf(),getCostReport:L},B=ho(n.gitRoot).getSystemPromptSnippet(),j=_b(f.context,n.gitRoot,n.contextTokenSnapshot,B);R&&R.length>0&&(j.inputArtifacts=[...R]),j.planModeBlockCheck=(re,ye)=>pn.current!=="plan"?null:vo(re,ye,n.gitRoot??process.cwd());try{return await ga({...f,session:{...f.session,initialMessages:S},context:j,events:E,abortSignal:Rt()},h)}finally{hx()}},"runAgentRound"),go=z(f=>{let h=xn([...f],n.lineage);return n.lineage=h,h},[n]),la=z(async f=>{if(n.messages.length===0)return;let h=rs(n.messages),S=Yr(f??q.current);q.current=S,n.title=h,n.uiHistory=S;let R=n.lineage??go(n.messages);n.lineage=R;let E={messages:n.messages,title:h,gitRoot:n.gitRoot??"",uiHistory:S,lineage:R,artifactLedger:n.artifactLedger};"appendSessionDelta"in o&&typeof o.appendSessionDelta=="function"?await o.appendSessionDelta(n.sessionId,E):await o.save(n.sessionId,E),Kd()&&Vd("persist",zd(n.messages,R,{historyItems:G.current,foregroundItems:un.current,streamingResponse:Z.current.currentResponse,streamingThinking:Z.current.thinkingContent,persistedUiHistory:q.current}))},[n,go,o]),Zf=z(()=>{if(Oc.current)return Oc.current;let f=(async()=>{try{for(;rr.current.requested;){rr.current.requested=!1;let h=rr.current.uiHistoryOverride;rr.current.uiHistoryOverride=void 0,await la(h)}}finally{Oc.current=null,rr.current.requested&&Zf()}})();return Oc.current=f,Mh.current=f,f},[la]),yi=z(f=>{if(f!==void 0){let h=Yr(f);q.current=h,rr.current.uiHistoryOverride=h}return rr.current.requested=!0,Zf()},[Zf]),KI=z(async()=>{if(Bs.current)return Bs.current;let f=(async()=>{Ze.current=!0,Se(),Ie(),Y(),Q(),Ee(),je(),be(void 0),fe(!1),await Mh.current.catch(()=>{}),await Lc.current?.().catch(()=>{}),Ps(!1),O&&w?.isRaw&&I(!1),w?.pause?.(),w?.unref?.(),y(),a()})();return Bs.current=f.finally(()=>{Bs.current=null}),Bs.current},[Se,je,Q,Ee,y,O,a,be,fe,I,w,Ie,Y]);Fe(()=>(Lc.current=yi,()=>{Lc.current=null}),[yi]);let Wy=z(f=>{if(f.length===0)return;let h=Jd(q.current,f);q.current=h,yi(h)},[yi]),ua=z(f=>{if(f.length!==0){for(let h of f)v(h);Wy(f)}},[v,Wy]),El=z(f=>{if(f.length!==0){for(let h of f)v(h);q.current=Jd(q.current,f)}},[v]);Fe(()=>(Ds.current=ua,()=>{Ds.current=null}),[ua]);let Uy=z(async f=>{n.messages=f.messages,n.contextTokenSnapshot=f.contextTokenSnapshot,go(f.messages);let h=f.success===!1&&!f.interrupted,S=ee().trim(),R=nT(f.messages,Qe(),f.managedTask?.verdict.summary,f.lastText),E=[...un.current],N=E.length>0,B=N&&E.some(ge=>ge.type==="assistant"&&"text"in ge&&Pr(String(ge.text??"")).length>0),j=!h&&R&&!B,re=[...ei.current],ye=h?[]:re.length===0?ef?o0(f):o0(f).filter(ge=>!u0(ge)):[],ut=N?[]:gh({thinking:S,response:void 0,toolCalls:Pt.current,toolNames:Kn.current}),Nt=[...E.map(ge=>Xr(ge)),...ut,...h?[]:re.map(ge=>Xr(ge)),...ye.map(ge=>r0(ge)),...j?[{type:"assistant",text:f.interrupted?`${R}
|
|
385
|
+
|
|
386
|
+
[Interrupted]`:R}]:!R&&!B&&!f.interrupted&&!h?[{type:"info",text:"[No response text was produced for this round]"}]:[]],da=Jd(q.current,Nt);Q(),je();for(let ge of E)v(Xr(ge));for(let ge of ut)v(ge);if(!h){for(let ge of ye)v(r0(ge));for(let ge of re)v(Xr(ge))}j?v({type:"assistant",text:f.interrupted?`${R}
|
|
387
|
+
|
|
388
|
+
[Interrupted]`:R}):!R&&!B&&!f.interrupted&&!h&&v({type:"info",text:"[No response text was produced for this round]"}),Kn.current=[],Pt.current=[],$o(),Ee(),be(void 0),ft(void 0),js(),ar.current=[],ei.current=[],Fs([]),_(),yi(da).catch(()=>{})},[v,_,Ee,je,Q,n,Qe,ee,yi,go,$o,js,be,ft,C.currentIteration]),Ml=z(async f=>{let h=f.trim();h&&(v({type:"user",text:h}),Pc(S=>S+1),io(n))},[v,n]),Al=z(async(f,h)=>{let S=aa.current;Ze.current=!1,Ns.current=!1,Ls(!0);try{return await Jb({initialPrompt:f,runRound:h,shiftPendingPrompt:Oe,onRoundComplete:i(async R=>{aa.current===S&&await Uy(R)},"onRoundComplete"),onBeforeQueuedRound:i(async R=>{Ze.current=!1,Ns.current=!1,await Ml(R)},"onBeforeQueuedRound"),shouldContinue:i(R=>!Ze.current&&R.success!==!1,"shouldContinue")})}finally{Ls(!1)}},[Uy,Oe,Ml]),em=z(async()=>{let f=Oe();if(!f||!f.trim())return;let h=f.trim();await Ml(h),await Al(h,async S=>ca(Ye.current,S))},[ca,Al,Oe,Ml]),tm=z(f=>{let h=f[f.length-1];if(h?.role!=="assistant")return;let S=Ua(h);for(let R of S)v(Wa(R))},[v]),jy=z(async(f,h)=>{let S=await jd({...Ye.current,provider:V.provider,thinking:V.thinking,reasoningMode:V.reasoningMode},f,h,R=>v({type:"info",text:R}));if(S.mode==="manual"){S.manualOutput&&v({type:"info",text:S.manualOutput}),await S.finalize();return}if(!S.prompt||!S.options){await S.finalize();return}Ls(!0);try{let R=S.mode==="fork"?[]:n.lineage?Mt(n.lineage,n.lineage.activeEntryId):n.messages,E=aa.current,N=await ca(S.options,S.prompt,R);if(aa.current!==E)await S.finalize();else{let B=q.current,j=[];if(S.mode==="fork"){let re=N.messages.find(ut=>ut.role==="user");re&&n.messages.push(re);let ye=N.messages.slice().reverse().find(ut=>ut.role==="assistant");if(ye){n.messages.push({role:"assistant",content:ye.content}),go(n.messages);for(let ut of Ua(ye)){let Nt=Wa(ut);v(Nt),j.push(Nt)}}}else{n.messages=N.messages,n.contextTokenSnapshot=N.contextTokenSnapshot,go(N.messages),tm(N.messages);let re=N.messages[N.messages.length-1];if(re?.role==="assistant")for(let ye of Ua(re))j.push(Wa(ye))}await la(Jd(B,j)),Kd()&&Vd("round-end",zd(n.messages,n.lineage,{historyItems:G.current,foregroundItems:un.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),Ls(!1),E}Ls(!1),await em()},[v,tm,n,V.provider,V.thinking,em,la,go,ca]),VI=z(async f=>{for(let h of f.pastedContents)if(h.type==="text"&&!h.content&&h.contentHash)try{let S=await ju(h.contentHash);S&&(h.content=S)}catch{}},[]),zI=z(async f=>{let{displayText:h,fullText:S,pastedContents:R}=f;if(!S.trim()||!Fn||qe||$e)return;for(let ge of R){if(ge.type!=="text"||ge.content.length<1024)continue;let _e=ST(ge.content);TT(_e,ge.content)}if(jh(!1),K){if(!hf)return;if(C.pendingInputs.length>=5){lr({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(Qb(S)){lr({type:"info",icon:"\u26A0",text:Yb},qb);return}let ge=C.currentTool;if(ge&&Ol(ge)?.interruptBehavior==="cancel"){tt(S),Se({preservePendingInputs:!0}),Nc(""),Dc(!0),Pc(on=>on+1),io(n);return}tt(S),Nc(""),Dc(!0),Pc(_e=>_e+1),io(n);return}let E=ph(Qe()),N=un.current.map(ge=>Xr(ge)),B=N.length>0;N.length>0&&El(N),!B&&E&&El([{type:"assistant",text:E+`
|
|
389
|
+
|
|
390
|
+
[Interrupted]`}]),El([{type:"user",text:h}]),Nc(""),Dc(!0),Pc(ge=>ge+1),Kd()&&Vd("turn-start",zd(n.messages,n.lineage,{historyItems:G.current,foregroundItems:un.current,streamingResponse:Z.current.currentResponse,streamingThinking:Z.current.thinkingContent,persistedUiHistory:q.current})),fe(!0),Ze.current=!1,Ns.current=!1,++aa.current,If(null),rt.current=null,kf.current=null,ft(void 0),js(),ar.current=[],ei.current=[],Fs([]),Vs(),Vc(void 0),Kn.current=[],Pt.current=[],$o(),je(),Ee(),be(void 0),_(),Re(),io(n),await new Promise(ge=>setTimeout(ge,50));let j=ls(S.trim());if(j){let ge={exit:KI,saveSession:i(async()=>{if(n.messages.length>0){let H=rs(n.messages);n.title=H;let le=n.lineage??go(n.messages);n.lineage=le,await o.save(n.sessionId,{messages:n.messages,title:H,gitRoot:n.gitRoot??"",uiHistory:q.current,lineage:le,artifactLedger:n.artifactLedger})}},"saveSession"),startNewSession:i(()=>{let H=pc(),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,Ye.current.session={...Ye.current.session,id:H},Un(null),ie(),Mo([]),Uu()?.reset(),Te(H),x?.writer.update({sessionId:H})},"startNewSession"),loadSession:i(async H=>{let le=await o.load(H);return le?Kr(V,"Resuming a saved session",Zd)?(n.messages=le.messages,n.uiHistory=Es(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??[],Un(null),ie(),Mo([]),Te(H),x?.writer.update({sessionId:H}),console.log(Ve.green(`[Session loaded: ${H}]`)),"loaded"):"blocked":"missing"},"loadSession"),listSessions:i(async()=>{let H=await o.list(n.gitRoot??void 0);if(H.length===0){console.log(Ve.dim(`
|
|
391
|
+
[No saved sessions]`));return}console.log(Ve.bold(`
|
|
392
|
+
Recent Sessions:
|
|
393
|
+
`));for(let le of H.slice(0,10))console.log(` ${Ve.cyan(le.id)} ${Ve.dim(`(${le.msgCount} messages)`)} ${le.title.slice(0,40)}`);console.log()},"listSessions"),clearHistory:i(()=>{n.uiHistory=[],ie(),Mo([])},"clearHistory"),printHistory:i(()=>{if(n.messages.length===0){console.log(Ve.dim(`
|
|
394
|
+
[No conversation history]`));return}console.log(Ve.bold(`
|
|
395
|
+
Conversation History:
|
|
396
|
+
`));let H=n.messages.slice(-20);for(let le=0;le<H.length;le++){let Ae=H[le],xi=Ve.cyan(Ae.role.padEnd(10)),Vy=ja(Ae.content),JI=Vy.slice(0,60).replace(/\n/g," "),ZI=Vy.length>60?"...":"";console.log(` ${(le+1).toString().padStart(2)}. ${xi} ${JI}${ZI}`)}console.log()},"printHistory"),switchProvider:i((H,le)=>{Ce(Ae=>({...Ae,provider:H,model:le})),Ye.current.provider=H,Ye.current.model=le},"switchProvider"),setThinking:i(H=>{let le=H?"auto":"off";Ce(Ae=>({...Ae,thinking:H,reasoningMode:le})),Ye.current.thinking=H,Ye.current.reasoningMode=le},"setThinking"),setReasoningMode:i(H=>{let le=H!=="off";Ce(Ae=>({...Ae,thinking:le,reasoningMode:H})),Ye.current.thinking=le,Ye.current.reasoningMode=H},"setReasoningMode"),setAgentMode:i(H=>{Ce(le=>({...le,agentMode:H})),Ye.current.agentMode=H},"setAgentMode"),setPermissionMode:i(H=>{Qf(H)},"setPermissionMode"),setRepoIntelligenceRuntime:i(H=>{Ce(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,Ye.current.context={...Ye.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,Ye.current.context={...Ye.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 o.delete?.(H)},"deleteSession"),deleteAllSessions:i(async()=>{await o.deleteAll?.(n.gitRoot??void 0)},"deleteAllSessions"),printSessionTree:i(async()=>{let H=await o.getLineage?.(n.sessionId);if(!H){console.log(Ve.dim(`
|
|
397
|
+
[No session tree available for this session]`));return}let le=Fd(Pl(H));console.log(Ve.bold(`
|
|
398
|
+
Session Tree:
|
|
399
|
+
`)),le.forEach(Ae=>console.log(` ${Ae}`)),console.log()},"printSessionTree"),switchSessionBranch:i(async H=>{if(!Kr(V,"Switching session branches",Zd))return"blocked";let Ae=await o.setActiveEntry?.(n.sessionId,H,{summarizeCurrentBranch:!0});return Ae?(n.messages=Ae.messages,n.uiHistory=Es(Ae.uiHistory),n.title=Ae.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[],Un(null),ie(),Mo([]),console.log(Ve.green(`
|
|
400
|
+
[Switched to tree entry: ${H}]`)),console.log(Ve.dim(` Messages: ${Ae.messages.length}`)),"switched"):"missing"},"switchSessionBranch"),labelSessionBranch:i(async(H,le)=>{if(!await o.setLabel?.(n.sessionId,H,le))return!1;let xi=le&&le.trim()?`checkpoint label set: ${le.trim()}`:"checkpoint label cleared";return console.log(Ve.green(`
|
|
401
|
+
[${xi}]`)),!0},"labelSessionBranch"),forkSession:i(async H=>{if(!Kr(V,"Forking a session branch",Zd))return"blocked";let Ae=await o.fork?.(n.sessionId,H);if(!Ae)return"failed";n.sessionId=Ae.sessionId,n.messages=Ae.data.messages,n.uiHistory=Es(Ae.data.uiHistory),n.title=Ae.data.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[];let xi=new Date().toISOString();return n.createdAt=xi,n.lastAccessed=xi,Ye.current.session={...Ye.current.session,id:Ae.sessionId},Un(null),ie(),Mo([]),Te(Ae.sessionId),x?.writer.update({sessionId:Ae.sessionId}),console.log(Ve.green(`
|
|
402
|
+
[Forked session: ${Ae.sessionId}]`)),console.log(Ve.dim(` Messages: ${Ae.data.messages.length}`)),"forked"},"forkSession"),rewindSession:i(async H=>{if(!Kr(V,"Rewinding session",Zd))return"blocked";let Ae=await o.rewind?.(n.sessionId,H);return Ae?(n.messages=Ae.messages,n.uiHistory=Es(Ae.uiHistory),n.title=Ae.title,n.contextTokenSnapshot=void 0,q.current=n.uiHistory??[],Un(null),ie(),Mo([]),console.log(Ve.green(`
|
|
403
|
+
[Rewound session${H?` to ${H}`:" to previous turn"}]`)),console.log(Ve.dim(` Messages: ${Ae.messages.length}`)),"rewound"):"failed"},"rewindSession"),getCostReport:i(()=>L.current?.()??null,"getCostReport"),getAutoModeStats:i(()=>{if(Qt(pn.current))return l.getGuardrail().getStats()},"getAutoModeStats"),setAutoModeEngine:i(H=>{Qt(pn.current)&&(l.getGuardrail().setEngine(H),Nf(H))},"setAutoModeEngine"),createKodaXOptions:i(()=>({...Ye.current,provider:V.provider,model:V.model,thinking:V.thinking,reasoningMode:V.reasoningMode,agentMode:V.agentMode,guardrails:lh(pn.current,l),events:Jf()}),"createKodaXOptions"),reloadAgentsFiles:i(async()=>{let H=await lm({cwd:process.cwd(),projectRoot:n.gitRoot??void 0});return g(H),H},"reloadAgentsFiles"),startCompacting:i(()=>{F()},"startCompacting"),stopCompacting:i(()=>{J()},"stopCompacting"),onCompactStats:i(H=>{Os.current=H.tokensBefore,Un(H.tokensAfter)},"onCompactStats"),confirm:i(async H=>(await mr("confirm",{_alwaysConfirm:!0,_message:H})).confirmed,"confirm"),ui:{select:i(async(H,le)=>GI(H,le),"select"),confirm:i(async H=>(await mr("confirm",{_alwaysConfirm:!0,_message:H})).confirmed,"confirm"),input:i(async(H,le)=>Fy(H,le),"input")}},_e=[],on=console.log;console.log=(...H)=>{let le=H.map(Ae=>typeof Ae=="string"?Ae:String(Ae)).join(" ");_e.push(le)};let gn;try{let H=await us(j,n,ge,V);typeof H=="object"&&H!==null&&"invocation"in H&&(gn=H.invocation)}finally{console.log=on}if(_e.length>0&&v({type:"info",text:_e.join(`
|
|
404
|
+
`)}),gn){fe(!1),Ie(),fe(!0),Re(),ce();try{await jy(gn,S.trim())}catch(H){let le=H instanceof Error?H:new Error(String(H)),Ae=le.name==="AbortError"||le.message.includes("aborted")||le.message.includes("ABORTED");console.log=on,Ae?Il():ua([{type:"error",text:le.message}])}finally{fe(!1),Ie(),Q()}return}fe(!1),Ie();return}let re=await _g(S.trim());if(S.trim().startsWith("!")&&hc(re)){fe(!1),Ie();return}let ye=Ye.current.context?.executionCwd??process.cwd(),ut=i(ge=>{ge.length!==0&&ua(ge.map(_e=>({type:"info",text:_e})))},"emitArtifactWarnings");ce();let Nt=[],da=console.log;console.log=(...ge)=>{let _e=ge.map(on=>typeof on=="string"?on:String(on)).join(" ");Nt.push(_e)};try{await Al(re,async ge=>{let _e=yc(ge,Ye.current.context?.executionCwd??process.cwd());return ut(_e.warnings),ca(Ye.current,_e.promptText,n.messages,_e.inputArtifacts)})}catch(ge){let _e=ge instanceof Error?ge:new Error(String(ge));if(_e.name==="AbortError"||_e.message.includes("aborted")||_e.message.includes("ABORTED"))console.log=da,Il();else{let gn=_e.message;_e.message.includes("rate limit")||_e.message.includes("Rate limit")?gn=`[Rate Limit] ${_e.message}
|
|
405
|
+
Suggestion: Wait a moment and try again, or switch provider with /mode`:_e.message.includes("API key")||_e.message.includes("not configured")?gn=`[Configuration Error] ${_e.message}
|
|
406
|
+
Suggestion: Set the required API key environment variable`:_e.message.includes("network")||_e.message.includes("ECONNREFUSED")||_e.message.includes("ETIMEDOUT")?gn=`[Network Error] ${_e.message}
|
|
407
|
+
Suggestion: Check your internet connection`:(_e.message.includes("token")||_e.message.includes("context too long"))&&(gn=`[Context Error] ${_e.message}
|
|
408
|
+
Suggestion: Use /clear to start fresh`),console.log=da,nt.current.workerId?fn({id:`error-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"error",text:gn,timestamp:Date.now()}):ua([{type:"error",text:gn}])}}finally{if(console.log=da,Nt.length>0){let _e=Nt.filter((on,gn,H)=>H.indexOf(on)===gn);v({type:"info",text:_e.join(`
|
|
409
|
+
`)})}if(!Ze.current){let _e=Gs(P.Cancelled,()=>({error:"Run ended before the tool result was observed.",output:void 0}));_e.length>0&&nt.current.workerId&&_e.forEach(on=>_n(on))}fe(!1),Ie(),je(),Q();let ge=hr(n.messages);n.contextTokenSnapshot={currentTokens:ge,baselineEstimatedTokens:ge,source:"estimate"},Un(ge)}},[Fn,n,V,hf,C.pendingInputs.length,o,qe,$e,y,a,v,ie,Re,Ie,je,Jf,jy,Rt,Qe,ee,El,tm,la,go,Al,em,F,J,$o,Gs,_n,Vs]),XI=se(Id,{left:se(bd,{items:fy}),right:se(vd,{items:my}),queued:se(vg,{pendingInputs:C.pendingInputs}),stashNotice:se(_d,{text:xl}),notifications:se(Ad,{notifications:yl}),inlineNotices:Uf.length>0?se(Ig,{notices:Uf}):void 0,activityBar:No||K&&mo.shouldRender?Kt(k,{paddingX:1,flexDirection:"row",children:[Kt(k,{flexGrow:1,children:[No?.showSpinner?se(kn,{color:ne("dark").colors.accent}):null,No?Kt(b,{color:No.kind==="waiting"?ne("dark").colors.warning:ne("dark").colors.accent,children:[No.showSpinner?" ":"",No.text]}):null,No?.showSpinner&&C.roundStartedAt!=null?se(qT,{roundStartedAt:C.roundStartedAt,charCount:C.currentResponse.length,theme:ne("dark")}):null]}),K&&mo.shouldRender?se(b,{dimColor:!0,children:`${mo.completedCount}/${mo.totalCount} completed`}):null]}):void 0,todoSurface:K&&mo.shouldRender?se(k,{paddingX:1,children:se(lb,{viewModel:mo})}):void 0,composer:se(pg,{onSubmit:zI,onHistoryRecall:VI,onPopPendingInputs:i(()=>{let f=Vt();if(f.length!==0)return f.join(`
|
|
410
|
+
---
|
|
411
|
+
`)},"onPopPendingInputs"),prompt:">",placeholder:Av({isLoading:K,canQueueFollowUps:hf,waitingReason:Bf}),focus:!qe&&!$e&&!it,cwd:process.cwd(),gitRoot:e.context?.gitRoot||n.gitRoot,onInputChange:LI}),inlineSuggestions:HI,helpSurface:Uh?se(hg,{sections:Xd()}):void 0,taskBar:ea?se($d,{items:li.backgroundTask.items,overflowLabel:li.backgroundTask.overflowLabel,ctaHint:li.backgroundTask.ctaHint,showSpinner:K}):void 0,statusLine:se(k,{children:se(ys,{...gl,viewModel:uy})}),inlineDialogs:WI}),YI=se(Id,{left:se(bd,{items:fy}),right:se(vd,{items:my}),stashNotice:se(_d,{text:xl}),notifications:se(Ad,{notifications:yl}),composer:se(ib,{searchActive:it,selectionActive:!!(fo||Xe),showAllActive:bt,searchQuery:Wt,searchCurrent:vt.length>0?Oo+1:0,searchCount:vt.length,searchDetailText:Of,pendingLiveUpdates:Ys,secondaryText:NI}),taskBar:ea?se($d,{items:li.backgroundTask.items,overflowLabel:li.backgroundTask.overflowLabel,ctaHint:li.backgroundTask.ctaHint,showSpinner:st}):void 0,statusLine:se(k,{children:se(ys,{...gl,viewModel:Ff})})}),nm=z(f=>se(sb,{banner:f?.bannerVisible?se(dh,{...dr}):void 0,items:Qs,isLoading:Ut,viewportRows:jt.messageRows,viewportWidth:M,scrollOffset:En,windowed:!!f?.rendererWindow,rendererWindow:f?.rendererWindow,transcriptModel:f?.rendererWindow?Js:cl,maxLines:yt,selectedTextRanges:_f?jc?.rowRanges:void 0,onMetricsChange:Sl,onVisibleRowsChange:Tl}),[dr,Qs,Ut,Sl,Tl,En,cl,M,yt,jc?.rowRanges,jt.messageRows,_f]),om=z(f=>se(ab,{banner:f?.bannerVisible?se(dh,{...dr}):void 0,items:qs,browse:{hintText:Do.browseHintText},selection:wl,search:ay,isLoading:st,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:V.agentMode,managedPhase:st?W?.phase:void 0,managedHarnessProfile:st?W?.harnessProfile:void 0,managedWorkerTitle:st?W?.activeWorkerTitle:void 0,managedRound:st?W?.currentRound:void 0,managedMaxRounds:st?W?.maxRounds:void 0,managedGlobalWorkBudget:st?W?.globalWorkBudget:void 0,managedBudgetUsage:st?W?.budgetUsage:void 0,managedBudgetApprovalRequired:st?W?.budgetApprovalRequired:void 0,lastLiveActivityLabel:pe.lastLiveActivityLabel,viewportRows:jt.messageRows,viewportWidth:M,scrollOffset:En,windowed:!!f?.windowed,animateSpinners:!!f?.rendererWindow&&di,rendererWindow:f?.rendererWindow,transcriptModel:f?.rendererWindow?Js:ll,maxLines:yt,showDetailedTools:bt,showAllContent:bt,selectedItemId:mn.selectionEnabled?Xe:void 0,selectedTextRanges:ir?.rowRanges,expandedItemKeys:mn.selectionEnabled?tn:void 0,onMetricsChange:Sl,onVisibleRowsChange:Tl}),[dr,V.agentMode,st,tn,s.transcriptSpinnerAnimation,Sl,Tl,En,Qh,W?.activeWorkerTitle,W?.budgetApprovalRequired,W?.budgetUsage,W?.currentRound,W?.globalWorkBudget,W?.harnessProfile,W?.maxRounds,W?.phase,Js,ll,Do.browseHintText,Xe,wl,M,di,qs,yt,pe.activeToolCalls,pe.currentIteration,pe.currentResponse,pe.currentTool,pe.isCompacting,pe.isThinking,pe.iterationHistory,pe.lastLiveActivityLabel,pe.thinkingCharCount,pe.thinkingContent,pe.toolInputCharCount,pe.toolInputContent,ir?.rowRanges,ay,bt,jt.messageRows]),qI=oe?om({bannerVisible:!1,windowed:xt}):nm({bannerVisible:!1}),Gy=oe?YI:XI,QI=s.enabled&&si,Ky=Kt(k,{flexDirection:"column",width:M,flexShrink:0,flexGrow:QI?1:0,children:[se(Wg,{currentConfig:V,setCurrentConfig:Ce,isLoading:K,abort:Se,stopThinking:Y,clearThinkingContent:Q,setCurrentTool:be,setIsLoading:fe,onToggleHelp:PI,setShowHelp:jh,onSetThinking:i(f=>{Ye.current.thinking=f},"onSetThinking"),onSetReasoningMode:i(f=>{Ye.current.reasoningMode=f,Ye.current.thinking=f!=="off"},"onSetReasoningMode"),onToggleTranscriptMode:UI,onOpenTranscriptSearch:Kf,canOpenTranscriptSearch:oe&&!qe&&!$e,isInteractiveDialogActive:!!(qe||$e),onSetAgentMode:i(f=>{Ye.current.agentMode=f},"onSetAgentMode"),onSetPermissionMode:i(f=>{Qf(f)},"onSetPermissionMode"),isInputEmpty:yf,onSavePermissionMode:Va}),Wn&&(s.enabled?null:se(Qi,{items:[1],children:i(()=>se(dh,{...dr},"banner"),"children")})),si?se(ug,{width:M,stickyHeader:Do.stickyHeader,jumpToLatest:Do.jumpToLatest,transcript:!s.enabled||!xt?oe?om({bannerVisible:!1}):nm({bannerVisible:!1}):void 0,renderTranscriptWindow:s.enabled&&xt?f=>(()=>{let S=ra(f).contentWindow;return oe?om({bannerVisible:!1,windowed:!0,rendererWindow:S}):nm({bannerVisible:!1,rendererWindow:S})})():void 0,overlay:Xf,scrollTop:En,scrollHeight:oa,viewportHeight:jt.messageRows,stickyScroll:!oe&&!Po&&Sf,scrollRef:TI,onWindowChange:FI,onScrollTopChange:bI,onStickyChange:vI,footer:Gy}):Kt(lO,{children:[Kt(k,{flexDirection:"column",flexGrow:1,children:[qI,Xf?se(k,{position:"absolute",bottom:0,left:0,right:0,flexDirection:"column",children:Xf}):null]}),Gy]})]});return Af?se(Ym,{mouseTracking:Lo.usesRendererMouseTracking,children:Ky}):Ky},"InkREPLInner"),CO=i(e=>{let t=process.cwd(),n=e.options?.context?.gitRoot??void 0;return se(Rd,{children:se(Pd,{children:se(bu,{children:se(Hg,{children:se(Up,{cwd:t,gitRoot:n,children:se(TO,{...e})})})})})})},"InkREPL");function bO(){return process.stdin.isTTY===!0&&typeof process.stdin.setRawMode=="function"}i(bO,"isRawModeSupported");async function hh(e){if(!bO())throw new sm("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 Cs,n=Cr(),o=br(),r=vr(n,o),{prepareRuntimeConfig:s,getGitRoot:a}=await import("./utils-TV3UYCHQ.js"),{loadCompactionConfig:c}=await import("./compaction-config-NAPRF7XR.js"),{resolveProvider:l}=await import("./dist-CCYBJJZY.js"),d=s(),m=e.provider??d.provider??_l,p=e.model??d.model,g=uO(e,d),x=e.agentMode??d.agentMode??"ama",y=g!=="off",T=Zn(d.permissionMode,"accept-edits")??"accept-edits",w=Ll(),I=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:I},$=e.session?.id,D=[],L,X,v,ie="",Te=await a().catch(()=>null)??void 0,G=$l({meta:{cwd:process.cwd(),startedAt:Date.now()}});if(G){let ae=i(()=>{G.shutdown()},"teamModeCleanup");process.on("exit",ae),process.on("SIGTERM",ae)}try{let{bootstrapConstructionRuntime:ae}=await import("./construction-bootstrap-PHTGBRNU.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)`:"",be=Y.tampered>0?`; ${Y.tampered} skipped due to manifest contentHash mismatch \u2014 re-stage and re-activate to re-approve`:"";console.log(Ve.dim(`[Constructed] Rehydrated ${Y.loaded} active tool(s)${Q}${be}.`))}if(Y.markdownLoaded>0||Y.markdownFailures.length>0){console.log(Ve.dim(`[Agents] Loaded ${Y.markdownLoaded} markdown agent(s).`));for(let Q of Y.markdownFailures)console.warn(Ve.yellow(`[Agents] Skipped ${Q.path}: ${Q.reason}`))}}catch(ae){console.warn(Ve.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=Es(ae.uiHistory),X=ae.lineage,v=ae.artifactLedger,ie=ae.title,$=e.session.id,console.log(Ve.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=Es(Q.uiHistory),X=Q.lineage,v=Q.artifactLedger,ie=Q.title,$=Y.id,console.log(Ve.green(`[Continuing session: ${Y.id}]`)))}}}let M=await mc({sessionId:$,gitRoot:Te,existingMessages:D,existingUiHistory:L,existingLineage:X,existingArtifactLedger:v});M.title=ie,G?.writer.update({sessionId:M.sessionId});let Z={current:await lm({cwd:process.cwd(),projectRoot:Te??void 0})},Re={current:null},Ie={current:null},Se={current:O},ce=Lu(),Ne=await gc({askUser:i(async(ae,Y,Q)=>{let be=Re.current;return be?be(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(Ve.yellow(Y)):console.log(Ve.dim(Y))},"log"),onEngineChange:i(ae=>{Ie.current?.(ae)},"onEngineChange"),extraCollectors:[Ba]});try{let ae=process.stdout,Y=process.stdin;import("./paste-5DSTHQGK.js").then(Ee=>Ee.prunePasteTmpDir()).catch(()=>{});let Q=!1,{waitUntilExit:be,cleanup:ve}=hu(se(CO,{options:e,config:O,context:M,storage:t,compactionInfo:q,rendererMode:o,fullscreenPolicy:r,autoModeBootstrap:Ne,setAutoModeAskUser:i(Ee=>{Re.current=Ee},"setAutoModeAskUser"),setAutoModeEngineChange:i(Ee=>{Ie.current=Ee},"setAutoModeEngineChange"),setCurrentConfigRef:i(Ee=>{Se.current=Ee},"setCurrentConfigRef"),onAgentsFilesReload:i(Ee=>{Z.current=Ee},"onAgentsFilesReload"),teamModeHandle:G,onExit:i(()=>{Q=!0},"onExit")}),{stdout:ae,stdin:Y,exitOnCtrlC:!1,patchConsole:!1,maxFps:30,shellMode:r.enabled?r.promptShell:"main-screen"});await be(),ve(),G?.shutdown(),Y.isTTY===!0&&typeof Y.setRawMode=="function"&&Y.isRaw&&Y.setRawMode(!1),Y.pause?.(),Y.unref?.(),Q&&console.log(Ve.dim(`
|
|
412
|
+
[Exiting KodaX...]`));let lt=e.hardExitOnClose??process.env.VITEST!=="true";if(Q&<){let Ee=process.exitCode??0,je=!1,xe=i(()=>{je||(je=!0,process.exit(Ee))},"requestProcessExit");setTimeout(xe,0).unref?.(),ae.write("",xe);return}}catch(ae){throw ae instanceof Error&&ae.message.includes("Raw mode")?new sm("Interactive mode failed to start.",['kodax -p "your task" # Run a single task',"kodax -c # Continue last session"]):ae}}i(hh,"runInkInteractiveMode");import ln from"chalk";var m0=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],p0=["\x1B[36m","\x1B[35m","\x1B[34m"],Tc=null,Ms=!1;function Sc(){let e=0,t=0,n=!1,o="Thinking...",r=i(()=>{if(n)return;let c=p0[t%p0.length],l="\x1B[0m",d=m0[e%m0.length];process.stdout.write(`\r${c}${d}${l} ${o}`)},"renderFrame"),s=setInterval(()=>{e++,e%10===0&&t++,r()},80);r();let a={stop:i(()=>{n||(n=!0,clearInterval(s),process.stdout.write("\r\x1B[K"))},"stop"),isStopped:i(()=>n,"isStopped"),updateText:i(c=>{o=c},"updateText")};return Tc=a,a}i(Sc,"startWaitingDots");function vO(e=!0){let t=null,n=0,o=!1;return{onSessionStart:i(s=>{console.log(e?ln.cyan(`[KodaX] Provider: ${s.provider} | Session: ${s.sessionId}`):ln.cyan(`[KodaX] Provider: ${s.provider}`))},"onSessionStart"),onTextDelta:i(s=>{t&&(t.stop(),t=null),n=0,process.stdout.write(s),o=!0},"onTextDelta"),onThinkingDelta:i(s=>{n+=s.length,t||(t=Sc()),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(ln.dim(`[Thinking] ${c}`))}},"onThinkingEnd"),onToolUseStart:i(s=>{t||(Ms||(process.stdout.write(`
|
|
413
|
+
`),Ms=!0),t=Sc()),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())&&(Ms||(process.stdout.write(`
|
|
414
|
+
`),Ms=!0,o=!1),t=Sc(),t.updateText(`Receiving ${s}... (${l} chars)`))},"onToolInputDelta"),onToolResult:i(s=>{t&&(t.stop(),t=null),console.log(ln.green(`[Result] ${s.content.slice(0,300)}${s.content.length>300?"...":""}`))},"onToolResult"),onRepoIntelligenceTrace:i(s=>{t&&(t.stop(),t=null),console.log(ln.dim(`[RepoIntel] ${s.summary}`))},"onRepoIntelligenceTrace"),onStreamEnd:i(()=>{Tc&&!Tc.isStopped()&&Tc.stop(),Tc=null,Ms=!1,o&&(console.log(),o=!1),(!t||t.isStopped())&&(t=Sc(),t.updateText("Processing..."))},"onStreamEnd"),onIterationStart:i((s,a)=>{t&&!t.isStopped()&&t.stop(),Ms=!1,o=!1,console.log(ln.magenta(`
|
|
415
|
+
[Assistant]`)),t=Sc()},"onIterationStart"),onCompactStart:i(()=>{console.log(ln.dim(`
|
|
416
|
+
[KodaX] Compacting context...`))},"onCompactStart"),onCompact:i(s=>{console.log(ln.dim(`[KodaX] Compaction finished (${s} tokens).`))},"onCompact"),onCompactEnd:i(()=>{},"onCompactEnd"),onRetry:i((s,a,c)=>{console.log(ln.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(ln.yellow(`[KodaX] ${a} (${s.errorClass}, ${s.stage})`))},"onProviderRecovery"),onComplete:i(()=>{t&&(t.stop(),t=null),console.log(ln.green(`
|
|
417
|
+
[KodaX] Done!`))},"onComplete"),onError:i(s=>{t&&(t.stop(),t=null),console.log(ln.red(`
|
|
418
|
+
[Error] ${s.message}`))},"onError"),onScoutSuspiciousCompletion:i(s=>{console.log(ln.yellow(`
|
|
419
|
+
[Scout] Completion marked uncertain \u2014 signals: ${s.signals.join(", ")}. Verify the result before continuing.`))},"onScoutSuspiciousCompletion"),beforeToolExecute:i(async(s,a)=>!0,"beforeToolExecute")}}i(vO,"createCliEvents");function ct(e,t){e.write(`${JSON.stringify(t)}
|
|
420
|
+
`)}i(ct,"writeJsonLine");function IO(e){return{type:"error",name:e.name,message:e.message,stack:e.stack}}i(IO,"serializeError");function kO(e={}){let t=e.stdout??process.stdout,n=e.stderr??process.stderr;return{onSessionStart:i(o=>{ct(t,{type:"session.start",provider:o.provider,sessionId:o.sessionId})},"onSessionStart"),onIterationStart:i((o,r)=>{ct(t,{type:"iteration.start",iter:o,maxIter:r})},"onIterationStart"),onIterationEnd:i(o=>{ct(t,{type:"iteration.end",iter:o.iter,maxIter:o.maxIter,tokenCount:o.tokenCount,tokenSource:o.tokenSource,usage:o.usage,contextTokenSnapshot:o.contextTokenSnapshot})},"onIterationEnd"),onTextDelta:i(o=>{ct(t,{type:"text.delta",text:o})},"onTextDelta"),onThinkingDelta:i(o=>{ct(t,{type:"thinking.delta",text:o})},"onThinkingDelta"),onThinkingEnd:i(o=>{ct(t,{type:"thinking.end",thinking:o})},"onThinkingEnd"),onToolUseStart:i(o=>{ct(t,{type:"tool.start",id:o.id,name:o.name,input:o.input})},"onToolUseStart"),onToolInputDelta:i((o,r,s)=>{ct(t,{type:"tool.input.delta",toolName:o,partialJson:r,toolId:s?.toolId})},"onToolInputDelta"),onToolResult:i(o=>{ct(t,{type:"tool.result",id:o.id,name:o.name,content:o.content})},"onToolResult"),onStreamEnd:i(()=>{ct(t,{type:"stream.end"})},"onStreamEnd"),onCompactStart:i(()=>{ct(t,{type:"compact.start"})},"onCompactStart"),onCompact:i(o=>{ct(t,{type:"compact.finish",estimatedTokens:o})},"onCompact"),onCompactStats:i(o=>{ct(t,{type:"compact.stats",tokensBefore:o.tokensBefore,tokensAfter:o.tokensAfter})},"onCompactStats"),onCompactEnd:i(()=>{ct(t,{type:"compact.end"})},"onCompactEnd"),onRetry:i((o,r,s)=>{ct(t,{type:"retry",reason:o,attempt:r,maxAttempts:s})},"onRetry"),onProviderRecovery:i(o=>{ct(t,{type:"provider.recovery",stage:o.stage,reasonCode:o.errorClass,attempt:o.attempt,maxAttempts:o.maxAttempts,delayMs:o.delayMs,nextAt:Date.now()+o.delayMs,recoveryAction:o.recoveryAction,fallbackUsed:o.fallbackUsed})},"onProviderRecovery"),onProviderRateLimit:i((o,r,s)=>{ct(t,{type:"provider.rate_limit",attempt:o,maxRetries:r,delayMs:s})},"onProviderRateLimit"),onRepoIntelligenceTrace:i(o=>{ct(t,{type:"repo_intelligence.trace",stage:o.stage,summary:o.summary,capability:o.capability,trace:o.trace})},"onRepoIntelligenceTrace"),onToolProgress:i(o=>{ct(t,{type:"tool.progress",id:o.id,message:o.message})},"onToolProgress"),onManagedTaskStatus:i(o=>{ct(t,{type:"managed_task.status",agentMode:o.agentMode,harnessProfile:o.harnessProfile,phase:o.phase,activeWorkerId:o.activeWorkerId,activeWorkerTitle:o.activeWorkerTitle,childFanoutClass:o.childFanoutClass,childFanoutCount:o.childFanoutCount,currentRound:o.currentRound,maxRounds:o.maxRounds,note:o.note,detailNote:o.detailNote,globalWorkBudget:o.globalWorkBudget,budgetUsage:o.budgetUsage,budgetApprovalRequired:o.budgetApprovalRequired})},"onManagedTaskStatus"),onScoutSuspiciousCompletion:i(o=>{ct(t,{type:"scout.suspicious_completion",confidence:o.confidence,signals:o.signals,sessionId:o.sessionId,lastTextPreview:o.lastTextPreview})},"onScoutSuspiciousCompletion"),onComplete:i(()=>{ct(t,{type:"complete"})},"onComplete"),onError:i(o=>{ct(n,IO(o))},"onError")}}i(kO,"createJsonEvents");import{jsx as dt,jsxs as Zt}from"react/jsx-runtime";import _O,{useMemo as Cc}from"react";var yh=/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@.*$/,g0=/^---\s+(.+)$/;function h0(e){if(!e)return[];let t=e.split(`
|
|
421
|
+
`),n=[],o=[],r=[],s=!1,a=null,c=null,l=0,d=0,m=i(()=>{if(o.length===0)return;let g=o.join(`
|
|
422
|
+
`);g.length>0&&n.push({kind:"text",text:g}),o=[]},"flushText"),p=i(()=>{r.length!==0&&(n.push({kind:"diff",text:r.join(`
|
|
423
|
+
`),addedLines:l,removedLines:d,filePath:c}),r=[],l=0,d=0,c=null)},"flushDiff");for(let g=0;g<t.length;g++){let x=t[g];if(!s){let w=g0.exec(x);if(w){let I=Math.min(g+3,t.length-1),O=!1;for(let $=g+1;$<=I;$++)if(t[$]?.startsWith("+++ ")||yh.test(t[$]??"")){O=!0;break}if(O){m(),s=!0,a=w[1]??null,c=a,r.push(x);continue}}if(yh.test(x)){m(),s=!0,r.push(x);continue}o.push(x);continue}let y=g0.exec(x);if(y){let w=Math.min(g+3,t.length-1),I=!1;for(let O=g+1;O<=w;O++)if(t[O]?.startsWith("+++ ")||yh.test(t[O]??"")){I=!0;break}if(I){p(),c=y[1]??null,r.push(x);continue}}let T=x[0];if(T==="+"||T==="-"||T===" "||T==="@"||x===""){T==="+"&&!x.startsWith("+++ ")&&l++,T==="-"&&!x.startsWith("--- ")&&d++,r.push(x);continue}p(),s=!1,a=null,o.push(x)}return p(),m(),n}i(h0,"parseUnifiedDiff");function y0(e){return e?/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/m.test(e):!1}i(y0,"containsUnifiedDiff");import{jsxs as As,jsx as RO}from"react/jsx-runtime";import EO from"react";function MO(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(MO,"classifyLine");function AO(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(AO,"colorFor");var xh=EO.memo(({text:e,addedLines:t,removedLines:n,filePath:o,theme:r,maxLines:s=16,extremeThreshold:a=200})=>{let c=r??ne("dark"),l=e.split(`
|
|
424
|
+
`),d=l.map(MO),m=`(${t>0?`+${t}`:"\xB10"} ${n>0?`-${n}`:""})`.trim();if(l.length>a)return As(k,{flexDirection:"column",marginLeft:4,children:[o&&As(b,{dimColor:!0,children:[o," ",m]}),As(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 As(k,{flexDirection:"column",marginLeft:4,children:[o&&As(b,{dimColor:!0,children:[o," ",m]}),p.map((x,y)=>{if(y===Math.floor(s/2)&&g>0&&x.kind==="context"&&x.text==="")return As(b,{dimColor:!0,children:["... ",g," lines collapsed ..."]},`collapse-${y}`);let w=AO(x.kind,c);return RO(b,{color:w,children:x.text||" "},y)})]})});xh.displayName="DiffHunk";function x0(e){switch(e){case P.Scheduled:return"\u25CB";case P.Validating:return"\u25D0";case P.AwaitingApproval:return"\u23F8";case P.Executing:return"\u25CF";case P.Success:return"\u2713";case P.Error:return"\u2717";case P.Cancelled:return"\u2298";default:return"?"}}i(x0,"getStatusIcon");function w0(e,t){switch(e){case P.Scheduled:case P.Validating:return t.colors.dim;case P.AwaitingApproval:return t.colors.accent;case P.Executing:return t.colors.primary;case P.Success:return t.colors.success??t.colors.primary;case P.Error:return t.colors.error;case P.Cancelled:return t.colors.dim;default:return t.colors.text}}i(w0,"getStatusColor");function $O(e,t){if(!t)return"";let n=t-e;return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}i($O,"formatDuration");function PO(e){if(!e)return"";let t=JSON.stringify(e);return t.length<=50?t:t.slice(0,47)+"..."}i(PO,"formatInputSummary");var LO=i(({status:e,theme:t})=>{let n=t??Cc(()=>ne("dark"),[]),o=x0(e),r=w0(e,n);return dt(b,{color:r,children:o})},"ToolStatusBadge"),S0=i(({progress:e,width:t=20,theme:n})=>{let o=n??Cc(()=>ne("dark"),[]),r=Math.max(0,Math.min(100,e)),s=Math.round(r/100*t),a=t-s,c="\u2588".repeat(s),l="\u2591".repeat(a);return Zt(k,{children:[dt(b,{color:o.colors.primary,children:c}),dt(b,{dimColor:!0,children:l}),Zt(b,{children:[" ",r,"%"]})]})},"ToolProgressBar"),T0=i(({tool:e,collapsed:t=!1,theme:n})=>{let o=n??Cc(()=>ne("dark"),[]),r=x0(e.status),s=w0(e.status,o),a=PO(e.input),c=$O(e.startTime,e.endTime);return t?Zt(k,{children:[Zt(b,{color:s,children:[r," "]}),dt(b,{color:o.colors.text,children:e.name})]}):Zt(k,{flexDirection:"column",marginLeft:2,children:[Zt(k,{children:[Zt(b,{color:s,children:[r," "]}),dt(b,{color:o.colors.text,bold:!0,children:e.name}),a&&Zt(b,{dimColor:!0,children:[" ",a]})]}),e.progress!==void 0&&e.status===P.Executing&&dt(k,{marginLeft:2,children:dt(S0,{progress:e.progress,theme:o})}),e.progressLines&&e.progressLines.length>0&&e.status===P.Executing&&dt(k,{flexDirection:"column",marginLeft:2,children:e.progressLines.slice(-5).map((l,d)=>dt(b,{dimColor:!0,children:l},d))}),e.error&&dt(k,{marginLeft:2,children:dt(b,{color:o.colors.error,children:e.error})}),e.status===P.Success&&typeof e.output=="string"&&e.output.length>0&&dt(C0,{output:e.output,theme:o}),c&&e.status!==P.Executing&&dt(k,{marginLeft:2,children:Zt(b,{dimColor:!0,children:["Completed in ",c]})})]})},"ToolCallDisplay"),C0=_O.memo(({output:e,theme:t})=>{if(!y0(e))return dt(k,{marginLeft:2,children:dt(b,{dimColor:!0,children:e})});let n=h0(e);return dt(k,{flexDirection:"column",marginLeft:2,children:n.map((o,r)=>o.kind==="text"?dt(b,{dimColor:!0,children:o.text},r):dt(xh,{text:o.text,addedLines:o.addedLines,removedLines:o.removedLines,filePath:o.filePath,theme:t},r))})});C0.displayName="ToolOutputBlock";var OO=i(({tools:e,collapsed:t=!1,title:n,theme:o})=>{let r=o??Cc(()=>ne("dark"),[]);if(e.length===0)return null;let s=Cc(()=>{let c={[P.Scheduled]:0,[P.Validating]:0,[P.AwaitingApproval]:0,[P.Executing]:0,[P.Success]:0,[P.Error]:0,[P.Cancelled]:0};for(let l of e)c[l.status]++;return c},[e]),a=n??"Tools";if(t){let c=s[P.Success],l=s[P.Error],d=s[P.Executing]+s[P.Scheduled]+s[P.Validating];return dt(k,{flexDirection:"column",marginBottom:1,children:Zt(k,{children:[dt(b,{color:r.colors.accent,bold:!0,children:a}),Zt(b,{dimColor:!0,children:[" ","(",e.length," tools",c>0&&`, ${c} succeeded`,l>0&&`, ${l} failed`,d>0&&`, ${d} running`,")"]})]})})}return Zt(k,{flexDirection:"column",marginBottom:1,children:[Zt(k,{children:[dt(b,{color:r.colors.accent,bold:!0,children:a}),Zt(b,{dimColor:!0,children:[" ","(",e.length," ",e.length===1?"tool":"tools",")"]})]}),e.map(c=>dt(T0,{tool:c,theme:r},c.id))]})},"ToolGroup");import{jsxs as b0,jsx as DO}from"react/jsx-runtime";var NO=i(({pendingInputs:e})=>{let t=UC(e);if(!t)return null;let n=ne("dark");return b0(k,{children:[b0(b,{color:n.colors.hint,children:["\u23F3"," "]}),DO(b,{color:n.colors.dim,children:t})]})},"PendingInputsIndicator");import*as v0 from"child_process";var bc;function BO(){if(process.platform!=="win32")return null;if(bc!==void 0)return bc;try{bc=v0.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{bc=null}return bc}i(BO,"detectWindowsCodePage");function tf(){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(tf,"supportsTrueColor");function I0(){if(tf())return!0;let e=process.env.TERM||"";return e.includes("256color")||e==="xterm-256color"||e==="screen-256color"||e==="tmux-256color"}i(I0,"supports256Colors");function Eo(){let e=process.env,t=e.LC_ALL||"",n=e.LC_CTYPE||"",o=e.LANG||"";if(t==="C"||t==="POSIX"||n==="C"||n==="POSIX"||o==="C"||o==="POSIX")return!1;let r=`${t}|${n}|${o}`.toLowerCase();return r.includes("utf-8")||r.includes("utf8")?!0:process.platform==="win32"?e.WT_SESSION||e.TERM_PROGRAM==="vscode"?!0:BO()==="65001":!0}i(Eo,"supportsUnicode");function k0(){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(k0,"supportsEmoji");function R0(){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(R0,"getTerminalWidth");function E0(){let e=process.env;return!!(e.NO_COLOR||e.TERM==="dumb"||e.CI)}i(E0,"isScreenReader");function HO(){return process.stdout?.isTTY??!1}i(HO,"isTTY");function FO(){return{trueColor:tf(),colors256:I0(),unicode:Eo(),emoji:k0(),tty:HO(),columns:R0(),screenReader:E0()}}i(FO,"detectTerminalCapabilities");var vc=class{static{i(this,"ConsoleCapturer")}captured=[];originalLog=null;start(){this.captured=[],this.originalLog=console.log,console.log=(...t)=>{let n=t.map(o=>typeof o=="string"?o:String(o)).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 WO(e){let t=new vc;t.start();try{let n=await e(),o=t.stop();return{result:n,captured:o}}finally{t.stop()}}i(WO,"withCapture");function UO(e){let t=new vc;t.start();try{let n=e(),o=t.stop();return{result:n,captured:o}}finally{t.stop()}}i(UO,"withCaptureSync");import*as D0 from"readline";import*as N0 from"child_process";import*as Ac from"path";import*as Mc from"fs";import*as B0 from"os";import U from"chalk";import Bn from"chalk";var jO=[{key:"y",label:"Yes",description:"Confirm the action",value:"yes"},{key:"n",label:"No",description:"Cancel the action",value:"no"}],GO=[{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 KO(e,t=!0){return e.map(n=>{let o=Bn.dim(`[${n.key}]`);return t?`${o} ${Bn.cyan(n.label)} ${Bn.dim(`- ${n.description}`)}`:`${o} ${n.label}`}).join(" ")}i(KO,"formatOptions");function _s(){return process.stdout.columns??80}i(_s,"getTerminalWidth");function VO(){return Eo()}i(VO,"supportsUnicode");function zO(){let e=VO();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(zO,"getSymbols");async function XO(e,t){let{message:n,default:o,options:r,showDescription:s=!0}=t,a=r??jO,c=KO(a,s);console.log(),console.log(Bn.cyan(`? ${n}`));let l=_s();if(c.length>l-4)for(let d of a){let m=Bn.dim(` [${d.key}]`);console.log(`${m} ${Bn.cyan(d.label)}`),s&&console.log(Bn.dim(` ${d.description}`))}else console.log(Bn.dim(` ${c}`));return new Promise(d=>{let m=o?` (${o})`:"";e.question(Bn.dim(` Choose${m}: `),p=>{let g=p.trim().toLowerCase()||o||"",x=a.find(y=>y.key===g||y.value===g||y.label.toLowerCase()===g);d(x?x.value:g===""?"no":g)})})}i(XO,"confirmEnhanced");async function Ic(e,t,n,o){let{isOutsideProject:r=!1,isProtectedPath:s=!1,permissionMode:a="accept-edits"}=o??{},c=zO(),l,d,m={...n,...r?{_outsideProject:!0}:{},...s?{_alwaysConfirm:!0}:{}},p=Wd(t,m),g=p.details.map(y=>` ${Bn.dim(y)}`);r||s?(l=`${Bn.yellow(c.warning)} Safety Warning`,g.length>0&&(l+=`
|
|
425
|
+
${g.join(`
|
|
426
|
+
`)}`),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+=`
|
|
427
|
+
${g.join(`
|
|
428
|
+
`)}`),d=a==="accept-edits"?GO:[{key:"y",label:"Yes",description:"Confirm the action",value:"yes"},{key:"n",label:"No",description:"Cancel",value:"no"}]);let x=await XO(e,{message:l,default:"n",options:d});return x==="always"?{confirmed:!0,always:!0}:{confirmed:x==="yes"}}i(Ic,"confirmToolExecution");import en from"chalk";var nf=/\x1b\[[0-9;]*m/g,co={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 YO(e,t){if(t<=0)return"";let n="",o=0,r=0;for(;r<e.length&&o<t;){nf.lastIndex=r;let s=nf.exec(e);if(s&&s.index===r){n+=s[0],r+=s[0].length;continue}n+=e[r],o+=1,r+=1}return n}i(YO,"truncateAnsi");function M0(e){return nf.lastIndex=0,e.replace(nf,"")}i(M0,"stripAnsi");function qO(e,t=_s()){let n=[],o=e.sessionId.slice(0,6);n.push(en.dim(`#${o}`));let r=e.permissionMode==="plan"?en.blue:e.permissionMode==="accept-edits"?en.cyan:e.permissionMode==="auto-in-project"?en.magenta:en.green,s=ts(e.permissionMode),c=(e.permissionMode==="auto"||e.permissionMode==="auto-in-project")&&e.autoModeEngine?e.autoModeEngine==="llm"?en.green("[LLM]"):en.yellow("[RULES]"):"";if(n.push(r(s)+c),e.reasoningMode&&n.push(en.yellow(`reason:${e.reasoningMode}`)),n.push(en.cyan(e.provider)),e.tokenUsage){let m=e.tokenUsage.total,p=m>=1e3?`${(m/1e3).toFixed(1)}k`:String(m);n.push(en.dim(`${p}t`))}if(e.currentTool&&n.push(en.magenta(`tool:${e.currentTool}`)),e.projectInfo){let{completedFeatures:m,totalFeatures:p}=e.projectInfo,g=p>0?Math.round(m/p*100):0;n.push(en.dim(`${m}/${p} [${g}%]`))}e.messageCount!==void 0&&n.push(en.dim(`${e.messageCount} msgs`));let l=n.join(en.dim(" | ")),d=t-1;return M0(l).length>d&&(l=`${YO(l,Math.max(0,d-3))}...`),l}i(qO,"buildStatusBarContent");var of=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=_s(),n=qO(this.state,t),o=n+" ".repeat(Math.max(0,t-M0(n).length));process.stdout.write(co.SAVE_CURSOR+co.MOVE_TO_BOTTOM+co.CLEAR_LINE+co.REVERSE+o+co.RESET+co.RESTORE_CURSOR)}clear(){process.stdout.write(co.SAVE_CURSOR+co.MOVE_TO_BOTTOM+co.CLEAR_LINE+co.RESTORE_CURSOR)}};function A0(e,t,n,o,r="off"){return{sessionId:e,permissionMode:t,reasoningMode:r,provider:n,model:o}}i(A0,"createStatusBarState");function _0(){if(!process.stdout.isTTY||Pi())return!1;let e=process.env.TERM??"",t=process.env.TERM_PROGRAM??"",n=["xterm","xterm-256color","screen","screen-256color","tmux","tmux-256color","vt100","vt220"],o=["iTerm.app","Terminal.app","Apple_Terminal","vscode","Hyper","Alacritty","kitty","Windows Terminal"];return n.some(r=>e.startsWith(r))||o.includes(t)||process.env.WT_SESSION!==void 0}i(_0,"supportsStatusBar");import z4 from"chalk";function $0(){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($0,"getUnicodeSymbols");function wh(){return{prompt:">",success:"[OK]",error:"[X]",warning:"[!]",info:"[i]",arrow:"->",bullet:"*",check:"[v]",cross:"[x]",spinner:["|","/","-","\\","|","/","-","\\"]}}i(wh,"getAsciiSymbols");var P0={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:Eo()?$0():wh(),spinner:{frames:Eo()?["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]:["|","/","-","\\","|","/","-","\\"],interval:80}},QO={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:Eo()?$0():wh(),spinner:{frames:Eo()?["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]:["|","/","-","\\","|","/","-","\\"],interval:80}},JO={name:"minimal",description:"Minimal theme without colors (for CI or limited terminals)",colors:{primary:"",secondary:"",accent:"",text:"",dim:"",success:"",warning:"",error:"",info:""},symbols:wh(),spinner:{frames:[".","o","O","0","O","o"],interval:120}},ZO={dark:P0,light:QO,minimal:JO},L0=P0;function Rc(){return L0}i(Rc,"getCurrentTheme");function kc(e){let t=ZO[e];return t?(L0=t,!0):!1}i(kc,"setTheme");function eD(){if(!process.stdout.isTTY){kc("minimal");return}let e=process.env;if(e.WT_SESSION!==void 0||e.TERM_PROGRAM==="vscode"){kc("dark");return}kc("dark")}i(eD,"autoSelectTheme");eD();var rf=class{static{i(this,"ReadlineUIContext")}rl;constructor(t){this.rl=t}async select(t,n){if(n.length!==0)return console.log(`
|
|
429
|
+
${t}`),console.log("\u2500".repeat(t.length)),n.forEach((o,r)=>{console.log(` ${r+1}. ${o}`)}),console.log(" 0. Cancel"),console.log(""),new Promise(o=>{this.rl.question("Enter choice (0 to cancel): ",r=>{let s=r.trim();if(s==="0"||s===""){o(void 0);return}let a=parseInt(s,10)-1;if(isNaN(a)||a<0||a>=n.length){console.log("Invalid choice. Please try again."),o(void 0);return}o(n[a])})})}async confirm(t){return new Promise(n=>{this.rl.question(`${t} (y/N): `,o=>{let r=o.trim().toLowerCase();n(r==="y"||r==="yes")})})}async input(t,n){let o=n?`${t} [${n}]: `:`${t}: `;return new Promise(r=>{this.rl.question(o,s=>{let a=s.trim();if(a===""&&n!==void 0){r(n);return}r(a||void 0)})})}};var Th=class{static{i(this,"MemorySessionStorage")}sessions=new Map;async save(t,n){let o=this.sessions.get(t),r=xn(n.messages,n.lineage??o?.data.lineage);this.sessions.set(t,{createdAt:o?.createdAt??new Date().toISOString(),data:{...structuredClone(n),scope:n.scope??o?.data.scope??"user",uiHistory:n.uiHistory??o?.data.uiHistory,extensionState:n.extensionState??o?.data.extensionState,extensionRecords:n.extensionRecords??o?.data.extensionRecords,lineage:r}})}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,o){let r=this.sessions.get(t);if(!r?.data.lineage)return null;let s=bi(r.data.lineage,n,o);if(!s)return null;let a={...structuredClone(r.data),messages:Mt(s),lineage:s};return this.sessions.set(t,{...r,data:a}),structuredClone(a)}async setLabel(t,n,o){let r=this.sessions.get(t);if(!r?.data.lineage)return null;let s=vi(r.data.lineage,n,o);if(!s)return null;let a={...structuredClone(r.data),lineage:s};return this.sessions.set(t,{...r,data:a}),structuredClone(a)}async fork(t,n,o){let r=this.sessions.get(t);if(!r?.data.lineage)return null;let s=Ri(r.data.lineage,n);if(!s)return null;let a=o?.sessionId??await Ci(),c={messages:Mt(s),title:o?.title??r.data.title,gitRoot:r.data.gitRoot,runtimeInfo:r.data.runtimeInfo?structuredClone(r.data.runtimeInfo):void 0,scope:r.data.scope??"user",extensionState:r.data.extensionState?structuredClone(r.data.extensionState):void 0,extensionRecords:r.data.extensionRecords?structuredClone(r.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 o=this.sessions.get(t);if(!o?.data.lineage)return null;let r=n??Ii(o.data.lineage);if(!r)return null;let s=ki(o.data.lineage,r);if(!s)return null;let a={...o.data,messages:Mt(s),lineage:s};return this.sessions.set(t,{...o,data:a}),structuredClone(a)}async list(t){return Array.from(this.sessions.entries()).filter(([,n])=>(n.data.scope??"user")==="user").map(([n,o])=>({id:n,title:o.data.title,msgCount:o.data.lineage?xr(o.data.lineage):o.data.messages.length,...o.data.runtimeInfo?{runtimeInfo:structuredClone(o.data.runtimeInfo)}:{}}))}async delete(t){this.sessions.delete(t)}async deleteAll(t){this.sessions.clear()}};function Sh(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(Sh,"applyRuntimeContext");function tD(e){e?.workspaceRoot&&(console.log(U.dim(` Workspace: ${vn(e)}`)),console.log(U.dim(` Use /status workspace for runtime details.
|
|
430
|
+
`)))}i(tD,"printWorkspaceEntryNotice");function nD(e,t){return e.reasoningMode?e.reasoningMode:t.reasoningMode?t.reasoningMode:(e.thinking===!0||t.thinking===!0,"auto")}i(nD,"resolveInitialReasoningMode");var Ch={current:null};async function oD(e){let t=await as({cwd:process.cwd()}),n=t.workspaceRoot??await Sr()??void 0,o=e.storage??new Th,r=$l({meta:{cwd:process.cwd(),startedAt:Date.now()}}),s=hm(),a=e.provider??s.provider??_l,c=e.model??s.model,l=nD(e,s),d=e.agentMode??s.agentMode??"ama",m=l!=="off",p=Zn(s.permissionMode,"accept-edits")??"accept-edits",g=vu();p==="auto-in-project"&&g();let x=Ll(),y=s.theme;y&&kc(y);let T=Rc(),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},I=p,O=is(),$=0,D="",L=!1,X=500,v=await mc({sessionId:e.session?.id,gitRoot:n,runtimeInfo:t});r?.writer.update({sessionId:v.sessionId});let ie=i(A=>Kr(w,A,(_,F,J)=>{console.log((_==="block"?U.red:U.yellow)(`
|
|
431
|
+
${F}`));for(let Be of J)console.log(U.dim(Be));console.log()}),"guardSessionTransition"),Te=await Hl(n??void 0),{resolveProvider:G}=await import("./dist-CCYBJJZY.js"),q=G(w.provider),M=Te.contextWindow??q.getEffectiveContextWindow?.(w.model)??q.getContextWindow?.()??2e5,{loadAgentsFiles:C}=await import("./dist-CCYBJJZY.js"),Z=i(async()=>C({cwd:process.cwd(),projectRoot:v.gitRoot??void 0}),"reloadAgentsFiles"),Re=await Z();aD(w,w.permissionMode,{contextWindow:M,triggerPercent:Te.triggerPercent,enabled:Te.enabled},Re),tD(t);let Ie=$T(()=>v.gitRoot??process.cwd()),Se=D0.createInterface({input:process.stdin,output:process.stdout,terminal:process.stdout.isTTY??!0,historySize:100,completer:i((A,_)=>{Ie(A).then(F=>{_(null,F)}).catch(()=>{_(null,[[],A])})},"completer")}),ce=Lu(),Ne=await gc({askUser:i(async(A,_,F)=>(await Ic(Se,A.name,{...A.input,...F&&F.length>0?{_classifierSignals:F}:{}},{permissionMode:I,reason:`[auto-mode] ${_}`})).confirmed?"allow":"block","askUser"),projectRoot:n??process.cwd(),getAgentsFiles:i(()=>Re,"getAgentsFiles"),getCurrentProviderName:i(()=>w.provider,"getCurrentProviderName"),getCurrentModel:i(()=>w.model,"getCurrentModel"),getCurrentPermissionMode:i(()=>I,"getCurrentPermissionMode"),autoModeSettings:ce,log:i((A,_)=>{A==="warn"?console.warn(U.yellow(_)):console.log(U.dim(_))},"log"),onEngineChange:i(A=>{Qt(I)&&Q?.update({autoModeEngine:A})},"onEngineChange"),extraCollectors:[Ba]}),ae=Dl({getProvider:i(()=>G(w.provider),"getProvider"),getModel:i(()=>w.model??"","getModel")}),Y=w.model??Xn(w.provider)??w.provider,Q=null;_0()&&(Q=new of(A0(v.sessionId,w.permissionMode,w.provider,Y,w.reasoningMode)),Qt(I)&&Q.update({autoModeEngine:Ne.getGuardrail().getEngine()}));let be=`
|
|
432
|
+
Keyboard Shortcuts:
|
|
433
|
+
Tab Auto-complete (@paths, /commands)
|
|
434
|
+
Esc+Esc Edit last message
|
|
435
|
+
Ctrl+T Cycle reasoning mode
|
|
436
|
+
Ctrl+E Open external editor
|
|
437
|
+
Ctrl+R Search command history (built-in)
|
|
438
|
+
Ctrl+C Cancel current input
|
|
439
|
+
Ctrl+D Exit REPL`,ve=i(()=>{console.log(U.dim(be))},"_printKeyboardShortcuts");process.stdin.isTTY&&process.stdin.on("keypress",(A,_)=>{if(_&&_.name==="escape"){let F=Date.now();F-$<X&&D&&(L=!0,console.log(U.dim(`
|
|
440
|
+
[Opening editor with last message...]`)),Se.pause()),$=F}});let Ee=ho(n).getSystemPromptSnippet(),je=!0,xe={...e,reasoningMode:l,thinking:m,context:{...e.context,gitRoot:n,executionCwd:t.executionCwd,repoIntelligenceMode:x.mode,repoIntelligenceTrace:x.trace,skillsPrompt:Ee},session:{...e.session,id:v.sessionId}};Ch.current=null;let Rt={exit:i(()=>{je=!1,r?.shutdown(),Se.close()},"exit"),saveSession:i(async()=>{if(v.messages.length>0){let A=Ec(v.messages);v.title=A,await o.save(v.sessionId,{messages:v.messages,title:A,gitRoot:v.gitRoot??"",runtimeInfo:v.runtimeInfo,artifactLedger:v.artifactLedger})}},"saveSession"),startNewSession:i(()=>{v.sessionId=pc(),v.title="",v.contextTokenSnapshot=void 0,v.artifactLedger=void 0,v.createdAt=new Date().toISOString(),v.lastAccessed=v.createdAt,Sh(v,xe,t),xe.session={...xe.session,id:v.sessionId},Q?.update({sessionId:v.sessionId,messageCount:0}),r?.writer.update({sessionId:v.sessionId})},"startNewSession"),loadSession:i(async A=>{let _=await o.load(A);if(_){if(!ie("Resuming a saved session"))return"blocked";let F=await as({cwd:process.cwd()}),J=Ya(_),Be=J??F;return J?.workspaceRoot&&!IT(J)?(console.log(U.yellow(`
|
|
441
|
+
[Saved workspace unavailable]`)),console.log(U.dim(` Session workspace: ${vn(J)}`)),console.log(U.dim(` Falling back to current workspace: ${vn(F)}`)),Be=F):J?.workspaceRoot&&F.workspaceRoot&&J.workspaceRoot!==F.workspaceRoot&&(console.log(U.cyan(`
|
|
442
|
+
[Loading sibling workspace session]`)),console.log(U.dim(` Current workspace: ${vn(F)}`)),console.log(U.dim(` Session workspace: ${vn(J)}`))),v.messages=_.messages,v.title=_.title,v.sessionId=A,v.contextTokenSnapshot=void 0,v.artifactLedger=_.artifactLedger,v.lastAccessed=new Date().toISOString(),Sh(v,xe,Be),xe.session={...xe.session,id:A},Q?.update({sessionId:A,messageCount:_.messages.length}),r?.writer.update({sessionId:A}),console.log(U.green(`
|
|
443
|
+
[Loaded session: ${A}]`)),console.log(U.dim(` Messages: ${_.messages.length}`)),v.runtimeInfo?.workspaceRoot&&console.log(U.dim(` Workspace: ${vn(v.runtimeInfo)}`)),"loaded"}return"missing"},"loadSession"),listSessions:i(async()=>{let A=await o.list(v.gitRoot??void 0);if(A.length===0){console.log(U.dim(`
|
|
444
|
+
[No saved sessions]`));return}console.log(U.bold(`
|
|
445
|
+
Recent Sessions:
|
|
446
|
+
`)),v.runtimeInfo?.workspaceRoot&&(console.log(U.dim(` Current workspace: ${vn(v.runtimeInfo)}`)),console.log());for(let _ of A.slice(0,10))if(console.log(` ${U.cyan(_.id)} ${U.dim(`(${_.msgCount} messages)`)} ${_.title.slice(0,40)}`),_.runtimeInfo?.workspaceRoot){let J=v.runtimeInfo?.workspaceRoot===_.runtimeInfo.workspaceRoot?" (current workspace)":"";console.log(U.dim(` workspace: ${vn(_.runtimeInfo)}${J}`))}console.log()},"listSessions"),clearHistory:i(()=>{v.messages=[],v.contextTokenSnapshot=void 0},"clearHistory"),printHistory:i(()=>{if(v.messages.length===0){console.log(U.dim(`
|
|
447
|
+
[No conversation history]`));return}console.log(U.bold(`
|
|
448
|
+
Conversation History:
|
|
449
|
+
`));let A=v.messages.slice(-20);for(let _=0;_<A.length;_++){let F=A[_],J=U.cyan(F.role.padEnd(10)),Be=typeof F.content=="string"?F.content:"[Complex content]",tt=Be.slice(0,60).replace(/\n/g," "),ke=Be.length>60?"...":"";console.log(` ${(_+1).toString().padStart(2)}. ${J} ${tt}${ke}`)}console.log()},"printHistory"),switchProvider:i((A,_)=>{w.provider=A,w.model=_,xe.provider=A,xe.model=_;let F=_??Xn(A);if(!F)try{F=Xy(A)?.getModel()??A}catch{F=A}Q?.update({provider:A,model:F})},"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,I=A;let _=Qt(A)?Ne.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 o.delete?.(A)},"deleteSession"),deleteAllSessions:i(async()=>{await o.deleteAll?.(v.gitRoot??void 0)},"deleteAllSessions"),printSessionTree:i(async()=>{let A=await o.getLineage?.(v.sessionId);if(!A){console.log(U.dim(`
|
|
450
|
+
[No session tree available for this session]`));return}let _=Fd(Pl(A));console.log(U.bold(`
|
|
451
|
+
Session Tree:
|
|
452
|
+
`));for(let F of _)console.log(` ${F}`);console.log()},"printSessionTree"),switchSessionBranch:i(async A=>{if(!ie("Switching session branches"))return"blocked";let _=await o.setActiveEntry?.(v.sessionId,A,{summarizeCurrentBranch:!0});return _?(v.messages=_.messages,v.title=_.title,v.contextTokenSnapshot=void 0,Q?.update({messageCount:v.messages.length}),console.log(U.green(`
|
|
453
|
+
[Switched to tree entry: ${A}]`)),console.log(U.dim(` Messages: ${_.messages.length}`)),"switched"):"missing"},"switchSessionBranch"),labelSessionBranch:i(async(A,_)=>{if(!await o.setLabel?.(v.sessionId,A,_))return!1;let J=_&&_.trim()?`checkpoint label set: ${_.trim()}`:"checkpoint label cleared";return console.log(U.green(`
|
|
454
|
+
[${J}]`)),!0},"labelSessionBranch"),forkSession:i(async A=>{if(!ie("Forking a session branch"))return"blocked";let _=await o.fork?.(v.sessionId,A);return _?(v.sessionId=_.sessionId,v.messages=_.data.messages,v.title=_.data.title,v.contextTokenSnapshot=void 0,v.createdAt=new Date().toISOString(),v.lastAccessed=v.createdAt,Sh(v,xe,Ya(_.data)??v.runtimeInfo),xe.session={...xe.session,id:_.sessionId},Q?.update({sessionId:_.sessionId,messageCount:v.messages.length}),console.log(U.green(`
|
|
455
|
+
[Forked session: ${_.sessionId}]`)),console.log(U.dim(` Messages: ${_.data.messages.length}`)),"forked"):"failed"},"forkSession"),rewindSession:i(async A=>{if(!ie("Rewinding session"))return"blocked";let _=await o.rewind?.(v.sessionId,A);return _?(v.messages=_.messages,v.title=_.title,v.contextTokenSnapshot=void 0,v.lastAccessed=new Date().toISOString(),Q?.update({messageCount:v.messages.length}),console.log(U.green(`
|
|
456
|
+
[Rewound session${A?` to ${A}`:" to previous turn"}]`)),console.log(U.dim(` Messages: ${_.messages.length}`)),"rewound"):"failed"},"rewindSession"),getCostReport:i(()=>Ch.current?.()??null,"getCostReport"),getAutoModeStats:i(()=>{if(Qt(I))return Ne.getGuardrail().getStats()},"getAutoModeStats"),setAutoModeEngine:i(A=>{Qt(I)&&(Ne.getGuardrail().setEngine(A),Q?.update({permissionMode:I}))},"setAutoModeEngine"),createKodaXOptions:i(()=>{let A=i((F,J)=>I!=="plan"?null:vo(F,J,n??process.cwd()),"planModeBlockCheck"),_=Qt(I)?[Ne.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 F=>I!=="plan"?"not-in-plan-mode":(await Ic(Se,"exit_plan_mode",{plan:F},{isProtectedPath:!1,permissionMode:I})).confirmed?(w.permissionMode="accept-edits",I="accept-edits",Q?.update({permissionMode:"accept-edits"}),!0):!1,"exitPlanMode"),beforeToolExecute:i(async(F,J)=>{let Be=I,tt=Ar(Be);if(Be==="plan"){let ke=vo(F,J,n??process.cwd());if(ke)return console.log(U.yellow(ke)),`${ke} 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(F==="bash"){let ke=J.command??"";if(On(ke))return!0}if(n&&Cn.has(F)){let ke=J.path;if(ke&&eo(ke,n))return(await Ic(Se,F,J,{isProtectedPath:!0,permissionMode:Be})).confirmed?!0:(console.log(U.dim("[Cancelled] Operation on protected path requires confirmation")),!1)}if(tt.has(F)){if(Be==="accept-edits"&&F==="bash"&&await Vo(F,J,O,ae))return!0;let ke=await Ic(Se,F,J,{isOutsideProject:J._outsideProject===!0,reason:J._reason,permissionMode:Be});if(!ke.confirmed)return console.log(U.dim("[Cancelled] Operation cancelled by user")),!1;ke.always&&Be==="accept-edits"&&(Ou(F,J,!1),O=is())}return!0},"beforeToolExecute")}}},"createKodaXOptions"),reloadAgentsFiles:i(async()=>(Re=await Z(),Re),"reloadAgentsFiles"),readline:Se,ui:new rf(Se)};Se.on("SIGINT",async()=>{console.log(U.dim(`
|
|
457
|
+
|
|
458
|
+
[Press /exit to quit]`)),Se.prompt()});let Qe=i(()=>{Q?.hide(),r?.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 F=await jd({...xe,provider:w.provider,thinking:w.thinking,reasoningMode:w.reasoningMode},A.invocation,_,J=>console.log(U.dim(`
|
|
459
|
+
${J}`)));if(F.mode==="manual"){F.manualOutput&&console.log(U.yellow(`
|
|
460
|
+
${F.manualOutput}
|
|
461
|
+
`)),await F.finalize();return}if(!F.prompt||!F.options){await F.finalize();return}try{let J=F.mode==="fork"?[]:v.messages,Be=await O0(F.options,v,F.prompt,J);if(F.mode==="fork"){let tt=Ga(Be.messages);tt.trim()&&(console.log(`
|
|
462
|
+
${tt}
|
|
463
|
+
`),v.messages.push({role:"assistant",content:tt}))}else v.messages=Be.messages,v.contextTokenSnapshot=Be.contextTokenSnapshot;if(Q?.update({messageCount:v.messages.length}),v.messages.length>0){let tt=Ec(v.messages);v.title=tt,await o.save(v.sessionId,{messages:v.messages,title:tt,gitRoot:v.gitRoot??"",runtimeInfo:v.runtimeInfo})}await F.finalize()}catch(J){throw await F.finalize(J instanceof Error?J:new Error(String(J))),J}},"handleCommandResult");for(;je;){if(L&&D){L=!1,Se.resume();let ke=await H0(D);if(ke&&ke.trim()&&ke!==D){console.log(U.dim(`
|
|
464
|
+
[Edited message ready to send]`));let Oe=ke.trim();io(v);let Vt=ls(Oe);if(Vt){let Ce=await us(Vt,v,Rt,w);await ee(Ce,Oe);continue}let K=await bh(Oe);if(Oe.startsWith("!")&&hc(K))continue;let fe=yc(K,xe.context?.executionCwd??process.cwd());for(let Ce of fe.warnings)console.log(U.yellow(`
|
|
465
|
+
${Ce}`));v.messages.push({role:"user",content:fe.messageContent}),D=Oe,Q?.update({messageCount:v.messages.length});let V=v.lineage?kx({getLineage:i(()=>v.lineage,"getLineage"),setLineage:i(Ce=>{v.lineage=Ce},"setLineage"),saveSession:i(async()=>{await o.save(v.sessionId,{messages:v.messages,title:v.title??Ec(v.messages),gitRoot:v.gitRoot??"",runtimeInfo:v.runtimeInfo,artifactLedger:v.artifactLedger,lineage:v.lineage})},"saveSession"),getLatestUsage:i(()=>{},"getLatestUsage"),getTurnStartMs:i(()=>{},"getTurnStartMs"),getPermissionMode:i(()=>I,"getPermissionMode"),hasPendingUserInput:i(()=>yn().has({agentId:void 0,maxPriority:"user",mode:"prompt"}),"hasPendingUserInput"),verifyComplete:i(async()=>({ok:!0}),"verifyComplete")}):void 0;try{let Ce=await ga({...xe,provider:w.provider,thinking:w.thinking,reasoningMode:w.reasoningMode,session:{...xe.session,initialMessages:v.lineage?Mt(v.lineage,v.lineage.activeEntryId):v.messages},context:{...xe.context,taskSurface:"repl",planModeBlockCheck:i((ot,Fn)=>I!=="plan"?null:vo(ot,Fn,n??process.cwd()),"planModeBlockCheck"),...fe.inputArtifacts.length>0?{inputArtifacts:fe.inputArtifacts}:{},...V?{goalRuntime:V}:{}}},K);if(v.messages=Ce.messages,v.contextTokenSnapshot=Ce.contextTokenSnapshot,v.artifactLedger=ma(v.artifactLedger??[],Ce.artifactLedger??am(Ce.messages)),v.messages.length>0){let ot=Ec(v.messages);v.title=ot,await o.save(v.sessionId,{messages:v.messages,title:ot,gitRoot:v.gitRoot??"",runtimeInfo:v.runtimeInfo,artifactLedger:v.artifactLedger})}}catch(Ce){let ot=Ce instanceof Error?Ce:new Error(String(Ce));v.messages.pop(),console.log(U.red(`
|
|
466
|
+
[Error] ${ot.message}`))}continue}else ke===D&&console.log(U.dim(`
|
|
467
|
+
[No changes made, continuing...]`))}let A=rD(w.permissionMode,w),_=await iD(Se,A);if(!je)break;let F=_.trim();if(!F)continue;io(v);let J=ls(F);if(J){let ke=await us(J,v,Rt,w);await ee(ke,F);continue}let Be=await bh(F);if(F.startsWith("!")&&hc(Be))continue;let tt=yc(Be,xe.context?.executionCwd??process.cwd());for(let ke of tt.warnings)console.log(U.yellow(`
|
|
468
|
+
${ke}`));v.messages.push({role:"user",content:tt.messageContent}),D=F,Q?.update({messageCount:v.messages.length});try{let ke=await O0(xe,v,Be,v.messages,tt.inputArtifacts);if(v.messages=ke.messages,v.contextTokenSnapshot=ke.contextTokenSnapshot,v.artifactLedger=ma(v.artifactLedger??[],ke.artifactLedger??am(ke.messages)),Q?.update({messageCount:v.messages.length}),v.messages.length>0){let Oe=Ec(v.messages);v.title=Oe,await o.save(v.sessionId,{messages:v.messages,title:Oe,gitRoot:v.gitRoot??"",runtimeInfo:v.runtimeInfo,artifactLedger:v.artifactLedger})}}catch(ke){let Oe=ke instanceof Error?ke:new Error(String(ke));v.messages.pop(),Oe.message.includes("rate limit")||Oe.message.includes("Rate limit")?(console.log(U.yellow(`
|
|
469
|
+
[Rate Limit] ${Oe.message}`)),console.log(U.dim(`Suggestion: Wait a moment and try again, or switch provider with /mode
|
|
470
|
+
`))):Oe.message.includes("API key")||Oe.message.includes("not configured")?(console.log(U.red(`
|
|
471
|
+
[Configuration Error] ${Oe.message}`)),console.log(U.dim(`Suggestion: Set the required API key environment variable
|
|
472
|
+
`))):Oe.message.includes("network")||Oe.message.includes("ECONNREFUSED")||Oe.message.includes("ETIMEDOUT")?(console.log(U.red(`
|
|
473
|
+
[Network Error] ${Oe.message}`)),console.log(U.dim(`Suggestion: Check your internet connection and try again
|
|
474
|
+
`))):Oe.message.includes("token")||Oe.message.includes("context too long")?(console.log(U.yellow(`
|
|
475
|
+
[Context Error] ${Oe.message}`)),console.log(U.dim(`Suggestion: Use /clear to start a fresh conversation
|
|
476
|
+
`))):(console.log(U.red(`
|
|
477
|
+
[Error] ${Oe.message}`)),console.log(U.dim(`Your message was not sent. Please try again.
|
|
478
|
+
`)))}}}i(oD,"runInteractiveMode");function rD(e,t){let n=Rc(),o=e==="plan"?U.hex(n.colors.warning):U.hex(n.colors.success),r=t.model??Xn(t.provider)??t.provider,s=_s();if(s<60){let c=e==="plan"?"?":n.symbols.prompt;return o(`${c} `)}else if(s<100){let c=t.reasoningMode!=="off"?t.reasoningMode[0]?.toUpperCase()??"R":"",l=c?U.hex(n.colors.dim)(`[${c}]`):"";return o(`kodax:${e}${l}> `)}let a=t.reasoningMode!=="off"?U.hex(n.colors.info)(`[reason:${t.reasoningMode}]`):"";return o(`kodax:${e} (${t.provider}:${r})${a}> `)}i(rD,"getPrompt");async function iD(e,t){let n=Rc(),o=[],r=await new Promise(a=>{e.question(t,a)});if(r===""||r.toLowerCase()==="/e")return await H0(o.join(`
|
|
479
|
+
`));for(o.push(r);sD(o.join(`
|
|
480
|
+
`));){let a=U.hex(n.colors.dim)("... "),c=await new Promise(l=>{e.question(a,l)});o.push(c)}return o.join(`
|
|
481
|
+
`).replace(/\\\n/g,`
|
|
482
|
+
`)}i(iD,"askInput");async function H0(e){let t=Ac.join(B0.tmpdir(),"kodax"),n=Ac.join(t,`input-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`);try{await Mc.promises.mkdir(t,{recursive:!0}),await Mc.promises.writeFile(n,e,"utf-8");let o=process.env.EDITOR??process.env.VISUAL??(process.platform==="win32"?"notepad.exe":"nano");if(o.includes("/")||o.includes("\\")||o.includes("&&")||o.includes("|")){let a=Ac.basename(o);console.log(U.yellow(`
|
|
483
|
+
[Security] Editor path sanitized: ${a}`)),o=a}console.log(U.dim(`
|
|
484
|
+
[Opening editor: ${o}]`));let r=process.platform==="win32"&&(o.toLowerCase()==="notepad"||o.toLowerCase()==="notepad.exe");return console.log(r?U.dim(`Note: Please close Notepad manually after editing to continue.
|
|
485
|
+
`):U.dim(`Save and close the editor to continue...
|
|
486
|
+
`)),N0.spawnSync(o,[n],{stdio:"inherit",timeout:3e5,shell:!1}),(await Mc.promises.readFile(n,"utf-8")).trim()}catch(o){let r=o instanceof Error?o:new Error(String(o));return console.log(U.red(`
|
|
487
|
+
[Editor Error] ${r.message}`)),e}finally{try{await Mc.promises.unlink(n)}catch{}}}i(H0,"openExternalEditor");function sD(e){if(e.endsWith("\\")&&!e.endsWith("\\\\"))return!0;let t={"(":0,"[":0,"{":0},n={")":"(","]":"[","}":"{"},o=null;for(let r=0;r<e.length;r++){let s=e[r];if((s==='"'||s==="'"||s==="`")&&e[r-1]!=="\\"){o===s?o=null:o===null&&(o=s);continue}if(!o){if(s in t)t[s]++;else if(s in n){let a=n[s];a&&t[a]--}}}return!!(Object.values(t).some(r=>r>0)||o)}i(sD,"needsContinuation");async function bh(e){let t=e.match(/@[\w./-]+/g);if(t)for(let n of t){let o=n.slice(1)}if(e.startsWith("!")){let n=e.slice(1).trim();return Dd(n,{cwd:process.cwd()})}return e}i(bh,"processSpecialSyntax");async function O0(e,t,n,o=t.messages,r){let s={...e.events??{},getCostReport:Ch};return ga({...e,events:s,session:{...e.session,initialMessages:o},context:{...e.context,contextTokenSnapshot:t.contextTokenSnapshot,taskSurface:"repl",...r&&r.length>0?{inputArtifacts:[...r]}:{}}},n)}i(O0,"runAgentRound");function Ec(e){return rs(e)}i(Ec,"extractTitle");function aD(e,t,n,o){let r=Rc(),s=e.model??Xn(e.provider)??e.provider;if(console.log(U.hex(r.colors.primary)(`
|
|
488
|
+
`+`
|
|
489
|
+
\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
|
|
490
|
+
\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
|
|
491
|
+
\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
|
|
492
|
+
\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
|
|
493
|
+
\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
|
|
494
|
+
\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(U.hex(r.colors.text)(`
|
|
495
|
+
v${Mi} | AI Coding Agent | ${e.provider}:${s}`)),console.log(U.hex(r.colors.dim)(`
|
|
496
|
+
\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(U.hex(r.colors.dim)(" Mode: ")+U.hex(r.colors.primary)(t)+U.hex(r.colors.dim)(" | Reasoning: ")+(e.reasoningMode==="off"?U.hex(r.colors.dim)("off"):U.hex(r.colors.success)(e.reasoningMode))),n){let c=Math.round(n.contextWindow/1e3),l=Math.round(n.contextWindow*n.triggerPercent/100/1e3),d=n.enabled?U.hex(r.colors.success)("on"):U.hex(r.colors.dim)("off");console.log(U.hex(r.colors.dim)(` Context: ${c}k | Compaction: `)+d+U.hex(r.colors.dim)(` @ ${n.triggerPercent}% (${l}k)`))}if(console.log(U.hex(r.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
|
|
497
|
+
`)),o){let c=o.length;console.log(U.hex(r.colors.dim)(" Project Rules: ")+U.hex(r.colors.success)(`${c} rule file(s) loaded`)),console.log(U.hex(r.colors.dim)(` Use /reload to refresh rules
|
|
498
|
+
`))}console.log(U.hex(r.colors.dim)(" Quick tips:")),console.log(U.hex(r.colors.primary)(" /help ")+U.hex(r.colors.dim)("Show all commands")),console.log(U.hex(r.colors.primary)(" /mode ")+U.hex(r.colors.dim)("Switch permission mode")),console.log(U.hex(r.colors.primary)(" /clear ")+U.hex(r.colors.dim)("Clear conversation")),console.log(U.hex(r.colors.primary)(" @path ")+U.hex(r.colors.dim)("Attach image to context")),console.log(U.hex(r.colors.primary)(" !cmd ")+U.hex(r.colors.dim)("Run read-only shell command")),console.log(U.hex(r.colors.dim)(`
|
|
499
|
+
Keyboard: Tab (complete) | Esc+Esc (edit last) | Ctrl+T (reasoning) | Ctrl+E (editor) | Ctrl+R (history)
|
|
500
|
+
`))}i(aD,"printStartupBanner");import sf from"node:fs";import cD from"node:path";function lD(){let e=cf();return lf(e).map(n=>af(n))}i(lD,"listCustomProviders");function uD(e){if(typeof e!="string"||e.length===0)return;let t=lf(cf()).find(n=>n.name===e);return t?af(t):void 0}i(uD,"getCustomProviderConfig");function dD(e){zy(e);let t=af(e),n=cf(),o=lf(n),r=o.findIndex(a=>a.name===t.name),s=r>=0?o.map((a,c)=>c===r?t:a):[...o,t];return W0({...n,customProviders:s}),im(s),af(t)}i(dD,"upsertCustomProvider");function fD(e){if(typeof e!="string"||e.length===0)return!1;let t=cf(),n=lf(t),o=n.filter(r=>r.name!==e);return o.length===n.length?!1:(W0({...t,customProviders:o}),im(o),!0)}i(fD,"removeCustomProvider");function F0(){return hn("config.json")}i(F0,"configFilePath");function cf(){let e=F0();if(!sf.existsSync(e))return{};try{let t=JSON.parse(sf.readFileSync(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}i(cf,"readWholeConfig");function W0(e){let t=F0();sf.mkdirSync(cD.dirname(t),{recursive:!0}),sf.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}i(W0,"writeWholeConfig");function lf(e){let t=e.customProviders;return Array.isArray(t)?t:[]}i(lf,"extractCustomProviders");function af(e){return structuredClone(e)}i(af,"cloneCustomProvider");import uf from"node:fs";import mD from"node:path";function pD(){let e=df();return xD(ff(e))}i(pD,"listMcpServers");function gD(e){if(typeof e!="string"||e.length===0)return;let n=ff(df())[e];return n?vh(n):void 0}i(gD,"getMcpServerConfig");function hD(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("upsertMcpServer: name must be a non-empty string");U0(e,t);let n=vh(t),o=df(),s={...ff(o),[e]:n};return G0({...o,mcpServers:s}),vh(n)}i(hD,"upsertMcpServer");function yD(e){if(typeof e!="string"||e.length===0)return!1;let t=df(),n=ff(t);if(!(e in n))return!1;let o={};for(let r of Object.keys(n))r!==e&&(o[r]=n[r]);return G0({...t,mcpServers:o}),!0}i(yD,"removeMcpServer");function U0(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(U0,"validateMcpServerConfig");function j0(){return hn("config.json")}i(j0,"configFilePath");function df(){let e=j0();if(!uf.existsSync(e))return{};try{let t=JSON.parse(uf.readFileSync(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}i(df,"readWholeConfig");function G0(e){let t=j0();uf.mkdirSync(mD.dirname(t),{recursive:!0}),uf.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}i(G0,"writeWholeConfig");function ff(e){let t=e.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?{}:t}i(ff,"extractMcpServers");function vh(e){return structuredClone(e)}i(vh,"cloneMcpServerConfig");function xD(e){return structuredClone(e)}i(xD,"cloneMcpServers");import Hn from"fs/promises";import mf from"fs";import pf from"path";import X0 from"chalk";var wD=new Set(["user","assistant","system"]);function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ct,"isRecord");function qr(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return!0;if(Array.isArray(e))return e.every(qr);if(!Ct(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(qr)}i(qr,"isKodaXJsonValue");function K0(e){return Ct(e)&&typeof e.id=="string"&&typeof e.extensionId=="string"&&typeof e.type=="string"&&typeof e.ts=="number"&&(e.data===void 0||qr(e.data))&&(e.dedupeKey===void 0||typeof e.dedupeKey=="string")}i(K0,"isKodaXExtensionSessionRecord");function V0(e){return Ct(e)?Object.values(e).every(t=>Ct(t)?Object.values(t).every(qr):!1):!1}i(V0,"isKodaXExtensionSessionState");function SD(e){if(!Ct(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"&&Ct(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(SD,"isKodaXContentBlock");function Ih(e){return!Ct(e)||typeof e.role!="string"||!wD.has(e.role)?!1:typeof e.content=="string"||Array.isArray(e.content)&&e.content.every(SD)}i(Ih,"isKodaXMessage");function z0(e){return Ct(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(z0,"isSessionErrorMetadata");function TD(e){return Ct(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(TD,"isKodaXSessionUiHistoryItem");function kh(e){return Array.isArray(e)&&e.every(TD)}i(kh,"isKodaXSessionUiHistory");function CD(e){return!Ct(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||kh(e.uiHistory))&&(e.scope===void 0||typeof e.scope=="string")}i(CD,"isPersistedMetaUpdateLine");function Y0(e,t){t!==0&&process.stderr.write(`[KodaX] Skipped ${t} malformed session record(s) from ${pf.basename(e)}.
|
|
501
|
+
`)}i(Y0,"warnMalformedSessionData");function nr(e){process.stderr.write(`${e}
|
|
502
|
+
`)}i(nr,"writeStorageNotice");function q0(e){return{_type:"extension_record",...e}}i(q0,"toExtensionRecordLine");function Q0(e){return{_type:"lineage_entry",entry:e}}i(Q0,"toLineageEntryLine");function J0(e){return{_type:"artifact_ledger_entry",entry:e}}i(J0,"toArtifactLedgerLine");function bD(e){return Ct(e)&&e._type==="extension_record"&&K0(e)}i(bD,"isPersistedExtensionRecordLine");function vD(e){return Ct(e)&&typeof e.id=="string"&&(e.parentId===null||typeof e.parentId=="string")&&typeof e.timestamp=="string"&&typeof e.type=="string"}i(vD,"hasEntryBase");function ID(e){if(!vD(e))return!1;let t=e;switch(t.type){case"message":return Ih(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||qr(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(ID,"isKodaXSessionEntry");function kD(e){return Ct(e)&&e._type==="lineage_entry"&&ID(e.entry)}i(kD,"isPersistedLineageEntryLine");function RD(e){return Ct(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||qr(e.metadata))}i(RD,"isKodaXSessionArtifactLedgerEntry");function ED(e){return Ct(e)&&e._type==="artifact_ledger_entry"&&RD(e.entry)}i(ED,"isPersistedArtifactLedgerLine");function eI(e){return Ct(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(eI,"isKodaXSessionRuntimeInfo");function Z0(e,t){return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase()===t.toLowerCase():e===t}i(Z0,"pathsEqual");function MD(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(MD,"getLastNavigableEntryId");function AD(e){if(e.lineageEntries.length>0)return{version:2,activeEntryId:e.meta?.activeEntryId??MD(e.lineageEntries),entries:e.lineageEntries};if(e.legacyMessages.length!==0)return xn(e.legacyMessages)}i(AD,"buildLineage");function _D(e){let t=AD(e);return{createdAt:e.meta?.createdAt,data:{messages:t?Mt(t):[...e.legacyMessages],title:e.meta?.title??"",gitRoot:e.meta?.gitRoot??"",runtimeInfo:eI(e.meta?.runtimeInfo)?{...e.meta.runtimeInfo}:void 0,scope:e.meta?.scope??"user",uiHistory:kh(e.meta?.uiHistory)?e.meta.uiHistory.map(n=>({...n})):void 0,errorMetadata:z0(e.meta?.errorMetadata)?{...e.meta.errorMetadata}:void 0,extensionState:V0(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(_D,"buildSessionData");function $D(e,t,n,o){return{_type:"meta",title:t.title,id:e,gitRoot:t.gitRoot,runtimeInfo:t.runtimeInfo?{...t.runtimeInfo}:void 0,createdAt:o??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?xr(n):t.messages.length}}i($D,"createSessionMeta");async function PD(e){if(!mf.existsSync(e))return null;let n=(await Hn.readFile(e,"utf-8")).trim();if(!n)return null;let o={legacyMessages:[],lineageEntries:[],artifactLedger:[],extensionRecords:[],malformedCount:0},r=n.split(`
|
|
503
|
+
`);for(let s=0;s<r.length;s+=1)try{let a=JSON.parse(r[s]);if(s===0&&Ct(a)&&a._type==="meta"){o.meta=a;continue}if(CD(a)){o.meta&&(a.title!==void 0&&(o.meta.title=a.title),a.activeEntryId!==void 0&&(o.meta.activeEntryId=a.activeEntryId),a.activeMessageCount!==void 0&&(o.meta.activeMessageCount=a.activeMessageCount),a.uiHistory!==void 0&&(o.meta.uiHistory=a.uiHistory),a.scope!==void 0&&(o.meta.scope=a.scope));continue}if(kD(a)){o.lineageEntries.push(a.entry);continue}if(ED(a)){o.artifactLedger.push(a.entry);continue}if(bD(a)){o.extensionRecords.push({id:a.id,extensionId:a.extensionId,type:a.type,ts:a.ts,data:a.data,dedupeKey:a.dedupeKey});continue}if(Ih(a)){o.legacyMessages.push(a);continue}o.malformedCount+=1}catch{o.malformedCount+=1}return o}i(PD,"readPersistedSessionFile");var or=class{static{i(this,"FileSessionStorage")}sessionsDir;constructor(t){this.sessionsDir=t?.sessionsDir??ha}writeQueues=new Map;serializedWrite(t,n){let r=(this.writeQueues.get(t)??Promise.resolve()).then(n,()=>n());return this.writeQueues.set(t,r),r}appendState=new Map;syncAppendState(t,n,o){let r=this.appendState.get(t);this.appendState.set(t,{lineageCount:n.lineage?.entries.length??r?.lineageCount??0,artifactCount:n.artifactLedger?.length??r?.artifactCount??0,extensionCount:n.extensionRecords?.length??r?.extensionCount??0,metaUpdateCount:o??r?.metaUpdateCount??0})}getSessionFilePath(t){return pf.join(this.sessionsDir,`${t}.jsonl`)}getArchiveFilePath(t){return pf.join(this.sessionsDir,`${t}.archive.jsonl`)}async readSession(t){let n=this.getSessionFilePath(t),o=await PD(n);return o?(Y0(n,o.malformedCount),_D(o)):null}async writeSessionInternal(t,n,o){await Hn.mkdir(this.sessionsDir,{recursive:!0});let r=this.getSessionFilePath(t),s=`${r}.${process.pid}.${Date.now()}.tmp`,a=n.lineage??xn(n.messages),c=$D(t,n,a,o);try{let l=await Hn.open(s,"w");try{await l.write(JSON.stringify(c)+`
|
|
504
|
+
`);for(let d of a.entries)await l.write(JSON.stringify(Q0(d))+`
|
|
505
|
+
`);for(let d of n.artifactLedger??[])await l.write(JSON.stringify(J0(d))+`
|
|
506
|
+
`);for(let d of n.extensionRecords??[])await l.write(JSON.stringify(q0(d))+`
|
|
507
|
+
`)}finally{await l.close()}await Hn.rename(s,r)}finally{mf.existsSync(s)&&await Hn.unlink(s).catch(()=>{})}}async mergeAndWriteInternal(t,n){let o=await this.readSession(t),r={...n,scope:n.scope??o?.data.scope??"user",uiHistory:n.uiHistory??o?.data.uiHistory,extensionState:n.extensionState??o?.data.extensionState,artifactLedger:n.artifactLedger??o?.data.artifactLedger,extensionRecords:n.extensionRecords??o?.data.extensionRecords,runtimeInfo:n.runtimeInfo??o?.data.runtimeInfo,errorMetadata:n.errorMetadata??o?.data.errorMetadata,lineage:n.lineage??xn(n.messages,o?.data.lineage)};await this.writeSessionInternal(t,r,o?.createdAt),this.syncAppendState(t,r)}async appendSessionDelta(t,n){let o=this.getSessionFilePath(t);if(!mf.existsSync(o)||!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(Q0(p)));for(let p of c)d.push(JSON.stringify(J0(p)));for(let p of l)d.push(JSON.stringify(q0(p)));let m={_type:"meta_update",title:n.title,activeEntryId:n.lineage.activeEntryId,activeMessageCount:xr(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 Hn.appendFile(o,`
|
|
508
|
+
`+d.join(`
|
|
509
|
+
`),"utf-8"),this.syncAppendState(t,n,s.metaUpdateCount+1)});let r=this.appendState.get(t);r&&this.shouldRunMaintenance(r)&&this.runMaintenance(t).catch(s=>{process.stderr.write(`[KodaX] Archive maintenance failed: ${String(s)}
|
|
510
|
+
`)})}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:o,archivedEntries:r,archiveBatchId:s}=cx(n.data.lineage);if(r.length===0){await this.writeSessionInternal(t,n.data,n.createdAt),this.syncAppendState(t,n.data,0);return}let a=this.getArchiveFilePath(t),c=await Hn.open(a,"a");try{await c.write(JSON.stringify({_type:"archive_batch",archiveBatchId:s,sessionId:t,archivedAt:new Date().toISOString(),entryCount:r.length})+`
|
|
511
|
+
`);for(let d of r)await c.write(JSON.stringify({_type:"archived_entry",archiveBatchId:s,entry:d})+`
|
|
512
|
+
`)}finally{await c.close()}let l={...n.data,lineage:o};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:o,createdAt:r}=n,s=this.getSessionFilePath(t),a=await Sr(),c=await as(),l=Ya(o);if((c.canonicalRepoRoot&&l?.canonicalRepoRoot&&!Gu(c,l)||a&&o.gitRoot&&a!==o.gitRoot&&!Gu(c,{canonicalRepoRoot:o.gitRoot}))&&(nr(X0.yellow(`
|
|
513
|
+
[Warning] Session project mismatch:`)),c.workspaceRoot&&nr(` Current workspace: ${c.workspaceRoot}`),l?.workspaceRoot&&nr(` Session workspace: ${l.workspaceRoot}`),c.canonicalRepoRoot&&nr(` Current repo: ${c.canonicalRepoRoot}`),l?.canonicalRepoRoot?nr(` Session repo: ${l.canonicalRepoRoot}`):o.gitRoot&&nr(` Session repo: ${o.gitRoot}`),nr(` Continuing anyway...
|
|
514
|
+
`)),o.errorMetadata?.consecutiveErrors&&o.errorMetadata.consecutiveErrors>0){let m=Qy(o.messages);if(m!==o.messages){nr(X0.cyan("[Session Recovery] Cleaned incomplete tool calls from previous session"));let p={...o,messages:m,errorMetadata:{...o.errorMetadata,consecutiveErrors:0},lineage:xn(m,o.lineage)};return await this.serializedWrite(t,async()=>{await this.writeSessionInternal(t,p,r),this.syncAppendState(t,p)}),p}}return Y0(s,0),o}async getLineage(t){return(await this.readSession(t))?.data.lineage??null}async setActiveEntry(t,n,o){let r=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,o);if(!a)return;let c={...s.data,messages:Mt(a),lineage:a};await this.writeSessionInternal(t,c,s.createdAt),this.syncAppendState(t,c),r=c}),r}async rewind(t,n){let o=null;return await this.serializedWrite(t,async()=>{let r=await this.readSession(t);if(!r?.data.lineage)return;let s=n??Ii(r.data.lineage);if(!s)return;let a=ki(r.data.lineage,s);if(!a)return;let c={...r.data,messages:Mt(a),lineage:a};await this.writeSessionInternal(t,c,r.createdAt),this.syncAppendState(t,c),o=c}),o}async setLabel(t,n,o){let r=null;return await this.serializedWrite(t,async()=>{let s=await this.readSession(t);if(!s?.data.lineage)return;let a=vi(s.data.lineage,n,o);if(!a)return;let c={...s.data,lineage:a};await this.writeSessionInternal(t,c,s.createdAt),this.syncAppendState(t,c),r=c}),r}async fork(t,n,o){let r=null;return await this.serializedWrite(t,async()=>{let s=await this.readSession(t);if(!s?.data.lineage)return;let a=Ri(s.data.lineage,n);if(!a)return;let c=o?.sessionId??await Ci(),l={messages:Mt(a),title:o?.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),r={sessionId:c,data:l}}),r}async list(t){await Hn.mkdir(this.sessionsDir,{recursive:!0});let n=t??await Sr(),o=await as({cwd:n??process.cwd()}),r=(await Hn.readdir(this.sessionsDir)).filter(a=>a.endsWith(".jsonl")),s=[];for(let a of r)try{let c=(await Hn.readFile(pf.join(this.sessionsDir,a),"utf-8")).trim(),l=c.split(`
|
|
515
|
+
`)[0];if(!l)continue;let d=JSON.parse(l);if(Ct(d)&&d._type==="meta"){let m=typeof d.gitRoot=="string"?d.gitRoot:"",p=eI(d.runtimeInfo)?d.runtimeInfo:void 0,g=d.scope==="managed-task-worker"?"managed-task-worker":"user";if(n){let w=Gu(o,p),I=p?.workspaceRoot?Z0(p.workspaceRoot,o.workspaceRoot??""):Z0(m,n);if(!w&&!I)continue}if(g!=="user")continue;let x=c.split(`
|
|
516
|
+
`).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(`
|
|
517
|
+
`).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);mf.existsSync(n)&&await Hn.unlink(n)}async deleteAll(t){let n=t??await Sr(),o=await this.list(n??void 0);for(let r of o)await this.delete(r.id)}};import _c from"node:fs";import Rh from"node:fs/promises";import tI from"node:path";function $s(e){return e!==void 0?new or({sessionsDir:e}):new or}i($s,"getStorage");function nI(e){return e??ha}i(nI,"resolveSessionsDir");async function oI(e){return rI(e,void 0)}i(oI,"listSessions");async function rI(e,t){try{let n=nI(t),o=e?.projectRoot,r=$s(t);await Rh.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"&&!o&&l===void 0&&!a)return(await r.list(o)).slice(0,c).map(LD);let d=(await Rh.readdir(n)).filter(p=>p.endsWith(".jsonl")&&(a||!p.startsWith("archived-"))),m=[];for(let p of d)try{let g=(await Rh.readFile(tI.join(n,p),"utf-8")).trim(),x=g.split(`
|
|
518
|
+
`)[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 I=typeof T.createdAt=="string"?T.createdAt:void 0;if(l!==void 0&&I!==void 0){let v=Date.parse(I);if(!Number.isNaN(v)&&v>=l)continue}let O=g.split(`
|
|
519
|
+
`).length,$=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-$),L=T.runtimeInfo!==null&&typeof T.runtimeInfo=="object"?iI(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:I,runtimeInfo:L??(X?{gitRoot:X}:void 0),_createdAtMs:I?Date.parse(I):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(rI,"listSessionsImpl");function iI(e){if(!(!e.workspaceRoot&&!e.canonicalRepoRoot))return{...e.workspaceRoot?{workspaceRoot:e.workspaceRoot}:{},...e.canonicalRepoRoot?{gitRoot:e.canonicalRepoRoot}:{}}}i(iI,"extractRuntimeInfoSummary");function LD(e){let t=e.runtimeInfo?iI(e.runtimeInfo):void 0;return{id:e.id,title:e.title,msgCount:e.msgCount,...t!==void 0?{runtimeInfo:t}:{}}}i(LD,"toSessionSummary");async function sI(e){return aI(e,void 0)}i(sI,"loadSession");async function aI(e,t){try{return await $s(t).load(e)}catch{return null}}i(aI,"loadSessionImpl");async function cI(e,t){return lI(e,t,void 0)}i(cI,"forkSession");async function lI(e,t,n){try{return await $s(n).fork(e,t?.selector,{sessionId:t?.sessionId,title:t?.title})}catch{return null}}i(lI,"forkSessionImpl");async function uI(e,t){return dI(e,t,void 0)}i(uI,"rewindSession");async function dI(e,t,n){try{return await $s(n).rewind(e,t?.selector)}catch{return null}}i(dI,"rewindSessionImpl");async function fI(e,t){return mI(e,t,void 0)}i(fI,"setActiveEntry");async function mI(e,t,n){try{return await $s(n).setActiveEntry(e,t)}catch{return null}}i(mI,"setActiveEntryImpl");async function gf(){try{return qy({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(gf,"listRunningSessions");async function pI(e){return gI(e,void 0)}i(pI,"deleteSession");async function gI(e,t){try{let o=(await gf()).find(r=>r.sessionId===e);return o?{error:{code:"session_running",runningProcess:{pid:o.pid,startedAt:o.startedAt}}}:(await $s(t).delete(e),{ok:!0})}catch{return{ok:!0}}}i(gI,"deleteSessionImpl");function hI(e){return yI(e,void 0)}i(hI,"watchSessions");function yI(e,t){let n=nI(t);return process.platform==="win32"?BD(e,n):DD(e,n)}i(yI,"watchSessionsImpl");function OD(e){return e.endsWith(".jsonl")?e.slice(0,-6):null}i(OD,"sessionIdFromFilename");function DD(e,t){let n=null,o=!1,r=new Map;function s(c,l){let d=r.get(l);d!==void 0&&clearTimeout(d);let m=setTimeout(()=>{r.delete(l),o||e({kind:c,sessionId:l})},100);r.set(l,m)}i(s,"emitDebounced");function a(){if(!o)try{if(!_c.existsSync(t)){setTimeout(a,1e3);return}n=_c.watch(t,(c,l)=>{if(!l)return;let d=OD(l);if(!d)return;let m=c==="rename"?ND(t,l):"change";s(m,d)}),n.on("error",()=>{n?.close(),n=null,o||setTimeout(a,1e3)})}catch{}}return i(a,"startWatch"),a(),{close(){o=!0,n?.close(),n=null;for(let c of r.values())clearTimeout(c);r.clear()}}}i(DD,"watchSessionsPosix");function ND(e,t){try{return _c.statSync(tI.join(e,t)),"add"}catch{return"remove"}}i(ND,"detectRenameKind");function BD(e,t){let n=!1,o=new Set;function r(){try{return _c.existsSync(t)?new Set(_c.readdirSync(t).filter(a=>a.endsWith(".jsonl")).map(a=>a.slice(0,-6))):new Set}catch{return new Set}}i(r,"buildSnapshot"),o=r();let s=setInterval(()=>{if(n)return;let a=r();for(let c of a)o.has(c)||e({kind:"add",sessionId:c});for(let c of o)a.has(c)||e({kind:"remove",sessionId:c});o=a},1e3);return{close(){n=!0,clearInterval(s)}}}i(BD,"watchSessionsWindows");function HD(e){let t=e?.sessionsDir,n=t!==void 0?new or({sessionsDir:t}):new or;return t===void 0?{listSessions:oI,loadSession:sI,forkSession:cI,rewindSession:uI,setActiveEntry:fI,deleteSession:pI,listRunningSessions:gf,watchSessions:hI,storage:n}:{listSessions:i(o=>rI(o,t),"listSessions"),loadSession:i(o=>aI(o,t),"loadSession"),forkSession:i((o,r)=>lI(o,r,t),"forkSession"),rewindSession:i((o,r)=>dI(o,r,t),"rewindSession"),setActiveEntry:i((o,r)=>mI(o,r,t),"setActiveEntry"),deleteSession:i(o=>gI(o,t),"deleteSession"),listRunningSessions:gf,watchSessions:i(o=>yI(o,t),"watchSessions"),storage:n}}i(HD,"createSessionManager");export{_i as a,$i as b,xa as c,Pi as d,wa as e,ym as f,Tr as g,Cr as h,Li as i,br as j,Wl as k,vr as l,Oi as m,Ul as n,jl as o,Di as p,rn as q,Yn as r,qn as s,sk as t,zt as u,Sa as v,Sm as w,Tm as x,Xt as y,Cm as z,bm as A,Kx as B,Vx as C,ne as D,tN as E,np as F,xM as G,Cu as H,La as I,CS as J,bM as K,vM as L,sn as M,P as N,ZW as O,Bt as P,rp as Q,sp as R,bu as S,ap as T,IS as U,Oa as V,ts as W,Ar as X,cp as Y,Zn as Z,On as _,Dn as $,Vo as aa,Mu as ba,eo as ca,_u as da,$r as ea,wp as fa,vo as ga,ja as ha,rs as ia,CA as ja,Mp as ka,ls as la,us as ma,Up as na,Hr as oa,qu as pa,jp as qa,ec as ra,Kp as sa,fs as ta,d$ as ua,kn as va,QT as wa,JT as xa,x$ as ya,w$ as za,oP as Aa,Ur as Ba,sP as Ca,ys as Da,kP as Ea,EP as Fa,MP as Ga,ug as Ha,dg as Ia,_P as Ja,mg as Ka,pg as La,bd as Ma,vd as Na,Id as Oa,hg as Pa,kd as Qa,yg as Ra,xg as Sa,Rd as Ta,ac as Ua,cc as Va,HC as Wa,Md as Xa,Sg as Ya,Cg as Za,vg as _a,Ad as $a,Ig as ab,_d as bb,$d as cb,Mg as db,Pd as eb,dc as fb,fc as gb,eb as hb,iL as ib,sL as jb,nb as kb,uL as lb,dL as mb,mc as nb,io as ob,gc as pb,Cs as qb,fL as rb,Dd as sb,gL as tb,hL as ub,Nd as vb,$g as wb,Bd as xb,Pg as yb,hh as zb,vO as Ab,kO as Bb,LO as Cb,S0 as Db,T0 as Eb,OO as Fb,NO as Gb,tf as Hb,I0 as Ib,Eo as Jb,k0 as Kb,R0 as Lb,E0 as Mb,FO as Nb,vc as Ob,WO as Pb,UO as Qb,oD as Rb,bh as Sb,lD as Tb,uD as Ub,dD as Vb,fD as Wb,pD as Xb,gD as Yb,hD as Zb,yD as _b,U0 as $b,or as ac,oI as bc,sI as cc,cI as dc,uI as ec,fI as fc,gf as gc,pI as hc,hI as ic,HD as jc};
|